From e512235299eef55ced7d692067ab3f845c00299d Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Fri, 14 Mar 2014 21:06:40 +0800 Subject: [PATCH 001/106] Remove the old implementation of LabelTTF --- cocos/2d/CCTextFieldTTF.cpp | 54 +++++++++++-------- cocos/2d/CCTextFieldTTF.h | 40 +++++++------- .../cocosbuilder/CCLabelTTFLoader.cpp | 22 ++++---- .../cocosbuilder/CCLabelTTFLoader.h | 4 +- cocos/ui/UIButton.cpp | 11 ++-- cocos/ui/UIButton.h | 2 +- cocos/ui/UIRichText.cpp | 6 +-- cocos/ui/UIText.cpp | 33 ++++++++---- cocos/ui/UIText.h | 2 +- cocos/ui/UITextField.cpp | 10 ++-- .../CCControlExtension/CCControlButton.cpp | 16 +++--- .../CCControlExtension/CCControlStepper.cpp | 6 ++- .../GUI/CCControlExtension/CCControlStepper.h | 6 +-- .../CCControlExtension/CCControlSwitch.cpp | 28 +++++----- .../GUI/CCControlExtension/CCControlSwitch.h | 6 +-- .../HelloCocosBuilderLayer.cpp | 2 +- .../HelloCocosBuilderLayer.h | 2 +- .../TimelineCallbackTestLayer.cpp | 2 +- .../TimelineCallbackTestLayer.h | 2 +- .../CCControlSwitchTest.cpp | 4 +- 20 files changed, 144 insertions(+), 114 deletions(-) diff --git a/cocos/2d/CCTextFieldTTF.cpp b/cocos/2d/CCTextFieldTTF.cpp index 4911187604..4c32778e7d 100644 --- a/cocos/2d/CCTextFieldTTF.cpp +++ b/cocos/2d/CCTextFieldTTF.cpp @@ -55,7 +55,7 @@ TextFieldTTF::TextFieldTTF() : _delegate(0) , _charCount(0) , _inputText("") -, _placeHolder("") // prevent LabelTTF initWithString assertion +, _placeHolder("") // prevent Label initWithString assertion , _secureTextEntry(false) { _colorSpaceHolder.r = _colorSpaceHolder.g = _colorSpaceHolder.b = 127; @@ -88,7 +88,7 @@ TextFieldTTF * TextFieldTTF::textFieldWithPlaceHolder(const std::string& placeho TextFieldTTF * TextFieldTTF::textFieldWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize) { TextFieldTTF *ret = new TextFieldTTF(); - if(ret && ret->initWithString("", fontName, fontSize)) + if(ret && ret->initWithPlaceHolder("", fontName, fontSize)) { ret->autorelease(); if (placeholder.size()>0) @@ -108,12 +108,22 @@ TextFieldTTF * TextFieldTTF::textFieldWithPlaceHolder(const std::string& placeho bool TextFieldTTF::initWithPlaceHolder(const std::string& placeholder, const Size& dimensions, TextHAlignment alignment, const std::string& fontName, float fontSize) { _placeHolder = placeholder; - return LabelTTF::initWithString(_placeHolder, fontName, fontSize, dimensions, alignment); + setDimensions(dimensions.width,dimensions.height); + setFontName(fontName); + setFontSize(fontSize); + setAlignment(alignment,TextVAlignment::CENTER); + Label::setString(_placeHolder); + + return true; } bool TextFieldTTF::initWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize) { _placeHolder = std::string(placeholder); - return LabelTTF::initWithString(_placeHolder, fontName, fontSize); + setFontName(fontName); + setFontSize(fontSize); + Label::setString(_placeHolder); + + return true; } ////////////////////////////////////////////////////////////////////////// @@ -228,7 +238,7 @@ void TextFieldTTF::deleteBackward() { _inputText = ""; _charCount = 0; - LabelTTF::setString(_placeHolder); + Label::setString(_placeHolder); return; } @@ -242,23 +252,19 @@ const std::string& TextFieldTTF::getContentText() return _inputText; } -void TextFieldTTF::draw(Renderer *renderer, const kmMat4 &transform, bool transformUpdated) +void TextFieldTTF::setColor(const Color3B& color) { - if (_delegate && _delegate->onDraw(this)) - { - return; - } - if (_inputText.length()) - { - LabelTTF::draw(renderer, transform, transformUpdated); - return; - } + _colorText = color; + Label::setColor(color); +} - // draw placeholder - Color3B color = getColor(); - setColor(_colorSpaceHolder); - LabelTTF::draw(renderer, transform, transformUpdated); - setColor(color); +void TextFieldTTF::visit(Renderer *renderer, const kmMat4 &parentTransform, bool parentTransformUpdated) +{ + if (_delegate && _delegate->onVisit(this,renderer,parentTransform,parentTransformUpdated)) + { + return; + } + Label::visit(renderer,parentTransform,parentTransformUpdated); } const Color3B& TextFieldTTF::getColorSpaceHolder() @@ -305,11 +311,13 @@ void TextFieldTTF::setString(const std::string &text) // if there is no input text, display placeholder instead if (! _inputText.length()) { - LabelTTF::setString(_placeHolder); + Label::setColor(_colorSpaceHolder); + Label::setString(_placeHolder); } else { - LabelTTF::setString(displayText); + Label::setColor(_colorText); + Label::setString(displayText); } _charCount = _calcCharCount(_inputText.c_str()); } @@ -325,7 +333,7 @@ void TextFieldTTF::setPlaceHolder(const std::string& text) _placeHolder = text; if (! _inputText.length()) { - LabelTTF::setString(_placeHolder); + Label::setString(_placeHolder); } } diff --git a/cocos/2d/CCTextFieldTTF.h b/cocos/2d/CCTextFieldTTF.h index 9019cf95ee..0c462e5923 100644 --- a/cocos/2d/CCTextFieldTTF.h +++ b/cocos/2d/CCTextFieldTTF.h @@ -26,7 +26,7 @@ THE SOFTWARE. #ifndef __CC_TEXT_FIELD_H__ #define __CC_TEXT_FIELD_H__ -#include "CCLabelTTF.h" +#include "CCLabel.h" #include "CCIMEDelegate.h" NS_CC_BEGIN @@ -86,7 +86,7 @@ public: /** @brief If the sender doesn't want to draw, return true. */ - virtual bool onDraw(TextFieldTTF * sender) + virtual bool onVisit(TextFieldTTF * sender,Renderer *renderer, const kmMat4 &transform, bool transformUpdated) { CC_UNUSED_PARAM(sender); return false; @@ -96,7 +96,7 @@ public: /** @brief A simple text input field with TTF font. */ -class CC_DLL TextFieldTTF : public LabelTTF, public IMEDelegate +class CC_DLL TextFieldTTF : public Label, public IMEDelegate { public: /** @@ -113,7 +113,7 @@ public: /** creates a TextFieldTTF from a fontname, alignment, dimension and font size */ static TextFieldTTF * textFieldWithPlaceHolder(const std::string& placeholder, const Size& dimensions, TextHAlignment alignment, const std::string& fontName, float fontSize); - /** creates a LabelTTF from a fontname and font size */ + /** creates a TextFieldTTF from a fontname and font size */ static TextFieldTTF * textFieldWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize); /** initializes the TextFieldTTF with a font name, alignment, dimension and font size */ bool initWithPlaceHolder(const std::string& placeholder, const Size& dimensions, TextHAlignment alignment, const std::string& fontName, float fontSize); @@ -148,33 +148,23 @@ public: virtual const Color3B& getColorSpaceHolder(); virtual void setColorSpaceHolder(const Color3B& color); + virtual void setColor(const Color3B& color) override; + // input text property -public: virtual void setString(const std::string& text) override; virtual const std::string& getString() const override; -protected: - TextFieldDelegate * _delegate; - int _charCount; - - std::string _inputText; // place holder text property // place holder text displayed when there is no text in the text field. -public: virtual void setPlaceHolder(const std::string& text); virtual const std::string& getPlaceHolder(void) const; -protected: - std::string _placeHolder; - Color3B _colorSpaceHolder; -public: + virtual void setSecureTextEntry(bool value); virtual bool isSecureTextEntry(); -protected: - bool _secureTextEntry; -protected: - virtual void draw(Renderer *renderer, const kmMat4 &transform, bool transformUpdated) override; + virtual void visit(Renderer *renderer, const kmMat4 &parentTransform, bool parentTransformUpdated) override; +protected: ////////////////////////////////////////////////////////////////////////// // IMEDelegate interface ////////////////////////////////////////////////////////////////////////// @@ -184,6 +174,18 @@ protected: virtual void insertText(const char * text, int len) override; virtual void deleteBackward() override; virtual const std::string& getContentText() override; + + TextFieldDelegate * _delegate; + int _charCount; + + std::string _inputText; + + std::string _placeHolder; + Color3B _colorSpaceHolder; + Color3B _colorText; + + bool _secureTextEntry; + private: class LengthStack; LengthStack * _lens; diff --git a/cocos/editor-support/cocosbuilder/CCLabelTTFLoader.cpp b/cocos/editor-support/cocosbuilder/CCLabelTTFLoader.cpp index 2ed3010e1f..5cb003b629 100644 --- a/cocos/editor-support/cocosbuilder/CCLabelTTFLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCLabelTTFLoader.cpp @@ -16,7 +16,7 @@ namespace cocosbuilder { void LabelTTFLoader::onHandlePropTypeColor3(Node * pNode, Node * pParent, const char * pPropertyName, Color3B pColor3B, CCBReader * ccbReader) { if(strcmp(pPropertyName, PROPERTY_COLOR) == 0) { - ((LabelTTF *)pNode)->setColor(pColor3B); + ((Label *)pNode)->setColor(pColor3B); } else { NodeLoader::onHandlePropTypeColor3(pNode, pParent, pPropertyName, pColor3B, ccbReader); } @@ -24,7 +24,7 @@ void LabelTTFLoader::onHandlePropTypeColor3(Node * pNode, Node * pParent, const void LabelTTFLoader::onHandlePropTypeByte(Node * pNode, Node * pParent, const char * pPropertyName, unsigned char pByte, CCBReader * ccbReader) { if(strcmp(pPropertyName, PROPERTY_OPACITY) == 0) { - ((LabelTTF *)pNode)->setOpacity(pByte); + ((Label *)pNode)->setOpacity(pByte); } else { NodeLoader::onHandlePropTypeByte(pNode, pParent, pPropertyName, pByte, ccbReader); } @@ -32,7 +32,7 @@ void LabelTTFLoader::onHandlePropTypeByte(Node * pNode, Node * pParent, const ch void LabelTTFLoader::onHandlePropTypeBlendFunc(Node * pNode, Node * pParent, const char * pPropertyName, BlendFunc pBlendFunc, CCBReader * ccbReader) { if(strcmp(pPropertyName, PROPERTY_BLENDFUNC) == 0) { - ((LabelTTF *)pNode)->setBlendFunc(pBlendFunc); + ((Label *)pNode)->setBlendFunc(pBlendFunc); } else { NodeLoader::onHandlePropTypeBlendFunc(pNode, pParent, pPropertyName, pBlendFunc, ccbReader); } @@ -40,7 +40,7 @@ void LabelTTFLoader::onHandlePropTypeBlendFunc(Node * pNode, Node * pParent, con void LabelTTFLoader::onHandlePropTypeFontTTF(Node * pNode, Node * pParent, const char * pPropertyName, const char * pFontTTF, CCBReader * ccbReader) { if(strcmp(pPropertyName, PROPERTY_FONTNAME) == 0) { - ((LabelTTF *)pNode)->setFontName(pFontTTF); + ((Label *)pNode)->setFontName(pFontTTF); } else { NodeLoader::onHandlePropTypeFontTTF(pNode, pParent, pPropertyName, pFontTTF, ccbReader); } @@ -48,7 +48,7 @@ void LabelTTFLoader::onHandlePropTypeFontTTF(Node * pNode, Node * pParent, const void LabelTTFLoader::onHandlePropTypeText(Node * pNode, Node * pParent, const char * pPropertyName, const char * pText, CCBReader * ccbReader) { if(strcmp(pPropertyName, PROPERTY_STRING) == 0) { - ((LabelTTF *)pNode)->setString(pText); + ((Label *)pNode)->setString(pText); } else { NodeLoader::onHandlePropTypeText(pNode, pParent, pPropertyName, pText, ccbReader); } @@ -56,7 +56,7 @@ void LabelTTFLoader::onHandlePropTypeText(Node * pNode, Node * pParent, const ch void LabelTTFLoader::onHandlePropTypeFloatScale(Node * pNode, Node * pParent, const char * pPropertyName, float pFloatScale, CCBReader * ccbReader) { if(strcmp(pPropertyName, PROPERTY_FONTSIZE) == 0) { - ((LabelTTF *)pNode)->setFontSize(pFloatScale); + ((Label *)pNode)->setFontSize(pFloatScale); } else { NodeLoader::onHandlePropTypeFloatScale(pNode, pParent, pPropertyName, pFloatScale, ccbReader); } @@ -64,19 +64,19 @@ void LabelTTFLoader::onHandlePropTypeFloatScale(Node * pNode, Node * pParent, co void LabelTTFLoader::onHandlePropTypeIntegerLabeled(Node * pNode, Node * pParent, const char * pPropertyName, int pIntegerLabeled, CCBReader * ccbReader) { if(strcmp(pPropertyName, PROPERTY_HORIZONTALALIGNMENT) == 0) { - ((LabelTTF *)pNode)->setHorizontalAlignment(TextHAlignment(pIntegerLabeled)); + ((Label *)pNode)->setHorizontalAlignment(TextHAlignment(pIntegerLabeled)); } else if(strcmp(pPropertyName, PROPERTY_VERTICALALIGNMENT) == 0) { - ((LabelTTF *)pNode)->setVerticalAlignment(TextVAlignment(pIntegerLabeled)); + ((Label *)pNode)->setVerticalAlignment(TextVAlignment(pIntegerLabeled)); } else { NodeLoader::onHandlePropTypeFloatScale(pNode, pParent, pPropertyName, pIntegerLabeled, ccbReader); } } -void LabelTTFLoader::onHandlePropTypeSize(Node * pNode, Node * pParent, const char * pPropertyName, Size pSize, CCBReader * ccbReader) { +void LabelTTFLoader::onHandlePropTypeSize(Node * pNode, Node * pParent, const char * pPropertyName, Size size, CCBReader * ccbReader) { if(strcmp(pPropertyName, PROPERTY_DIMENSIONS) == 0) { - ((LabelTTF *)pNode)->setDimensions(pSize); + ((Label *)pNode)->setDimensions(size.width,size.height); } else { - NodeLoader::onHandlePropTypeSize(pNode, pParent, pPropertyName, pSize, ccbReader); + NodeLoader::onHandlePropTypeSize(pNode, pParent, pPropertyName, size, ccbReader); } } diff --git a/cocos/editor-support/cocosbuilder/CCLabelTTFLoader.h b/cocos/editor-support/cocosbuilder/CCLabelTTFLoader.h index 2809fe3bfd..029db06f99 100644 --- a/cocos/editor-support/cocosbuilder/CCLabelTTFLoader.h +++ b/cocos/editor-support/cocosbuilder/CCLabelTTFLoader.h @@ -2,7 +2,7 @@ #define _CCB_CCLABELTTFLOADER_H_ #include "CCRef.h" -#include "CCLabelTTF.h" +#include "CCLabel.h" #include "CCNodeLoader.h" @@ -21,7 +21,7 @@ public: CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(LabelTTFLoader, loader); protected: - CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(cocos2d::LabelTTF); + CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(cocos2d::Label); virtual void onHandlePropTypeColor3(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, cocos2d::Color3B pColor3B, CCBReader * ccbReader); virtual void onHandlePropTypeByte(cocos2d::Node * pNode, cocos2d::Node * pParent, const char * pPropertyName, unsigned char pByte, CCBReader * ccbReader); diff --git a/cocos/ui/UIButton.cpp b/cocos/ui/UIButton.cpp index 63c21a2fc1..114b73b419 100644 --- a/cocos/ui/UIButton.cpp +++ b/cocos/ui/UIButton.cpp @@ -99,7 +99,8 @@ void Button::initRenderer() _buttonNormalRenderer = Sprite::create(); _buttonClickedRenderer = Sprite::create(); _buttonDisableRenderer = Sprite::create(); - _titleRenderer = LabelTTF::create(); + _titleRenderer = Label::create(); + _titleRenderer->setAnchorPoint(Point::ANCHOR_MIDDLE); Node::addChild(_buttonNormalRenderer, NORMAL_RENDERER_Z, -1); Node::addChild(_buttonClickedRenderer, PRESSED_RENDERER_Z, -1); @@ -433,10 +434,10 @@ void Button::onPressStateChangedToDisabled() void Button::updateFlippedX() { - _titleRenderer->setFlippedX(_flippedX); + float flip = _flippedX ? -1.0f : 1.0f; + _titleRenderer->setScaleX(flip); if (_scale9Enabled) { - float flip = _flippedX ? -1.0f : 1.0f; _buttonNormalRenderer->setScaleX(flip); _buttonClickedRenderer->setScaleX(flip); _buttonDisableRenderer->setScaleX(flip); @@ -451,10 +452,10 @@ void Button::updateFlippedX() void Button::updateFlippedY() { - _titleRenderer->setFlippedY(_flippedY); + float flip = _flippedY ? -1.0f : 1.0f; + _titleRenderer->setScaleY(flip); if (_scale9Enabled) { - float flip = _flippedY ? -1.0f : 1.0f; _buttonNormalRenderer->setScaleY(flip); _buttonClickedRenderer->setScaleY(flip); _buttonDisableRenderer->setScaleY(flip); diff --git a/cocos/ui/UIButton.h b/cocos/ui/UIButton.h index 7e4dc758e1..7520bb76ef 100644 --- a/cocos/ui/UIButton.h +++ b/cocos/ui/UIButton.h @@ -193,7 +193,7 @@ protected: Node* _buttonNormalRenderer; Node* _buttonClickedRenderer; Node* _buttonDisableRenderer; - LabelTTF* _titleRenderer; + Label* _titleRenderer; std::string _normalFileName; std::string _clickedFileName; std::string _disabledFileName; diff --git a/cocos/ui/UIRichText.cpp b/cocos/ui/UIRichText.cpp index a9099ad291..108bb1347b 100644 --- a/cocos/ui/UIRichText.cpp +++ b/cocos/ui/UIRichText.cpp @@ -193,7 +193,7 @@ void RichText::formatText() case RICH_TEXT: { RichElementText* elmtText = static_cast(element); - elementRenderer = LabelTTF::create(elmtText->_text.c_str(), elmtText->_fontName.c_str(), elmtText->_fontSize); + elementRenderer = Label::create(elmtText->_text.c_str(), elmtText->_fontName.c_str(), elmtText->_fontSize); break; } case RICH_IMAGE: @@ -255,7 +255,7 @@ void RichText::formatText() void RichText::handleTextRenderer(const char *text, const char *fontName, float fontSize, const Color3B &color, GLubyte opacity) { - LabelTTF* textRenderer = LabelTTF::create(text, fontName, fontSize); + Label* textRenderer = Label::create(text, fontName, fontSize); float textRendererWidth = textRenderer->getContentSize().width; _leftSpaceWidth -= textRendererWidth; if (_leftSpaceWidth < 0.0f) @@ -268,7 +268,7 @@ void RichText::handleTextRenderer(const char *text, const char *fontName, float std::string cutWords = curText.substr(leftLength, curText.length()-1); if (leftLength > 0) { - LabelTTF* leftRenderer = LabelTTF::create(leftWords.substr(0, leftLength).c_str(), fontName, fontSize); + Label* leftRenderer = Label::create(leftWords.substr(0, leftLength).c_str(), fontName, fontSize); leftRenderer->setColor(color); leftRenderer->setOpacity(opacity); pushToContainer(leftRenderer); diff --git a/cocos/ui/UIText.cpp b/cocos/ui/UIText.cpp index be67c99905..6dae8a1970 100644 --- a/cocos/ui/UIText.cpp +++ b/cocos/ui/UIText.cpp @@ -71,7 +71,7 @@ bool Text::init() void Text::initRenderer() { - _labelRenderer = LabelTTF::create(); + _labelRenderer = Label::create(); Node::addChild(_labelRenderer, LABEL_RENDERER_Z, -1); } @@ -117,7 +117,7 @@ const std::string& Text::getFontName() void Text::setTextAreaSize(const Size &size) { - _labelRenderer->setDimensions(size); + _labelRenderer->setDimensions(size.width,size.height); labelScaleChangedWithSize(); } @@ -164,7 +164,8 @@ void Text::onPressStateChangedToNormal() { return; } - _labelRenderer->setScale(_normalScaleValueX, _normalScaleValueY); + _labelRenderer->setScaleX(_normalScaleValueX); + _labelRenderer->setScaleY(_normalScaleValueY); } void Text::onPressStateChangedToPressed() @@ -173,7 +174,8 @@ void Text::onPressStateChangedToPressed() { return; } - _labelRenderer->setScale(_normalScaleValueX + _onSelectedScaleOffset, _normalScaleValueY + _onSelectedScaleOffset); + _labelRenderer->setScaleX(_normalScaleValueX + _onSelectedScaleOffset); + _labelRenderer->setScaleY(_normalScaleValueY + _onSelectedScaleOffset); } void Text::onPressStateChangedToDisabled() @@ -183,13 +185,26 @@ void Text::onPressStateChangedToDisabled() void Text::updateFlippedX() { - _labelRenderer->setFlippedX(_flippedX); - + if (_flippedX) + { + _labelRenderer->setScaleX(-1.0f); + } + else + { + _labelRenderer->setScaleX(1.0f); + } } void Text::updateFlippedY() { - _labelRenderer->setFlippedY(_flippedY); + if (_flippedY) + { + _labelRenderer->setScaleY(-1.0f); + } + else + { + _labelRenderer->setScaleY(1.0f); + } } void Text::setAnchorPoint(const Point &pt) @@ -218,14 +233,14 @@ void Text::labelScaleChangedWithSize() { if (_ignoreSize) { - _labelRenderer->setDimensions(Size::ZERO); + _labelRenderer->setDimensions(0,0); _labelRenderer->setScale(1.0f); _size = _labelRenderer->getContentSize(); _normalScaleValueX = _normalScaleValueY = 1.0f; } else { - _labelRenderer->setDimensions(_size); + _labelRenderer->setDimensions(_size.width,_size.height); Size textureSize = _labelRenderer->getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { diff --git a/cocos/ui/UIText.h b/cocos/ui/UIText.h index 46faa4d183..ff84a2d03a 100644 --- a/cocos/ui/UIText.h +++ b/cocos/ui/UIText.h @@ -157,7 +157,7 @@ protected: std::string _fontName; int _fontSize; float _onSelectedScaleOffset; - LabelTTF* _labelRenderer; + Label* _labelRenderer; }; } diff --git a/cocos/ui/UITextField.cpp b/cocos/ui/UITextField.cpp index 30f633503c..1501397492 100644 --- a/cocos/ui/UITextField.cpp +++ b/cocos/ui/UITextField.cpp @@ -65,7 +65,7 @@ UICCTextField * UICCTextField::create(const char *placeholder, const char *fontN { UICCTextField *pRet = new UICCTextField(); - if(pRet && pRet->initWithString("", fontName, fontSize)) + if(pRet && pRet->initWithPlaceHolder("", fontName, fontSize)) { pRet->autorelease(); if (placeholder) @@ -296,7 +296,7 @@ void UICCTextField::setPasswordText(const char *text) { tempStr.append(_passwordStyleText); } - LabelTTF::setString(tempStr.c_str()); + Label::setString(tempStr.c_str()); } void UICCTextField::setAttachWithIME(bool attach) @@ -672,13 +672,13 @@ void TextField::textfieldRendererScaleChangedWithSize() { if (_ignoreSize) { - _textFieldRenderer->setDimensions(Size::ZERO); + _textFieldRenderer->setDimensions(0,0); _textFieldRenderer->setScale(1.0f); _size = getContentSize(); } else { - _textFieldRenderer->setDimensions(_size); + _textFieldRenderer->setDimensions(_size.width,_size.height); Size textureSize = getContentSize(); if (textureSize.width <= 0.0f || textureSize.height <= 0.0f) { @@ -754,7 +754,7 @@ void TextField::copySpecialProperties(Widget *widget) void TextField::setTextAreaSize(const Size &size) { - _textFieldRenderer->setDimensions(size); + _textFieldRenderer->setDimensions(size.width,size.height); } void TextField::setTextHorizontalAlignment(TextHAlignment alignment) diff --git a/extensions/GUI/CCControlExtension/CCControlButton.cpp b/extensions/GUI/CCControlExtension/CCControlButton.cpp index eb3792e701..445af3b689 100644 --- a/extensions/GUI/CCControlExtension/CCControlButton.cpp +++ b/extensions/GUI/CCControlExtension/CCControlButton.cpp @@ -27,7 +27,7 @@ #include "CCControlButton.h" #include "CCScale9Sprite.h" -#include "CCLabelTTF.h" +#include "CCLabel.h" #include "CCLabelBMFont.h" #include "CCAction.h" #include "CCActionInterval.h" @@ -65,7 +65,7 @@ ControlButton::~ControlButton() bool ControlButton::init() { - return this->initWithLabelAndBackgroundSprite(LabelTTF::create("", "Helvetica", 12), Scale9Sprite::create()); + return this->initWithLabelAndBackgroundSprite(Label::create("", "Helvetica", 12), Scale9Sprite::create()); } bool ControlButton::initWithLabelAndBackgroundSprite(Node* node, Scale9Sprite* backgroundSprite) @@ -132,7 +132,7 @@ ControlButton* ControlButton::create(Node* label, Scale9Sprite* backgroundSprite bool ControlButton::initWithTitleAndFontNameAndFontSize(const std::string& title, const std::string& fontName, float fontSize) { - LabelTTF *label = LabelTTF::create(title, fontName, fontSize); + Label *label = Label::create(title, fontName, fontSize); return initWithLabelAndBackgroundSprite(label, Scale9Sprite::create()); } @@ -146,7 +146,7 @@ ControlButton* ControlButton::create(const std::string& title, const std::string bool ControlButton::initWithBackgroundSprite(Scale9Sprite* sprite) { - LabelTTF *label = LabelTTF::create("", "Arial", 30);// + Label *label = Label::create("", "Arial", 30);// return initWithLabelAndBackgroundSprite(label, sprite); } @@ -363,13 +363,13 @@ void ControlButton::setTitleLabelForState(Node* titleLabel, State state) void ControlButton::setTitleTTFForState(const std::string& fntFile, State state) { std::string title = this->getTitleForState(state); - this->setTitleLabelForState(LabelTTF::create(title, fntFile, 12), state); + this->setTitleLabelForState(Label::create(title, fntFile, 12), state); } const std::string& ControlButton::getTitleTTFForState(State state) { LabelProtocol* label = dynamic_cast(this->getTitleLabelForState(state)); - LabelTTF* labelTTF = dynamic_cast(label); + Label* labelTTF = dynamic_cast(label); if(labelTTF != 0) { return labelTTF->getFontName(); @@ -384,7 +384,7 @@ void ControlButton::setTitleTTFSizeForState(float size, State state) LabelProtocol* label = dynamic_cast(this->getTitleLabelForState(state)); if(label) { - LabelTTF* labelTTF = dynamic_cast(label); + Label* labelTTF = dynamic_cast(label); if(labelTTF != 0) { return labelTTF->setFontSize(size); @@ -395,7 +395,7 @@ void ControlButton::setTitleTTFSizeForState(float size, State state) float ControlButton::getTitleTTFSizeForState(State state) { LabelProtocol* label = dynamic_cast(this->getTitleLabelForState(state)); - LabelTTF* labelTTF = dynamic_cast(label); + Label* labelTTF = dynamic_cast(label); if(labelTTF != 0) { return labelTTF->getFontSize(); diff --git a/extensions/GUI/CCControlExtension/CCControlStepper.cpp b/extensions/GUI/CCControlExtension/CCControlStepper.cpp index 4c4df49589..c5e3bd41c2 100644 --- a/extensions/GUI/CCControlExtension/CCControlStepper.cpp +++ b/extensions/GUI/CCControlExtension/CCControlStepper.cpp @@ -89,8 +89,9 @@ bool ControlStepper::initWithMinusSpriteAndPlusSprite(Sprite *minusSprite, Sprit _minusSprite->setPosition( Point(minusSprite->getContentSize().width / 2, minusSprite->getContentSize().height / 2) ); this->addChild(_minusSprite); - this->setMinusLabel( LabelTTF::create("-", ControlStepperLabelFont, 40)); + this->setMinusLabel( Label::create("-", ControlStepperLabelFont, 40)); _minusLabel->setColor(ControlStepperLabelColorDisabled); + _minusLabel->setAnchorPoint(Point::ANCHOR_MIDDLE); _minusLabel->setPosition(Point(_minusSprite->getContentSize().width / 2, _minusSprite->getContentSize().height / 2) ); _minusSprite->addChild(_minusLabel); @@ -100,8 +101,9 @@ bool ControlStepper::initWithMinusSpriteAndPlusSprite(Sprite *minusSprite, Sprit minusSprite->getContentSize().height / 2) ); this->addChild(_plusSprite); - this->setPlusLabel( LabelTTF::create("+", ControlStepperLabelFont, 40 )); + this->setPlusLabel( Label::create("+", ControlStepperLabelFont, 40 )); _plusLabel->setColor( ControlStepperLabelColorEnabled ); + _plusLabel->setAnchorPoint(Point::ANCHOR_MIDDLE); _plusLabel->setPosition( Point(_plusSprite->getContentSize().width / 2, _plusSprite->getContentSize().height / 2) ); _plusSprite->addChild(_plusLabel); diff --git a/extensions/GUI/CCControlExtension/CCControlStepper.h b/extensions/GUI/CCControlExtension/CCControlStepper.h index 2376db9c99..2b9447c0a2 100644 --- a/extensions/GUI/CCControlExtension/CCControlStepper.h +++ b/extensions/GUI/CCControlExtension/CCControlStepper.h @@ -29,7 +29,7 @@ #define __CCCONTROLSTEPPER_H__ #include "CCControl.h" -#include "CCLabelTTF.h" +#include "CCLabel.h" NS_CC_EXT_BEGIN @@ -111,8 +111,8 @@ protected: // Weak links to children CC_SYNTHESIZE_RETAIN(Sprite*, _minusSprite, MinusSprite) CC_SYNTHESIZE_RETAIN(Sprite*, _plusSprite, PlusSprite) - CC_SYNTHESIZE_RETAIN(LabelTTF*, _minusLabel, MinusLabel) - CC_SYNTHESIZE_RETAIN(LabelTTF*, _plusLabel, PlusLabel) + CC_SYNTHESIZE_RETAIN(Label*, _minusLabel, MinusLabel) + CC_SYNTHESIZE_RETAIN(Label*, _plusLabel, PlusLabel) }; // end of GUI group diff --git a/extensions/GUI/CCControlExtension/CCControlSwitch.cpp b/extensions/GUI/CCControlExtension/CCControlSwitch.cpp index a7d6d26753..336ee62bf9 100644 --- a/extensions/GUI/CCControlExtension/CCControlSwitch.cpp +++ b/extensions/GUI/CCControlExtension/CCControlSwitch.cpp @@ -28,7 +28,7 @@ #include "CCControlSwitch.h" #include "CCSprite.h" #include "CCActionTween.h" -#include "CCLabelTTF.h" +#include "CCLabel.h" #include "CCClippingNode.h" #include "ccShaders.h" #include "CCRenderTexture.h" @@ -45,8 +45,8 @@ public: Sprite *onSprite, Sprite *offSprite, Sprite *thumbSprite, - LabelTTF* onLabel, - LabelTTF* offLabel); + Label* onLabel, + Label* offLabel); /** * @js NA @@ -91,8 +91,8 @@ public: CC_SYNTHESIZE_RETAIN(Sprite*, _onSprite, OnSprite) CC_SYNTHESIZE_RETAIN(Sprite*, _offSprite, OffSprite) CC_SYNTHESIZE_RETAIN(Sprite*, _thumbSprite, ThumbSprite) - CC_SYNTHESIZE_RETAIN(LabelTTF*, _onLabel, OnLabel) - CC_SYNTHESIZE_RETAIN(LabelTTF*, _offLabel, OffLabel) + CC_SYNTHESIZE_RETAIN(Label*, _onLabel, OnLabel) + CC_SYNTHESIZE_RETAIN(Label*, _offLabel, OffLabel) Sprite* _clipperStencil; @@ -116,8 +116,8 @@ protected: Sprite *onSprite, Sprite *offSprite, Sprite *thumbSprite, - LabelTTF* onLabel, - LabelTTF* offLabel); + Label* onLabel, + Label* offLabel); private: CC_DISALLOW_COPY_AND_ASSIGN(ControlSwitchSprite); }; @@ -126,8 +126,8 @@ ControlSwitchSprite* ControlSwitchSprite::create(Sprite *maskSprite, Sprite *onSprite, Sprite *offSprite, Sprite *thumbSprite, - LabelTTF* onLabel, - LabelTTF* offLabel) + Label* onLabel, + Label* offLabel) { auto ret = new ControlSwitchSprite(); ret->initWithMaskSprite(maskSprite, onSprite, offSprite, thumbSprite, onLabel, offLabel); @@ -168,8 +168,8 @@ bool ControlSwitchSprite::initWithMaskSprite( Sprite *onSprite, Sprite *offSprite, Sprite *thumbSprite, - LabelTTF* onLabel, - LabelTTF* offLabel) + Label* onLabel, + Label* offLabel) { if (Sprite::initWithTexture(maskSprite->getTexture())) { @@ -254,11 +254,13 @@ void ControlSwitchSprite::needsLayout() if (_onLabel) { + _onLabel->setAnchorPoint(Point::ANCHOR_MIDDLE); _onLabel->setPosition(Point(_onSprite->getPosition().x - _thumbSprite->getContentSize().width / 6, _onSprite->getContentSize().height / 2)); } if (_offLabel) { + _offLabel->setAnchorPoint(Point::ANCHOR_MIDDLE); _offLabel->setPosition(Point(_offSprite->getPosition().x + _thumbSprite->getContentSize().width / 6, _offSprite->getContentSize().height / 2)); } @@ -330,7 +332,7 @@ ControlSwitch* ControlSwitch::create(Sprite *maskSprite, Sprite * onSprite, Spri return pRet; } -bool ControlSwitch::initWithMaskSprite(Sprite *maskSprite, Sprite * onSprite, Sprite * offSprite, Sprite * thumbSprite, LabelTTF* onLabel, LabelTTF* offLabel) +bool ControlSwitch::initWithMaskSprite(Sprite *maskSprite, Sprite * onSprite, Sprite * offSprite, Sprite * thumbSprite, Label* onLabel, Label* offLabel) { if (Control::init()) { @@ -359,7 +361,7 @@ bool ControlSwitch::initWithMaskSprite(Sprite *maskSprite, Sprite * onSprite, Sp return false; } -ControlSwitch* ControlSwitch::create(Sprite *maskSprite, Sprite * onSprite, Sprite * offSprite, Sprite * thumbSprite, LabelTTF* onLabel, LabelTTF* offLabel) +ControlSwitch* ControlSwitch::create(Sprite *maskSprite, Sprite * onSprite, Sprite * offSprite, Sprite * thumbSprite, Label* onLabel, Label* offLabel) { ControlSwitch* pRet = new ControlSwitch(); if (pRet && pRet->initWithMaskSprite(maskSprite, onSprite, offSprite, thumbSprite, onLabel, offLabel)) diff --git a/extensions/GUI/CCControlExtension/CCControlSwitch.h b/extensions/GUI/CCControlExtension/CCControlSwitch.h index 0df5cf1197..57a7ef1619 100644 --- a/extensions/GUI/CCControlExtension/CCControlSwitch.h +++ b/extensions/GUI/CCControlExtension/CCControlSwitch.h @@ -32,7 +32,7 @@ namespace cocos2d { class Sprite; } -namespace cocos2d { class LabelTTF; } +namespace cocos2d { class Label; } NS_CC_EXT_BEGIN @@ -50,7 +50,7 @@ class ControlSwitch : public Control { public: /** Creates a switch with a mask sprite, on/off sprites for on/off states, a thumb sprite and an on/off labels. */ - static ControlSwitch* create(Sprite *maskSprite, Sprite * onSprite, Sprite * offSprite, Sprite * thumbSprite, LabelTTF* onLabel, LabelTTF* offLabel); + static ControlSwitch* create(Sprite *maskSprite, Sprite * onSprite, Sprite * offSprite, Sprite * thumbSprite, Label* onLabel, Label* offLabel); /** Creates a switch with a mask sprite, on/off sprites for on/off states and a thumb sprite. */ static ControlSwitch* create(Sprite *maskSprite, Sprite * onSprite, Sprite * offSprite, Sprite * thumbSprite); /** @@ -66,7 +66,7 @@ public: /** Initializes a switch with a mask sprite, on/off sprites for on/off states and a thumb sprite. */ bool initWithMaskSprite(Sprite *maskSprite, Sprite * onSprite, Sprite * offSprite, Sprite * thumbSprite); /** Initializes a switch with a mask sprite, on/off sprites for on/off states, a thumb sprite and an on/off labels. */ - bool initWithMaskSprite(Sprite *maskSprite, Sprite * onSprite, Sprite * offSprite, Sprite * thumbSprite, LabelTTF* onLabel, LabelTTF* offLabel); + bool initWithMaskSprite(Sprite *maskSprite, Sprite * onSprite, Sprite * offSprite, Sprite * thumbSprite, Label* onLabel, Label* offLabel); /** * Set the state of the switch to On or Off, optionally animating the transition. diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.cpp index 92077a4438..dfec4d2ebc 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.cpp @@ -87,7 +87,7 @@ Control::Handler HelloCocosBuilderLayer::onResolveCCBCCControlSelector(Ref * pTa bool HelloCocosBuilderLayer::onAssignCCBMemberVariable(Ref * pTarget, const char * pMemberVariableName, Node * pNode) { CCB_MEMBERVARIABLEASSIGNER_GLUE(this, "mBurstSprite", Sprite *, this->mBurstSprite); - CCB_MEMBERVARIABLEASSIGNER_GLUE(this, "mTestTitleLabelTTF", LabelTTF *, this->mTestTitleLabelTTF); + CCB_MEMBERVARIABLEASSIGNER_GLUE(this, "mTestTitleLabelTTF", Label *, this->mTestTitleLabelTTF); return false; } diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.h b/tests/cpp-tests/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.h index f2d6a0a9cd..2d50925b1b 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.h +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.h @@ -45,7 +45,7 @@ class HelloCocosBuilderLayer private: cocos2d::Sprite * mBurstSprite; - cocos2d::LabelTTF * mTestTitleLabelTTF; + cocos2d::Label * mTestTitleLabelTTF; int mCustomPropertyInt; float mCustomPropertyFloat; diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.cpp index 8667067870..2a719f1ab6 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.cpp @@ -31,7 +31,7 @@ SEL_CallFuncN TimelineCallbackTestLayer::onResolveCCBCCCallFuncSelector(Ref * pT } bool TimelineCallbackTestLayer::onAssignCCBMemberVariable(Ref * pTarget, const char * pMemberVariableName, Node * pNode) { - CCB_MEMBERVARIABLEASSIGNER_GLUE(this, "helloLabel", LabelTTF *, this->_helloLabel); + CCB_MEMBERVARIABLEASSIGNER_GLUE(this, "helloLabel", Label *, this->_helloLabel); return false; } diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.h b/tests/cpp-tests/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.h index 73200bb9dc..ed55549d88 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.h +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.h @@ -24,7 +24,7 @@ class TimelineCallbackTestLayer void onCallback1(Node* sender); void onCallback2(Node* sender); private: - cocos2d::LabelTTF* _helloLabel; + cocos2d::Label* _helloLabel; }; #endif /* _TIMELINE_TESTLAYER_H_ */ diff --git a/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp b/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp index dd724930e8..b499c72bd7 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp @@ -64,8 +64,8 @@ bool ControlSwitchTest::init() Sprite::create("extensions/switch-on.png"), Sprite::create("extensions/switch-off.png"), Sprite::create("extensions/switch-thumb.png"), - LabelTTF::create("On", "Arial-BoldMT", 16), - LabelTTF::create("Off", "Arial-BoldMT", 16) + Label::create("On", "Arial-BoldMT", 16), + Label::create("Off", "Arial-BoldMT", 16) ); switchControl->setPosition(Point(layer_width + 10 + switchControl->getContentSize().width / 2, 0)); layer->addChild(switchControl); From 00249328a60c7d4dff562faeb82b21e4fa5ab8f2 Mon Sep 17 00:00:00 2001 From: andyque Date: Tue, 18 Mar 2014 14:59:59 +0800 Subject: [PATCH 002/106] add boolean support for mac and ios --- cocos/2d/platform/CCFileUtils.cpp | 1 - cocos/2d/platform/apple/CCFileUtilsApple.mm | 51 +++++++++++++++++++ .../Classes/FileUtilsTest/FileUtilsTest.cpp | 20 +++++++- 3 files changed, 70 insertions(+), 2 deletions(-) diff --git a/cocos/2d/platform/CCFileUtils.cpp b/cocos/2d/platform/CCFileUtils.cpp index 845739ccd3..84b15a50e0 100644 --- a/cocos/2d/platform/CCFileUtils.cpp +++ b/cocos/2d/platform/CCFileUtils.cpp @@ -402,7 +402,6 @@ static tinyxml2::XMLElement* generateElementForObject(const Value& value, tinyxm return node; } - //FIXME:XXX How to deal with Boolean ?? // object is Array if (value.getType() == Value::Type::VECTOR) diff --git a/cocos/2d/platform/apple/CCFileUtilsApple.mm b/cocos/2d/platform/apple/CCFileUtilsApple.mm index 9c9443e0f7..224ad99fc5 100644 --- a/cocos/2d/platform/apple/CCFileUtilsApple.mm +++ b/cocos/2d/platform/apple/CCFileUtilsApple.mm @@ -94,6 +94,31 @@ static void addObjectToNSArray(const Value& value, NSMutableArray *array) return; } + //add float into array + if (value.getType() == Value::Type::FLOAT) { + NSNumber *number = [NSNumber numberWithFloat:value.asFloat()]; + [array addObject:number]; + } + + //add double into array + if (value.getType() == Value::Type::DOUBLE) { + NSNumber *number = [NSNumber numberWithDouble:value.asDouble()]; + [array addObject:number]; + } + + //add boolean into array + if (value.getType() == Value::Type::BOOLEAN) { + NSNumber *element = [NSNumber numberWithBool:value.asBool()]; + [array addObject:element]; + } + + if (value.getType() == Value::Type::INTEGER) { + NSNumber *element = [NSNumber numberWithInt:value.asInt()]; + [array addObject:element]; + } + + //todo: add date and data support + // add array into array if (value.getType() == Value::Type::VECTOR) { @@ -144,6 +169,7 @@ static void addValueToDict(id nsKey, id nsValue, ValueMap& dict) dict[key] = Value([nsValue doubleValue]); return; } + // the value is a new dictionary if ([nsValue isKindOfClass:[NSDictionary class]]) @@ -171,6 +197,7 @@ static void addValueToDict(id nsKey, id nsValue, ValueMap& dict) dict[key] = Value(valueArray); return; } + } static void addObjectToNSDict(const std::string& key, const Value& value, NSMutableDictionary *dict) @@ -191,6 +218,30 @@ static void addObjectToNSDict(const std::string& key, const Value& value, NSMuta return; } + //add float into dict + if (value.getType() == Value::Type::FLOAT) { + NSNumber *number = [NSNumber numberWithFloat:value.asFloat()]; + [dict setObject:number forKey:NSkey]; + } + + //add double into dict + if (value.getType() == Value::Type::DOUBLE) { + NSNumber *number = [NSNumber numberWithDouble:value.asDouble()]; + [dict setObject:number forKey:NSkey]; + } + + //add boolean into dict + if (value.getType() == Value::Type::BOOLEAN) { + NSNumber *element = [NSNumber numberWithBool:value.asBool()]; + [dict setObject:element forKey:NSkey]; + } + + //add integer into dict + if (value.getType() == Value::Type::INTEGER) { + NSNumber *element = [NSNumber numberWithInt:value.asInt()]; + [dict setObject:element forKey:NSkey]; + } + // the object is a String if (value.getType() == Value::Type::STRING) { diff --git a/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp b/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp index c1ad0d52f9..f9dc88b540 100644 --- a/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp +++ b/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp @@ -334,8 +334,26 @@ void TextWritePlist::onEnter() auto dictInDict = Dictionary::create(); dictInDict->setObject(String::create("string in dictInDict value"), "string in dictInDict key"); + + //add boolean to the plist + auto booleanObject = Bool::create(true); + dictInDict->setObject(booleanObject, "bool"); - root->setObject(dictInDict, "dictInDict"); + //add interger to the plist + auto intObject = Integer::create(1024); + dictInDict->setObject(intObject, "integer"); + + //add float to the plist + auto floatObject = Float::create(1024.1024f); + dictInDict->setObject(floatObject, "float"); + + //add double to the plist + auto doubleObject = Double::create(1024.123); + dictInDict->setObject(doubleObject, "double"); + + + + root->setObject(dictInDict, "dictInDict, Hello World"); // end with / std::string writablePath = FileUtils::getInstance()->getWritablePath(); From cadbfbe9b11bf1b4d775a4133db530cb918c4a12 Mon Sep 17 00:00:00 2001 From: andyque Date: Wed, 19 Mar 2014 11:58:11 +0800 Subject: [PATCH 003/106] add Bool Integer Float Double support to CCDictionary --- cocos/2d/platform/apple/CCFileUtilsApple.mm | 38 +++++++++++++- cocos/base/CCDictionary.cpp | 52 ++++++++++++++++++- .../Classes/FileUtilsTest/FileUtilsTest.cpp | 7 +++ 3 files changed, 93 insertions(+), 4 deletions(-) diff --git a/cocos/2d/platform/apple/CCFileUtilsApple.mm b/cocos/2d/platform/apple/CCFileUtilsApple.mm index 224ad99fc5..53a2ed1326 100644 --- a/cocos/2d/platform/apple/CCFileUtilsApple.mm +++ b/cocos/2d/platform/apple/CCFileUtilsApple.mm @@ -51,11 +51,29 @@ static void addItemToArray(id item, ValueVector& array) } // add number value into array(such as int, float, bool and so on) + // the value is a number if ([item isKindOfClass:[NSNumber class]]) { - array.push_back(Value([item doubleValue])); + NSNumber* num = item; + const char* numType = [num objCType]; + if(num == (void*)kCFBooleanFalse || num == (void*)kCFBooleanTrue) + { + array.push_back(Value([num boolValue])); + } + else if(strcmp(numType, @encode(float)) == 0) + { + array.push_back(Value([num floatValue])); + } + else if(strcmp(numType, @encode(double)) == 0) + { + array.push_back(Value([num doubleValue])); + } + else{ + array.push_back(Value([num intValue])); + } return; } + // add dictionary value into array if ([item isKindOfClass:[NSDictionary class]]) @@ -166,7 +184,23 @@ static void addValueToDict(id nsKey, id nsValue, ValueMap& dict) // the value is a number if ([nsValue isKindOfClass:[NSNumber class]]) { - dict[key] = Value([nsValue doubleValue]); + NSNumber* num = nsValue; + const char* numType = [num objCType]; + if(num == (void*)kCFBooleanFalse || num == (void*)kCFBooleanTrue) + { + dict[key] = Value([num boolValue]); + } + else if(strcmp(numType, @encode(float)) == 0) + { + dict[key] = Value([num floatValue]); + } + else if(strcmp(numType, @encode(double)) == 0) + { + dict[key] = Value([num doubleValue]); + } + else{ + dict[key] = Value([num intValue]); + } return; } diff --git a/cocos/base/CCDictionary.cpp b/cocos/base/CCDictionary.cpp index 9c4dfb791c..9e7f1582f1 100644 --- a/cocos/base/CCDictionary.cpp +++ b/cocos/base/CCDictionary.cpp @@ -407,12 +407,36 @@ static __Dictionary* visitDict(const ValueMap& dict) ret->setObject(sub, iter->first); sub->release(); } - else + else if(iter->second.getType() == Value::Type::STRING) { auto str = new __String(iter->second.asString()); ret->setObject(str, iter->first); str->release(); } + else if(iter->second.getType() == Value::Type::BOOLEAN) + { + auto boolean = new __Bool(iter->second.asBool()); + ret->setObject(boolean, iter->first); + boolean->release(); + } + else if(iter->second.getType() == Value::Type::FLOAT) + { + auto flt = new __Float(iter->second.asFloat()); + ret->setObject(flt, iter->first); + flt->release(); + }else if(iter->second.getType() == Value::Type::DOUBLE) + { + auto dbl = new __Double(iter->second.asDouble()); + ret->setObject(dbl, iter->first); + dbl->release(); + }else if(iter->second.getType() == Value::Type::INTEGER) + { + auto integer = new __Integer(iter->second.asInt()); + ret->setObject(integer, iter->first); + integer->release(); + }else{ + CCASSERT(false, "the type isn't suppored."); + } } return ret; } @@ -437,12 +461,36 @@ static __Array* visitArray(const ValueVector& array) ret->addObject(sub); sub->release(); } - else + else if(value.getType() == Value::Type::STRING) { auto str = new __String(value.asString()); ret->addObject(str); str->release(); } + else if(value.getType() == Value::Type::BOOLEAN) + { + auto boolean = new __Bool(value.asBool()); + ret->addObject(boolean); + boolean->release(); + } + else if(value.getType() == Value::Type::FLOAT) + { + auto flt = new __Float(value.asFloat()); + ret->addObject(flt); + flt->release(); + }else if(value.getType() == Value::Type::DOUBLE) + { + auto dbl = new __Double(value.asDouble()); + ret->addObject(dbl); + dbl->release(); + }else if(value.getType() == Value::Type::INTEGER) + { + auto integer = new __Integer(value.asInt()); + ret->addObject(integer); + integer->release(); + }else{ + CCASSERT(false, "the type isn't suppored."); + } } return ret; diff --git a/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp b/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp index f9dc88b540..7f69ce7873 100644 --- a/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp +++ b/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp @@ -367,6 +367,13 @@ void TextWritePlist::onEnter() this->addChild(label); auto winSize = Director::getInstance()->getWinSize(); label->setPosition(Point(winSize.width/2, winSize.height/3)); + +// auto loadDict = Dictionary::createWithContentsOfFile("/Users/guanghui/Library/Application Support/iPhone Simulator/7.1-64/Applications/92E7DFA5-5B92-44FE-AF61-798F5A50B091/Documents/text.plist"); +// auto loadDictInDict = (Dictionary*)loadDict->objectForKey("dictInDict, Hello World"); +// auto boolValue = (Bool*)loadDictInDict->objectForKey("bool"); +// if (boolValue->getValue()) { +// CCLOG("true"); +// } } void TextWritePlist::onExit() From bab53ef2bd61dd82c912746ac6fa4fddac5bee2c Mon Sep 17 00:00:00 2001 From: andyque Date: Wed, 19 Mar 2014 14:31:15 +0800 Subject: [PATCH 004/106] add test for ios and mac --- cocos/base/CCDictionary.cpp | 52 +------------------ .../Classes/FileUtilsTest/FileUtilsTest.cpp | 17 +++--- 2 files changed, 13 insertions(+), 56 deletions(-) diff --git a/cocos/base/CCDictionary.cpp b/cocos/base/CCDictionary.cpp index 9e7f1582f1..9c4dfb791c 100644 --- a/cocos/base/CCDictionary.cpp +++ b/cocos/base/CCDictionary.cpp @@ -407,36 +407,12 @@ static __Dictionary* visitDict(const ValueMap& dict) ret->setObject(sub, iter->first); sub->release(); } - else if(iter->second.getType() == Value::Type::STRING) + else { auto str = new __String(iter->second.asString()); ret->setObject(str, iter->first); str->release(); } - else if(iter->second.getType() == Value::Type::BOOLEAN) - { - auto boolean = new __Bool(iter->second.asBool()); - ret->setObject(boolean, iter->first); - boolean->release(); - } - else if(iter->second.getType() == Value::Type::FLOAT) - { - auto flt = new __Float(iter->second.asFloat()); - ret->setObject(flt, iter->first); - flt->release(); - }else if(iter->second.getType() == Value::Type::DOUBLE) - { - auto dbl = new __Double(iter->second.asDouble()); - ret->setObject(dbl, iter->first); - dbl->release(); - }else if(iter->second.getType() == Value::Type::INTEGER) - { - auto integer = new __Integer(iter->second.asInt()); - ret->setObject(integer, iter->first); - integer->release(); - }else{ - CCASSERT(false, "the type isn't suppored."); - } } return ret; } @@ -461,36 +437,12 @@ static __Array* visitArray(const ValueVector& array) ret->addObject(sub); sub->release(); } - else if(value.getType() == Value::Type::STRING) + else { auto str = new __String(value.asString()); ret->addObject(str); str->release(); } - else if(value.getType() == Value::Type::BOOLEAN) - { - auto boolean = new __Bool(value.asBool()); - ret->addObject(boolean); - boolean->release(); - } - else if(value.getType() == Value::Type::FLOAT) - { - auto flt = new __Float(value.asFloat()); - ret->addObject(flt); - flt->release(); - }else if(value.getType() == Value::Type::DOUBLE) - { - auto dbl = new __Double(value.asDouble()); - ret->addObject(dbl); - dbl->release(); - }else if(value.getType() == Value::Type::INTEGER) - { - auto integer = new __Integer(value.asInt()); - ret->addObject(integer); - integer->release(); - }else{ - CCASSERT(false, "the type isn't suppored."); - } } return ret; diff --git a/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp b/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp index 7f69ce7873..3c2c527cb8 100644 --- a/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp +++ b/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp @@ -368,12 +368,17 @@ void TextWritePlist::onEnter() auto winSize = Director::getInstance()->getWinSize(); label->setPosition(Point(winSize.width/2, winSize.height/3)); -// auto loadDict = Dictionary::createWithContentsOfFile("/Users/guanghui/Library/Application Support/iPhone Simulator/7.1-64/Applications/92E7DFA5-5B92-44FE-AF61-798F5A50B091/Documents/text.plist"); -// auto loadDictInDict = (Dictionary*)loadDict->objectForKey("dictInDict, Hello World"); -// auto boolValue = (Bool*)loadDictInDict->objectForKey("bool"); -// if (boolValue->getValue()) { -// CCLOG("true"); -// } + auto loadDict = Dictionary::createWithContentsOfFile(fullPath.c_str()); + auto loadDictInDict = (Dictionary*)loadDict->objectForKey("dictInDict, Hello World"); + auto boolValue = (String*)loadDictInDict->objectForKey("bool"); + CCLOG("%s",boolValue->getCString()); + auto floatValue = (String*)loadDictInDict->objectForKey("float"); + CCLOG("%s",floatValue->getCString()); + auto intValue = (String*)loadDictInDict->objectForKey("integer"); + CCLOG("%s",intValue->getCString()); + auto doubleValue = (String*)loadDictInDict->objectForKey("double"); + CCLOG("%s",doubleValue->getCString()); + } void TextWritePlist::onExit() From c90ef0066823f6b9673a8062860d8c254079e137 Mon Sep 17 00:00:00 2001 From: andyque Date: Wed, 19 Mar 2014 16:42:14 +0800 Subject: [PATCH 005/106] add bool support for other platform --- cocos/2d/platform/CCFileUtils.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/cocos/2d/platform/CCFileUtils.cpp b/cocos/2d/platform/CCFileUtils.cpp index 84b15a50e0..2d51d34cc7 100644 --- a/cocos/2d/platform/CCFileUtils.cpp +++ b/cocos/2d/platform/CCFileUtils.cpp @@ -401,6 +401,12 @@ static tinyxml2::XMLElement* generateElementForObject(const Value& value, tinyxm node->LinkEndChild(content); return node; } + + //object is bool + if (value.getType() == Value::Type::BOOLEAN) { + tinyxml2::XMLElement* node = doc->NewElement(value.asString().c_str()); + return node; + } // object is Array From 5edb9b9f864b121b6992cb2167c2842d2d0c3629 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Fri, 21 Mar 2014 16:25:22 +0800 Subject: [PATCH 006/106] closed #4499: Read ParticleSystem::_endRadiusVar from "minRadiusVariance" in plist. --- cocos/2d/CCParticleSystem.cpp | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/cocos/2d/CCParticleSystem.cpp b/cocos/2d/CCParticleSystem.cpp index f34e692792..9e11835a48 100644 --- a/cocos/2d/CCParticleSystem.cpp +++ b/cocos/2d/CCParticleSystem.cpp @@ -312,8 +312,17 @@ bool ParticleSystem::initWithDictionary(ValueMap& dictionary, const std::string& { modeB.endRadius = dictionary["minRadius"].asFloat(); } - modeB.endRadiusVar = 0.0f; - if (_configName.length()>0) + + if (dictionary.find("minRadiusVariance") != dictionary.end()) + { + modeB.endRadiusVar = dictionary["minRadiusVariance"].asFloat(); + } + else + { + modeB.endRadiusVar = 0.0f; + } + + if (_configName.length()>0) { modeB.rotatePerSecond = dictionary["rotatePerSecond"].asInt(); } From e3e4e88bceeba984bca765870cb027318c42e4d4 Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 05:50:55 -0700 Subject: [PATCH 007/106] added WP8 and WINRT platforms --- cocos/2d/platform/CCApplicationProtocol.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cocos/2d/platform/CCApplicationProtocol.h b/cocos/2d/platform/CCApplicationProtocol.h index 7c47c46e81..ed948ebff5 100644 --- a/cocos/2d/platform/CCApplicationProtocol.h +++ b/cocos/2d/platform/CCApplicationProtocol.h @@ -52,7 +52,9 @@ public: OS_BLACKBERRY, OS_NACL, OS_EMSCRIPTEN, - OS_TIZEN + OS_TIZEN, + OS_WINRT, + OS_WP8 }; /** From 409ad77b6ca7a88d2840ebefb28770f70168ffb8 Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 05:51:39 -0700 Subject: [PATCH 008/106] disabled webp for wp8 and winrt --- cocos/2d/platform/CCImage.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/cocos/2d/platform/CCImage.cpp b/cocos/2d/platform/CCImage.cpp index 918a4cedfc..4a991c8939 100644 --- a/cocos/2d/platform/CCImage.cpp +++ b/cocos/2d/platform/CCImage.cpp @@ -46,7 +46,9 @@ extern "C" #include "atitc.h" #include "TGAlib.h" +#if (CC_TARGET_PLATFORM != CC_PLATFORM_WP8) && (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT) #include "decode.h" +#endif #include "ccMacros.h" #include "CCCommon.h" @@ -1832,7 +1834,11 @@ bool Image::initWithPVRData(const unsigned char * data, ssize_t dataLen) bool Image::initWithWebpData(const unsigned char * data, ssize_t dataLen) { - bool bRet = false; + bool bRet = false; + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) + CCLOG("WEBP image format not supported on WinRT or WP8"); +#else do { WebPDecoderConfig config; @@ -1862,9 +1868,11 @@ bool Image::initWithWebpData(const unsigned char * data, ssize_t dataLen) bRet = true; } while (0); +#endif return bRet; } + bool Image::initWithRawData(const unsigned char * data, ssize_t dataLen, int width, int height, int bitsPerComponent, bool preMulti) { bool bRet = false; From 77ab59ebab01393853fae54ca4d883ac900a1c97 Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 05:52:45 -0700 Subject: [PATCH 009/106] #pragma mark for ios and mac only --- cocos/2d/ccCArray.cpp | 2 ++ cocos/2d/ccCArray.h | 2 ++ 2 files changed, 4 insertions(+) diff --git a/cocos/2d/ccCArray.cpp b/cocos/2d/ccCArray.cpp index 69dd34f24e..a25a636239 100644 --- a/cocos/2d/ccCArray.cpp +++ b/cocos/2d/ccCArray.cpp @@ -278,8 +278,10 @@ void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr) arr->num -= back; } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) // #pragma mark - // #pragma mark ccCArray for Values (c structures) +#endif /** Allocates and initializes a new C array with specified capacity */ ccCArray* ccCArrayNew(ssize_t capacity) diff --git a/cocos/2d/ccCArray.h b/cocos/2d/ccCArray.h index 5cc80bbecd..0529d83ac3 100644 --- a/cocos/2d/ccCArray.h +++ b/cocos/2d/ccCArray.h @@ -130,8 +130,10 @@ void ccArrayRemoveArray(ccArray *arr, ccArray *minusArr); matching instances in arr will be removed. */ void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr); +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) // #pragma mark - // #pragma mark ccCArray for Values (c structures) +#endif typedef struct _ccCArray { ssize_t num, max; From f6b57df505758082db24c7f0685322cd5d10d8ce Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 05:53:09 -0700 Subject: [PATCH 010/106] added WP8 and WINRT platforms --- cocos/2d/CCDeprecated.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cocos/2d/CCDeprecated.h b/cocos/2d/CCDeprecated.h index 89808e5c59..51c2cb98bd 100644 --- a/cocos/2d/CCDeprecated.h +++ b/cocos/2d/CCDeprecated.h @@ -963,6 +963,8 @@ CC_DEPRECATED_ATTRIBUTE const Application::Platform kTargetBlackBerry = Applic CC_DEPRECATED_ATTRIBUTE const Application::Platform kTargetNaCl = Application::Platform::OS_NACL; CC_DEPRECATED_ATTRIBUTE const Application::Platform kTargetEmscripten = Application::Platform::OS_EMSCRIPTEN; CC_DEPRECATED_ATTRIBUTE const Application::Platform kTargetTizen = Application::Platform::OS_TIZEN; +CC_DEPRECATED_ATTRIBUTE const Application::Platform kTargetWinRT = Application::Platform::OS_WINRT; +CC_DEPRECATED_ATTRIBUTE const Application::Platform kTargetWP8 = Application::Platform::OS_WP8; CC_DEPRECATED_ATTRIBUTE typedef Application::Platform TargetPlatform; CC_DEPRECATED_ATTRIBUTE const ResolutionPolicy kResolutionExactFit = ResolutionPolicy::EXACT_FIT; From 65400bf87bd9ffd6bcc590714680725011914089 Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 05:55:08 -0700 Subject: [PATCH 011/106] added wp8 device orientation. added purge for FontAtlasCache. Disabled console for wp8/winrt until networking code is added --- cocos/2d/CCDirector.cpp | 35 +++++++++++++++++++++++++++++++++-- cocos/2d/CCDirector.h | 9 ++++++++- 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index baec3f1127..43f440a334 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -45,6 +45,7 @@ THE SOFTWARE. #include "platform/CCFileUtils.h" #include "CCApplication.h" #include "CCFontFNT.h" +#include "CCFontAtlasCache.h" #include "CCActionManager.h" #include "CCAnimationCache.h" #include "CCTouch.h" @@ -157,8 +158,10 @@ bool Director::init(void) initTextureCache(); _renderer = new Renderer; - _console = new Console; +#if (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT) && (CC_TARGET_PLATFORM != CC_PLATFORM_WP8) + _console = new Console; +#endif return true; } @@ -182,7 +185,10 @@ Director::~Director(void) delete _eventProjectionChanged; delete _renderer; + +#if (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT) && (CC_TARGET_PLATFORM != CC_PLATFORM_WP8) delete _console; +#endif // clean auto release pool PoolManager::destroyInstance(); @@ -432,6 +438,12 @@ void Director::setProjection(Projection projection) case Projection::_2D: kmGLMatrixMode(KM_GL_PROJECTION); kmGLLoadIdentity(); +#if CC_TARGET_PLATFORM == CC_PLATFORM_WP8 + if(getOpenGLView() != nullptr) + { + kmGLMultMatrix( getOpenGLView()->getOrientationMatrix()); + } +#endif kmMat4 orthoMatrix; kmMat4OrthographicProjection(&orthoMatrix, 0, size.width, 0, size.height, -1024, 1024); kmGLMultMatrix(&orthoMatrix); @@ -447,7 +459,15 @@ void Director::setProjection(Projection projection) kmGLMatrixMode(KM_GL_PROJECTION); kmGLLoadIdentity(); - + +#if CC_TARGET_PLATFORM == CC_PLATFORM_WP8 + //if needed, we need to add a rotation for Landscape orientations on Windows Phone 8 since it is always in Portrait Mode + GLView* view = getOpenGLView(); + if(getOpenGLView() != nullptr) + { + kmGLMultMatrix(getOpenGLView()->getOrientationMatrix()); + } +#endif // issue #1334 kmMat4PerspectiveProjection(&matrixPerspective, 60, (GLfloat)size.width/size.height, 10, zeye+size.height/2); // kmMat4PerspectiveProjection( &matrixPerspective, 60, (GLfloat)size.width/size.height, 0.1f, 1500); @@ -485,10 +505,16 @@ void Director::setProjection(Projection projection) void Director::purgeCachedData(void) { FontFNT::purgeCachedData(); + FontAtlasCache::purgeCachedData(); + if (s_SharedDirector->getOpenGLView()) { SpriteFrameCache::getInstance()->removeUnusedSpriteFrames(); _textureCache->removeUnusedTextures(); + + // Note: some tests such as ActionsTest are leaking refcounted textures + // There should be no test textures left in the cache + log("%s\n", _textureCache->getCachedTextureInfo().c_str()); } FileUtils::getInstance()->purgeCachedEntries(); } @@ -533,6 +559,11 @@ static void GLToClipTransform(kmMat4 *transformOut) kmMat4 projection; kmGLGetMatrix(KM_GL_PROJECTION, &projection); +#if CC_TARGET_PLATFORM == CC_PLATFORM_WP8 + //if needed, we need to undo the rotation for Landscape orientation in order to get the correct positions + kmMat4Multiply(&projection, Director::getInstance()->getOpenGLView()->getReverseOrientationMatrix(), &projection); +#endif + kmMat4 modelview; kmGLGetMatrix(KM_GL_MODELVIEW, &modelview); diff --git a/cocos/2d/CCDirector.h b/cocos/2d/CCDirector.h index f6c8e1f6e1..c58214b57b 100644 --- a/cocos/2d/CCDirector.h +++ b/cocos/2d/CCDirector.h @@ -59,7 +59,10 @@ class EventCustom; class EventListenerCustom; class TextureCache; class Renderer; + +#if (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT) && (CC_TARGET_PLATFORM != CC_PLATFORM_WP8) class Console; +#endif /** @brief Class that creates and handles the main Window and manages how @@ -368,7 +371,9 @@ public: /** Returns the Console @since v3.0 */ +#if (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT) && (CC_TARGET_PLATFORM != CC_PLATFORM_WP8) Console* getConsole() const { return _console; } +#endif /* Gets delta time since last tick to main loop */ float getDeltaTime() const; @@ -477,9 +482,11 @@ protected: /* Renderer for the Director */ Renderer *_renderer; +#if (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT) && (CC_TARGET_PLATFORM != CC_PLATFORM_WP8) /* Console for the director */ Console *_console; - +#endif + // GLViewProtocol will recreate stats labels to fit visible rect friend class GLViewProtocol; }; From 294341d0abaf8ea4c5069115e3a1a33bbd63d2f0 Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 05:56:08 -0700 Subject: [PATCH 012/106] fixed texture memory leak and added comments to indicate problem --- cocos/2d/CCFontAtlas.cpp | 12 +++++++++--- cocos/2d/CCTexture2D.cpp | 11 +++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/cocos/2d/CCFontAtlas.cpp b/cocos/2d/CCFontAtlas.cpp index 3e40e41419..0710d13566 100644 --- a/cocos/2d/CCFontAtlas.cpp +++ b/cocos/2d/CCFontAtlas.cpp @@ -185,7 +185,9 @@ void FontAtlas::listenToForeground(EventCustom *event) auto contentSize = Size(CacheTextureWidth,CacheTextureHeight); auto pixelFormat = fontTTf->getOutlineSize() > 0 ? Texture2D::PixelFormat::AI88 : Texture2D::PixelFormat::A8; - _atlasTextures[_currentPage]->initWithData(_currentPageData, _currentPageDataSize, pixelFormat, CacheTextureWidth, CacheTextureHeight, contentSize ); + // this is a memory leak as the texture previously in _atlasTextures[_currentPage] is not deleted from OpenGL + // see CCTexture2D::initWithData for the temporary fix + _atlasTextures[_currentPage]->initWithData(_currentPageData, _currentPageDataSize, pixelFormat, CacheTextureWidth, CacheTextureHeight, contentSize ); } } #endif @@ -254,8 +256,10 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) _currentPageOrigY += _commonLineHeight; _currentPageOrigX = 0; if(_currentPageOrigY + _commonLineHeight >= CacheTextureHeight) - { - _atlasTextures[_currentPage]->initWithData(_currentPageData, _currentPageDataSize, pixelFormat, CacheTextureWidth, CacheTextureHeight, contentSize ); + { + // this is a memory leak as the texture previously in _atlasTextures[_currentPage] is not deleted from OpenGL + // see CCTexture2D::initWithData for the temporary fix + _atlasTextures[_currentPage]->initWithData(_currentPageData, _currentPageDataSize, pixelFormat, CacheTextureWidth, CacheTextureHeight, contentSize ); _currentPageOrigY = 0; memset(_currentPageData, 0, _currentPageDataSize); _currentPage++; @@ -299,6 +303,8 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) if(existNewLetter) { + // this is a memory leak as the texture previously in _atlasTextures[_currentPage] is not deleted from OpenGL + // see CCTexture2D::initWithData for the temporary fix _atlasTextures[_currentPage]->initWithData(_currentPageData, _currentPageDataSize, pixelFormat, CacheTextureWidth, CacheTextureHeight, contentSize ); } return true; diff --git a/cocos/2d/CCTexture2D.cpp b/cocos/2d/CCTexture2D.cpp index a43563d862..54c59ec088 100644 --- a/cocos/2d/CCTexture2D.cpp +++ b/cocos/2d/CCTexture2D.cpp @@ -51,6 +51,8 @@ THE SOFTWARE. NS_CC_BEGIN + + namespace { typedef Texture2D::PixelFormatInfoMap::value_type PixelFormatInfoMapValue; static const PixelFormatInfoMapValue TexturePixelFormatInfoTablesValue[] = @@ -533,6 +535,15 @@ bool Texture2D::hasPremultipliedAlpha() const bool Texture2D::initWithData(const void *data, ssize_t dataLen, Texture2D::PixelFormat pixelFormat, int pixelsWide, int pixelsHigh, const Size& contentSize) { + // cocos2d-x is currently calling this multiple times on the same Texture2D + // if the GL texture has already been created,it will be leaked in OpenGL + // For now, call deleteTexture if the texture already exists + if(_name) + { + GL::deleteTexture(_name); + _name = 0; + } + CCASSERT(dataLen>0 && pixelsWide>0 && pixelsHigh>0, "Invalid size"); //if data has no mipmaps, we will consider it has only one mipmap From 5e402ee433bee316e06fc5eb438e4ca6b3a10190 Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 05:56:49 -0700 Subject: [PATCH 013/106] fix for generic already defined in wp8 --- cocos/2d/CCFontFreeType.h | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/cocos/2d/CCFontFreeType.h b/cocos/2d/CCFontFreeType.h index a103ee6570..00ecc41bac 100644 --- a/cocos/2d/CCFontFreeType.h +++ b/cocos/2d/CCFontFreeType.h @@ -26,15 +26,29 @@ #ifndef _FontFreetype_h_ #define _FontFreetype_h_ + + + #include "CCFont.h" #include "CCData.h" #include #include +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) +#define generic GenericFromFreeTypeLibrary +#define internal InternalFromFreeTypeLibrary +#endif + #include FT_FREETYPE_H #include FT_STROKER_H +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) +#undef generic +#undef internal +#endif + + NS_CC_BEGIN class CC_DLL FontFreeType : public Font From fb574697aa21ce30033dfc3445bef83679a2db35 Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 05:58:07 -0700 Subject: [PATCH 014/106] added support for precompiled shaders in wp8 --- cocos/2d/CCGLProgram.cpp | 65 ++++++++++++++++++++++++++++++++++++++-- cocos/2d/CCGLProgram.h | 15 ++++++++++ 2 files changed, 77 insertions(+), 3 deletions(-) diff --git a/cocos/2d/CCGLProgram.cpp b/cocos/2d/CCGLProgram.cpp index ee6b53cb42..6f3bce0f3b 100644 --- a/cocos/2d/CCGLProgram.cpp +++ b/cocos/2d/CCGLProgram.cpp @@ -37,6 +37,10 @@ THE SOFTWARE. #include "kazmath/GL/matrix.h" #include "kazmath/kazmath.h" +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) +#include "CCPrecompiledShaders.h" +#endif + NS_CC_BEGIN typedef struct _hashUniformEntry @@ -116,6 +120,18 @@ GLProgram::~GLProgram() bool GLProgram::initWithByteArrays(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray) { + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) + GLboolean hasCompiler = false; + glGetBooleanv(GL_SHADER_COMPILER, &hasCompiler); + _hasShaderCompiler = (hasCompiler == GL_TRUE); + + if(!_hasShaderCompiler) + { + return initWithPrecompiledProgramByteArray(vShaderByteArray,fShaderByteArray); + } +#endif + _program = glCreateProgram(); CHECK_GL_ERROR_DEBUG(); @@ -126,7 +142,8 @@ bool GLProgram::initWithByteArrays(const GLchar* vShaderByteArray, const GLchar* if (!compileShader(&_vertShader, GL_VERTEX_SHADER, vShaderByteArray)) { CCLOG("cocos2d: ERROR: Failed to compile vertex shader"); - } + return false; + } } // Create and compile fragment shader @@ -135,6 +152,7 @@ bool GLProgram::initWithByteArrays(const GLchar* vShaderByteArray, const GLchar* if (!compileShader(&_fragShader, GL_FRAGMENT_SHADER, fShaderByteArray)) { CCLOG("cocos2d: ERROR: Failed to compile fragment shader"); + return false; } } @@ -152,9 +170,34 @@ bool GLProgram::initWithByteArrays(const GLchar* vShaderByteArray, const GLchar* CHECK_GL_ERROR_DEBUG(); +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) + _shaderId = CCPrecompiledShaders::getInstance()->addShaders(vShaderByteArray, fShaderByteArray); +#endif + return true; } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) +bool GLProgram::initWithPrecompiledProgramByteArray(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray) +{ + bool haveProgram = false; + + _program = glCreateProgram(); + CHECK_GL_ERROR_DEBUG(); + + _vertShader = _fragShader = 0; + + haveProgram = CCPrecompiledShaders::getInstance()->loadProgram(_program, vShaderByteArray, fShaderByteArray); + + CHECK_GL_ERROR_DEBUG(); + _hashForUniforms = NULL; + + CHECK_GL_ERROR_DEBUG(); + + return haveProgram; +} +#endif + bool GLProgram::initWithFilenames(const std::string &vShaderFilename, const std::string &fShaderFilename) { auto fileUtils = FileUtils::getInstance(); @@ -275,6 +318,15 @@ bool GLProgram::link() { CCASSERT(_program != 0, "Cannot link invalid program"); + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) + if(!_hasShaderCompiler) + { + // precompiled shader program is already linked + return true; + } +#endif + GLint status = GL_TRUE; glLinkProgram(_program); @@ -291,7 +343,7 @@ bool GLProgram::link() _vertShader = _fragShader = 0; -#if COCOS2D_DEBUG +#if DEBUG || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) glGetProgramiv(_program, GL_LINK_STATUS, &status); if (status == GL_FALSE) @@ -301,7 +353,14 @@ bool GLProgram::link() _program = 0; } #endif - + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) + if (status == GL_TRUE) + { + CCPrecompiledShaders::getInstance()->addProgram(_program, _shaderId); + } +#endif + return (status == GL_TRUE); } diff --git a/cocos/2d/CCGLProgram.h b/cocos/2d/CCGLProgram.h index c111c0c724..19c9865f7d 100644 --- a/cocos/2d/CCGLProgram.h +++ b/cocos/2d/CCGLProgram.h @@ -126,7 +126,18 @@ public: * @js initWithString * @lua initWithString */ + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) + /** Initializes the CCGLProgram with precompiled shader program */ + bool initWithPrecompiledProgramByteArray(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray); +#endif + + /** Initializes the GLProgram with a vertex and fragment with bytes array + * @js initWithString + * @lua initWithString + */ bool initWithByteArrays(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray); + /** Initializes the GLProgram with a vertex and fragment with contents of filenames * @js init * @lua init @@ -266,6 +277,10 @@ private: GLuint _fragShader; GLint _uniforms[UNIFORM_MAX]; struct _hashUniformEntry* _hashForUniforms; + bool _hasShaderCompiler; +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) + std::string _shaderId; +#endif struct flag_struct { unsigned int usesTime:1; From 2577fc39d8c2ae9de691717432f378a0376aa98b Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 05:58:37 -0700 Subject: [PATCH 015/106] #pragma mark for ios and mac only --- cocos/2d/ccGLStateCache.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/cocos/2d/ccGLStateCache.cpp b/cocos/2d/ccGLStateCache.cpp index d8a620f463..cb0c5bc56c 100644 --- a/cocos/2d/ccGLStateCache.cpp +++ b/cocos/2d/ccGLStateCache.cpp @@ -217,7 +217,9 @@ void bindVAO(GLuint vaoId) } } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) //#pragma mark - GL Vertex Attrib functions +#endif void enableVertexAttribs( unsigned int flags ) { @@ -260,8 +262,9 @@ void enableVertexAttribs( unsigned int flags ) } } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) //#pragma mark - GL Uniforms functions - +#endif void setProjectionMatrixDirty( void ) { s_currentProjectionMatrix = -1; From b50a158b62051f1cbf7416aba922753b6da769a2 Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 06:04:36 -0700 Subject: [PATCH 016/106] need to terminate variable args list with NULL. nullptr will not work with wp8 compiler --- cocos/2d/CCLayer.cpp | 2 +- cocos/2d/CCMenu.cpp | 8 ++- cocos/2d/CCTransition.cpp | 66 +++++++++---------- cocos/2d/CCTransitionPageTurn.cpp | 4 +- cocos/2d/CCTransitionProgress.cpp | 2 +- .../cocostudio/CCActionNode.cpp | 2 +- .../Classes/ActionsTest/ActionsTest.cpp | 23 +++++-- .../CocoStudioArmatureTest/ArmatureScene.cpp | 12 ++-- .../ComponentsTestScene.cpp | 2 +- .../EnemyController.cpp | 2 +- .../GameOverScene.cpp | 4 +- .../CocoStudioSceneTest/SceneEditorTest.cpp | 10 +-- .../CocoStudioSceneTest/TriggerCode/acts.cpp | 8 +-- .../Classes/LabelTest/LabelTestNew.cpp | 2 +- .../NewEventDispatcherTest.cpp | 16 ++--- .../SpriteTest/SpriteTest.cpp.REMOVED.git-id | 2 +- 16 files changed, 89 insertions(+), 76 deletions(-) diff --git a/cocos/2d/CCLayer.cpp b/cocos/2d/CCLayer.cpp index feb6c9c12e..ea79ce6ea5 100644 --- a/cocos/2d/CCLayer.cpp +++ b/cocos/2d/CCLayer.cpp @@ -852,7 +852,7 @@ LayerMultiplex * LayerMultiplex::create(Layer * layer, ...) LayerMultiplex * LayerMultiplex::createWithLayer(Layer* layer) { - return LayerMultiplex::create(layer, nullptr); + return LayerMultiplex::create(layer, NULL); } LayerMultiplex* LayerMultiplex::create() diff --git a/cocos/2d/CCMenu.cpp b/cocos/2d/CCMenu.cpp index c6cb20c5c1..929e1d75e2 100644 --- a/cocos/2d/CCMenu.cpp +++ b/cocos/2d/CCMenu.cpp @@ -53,9 +53,12 @@ Menu::~Menu() CCLOGINFO("In the destructor of Menu. %p", this); } + Menu* Menu::create() { - return Menu::create(nullptr, nullptr); + // nullptr doesn't work for WP8. Compiler can't convert nulltpr termination to MenuItem* + // must use NULL for variable arg termination + return Menu::create(nullptr, NULL); } Menu * Menu::create(MenuItem* item, ...) @@ -104,7 +107,8 @@ Menu* Menu::createWithItems(MenuItem* item, va_list args) Menu* Menu::createWithItem(MenuItem* item) { - return Menu::create(item, nullptr); + // nullptr doesn't work for WP8 + return Menu::create(item, NULL); } bool Menu::init() diff --git a/cocos/2d/CCTransition.cpp b/cocos/2d/CCTransition.cpp index 0777474369..ac76ecea8f 100644 --- a/cocos/2d/CCTransition.cpp +++ b/cocos/2d/CCTransition.cpp @@ -258,10 +258,10 @@ void TransitionRotoZoom:: onEnter() ( ScaleBy::create(_duration/2, 0.001f), RotateBy::create(_duration/2, 360 * 2), - nullptr + NULL ), DelayTime::create(_duration/2), - nullptr + NULL )); _outScene->runAction(rotozoom); @@ -271,7 +271,7 @@ void TransitionRotoZoom:: onEnter() ( rotozoom->reverse(), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - nullptr + NULL ) ); } @@ -312,8 +312,8 @@ void TransitionJumpZoom::onEnter() ActionInterval *scaleIn = ScaleTo::create(_duration/4, 1.0f); ActionInterval *scaleOut = ScaleTo::create(_duration/4, 0.5f); - ActionInterval *jumpZoomOut = (ActionInterval*)(Sequence::create(scaleOut, jump, nullptr)); - ActionInterval *jumpZoomIn = (ActionInterval*)(Sequence::create(jump, scaleIn, nullptr)); + ActionInterval *jumpZoomOut = (ActionInterval*)(Sequence::create(scaleOut, jump, NULL)); + ActionInterval *jumpZoomIn = (ActionInterval*)(Sequence::create(jump, scaleIn, NULL)); ActionInterval *delay = DelayTime::create(_duration/2); @@ -325,7 +325,7 @@ void TransitionJumpZoom::onEnter() delay, jumpZoomIn, CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - nullptr + NULL ) ); } @@ -366,7 +366,7 @@ void TransitionMoveInL::onEnter() ( this->easeActionWithAction(a), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - nullptr + NULL ) ); } @@ -503,7 +503,7 @@ void TransitionSlideInL::onEnter() ( easeActionWithAction(out), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - nullptr + NULL ); _inScene->runAction(inAction); _outScene->runAction(outAction); @@ -706,7 +706,7 @@ void TransitionShrinkGrow::onEnter() ( this->easeActionWithAction(scaleOut), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - nullptr + NULL ) ); } @@ -757,7 +757,7 @@ void TransitionFlipX::onEnter() Show::create(), OrbitCamera::create(_duration/2, 1, 0, inAngleZ, inDeltaZ, 0, 0), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - nullptr + NULL ); outA = (ActionInterval *)Sequence::create @@ -765,7 +765,7 @@ void TransitionFlipX::onEnter() OrbitCamera::create(_duration/2, 1, 0, outAngleZ, outDeltaZ, 0, 0), Hide::create(), DelayTime::create(_duration/2), - nullptr + NULL ); _inScene->runAction(inA); @@ -827,14 +827,14 @@ void TransitionFlipY::onEnter() Show::create(), OrbitCamera::create(_duration/2, 1, 0, inAngleZ, inDeltaZ, 90, 0), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - nullptr + NULL ); outA = (ActionInterval*)Sequence::create ( OrbitCamera::create(_duration/2, 1, 0, outAngleZ, outDeltaZ, 90, 0), Hide::create(), DelayTime::create(_duration/2), - nullptr + NULL ); _inScene->runAction(inA); @@ -898,14 +898,14 @@ void TransitionFlipAngular::onEnter() Show::create(), OrbitCamera::create(_duration/2, 1, 0, inAngleZ, inDeltaZ, -45, 0), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - nullptr + NULL ); outA = (ActionInterval *)Sequence::create ( OrbitCamera::create(_duration/2, 1, 0, outAngleZ, outDeltaZ, 45, 0), Hide::create(), DelayTime::create(_duration/2), - nullptr + NULL ); _inScene->runAction(inA); @@ -967,10 +967,10 @@ void TransitionZoomFlipX::onEnter() OrbitCamera::create(_duration/2, 1, 0, inAngleZ, inDeltaZ, 0, 0), ScaleTo::create(_duration/2, 1), Show::create(), - nullptr + NULL ), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - nullptr + NULL ); outA = (ActionInterval *)Sequence::create ( @@ -978,11 +978,11 @@ void TransitionZoomFlipX::onEnter() ( OrbitCamera::create(_duration/2, 1, 0, outAngleZ, outDeltaZ, 0, 0), ScaleTo::create(_duration/2, 0.5f), - nullptr + NULL ), Hide::create(), DelayTime::create(_duration/2), - nullptr + NULL ); _inScene->setScale(0.5f); @@ -1045,10 +1045,10 @@ void TransitionZoomFlipY::onEnter() OrbitCamera::create(_duration/2, 1, 0, inAngleZ, inDeltaZ, 90, 0), ScaleTo::create(_duration/2, 1), Show::create(), - nullptr + NULL ), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - nullptr + NULL ); outA = (ActionInterval *)Sequence::create @@ -1057,11 +1057,11 @@ void TransitionZoomFlipY::onEnter() ( OrbitCamera::create(_duration/2, 1, 0, outAngleZ, outDeltaZ, 90, 0), ScaleTo::create(_duration/2, 0.5f), - nullptr + NULL ), Hide::create(), DelayTime::create(_duration/2), - nullptr + NULL ); _inScene->setScale(0.5f); @@ -1126,11 +1126,11 @@ void TransitionZoomFlipAngular::onEnter() OrbitCamera::create(_duration/2, 1, 0, inAngleZ, inDeltaZ, -45, 0), ScaleTo::create(_duration/2, 1), Show::create(), - nullptr + NULL ), Show::create(), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - nullptr + NULL ); outA = (ActionInterval *)Sequence::create ( @@ -1138,11 +1138,11 @@ void TransitionZoomFlipAngular::onEnter() ( OrbitCamera::create(_duration/2, 1, 0 , outAngleZ, outDeltaZ, 45, 0), ScaleTo::create(_duration/2, 0.5f), - nullptr + NULL ), Hide::create(), DelayTime::create(_duration/2), - nullptr + NULL ); _inScene->setScale(0.5f); @@ -1222,7 +1222,7 @@ void TransitionFade :: onEnter() FadeOut::create(_duration/2), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - nullptr + NULL ); f->runAction(a); } @@ -1321,7 +1321,7 @@ void TransitionCrossFade::onEnter() FadeTo::create(_duration, 0), CallFunc::create(CC_CALLBACK_0(TransitionScene::hideOutShowIn,this)), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - nullptr + NULL ); @@ -1392,7 +1392,7 @@ void TransitionTurnOffTiles::onEnter() action, CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), StopGrid::create(), - nullptr + NULL ) ); } @@ -1464,7 +1464,7 @@ void TransitionSplitCols::onEnter() split, CallFunc::create(CC_CALLBACK_0(TransitionSplitCols::switchTargetToInscene,this)), split->reverse(), - nullptr + NULL ); _gridProxy->runAction @@ -1474,7 +1474,7 @@ void TransitionSplitCols::onEnter() easeActionWithAction(seq), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), StopGrid::create(), - nullptr + NULL ) ); } @@ -1588,7 +1588,7 @@ void TransitionFadeTR::onEnter() easeActionWithAction(action), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), StopGrid::create(), - nullptr + NULL ) ); } diff --git a/cocos/2d/CCTransitionPageTurn.cpp b/cocos/2d/CCTransitionPageTurn.cpp index 9736dcda21..eb11e3937c 100644 --- a/cocos/2d/CCTransitionPageTurn.cpp +++ b/cocos/2d/CCTransitionPageTurn.cpp @@ -154,7 +154,7 @@ void TransitionPageTurn::onEnter() action, CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), StopGrid::create(), - nullptr + NULL ) ); } @@ -170,7 +170,7 @@ void TransitionPageTurn::onEnter() action, CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), StopGrid::create(), - nullptr + NULL ) ); } diff --git a/cocos/2d/CCTransitionProgress.cpp b/cocos/2d/CCTransitionProgress.cpp index 5735f1bb40..9ee60cf6df 100644 --- a/cocos/2d/CCTransitionProgress.cpp +++ b/cocos/2d/CCTransitionProgress.cpp @@ -95,7 +95,7 @@ void TransitionProgress::onEnter() ActionInterval* layerAction = (ActionInterval*)Sequence::create( ProgressFromTo::create(_duration, _from, _to), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - nullptr); + NULL); // run the blend action node->runAction(layerAction); diff --git a/cocos/editor-support/cocostudio/CCActionNode.cpp b/cocos/editor-support/cocostudio/CCActionNode.cpp index d615b11c46..d537dafdc2 100644 --- a/cocos/editor-support/cocostudio/CCActionNode.cpp +++ b/cocos/editor-support/cocostudio/CCActionNode.cpp @@ -351,7 +351,7 @@ void ActionNode::playAction() _action->release(); } - _action = Sequence::create(_actionSpawn, nullptr); + _action = Sequence::create(_actionSpawn, NULL); _action->retain(); this->runAction(); diff --git a/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp b/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp index e55b5c235e..6601a3214b 100644 --- a/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp +++ b/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp @@ -517,9 +517,9 @@ void ActionRotateBy3D::onEnter() auto actionBy2 = RotateBy::create(4, Vertex3F(0, 360, 0)); auto actionBy3 = RotateBy::create(4 ,Vertex3F(0, 0, 360)); - _tamara->runAction( Sequence::create(actionBy1, actionBy1->reverse(), nullptr)); - _grossini->runAction( Sequence::create(actionBy2, actionBy2->reverse(), nullptr)); - _kathia->runAction( Sequence::create(actionBy3, actionBy3->reverse(), nullptr)); + _tamara->runAction( Sequence::create(actionBy1, actionBy1->reverse(), NULL)); + _grossini->runAction( Sequence::create(actionBy2, actionBy2->reverse(), NULL)); + _kathia->runAction( Sequence::create(actionBy3, actionBy3->reverse(), NULL)); } std::string ActionRotateBy3D::subtitle() const @@ -1287,19 +1287,19 @@ void ActionOrbit::onEnter() auto action1 = Sequence::create( orbit1, orbit1->reverse(), - nullptr); + NULL); auto orbit2 = OrbitCamera::create(2,1, 0, 0, 180, -45, 0); auto action2 = Sequence::create( orbit2, orbit2->reverse(), - nullptr); + NULL); auto orbit3 = OrbitCamera::create(2,1, 0, 0, 180, 90, 0); auto action3 = Sequence::create( orbit3, orbit3->reverse(), - nullptr); + NULL); _kathia->runAction(RepeatForever::create(action1)); _tamara->runAction(RepeatForever::create(action2)); @@ -1432,7 +1432,9 @@ std::string ActionTargetedReverse::subtitle() const return "Action that runs reversely on another target. Useful for sequences"; } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) //#pragma mark - ActionStacked +#endif void ActionStacked::onEnter() { @@ -1486,8 +1488,9 @@ std::string ActionStacked::subtitle() const return "Tap screen"; } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) //#pragma mark - ActionMoveStacked - +#endif void ActionMoveStacked::runActionsInSprite(Sprite *sprite) { @@ -1513,7 +1516,9 @@ std::string ActionMoveStacked::title() const return "Stacked MoveBy/To actions"; } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) //#pragma mark - ActionMoveJumpStacked +#endif void ActionMoveJumpStacked::runActionsInSprite(Sprite *sprite) { @@ -1538,7 +1543,9 @@ std::string ActionMoveJumpStacked::title() const return "tacked Move + Jump actions"; } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) //#pragma mark - ActionMoveBezierStacked +#endif void ActionMoveBezierStacked::runActionsInSprite(Sprite *sprite) { @@ -1692,7 +1699,9 @@ std::string ActionCatmullRomStacked::subtitle() const } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) //#pragma mark - ActionCardinalSplineStacked +#endif void ActionCardinalSplineStacked::onEnter() { diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index e1043b8dc5..12d13de41e 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -179,7 +179,7 @@ void ArmatureTestLayer::onEnter() restartItem = MenuItemImage::create(s_pathR1, s_pathR2, CC_CALLBACK_1(ArmatureTestLayer::restartCallback, this) ); nextItem = MenuItemImage::create(s_pathF1, s_pathF2, CC_CALLBACK_1(ArmatureTestLayer::nextCallback, this) ); - Menu *menu = Menu::create(backItem, restartItem, nextItem, nullptr); + Menu *menu = Menu::create(backItem, restartItem, nextItem, NULL); menu->setPosition(Point::ZERO); backItem->setPosition(Point(VisibleRect::center().x - restartItem->getContentSize().width * 2, VisibleRect::bottom().y + restartItem->getContentSize().height / 2)); @@ -371,7 +371,7 @@ void TestPerformance::onEnter() MenuItemFont *increase = MenuItemFont::create(" + ", CC_CALLBACK_1(TestPerformance::onIncrease, this)); increase->setColor(Color3B(0,200,20)); - Menu *menu = Menu::create(decrease, increase, nullptr); + Menu *menu = Menu::create(decrease, increase, NULL); menu->alignItemsHorizontally(); menu->setPosition(Point(VisibleRect::getVisibleRect().size.width/2, VisibleRect::getVisibleRect().size.height-100)); addChild(menu, 10000); @@ -540,14 +540,14 @@ void TestAnimationEvent::animationEvent(Armature *armature, MovementEventType mo { ActionInterval *actionToRight = MoveTo::create(2, Point(VisibleRect::right().x - 50, VisibleRect::right().y)); armature->stopAllActions(); - armature->runAction(Sequence::create(actionToRight, CallFunc::create( CC_CALLBACK_0(TestAnimationEvent::callback1, this)), nullptr)); + armature->runAction(Sequence::create(actionToRight, CallFunc::create( CC_CALLBACK_0(TestAnimationEvent::callback1, this)), NULL)); armature->getAnimation()->play("Walk"); } else if (movementID == "FireMax") { ActionInterval *actionToLeft = MoveTo::create(2, Point(VisibleRect::left().x + 50, VisibleRect::left().y)); armature->stopAllActions(); - armature->runAction(Sequence::create(actionToLeft, CallFunc::create( CC_CALLBACK_0(TestAnimationEvent::callback2, this)), nullptr)); + armature->runAction(Sequence::create(actionToLeft, CallFunc::create( CC_CALLBACK_0(TestAnimationEvent::callback2, this)), NULL)); armature->getAnimation()->play("Walk"); } } @@ -1278,7 +1278,7 @@ void TestArmatureNesting2::onEnter() LabelTTF* label = CCLabelTTF::create("Change Mount", "Arial", 20); MenuItemLabel* pMenuItem = CCMenuItemLabel::create(label, CC_CALLBACK_1(TestArmatureNesting2::changeMountCallback, this)); - Menu* pMenu =Menu::create(pMenuItem, nullptr); + Menu* pMenu =Menu::create(pMenuItem, NULL); pMenu->setPosition( Point() ); pMenuItem->setPosition( Point( VisibleRect::right().x - 67, VisibleRect::bottom().y + 50) ); @@ -1330,7 +1330,7 @@ void TestArmatureNesting2::onTouchesEnded(const std::vector& touches, Ev ActionInterval *move = CCMoveTo::create(2, point); armature->stopAllActions(); - armature->runAction(Sequence::create(move, nullptr)); + armature->runAction(Sequence::create(move, NULL)); } void TestArmatureNesting2::changeMountCallback(Ref* pSender) diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp index 3f844b265c..7816913985 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp @@ -89,7 +89,7 @@ cocos2d::Node* ComponentsTestLayer::createGameScene() itemBack->setColor(Color3B(0, 0, 0)); itemBack->setPosition(Point(VisibleRect::rightBottom().x - 50, VisibleRect::rightBottom().y + 25)); - auto menuBack = Menu::create(itemBack, nullptr); + auto menuBack = Menu::create(itemBack, NULL); menuBack->setPosition(Point::ZERO); addChild(menuBack); diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp index c866ff4cdd..2338e13b77 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp @@ -48,7 +48,7 @@ void EnemyController::onEnter() FiniteTimeAction* actionMoveDone = CallFuncN::create( CC_CALLBACK_1(SceneController::spriteMoveFinished, static_cast( getOwner()->getParent()->getComponent("SceneController") ))); - _owner->runAction( Sequence::create(actionMove, actionMoveDone, nullptr) ); + _owner->runAction( Sequence::create(actionMove, actionMoveDone, NULL) ); } void EnemyController::onExit() diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.cpp index d9f9960045..f6e8b495e2 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.cpp @@ -69,7 +69,7 @@ bool GameOverLayer::init() this->runAction( Sequence::create( DelayTime::create(3), CallFunc::create(CC_CALLBACK_0(GameOverLayer::gameOverDone, this)), - nullptr)); + NULL)); auto itemBack = MenuItemFont::create("Back", [](Ref* sender){ @@ -80,7 +80,7 @@ bool GameOverLayer::init() itemBack->setColor(Color3B(0, 0, 0)); itemBack->setPosition(Point(VisibleRect::rightBottom().x - 50, VisibleRect::rightBottom().y + 25)); - auto menuBack = Menu::create(itemBack, nullptr); + auto menuBack = Menu::create(itemBack, NULL); menuBack->setPosition(Point::ZERO); addChild(menuBack); diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp index e8f947004e..103c568ce5 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp @@ -134,7 +134,7 @@ void SceneEditorTestLayer::onEnter() nextItem = MenuItemImage::create(s_pathF1, s_pathF2, CC_CALLBACK_1(SceneEditorTestLayer::nextCallback, this) ); - Menu *menu = Menu::create(backItem, restartItem, nextItem, nullptr); + Menu *menu = Menu::create(backItem, restartItem, nextItem, NULL); float fScale = 0.5f; @@ -473,9 +473,9 @@ cocos2d::Node* TmxMapComponentTest::createGameScene() ActionInterval *rotateToBack = RotateTo::create(2, 0); ActionInterval *actionToBack = SkewTo::create(2, 0, 0); - tmxMap->getNode()->runAction(Sequence::create(actionTo, actionToBack, nullptr)); - tmxMap->getNode()->runAction(Sequence::create(rotateTo, rotateToBack, nullptr)); - tmxMap->getNode()->runAction(Sequence::create(actionScaleTo, actionScaleToBack, nullptr)); + tmxMap->getNode()->runAction(Sequence::create(actionTo, actionToBack, NULL)); + tmxMap->getNode()->runAction(Sequence::create(rotateTo, rotateToBack, NULL)); + tmxMap->getNode()->runAction(Sequence::create(actionScaleTo, actionScaleToBack, NULL)); return node; } @@ -523,7 +523,7 @@ cocos2d::Node* ParticleComponentTest::createGameScene() ComRender* Particle = static_cast(node->getChildByTag(10020)->getComponent("CCParticleSystemQuad")); ActionInterval* jump = JumpBy::create(5, Point(-500,0), 50, 4); - FiniteTimeAction* action = Sequence::create( jump, jump->reverse(), nullptr); + FiniteTimeAction* action = Sequence::create( jump, jump->reverse(), NULL); Particle->getNode()->runAction(action); return node; } diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.cpp index 4449d2cd9d..dbc0a8ae0e 100755 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.cpp @@ -161,7 +161,7 @@ void TMoveBy::done() if (_reverse == true) { ActionInterval* actionByBack = actionBy->reverse(); - node->runAction( CCSequence::create(actionBy, actionByBack, nullptr)); + node->runAction( CCSequence::create(actionBy, actionByBack, NULL)); } else { @@ -304,7 +304,7 @@ void TRotateBy::done() if (_reverse == true) { ActionInterval* actionByBack = actionBy->reverse(); - node->runAction( Sequence::create(actionBy, actionByBack, nullptr)); + node->runAction( Sequence::create(actionBy, actionByBack, NULL)); } else { @@ -445,7 +445,7 @@ void TScaleBy::done() if (_reverse == true) { ActionInterval* actionByBack = actionBy->reverse(); - node->runAction(Sequence::create(actionBy, actionByBack, nullptr)); + node->runAction(Sequence::create(actionBy, actionByBack, NULL)); } else { @@ -591,7 +591,7 @@ void TSkewBy::done() if (_reverse == true) { ActionInterval* actionByBack = actionBy->reverse(); - node->runAction(Sequence::create(actionBy, actionByBack, nullptr)); + node->runAction(Sequence::create(actionBy, actionByBack, NULL)); } else { diff --git a/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp b/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp index 01b5cb1335..aad6a21d87 100644 --- a/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp +++ b/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp @@ -1275,7 +1275,7 @@ LabelTTFDistanceField::LabelTTFDistanceField() DelayTime::create(1.0f), ScaleTo::create(6.0f,5.0f,5.0f), ScaleTo::create(6.0f,1.0f,1.0f), - nullptr); + NULL); label1->runAction(RepeatForever::create(action)); auto label2 = Label::createWithTTF(ttfConfig,"Distance Field",TextHAlignment::CENTER,size.width); diff --git a/tests/cpp-tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp b/tests/cpp-tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp index 9852b62323..80fa5c04b4 100644 --- a/tests/cpp-tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp +++ b/tests/cpp-tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp @@ -206,7 +206,7 @@ void TouchableSpriteTest::onEnter() removeAllTouchItem->setFontSizeObj(16); removeAllTouchItem->setPosition(VisibleRect::right() + Point(-100, 0)); - auto menu = Menu::create(removeAllTouchItem, nullptr); + auto menu = Menu::create(removeAllTouchItem, NULL); menu->setPosition(Point(0, 0)); menu->setAnchorPoint(Point(0, 0)); addChild(menu); @@ -402,7 +402,7 @@ void RemoveListenerWhenDispatching::onEnter() }, MenuItemFont::create("Enabled"), MenuItemFont::create("Disabled"), NULL); toggleItem->setPosition(origin + Point(size.width/2, 80)); - auto menu = Menu::create(toggleItem, nullptr); + auto menu = Menu::create(toggleItem, NULL); menu->setPosition(Point(0, 0)); menu->setAnchorPoint(Point(0, 0)); addChild(menu, -1); @@ -480,7 +480,7 @@ void CustomEventTest::onEnter() }); sendItem2->setPosition(origin + Point(size.width/2, size.height/2 - 40)); - auto menu = Menu::create(sendItem, sendItem2, nullptr); + auto menu = Menu::create(sendItem, sendItem2, NULL); menu->setPosition(Point(0, 0)); menu->setAnchorPoint(Point(0, 0)); addChild(menu, -1); @@ -656,7 +656,7 @@ void RemoveAndRetainNodeTest::onEnter() this->addChild(_sprite); _sprite->release(); }), - nullptr + NULL )); } @@ -703,7 +703,7 @@ void RemoveListenerAfterAddingTest::onEnter() }); next->setPosition(VisibleRect::center() + Point(0, -40)); - auto menu = Menu::create(next, nullptr); + auto menu = Menu::create(next, NULL); menu->setPosition(VisibleRect::leftBottom()); menu->setAnchorPoint(Point::ZERO); this->addChild(menu); @@ -739,7 +739,7 @@ void RemoveListenerAfterAddingTest::onEnter() item3->setPosition(VisibleRect::center()); - auto menu = Menu::create(item1, item2, item3, nullptr); + auto menu = Menu::create(item1, item2, item3, NULL); menu->setPosition(VisibleRect::leftBottom()); menu->setAnchorPoint(Point::ZERO); @@ -1149,7 +1149,7 @@ PauseResumeTargetTest::PauseResumeTargetTest() popup->setAnchorPoint(Point::ANCHOR_MIDDLE_RIGHT); popup->setPosition(VisibleRect::right()); - auto menu = Menu::create(popup, nullptr); + auto menu = Menu::create(popup, NULL); menu->setAnchorPoint(Point::ANCHOR_BOTTOM_LEFT); menu->setPosition(Point::ZERO); @@ -1214,7 +1214,7 @@ Issue4129::Issue4129() removeAllTouchItem->setFontSizeObj(16); removeAllTouchItem->setPosition(VisibleRect::right() + Point(-100, 0)); - auto menu = Menu::create(removeAllTouchItem, nullptr); + auto menu = Menu::create(removeAllTouchItem, NULL); menu->setPosition(Point(0, 0)); menu->setAnchorPoint(Point(0, 0)); addChild(menu); diff --git a/tests/cpp-tests/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id b/tests/cpp-tests/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id index b98c1b9d46..16313475b7 100644 --- a/tests/cpp-tests/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id +++ b/tests/cpp-tests/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id @@ -1 +1 @@ -4bb0b2a6151e4910ea662bedd91a5be655ec05d1 \ No newline at end of file +6b26ef0158192c2d538b79758cda7ee7233a2f89 \ No newline at end of file From 44e6efea64dbb13707a94a48033fbfacd6206c5f Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 06:08:05 -0700 Subject: [PATCH 017/106] #pragma mark for ios and mac only --- cocos/2d/CCNode.h | 2 ++ cocos/2d/CCProfiling.cpp | 3 +++ cocos/2d/CCScriptSupport.cpp | 9 +++++++- cocos/ui/GUIDefine.h | 18 ++++++++++------ .../CCControlExtension/CCControlStepper.cpp | 3 +++ .../ClippingNodeTest/ClippingNodeTest.cpp | 21 ++++++++++++++++++- .../CustomImageTest/CustomImageTest.cpp | 4 ++++ .../CustomParticleWidgetTest.cpp | 4 ++++ .../Classes/FileUtilsTest/FileUtilsTest.cpp | 12 +++++++++++ .../cpp-tests/Classes/LayerTest/LayerTest.cpp | 2 ++ 10 files changed, 70 insertions(+), 8 deletions(-) diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index 249ef11de9..035a2f720a 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -1456,7 +1456,9 @@ private: CC_DISALLOW_COPY_AND_ASSIGN(Node); }; +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) //#pragma mark - NodeRGBA +#endif /** NodeRGBA is a subclass of Node that implements the RGBAProtocol protocol. diff --git a/cocos/2d/CCProfiling.cpp b/cocos/2d/CCProfiling.cpp index 3f6979a951..11ee529ce6 100644 --- a/cocos/2d/CCProfiling.cpp +++ b/cocos/2d/CCProfiling.cpp @@ -31,7 +31,10 @@ using namespace std; NS_CC_BEGIN +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) //#pragma mark - Profiling Categories +#endif + /* set to false the categories that you don't want to profile */ bool kProfilerCategorySprite = false; bool kProfilerCategoryBatchSprite = false; diff --git a/cocos/2d/CCScriptSupport.cpp b/cocos/2d/CCScriptSupport.cpp index 78cd476547..ccc8ed48a5 100644 --- a/cocos/2d/CCScriptSupport.cpp +++ b/cocos/2d/CCScriptSupport.cpp @@ -41,8 +41,10 @@ bool CC_DLL cc_assert_script_compatible(const char *msg) NS_CC_BEGIN +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) // #pragma mark - // #pragma mark ScriptHandlerEntry +#endif ScriptHandlerEntry* ScriptHandlerEntry::create(int handler) { @@ -61,8 +63,10 @@ ScriptHandlerEntry::~ScriptHandlerEntry(void) } } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) // #pragma mark - // #pragma mark SchedulerScriptHandlerEntry +#endif SchedulerScriptHandlerEntry* SchedulerScriptHandlerEntry::create(int handler, float interval, bool paused) { @@ -87,9 +91,10 @@ SchedulerScriptHandlerEntry::~SchedulerScriptHandlerEntry(void) LUALOG("[LUA] DEL script schedule %d, entryID: %d", _handler, _entryId); } - +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) // #pragma mark - // #pragma mark TouchScriptHandlerEntry +#endif TouchScriptHandlerEntry* TouchScriptHandlerEntry::create(int handler, bool isMultiTouches, @@ -115,8 +120,10 @@ bool TouchScriptHandlerEntry::init(bool isMultiTouches, int priority, bool swall return true; } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) // #pragma mark - // #pragma mark ScriptEngineManager +#endif static ScriptEngineManager* s_pSharedScriptEngineManager = nullptr; diff --git a/cocos/ui/GUIDefine.h b/cocos/ui/GUIDefine.h index 788439e7aa..59d36a0b34 100644 --- a/cocos/ui/GUIDefine.h +++ b/cocos/ui/GUIDefine.h @@ -30,9 +30,12 @@ #include #include "cocostudio/ObjectFactory.h" -//#pragma mark - -//#pragma mark Widget macro -//#pragma mark - +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) +#pragma mark - +#pragma mark Widget macro +#pragma mark - +#endif + #define DECLARE_CLASS_GUI_INFO \ public: \ @@ -50,9 +53,12 @@ cocostudio::ObjectFactory::TInfo(#className, &className::createInstance) \ -//#pragma mark - -//#pragma mark Reader macro -//#pragma mark - +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) +#pragma mark - +#pragma mark Reader macro +#pragma mark - +#endif + #define DECLARE_CLASS_WIDGET_READER_INFO \ public: \ diff --git a/extensions/GUI/CCControlExtension/CCControlStepper.cpp b/extensions/GUI/CCControlExtension/CCControlStepper.cpp index 4c4df49589..721c9e17e3 100644 --- a/extensions/GUI/CCControlExtension/CCControlStepper.cpp +++ b/extensions/GUI/CCControlExtension/CCControlStepper.cpp @@ -188,8 +188,11 @@ bool ControlStepper::isContinuous() const { return _continuous; } + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) //#pragma mark - //#pragma mark ControlStepper Public Methods +#endif void ControlStepper::setValueWithSendingEvent(double value, bool send) { diff --git a/tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.cpp b/tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.cpp index da1423de7f..301e397be1 100644 --- a/tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.cpp +++ b/tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.cpp @@ -130,7 +130,9 @@ void BaseClippingNodeTest::setup() } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) //#pragma mark - BasicTest +#endif std::string BasicTest::title() const { @@ -209,7 +211,9 @@ Node* BasicTest::content() } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) //#pragma mark - ShapeTest +#endif std::string ShapeTest::title() const { @@ -235,8 +239,9 @@ Node* ShapeTest::content() return node; } - +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) //#pragma mark - ShapeInvertedTest +#endif std::string ShapeInvertedTest::title() const { @@ -255,7 +260,9 @@ ClippingNode* ShapeInvertedTest::clipper() return clipper; } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) //#pragma mark - SpriteTest +#endif std::string SpriteTest::title() const { @@ -288,7 +295,9 @@ Node* SpriteTest::content() return node; } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) //#pragma mark - SpriteNoAlphaTest +#endif std::string SpriteNoAlphaTest::title() const { @@ -307,7 +316,9 @@ ClippingNode* SpriteNoAlphaTest::clipper() return clipper; } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) //#pragma mark - SpriteInvertedTest +#endif std::string SpriteInvertedTest::title() const { @@ -327,7 +338,9 @@ ClippingNode* SpriteInvertedTest::clipper() return clipper; } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) //#pragma mark - NestedTest +#endif std::string NestedTest::title() const { @@ -372,7 +385,9 @@ void NestedTest::setup() } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) //#pragma mark - HoleDemo +#endif HoleDemo::~HoleDemo() { @@ -467,7 +482,9 @@ void HoleDemo::onTouchesBegan(const std::vector& touches, Event* event) this->pokeHoleAtPoint(point); } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) //#pragma mark - ScrollViewDemo +#endif std::string ScrollViewDemo::title() const { @@ -543,7 +560,9 @@ void ScrollViewDemo::onTouchesEnded(const std::vector& touches, Event * _scrolling = false; } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) //#pragma mark - RawStencilBufferTests +#endif //#if COCOS2D_DEBUG > 1 diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/CustomTest/CustomImageTest/CustomImageTest.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/CustomTest/CustomImageTest/CustomImageTest.cpp index 4c65ddaae0..e32efbf736 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/CustomTest/CustomImageTest/CustomImageTest.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/CustomTest/CustomImageTest/CustomImageTest.cpp @@ -10,9 +10,11 @@ USING_NS_CC; USING_NS_CC_EXT; +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) #pragma mark - #pragma mark CustomImageLayer #pragma mark - +#endif void CustomImageLayer::onEnter() { @@ -28,9 +30,11 @@ void CustomImageLayer::onEnter() addChild(layout); } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) #pragma mark - #pragma mark CustomImageScene #pragma mark - +#endif void CustomImageScene::onEnter() { diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/CustomTest/CustomParticleWidgetTest/CustomParticleWidgetTest.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/CustomTest/CustomParticleWidgetTest/CustomParticleWidgetTest.cpp index 2b328fdbda..ae956b8097 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/CustomTest/CustomParticleWidgetTest/CustomParticleWidgetTest.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/CustomTest/CustomParticleWidgetTest/CustomParticleWidgetTest.cpp @@ -18,9 +18,11 @@ USING_NS_CC_EXT; using namespace ui; using namespace cocostudio; +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) #pragma mark - #pragma mark CustomParticleWidgetLayer #pragma mark - +#endif void CustomParticleWidgetLayer::onEnter() { @@ -38,9 +40,11 @@ void CustomParticleWidgetLayer::onEnter() addChild(custom, 10, -1); } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) #pragma mark - #pragma mark CustomImageScene #pragma mark - +#endif void CustomParticleWidgetScene::onEnter() { diff --git a/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp b/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp index 646d0f04be..b0a7bf17ce 100644 --- a/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp +++ b/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp @@ -45,7 +45,9 @@ void FileUtilsTestScene::runThisTest() Director::getInstance()->replaceScene(this); } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) // #pragma mark - FileUtilsDemo +#endif void FileUtilsDemo::onEnter() { @@ -92,7 +94,9 @@ std::string FileUtilsDemo::subtitle() const return ""; } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) //#pragma mark - TestResolutionDirectories +#endif void TestResolutionDirectories::onEnter() { @@ -146,7 +150,9 @@ std::string TestResolutionDirectories::subtitle() const return "See the console"; } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) //#pragma mark - TestSearchPath +#endif void TestSearchPath::onEnter() { @@ -225,7 +231,9 @@ std::string TestSearchPath::subtitle() const return "See the console"; } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) //#pragma mark - TestFilenameLookup +#endif void TestFilenameLookup::onEnter() { @@ -263,7 +271,9 @@ std::string TestFilenameLookup::title() const return "FileUtils: filename lookup"; } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) //#pragma mark - TestIsFileExist +#endif void TestIsFileExist::onEnter() { @@ -307,7 +317,9 @@ std::string TestIsFileExist::subtitle() const return ""; } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) //#pragma mark - TestWritePlist +#endif void TextWritePlist::onEnter() { diff --git a/tests/cpp-tests/Classes/LayerTest/LayerTest.cpp b/tests/cpp-tests/Classes/LayerTest/LayerTest.cpp index 4597a9a716..a3c82737c8 100644 --- a/tests/cpp-tests/Classes/LayerTest/LayerTest.cpp +++ b/tests/cpp-tests/Classes/LayerTest/LayerTest.cpp @@ -111,7 +111,9 @@ void LayerTest::backCallback(Ref* sender) s->release(); } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) //#pragma mark - Cascading support extensions +#endif static void setEnableRecursiveCascading(Node* node, bool enable) { From bfaa5882feed801044343a48e889b8fe7dca5e3d Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 06:09:16 -0700 Subject: [PATCH 018/106] fix for RELATIVE reserved word in wp8 compiler --- cocos/2d/CCParticleSystem.h | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/cocos/2d/CCParticleSystem.h b/cocos/2d/CCParticleSystem.h index 74d6bab382..921a694c88 100644 --- a/cocos/2d/CCParticleSystem.h +++ b/cocos/2d/CCParticleSystem.h @@ -125,6 +125,13 @@ emitter.startSpin = 0; @endcode */ + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) +#ifdef RELATIVE +#undef RELATIVE +#endif +#endif + class CC_DLL ParticleSystem : public Node, public TextureProtocol { public: From 6ee7f5d325af319618564386ce1ef95fdcbd8eaa Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 06:09:48 -0700 Subject: [PATCH 019/106] added CC_PLATFORM_WINRT and WP8 --- cocos/2d/cocos2d.h | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/cocos/2d/cocos2d.h b/cocos/2d/cocos2d.h index 6e4b798715..e1699ab5af 100644 --- a/cocos/2d/cocos2d.h +++ b/cocos/2d/cocos2d.h @@ -195,6 +195,22 @@ THE SOFTWARE. #include "platform/linux/CCStdC.h" #endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) + #include "platform/winrt/CCApplication.h" + #include "platform/winrt/CCGLView.h" + #include "platform/winrt/CCGL.h" + #include "platform/winrt/CCStdC.h" + #include "platform/winrt/CCPrecompiledShaders.h" +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_WINRT + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) + #include "platform/winrt/CCApplication.h" + #include "platform/wp8/CCGLView.h" + #include "platform/winrt/CCGL.h" + #include "platform/winrt/CCStdC.h" + #include "platform/winrt/CCPrecompiledShaders.h" +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_WP8 + // script_support #include "CCScriptSupport.h" From aa0dae4d1f87be150b798b98229b111f42019de5 Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 06:10:07 -0700 Subject: [PATCH 020/106] added CC_PLATFORM_WINRT and WP8 --- cocos/2d/ZipUtils.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/ZipUtils.h b/cocos/2d/ZipUtils.h index 3611679248..8a342d9ac5 100644 --- a/cocos/2d/ZipUtils.h +++ b/cocos/2d/ZipUtils.h @@ -32,7 +32,7 @@ THE SOFTWARE. #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #include "platform/android/CCFileUtilsAndroid.h" -#elif(CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) +#elif(CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) // for import ssize_t on win32 platform #include "CCStdC.h" #endif From 6a4d459c77a9a6561e9e80f1ffd01bd361336634 Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 06:10:54 -0700 Subject: [PATCH 021/106] Disabled console for wp8/winrt until networking code is added --- cocos/base/CCConsole.cpp | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index c58b933384..0f9d7f625f 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -106,6 +106,8 @@ static bool isFloat( std::string myString ) { return iss.eof() && !iss.fail(); } +#if CC_TARGET_PLATFORM != CC_PLATFORM_WINRT && CC_TARGET_PLATFORM != CC_PLATFORM_WP8 + // helper free functions // dprintf() is not defined in Android @@ -176,6 +178,7 @@ static void printFileUtils(int fd) } sendPrompt(fd); } +#endif #if defined(__MINGW32__) @@ -210,20 +213,22 @@ static void _log(const char *format, va_list args) #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID __android_log_print(ANDROID_LOG_DEBUG, "cocos2d-x debug info", "%s", buf); -#elif CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 +#elif CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT || CC_TARGET_PLATFORM == CC_PLATFORM_WP8 WCHAR wszBuf[MAX_LOG_LENGTH] = {0}; MultiByteToWideChar(CP_UTF8, 0, buf, -1, wszBuf, sizeof(wszBuf)); OutputDebugStringW(wszBuf); WideCharToMultiByte(CP_ACP, 0, wszBuf, -1, buf, sizeof(buf), NULL, FALSE); printf("%s", buf); - #else // Linux, Mac, iOS, etc fprintf(stdout, "cocos2d: %s", buf); fflush(stdout); #endif +#if (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT) && (CC_TARGET_PLATFORM != CC_PLATFORM_WP8) Director::getInstance()->getConsole()->log(buf); +#endif + } // XXX: Deprecated @@ -243,6 +248,8 @@ void log(const char * format, ...) va_end(args); } +#if (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT) && (CC_TARGET_PLATFORM != CC_PLATFORM_WP8) + // // Console code // @@ -1081,4 +1088,7 @@ void Console::loop() _running = false; } +#endif /* #if (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT) && (CC_TARGET_PLATFORM != CC_PLATFORM_WP8) */ + + NS_CC_END From 347f91fcb629957d72a00b75415845b0bc31adec Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 06:11:10 -0700 Subject: [PATCH 022/106] Disabled console for wp8/winrt until networking code is added --- cocos/base/CCConsole.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/cocos/base/CCConsole.h b/cocos/base/CCConsole.h index 66ae38e54e..04d1d622ae 100644 --- a/cocos/base/CCConsole.h +++ b/cocos/base/CCConsole.h @@ -68,6 +68,8 @@ void CC_DLL log(const char * format, ...) CC_FORMAT_PRINTF(1, 2); scheduler->performFunctionInCocosThread( ... ); ``` */ + +#if (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT) && (CC_TARGET_PLATFORM != CC_PLATFORM_WP8) class CC_DLL Console { public: @@ -142,6 +144,7 @@ private: CC_DISALLOW_COPY_AND_ASSIGN(Console); }; +#endif /* #if (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT) && (CC_TARGET_PLATFORM != CC_PLATFORM_WP8) */ NS_CC_END #endif /* defined(__CCCONSOLE_H__) */ From a14728f1848d73d5db2ab50c7da2d88196d4cb07 Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 06:11:27 -0700 Subject: [PATCH 023/106] added CC_PLATFORM_WINRT and WP8 --- cocos/base/CCPlatformConfig.h | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/cocos/base/CCPlatformConfig.h b/cocos/base/CCPlatformConfig.h index 7d171b8d8b..f9e5e698a3 100644 --- a/cocos/base/CCPlatformConfig.h +++ b/cocos/base/CCPlatformConfig.h @@ -48,6 +48,8 @@ Config of cocos2d-x project, per target platform. #define CC_PLATFORM_EMSCRIPTEN 10 #define CC_PLATFORM_TIZEN 11 #define CC_PLATFORM_QT5 12 +#define CC_PLATFORM_WP8 13 +#define CC_PLATFORM_WINRT 14 // Determine target platform by compile environment macro. #define CC_TARGET_PLATFORM CC_PLATFORM_UNKNOWN @@ -124,6 +126,19 @@ Config of cocos2d-x project, per target platform. #define CC_TARGET_PLATFORM CC_PLATFORM_QT5 #endif +// WinRT (Windows Store App) +#if defined(WINRT) + #undef CC_TARGET_PLATFORM + #define CC_TARGET_PLATFORM CC_PLATFORM_WINRT +#endif + +// WP8 (Windows Phone 8 App) +#if defined(WP8) + #undef CC_TARGET_PLATFORM + #define CC_TARGET_PLATFORM CC_PLATFORM_WP8 +#endif + + ////////////////////////////////////////////////////////////////////////// // post configure ////////////////////////////////////////////////////////////////////////// From 762433e8aac0e09b9ef4bfef3202f556e07a0b7d Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 06:12:04 -0700 Subject: [PATCH 024/106] enable CC_ENABLE_CACHE_TEXTURE_DATA for wp8 --- cocos/base/CCPlatformMacros.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/base/CCPlatformMacros.h b/cocos/base/CCPlatformMacros.h index 426d898420..f711cbfdee 100644 --- a/cocos/base/CCPlatformMacros.h +++ b/cocos/base/CCPlatformMacros.h @@ -82,7 +82,7 @@ to be different from other platforms unless there's a good reason. It's new in cocos2d-x since v0.99.5 */ -#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) +#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) #define CC_ENABLE_CACHE_TEXTURE_DATA 1 #else #define CC_ENABLE_CACHE_TEXTURE_DATA 0 From 3834d4e80b08f4bf0a4345f44bcd42cbf8cde811 Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 06:12:32 -0700 Subject: [PATCH 025/106] fix for ABSOLUTE reserved word in wp8 compiler --- cocos/editor-support/cocosbuilder/CCBReader.h | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/cocos/editor-support/cocosbuilder/CCBReader.h b/cocos/editor-support/cocosbuilder/CCBReader.h index 0fc9bef999..6fbcb3ef19 100644 --- a/cocos/editor-support/cocosbuilder/CCBReader.h +++ b/cocos/editor-support/cocosbuilder/CCBReader.h @@ -128,7 +128,12 @@ public: PERCENT, MULTIPLY_RESOLUTION, }; - + +#if CC_TARGET_PLATFORM == CC_PLATFORM_WP8 +#ifdef ABSOLUTE +#undef ABSOLUTE +#endif +#endif enum class SizeType { ABSOLUTE, From ea9fb140fad0619bb12db39271bb65c6072562d8 Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 06:13:02 -0700 Subject: [PATCH 026/106] no mp3 support for wp8 --- cocos/editor-support/cocostudio/CCComAudio.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/cocos/editor-support/cocostudio/CCComAudio.cpp b/cocos/editor-support/cocostudio/CCComAudio.cpp index e232d07569..04d4efd235 100644 --- a/cocos/editor-support/cocostudio/CCComAudio.cpp +++ b/cocos/editor-support/cocostudio/CCComAudio.cpp @@ -97,6 +97,15 @@ bool ComAudio::serialize(void* r) CC_BREAK_IF(resType != 0); if (strcmp(className, "CCBackgroundAudio") == 0) { +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) + // no MP3 support for CC_PLATFORM_WP8 + std::string::size_type pos = filePath.find(".mp3"); + if (pos == filePath.npos) + { + continue; + } + filePath.replace(pos, filePath.length(), ".wav"); +#endif preloadBackgroundMusic(filePath.c_str()); bool loop = DICTOOL->getIntValue_json(*v, "loop") != 0? true:false; setLoop(loop); From 60d967b5f6d98249893dbed517536d97c0fd2ad3 Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 06:13:27 -0700 Subject: [PATCH 027/106] added CC_PLATFORM_WINRT and WP8 --- extensions/assets-manager/AssetsManager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/assets-manager/AssetsManager.cpp b/extensions/assets-manager/AssetsManager.cpp index b8a3717de5..51aba846bb 100644 --- a/extensions/assets-manager/AssetsManager.cpp +++ b/extensions/assets-manager/AssetsManager.cpp @@ -30,7 +30,7 @@ #include #include -#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) +#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) && (CC_TARGET_PLATFORM != CC_PLATFORM_WP8) && (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT) #include #include #include From 4df55dc6ee169e9003c801726735200997178749 Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 06:14:03 -0700 Subject: [PATCH 028/106] no mp3 support for wp8. Added define for .wav --- tests/cpp-tests/Classes/CocosDenshionTest/CocosDenshionTest.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/cpp-tests/Classes/CocosDenshionTest/CocosDenshionTest.cpp b/tests/cpp-tests/Classes/CocosDenshionTest/CocosDenshionTest.cpp index 9ae653f43b..66ec4c4a02 100644 --- a/tests/cpp-tests/Classes/CocosDenshionTest/CocosDenshionTest.cpp +++ b/tests/cpp-tests/Classes/CocosDenshionTest/CocosDenshionTest.cpp @@ -14,6 +14,8 @@ #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) #define MUSIC_FILE "music.mid" +#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) + #define MUSIC_FILE "background.wav" #elif (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY || CC_TARGET_PLATFORM == CC_PLATFORM_LINUX ) #define MUSIC_FILE "background.ogg" #elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) From 4c03c526c19df989306e93025176b520b549ac47 Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 06:14:44 -0700 Subject: [PATCH 029/106] added missing virtual. disabled console for wp8/winrt until networking code is added --- tests/cpp-tests/Classes/ConsoleTest/ConsoleTest.h | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/cpp-tests/Classes/ConsoleTest/ConsoleTest.h b/tests/cpp-tests/Classes/ConsoleTest/ConsoleTest.h index d5b5788488..e188228ed2 100644 --- a/tests/cpp-tests/Classes/ConsoleTest/ConsoleTest.h +++ b/tests/cpp-tests/Classes/ConsoleTest/ConsoleTest.h @@ -40,9 +40,9 @@ public: virtual std::string title() const override; virtual void onEnter() override; - void restartCallback(Ref* sender) override; - void nextCallback(Ref* sender) override; - void backCallback(Ref* sender) override; + virtual void restartCallback(Ref* sender) override; + virtual void nextCallback(Ref* sender) override; + virtual void backCallback(Ref* sender) override; }; @@ -59,7 +59,10 @@ protected: ConsoleCustomCommand(); virtual ~ConsoleCustomCommand(); +#if (CC_TARGET_PLATFORM != CC_PLATFORM_WP8) && (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT) cocos2d::Console *_console; +#endif + private: CC_DISALLOW_COPY_AND_ASSIGN(ConsoleCustomCommand); }; From 2a13bbccc9da087c447a7a6b10fd4ba885b781ca Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 06:15:18 -0700 Subject: [PATCH 030/106] disabled network tests for wp8/winrt until networking code is added --- tests/cpp-tests/Classes/ExtensionsTest/ExtensionsTest.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/cpp-tests/Classes/ExtensionsTest/ExtensionsTest.cpp b/tests/cpp-tests/Classes/ExtensionsTest/ExtensionsTest.cpp index 98ca91efd0..5e4c84f5a9 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/ExtensionsTest.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/ExtensionsTest.cpp @@ -3,7 +3,7 @@ #include "NotificationCenterTest/NotificationCenterTest.h" #include "ControlExtensionTest/CCControlSceneManager.h" #include "CocosBuilderTest/CocosBuilderTest.h" -#if (CC_TARGET_PLATFORM != CC_PLATFORM_EMSCRIPTEN) && (CC_TARGET_PLATFORM != CC_PLATFORM_NACL) +#if (CC_TARGET_PLATFORM != CC_PLATFORM_EMSCRIPTEN) && (CC_TARGET_PLATFORM != CC_PLATFORM_NACL) && (CC_TARGET_PLATFORM != CC_PLATFORM_WP8) && (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT) #include "NetworkTest/HttpClientTest.h" #endif #include "TableViewTest/TableViewTestScene.h" @@ -58,7 +58,7 @@ static struct { scene->release(); } }}, -#if (CC_TARGET_PLATFORM != CC_PLATFORM_EMSCRIPTEN) && (CC_TARGET_PLATFORM != CC_PLATFORM_NACL) +#if (CC_TARGET_PLATFORM != CC_PLATFORM_EMSCRIPTEN) && (CC_TARGET_PLATFORM != CC_PLATFORM_NACL) && (CC_TARGET_PLATFORM != CC_PLATFORM_WP8) && (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT) { "HttpClientTest", [](Ref *sender){ runHttpClientTest();} }, #endif From 0d4ae12f1ed31de2aecec894f9d4513b7cdf19f0 Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 06:15:45 -0700 Subject: [PATCH 031/106] disables webp tests for wp8 and winrt --- tests/cpp-tests/Classes/Texture2dTest/Texture2dTest.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/cpp-tests/Classes/Texture2dTest/Texture2dTest.cpp b/tests/cpp-tests/Classes/Texture2dTest/Texture2dTest.cpp index 4f80334657..b202eb1c6e 100644 --- a/tests/cpp-tests/Classes/Texture2dTest/Texture2dTest.cpp +++ b/tests/cpp-tests/Classes/Texture2dTest/Texture2dTest.cpp @@ -79,7 +79,9 @@ static std::function createFunctions[] = CL(TextureJPEG), CL(TextureTIFF), CL(TextureTGA), +#if (CC_TARGET_PLATFORM != CC_PLATFORM_WP8) && (CC_TARGET_PLATFORM != CC_PLATFORM_INRT) CL(TextureWEBP), +#endif CL(TexturePixelFormat), CL(TextureBlend), CL(TextureAsync), From 912d316ae5a0db56d11577573d577b9acfbe86fd Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 06:16:43 -0700 Subject: [PATCH 032/106] use ResolutionPolicy::SHOW_ALL for winrt/wp8. disabled console for wp8/winrt --- tests/cpp-tests/Classes/AppDelegate.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/cpp-tests/Classes/AppDelegate.cpp b/tests/cpp-tests/Classes/AppDelegate.cpp index d62b6c9ef9..9c36a00913 100644 --- a/tests/cpp-tests/Classes/AppDelegate.cpp +++ b/tests/cpp-tests/Classes/AppDelegate.cpp @@ -102,19 +102,28 @@ bool AppDelegate::applicationDidFinishLaunching() fileUtils->setSearchPaths(searchPaths); // glview->setDesignResolutionSize(screenSize.width, screenSize.height, ResolutionPolicy::NO_BORDER); +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) + glview->setDesignResolutionSize(designSize.width, designSize.height, ResolutionPolicy::SHOW_ALL); +#else glview->setDesignResolutionSize(designSize.width, designSize.height, ResolutionPolicy::NO_BORDER); +#endif auto scene = Scene::create(); auto layer = new TestController(); +#if (CC_TARGET_PLATFORM != CC_PLATFORM_WP8) && (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT) layer->addConsoleAutoTest(); +#endif + layer->autorelease(); scene->addChild(layer); director->runWithScene(scene); // Enable Remote Console +#if (CC_TARGET_PLATFORM != CC_PLATFORM_WP8) && (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT) auto console = director->getConsole(); console->listenOnTCP(5678); +#endif return true; } From 62e45b37f909a35fbff381044ccfbc485237d57d Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Sat, 22 Mar 2014 06:17:34 -0700 Subject: [PATCH 033/106] disabled console for wp8/winrt. Don't quit app for winrt/wp8 --- tests/cpp-tests/Classes/controller.cpp | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/tests/cpp-tests/Classes/controller.cpp b/tests/cpp-tests/Classes/controller.cpp index 3c391c6b3e..e6213f337e 100644 --- a/tests/cpp-tests/Classes/controller.cpp +++ b/tests/cpp-tests/Classes/controller.cpp @@ -12,7 +12,7 @@ #include "testResource.h" #include "tests.h" -#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) +#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) && (CC_TARGET_PLATFORM != CC_PLATFORM_WP8) && (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT) #include #include #else @@ -42,7 +42,13 @@ Controller g_aTestNames[] = { { "Chipmunk", []() { return new ChipmunkAccelTouchTestScene(); } }, { "Click and Move", [](){return new ClickAndMoveTestScene(); } }, { "Configuration", []() { return new ConfigurationTestScene(); } }, +#if (CC_TARGET_PLATFORM != CC_PLATFORM_WP8) +#if (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT) { "Console", []() { return new ConsoleTestScene(); } }, +#endif +#endif +#if (CC_TARGET_PLATFORM != CC_PLATFORM_WP8) +#if (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT) #if (CC_TARGET_PLATFORM != CC_PLATFORM_EMSCRIPTEN) #if (CC_TARGET_PLATFORM != CC_PLATFORM_NACL) #if (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE) @@ -51,6 +57,8 @@ Controller g_aTestNames[] = { #endif #endif #endif +#endif +#endif #endif { "Current Language", []() { return new CurrentLanguageTestScene(); } }, { "EventDispatcher", []() { return new EventDispatcherTestScene(); } }, @@ -180,6 +188,11 @@ void TestController::menuCallback(Ref * sender) void TestController::closeCallback(Ref * sender) { +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) + MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert"); + return; +#endif + Director::getInstance()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); @@ -241,6 +254,7 @@ void TestController::onMouseScroll(Event *event) s_tCurPos = nextPos; } +#if (CC_TARGET_PLATFORM != CC_PLATFORM_WP8) && (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT) void TestController::addConsoleAutoTest() { auto console = Director::getInstance()->getConsole(); @@ -435,4 +449,5 @@ void TestController::addConsoleAutoTest() }; console->addCommand(autotest); } +#endif From f5795c25b6d8f1c6f30b0fe127c9575ee0c1beff Mon Sep 17 00:00:00 2001 From: andyque Date: Mon, 24 Mar 2014 10:12:40 +0800 Subject: [PATCH 034/106] remove warnings under win32 --- cocos/2d/CCEventDispatcher.cpp | 2 +- cocos/2d/CCFontFreeType.cpp | 2 +- cocos/2d/CCTMXLayer.cpp | 2 +- cocos/2d/cocos2d.vcxproj | 4 ++- .../cocostudio/CCActionNode.cpp | 6 ++-- cocos/editor-support/cocostudio/CCSkin.cpp | 4 +-- cocos/ui/UIRichText.cpp | 6 ++-- .../CocoStudioArmatureTest/ArmatureScene.cpp | 2 +- .../CustomWidget/CustomImageView.cpp | 2 +- .../CustomWidget/CustomParticleWidget.cpp | 2 +- .../UILayoutTest/UILayoutTest_Editor.cpp | 36 +++++++++---------- .../UIListViewTest/UIListViewTest_Editor.cpp | 8 ++--- .../UIPageViewTest/UIPageViewTest_Editor.cpp | 4 +-- .../UIRichTextTest/UIRichTextTest.cpp | 4 +-- .../UIScrollViewTest_Editor.cpp | 12 +++---- .../UITextFieldTest/UITextFieldTest.cpp | 4 +-- .../UIWidgetAddNodeTest_Editor.cpp | 2 +- .../CocoStudioSceneTest/TriggerCode/acts.cpp | 8 ++--- .../CocoStudioSceneTest/TriggerCode/cons.cpp | 2 +- .../Classes/PhysicsTest/PhysicsTest.cpp | 18 +++++----- .../RenderTextureTest/RenderTextureTest.cpp | 24 ++++++------- .../SpriteTest/SpriteTest.cpp.REMOVED.git-id | 2 +- .../Classes/TileMapTest/TileMapTest.cpp | 8 ++--- .../Classes/ZwoptexTest/ZwoptexTest.cpp | 4 +-- tests/cpp-tests/proj.win32/cpp-tests.vcxproj | 14 +++++--- 25 files changed, 95 insertions(+), 87 deletions(-) mode change 100755 => 100644 tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.cpp mode change 100755 => 100644 tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/cons.cpp diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index 6dedb2f3cb..6b12aa58e1 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -590,7 +590,7 @@ void EventDispatcher::dispatchEventToListeners(EventListenerVector* listeners, c // priority < 0 if (fixedPriorityListeners) { - CCASSERT(listeners->getGt0Index() <= fixedPriorityListeners->size(), "Out of range exception!"); + CCASSERT(listeners->getGt0Index() <= static_cast(fixedPriorityListeners->size()), "Out of range exception!"); if (!fixedPriorityListeners->empty()) { diff --git a/cocos/2d/CCFontFreeType.cpp b/cocos/2d/CCFontFreeType.cpp index caaf2eb6ba..19aace6e9c 100644 --- a/cocos/2d/CCFontFreeType.cpp +++ b/cocos/2d/CCFontFreeType.cpp @@ -388,7 +388,7 @@ unsigned char * makeDistanceMap( unsigned char *img, long width, long height) double * data = (double *) calloc( pixelAmount, sizeof(double) ); double * outside = (double *) calloc( pixelAmount, sizeof(double) ); double * inside = (double *) calloc( pixelAmount, sizeof(double) ); - unsigned int i,j; + long i,j; // Convert img into double (data) rescale image levels between 0 and 1 long outWidth = width + 2 * FontFreeType::DistanceMapSpread; diff --git a/cocos/2d/CCTMXLayer.cpp b/cocos/2d/CCTMXLayer.cpp index 1007dd9585..983d7e9d14 100644 --- a/cocos/2d/CCTMXLayer.cpp +++ b/cocos/2d/CCTMXLayer.cpp @@ -492,7 +492,7 @@ void TMXLayer::setTileGID(uint32_t gid, const Point& pos, TMXTileFlags flags) { CCASSERT(pos.x < _layerSize.width && pos.y < _layerSize.height && pos.x >=0 && pos.y >=0, "TMXLayer: invalid position"); CCASSERT(_tiles && _atlasIndexArray, "TMXLayer: the tiles map has been released"); - CCASSERT(gid == 0 || gid >= _tileSet->_firstGid, "TMXLayer: invalid gid" ); + CCASSERT(gid == 0 || (int)gid >= _tileSet->_firstGid, "TMXLayer: invalid gid" ); TMXTileFlags currentFlags; uint32_t currentGID = getTileGIDAt(pos, ¤tFlags); diff --git a/cocos/2d/cocos2d.vcxproj b/cocos/2d/cocos2d.vcxproj index b491f0fd9d..7f9a6fb1ff 100644 --- a/cocos/2d/cocos2d.vcxproj +++ b/cocos/2d/cocos2d.vcxproj @@ -317,7 +317,9 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - + + 4267;4996;4251;4244;%(DisableSpecificWarnings) + diff --git a/cocos/editor-support/cocostudio/CCActionNode.cpp b/cocos/editor-support/cocostudio/CCActionNode.cpp index d615b11c46..2ef5097230 100644 --- a/cocos/editor-support/cocostudio/CCActionNode.cpp +++ b/cocos/editor-support/cocostudio/CCActionNode.cpp @@ -241,7 +241,7 @@ void ActionNode::insertFrame(int index, ActionFrame* frame) return; } int frameType = frame->getFrameType(); - if(frameType < _frameArray.size()) + if(frameType < (int)_frameArray.size()) { auto cArray = _frameArray.at(frameType); cArray->insert(index, frame); @@ -256,7 +256,7 @@ void ActionNode::addFrame(ActionFrame* frame) } int frameType = frame->getFrameType(); - if(frameType < _frameArray.size()) + if(frameType < (int)_frameArray.size()) { auto cArray = _frameArray.at(frameType); cArray->pushBack(frame); @@ -270,7 +270,7 @@ void ActionNode::deleteFrame(ActionFrame* frame) return; } int frameType = frame->getFrameType(); - if(frameType < _frameArray.size()) + if(frameType < (int)_frameArray.size()) { auto cArray = _frameArray.at(frameType); cArray->eraseObject(frame); diff --git a/cocos/editor-support/cocostudio/CCSkin.cpp b/cocos/editor-support/cocostudio/CCSkin.cpp index 4d153f5baf..259eb4af6d 100644 --- a/cocos/editor-support/cocostudio/CCSkin.cpp +++ b/cocos/editor-support/cocostudio/CCSkin.cpp @@ -126,8 +126,8 @@ void Skin::setSkinData(const BaseData &var) setScaleX(_skinData.scaleX); setScaleY(_skinData.scaleY); - setRotationX(CC_RADIANS_TO_DEGREES(_skinData.skewX)); - setRotationY(CC_RADIANS_TO_DEGREES(-_skinData.skewY)); + setRotationSkewX(CC_RADIANS_TO_DEGREES(_skinData.skewX)); + setRotationSkewY(CC_RADIANS_TO_DEGREES(-_skinData.skewY)); setPosition(Point(_skinData.x, _skinData.y)); _skinTransform = getNodeToParentTransform(); diff --git a/cocos/ui/UIRichText.cpp b/cocos/ui/UIRichText.cpp index 3c33e33beb..c1684259a4 100644 --- a/cocos/ui/UIRichText.cpp +++ b/cocos/ui/UIRichText.cpp @@ -340,7 +340,7 @@ void RichText::formarRenderers() float newContentSizeHeight = 0.0f; float *maxHeights = new float[_elementRenders.size()]; - for (ssize_t i=0; i<_elementRenders.size(); i++) + for (size_t i=0; i<_elementRenders.size(); i++) { Vector* row = (_elementRenders[i]); float maxHeight = 0.0f; @@ -355,7 +355,7 @@ void RichText::formarRenderers() float nextPosY = _customSize.height; - for (ssize_t i=0; i<_elementRenders.size(); i++) + for (size_t i=0; i<_elementRenders.size(); i++) { Vector* row = (_elementRenders[i]); float nextPosX = 0.0f; @@ -375,7 +375,7 @@ void RichText::formarRenderers() } size_t length = _elementRenders.size(); - for (ssize_t i = 0; i* l = _elementRenders[i]; l->clear(); diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index e1043b8dc5..32f624d1ab 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -1040,7 +1040,7 @@ void TestColliderDetector::update(float delta) float minx = 0, miny = 0, maxx = 0, maxy = 0; size_t length = vertexList.size(); - for (int i = 0; iremoveFromParent(); _emitter = ParticleSystemQuad::create(plist); } - Node::addChild(_emitter , getZOrder() + 1, -1); + Node::addChild(_emitter , getLocalZOrder() + 1, -1); _emitterPlist = plist; } diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UILayoutTest/UILayoutTest_Editor.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UILayoutTest/UILayoutTest_Editor.cpp index 5780b30a08..9c78795fe5 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UILayoutTest/UILayoutTest_Editor.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UILayoutTest/UILayoutTest_Editor.cpp @@ -39,7 +39,7 @@ bool UILayoutTest_Editor::init() left_button->getSize().height)); left_button->setTouchEnabled(true); left_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::previousCallback)); - left_button->setZOrder(_layout->getZOrder() + 1); + left_button->setLocalZOrder(_layout->getLocalZOrder() + 1); _layout->addChild(left_button); Button* right_button = Button::create(); @@ -47,7 +47,7 @@ bool UILayoutTest_Editor::init() right_button->setPosition(Point(_layout->getSize().width / 2 + right_button->getSize().width, right_button->getSize().height)); right_button->setTouchEnabled(true); - right_button->setZOrder(_layout->getZOrder() + 1); + right_button->setLocalZOrder(_layout->getLocalZOrder() + 1); right_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::nextCallback)); _layout->addChild(right_button); @@ -94,7 +94,7 @@ bool UILayoutTest_Color_Editor::init() left_button->getSize().height)); left_button->setTouchEnabled(true); left_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::previousCallback)); - left_button->setZOrder(_layout->getZOrder() + 1); + left_button->setLocalZOrder(_layout->getLocalZOrder() + 1); _layout->addChild(left_button); Button* right_button = Button::create(); @@ -102,7 +102,7 @@ bool UILayoutTest_Color_Editor::init() right_button->setPosition(Point(_layout->getSize().width / 2 + right_button->getSize().width, right_button->getSize().height)); right_button->setTouchEnabled(true); - right_button->setZOrder(_layout->getZOrder() + 1); + right_button->setLocalZOrder(_layout->getLocalZOrder() + 1); right_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::nextCallback)); _layout->addChild(right_button); @@ -149,7 +149,7 @@ bool UILayoutTest_Gradient_Editor::init() left_button->getSize().height)); left_button->setTouchEnabled(true); left_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::previousCallback)); - left_button->setZOrder(_layout->getZOrder() + 1); + left_button->setLocalZOrder(_layout->getLocalZOrder() + 1); _layout->addChild(left_button); Button* right_button = Button::create(); @@ -157,7 +157,7 @@ bool UILayoutTest_Gradient_Editor::init() right_button->setPosition(Point(_layout->getSize().width / 2 + right_button->getSize().width, right_button->getSize().height)); right_button->setTouchEnabled(true); - right_button->setZOrder(_layout->getZOrder() + 1); + right_button->setLocalZOrder(_layout->getLocalZOrder() + 1); right_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::nextCallback)); _layout->addChild(right_button); @@ -204,7 +204,7 @@ bool UILayoutTest_BackGroundImage_Editor::init() left_button->getSize().height * 0.625)); left_button->setTouchEnabled(true); left_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::previousCallback)); - left_button->setZOrder(_layout->getZOrder() + 1); + left_button->setLocalZOrder(_layout->getLocalZOrder() + 1); _layout->addChild(left_button); Button* right_button = Button::create(); @@ -212,7 +212,7 @@ bool UILayoutTest_BackGroundImage_Editor::init() right_button->setPosition(Point(_layout->getSize().width / 2 + right_button->getSize().width, right_button->getSize().height * 0.625)); right_button->setTouchEnabled(true); - right_button->setZOrder(_layout->getZOrder() + 1); + right_button->setLocalZOrder(_layout->getLocalZOrder() + 1); right_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::nextCallback)); _layout->addChild(right_button); @@ -259,7 +259,7 @@ bool UILayoutTest_BackGroundImage_Scale9_Editor::init() left_button->getSize().height)); left_button->setTouchEnabled(true); left_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::previousCallback)); - left_button->setZOrder(_layout->getZOrder() + 1); + left_button->setLocalZOrder(_layout->getLocalZOrder() + 1); _layout->addChild(left_button); Button* right_button = Button::create(); @@ -267,7 +267,7 @@ bool UILayoutTest_BackGroundImage_Scale9_Editor::init() right_button->setPosition(Point(_layout->getSize().width / 2 + right_button->getSize().width, right_button->getSize().height)); right_button->setTouchEnabled(true); - right_button->setZOrder(_layout->getZOrder() + 1); + right_button->setLocalZOrder(_layout->getLocalZOrder() + 1); right_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::nextCallback)); _layout->addChild(right_button); @@ -314,7 +314,7 @@ bool UILayoutTest_Layout_Linear_Vertical_Editor::init() left_button->getSize().height * 0.625)); left_button->setTouchEnabled(true); left_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::previousCallback)); - left_button->setZOrder(_layout->getZOrder() + 1); + left_button->setLocalZOrder(_layout->getLocalZOrder() + 1); _layout->addChild(left_button); Button* right_button = Button::create(); @@ -322,7 +322,7 @@ bool UILayoutTest_Layout_Linear_Vertical_Editor::init() right_button->setPosition(Point(_layout->getSize().width / 2 + right_button->getSize().width, right_button->getSize().height * 0.625)); right_button->setTouchEnabled(true); - right_button->setZOrder(_layout->getZOrder() + 1); + right_button->setLocalZOrder(_layout->getLocalZOrder() + 1); right_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::nextCallback)); _layout->addChild(right_button); @@ -369,7 +369,7 @@ bool UILayoutTest_Layout_Linear_Horizontal_Editor::init() left_button->getSize().height * 0.625)); left_button->setTouchEnabled(true); left_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::previousCallback)); - left_button->setZOrder(_layout->getZOrder() + 1); + left_button->setLocalZOrder(_layout->getLocalZOrder() + 1); _layout->addChild(left_button); Button* right_button = Button::create(); @@ -377,7 +377,7 @@ bool UILayoutTest_Layout_Linear_Horizontal_Editor::init() right_button->setPosition(Point(_layout->getSize().width / 2 + right_button->getSize().width, right_button->getSize().height * 0.625)); right_button->setTouchEnabled(true); - right_button->setZOrder(_layout->getZOrder() + 1); + right_button->setLocalZOrder(_layout->getLocalZOrder() + 1); right_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::nextCallback)); _layout->addChild(right_button); @@ -425,7 +425,7 @@ bool UILayoutTest_Layout_Relative_Align_Parent_Editor::init() left_button->getSize().height * 0.625)); left_button->setTouchEnabled(true); left_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::previousCallback)); - left_button->setZOrder(_layout->getZOrder() + 1); + left_button->setLocalZOrder(_layout->getLocalZOrder() + 1); _layout->addChild(left_button); Button* right_button = Button::create(); @@ -433,7 +433,7 @@ bool UILayoutTest_Layout_Relative_Align_Parent_Editor::init() right_button->setPosition(Point(_layout->getSize().width / 2 + right_button->getSize().width, right_button->getSize().height * 0.625)); right_button->setTouchEnabled(true); - right_button->setZOrder(_layout->getZOrder() + 1); + right_button->setLocalZOrder(_layout->getLocalZOrder() + 1); right_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::nextCallback)); _layout->addChild(right_button); @@ -480,7 +480,7 @@ bool UILayoutTest_Layout_Relative_Location_Editor::init() left_button->getSize().height * 0.625)); left_button->setTouchEnabled(true); left_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::previousCallback)); - left_button->setZOrder(_layout->getZOrder() + 1); + left_button->setLocalZOrder(_layout->getLocalZOrder() + 1); _layout->addChild(left_button); Button* right_button = Button::create(); @@ -488,7 +488,7 @@ bool UILayoutTest_Layout_Relative_Location_Editor::init() right_button->setPosition(Point(_layout->getSize().width / 2 + right_button->getSize().width, right_button->getSize().height * 0.625)); right_button->setTouchEnabled(true); - right_button->setZOrder(_layout->getZOrder() + 1); + right_button->setLocalZOrder(_layout->getLocalZOrder() + 1); right_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::nextCallback)); _layout->addChild(right_button); diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest_Editor.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest_Editor.cpp index 83cfeccd19..89c2954979 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest_Editor.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest_Editor.cpp @@ -42,7 +42,7 @@ bool UIListViewTest_Vertical_Editor::init() left_button->getSize().height * 0.625)); left_button->setTouchEnabled(true); left_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::previousCallback)); - left_button->setZOrder(_layout->getZOrder() + 1); + left_button->setLocalZOrder(_layout->getLocalZOrder() + 1); _layout->addChild(left_button); Button* right_button = Button::create(); @@ -50,7 +50,7 @@ bool UIListViewTest_Vertical_Editor::init() right_button->setPosition(Point(_layout->getSize().width / 2 + right_button->getSize().width, right_button->getSize().height * 0.625)); right_button->setTouchEnabled(true); - right_button->setZOrder(_layout->getZOrder() + 1); + right_button->setLocalZOrder(_layout->getLocalZOrder() + 1); right_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::nextCallback)); _layout->addChild(right_button); @@ -98,7 +98,7 @@ bool UIListViewTest_Horizontal_Editor::init() left_button->getSize().height * 0.625)); left_button->setTouchEnabled(true); left_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::previousCallback)); - left_button->setZOrder(_layout->getZOrder() + 1); + left_button->setLocalZOrder(_layout->getLocalZOrder() + 1); _layout->addChild(left_button); Button* right_button = Button::create(); @@ -106,7 +106,7 @@ bool UIListViewTest_Horizontal_Editor::init() right_button->setPosition(Point(_layout->getSize().width / 2 + right_button->getSize().width, right_button->getSize().height * 0.625)); right_button->setTouchEnabled(true); - right_button->setZOrder(_layout->getZOrder() + 1); + right_button->setLocalZOrder(_layout->getLocalZOrder() + 1); right_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::nextCallback)); _layout->addChild(right_button); return true; diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest_Editor.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest_Editor.cpp index 743b5fc1f7..427b847820 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest_Editor.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest_Editor.cpp @@ -40,7 +40,7 @@ bool UIPageViewTest_Editor::init() left_button->getSize().height * 0.625)); left_button->setTouchEnabled(true); left_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::previousCallback)); - left_button->setZOrder(_layout->getZOrder() + 1); + left_button->setLocalZOrder(_layout->getLocalZOrder() + 1); _layout->addChild(left_button); Button* right_button = Button::create(); @@ -48,7 +48,7 @@ bool UIPageViewTest_Editor::init() right_button->setPosition(Point(_layout->getSize().width / 2 + right_button->getSize().width, right_button->getSize().height * 0.625)); right_button->setTouchEnabled(true); - right_button->setZOrder(_layout->getZOrder() + 1); + right_button->setLocalZOrder(_layout->getLocalZOrder() + 1); right_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::nextCallback)); _layout->addChild(right_button); diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIRichTextTest/UIRichTextTest.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIRichTextTest/UIRichTextTest.cpp index afd0e47ba8..f0f33e7afd 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIRichTextTest/UIRichTextTest.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIRichTextTest/UIRichTextTest.cpp @@ -36,7 +36,7 @@ bool UIRichTextTest::init() button->setTitleText("switch"); button->setPosition(Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f + button->getSize().height * 2.5)); button->addTouchEventListener(this, toucheventselector(UIRichTextTest::touchEvent)); - button->setZOrder(10); + button->setLocalZOrder(10); _widget->addChild(button); @@ -69,7 +69,7 @@ bool UIRichTextTest::init() _richText->pushBackElement(re6); _richText->setPosition(Point(widgetSize.width / 2, widgetSize.height / 2)); - _richText->setZOrder(10); + _richText->setLocalZOrder(10); _widget->addChild(_richText); diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest_Editor.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest_Editor.cpp index d9a0d53e55..d3d7077f2d 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest_Editor.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest_Editor.cpp @@ -39,7 +39,7 @@ bool UIScrollViewTest_Vertical_Editor::init() left_button->getSize().height * 0.625)); left_button->setTouchEnabled(true); left_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::previousCallback)); - left_button->setZOrder(_layout->getZOrder() + 1); + left_button->setLocalZOrder(_layout->getLocalZOrder() + 1); _layout->addChild(left_button); Button* right_button = Button::create(); @@ -47,7 +47,7 @@ bool UIScrollViewTest_Vertical_Editor::init() right_button->setPosition(Point(_layout->getSize().width / 2 + right_button->getSize().width, right_button->getSize().height * 0.625)); right_button->setTouchEnabled(true); - right_button->setZOrder(_layout->getZOrder() + 1); + right_button->setLocalZOrder(_layout->getLocalZOrder() + 1); right_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::nextCallback)); _layout->addChild(right_button); @@ -94,7 +94,7 @@ bool UIScrollViewTest_Horizontal_Editor::init() left_button->getSize().height * 0.625)); left_button->setTouchEnabled(true); left_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::previousCallback)); - left_button->setZOrder(_layout->getZOrder() + 1); + left_button->setLocalZOrder(_layout->getLocalZOrder() + 1); _layout->addChild(left_button); Button* right_button = Button::create(); @@ -102,7 +102,7 @@ bool UIScrollViewTest_Horizontal_Editor::init() right_button->setPosition(Point(_layout->getSize().width / 2 + right_button->getSize().width, right_button->getSize().height * 0.625)); right_button->setTouchEnabled(true); - right_button->setZOrder(_layout->getZOrder() + 1); + right_button->setLocalZOrder(_layout->getLocalZOrder() + 1); right_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::nextCallback)); _layout->addChild(right_button); @@ -149,7 +149,7 @@ bool UIScrollViewTest_Both_Editor::init() left_button->getSize().height * 0.625)); left_button->setTouchEnabled(true); left_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::previousCallback)); - left_button->setZOrder(_layout->getZOrder() + 1); + left_button->setLocalZOrder(_layout->getLocalZOrder() + 1); _layout->addChild(left_button); Button* right_button = Button::create(); @@ -157,7 +157,7 @@ bool UIScrollViewTest_Both_Editor::init() right_button->setPosition(Point(_layout->getSize().width / 2 + right_button->getSize().width, right_button->getSize().height * 0.625)); right_button->setTouchEnabled(true); - right_button->setZOrder(_layout->getZOrder() + 1); + right_button->setLocalZOrder(_layout->getLocalZOrder() + 1); right_button->addTouchEventListener(this, toucheventselector(UIScene_Editor::nextCallback)); _layout->addChild(right_button); diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp index b65d499f76..d50b5afc9b 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp @@ -336,7 +336,7 @@ void UITextFieldTest_LineWrap::textFieldEvent(Ref *pSender, TextFiledEventType t { TextField* textField = dynamic_cast(pSender); Size widgetSize = _widget->getSize(); - textField->runAction(CCMoveTo::create(0.225, + textField->runAction(CCMoveTo::create(0.225f, Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f + textField->getContentSize().height / 2))); textField->setTextHorizontalAlignment(TextHAlignment::LEFT); textField->setTextVerticalAlignment(TextVAlignment::TOP); @@ -349,7 +349,7 @@ void UITextFieldTest_LineWrap::textFieldEvent(Ref *pSender, TextFiledEventType t { TextField* textField = dynamic_cast(pSender); Size widgetSize = _widget->getSize(); - textField->runAction(CCMoveTo::create(0.175, Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f))); + textField->runAction(CCMoveTo::create(0.175f, Point(widgetSize.width / 2.0f, widgetSize.height / 2.0f))); textField->setTextHorizontalAlignment(TextHAlignment::CENTER); textField->setTextVerticalAlignment(TextVAlignment::CENTER); diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIWidgetAddNodeTest/UIWidgetAddNodeTest_Editor.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIWidgetAddNodeTest/UIWidgetAddNodeTest_Editor.cpp index 6bc4101250..ba0ae2baf1 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIWidgetAddNodeTest/UIWidgetAddNodeTest_Editor.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIWidgetAddNodeTest/UIWidgetAddNodeTest_Editor.cpp @@ -37,7 +37,7 @@ bool UIWidgetAddNodeTest_Editor::init() // Create the ui widget Widget* widget = Widget::create(); widget->setPosition(Point(rootSize.width / 2.0f, rootSize.height / 2.0f)); - widget->setZOrder(_layout->getZOrder() + 1); + widget->setLocalZOrder(_layout->getLocalZOrder() + 1); _layout->addChild(widget); Sprite* sprite = Sprite::create("cocosui/ccicon.png"); diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.cpp old mode 100755 new mode 100644 index 4449d2cd9d..4e29ed3236 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.cpp @@ -199,7 +199,7 @@ void TMoveBy::serialize(const rapidjson::Value &val) } else if (key == "IsReverse") { - _reverse = (bool)(DICTOOL->getIntValue_json(subDict, "value")); + _reverse = DICTOOL->getIntValue_json(subDict, "value") ? true : false; continue; } } @@ -337,7 +337,7 @@ void TRotateBy::serialize(const rapidjson::Value &val) } else if (key == "IsReverse") { - _reverse = (int)(DICTOOL->getIntValue_json(subDict, "value")); + _reverse = (DICTOOL->getIntValue_json(subDict, "value")) ? true : false; continue; } } @@ -483,7 +483,7 @@ void TScaleBy::serialize(const rapidjson::Value &val) } else if (key == "IsReverse") { - _reverse = (bool)(DICTOOL->getIntValue_json(subDict, "value")); + _reverse = (DICTOOL->getIntValue_json(subDict, "value")) ? true : false; continue; } } @@ -629,7 +629,7 @@ void TSkewBy::serialize(const rapidjson::Value &val) } else if (key == "IsReverse") { - _reverse = (bool)(DICTOOL->getIntValue_json(subDict, "value")); + _reverse = DICTOOL->getIntValue_json(subDict, "value") ? true : false; } } } diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/cons.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/cons.cpp old mode 100755 new mode 100644 index ea2f3a3971..e0f402d587 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/cons.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/cons.cpp @@ -255,7 +255,7 @@ void NodeVisible::serialize(const rapidjson::Value &val) } else if (key == "Visible") { - _visible = DICTOOL->getIntValue_json(subDict, "value"); + _visible = DICTOOL->getIntValue_json(subDict, "value") ? true : false; continue; } } diff --git a/tests/cpp-tests/Classes/PhysicsTest/PhysicsTest.cpp b/tests/cpp-tests/Classes/PhysicsTest/PhysicsTest.cpp index 013718db01..a94052cac4 100644 --- a/tests/cpp-tests/Classes/PhysicsTest/PhysicsTest.cpp +++ b/tests/cpp-tests/Classes/PhysicsTest/PhysicsTest.cpp @@ -844,7 +844,7 @@ void PhysicsDemoJoints::onEnter() _scene->getPhysicsWorld()->addJoint(PhysicsJointPin::construct(sp1->getPhysicsBody(), box, sp1->getPosition())); _scene->getPhysicsWorld()->addJoint(PhysicsJointPin::construct(sp2->getPhysicsBody(), box, sp2->getPosition())); - PhysicsJointRotaryLimit* joint = PhysicsJointRotaryLimit::construct(sp1->getPhysicsBody(), sp2->getPhysicsBody(), 0.0f, M_PI_2); + PhysicsJointRotaryLimit* joint = PhysicsJointRotaryLimit::construct(sp1->getPhysicsBody(), sp2->getPhysicsBody(), 0.0f,(float) M_PI_2); _scene->getPhysicsWorld()->addJoint(joint); this->addChild(sp1); @@ -860,7 +860,7 @@ void PhysicsDemoJoints::onEnter() _scene->getPhysicsWorld()->addJoint(PhysicsJointPin::construct(sp1->getPhysicsBody(), box, sp1->getPosition())); _scene->getPhysicsWorld()->addJoint(PhysicsJointPin::construct(sp2->getPhysicsBody(), box, sp2->getPosition())); - PhysicsJointRatchet* joint = PhysicsJointRatchet::construct(sp1->getPhysicsBody(), sp2->getPhysicsBody(), 0.0f, M_PI_2); + PhysicsJointRatchet* joint = PhysicsJointRatchet::construct(sp1->getPhysicsBody(), sp2->getPhysicsBody(), 0.0f, (float)M_PI_2); _scene->getPhysicsWorld()->addJoint(joint); this->addChild(sp1); @@ -892,7 +892,7 @@ void PhysicsDemoJoints::onEnter() _scene->getPhysicsWorld()->addJoint(PhysicsJointPin::construct(sp1->getPhysicsBody(), box, sp1->getPosition())); _scene->getPhysicsWorld()->addJoint(PhysicsJointPin::construct(sp2->getPhysicsBody(), box, sp2->getPosition())); - PhysicsJointMotor* joint = PhysicsJointMotor::construct(sp1->getPhysicsBody(), sp2->getPhysicsBody(), M_PI_2); + PhysicsJointMotor* joint = PhysicsJointMotor::construct(sp1->getPhysicsBody(), sp2->getPhysicsBody(), (float)M_PI_2); _scene->getPhysicsWorld()->addJoint(joint); this->addChild(sp1); @@ -1444,7 +1444,7 @@ void PhysicsContactTest::resetTest() label->setPosition(Point(s.width/2, s.height-170)); auto wall = Node::create(); - wall->setPhysicsBody(PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size, PhysicsMaterial(0.1, 1, 0.0))); + wall->setPhysicsBody(PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size, PhysicsMaterial(0.1f, 1, 0.0f))); wall->setPosition(VisibleRect::center()); root->addChild(wall); @@ -1462,7 +1462,7 @@ void PhysicsContactTest::resetTest() position.y = position.y * CCRANDOM_0_1(); position = VisibleRect::leftBottom() + position + Point(size.width/2, size.height/2); Vect velocity((CCRANDOM_0_1() - 0.5)*200, (CCRANDOM_0_1() - 0.5)*200); - auto box = makeBox(position, size, 1, PhysicsMaterial(0.1, 1, 0.0)); + auto box = makeBox(position, size, 1, PhysicsMaterial(0.1f, 1, 0.0f)); box->getPhysicsBody()->setVelocity(velocity); box->getPhysicsBody()->setCategoryBitmask(0x01); // 0001 box->getPhysicsBody()->setContactTestBitmask(0x04); // 0100 @@ -1480,7 +1480,7 @@ void PhysicsContactTest::resetTest() position.y = position.y * CCRANDOM_0_1(); position = VisibleRect::leftBottom() + position + Point(size.width/2, size.height/2); Vect velocity((CCRANDOM_0_1() - 0.5)*200, (CCRANDOM_0_1() - 0.5)*200); - auto box = makeBox(position, size, 2, PhysicsMaterial(0.1, 1, 0.0)); + auto box = makeBox(position, size, 2, PhysicsMaterial(0.1f, 1, 0.0f)); box->getPhysicsBody()->setVelocity(velocity); box->getPhysicsBody()->setCategoryBitmask(0x02); // 0010 box->getPhysicsBody()->setContactTestBitmask(0x08); // 1000 @@ -1498,7 +1498,7 @@ void PhysicsContactTest::resetTest() position.y = position.y * CCRANDOM_0_1(); position = VisibleRect::leftBottom() + position + Point(size.width/2, size.height/2); Vect velocity((CCRANDOM_0_1() - 0.5)*300, (CCRANDOM_0_1() - 0.5)*300); - auto triangle = makeTriangle(position, size, 1, PhysicsMaterial(0.1, 1, 0.0)); + auto triangle = makeTriangle(position, size, 1, PhysicsMaterial(0.1f, 1, 0.0f)); triangle->getPhysicsBody()->setVelocity(velocity); triangle->getPhysicsBody()->setCategoryBitmask(0x04); // 0100 triangle->getPhysicsBody()->setContactTestBitmask(0x01); // 0001 @@ -1516,7 +1516,7 @@ void PhysicsContactTest::resetTest() position.y = position.y * CCRANDOM_0_1(); position = VisibleRect::leftBottom() + position + Point(size.width/2, size.height/2); Vect velocity((CCRANDOM_0_1() - 0.5)*300, (CCRANDOM_0_1() - 0.5)*300); - auto triangle = makeTriangle(position, size, 2, PhysicsMaterial(0.1, 1, 0.0)); + auto triangle = makeTriangle(position, size, 2, PhysicsMaterial(0.1f, 1, 0.0f)); triangle->getPhysicsBody()->setVelocity(velocity); triangle->getPhysicsBody()->setCategoryBitmask(0x08); // 1000 triangle->getPhysicsBody()->setContactTestBitmask(0x02); // 0010 @@ -1565,7 +1565,7 @@ void PhysicsPositionRotationTest::onEnter() // anchor test auto anchorNode = Sprite::create("Images/YellowSquare.png"); - anchorNode->setAnchorPoint(Point(0.1, 0.9)); + anchorNode->setAnchorPoint(Point(0.1f, 0.9f)); anchorNode->setPosition(100, 100); anchorNode->setScale(0.25); anchorNode->setPhysicsBody(PhysicsBody::createBox(anchorNode->getContentSize()*anchorNode->getScale())); diff --git a/tests/cpp-tests/Classes/RenderTextureTest/RenderTextureTest.cpp b/tests/cpp-tests/Classes/RenderTextureTest/RenderTextureTest.cpp index b817ed6701..49e5848a08 100644 --- a/tests/cpp-tests/Classes/RenderTextureTest/RenderTextureTest.cpp +++ b/tests/cpp-tests/Classes/RenderTextureTest/RenderTextureTest.cpp @@ -314,9 +314,9 @@ RenderTextureZbuffer::RenderTextureZbuffer() label3->setPosition(Point(size.width / 2, size.height * 0.75f)); this->addChild(label3); - label->setVertexZ(50); - label2->setVertexZ(0); - label3->setVertexZ(-50); + label->setPositionZ(50); + label2->setPositionZ(0); + label3->setPositionZ(-50); SpriteFrameCache::getInstance()->addSpriteFramesWithFile("Images/bugs/circle.plist"); mgr = SpriteBatchNode::create("Images/bugs/circle.png", 9); @@ -341,15 +341,15 @@ RenderTextureZbuffer::RenderTextureZbuffer() mgr->addChild(sp8, 2); mgr->addChild(sp9, 1); - sp1->setVertexZ(400); - sp2->setVertexZ(300); - sp3->setVertexZ(200); - sp4->setVertexZ(100); - sp5->setVertexZ(0); - sp6->setVertexZ(-100); - sp7->setVertexZ(-200); - sp8->setVertexZ(-300); - sp9->setVertexZ(-400); + sp1->setPositionZ(400); + sp2->setPositionZ(300); + sp3->setPositionZ(200); + sp4->setPositionZ(100); + sp5->setPositionZ(0); + sp6->setPositionZ(-100); + sp7->setPositionZ(-200); + sp8->setPositionZ(-300); + sp9->setPositionZ(-400); sp9->setScale(2); sp9->setColor(Color3B::YELLOW); diff --git a/tests/cpp-tests/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id b/tests/cpp-tests/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id index b98c1b9d46..ac73085b6b 100644 --- a/tests/cpp-tests/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id +++ b/tests/cpp-tests/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id @@ -1 +1 @@ -4bb0b2a6151e4910ea662bedd91a5be655ec05d1 \ No newline at end of file +4d17613c96e30631ec5da21b2629fa3d0fc39f2d \ No newline at end of file diff --git a/tests/cpp-tests/Classes/TileMapTest/TileMapTest.cpp b/tests/cpp-tests/Classes/TileMapTest/TileMapTest.cpp index ecad3ef353..4b26ddbe49 100644 --- a/tests/cpp-tests/Classes/TileMapTest/TileMapTest.cpp +++ b/tests/cpp-tests/Classes/TileMapTest/TileMapTest.cpp @@ -285,7 +285,7 @@ TMXOrthoTest::TMXOrthoTest() Size CC_UNUSED s = map->getContentSize(); CCLOG("ContentSize: %f, %f", s.width,s.height); - auto scale = ScaleBy::create(10, 0.1); + auto scale = ScaleBy::create(10, 0.1f); auto back = scale->reverse(); auto seq = Sequence::create(scale, back, NULL); auto repeat = RepeatForever::create(seq); @@ -1086,7 +1086,7 @@ void TMXIsoVertexZ::repositionSprite(float dt) auto p = _tamara->getPosition(); p = CC_POINT_POINTS_TO_PIXELS(p); float newZ = -(p.y+32) /16; - _tamara->setVertexZ( newZ ); + _tamara->setPositionZ( newZ ); } void TMXIsoVertexZ::onEnter() @@ -1132,7 +1132,7 @@ TMXOrthoVertexZ::TMXOrthoVertexZ() // can use any Sprite and it will work OK. auto layer = map->getLayer("trees"); _tamara = layer->getTileAt(Point(0,11)); - CCLOG("%p vertexZ: %f", _tamara, _tamara->getVertexZ()); + CCLOG("%p vertexZ: %f", _tamara, _tamara->getPositionZ()); _tamara->retain(); auto move = MoveBy::create(10, Point(400,450) * (1/CC_CONTENT_SCALE_FACTOR())); @@ -1155,7 +1155,7 @@ void TMXOrthoVertexZ::repositionSprite(float dt) // map size: 12x12 auto p = _tamara->getPosition(); p = CC_POINT_POINTS_TO_PIXELS(p); - _tamara->setVertexZ( -( (p.y+81) /81) ); + _tamara->setPositionZ( -( (p.y+81) /81) ); } void TMXOrthoVertexZ::onEnter() diff --git a/tests/cpp-tests/Classes/ZwoptexTest/ZwoptexTest.cpp b/tests/cpp-tests/Classes/ZwoptexTest/ZwoptexTest.cpp index 6687de06da..25a44638ed 100644 --- a/tests/cpp-tests/Classes/ZwoptexTest/ZwoptexTest.cpp +++ b/tests/cpp-tests/Classes/ZwoptexTest/ZwoptexTest.cpp @@ -185,8 +185,8 @@ void ZwoptexGenericTest::flipSprites(float dt) char str2[32] = {0}; sprintf(str1, "grossini_dance_%02d.png", spriteFrameIndex); sprintf(str2, "grossini_dance_generic_%02d.png", spriteFrameIndex); - sprite1->setDisplayFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName(str1)); - sprite2->setDisplayFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName(str2)); + sprite1->setSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName(str1)); + sprite2->setSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName(str2)); } ZwoptexGenericTest::~ZwoptexGenericTest() diff --git a/tests/cpp-tests/proj.win32/cpp-tests.vcxproj b/tests/cpp-tests/proj.win32/cpp-tests.vcxproj index 172ef28da3..12c78bf5ff 100644 --- a/tests/cpp-tests/proj.win32/cpp-tests.vcxproj +++ b/tests/cpp-tests/proj.win32/cpp-tests.vcxproj @@ -153,8 +153,12 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\external\websockets\prebuilt\win32\*.*" "$(Ou - - + + 4267;4251;4068;4244;%(DisableSpecificWarnings) + + + 4267;4251;4244;4068;%(DisableSpecificWarnings) + @@ -209,7 +213,9 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\external\websockets\prebuilt\win32\*.*" "$(Ou - + + 4267;4251;4244;4819;%(DisableSpecificWarnings) + @@ -583,4 +589,4 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\external\websockets\prebuilt\win32\*.*" "$(Ou - + \ No newline at end of file From 4a974e24df252e2fb00266681cf6f03a7ccccb6b Mon Sep 17 00:00:00 2001 From: andyque Date: Mon, 24 Mar 2014 10:50:48 +0800 Subject: [PATCH 035/106] revert vcxproj files --- cocos/2d/cocos2d.vcxproj | 4 +--- tests/cpp-tests/proj.win32/cpp-tests.vcxproj | 14 ++++---------- 2 files changed, 5 insertions(+), 13 deletions(-) diff --git a/cocos/2d/cocos2d.vcxproj b/cocos/2d/cocos2d.vcxproj index 7f9a6fb1ff..b491f0fd9d 100644 --- a/cocos/2d/cocos2d.vcxproj +++ b/cocos/2d/cocos2d.vcxproj @@ -317,9 +317,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - - 4267;4996;4251;4244;%(DisableSpecificWarnings) - + diff --git a/tests/cpp-tests/proj.win32/cpp-tests.vcxproj b/tests/cpp-tests/proj.win32/cpp-tests.vcxproj index 12c78bf5ff..172ef28da3 100644 --- a/tests/cpp-tests/proj.win32/cpp-tests.vcxproj +++ b/tests/cpp-tests/proj.win32/cpp-tests.vcxproj @@ -153,12 +153,8 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\external\websockets\prebuilt\win32\*.*" "$(Ou - - 4267;4251;4068;4244;%(DisableSpecificWarnings) - - - 4267;4251;4244;4068;%(DisableSpecificWarnings) - + + @@ -213,9 +209,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\external\websockets\prebuilt\win32\*.*" "$(Ou - - 4267;4251;4244;4819;%(DisableSpecificWarnings) - + @@ -589,4 +583,4 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\external\websockets\prebuilt\win32\*.*" "$(Ou - \ No newline at end of file + From b41879916cebb80e98fea05ec304c586dd55a966 Mon Sep 17 00:00:00 2001 From: andyque Date: Mon, 24 Mar 2014 12:03:25 +0800 Subject: [PATCH 036/106] issue #4429, fixed Value to string precesion error --- cocos/base/CCValue.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/cocos/base/CCValue.cpp b/cocos/base/CCValue.cpp index 6aabf25c6e..c2829ab17e 100644 --- a/cocos/base/CCValue.cpp +++ b/cocos/base/CCValue.cpp @@ -24,6 +24,7 @@ #include "CCValue.h" #include +#include NS_CC_BEGIN @@ -571,6 +572,7 @@ std::string Value::asString() const } std::stringstream ret; + switch (_type) { case Type::BYTE: @@ -580,10 +582,10 @@ std::string Value::asString() const ret << _baseData.intVal; break; case Type::FLOAT: - ret << _baseData.floatVal; + ret << std::fixed << std::setprecision( 7 )<< _baseData.floatVal; break; case Type::DOUBLE: - ret << _baseData.doubleVal; + ret << std::fixed << std::setprecision( 16 ) << _baseData.doubleVal; break; case Type::BOOLEAN: ret << (_baseData.boolVal ? "true" : "false"); From 538c01e76ee8035a1183a95493ea3fcd1e79fdc5 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Mon, 24 Mar 2014 14:16:27 +0800 Subject: [PATCH 037/106] label:support clip blank of upper and lower margin. --- cocos/2d/CCFontAtlas.cpp | 4 +++ cocos/2d/CCFontAtlas.h | 2 ++ cocos/2d/CCLabel.cpp | 2 ++ cocos/2d/CCLabel.h | 6 ++++ cocos/2d/CCLabelTextFormatter.cpp | 50 ++++++++++++++++++++++++++++++- 5 files changed, 63 insertions(+), 1 deletion(-) diff --git a/cocos/2d/CCFontAtlas.cpp b/cocos/2d/CCFontAtlas.cpp index 3e40e41419..11f9998d6c 100644 --- a/cocos/2d/CCFontAtlas.cpp +++ b/cocos/2d/CCFontAtlas.cpp @@ -231,6 +231,8 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) auto pixelFormat = fontTTf->getOutlineSize() > 0 ? Texture2D::PixelFormat::AI88 : Texture2D::PixelFormat::A8; bool existNewLetter = false; + int bottomHeight = _commonLineHeight - _fontAscender; + for (int i = 0; i < length; ++i) { auto outIterator = _fontLetterDefinitions.find(utf16String[i]); @@ -248,6 +250,7 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) tempDef.height = tempRect.size.height + _letterPadding; tempDef.offsetX = tempRect.origin.x + offsetAdjust; tempDef.offsetY = _fontAscender + tempRect.origin.y - offsetAdjust; + tempDef.clipBottom = bottomHeight - (tempDef.height + tempRect.origin.y + offsetAdjust); if (_currentPageOrigX + tempDef.width > CacheTextureWidth) { @@ -290,6 +293,7 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) tempDef.offsetX = 0; tempDef.offsetY = 0; tempDef.textureID = 0; + tempDef.clipBottom = 0; _currentPageOrigX += 1; } diff --git a/cocos/2d/CCFontAtlas.h b/cocos/2d/CCFontAtlas.h index 2d3eb615a3..a10fe9eb9f 100644 --- a/cocos/2d/CCFontAtlas.h +++ b/cocos/2d/CCFontAtlas.h @@ -50,6 +50,8 @@ struct FontLetterDefinition int textureID; bool validDefinition; int xAdvance; + + int clipBottom; }; class CC_DLL FontAtlas : public Ref diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index 3d6bc68508..644ceeec06 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -339,6 +339,8 @@ void Label::reset() _textColor = Color4B::WHITE; _textColorF = Color4F::WHITE; setColor(Color3B::WHITE); + + _clipEnabled = false; } void Label::updateShaderProgram() diff --git a/cocos/2d/CCLabel.h b/cocos/2d/CCLabel.h index 93130c4e10..dc9271d8ab 100644 --- a/cocos/2d/CCLabel.h +++ b/cocos/2d/CCLabel.h @@ -217,6 +217,10 @@ public: virtual Sprite * getLetter(int lettetIndex); + /** clip upper and lower margin for reduce height of label. + */ + void setClipMarginEnabled(bool clipEnabled) { _clipEnabled = clipEnabled; } + // font related stuff int getCommonLineHeight() const; @@ -365,6 +369,8 @@ protected: Color4B _textColor; Color4F _textColorF; + bool _clipEnabled; + private: CC_DISALLOW_COPY_AND_ASSIGN(Label); diff --git a/cocos/2d/CCLabelTextFormatter.cpp b/cocos/2d/CCLabelTextFormatter.cpp index 9f0efe1eaa..119456caa6 100644 --- a/cocos/2d/CCLabelTextFormatter.cpp +++ b/cocos/2d/CCLabelTextFormatter.cpp @@ -321,6 +321,16 @@ bool LabelTextFormatter::createStringSprites(Label *theLabel) FontLetterDefinition tempDefinition; Point letterPosition; const auto& kernings = theLabel->_horizontalKernings; + + float clipTop = 0; + float clipBottom = 0; + int lineIndex = 0; + bool lineStart = true; + bool clip = false; + if (theLabel->_currentLabelType == Label::LabelType::TTF && theLabel->_clipEnabled) + { + clip = true; + } for (unsigned int i = 0; i < stringLen; i++) { @@ -337,9 +347,10 @@ bool LabelTextFormatter::createStringSprites(Label *theLabel) charYOffset = -1; charAdvance = -1; } - + if (c == '\n') { + lineIndex++; nextFontPositionX = 0; nextFontPositionY -= theLabel->_commonLineHeight; @@ -347,8 +358,30 @@ bool LabelTextFormatter::createStringSprites(Label *theLabel) if(nextFontPositionY < theLabel->_commonLineHeight) break; + lineStart = true; continue; } + else if (clip && tempDefinition.height > 0.0f) + { + if (lineStart) + { + if (lineIndex == 0) + { + clipTop = charYOffset; + } + lineStart = false; + clipBottom = tempDefinition.clipBottom; + } + else if(tempDefinition.clipBottom < clipBottom) + { + clipBottom = tempDefinition.clipBottom; + } + + if (lineIndex == 0 && charYOffset < clipTop) + { + clipTop = charYOffset; + } + } letterPosition.x = (nextFontPositionX + charXOffset + kernings[i]) / contentScaleFactor; letterPosition.y = (nextFontPositionY - charYOffset) / contentScaleFactor; @@ -382,11 +415,26 @@ bool LabelTextFormatter::createStringSprites(Label *theLabel) } tmpSize.height = totalHeight; + if (theLabel->_labelHeight > 0) { tmpSize.height = theLabel->_labelHeight * contentScaleFactor; } + + if (clip) + { + int clipTotal = (clipTop + clipBottom) / contentScaleFactor; + tmpSize.height -= clipTotal * contentScaleFactor; + clipBottom /= contentScaleFactor; + + for (int i = 0; i < theLabel->_limitShowCount; i++) + { + theLabel->_lettersInfo[i].position.y -= clipBottom; + } + } + theLabel->setContentSize(CC_SIZE_PIXELS_TO_POINTS(tmpSize)); + return true; } From db7057e6f26a8d30a03d8c3a10fde3d21ac78b47 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 24 Mar 2014 16:54:16 +0800 Subject: [PATCH 038/106] closed #4529: Stroke size and shadow offset don't consider ContentScaleFactor --- cocos/2d/CCTexture2D.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/cocos/2d/CCTexture2D.cpp b/cocos/2d/CCTexture2D.cpp index a43563d862..03a9187747 100644 --- a/cocos/2d/CCTexture2D.cpp +++ b/cocos/2d/CCTexture2D.cpp @@ -1088,6 +1088,10 @@ bool Texture2D::initWithString(const char *text, const FontDefinition& textDefin textDef._fontSize *= contentScaleFactor; textDef._dimensions.width *= contentScaleFactor; textDef._dimensions.height *= contentScaleFactor; + textDef._stroke._strokeSize *= contentScaleFactor; + textDef._shadow._shadowOffset.width *= contentScaleFactor; + textDef._shadow._shadowOffset.height *= contentScaleFactor; + Data outData = Device::getTextureDataForText(text,textDef,align,imageWidth,imageHeight); if(outData.isNull()) return false; From 6defa062a803f5700052968bad6f7565dd4224c2 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 24 Mar 2014 11:33:52 +0800 Subject: [PATCH 039/106] closed #4530: Using 'Outside stroke' instead of 'Inside Stroke' for Label generated by 'Font name'. And fix stroke could not work on iOS7. --- .../src/org/cocos2dx/lib/Cocos2dxBitmap.java | 39 ++++--- cocos/2d/platform/ios/CCDevice.mm | 105 +++++++++--------- 2 files changed, 74 insertions(+), 70 deletions(-) diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxBitmap.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxBitmap.java index 578f7120c2..fd32a0682b 100644 --- a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxBitmap.java +++ b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxBitmap.java @@ -173,41 +173,44 @@ public class Cocos2dxBitmap { /* Draw string. */ final FontMetricsInt fontMetricsInt = paint.getFontMetricsInt(); - - int x = 0; - int y = Cocos2dxBitmap.computeY(fontMetricsInt, height, textProperty.mTotalHeight, verticalAlignment); - - final String[] lines = textProperty.mLines; - - for (final String line : lines) { - - x = Cocos2dxBitmap.computeX(line, textProperty.mMaxWidth, horizontalAlignment); - canvas.drawText(line, x + renderTextDeltaX, y + renderTextDeltaY, paint); - y += textProperty.mHeightPerLine; - - } // draw again with stroke on if needed - if ( stroke ) { - + if ( stroke ) + { final Paint paintStroke = Cocos2dxBitmap.newPaint(fontName, fontSize, horizontalAlignment); paintStroke.setStyle(Paint.Style.STROKE); - paintStroke.setStrokeWidth(strokeSize * 0.5f); + paintStroke.setStrokeWidth(strokeSize); paintStroke.setARGB(255, (int) (strokeR * 255), (int) (strokeG * 255), (int) (strokeB * 255)); - x = 0; - y = Cocos2dxBitmap.computeY(fontMetricsInt, height, textProperty.mTotalHeight, verticalAlignment); + int x = 0; + int y = Cocos2dxBitmap.computeY(fontMetricsInt, height, textProperty.mTotalHeight, verticalAlignment); final String[] lines2 = textProperty.mLines; for (final String line : lines2) { x = Cocos2dxBitmap.computeX(line, textProperty.mMaxWidth, horizontalAlignment); canvas.drawText(line, x + renderTextDeltaX, y + renderTextDeltaY, paintStroke); + canvas.drawText(line, x + renderTextDeltaX, y + renderTextDeltaY, paint); y += textProperty.mHeightPerLine; } } + else + { + int x = 0; + int y = Cocos2dxBitmap.computeY(fontMetricsInt, height, textProperty.mTotalHeight, verticalAlignment); + + final String[] lines = textProperty.mLines; + + for (final String line : lines) { + + x = Cocos2dxBitmap.computeX(line, textProperty.mMaxWidth, horizontalAlignment); + canvas.drawText(line, x + renderTextDeltaX, y + renderTextDeltaY, paint); + y += textProperty.mHeightPerLine; + + } + } Cocos2dxBitmap.initNativeObject(bitmap); diff --git a/cocos/2d/platform/ios/CCDevice.mm b/cocos/2d/platform/ios/CCDevice.mm index 7d91cb68ce..a2ff8e64c6 100644 --- a/cocos/2d/platform/ios/CCDevice.mm +++ b/cocos/2d/platform/ios/CCDevice.mm @@ -322,8 +322,8 @@ static bool _initWithString(const char * text, cocos2d::Device::TextAlign align, } // add the padding (this could be 0 if no shadow and no stroke) - dim.width += shadowStrokePaddingX; - dim.height += shadowStrokePaddingY; + dim.width += shadowStrokePaddingX*2; + dim.height += shadowStrokePaddingY*2; unsigned char* data = (unsigned char*)malloc(sizeof(unsigned char) * (int)(dim.width * dim.height * 4)); @@ -356,19 +356,11 @@ static bool _initWithString(const char * text, cocos2d::Device::TextAlign align, // measure text size with specified font and determine the rectangle to draw text in unsigned uHoriFlag = (int)align & 0x0f; - UITextAlignment testAlign = (UITextAlignment)((2 == uHoriFlag) ? UITextAlignmentRight - : (3 == uHoriFlag) ? UITextAlignmentCenter - : UITextAlignmentLeft); + NSTextAlignment nsAlign = (2 == uHoriFlag) ? NSTextAlignmentRight + : (3 == uHoriFlag) ? NSTextAlignmentCenter + : NSTextAlignmentLeft; - // take care of stroke if needed - if ( info->hasStroke ) - { - CGContextSetTextDrawingMode(context, kCGTextFillStroke); - CGContextSetRGBStrokeColor(context, info->strokeColorR, info->strokeColorG, info->strokeColorB, 1); - CGContextSetLineWidth(context, info->strokeSize); - } - // take care of shadow if needed if ( info->hasShadow ) { @@ -386,54 +378,63 @@ static bool _initWithString(const char * text, cocos2d::Device::TextAlign align, CGColorSpaceRelease(colorSpace); - // normal fonts - //if( [font isKindOfClass:[UIFont class] ] ) - //{ - // [str drawInRect:CGRectMake(0, startH, dim.width, dim.height) withFont:font lineBreakMode:(UILineBreakMode)UILineBreakModeWordWrap alignment:align]; - //} - //else // ZFont class - //{ - // [FontLabelStringDrawingHelper drawInRect:str rect:CGRectMake(0, startH, dim.width, dim.height) withZFont:font lineBreakMode:(UILineBreakMode)UILineBreakModeWordWrap - ////alignment:align]; - //} - - // compute the rect used for rendering the text // based on wether shadows or stroke are enabled - float textOriginX = 0.0; - float textOrigingY = 0.0; + float textOriginX = 0; + float textOrigingY = startH; - float textWidth = dim.width - shadowStrokePaddingX; - float textHeight = dim.height - shadowStrokePaddingY; - - - if ( info->shadowOffset.width < 0 ) - { - textOriginX = shadowStrokePaddingX; - } - else - { - textOriginX = 0.0; - } - - if (info->shadowOffset.height > 0) - { - textOrigingY = startH; - } - else - { - textOrigingY = startH - shadowStrokePaddingY; - } + float textWidth = dim.width; + float textHeight = dim.height; CGRect rect = CGRectMake(textOriginX, textOrigingY, textWidth, textHeight); - CGContextBeginTransparencyLayerWithRect(context, rect, nullptr); - // actually draw the text in the context - // XXX: ios7 casting - [str drawInRect: rect withFont:font lineBreakMode:NSLineBreakByWordWrapping alignment:(NSTextAlignment)testAlign]; + CGContextSetShouldSubpixelQuantizeFonts(context, false); + CGContextBeginTransparencyLayerWithRect(context, rect, NULL); + + if ( info->hasStroke ) + { + CGContextSetTextDrawingMode(context, kCGTextStroke); + + if([[[UIDevice currentDevice] systemVersion] compare:@"7.0" options:NSNumericSearch] != NSOrderedAscending) + { + NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; + paragraphStyle.alignment = nsAlign; + paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping; + [str drawInRect:rect withAttributes:@{ + NSFontAttributeName: font, + NSStrokeWidthAttributeName: [NSNumber numberWithFloat: info->strokeSize / size * 100 ], + NSForegroundColorAttributeName:[UIColor colorWithRed:info->tintColorR + green:info->tintColorG + blue:info->tintColorB + alpha:1.0f], + NSParagraphStyleAttributeName:paragraphStyle, + NSStrokeColorAttributeName: [UIColor colorWithRed:info->strokeColorR + green:info->strokeColorG + blue:info->strokeColorB + alpha:1.0f] + } + ]; + + [paragraphStyle release]; + } + else + { + CGContextSetRGBStrokeColor(context, info->strokeColorR, info->strokeColorG, info->strokeColorB, 1); + CGContextSetLineWidth(context, info->strokeSize); + + //original code that was not working in iOS 7 + [str drawInRect: rect withFont:font lineBreakMode:NSLineBreakByWordWrapping alignment:nsAlign]; + } + } + + CGContextSetTextDrawingMode(context, kCGTextFill); + + // actually draw the text in the context + [str drawInRect: rect withFont:font lineBreakMode:NSLineBreakByWordWrapping alignment:nsAlign]; + CGContextEndTransparencyLayer(context); // pop the context From 99b65f0a7c944d75c73893414a6e9fd7f731dc86 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 24 Mar 2014 17:05:24 +0800 Subject: [PATCH 040/106] LabelTest , changed stroke color to blue. --- tests/cpp-tests/Classes/LabelTest/LabelTest.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/cpp-tests/Classes/LabelTest/LabelTest.cpp b/tests/cpp-tests/Classes/LabelTest/LabelTest.cpp index 9c19200069..b3b1dfbfdc 100644 --- a/tests/cpp-tests/Classes/LabelTest/LabelTest.cpp +++ b/tests/cpp-tests/Classes/LabelTest/LabelTest.cpp @@ -1486,7 +1486,7 @@ TTFFontShadowAndStroke::TTFFontShadowAndStroke() Color3B tintColorRed( 255, 0, 0 ); Color3B tintColorYellow( 255, 255, 0 ); Color3B tintColorBlue( 0, 0, 255 ); - Color3B strokeColor( 0, 10, 255 ); + Color3B strokeColor( 0, 0, 255 ); Color3B strokeShadowColor( 255, 0, 0 ); Size shadowOffset(12.0, 12.0); From a2d00c8f95f56d82fd5508c507ee1f501465afa9 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 24 Mar 2014 17:39:23 +0800 Subject: [PATCH 041/106] Adds another test for stroke. --- .../cpp-tests/Classes/LabelTest/LabelTest.cpp | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/tests/cpp-tests/Classes/LabelTest/LabelTest.cpp b/tests/cpp-tests/Classes/LabelTest/LabelTest.cpp index b3b1dfbfdc..ec91f53be6 100644 --- a/tests/cpp-tests/Classes/LabelTest/LabelTest.cpp +++ b/tests/cpp-tests/Classes/LabelTest/LabelTest.cpp @@ -1552,6 +1552,37 @@ TTFFontShadowAndStroke::TTFFontShadowAndStroke() // add label to the scene this->addChild(fontStrokeAndShadow); fontStrokeAndShadow->setPosition(Point(s.width/2,s.height/4*1.1)); + + auto buttonBG = MenuItemImage::create("cocosui/animationbuttonnormal.png", "cocosui/animationbuttonpressed.png"); + buttonBG->setAnchorPoint(Point::ANCHOR_MIDDLE_LEFT); + buttonBG->setPosition(VisibleRect::left()); + + // create the label stroke and shadow + strokeShaodwTextDef._fontSize = 18; + strokeShaodwTextDef._fontName = "Marker Felt"; + + strokeShaodwTextDef._stroke._strokeEnabled = true; + strokeShaodwTextDef._stroke._strokeColor = Color3B::BLACK; + strokeShaodwTextDef._stroke._strokeSize = 3.0f; + + strokeShaodwTextDef._shadow._shadowEnabled = false; + strokeShaodwTextDef._shadow._shadowOffset = Size(1, 1); + strokeShaodwTextDef._shadow._shadowOpacity = 1.0; + strokeShaodwTextDef._shadow._shadowBlur = 0.5f; + + strokeShaodwTextDef._fontFillColor = Color3B::WHITE; + + // shadow + stroke label + fontStrokeAndShadow = LabelTTF::createWithFontDefinition("Test", strokeShaodwTextDef); + + // add label to the scene + buttonBG->addChild(fontStrokeAndShadow); + fontStrokeAndShadow->setPosition(Point(buttonBG->getContentSize().width/2, buttonBG->getContentSize().height/2)); + + auto menu = Menu::create(buttonBG, nullptr); + menu->setAnchorPoint(Point::ANCHOR_BOTTOM_LEFT); + menu->setPosition(Point::ZERO); + addChild(menu); } std::string TTFFontShadowAndStroke::title() const From 759ec61639b70223deaaef9eaccfeda7c8c5d54d Mon Sep 17 00:00:00 2001 From: boyu0 Date: Mon, 24 Mar 2014 18:08:55 +0800 Subject: [PATCH 042/106] closed #4513: Particle doesn't animate when readd it. --- cocos/2d/CCParticleSystem.cpp | 10 ++++++++-- cocos/2d/CCParticleSystem.h | 1 + .../Classes/ParticleTest/ParticleTest.cpp | 20 +++++++++++++++++-- .../Classes/ParticleTest/ParticleTest.h | 1 + 4 files changed, 28 insertions(+), 4 deletions(-) diff --git a/cocos/2d/CCParticleSystem.cpp b/cocos/2d/CCParticleSystem.cpp index f34e692792..48172bc859 100644 --- a/cocos/2d/CCParticleSystem.cpp +++ b/cocos/2d/CCParticleSystem.cpp @@ -468,8 +468,6 @@ bool ParticleSystem::initWithTotalParticles(int numberOfParticles) //updateParticleImp = (CC_UPDATE_PARTICLE_IMP) [self methodForSelector:updateParticleSel]; //for batchNode _transformSystemDirty = false; - // update after action in run! - this->scheduleUpdateWithPriority(1); return true; } @@ -609,6 +607,14 @@ void ParticleSystem::initParticle(tParticle* particle) } } +void ParticleSystem::onEnter() +{ + Node::onEnter(); + + // update after action in run! + this->scheduleUpdateWithPriority(1); +} + void ParticleSystem::stopSystem() { _isActive = false; diff --git a/cocos/2d/CCParticleSystem.h b/cocos/2d/CCParticleSystem.h index 74d6bab382..53f6f968ea 100644 --- a/cocos/2d/CCParticleSystem.h +++ b/cocos/2d/CCParticleSystem.h @@ -184,6 +184,7 @@ public: //! whether or not the system is full bool isFull(); + virtual void onEnter(); //! should be overridden by subclasses virtual void updateQuadWithParticle(tParticle* particle, const Point& newPosition); //! should be overridden by subclasses diff --git a/tests/cpp-tests/Classes/ParticleTest/ParticleTest.cpp b/tests/cpp-tests/Classes/ParticleTest/ParticleTest.cpp index 707aa7daba..94c4f2496e 100644 --- a/tests/cpp-tests/Classes/ParticleTest/ParticleTest.cpp +++ b/tests/cpp-tests/Classes/ParticleTest/ParticleTest.cpp @@ -1836,6 +1836,20 @@ std::string PremultipliedAlphaTest::subtitle() const return "no black halo, particles should fade out"; } +void PremultipliedAlphaTest::readdPaticle(float delta) +{ + static int count = 0; + + if (count++ % 2 == 0) + { + _emitter->removeFromParent(); + } + else + { + this->addChild(_emitter); + } +} + void PremultipliedAlphaTest::onEnter() { ParticleDemo::onEnter(); @@ -1863,6 +1877,8 @@ void PremultipliedAlphaTest::onEnter() _emitter->setEndColorVar(Color4F(0, 0, 0, 0)); this->addChild(_emitter, 10); + + schedule(schedule_selector(PremultipliedAlphaTest::readdPaticle), 1.0); } // PremultipliedAlphaTest2 @@ -1882,12 +1898,12 @@ void PremultipliedAlphaTest2::onEnter() std::string PremultipliedAlphaTest2::title() const { - return "premultiplied alpha 2"; + return "premultiplied alpha and readd child test"; } std::string PremultipliedAlphaTest2::subtitle() const { - return "Arrows should be faded"; + return "Arrows should be faded\n animation should be normal"; } diff --git a/tests/cpp-tests/Classes/ParticleTest/ParticleTest.h b/tests/cpp-tests/Classes/ParticleTest/ParticleTest.h index b490ecb4a6..963d4b4a98 100644 --- a/tests/cpp-tests/Classes/ParticleTest/ParticleTest.h +++ b/tests/cpp-tests/Classes/ParticleTest/ParticleTest.h @@ -289,6 +289,7 @@ class PremultipliedAlphaTest : public ParticleDemo { public: virtual void onEnter() override; + void readdPaticle(float delta); virtual std::string title() const override; virtual std::string subtitle() const override; }; From 1520f85b324758e567757e4aea8433c85a4b02e8 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Mon, 24 Mar 2014 18:20:11 +0800 Subject: [PATCH 043/106] closed #4513: fix titles. --- tests/cpp-tests/Classes/ParticleTest/ParticleTest.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/cpp-tests/Classes/ParticleTest/ParticleTest.cpp b/tests/cpp-tests/Classes/ParticleTest/ParticleTest.cpp index 94c4f2496e..12063ca97b 100644 --- a/tests/cpp-tests/Classes/ParticleTest/ParticleTest.cpp +++ b/tests/cpp-tests/Classes/ParticleTest/ParticleTest.cpp @@ -1828,12 +1828,12 @@ std::string ReorderParticleSystems::subtitle() const std::string PremultipliedAlphaTest::title() const { - return "premultiplied alpha"; + return "premultiplied alpha and readd child test"; } std::string PremultipliedAlphaTest::subtitle() const { - return "no black halo, particles should fade out"; + return "no black halo, particles should fade out\n animation should be normal"; } void PremultipliedAlphaTest::readdPaticle(float delta) @@ -1898,12 +1898,12 @@ void PremultipliedAlphaTest2::onEnter() std::string PremultipliedAlphaTest2::title() const { - return "premultiplied alpha and readd child test"; + return "premultiplied alpha 2"; } std::string PremultipliedAlphaTest2::subtitle() const { - return "Arrows should be faded\n animation should be normal"; + return "Arrows should be faded"; } From 9034549932e2df522d8603133024a6fc4c3c3eeb Mon Sep 17 00:00:00 2001 From: TwistedUmbrella Date: Mon, 24 Mar 2014 11:28:03 -0400 Subject: [PATCH 044/106] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5562ebd9f7..2697a79a46 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ Example: ### Build and run new project for android ### - $ cocos run -p -j 4 android + $ cocos run -p android -j 4 ### Build and run new project for iOS ### From 04b529d328b5755cf2c1e148cb9d3a9b8172cc66 Mon Sep 17 00:00:00 2001 From: Dale Stammen Date: Mon, 24 Mar 2014 15:09:24 -0700 Subject: [PATCH 045/106] fixed use of nullptr in variable args for wp8 --- AUTHORS | 1 + CHANGELOG.REMOVED.git-id | 2 +- cocos/2d/CCActionInterval.cpp | 28 + cocos/2d/CCActionInterval.h | 37 ++ cocos/2d/CCComponent.cpp | 49 ++ cocos/2d/CCComponent.h | 22 +- cocos/2d/CCDrawNode.h | 5 +- cocos/2d/CCLayer.h | 18 + cocos/2d/CCMenu.cpp | 24 +- cocos/2d/CCMenu.h | 21 + cocos/2d/CCScriptSupport.h | 1 + cocos/2d/CCTexture2D.cpp | 18 +- cocos/2d/CCTransition.cpp | 66 +- cocos/2d/CCTransitionPageTurn.cpp | 4 +- cocos/2d/CCTransitionProgress.cpp | 2 +- .../cocostudio/CCActionNode.cpp | 2 +- cocos/network/SocketIO.cpp | 619 +++++++++--------- cocos/network/SocketIO.h | 109 +-- cocos/network/WebSocket.h | 38 +- extensions/GUI/CCScrollView/CCScrollView.cpp | 2 +- .../Classes/ActionsTest/ActionsTest.cpp | 12 +- .../CocoStudioArmatureTest/ArmatureScene.cpp | 12 +- .../ComponentsTestScene.cpp | 2 +- .../EnemyController.cpp | 2 +- .../GameOverScene.cpp | 4 +- .../CocoStudioGUITest/GUIEditorTest.cpp | 4 +- .../CocoStudioSceneTest/SceneEditorTest.cpp | 10 +- .../CocoStudioSceneTest/TriggerCode/acts.cpp | 8 +- .../Classes/LabelTest/LabelTestNew.cpp | 2 +- .../NewEventDispatcherTest.cpp | 16 +- .../SpriteTest/SpriteTest.cpp.REMOVED.git-id | 2 +- 31 files changed, 664 insertions(+), 478 deletions(-) diff --git a/AUTHORS b/AUTHORS index 0a6e6371dd..343d846368 100644 --- a/AUTHORS +++ b/AUTHORS @@ -548,6 +548,7 @@ Developers: hannon235 (Chris) Fixing a bug that the submenu of ExtensionTest in TestCpp can't scroll. Implements a socket.io client extension and adds a test case. + Implements 'SIODelegate::fireEventToScript' method to integrate JSB event handling with the original native code. pktangyue Fixing a bug that CCScale9Sprite::setInsetLeft/XXX can't work for rotated sprite frame. diff --git a/CHANGELOG.REMOVED.git-id b/CHANGELOG.REMOVED.git-id index 89e75b9d62..99658a8dd4 100644 --- a/CHANGELOG.REMOVED.git-id +++ b/CHANGELOG.REMOVED.git-id @@ -1 +1 @@ -e1d0a713b9c239ae437f21ab7c256413cebf3241 \ No newline at end of file +a220377dfc7c4fce177d53c2fb3ab5baddf8e404 \ No newline at end of file diff --git a/cocos/2d/CCActionInterval.cpp b/cocos/2d/CCActionInterval.cpp index ba76229207..c4d46df023 100644 --- a/cocos/2d/CCActionInterval.cpp +++ b/cocos/2d/CCActionInterval.cpp @@ -159,6 +159,19 @@ Sequence* Sequence::createWithTwoActions(FiniteTimeAction *actionOne, FiniteTime return sequence; } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) +Sequence* Sequence::variadicCreate(FiniteTimeAction *action1, ...) +{ + va_list params; + va_start(params, action1); + + Sequence *ret = Sequence::createWithVariableList(action1, params); + + va_end(params); + + return ret; +} +#else Sequence* Sequence::create(FiniteTimeAction *action1, ...) { va_list params; @@ -170,6 +183,7 @@ Sequence* Sequence::create(FiniteTimeAction *action1, ...) return ret; } +#endif Sequence* Sequence::createWithVariableList(FiniteTimeAction *action1, va_list args) { @@ -532,6 +546,19 @@ RepeatForever *RepeatForever::reverse() const // Spawn // +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) +Spawn* Spawn::variadicCreate(FiniteTimeAction *action1, ...) +{ + va_list params; + va_start(params, action1); + + Spawn *ret = Spawn::createWithVariableList(action1, params); + + va_end(params); + + return ret; +} +#else Spawn* Spawn::create(FiniteTimeAction *action1, ...) { va_list params; @@ -543,6 +570,7 @@ Spawn* Spawn::create(FiniteTimeAction *action1, ...) return ret; } +#endif Spawn* Spawn::createWithVariableList(FiniteTimeAction *action1, va_list args) { diff --git a/cocos/2d/CCActionInterval.h b/cocos/2d/CCActionInterval.h index fd55545e6d..5f52e7b8a4 100644 --- a/cocos/2d/CCActionInterval.h +++ b/cocos/2d/CCActionInterval.h @@ -93,7 +93,26 @@ class CC_DLL Sequence : public ActionInterval { public: /** helper constructor to create an array of sequenceable actions */ +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) + // WP8 in VS2012 does not support nullptr in variable args lists and variadic templates are also not supported + typedef FiniteTimeAction* M; + static Sequence* create(M m1, std::nullptr_t listEnd) { return variadicCreate(m1, NULL); } + static Sequence* create(M m1, M m2, std::nullptr_t listEnd) { return variadicCreate(m1, m2, NULL); } + static Sequence* create(M m1, M m2, M m3, std::nullptr_t listEnd) { return variadicCreate(m1, m2, m3, NULL); } + static Sequence* create(M m1, M m2, M m3, M m4, std::nullptr_t listEnd) { return variadicCreate(m1, m2, m3, m4, NULL); } + static Sequence* create(M m1, M m2, M m3, M m4, M m5, std::nullptr_t listEnd) { return variadicCreate(m1, m2, m3, m4, m5, NULL); } + static Sequence* create(M m1, M m2, M m3, M m4, M m5, M m6, std::nullptr_t listEnd) { return variadicCreate(m1, m2, m3, m4, m5, m6, NULL); } + static Sequence* create(M m1, M m2, M m3, M m4, M m5, M m6, M m7, std::nullptr_t listEnd) { return variadicCreate(m1, m2, m3, m4, m5, m6, m7, NULL); } + static Sequence* create(M m1, M m2, M m3, M m4, M m5, M m6, M m7, M m8, std::nullptr_t listEnd) { return variadicCreate(m1, m2, m3, m4, m5, m6, m7, m8, NULL); } + static Sequence* create(M m1, M m2, M m3, M m4, M m5, M m6, M m7, M m8, M m9, std::nullptr_t listEnd) { return variadicCreate(m1, m2, m3, m4, m5, m6, m7, m8, m9, NULL); } + static Sequence* create(M m1, M m2, M m3, M m4, M m5, M m6, M m7, M m8, M m9, M m10, std::nullptr_t listEnd) { return variadicCreate(m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, NULL); } + + // On WP8 for variable argument lists longer than 10 items, use the other create functions or variadicCreate with NULL as the last argument + static Sequence* variadicCreate(FiniteTimeAction* item, ...); +#else static Sequence* create(FiniteTimeAction *action1, ...) CC_REQUIRES_NULL_TERMINATION; +#endif + /** helper constructor to create an array of sequenceable actions given an array * @code * When this funtion bound to the js or lua,the input params changed @@ -248,7 +267,25 @@ public: * in lua :local create(local object1,local object2, ...) * @endcode */ +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) + // WP8 in VS2012 does not support nullptr in variable args lists and variadic templates are also not supported + typedef FiniteTimeAction* M; + static Spawn* create(M m1, std::nullptr_t listEnd) { return variadicCreate(m1, NULL); } + static Spawn* create(M m1, M m2, std::nullptr_t listEnd) { return variadicCreate(m1, m2, NULL); } + static Spawn* create(M m1, M m2, M m3, std::nullptr_t listEnd) { return variadicCreate(m1, m2, m3, NULL); } + static Spawn* create(M m1, M m2, M m3, M m4, std::nullptr_t listEnd) { return variadicCreate(m1, m2, m3, m4, NULL); } + static Spawn* create(M m1, M m2, M m3, M m4, M m5, std::nullptr_t listEnd) { return variadicCreate(m1, m2, m3, m4, m5, NULL); } + static Spawn* create(M m1, M m2, M m3, M m4, M m5, M m6, std::nullptr_t listEnd) { return variadicCreate(m1, m2, m3, m4, m5, m6, NULL); } + static Spawn* create(M m1, M m2, M m3, M m4, M m5, M m6, M m7, std::nullptr_t listEnd) { return variadicCreate(m1, m2, m3, m4, m5, m6, m7, NULL); } + static Spawn* create(M m1, M m2, M m3, M m4, M m5, M m6, M m7, M m8, std::nullptr_t listEnd) { return variadicCreate(m1, m2, m3, m4, m5, m6, m7, m8, NULL); } + static Spawn* create(M m1, M m2, M m3, M m4, M m5, M m6, M m7, M m8, M m9, std::nullptr_t listEnd) { return variadicCreate(m1, m2, m3, m4, m5, m6, m7, m8, m9, NULL); } + static Spawn* create(M m1, M m2, M m3, M m4, M m5, M m6, M m7, M m8, M m9, M m10, std::nullptr_t listEnd) { return variadicCreate(m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, NULL); } + + // On WP8 for variable argument lists longer than 10 items, use the other create functions or createSpawn with NULL as the last argument + static Spawn* variadicCreate(FiniteTimeAction* item, ...); +#else static Spawn* create(FiniteTimeAction *action1, ...) CC_REQUIRES_NULL_TERMINATION; +#endif /** helper constructor to create an array of spawned actions */ static Spawn* createWithVariableList(FiniteTimeAction *action1, va_list args); diff --git a/cocos/2d/CCComponent.cpp b/cocos/2d/CCComponent.cpp index 1d5c83a8c7..8f91cd764d 100644 --- a/cocos/2d/CCComponent.cpp +++ b/cocos/2d/CCComponent.cpp @@ -23,6 +23,7 @@ THE SOFTWARE. ****************************************************************************/ #include "CCComponent.h" +#include "CCScriptSupport.h" NS_CC_BEGIN @@ -31,6 +32,10 @@ Component::Component(void) : _owner(nullptr) , _enabled(true) { +#if CC_ENABLE_SCRIPT_BINDING + ScriptEngineProtocol* engine = ScriptEngineManager::getInstance()->getScriptEngine(); + _scriptType = engine != nullptr ? engine->getScriptType() : kScriptTypeNone; +#endif } Component::~Component(void) @@ -42,16 +47,60 @@ bool Component::init() return true; } +#if CC_ENABLE_SCRIPT_BINDING + +static bool sendComponentEventToJS(Component* node, int action) +{ + auto scriptEngine = ScriptEngineManager::getInstance()->getScriptEngine(); + + if (scriptEngine->isCalledFromScript()) + { + scriptEngine->setCalledFromScript(false); + } + else + { + BasicScriptData data(node,(void*)&action); + ScriptEvent scriptEvent(kComponentEvent,(void*)&data); + if (scriptEngine->sendEvent(&scriptEvent)) + return true; + } + + return false; +} + +#endif + void Component::onEnter() { +#if CC_ENABLE_SCRIPT_BINDING + if (_scriptType == kScriptTypeJavascript) + { + if (sendComponentEventToJS(this, kComponentOnEnter)) + return; + } +#endif } void Component::onExit() { +#if CC_ENABLE_SCRIPT_BINDING + if (_scriptType == kScriptTypeJavascript) + { + if (sendComponentEventToJS(this, kComponentOnExit)) + return; + } +#endif } void Component::update(float delta) { +#if CC_ENABLE_SCRIPT_BINDING + if (_scriptType == kScriptTypeJavascript) + { + if (sendComponentEventToJS(this, kComponentOnUpdate)) + return; + } +#endif } bool Component::serialize(void *ar) diff --git a/cocos/2d/CCComponent.h b/cocos/2d/CCComponent.h index 6b6a5ed351..97d652a940 100644 --- a/cocos/2d/CCComponent.h +++ b/cocos/2d/CCComponent.h @@ -26,15 +26,22 @@ THE SOFTWARE. #define __CC_FRAMEWORK_COMPONENT_H__ #include "CCRef.h" +#include "CCScriptSupport.h" #include NS_CC_BEGIN class Node; +enum { + kComponentOnEnter, + kComponentOnExit, + kComponentOnUpdate +}; + class CC_DLL Component : public Ref { -protected: +CC_CONSTRUCTOR_ACCESS: /** * @js ctor */ @@ -46,15 +53,8 @@ public: */ virtual ~Component(void); virtual bool init(); - /** - * @js NA - * @lua NA - */ + virtual void onEnter(); - /** - * @js NA - * @lua NA - */ virtual void onExit(); virtual void update(float delta); virtual bool serialize(void* r); @@ -72,6 +72,10 @@ protected: Node *_owner; std::string _name; bool _enabled; + +#if CC_ENABLE_SCRIPT_BINDING + ccScriptType _scriptType; ///< type of script binding, lua or javascript +#endif }; NS_CC_END diff --git a/cocos/2d/CCDrawNode.h b/cocos/2d/CCDrawNode.h index 7ac74def79..2df6e67550 100644 --- a/cocos/2d/CCDrawNode.h +++ b/cocos/2d/CCDrawNode.h @@ -93,12 +93,13 @@ public: // Overrides virtual void draw(Renderer *renderer, const kmMat4 &transform, bool transformUpdated) override; - -protected: + +CC_CONSTRUCTOR_ACCESS: DrawNode(); virtual ~DrawNode(); virtual bool init(); +protected: void ensureCapacity(int count); GLuint _vao; diff --git a/cocos/2d/CCLayer.h b/cocos/2d/CCLayer.h index b1f96f5c78..86443b75c3 100644 --- a/cocos/2d/CCLayer.h +++ b/cocos/2d/CCLayer.h @@ -431,7 +431,25 @@ public: * In lua:local create(...) * @endcode */ +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) + // WP8 in VS2012 does not support nullptr in variable args lists and variadic templates are also not supported + typedef Layer* M; + static LayerMultiplex* create(M m1, std::nullptr_t listEnd) { return createVariadic(m1, NULL); } + static LayerMultiplex* create(M m1, M m2, std::nullptr_t listEnd) { return createVariadic(m1, m2, NULL); } + static LayerMultiplex* create(M m1, M m2, M m3, std::nullptr_t listEnd) { return createVariadic(m1, m2, m3, NULL); } + static LayerMultiplex* create(M m1, M m2, M m3, M m4, std::nullptr_t listEnd) { return createVariadic(m1, m2, m3, m4, NULL); } + static LayerMultiplex* create(M m1, M m2, M m3, M m4, M m5, std::nullptr_t listEnd) { return createVariadic(m1, m2, m3, m4, m5, NULL); } + static LayerMultiplex* create(M m1, M m2, M m3, M m4, M m5, M m6, std::nullptr_t listEnd) { return createVariadic(m1, m2, m3, m4, m5, m6, NULL); } + static LayerMultiplex* create(M m1, M m2, M m3, M m4, M m5, M m6, M m7, std::nullptr_t listEnd) { return createVariadic(m1, m2, m3, m4, m5, m6, m7, NULL); } + static LayerMultiplex* create(M m1, M m2, M m3, M m4, M m5, M m6, M m7, M m8, std::nullptr_t listEnd) { return createVariadic(m1, m2, m3, m4, m5, m6, m7, m8, NULL); } + static LayerMultiplex* create(M m1, M m2, M m3, M m4, M m5, M m6, M m7, M m8, M m9, std::nullptr_t listEnd) { return createVariadic(m1, m2, m3, m4, m5, m6, m7, m8, m9, NULL); } + static LayerMultiplex* create(M m1, M m2, M m3, M m4, M m5, M m6, M m7, M m8, M m9, M m10, std::nullptr_t listEnd) { return createVariadic(m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, NULL); } + + // On WP8 for variable argument lists longer than 10 items, use createWithArray or createVariadic with NULL as the last argument + static LayerMultiplex* createVariadic(Layer* item, ...) CC_REQUIRES_NULL_TERMINATION; +#else static LayerMultiplex * create(Layer* layer, ... ); +#endif /** * lua script can not init with undetermined number of variables diff --git a/cocos/2d/CCMenu.cpp b/cocos/2d/CCMenu.cpp index 929e1d75e2..da226b8d28 100644 --- a/cocos/2d/CCMenu.cpp +++ b/cocos/2d/CCMenu.cpp @@ -56,11 +56,24 @@ Menu::~Menu() Menu* Menu::create() { - // nullptr doesn't work for WP8. Compiler can't convert nulltpr termination to MenuItem* - // must use NULL for variable arg termination - return Menu::create(nullptr, NULL); + return Menu::create(nullptr, nullptr); } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) +Menu * Menu::variadicCreate(MenuItem* item, ...) +{ + va_list args; + va_start(args,item); + + Menu *ret = Menu::createWithItems(item, args); + + va_end(args); + + return ret; +} +#else + + Menu * Menu::create(MenuItem* item, ...) { va_list args; @@ -72,6 +85,8 @@ Menu * Menu::create(MenuItem* item, ...) return ret; } +#endif + Menu* Menu::createWithArray(const Vector& arrayOfItems) { @@ -107,8 +122,7 @@ Menu* Menu::createWithItems(MenuItem* item, va_list args) Menu* Menu::createWithItem(MenuItem* item) { - // nullptr doesn't work for WP8 - return Menu::create(item, NULL); + return Menu::create(item, nullptr); } bool Menu::init() diff --git a/cocos/2d/CCMenu.h b/cocos/2d/CCMenu.h index 02287693c1..9fdb05e82b 100644 --- a/cocos/2d/CCMenu.h +++ b/cocos/2d/CCMenu.h @@ -60,9 +60,27 @@ public: /** creates an empty Menu */ static Menu* create(); + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) + // WP8 in VS2012 does not support nullptr in variable args lists and variadic templates are also not supported + typedef MenuItem* M; + static Menu* create(M m1, std::nullptr_t listEnd) { return variadicCreate(m1, NULL); } + static Menu* create(M m1, M m2, std::nullptr_t listEnd) { return variadicCreate(m1, m2, NULL); } + static Menu* create(M m1, M m2, M m3, std::nullptr_t listEnd) { return variadicCreate(m1, m2, m3, NULL); } + static Menu* create(M m1, M m2, M m3, M m4, std::nullptr_t listEnd) { return variadicCreate(m1, m2, m3, m4, NULL); } + static Menu* create(M m1, M m2, M m3, M m4, M m5, std::nullptr_t listEnd) { return variadicCreate(m1, m2, m3, m4, m5, NULL); } + static Menu* create(M m1, M m2, M m3, M m4, M m5, M m6, std::nullptr_t listEnd) { return variadicCreate(m1, m2, m3, m4, m5, m6, NULL); } + static Menu* create(M m1, M m2, M m3, M m4, M m5, M m6, M m7, std::nullptr_t listEnd) { return variadicCreate(m1, m2, m3, m4, m5, m6, m7, NULL); } + static Menu* create(M m1, M m2, M m3, M m4, M m5, M m6, M m7, M m8, std::nullptr_t listEnd) { return variadicCreate(m1, m2, m3, m4, m5, m6, m7, m8, NULL); } + static Menu* create(M m1, M m2, M m3, M m4, M m5, M m6, M m7, M m8, M m9, std::nullptr_t listEnd) { return variadicCreate(m1, m2, m3, m4, m5, m6, m7, m8, m9, NULL); } + static Menu* create(M m1, M m2, M m3, M m4, M m5, M m6, M m7, M m8, M m9, M m10, std::nullptr_t listEnd) { return variadicCreate(m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, NULL); } + // On WP8 for lists longer than 10 items, use createWithArray or variadicCreate with NULL as the last argument + static Menu* variadicCreate(MenuItem* item, ...); +#else /** creates a Menu with MenuItem objects */ static Menu* create(MenuItem* item, ...) CC_REQUIRES_NULL_TERMINATION; +#endif /** creates a Menu with a Array of MenuItem objects */ static Menu* createWithArray(const Vector& arrayOfItems); @@ -136,6 +154,9 @@ CC_CONSTRUCTOR_ACCESS: bool initWithArray(const Vector& arrayOfItems); protected: + + + /** whether or not the menu will receive events */ bool _enabled; diff --git a/cocos/2d/CCScriptSupport.h b/cocos/2d/CCScriptSupport.h index 7ba1286796..c24f41fdd5 100644 --- a/cocos/2d/CCScriptSupport.h +++ b/cocos/2d/CCScriptSupport.h @@ -212,6 +212,7 @@ enum ScriptEventType kAccelerometerEvent, kControlEvent, kCommonEvent, + kComponentEvent }; struct BasicScriptData diff --git a/cocos/2d/CCTexture2D.cpp b/cocos/2d/CCTexture2D.cpp index 54c59ec088..41c3e4e8fd 100644 --- a/cocos/2d/CCTexture2D.cpp +++ b/cocos/2d/CCTexture2D.cpp @@ -535,15 +535,6 @@ bool Texture2D::hasPremultipliedAlpha() const bool Texture2D::initWithData(const void *data, ssize_t dataLen, Texture2D::PixelFormat pixelFormat, int pixelsWide, int pixelsHigh, const Size& contentSize) { - // cocos2d-x is currently calling this multiple times on the same Texture2D - // if the GL texture has already been created,it will be leaked in OpenGL - // For now, call deleteTexture if the texture already exists - if(_name) - { - GL::deleteTexture(_name); - _name = 0; - } - CCASSERT(dataLen>0 && pixelsWide>0 && pixelsHigh>0, "Invalid size"); //if data has no mipmaps, we will consider it has only one mipmap @@ -560,6 +551,15 @@ bool Texture2D::initWithData(const void *data, ssize_t dataLen, Texture2D::Pixel bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat pixelFormat, int pixelsWide, int pixelsHigh) { + // cocos2d-x is currently calling this multiple times on the same Texture2D + // if the GL texture has already been created,it will be leaked in OpenGL + // For now, call deleteTexture if the texture already exists + if(_name) + { + GL::deleteTexture(_name); + _name = 0; + } + //the pixelFormat must be a certain value CCASSERT(pixelFormat != PixelFormat::NONE && pixelFormat != PixelFormat::AUTO, "the \"pixelFormat\" param must be a certain value!"); CCASSERT(pixelsWide>0 && pixelsHigh>0, "Invalid size"); diff --git a/cocos/2d/CCTransition.cpp b/cocos/2d/CCTransition.cpp index ac76ecea8f..0777474369 100644 --- a/cocos/2d/CCTransition.cpp +++ b/cocos/2d/CCTransition.cpp @@ -258,10 +258,10 @@ void TransitionRotoZoom:: onEnter() ( ScaleBy::create(_duration/2, 0.001f), RotateBy::create(_duration/2, 360 * 2), - NULL + nullptr ), DelayTime::create(_duration/2), - NULL + nullptr )); _outScene->runAction(rotozoom); @@ -271,7 +271,7 @@ void TransitionRotoZoom:: onEnter() ( rotozoom->reverse(), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - NULL + nullptr ) ); } @@ -312,8 +312,8 @@ void TransitionJumpZoom::onEnter() ActionInterval *scaleIn = ScaleTo::create(_duration/4, 1.0f); ActionInterval *scaleOut = ScaleTo::create(_duration/4, 0.5f); - ActionInterval *jumpZoomOut = (ActionInterval*)(Sequence::create(scaleOut, jump, NULL)); - ActionInterval *jumpZoomIn = (ActionInterval*)(Sequence::create(jump, scaleIn, NULL)); + ActionInterval *jumpZoomOut = (ActionInterval*)(Sequence::create(scaleOut, jump, nullptr)); + ActionInterval *jumpZoomIn = (ActionInterval*)(Sequence::create(jump, scaleIn, nullptr)); ActionInterval *delay = DelayTime::create(_duration/2); @@ -325,7 +325,7 @@ void TransitionJumpZoom::onEnter() delay, jumpZoomIn, CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - NULL + nullptr ) ); } @@ -366,7 +366,7 @@ void TransitionMoveInL::onEnter() ( this->easeActionWithAction(a), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - NULL + nullptr ) ); } @@ -503,7 +503,7 @@ void TransitionSlideInL::onEnter() ( easeActionWithAction(out), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - NULL + nullptr ); _inScene->runAction(inAction); _outScene->runAction(outAction); @@ -706,7 +706,7 @@ void TransitionShrinkGrow::onEnter() ( this->easeActionWithAction(scaleOut), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - NULL + nullptr ) ); } @@ -757,7 +757,7 @@ void TransitionFlipX::onEnter() Show::create(), OrbitCamera::create(_duration/2, 1, 0, inAngleZ, inDeltaZ, 0, 0), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - NULL + nullptr ); outA = (ActionInterval *)Sequence::create @@ -765,7 +765,7 @@ void TransitionFlipX::onEnter() OrbitCamera::create(_duration/2, 1, 0, outAngleZ, outDeltaZ, 0, 0), Hide::create(), DelayTime::create(_duration/2), - NULL + nullptr ); _inScene->runAction(inA); @@ -827,14 +827,14 @@ void TransitionFlipY::onEnter() Show::create(), OrbitCamera::create(_duration/2, 1, 0, inAngleZ, inDeltaZ, 90, 0), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - NULL + nullptr ); outA = (ActionInterval*)Sequence::create ( OrbitCamera::create(_duration/2, 1, 0, outAngleZ, outDeltaZ, 90, 0), Hide::create(), DelayTime::create(_duration/2), - NULL + nullptr ); _inScene->runAction(inA); @@ -898,14 +898,14 @@ void TransitionFlipAngular::onEnter() Show::create(), OrbitCamera::create(_duration/2, 1, 0, inAngleZ, inDeltaZ, -45, 0), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - NULL + nullptr ); outA = (ActionInterval *)Sequence::create ( OrbitCamera::create(_duration/2, 1, 0, outAngleZ, outDeltaZ, 45, 0), Hide::create(), DelayTime::create(_duration/2), - NULL + nullptr ); _inScene->runAction(inA); @@ -967,10 +967,10 @@ void TransitionZoomFlipX::onEnter() OrbitCamera::create(_duration/2, 1, 0, inAngleZ, inDeltaZ, 0, 0), ScaleTo::create(_duration/2, 1), Show::create(), - NULL + nullptr ), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - NULL + nullptr ); outA = (ActionInterval *)Sequence::create ( @@ -978,11 +978,11 @@ void TransitionZoomFlipX::onEnter() ( OrbitCamera::create(_duration/2, 1, 0, outAngleZ, outDeltaZ, 0, 0), ScaleTo::create(_duration/2, 0.5f), - NULL + nullptr ), Hide::create(), DelayTime::create(_duration/2), - NULL + nullptr ); _inScene->setScale(0.5f); @@ -1045,10 +1045,10 @@ void TransitionZoomFlipY::onEnter() OrbitCamera::create(_duration/2, 1, 0, inAngleZ, inDeltaZ, 90, 0), ScaleTo::create(_duration/2, 1), Show::create(), - NULL + nullptr ), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - NULL + nullptr ); outA = (ActionInterval *)Sequence::create @@ -1057,11 +1057,11 @@ void TransitionZoomFlipY::onEnter() ( OrbitCamera::create(_duration/2, 1, 0, outAngleZ, outDeltaZ, 90, 0), ScaleTo::create(_duration/2, 0.5f), - NULL + nullptr ), Hide::create(), DelayTime::create(_duration/2), - NULL + nullptr ); _inScene->setScale(0.5f); @@ -1126,11 +1126,11 @@ void TransitionZoomFlipAngular::onEnter() OrbitCamera::create(_duration/2, 1, 0, inAngleZ, inDeltaZ, -45, 0), ScaleTo::create(_duration/2, 1), Show::create(), - NULL + nullptr ), Show::create(), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - NULL + nullptr ); outA = (ActionInterval *)Sequence::create ( @@ -1138,11 +1138,11 @@ void TransitionZoomFlipAngular::onEnter() ( OrbitCamera::create(_duration/2, 1, 0 , outAngleZ, outDeltaZ, 45, 0), ScaleTo::create(_duration/2, 0.5f), - NULL + nullptr ), Hide::create(), DelayTime::create(_duration/2), - NULL + nullptr ); _inScene->setScale(0.5f); @@ -1222,7 +1222,7 @@ void TransitionFade :: onEnter() FadeOut::create(_duration/2), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - NULL + nullptr ); f->runAction(a); } @@ -1321,7 +1321,7 @@ void TransitionCrossFade::onEnter() FadeTo::create(_duration, 0), CallFunc::create(CC_CALLBACK_0(TransitionScene::hideOutShowIn,this)), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - NULL + nullptr ); @@ -1392,7 +1392,7 @@ void TransitionTurnOffTiles::onEnter() action, CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), StopGrid::create(), - NULL + nullptr ) ); } @@ -1464,7 +1464,7 @@ void TransitionSplitCols::onEnter() split, CallFunc::create(CC_CALLBACK_0(TransitionSplitCols::switchTargetToInscene,this)), split->reverse(), - NULL + nullptr ); _gridProxy->runAction @@ -1474,7 +1474,7 @@ void TransitionSplitCols::onEnter() easeActionWithAction(seq), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), StopGrid::create(), - NULL + nullptr ) ); } @@ -1588,7 +1588,7 @@ void TransitionFadeTR::onEnter() easeActionWithAction(action), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), StopGrid::create(), - NULL + nullptr ) ); } diff --git a/cocos/2d/CCTransitionPageTurn.cpp b/cocos/2d/CCTransitionPageTurn.cpp index eb11e3937c..9736dcda21 100644 --- a/cocos/2d/CCTransitionPageTurn.cpp +++ b/cocos/2d/CCTransitionPageTurn.cpp @@ -154,7 +154,7 @@ void TransitionPageTurn::onEnter() action, CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), StopGrid::create(), - NULL + nullptr ) ); } @@ -170,7 +170,7 @@ void TransitionPageTurn::onEnter() action, CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), StopGrid::create(), - NULL + nullptr ) ); } diff --git a/cocos/2d/CCTransitionProgress.cpp b/cocos/2d/CCTransitionProgress.cpp index 9ee60cf6df..5735f1bb40 100644 --- a/cocos/2d/CCTransitionProgress.cpp +++ b/cocos/2d/CCTransitionProgress.cpp @@ -95,7 +95,7 @@ void TransitionProgress::onEnter() ActionInterval* layerAction = (ActionInterval*)Sequence::create( ProgressFromTo::create(_duration, _from, _to), CallFunc::create(CC_CALLBACK_0(TransitionScene::finish,this)), - NULL); + nullptr); // run the blend action node->runAction(layerAction); diff --git a/cocos/editor-support/cocostudio/CCActionNode.cpp b/cocos/editor-support/cocostudio/CCActionNode.cpp index d537dafdc2..d615b11c46 100644 --- a/cocos/editor-support/cocostudio/CCActionNode.cpp +++ b/cocos/editor-support/cocostudio/CCActionNode.cpp @@ -351,7 +351,7 @@ void ActionNode::playAction() _action->release(); } - _action = Sequence::create(_actionSpawn, NULL); + _action = Sequence::create(_actionSpawn, nullptr); _action->retain(); this->runAction(); diff --git a/cocos/network/SocketIO.cpp b/cocos/network/SocketIO.cpp index af7b295543..9e669f7e0a 100644 --- a/cocos/network/SocketIO.cpp +++ b/cocos/network/SocketIO.cpp @@ -1,19 +1,19 @@ /**************************************************************************** Copyright (c) 2013 Chris Hannon Copyright (c) 2013-2014 Chukong Technologies Inc. - + http://www.cocos2d-x.org - + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -43,114 +43,114 @@ namespace network { /** * @brief The implementation of the socket.io connection - * Clients/endpoints may share the same impl to accomplish multiplexing on the same websocket + * Clients/endpoints may share the same impl to accomplish multiplexing on the same websocket */ -class SIOClientImpl : - public cocos2d::Ref, - public WebSocket::Delegate +class SIOClientImpl : + public cocos2d::Ref, + public WebSocket::Delegate { -private: - int _port, _heartbeat, _timeout; - std::string _host, _sid, _uri; - bool _connected; +private: + int _port, _heartbeat, _timeout; + std::string _host, _sid, _uri; + bool _connected; - WebSocket *_ws; + WebSocket *_ws; - Map _clients; + Map _clients; public: - SIOClientImpl(const std::string& host, int port); - virtual ~SIOClientImpl(void); + SIOClientImpl(const std::string& host, int port); + virtual ~SIOClientImpl(void); - static SIOClientImpl* create(const std::string& host, int port); - - virtual void onOpen(WebSocket* ws); + static SIOClientImpl* create(const std::string& host, int port); + + virtual void onOpen(WebSocket* ws); virtual void onMessage(WebSocket* ws, const WebSocket::Data& data); virtual void onClose(WebSocket* ws); virtual void onError(WebSocket* ws, const WebSocket::ErrorCode& error); - void connect(); - void disconnect(); - bool init(); - void handshake(); - void handshakeResponse(HttpClient *sender, HttpResponse *response); - void openSocket(); - void heartbeat(float dt); + void connect(); + void disconnect(); + bool init(); + void handshake(); + void handshakeResponse(HttpClient *sender, HttpResponse *response); + void openSocket(); + void heartbeat(float dt); - SIOClient* getClient(const std::string& endpoint); - void addClient(const std::string& endpoint, SIOClient* client); - - void connectToEndpoint(const std::string& endpoint); - void disconnectFromEndpoint(const std::string& endpoint); + SIOClient* getClient(const std::string& endpoint); + void addClient(const std::string& endpoint, SIOClient* client); - void send(std::string endpoint, std::string s); - void emit(std::string endpoint, std::string eventname, std::string args); + void connectToEndpoint(const std::string& endpoint); + void disconnectFromEndpoint(const std::string& endpoint); + + void send(std::string endpoint, std::string s); + void emit(std::string endpoint, std::string eventname, std::string args); }; - + //method implementations //begin SIOClientImpl methods SIOClientImpl::SIOClientImpl(const std::string& host, int port) : - _port(port), - _host(host), - _connected(false) + _port(port), + _host(host), + _connected(false) { - std::stringstream s; - s << host << ":" << port; - _uri = s.str(); + std::stringstream s; + s << host << ":" << port; + _uri = s.str(); - _ws = nullptr; + _ws = nullptr; } SIOClientImpl::~SIOClientImpl() { - if (_connected) + if (_connected) disconnect(); - CC_SAFE_DELETE(_ws); + CC_SAFE_DELETE(_ws); } void SIOClientImpl::handshake() { - log("SIOClientImpl::handshake() called"); + log("SIOClientImpl::handshake() called"); - std::stringstream pre; - pre << "http://" << _uri << "/socket.io/1"; + std::stringstream pre; + pre << "http://" << _uri << "/socket.io/1"; - HttpRequest* request = new HttpRequest(); - request->setUrl(pre.str().c_str()); + HttpRequest* request = new HttpRequest(); + request->setUrl(pre.str().c_str()); request->setRequestType(HttpRequest::Type::GET); request->setResponseCallback(this, httpresponse_selector(SIOClientImpl::handshakeResponse)); request->setTag("handshake"); - log("SIOClientImpl::handshake() waiting"); + log("SIOClientImpl::handshake() waiting"); HttpClient::getInstance()->send(request); - - request->release(); - - return; + + request->release(); + + return; } void SIOClientImpl::handshakeResponse(HttpClient *sender, HttpResponse *response) { - log("SIOClientImpl::handshakeResponse() called"); + log("SIOClientImpl::handshakeResponse() called"); - if (0 != strlen(response->getHttpRequest()->getTag())) + if (0 != strlen(response->getHttpRequest()->getTag())) { log("%s completed", response->getHttpRequest()->getTag()); } - long statusCode = response->getResponseCode(); + long statusCode = response->getResponseCode(); char statusString[64] = {}; sprintf(statusString, "HTTP Status Code: %ld, tag = %s", statusCode, response->getHttpRequest()->getTag()); - log("response code: %ld", statusCode); + log("response code: %ld", statusCode); - if (!response->isSucceed()) + if (!response->isSucceed()) { log("SIOClientImpl::handshake() failed"); log("error buffer: %s", response->getErrorBuffer()); @@ -163,302 +163,302 @@ void SIOClientImpl::handshakeResponse(HttpClient *sender, HttpResponse *response return; } - log("SIOClientImpl::handshake() succeeded"); + log("SIOClientImpl::handshake() succeeded"); - std::vector *buffer = response->getResponseData(); - std::stringstream s; - - for (unsigned int i = 0; i < buffer->size(); i++) + std::vector *buffer = response->getResponseData(); + std::stringstream s; + + for (unsigned int i = 0; i < buffer->size(); i++) { - s << (*buffer)[i]; + s << (*buffer)[i]; } - - log("SIOClientImpl::handshake() dump data: %s", s.str().c_str()); - std::string res = s.str(); - std::string sid; - size_t pos = 0; - int heartbeat = 0, timeout = 0; + log("SIOClientImpl::handshake() dump data: %s", s.str().c_str()); - pos = res.find(":"); - if(pos != std::string::npos) + std::string res = s.str(); + std::string sid; + size_t pos = 0; + int heartbeat = 0, timeout = 0; + + pos = res.find(":"); + if(pos != std::string::npos) { - sid = res.substr(0, pos); - res.erase(0, pos+1); - } + sid = res.substr(0, pos); + res.erase(0, pos+1); + } - pos = res.find(":"); + pos = res.find(":"); if(pos != std::string::npos) { heartbeat = atoi(res.substr(pos+1, res.size()).c_str()); } - pos = res.find(":"); + pos = res.find(":"); if(pos != std::string::npos) { timeout = atoi(res.substr(pos+1, res.size()).c_str()); } - _sid = sid; - _heartbeat = heartbeat; - _timeout = timeout; - - openSocket(); + _sid = sid; + _heartbeat = heartbeat; + _timeout = timeout; - return; + openSocket(); + + return; } void SIOClientImpl::openSocket() { - log("SIOClientImpl::openSocket() called"); + log("SIOClientImpl::openSocket() called"); - std::stringstream s; - s << _uri << "/socket.io/1/websocket/" << _sid; + std::stringstream s; + s << _uri << "/socket.io/1/websocket/" << _sid; - _ws = new WebSocket(); - if (!_ws->init(*this, s.str())) - { - CC_SAFE_DELETE(_ws); - } - - return; + _ws = new WebSocket(); + if (!_ws->init(*this, s.str())) + { + CC_SAFE_DELETE(_ws); + } + + return; } bool SIOClientImpl::init() { - log("SIOClientImpl::init() successful"); - return true; + log("SIOClientImpl::init() successful"); + return true; } void SIOClientImpl::connect() { - this->handshake(); + this->handshake(); } void SIOClientImpl::disconnect() { - if(_ws->getReadyState() == WebSocket::State::OPEN) + if(_ws->getReadyState() == WebSocket::State::OPEN) { - std::string s = "0::"; + std::string s = "0::"; - _ws->send(s); + _ws->send(s); - log("Disconnect sent"); + log("Disconnect sent"); - _ws->close(); - } + _ws->close(); + } - Director::getInstance()->getScheduler()->unscheduleAllForTarget(this); + Director::getInstance()->getScheduler()->unscheduleAllForTarget(this); - _connected = false; + _connected = false; - SocketIO::getInstance()->removeSocket(_uri); + SocketIO::getInstance()->removeSocket(_uri); } SIOClientImpl* SIOClientImpl::create(const std::string& host, int port) { - SIOClientImpl *s = new SIOClientImpl(host, port); + SIOClientImpl *s = new SIOClientImpl(host, port); - if (s && s->init()) + if (s && s->init()) { - return s; - } + return s; + } - return nullptr; + return nullptr; } SIOClient* SIOClientImpl::getClient(const std::string& endpoint) -{ - return _clients.at(endpoint); +{ + return _clients.at(endpoint); } void SIOClientImpl::addClient(const std::string& endpoint, SIOClient* client) { - _clients.insert(endpoint, client); + _clients.insert(endpoint, client); } void SIOClientImpl::connectToEndpoint(const std::string& endpoint) { - std::string path = endpoint == "/" ? "" : endpoint; + std::string path = endpoint == "/" ? "" : endpoint; - std::string s = "1::" + path; + std::string s = "1::" + path; - _ws->send(s); + _ws->send(s); } void SIOClientImpl::disconnectFromEndpoint(const std::string& endpoint) { - _clients.erase(endpoint); + _clients.erase(endpoint); - if (_clients.empty() || endpoint == "/") + if (_clients.empty() || endpoint == "/") { - log("SIOClientImpl::disconnectFromEndpoint out of endpoints, checking for disconnect"); - - if(_connected) + log("SIOClientImpl::disconnectFromEndpoint out of endpoints, checking for disconnect"); + + if(_connected) this->disconnect(); - } + } else { - std::string path = endpoint == "/" ? "" : endpoint; + std::string path = endpoint == "/" ? "" : endpoint; - std::string s = "0::" + path; + std::string s = "0::" + path; - _ws->send(s); - } + _ws->send(s); + } } void SIOClientImpl::heartbeat(float dt) { - std::string s = "2::"; + std::string s = "2::"; - _ws->send(s); + _ws->send(s); - log("Heartbeat sent"); + log("Heartbeat sent"); } void SIOClientImpl::send(std::string endpoint, std::string s) { - std::stringstream pre; + std::stringstream pre; - std::string path = endpoint == "/" ? "" : endpoint; - - pre << "3::" << path << ":" << s; + std::string path = endpoint == "/" ? "" : endpoint; - std::string msg = pre.str(); + pre << "3::" << path << ":" << s; - log("sending message: %s", msg.c_str()); + std::string msg = pre.str(); - _ws->send(msg); + log("sending message: %s", msg.c_str()); + + _ws->send(msg); } void SIOClientImpl::emit(std::string endpoint, std::string eventname, std::string args) { - std::stringstream pre; + std::stringstream pre; - std::string path = endpoint == "/" ? "" : endpoint; - - pre << "5::" << path << ":{\"name\":\"" << eventname << "\",\"args\":" << args << "}"; + std::string path = endpoint == "/" ? "" : endpoint; - std::string msg = pre.str(); + pre << "5::" << path << ":{\"name\":\"" << eventname << "\",\"args\":" << args << "}"; - log("emitting event with data: %s", msg.c_str()); + std::string msg = pre.str(); - _ws->send(msg); + log("emitting event with data: %s", msg.c_str()); + + _ws->send(msg); } void SIOClientImpl::onOpen(WebSocket* ws) { - _connected = true; + _connected = true; - SocketIO::getInstance()->addSocket(_uri, this); + SocketIO::getInstance()->addSocket(_uri, this); for (auto iter = _clients.begin(); iter != _clients.end(); ++iter) { iter->second->onOpen(); } - Director::getInstance()->getScheduler()->schedule(schedule_selector(SIOClientImpl::heartbeat), this, (_heartbeat * .9f), false); - - log("SIOClientImpl::onOpen socket connected!"); + Director::getInstance()->getScheduler()->schedule(schedule_selector(SIOClientImpl::heartbeat), this, (_heartbeat * .9f), false); + + log("SIOClientImpl::onOpen socket connected!"); } void SIOClientImpl::onMessage(WebSocket* ws, const WebSocket::Data& data) { - log("SIOClientImpl::onMessage received: %s", data.bytes); + log("SIOClientImpl::onMessage received: %s", data.bytes); - int control = atoi(&data.bytes[0]); + int control = atoi(&data.bytes[0]); - std::string payload, msgid, endpoint, s_data, eventname; - payload = data.bytes; + std::string payload, msgid, endpoint, s_data, eventname; + payload = data.bytes; - size_t pos, pos2; + size_t pos, pos2; - pos = payload.find(":"); - if(pos != std::string::npos ) { - payload.erase(0, pos+1); - } + pos = payload.find(":"); + if(pos != std::string::npos ) { + payload.erase(0, pos+1); + } - pos = payload.find(":"); - if(pos != std::string::npos ) { - msgid = atoi(payload.substr(0, pos+1).c_str()); - } - payload.erase(0, pos+1); + pos = payload.find(":"); + if(pos != std::string::npos ) { + msgid = atoi(payload.substr(0, pos+1).c_str()); + } + payload.erase(0, pos+1); - pos = payload.find(":"); - if(pos != std::string::npos) + pos = payload.find(":"); + if(pos != std::string::npos) { - endpoint = payload.substr(0, pos); - payload.erase(0, pos+1); - } + endpoint = payload.substr(0, pos); + payload.erase(0, pos+1); + } else { - endpoint = payload; - } + endpoint = payload; + } - if (endpoint == "") endpoint = "/"; + if (endpoint == "") endpoint = "/"; - s_data = payload; - SIOClient *c = NULL; - c = getClient(endpoint); - if (c == NULL) log("SIOClientImpl::onMessage client lookup returned NULL"); + s_data = payload; + SIOClient *c = NULL; + c = getClient(endpoint); + if (c == NULL) log("SIOClientImpl::onMessage client lookup returned NULL"); - switch(control) + switch(control) { - case 0: - log("Received Disconnect Signal for Endpoint: %s\n", endpoint.c_str()); - if(c) c->receivedDisconnect(); - disconnectFromEndpoint(endpoint); - break; - case 1: - log("Connected to endpoint: %s \n",endpoint.c_str()); - if(c) c->onConnect(); - break; - case 2: - log("Heartbeat received\n"); - break; - case 3: - log("Message received: %s \n", s_data.c_str()); - if(c) c->getDelegate()->onMessage(c, s_data); - break; - case 4: - log("JSON Message Received: %s \n", s_data.c_str()); - if(c) c->getDelegate()->onMessage(c, s_data); - break; - case 5: - log("Event Received with data: %s \n", s_data.c_str()); + case 0: + log("Received Disconnect Signal for Endpoint: %s\n", endpoint.c_str()); + if(c) c->receivedDisconnect(); + disconnectFromEndpoint(endpoint); + break; + case 1: + log("Connected to endpoint: %s \n",endpoint.c_str()); + if(c) c->onConnect(); + break; + case 2: + log("Heartbeat received\n"); + break; + case 3: + log("Message received: %s \n", s_data.c_str()); + if(c) c->getDelegate()->onMessage(c, s_data); + break; + case 4: + log("JSON Message Received: %s \n", s_data.c_str()); + if(c) c->getDelegate()->onMessage(c, s_data); + break; + case 5: + log("Event Received with data: %s \n", s_data.c_str()); - if(c) + if(c) { - eventname = ""; - pos = s_data.find(":"); - pos2 = s_data.find(","); - if(pos2 > pos) + eventname = ""; + pos = s_data.find(":"); + pos2 = s_data.find(","); + if(pos2 > pos) { - s_data = s_data.substr(pos+1, pos2-pos-1); - std::remove_copy(s_data.begin(), s_data.end(), - std::back_inserter(eventname), '"'); - } + s_data = s_data.substr(pos+1, pos2-pos-1); + std::remove_copy(s_data.begin(), s_data.end(), + std::back_inserter(eventname), '"'); + } - c->fireEvent(eventname, payload); - } - - break; - case 6: - log("Message Ack\n"); - break; - case 7: - log("Error\n"); - if(c) c->getDelegate()->onError(c, s_data); - break; - case 8: - log("Noop\n"); - break; - } + c->fireEvent(eventname, payload); + } - return; + break; + case 6: + log("Message Ack\n"); + break; + case 7: + log("Error\n"); + if(c) c->getDelegate()->onError(c, s_data); + break; + case 8: + log("Noop\n"); + break; + } + + return; } void SIOClientImpl::onClose(WebSocket* ws) @@ -467,11 +467,11 @@ void SIOClientImpl::onClose(WebSocket* ws) { for (auto iter = _clients.begin(); iter != _clients.end(); ++iter) { - iter->second->receivedDisconnect(); + iter->second->receivedDisconnect(); } } - this->release(); + this->release(); } void SIOClientImpl::onError(WebSocket* ws, const WebSocket::ErrorCode& error) @@ -479,104 +479,106 @@ void SIOClientImpl::onError(WebSocket* ws, const WebSocket::ErrorCode& error) } //begin SIOClient methods -SIOClient::SIOClient(const std::string& host, int port, const std::string& path, SIOClientImpl* impl, SocketIO::SIODelegate& delegate) - : _port(port) - , _host(host) - , _path(path) +SIOClient::SIOClient(const std::string& host, int port, const std::string& path, SIOClientImpl* impl, SocketIO::SIODelegate& delegate) + : _port(port) + , _host(host) + , _path(path) , _connected(false) - , _socket(impl) - , _delegate(&delegate) + , _socket(impl) + , _delegate(&delegate) { } SIOClient::~SIOClient(void) { - if (_connected) + if (_connected) { - _socket->disconnectFromEndpoint(_path); - } + _socket->disconnectFromEndpoint(_path); + } } void SIOClient::onOpen() { - if (_path != "/") + if (_path != "/") { _socket->connectToEndpoint(_path); - } + } } void SIOClient::onConnect() { - _connected = true; - _delegate->onConnect(this); + _connected = true; + _delegate->onConnect(this); } void SIOClient::send(std::string s) { - if (_connected) + if (_connected) { - _socket->send(_path, s); - } + _socket->send(_path, s); + } else { - _delegate->onError(this, "Client not yet connected"); - } + _delegate->onError(this, "Client not yet connected"); + } } void SIOClient::emit(std::string eventname, std::string args) { - if(_connected) + if(_connected) { - _socket->emit(_path, eventname, args); - } + _socket->emit(_path, eventname, args); + } else { - _delegate->onError(this, "Client not yet connected"); - } + _delegate->onError(this, "Client not yet connected"); + } } void SIOClient::disconnect() { - _connected = false; + _connected = false; - _socket->disconnectFromEndpoint(_path); + _socket->disconnectFromEndpoint(_path); - _delegate->onClose(this); - - this->release(); + _delegate->onClose(this); + + this->release(); } void SIOClient::receivedDisconnect() { - _connected = false; + _connected = false; - _delegate->onClose(this); + _delegate->onClose(this); - this->release(); + this->release(); } void SIOClient::on(const std::string& eventName, SIOEvent e) { - _eventRegistry[eventName] = e; + _eventRegistry[eventName] = e; } void SIOClient::fireEvent(const std::string& eventName, const std::string& data) { - log("SIOClient::fireEvent called with event name: %s and data: %s", eventName.c_str(), data.c_str()); + log("SIOClient::fireEvent called with event name: %s and data: %s", eventName.c_str(), data.c_str()); - if(_eventRegistry[eventName]) + _delegate->fireEventToScript(this, eventName, data); + + if(_eventRegistry[eventName]) { - SIOEvent e = _eventRegistry[eventName]; + SIOEvent e = _eventRegistry[eventName]; - e(this, data); + e(this, data); - return; - } + return; + } - log("SIOClient::fireEvent no event with name %s found", eventName.c_str()); + log("SIOClient::fireEvent no native event with name %s found", eventName.c_str()); } //begin SocketIO methods @@ -592,102 +594,109 @@ SocketIO::~SocketIO(void) SocketIO* SocketIO::getInstance() { - if (nullptr == _inst) + if (nullptr == _inst) _inst = new SocketIO(); - - return _inst; + + return _inst; } void SocketIO::destroyInstance() { CC_SAFE_DELETE(_inst); } - + SIOClient* SocketIO::connect(SocketIO::SIODelegate& delegate, const std::string& uri) { - std::string host = uri; - int port = 0; + + return SocketIO::connect(uri, delegate); + +} + +SIOClient* SocketIO::connect(const std::string& uri, SocketIO::SIODelegate& delegate) +{ + std::string host = uri; + int port = 0; size_t pos = 0; - pos = host.find("//"); - if (pos != std::string::npos) + pos = host.find("//"); + if (pos != std::string::npos) { - host.erase(0, pos+2); - } + host.erase(0, pos+2); + } - pos = host.find(":"); + pos = host.find(":"); if (pos != std::string::npos) { port = atoi(host.substr(pos+1, host.size()).c_str()); } - pos = host.find("/", 0); + pos = host.find("/", 0); std::string path = "/"; if (pos != std::string::npos) { path += host.substr(pos + 1, host.size()); } - pos = host.find(":"); + pos = host.find(":"); if (pos != std::string::npos) { host.erase(pos, host.size()); } else if ((pos = host.find("/")) != std::string::npos) { - host.erase(pos, host.size()); + host.erase(pos, host.size()); } - std::stringstream s; - s << host << ":" << port; - - SIOClientImpl* socket = nullptr; - SIOClient *c = nullptr; + std::stringstream s; + s << host << ":" << port; - socket = SocketIO::getInstance()->getSocket(s.str()); + SIOClientImpl* socket = nullptr; + SIOClient *c = nullptr; - if(socket == nullptr) + socket = SocketIO::getInstance()->getSocket(s.str()); + + if(socket == nullptr) { - //create a new socket, new client, connect - socket = SIOClientImpl::create(host, port); + //create a new socket, new client, connect + socket = SIOClientImpl::create(host, port); - c = new SIOClient(host, port, path, socket, delegate); - - socket->addClient(path, c); + c = new SIOClient(host, port, path, socket, delegate); - socket->connect(); - } + socket->addClient(path, c); + + socket->connect(); + } else { - //check if already connected to endpoint, handle - c = socket->getClient(path); + //check if already connected to endpoint, handle + c = socket->getClient(path); - if(c == NULL) + if(c == NULL) { - c = new SIOClient(host, port, path, socket, delegate); - - socket->addClient(path, c); + c = new SIOClient(host, port, path, socket, delegate); - socket->connectToEndpoint(path); - } - } - - return c; + socket->addClient(path, c); + + socket->connectToEndpoint(path); + } + } + + return c; } SIOClientImpl* SocketIO::getSocket(const std::string& uri) { - return _sockets.at(uri); + return _sockets.at(uri); } void SocketIO::addSocket(const std::string& uri, SIOClientImpl* socket) { - _sockets.insert(uri, socket); + _sockets.insert(uri, socket); } void SocketIO::removeSocket(const std::string& uri) { - _sockets.erase(uri); + _sockets.erase(uri); } } diff --git a/cocos/network/SocketIO.h b/cocos/network/SocketIO.h index 4721810c5c..5a3d73f9c1 100644 --- a/cocos/network/SocketIO.h +++ b/cocos/network/SocketIO.h @@ -1,17 +1,17 @@ /**************************************************************************** Copyright (c) 2013 Chris Hannon http://www.channon.us Copyright (c) 2013-2014 Chukong Technologies Inc. - + 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 @@ -27,32 +27,32 @@ Usage is described below, a full working example can be found in TestCpp under E creating a new connection to a socket.io server running at localhost:3000 - SIOClient *client = SocketIO::connect(*delegate, "ws://localhost:3000"); + SIOClient *client = SocketIO::connect(*delegate, "ws://localhost:3000"); the connection process will begin and if successful delegate::onOpen will be called if the connection process results in an error, delegate::onError will be called with the err msg sending a message to the server - client->send("Hello!"); + client->send("Hello!"); emitting an event to be handled by the server, argument json formatting is up to you - client->emit("eventname", "[{\"arg\":\"value\"}]"); + client->emit("eventname", "[{\"arg\":\"value\"}]"); registering an event callback, target should be a member function in a subclass of SIODelegate CC_CALLBACK_2 is used to wrap the callback with std::bind and store as an SIOEvent - client->on("eventname", CC_CALLBACK_2(TargetClass::targetfunc, *targetclass_instance)); + client->on("eventname", CC_CALLBACK_2(TargetClass::targetfunc, *targetclass_instance)); event target function should match this pattern, *this pointer will be made available - void TargetClass::targetfunc(SIOClient *, const std::string&) + void TargetClass::targetfunc(SIOClient *, const std::string&) disconnect from the endpoint by calling disconnect(), onClose will be called on the delegate once complete in the onClose method the pointer should be set to NULL or used to connect to a new endpoint - client->disconnect(); + client->disconnect(); ****************************************************************************/ @@ -78,44 +78,47 @@ class SIOClient; class SocketIO { public: - static SocketIO* getInstance(); + static SocketIO* getInstance(); static void destroyInstance(); - /** + /** * @brief The delegate class to process socket.io events */ - class SIODelegate + class SIODelegate { public: virtual ~SIODelegate() {} - virtual void onConnect(SIOClient* client) = 0; + virtual void onConnect(SIOClient* client) = 0; virtual void onMessage(SIOClient* client, const std::string& data) = 0; virtual void onClose(SIOClient* client) = 0; virtual void onError(SIOClient* client, const std::string& data) = 0; + virtual void fireEventToScript(SIOClient* client, const std::string& eventName, const std::string& data) { CCLOG("SIODelegate event '%s' fired with data: %s", eventName.c_str(), data.c_str()); }; }; - /** + /** * @brief Static client creation method, similar to socketio.connect(uri) in JS * @param delegate The delegate which want to receive events from the socket.io client * @param uri The URI of the socket.io server * @return An initialized SIOClient if connected successfully, otherwise NULL */ - static SIOClient* connect(SocketIO::SIODelegate& delegate, const std::string& uri); - + static SIOClient* connect(const std::string& uri, SocketIO::SIODelegate& delegate); + + CC_DEPRECATED_ATTRIBUTE static SIOClient* connect(SocketIO::SIODelegate& delegate, const std::string& uri); + private: SocketIO(); - virtual ~SocketIO(void); - - static SocketIO *_inst; + virtual ~SocketIO(void); - cocos2d::Map _sockets; + static SocketIO *_inst; - SIOClientImpl* getSocket(const std::string& uri); - void addSocket(const std::string& uri, SIOClientImpl* socket); - void removeSocket(const std::string& uri); + cocos2d::Map _sockets; - friend class SIOClientImpl; + SIOClientImpl* getSocket(const std::string& uri); + void addSocket(const std::string& uri, SIOClientImpl* socket); + void removeSocket(const std::string& uri); + + friend class SIOClientImpl; private: CC_DISALLOW_COPY_AND_ASSIGN(SocketIO) }; @@ -129,59 +132,59 @@ typedef std::unordered_map EventRegistry; * @brief A single connection to a socket.io endpoint */ class SIOClient - : public cocos2d::Ref + : public cocos2d::Ref { private: - int _port; - std::string _host, _path, _tag; - bool _connected; - SIOClientImpl* _socket; + int _port; + std::string _host, _path, _tag; + bool _connected; + SIOClientImpl* _socket; - SocketIO::SIODelegate* _delegate; + SocketIO::SIODelegate* _delegate; - EventRegistry _eventRegistry; + EventRegistry _eventRegistry; - void fireEvent(const std::string& eventName, const std::string& data); + void fireEvent(const std::string& eventName, const std::string& data); - void onOpen(); - void onConnect(); - void receivedDisconnect(); + void onOpen(); + void onConnect(); + void receivedDisconnect(); - friend class SIOClientImpl; + friend class SIOClientImpl; public: - SIOClient(const std::string& host, int port, const std::string& path, SIOClientImpl* impl, SocketIO::SIODelegate& delegate); - virtual ~SIOClient(void); + SIOClient(const std::string& host, int port, const std::string& path, SIOClientImpl* impl, SocketIO::SIODelegate& delegate); + virtual ~SIOClient(void); - /** + /** * @brief Returns the delegate for the client */ - SocketIO::SIODelegate* getDelegate() { return _delegate; }; + SocketIO::SIODelegate* getDelegate() { return _delegate; }; - /** + /** * @brief Disconnect from the endpoint, onClose will be called on the delegate when comlpete */ - void disconnect(); - /** + void disconnect(); + /** * @brief Send a message to the socket.io server */ - void send(std::string s); - /** + void send(std::string s); + /** * @brief The delegate class to process socket.io events */ - void emit(std::string eventname, std::string args); - /** + void emit(std::string eventname, std::string args); + /** * @brief Used to resgister a socket.io event callback - * Event argument should be passed using CC_CALLBACK2(&Base::function, this) + * Event argument should be passed using CC_CALLBACK2(&Base::function, this) */ - void on(const std::string& eventName, SIOEvent e); - - inline void setTag(const char* tag) + void on(const std::string& eventName, SIOEvent e); + + inline void setTag(const char* tag) { _tag = tag; }; - - inline const char* getTag() + + inline const char* getTag() { return _tag.c_str(); }; diff --git a/cocos/network/WebSocket.h b/cocos/network/WebSocket.h index 3d4e9bf737..afd34721ea 100644 --- a/cocos/network/WebSocket.h +++ b/cocos/network/WebSocket.h @@ -1,19 +1,19 @@ /**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies Inc. - + http://www.cocos2d-x.org - + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -59,7 +59,7 @@ public: * @lua NA */ virtual ~WebSocket(); - + /** * @brief Data structure for message */ @@ -70,7 +70,7 @@ public: ssize_t len, issued; bool isBinary; }; - + /** * @brief Errors in websocket */ @@ -80,7 +80,7 @@ public: CONNECTION_FAILURE, UNKNOWN, }; - + /** * Websocket state */ @@ -104,8 +104,8 @@ public: virtual void onClose(WebSocket* ws) = 0; virtual void onError(WebSocket* ws, const ErrorCode& error) = 0; }; - - + + /** * @brief The initialized method for websocket. * It needs to be invoked right after websocket instance is allocated. @@ -116,53 +116,53 @@ public: bool init(const Delegate& delegate, const std::string& url, const std::vector* protocols = nullptr); - + /** * @brief Sends string data to websocket server. */ void send(const std::string& message); - + /** * @brief Sends binary data to websocket server. */ void send(const unsigned char* binaryMsg, unsigned int len); - + /** * @brief Closes the connection to server. */ void close(); - + /** * @brief Gets current state of connection. */ State getReadyState(); - + private: virtual void onSubThreadStarted(); virtual int onSubThreadLoop(); virtual void onSubThreadEnded(); virtual void onUIThreadReceiveMessage(WsMessage* msg); - + friend class WebSocketCallbackWrapper; int onSocketCallback(struct libwebsocket_context *ctx, struct libwebsocket *wsi, int reason, void *user, void *in, ssize_t len); - + private: - State _readyState; + State _readyState; std::string _host; unsigned int _port; std::string _path; - + ssize_t _pendingFrameDataLen; ssize_t _currentDataLen; char *_currentData; friend class WsThreadHelper; WsThreadHelper* _wsHelper; - + struct libwebsocket* _wsInstance; struct libwebsocket_context* _wsContext; Delegate* _delegate; diff --git a/extensions/GUI/CCScrollView/CCScrollView.cpp b/extensions/GUI/CCScrollView/CCScrollView.cpp index ef943f9228..afaac3ee2d 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.cpp +++ b/extensions/GUI/CCScrollView/CCScrollView.cpp @@ -238,7 +238,7 @@ void ScrollView::setContentOffsetInDuration(Point offset, float dt) scroll = MoveTo::create(dt, offset); expire = CallFuncN::create(CC_CALLBACK_1(ScrollView::stoppedAnimatedScroll,this)); - _container->runAction(Sequence::create(scroll, expire, NULL)); + _container->runAction(Sequence::create(scroll, expire, nullptr)); this->schedule(schedule_selector(ScrollView::performedAnimatedScroll)); } diff --git a/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp b/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp index 6601a3214b..fbf786ec22 100644 --- a/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp +++ b/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp @@ -517,9 +517,9 @@ void ActionRotateBy3D::onEnter() auto actionBy2 = RotateBy::create(4, Vertex3F(0, 360, 0)); auto actionBy3 = RotateBy::create(4 ,Vertex3F(0, 0, 360)); - _tamara->runAction( Sequence::create(actionBy1, actionBy1->reverse(), NULL)); - _grossini->runAction( Sequence::create(actionBy2, actionBy2->reverse(), NULL)); - _kathia->runAction( Sequence::create(actionBy3, actionBy3->reverse(), NULL)); + _tamara->runAction( Sequence::create(actionBy1, actionBy1->reverse(), nullptr)); + _grossini->runAction( Sequence::create(actionBy2, actionBy2->reverse(), nullptr)); + _kathia->runAction( Sequence::create(actionBy3, actionBy3->reverse(), nullptr)); } std::string ActionRotateBy3D::subtitle() const @@ -1287,19 +1287,19 @@ void ActionOrbit::onEnter() auto action1 = Sequence::create( orbit1, orbit1->reverse(), - NULL); + nullptr); auto orbit2 = OrbitCamera::create(2,1, 0, 0, 180, -45, 0); auto action2 = Sequence::create( orbit2, orbit2->reverse(), - NULL); + nullptr); auto orbit3 = OrbitCamera::create(2,1, 0, 0, 180, 90, 0); auto action3 = Sequence::create( orbit3, orbit3->reverse(), - NULL); + nullptr); _kathia->runAction(RepeatForever::create(action1)); _tamara->runAction(RepeatForever::create(action2)); diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index 12d13de41e..e1043b8dc5 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -179,7 +179,7 @@ void ArmatureTestLayer::onEnter() restartItem = MenuItemImage::create(s_pathR1, s_pathR2, CC_CALLBACK_1(ArmatureTestLayer::restartCallback, this) ); nextItem = MenuItemImage::create(s_pathF1, s_pathF2, CC_CALLBACK_1(ArmatureTestLayer::nextCallback, this) ); - Menu *menu = Menu::create(backItem, restartItem, nextItem, NULL); + Menu *menu = Menu::create(backItem, restartItem, nextItem, nullptr); menu->setPosition(Point::ZERO); backItem->setPosition(Point(VisibleRect::center().x - restartItem->getContentSize().width * 2, VisibleRect::bottom().y + restartItem->getContentSize().height / 2)); @@ -371,7 +371,7 @@ void TestPerformance::onEnter() MenuItemFont *increase = MenuItemFont::create(" + ", CC_CALLBACK_1(TestPerformance::onIncrease, this)); increase->setColor(Color3B(0,200,20)); - Menu *menu = Menu::create(decrease, increase, NULL); + Menu *menu = Menu::create(decrease, increase, nullptr); menu->alignItemsHorizontally(); menu->setPosition(Point(VisibleRect::getVisibleRect().size.width/2, VisibleRect::getVisibleRect().size.height-100)); addChild(menu, 10000); @@ -540,14 +540,14 @@ void TestAnimationEvent::animationEvent(Armature *armature, MovementEventType mo { ActionInterval *actionToRight = MoveTo::create(2, Point(VisibleRect::right().x - 50, VisibleRect::right().y)); armature->stopAllActions(); - armature->runAction(Sequence::create(actionToRight, CallFunc::create( CC_CALLBACK_0(TestAnimationEvent::callback1, this)), NULL)); + armature->runAction(Sequence::create(actionToRight, CallFunc::create( CC_CALLBACK_0(TestAnimationEvent::callback1, this)), nullptr)); armature->getAnimation()->play("Walk"); } else if (movementID == "FireMax") { ActionInterval *actionToLeft = MoveTo::create(2, Point(VisibleRect::left().x + 50, VisibleRect::left().y)); armature->stopAllActions(); - armature->runAction(Sequence::create(actionToLeft, CallFunc::create( CC_CALLBACK_0(TestAnimationEvent::callback2, this)), NULL)); + armature->runAction(Sequence::create(actionToLeft, CallFunc::create( CC_CALLBACK_0(TestAnimationEvent::callback2, this)), nullptr)); armature->getAnimation()->play("Walk"); } } @@ -1278,7 +1278,7 @@ void TestArmatureNesting2::onEnter() LabelTTF* label = CCLabelTTF::create("Change Mount", "Arial", 20); MenuItemLabel* pMenuItem = CCMenuItemLabel::create(label, CC_CALLBACK_1(TestArmatureNesting2::changeMountCallback, this)); - Menu* pMenu =Menu::create(pMenuItem, NULL); + Menu* pMenu =Menu::create(pMenuItem, nullptr); pMenu->setPosition( Point() ); pMenuItem->setPosition( Point( VisibleRect::right().x - 67, VisibleRect::bottom().y + 50) ); @@ -1330,7 +1330,7 @@ void TestArmatureNesting2::onTouchesEnded(const std::vector& touches, Ev ActionInterval *move = CCMoveTo::create(2, point); armature->stopAllActions(); - armature->runAction(Sequence::create(move, NULL)); + armature->runAction(Sequence::create(move, nullptr)); } void TestArmatureNesting2::changeMountCallback(Ref* pSender) diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp index 7816913985..3f844b265c 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp @@ -89,7 +89,7 @@ cocos2d::Node* ComponentsTestLayer::createGameScene() itemBack->setColor(Color3B(0, 0, 0)); itemBack->setPosition(Point(VisibleRect::rightBottom().x - 50, VisibleRect::rightBottom().y + 25)); - auto menuBack = Menu::create(itemBack, NULL); + auto menuBack = Menu::create(itemBack, nullptr); menuBack->setPosition(Point::ZERO); addChild(menuBack); diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp index 2338e13b77..c866ff4cdd 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp @@ -48,7 +48,7 @@ void EnemyController::onEnter() FiniteTimeAction* actionMoveDone = CallFuncN::create( CC_CALLBACK_1(SceneController::spriteMoveFinished, static_cast( getOwner()->getParent()->getComponent("SceneController") ))); - _owner->runAction( Sequence::create(actionMove, actionMoveDone, NULL) ); + _owner->runAction( Sequence::create(actionMove, actionMoveDone, nullptr) ); } void EnemyController::onExit() diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.cpp index f6e8b495e2..d9f9960045 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.cpp @@ -69,7 +69,7 @@ bool GameOverLayer::init() this->runAction( Sequence::create( DelayTime::create(3), CallFunc::create(CC_CALLBACK_0(GameOverLayer::gameOverDone, this)), - NULL)); + nullptr)); auto itemBack = MenuItemFont::create("Back", [](Ref* sender){ @@ -80,7 +80,7 @@ bool GameOverLayer::init() itemBack->setColor(Color3B(0, 0, 0)); itemBack->setPosition(Point(VisibleRect::rightBottom().x - 50, VisibleRect::rightBottom().y + 25)); - auto menuBack = Menu::create(itemBack, NULL); + auto menuBack = Menu::create(itemBack, nullptr); menuBack->setPosition(Point::ZERO); addChild(menuBack); diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/GUIEditorTest.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/GUIEditorTest.cpp index da2f82c47b..1cc279395e 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/GUIEditorTest.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/GUIEditorTest.cpp @@ -337,8 +337,8 @@ void GUIEditorTestScene::onEnter() auto pMenuItem = MenuItemLabel::create(label, CC_CALLBACK_1(GUIEditorTestScene::BackCallback, this)); - Menu* pMenu =CCMenu::create(pMenuItem, NULL); - + Menu* pMenu =CCMenu::create(pMenuItem, nullptr); + pMenu->setPosition( Point::ZERO ); pMenuItem->setPosition( Point( VisibleRect::right().x - 50, VisibleRect::bottom().y + 25) ); diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp index 103c568ce5..e8f947004e 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp @@ -134,7 +134,7 @@ void SceneEditorTestLayer::onEnter() nextItem = MenuItemImage::create(s_pathF1, s_pathF2, CC_CALLBACK_1(SceneEditorTestLayer::nextCallback, this) ); - Menu *menu = Menu::create(backItem, restartItem, nextItem, NULL); + Menu *menu = Menu::create(backItem, restartItem, nextItem, nullptr); float fScale = 0.5f; @@ -473,9 +473,9 @@ cocos2d::Node* TmxMapComponentTest::createGameScene() ActionInterval *rotateToBack = RotateTo::create(2, 0); ActionInterval *actionToBack = SkewTo::create(2, 0, 0); - tmxMap->getNode()->runAction(Sequence::create(actionTo, actionToBack, NULL)); - tmxMap->getNode()->runAction(Sequence::create(rotateTo, rotateToBack, NULL)); - tmxMap->getNode()->runAction(Sequence::create(actionScaleTo, actionScaleToBack, NULL)); + tmxMap->getNode()->runAction(Sequence::create(actionTo, actionToBack, nullptr)); + tmxMap->getNode()->runAction(Sequence::create(rotateTo, rotateToBack, nullptr)); + tmxMap->getNode()->runAction(Sequence::create(actionScaleTo, actionScaleToBack, nullptr)); return node; } @@ -523,7 +523,7 @@ cocos2d::Node* ParticleComponentTest::createGameScene() ComRender* Particle = static_cast(node->getChildByTag(10020)->getComponent("CCParticleSystemQuad")); ActionInterval* jump = JumpBy::create(5, Point(-500,0), 50, 4); - FiniteTimeAction* action = Sequence::create( jump, jump->reverse(), NULL); + FiniteTimeAction* action = Sequence::create( jump, jump->reverse(), nullptr); Particle->getNode()->runAction(action); return node; } diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.cpp index dbc0a8ae0e..4449d2cd9d 100755 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.cpp @@ -161,7 +161,7 @@ void TMoveBy::done() if (_reverse == true) { ActionInterval* actionByBack = actionBy->reverse(); - node->runAction( CCSequence::create(actionBy, actionByBack, NULL)); + node->runAction( CCSequence::create(actionBy, actionByBack, nullptr)); } else { @@ -304,7 +304,7 @@ void TRotateBy::done() if (_reverse == true) { ActionInterval* actionByBack = actionBy->reverse(); - node->runAction( Sequence::create(actionBy, actionByBack, NULL)); + node->runAction( Sequence::create(actionBy, actionByBack, nullptr)); } else { @@ -445,7 +445,7 @@ void TScaleBy::done() if (_reverse == true) { ActionInterval* actionByBack = actionBy->reverse(); - node->runAction(Sequence::create(actionBy, actionByBack, NULL)); + node->runAction(Sequence::create(actionBy, actionByBack, nullptr)); } else { @@ -591,7 +591,7 @@ void TSkewBy::done() if (_reverse == true) { ActionInterval* actionByBack = actionBy->reverse(); - node->runAction(Sequence::create(actionBy, actionByBack, NULL)); + node->runAction(Sequence::create(actionBy, actionByBack, nullptr)); } else { diff --git a/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp b/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp index aad6a21d87..01b5cb1335 100644 --- a/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp +++ b/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp @@ -1275,7 +1275,7 @@ LabelTTFDistanceField::LabelTTFDistanceField() DelayTime::create(1.0f), ScaleTo::create(6.0f,5.0f,5.0f), ScaleTo::create(6.0f,1.0f,1.0f), - NULL); + nullptr); label1->runAction(RepeatForever::create(action)); auto label2 = Label::createWithTTF(ttfConfig,"Distance Field",TextHAlignment::CENTER,size.width); diff --git a/tests/cpp-tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp b/tests/cpp-tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp index 80fa5c04b4..9852b62323 100644 --- a/tests/cpp-tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp +++ b/tests/cpp-tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp @@ -206,7 +206,7 @@ void TouchableSpriteTest::onEnter() removeAllTouchItem->setFontSizeObj(16); removeAllTouchItem->setPosition(VisibleRect::right() + Point(-100, 0)); - auto menu = Menu::create(removeAllTouchItem, NULL); + auto menu = Menu::create(removeAllTouchItem, nullptr); menu->setPosition(Point(0, 0)); menu->setAnchorPoint(Point(0, 0)); addChild(menu); @@ -402,7 +402,7 @@ void RemoveListenerWhenDispatching::onEnter() }, MenuItemFont::create("Enabled"), MenuItemFont::create("Disabled"), NULL); toggleItem->setPosition(origin + Point(size.width/2, 80)); - auto menu = Menu::create(toggleItem, NULL); + auto menu = Menu::create(toggleItem, nullptr); menu->setPosition(Point(0, 0)); menu->setAnchorPoint(Point(0, 0)); addChild(menu, -1); @@ -480,7 +480,7 @@ void CustomEventTest::onEnter() }); sendItem2->setPosition(origin + Point(size.width/2, size.height/2 - 40)); - auto menu = Menu::create(sendItem, sendItem2, NULL); + auto menu = Menu::create(sendItem, sendItem2, nullptr); menu->setPosition(Point(0, 0)); menu->setAnchorPoint(Point(0, 0)); addChild(menu, -1); @@ -656,7 +656,7 @@ void RemoveAndRetainNodeTest::onEnter() this->addChild(_sprite); _sprite->release(); }), - NULL + nullptr )); } @@ -703,7 +703,7 @@ void RemoveListenerAfterAddingTest::onEnter() }); next->setPosition(VisibleRect::center() + Point(0, -40)); - auto menu = Menu::create(next, NULL); + auto menu = Menu::create(next, nullptr); menu->setPosition(VisibleRect::leftBottom()); menu->setAnchorPoint(Point::ZERO); this->addChild(menu); @@ -739,7 +739,7 @@ void RemoveListenerAfterAddingTest::onEnter() item3->setPosition(VisibleRect::center()); - auto menu = Menu::create(item1, item2, item3, NULL); + auto menu = Menu::create(item1, item2, item3, nullptr); menu->setPosition(VisibleRect::leftBottom()); menu->setAnchorPoint(Point::ZERO); @@ -1149,7 +1149,7 @@ PauseResumeTargetTest::PauseResumeTargetTest() popup->setAnchorPoint(Point::ANCHOR_MIDDLE_RIGHT); popup->setPosition(VisibleRect::right()); - auto menu = Menu::create(popup, NULL); + auto menu = Menu::create(popup, nullptr); menu->setAnchorPoint(Point::ANCHOR_BOTTOM_LEFT); menu->setPosition(Point::ZERO); @@ -1214,7 +1214,7 @@ Issue4129::Issue4129() removeAllTouchItem->setFontSizeObj(16); removeAllTouchItem->setPosition(VisibleRect::right() + Point(-100, 0)); - auto menu = Menu::create(removeAllTouchItem, NULL); + auto menu = Menu::create(removeAllTouchItem, nullptr); menu->setPosition(Point(0, 0)); menu->setAnchorPoint(Point(0, 0)); addChild(menu); diff --git a/tests/cpp-tests/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id b/tests/cpp-tests/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id index 16313475b7..b98c1b9d46 100644 --- a/tests/cpp-tests/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id +++ b/tests/cpp-tests/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id @@ -1 +1 @@ -6b26ef0158192c2d538b79758cda7ee7233a2f89 \ No newline at end of file +4bb0b2a6151e4910ea662bedd91a5be655ec05d1 \ No newline at end of file From 859fe98502f07aca11aaebf1316e048c9df60357 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Tue, 25 Mar 2014 09:58:16 +0800 Subject: [PATCH 046/106] label:1.change default value of anchor point. 2.Shadow offset and outline size passed to new Label didn't consider 'contentScaleFactor' --- cocos/2d/CCFontAtlasCache.cpp | 7 +++++-- cocos/2d/CCLabel.cpp | 1 + cocos/2d/CCLabelBMFont.cpp | 5 ++--- cocos/2d/CCLabelTTF.cpp | 1 + cocos/2d/CCMenuItem.cpp | 5 +++-- 5 files changed, 12 insertions(+), 7 deletions(-) diff --git a/cocos/2d/CCFontAtlasCache.cpp b/cocos/2d/CCFontAtlasCache.cpp index 119332d009..c2679e464d 100644 --- a/cocos/2d/CCFontAtlasCache.cpp +++ b/cocos/2d/CCFontAtlasCache.cpp @@ -52,9 +52,11 @@ FontAtlas * FontAtlasCache::getFontAtlasTTF(const TTFConfig & config) useDistanceField = false; } int fontSize = config.fontSize; + auto contentScaleFactor = CC_CONTENT_SCALE_FACTOR(); + if (useDistanceField) { - fontSize = Label::DistanceFieldFontSize / CC_CONTENT_SCALE_FACTOR(); + fontSize = Label::DistanceFieldFontSize / contentScaleFactor; } std::string atlasName = generateFontName(config.fontFilePath, fontSize, GlyphCollection::DYNAMIC, useDistanceField); @@ -67,7 +69,8 @@ FontAtlas * FontAtlasCache::getFontAtlasTTF(const TTFConfig & config) if ( !tempAtlas ) { - FontFreeType *font = FontFreeType::create(config.fontFilePath, fontSize * CC_CONTENT_SCALE_FACTOR(), config.glyphs, config.customGlyphs,useDistanceField,config.outlineSize); + FontFreeType *font = FontFreeType::create(config.fontFilePath, fontSize * contentScaleFactor, config.glyphs, + config.customGlyphs,useDistanceField,config.outlineSize * contentScaleFactor); if (font) { tempAtlas = font->createFontAtlas(); diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index 3d6bc68508..3be117654e 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -279,6 +279,7 @@ Label::Label(FontAtlas *atlas /* = nullptr */, TextHAlignment hAlignment /* = Te , _textSprite(nullptr) , _contentDirty(false) { + setAnchorPoint(Point::ANCHOR_MIDDLE); reset(); #if CC_ENABLE_CACHE_TEXTURE_DATA diff --git a/cocos/2d/CCLabelBMFont.cpp b/cocos/2d/CCLabelBMFont.cpp index 2df1f9e6ff..948087d0a3 100644 --- a/cocos/2d/CCLabelBMFont.cpp +++ b/cocos/2d/CCLabelBMFont.cpp @@ -43,7 +43,7 @@ NS_CC_BEGIN LabelBMFont * LabelBMFont::create() { LabelBMFont * pRet = new LabelBMFont(); - if (pRet && pRet->init()) + if (pRet) { pRet->autorelease(); return pRet; @@ -72,8 +72,6 @@ bool LabelBMFont::initWithString(const std::string& str, const std::string& fntF _fntFile = fntFile; _label->setMaxLineWidth(width); _label->setAlignment(alignment); - _label->setAnchorPoint(Point::ANCHOR_BOTTOM_LEFT); - _label->setPosition(Point::ZERO); _label->setString(str); this->setContentSize(_label->getContentSize()); return true; @@ -85,6 +83,7 @@ bool LabelBMFont::initWithString(const std::string& str, const std::string& fntF LabelBMFont::LabelBMFont() { _label = Label::create(); + _label->setAnchorPoint(Point::ANCHOR_BOTTOM_LEFT); this->addChild(_label); this->setAnchorPoint(Point::ANCHOR_MIDDLE); _cascadeOpacityEnabled = true; diff --git a/cocos/2d/CCLabelTTF.cpp b/cocos/2d/CCLabelTTF.cpp index 862c283fea..bf8071f56d 100644 --- a/cocos/2d/CCLabelTTF.cpp +++ b/cocos/2d/CCLabelTTF.cpp @@ -32,6 +32,7 @@ NS_CC_BEGIN LabelTTF::LabelTTF() { _renderLabel = Label::create(); + _renderLabel->setAnchorPoint(Point::ANCHOR_BOTTOM_LEFT); this->addChild(_renderLabel); this->setAnchorPoint(Point::ANCHOR_MIDDLE); diff --git a/cocos/2d/CCMenuItem.cpp b/cocos/2d/CCMenuItem.cpp index cfcee2e726..42b1c42159 100644 --- a/cocos/2d/CCMenuItem.cpp +++ b/cocos/2d/CCMenuItem.cpp @@ -178,9 +178,10 @@ void MenuItemLabel::setLabel(Node* var) { if (var) { + var->setAnchorPoint(Point::ANCHOR_BOTTOM_LEFT); + var->setPosition(Point::ZERO); + setContentSize(var->getContentSize()); addChild(var); - var->setAnchorPoint(Point(0, 0)); - setContentSize(var->getContentSize()); } if (_label) From 8278a510aa112f2db84b53788d750b0f4d326851 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Tue, 25 Mar 2014 10:41:53 +0800 Subject: [PATCH 047/106] Label:fixed shadow offset didn't consider 'contentScaleFactor' --- cocos/2d/CCLabel.cpp | 6 ++++-- cocos/2d/CCMenuItem.cpp | 1 - 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index 3be117654e..55220b4df4 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -837,14 +837,16 @@ void Label::enableShadow(const Color4B& shadowColor /* = Color4B::BLACK */,const _effectColorF.g = _effectColor.g / 255.0f; _effectColorF.b = _effectColor.b / 255.0f; _effectColorF.a = _effectColor.a / 255.0f; - _shadowOffset = offset; + auto contentScaleFactor = CC_CONTENT_SCALE_FACTOR(); + _shadowOffset.width = offset.width * contentScaleFactor; + _shadowOffset.height = offset.height * contentScaleFactor; //todo:support blur for shadow _shadowBlurRadius = 0; _currLabelEffect = LabelEffect::SHADOW; _fontDefinition._shadow._shadowEnabled = true; _fontDefinition._shadow._shadowBlur = blurRadius; - _fontDefinition._shadow._shadowOffset = offset; + _fontDefinition._shadow._shadowOffset = _shadowOffset; _fontDefinition._shadow._shadowOpacity = shadowColor.a / 255.0f; _contentDirty = true; diff --git a/cocos/2d/CCMenuItem.cpp b/cocos/2d/CCMenuItem.cpp index 42b1c42159..3615905f6b 100644 --- a/cocos/2d/CCMenuItem.cpp +++ b/cocos/2d/CCMenuItem.cpp @@ -179,7 +179,6 @@ void MenuItemLabel::setLabel(Node* var) if (var) { var->setAnchorPoint(Point::ANCHOR_BOTTOM_LEFT); - var->setPosition(Point::ZERO); setContentSize(var->getContentSize()); addChild(var); } From 3a0ee65a7ebfdf369ec01890c2f1db9a4f251b70 Mon Sep 17 00:00:00 2001 From: mine_masahiro Date: Tue, 25 Mar 2014 11:44:26 +0900 Subject: [PATCH 048/106] Fix ActionObject memory leak bug --- cocos/editor-support/cocostudio/CCActionManagerEx.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos/editor-support/cocostudio/CCActionManagerEx.cpp b/cocos/editor-support/cocostudio/CCActionManagerEx.cpp index 5d298b81aa..03617ca26a 100644 --- a/cocos/editor-support/cocostudio/CCActionManagerEx.cpp +++ b/cocos/editor-support/cocostudio/CCActionManagerEx.cpp @@ -63,6 +63,7 @@ void ActionManagerEx::initWithDictionary(const char* jsonName,const rapidjson::V int actionCount = DICTOOL->getArrayCount_json(dic, "actionlist"); for (int i=0; iautorelease(); const rapidjson::Value &actionDic = DICTOOL->getDictionaryFromArray_json(dic, "actionlist", i); action->initWithDictionary(actionDic,root); actionList.pushBack(action); From 3fba61f384c9ad2fea47212c54bb70fbf015a459 Mon Sep 17 00:00:00 2001 From: Kazuki Sakamoto Date: Mon, 24 Mar 2014 19:57:29 -0700 Subject: [PATCH 049/106] Remove NativeActivity --- cocos/2d/platform/android/Android.mk | 10 +- cocos/2d/platform/android/CCDevice.cpp | 2 +- .../cocos2dx/lib/Cocos2dxAccelerometer.java | 144 ++++ .../org/cocos2dx/lib/Cocos2dxActivity.java | 193 +++++ .../org/cocos2dx/lib/Cocos2dxETCLoader.java | 109 +++ .../org/cocos2dx/lib/Cocos2dxEditText.java | 195 +---- .../cocos2dx/lib/Cocos2dxGLSurfaceView.java | 370 +++++++++ .../src/org/cocos2dx/lib/Cocos2dxHandler.java | 135 ++++ .../src/org/cocos2dx/lib/Cocos2dxHelper.java | 135 ++-- .../cocos2dx/lib/Cocos2dxLocalStorage.java | 4 +- .../org/cocos2dx/lib/Cocos2dxRenderer.java | 171 ++++ .../cocos2dx/lib/Cocos2dxTextInputWraper.java | 168 ++++ cocos/2d/platform/android/javaactivity.cpp | 82 ++ cocos/2d/platform/android/jni/IMEJni.cpp | 24 +- ...org_cocos2dx_lib_Cocos2dxAccelerometer.cpp | 22 + .../Java_org_cocos2dx_lib_Cocos2dxHelper.cpp | 53 ++ .../Java_org_cocos2dx_lib_Cocos2dxHelper.h | 3 + ...Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp | 46 ++ cocos/2d/platform/android/jni/JniHelper.cpp | 49 +- cocos/2d/platform/android/jni/JniHelper.h | 6 +- cocos/2d/platform/android/jni/TouchesJni.cpp | 93 +++ cocos/2d/platform/android/nativeactivity.cpp | 765 ------------------ .../proj.android/AndroidManifest.xml | 12 +- .../cpp-empty-test/proj.android/jni/main.cpp | 2 +- .../cocos2dx/cpp_empty_test/AppActivity.java | 21 +- .../cpp_empty_test/Cocos2dxActivity.java | 32 - .../proj.android/AndroidManifest.xml | 12 +- tests/cpp-tests/proj.android/jni/main.cpp | 2 +- .../org/cocos2dx/cpp_tests/AppActivity.java | 29 + .../cocos2dx/cpp_tests/Cocos2dxActivity.java | 32 - 30 files changed, 1739 insertions(+), 1182 deletions(-) create mode 100644 cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxAccelerometer.java create mode 100644 cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java create mode 100644 cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxETCLoader.java create mode 100644 cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java create mode 100644 cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHandler.java create mode 100644 cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxRenderer.java create mode 100644 cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxTextInputWraper.java create mode 100644 cocos/2d/platform/android/javaactivity.cpp create mode 100644 cocos/2d/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxAccelerometer.cpp create mode 100644 cocos/2d/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp create mode 100644 cocos/2d/platform/android/jni/TouchesJni.cpp delete mode 100644 cocos/2d/platform/android/nativeactivity.cpp rename cocos/2d/platform/android/nativeactivity.h => tests/cpp-empty-test/proj.android/src/org/cocos2dx/cpp_empty_test/AppActivity.java (71%) delete mode 100644 tests/cpp-empty-test/proj.android/src/org/cocos2dx/cpp_empty_test/Cocos2dxActivity.java create mode 100644 tests/cpp-tests/proj.android/src/org/cocos2dx/cpp_tests/AppActivity.java delete mode 100644 tests/cpp-tests/proj.android/src/org/cocos2dx/cpp_tests/Cocos2dxActivity.java diff --git a/cocos/2d/platform/android/Android.mk b/cocos/2d/platform/android/Android.mk index 1c57245387..0dc5a9cb13 100644 --- a/cocos/2d/platform/android/Android.mk +++ b/cocos/2d/platform/android/Android.mk @@ -12,12 +12,15 @@ CCCommon.cpp \ CCDevice.cpp \ CCGLView.cpp \ CCFileUtilsAndroid.cpp \ -nativeactivity.cpp \ +javaactivity.cpp \ jni/DPIJni.cpp \ jni/IMEJni.cpp \ +jni/Java_org_cocos2dx_lib_Cocos2dxAccelerometer.cpp \ jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp \ jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp \ -jni/JniHelper.cpp +jni/Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp \ +jni/JniHelper.cpp \ +jni/TouchesJni.cpp LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) @@ -41,7 +44,7 @@ LOCAL_EXPORT_LDLIBS := -lGLESv1_CM \ -lz \ -landroid -LOCAL_WHOLE_STATIC_LIBRARIES := android_native_app_glue cocos_png_static cocos_jpeg_static cocos_tiff_static cocos_webp_static +LOCAL_WHOLE_STATIC_LIBRARIES := cocos_png_static cocos_jpeg_static cocos_tiff_static cocos_webp_static include $(BUILD_STATIC_LIBRARY) @@ -50,4 +53,3 @@ $(call import-module,jpeg/prebuilt/android) $(call import-module,png/prebuilt/android) $(call import-module,tiff/prebuilt/android) $(call import-module,webp/prebuilt/android) -$(call import-module,android/native_app_glue) diff --git a/cocos/2d/platform/android/CCDevice.cpp b/cocos/2d/platform/android/CCDevice.cpp index b311c8cc8e..f58c71dc30 100644 --- a/cocos/2d/platform/android/CCDevice.cpp +++ b/cocos/2d/platform/android/CCDevice.cpp @@ -32,8 +32,8 @@ THE SOFTWARE. #include #include "ccTypes.h" #include "jni/DPIJni.h" +#include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h" #include "jni/JniHelper.h" -#include "nativeactivity.h" #include "platform/CCFileUtils.h" NS_CC_BEGIN diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxAccelerometer.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxAccelerometer.java new file mode 100644 index 0000000000..3447242c8a --- /dev/null +++ b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxAccelerometer.java @@ -0,0 +1,144 @@ +/**************************************************************************** +Copyright (c) 2010-2011 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. + ****************************************************************************/ +package org.cocos2dx.lib; + +import android.content.Context; +import android.content.res.Configuration; +import android.hardware.Sensor; +import android.hardware.SensorEvent; +import android.hardware.SensorEventListener; +import android.hardware.SensorManager; +import android.util.Log; +import android.view.Display; +import android.view.Surface; +import android.view.WindowManager; +import android.os.Build.*; + +public class Cocos2dxAccelerometer implements SensorEventListener { + // =========================================================== + // Constants + // =========================================================== + + private static final String TAG = Cocos2dxAccelerometer.class.getSimpleName(); + + // =========================================================== + // Fields + // =========================================================== + + private final Context mContext; + private final SensorManager mSensorManager; + private final Sensor mAccelerometer; + private final int mNaturalOrientation; + + // =========================================================== + // Constructors + // =========================================================== + + public Cocos2dxAccelerometer(final Context pContext) { + this.mContext = pContext; + + this.mSensorManager = (SensorManager) this.mContext.getSystemService(Context.SENSOR_SERVICE); + this.mAccelerometer = this.mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); + + final Display display = ((WindowManager) this.mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); + this.mNaturalOrientation = display.getOrientation(); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + public void enable() { + this.mSensorManager.registerListener(this, this.mAccelerometer, SensorManager.SENSOR_DELAY_GAME); + } + + public void setInterval(float interval) { + // Honeycomb version is 11 + if(android.os.Build.VERSION.SDK_INT < 11) { + this.mSensorManager.registerListener(this, this.mAccelerometer, SensorManager.SENSOR_DELAY_GAME); + } else { + //convert seconds to microseconds + this.mSensorManager.registerListener(this, this.mAccelerometer, (int)(interval*100000)); + } + } + + public void disable() { + this.mSensorManager.unregisterListener(this); + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void onSensorChanged(final SensorEvent pSensorEvent) { + if (pSensorEvent.sensor.getType() != Sensor.TYPE_ACCELEROMETER) { + return; + } + + float x = pSensorEvent.values[0]; + float y = pSensorEvent.values[1]; + final float z = pSensorEvent.values[2]; + + /* + * Because the axes are not swapped when the device's screen orientation + * changes. So we should swap it here. In tablets such as Motorola Xoom, + * the default orientation is landscape, so should consider this. + */ + final int orientation = this.mContext.getResources().getConfiguration().orientation; + + if ((orientation == Configuration.ORIENTATION_LANDSCAPE) && (this.mNaturalOrientation != Surface.ROTATION_0)) { + final float tmp = x; + x = -y; + y = tmp; + } else if ((orientation == Configuration.ORIENTATION_PORTRAIT) && (this.mNaturalOrientation != Surface.ROTATION_0)) { + final float tmp = x; + x = y; + y = -tmp; + } + + Cocos2dxGLSurfaceView.queueAccelerometer(x,y,z,pSensorEvent.timestamp); + + /* + if(BuildConfig.DEBUG) { + Log.d(TAG, "x = " + pSensorEvent.values[0] + " y = " + pSensorEvent.values[1] + " z = " + pSensorEvent.values[2]); + } + */ + } + + @Override + public void onAccuracyChanged(final Sensor pSensor, final int pAccuracy) { + } + + // =========================================================== + // Methods + // Native method called from Cocos2dxGLSurfaceView (To be in the same thread) + // =========================================================== + + public static native void onSensorChanged(final float pX, final float pY, final float pZ, final long pTimestamp); + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java new file mode 100644 index 0000000000..445fe2875d --- /dev/null +++ b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java @@ -0,0 +1,193 @@ +/**************************************************************************** +Copyright (c) 2010-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. + ****************************************************************************/ +package org.cocos2dx.lib; + +import org.cocos2dx.lib.Cocos2dxHelper.Cocos2dxHelperListener; + +import android.app.Activity; +import android.content.Context; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; +import android.os.Build; +import android.os.Bundle; +import android.os.Message; +import android.view.ViewGroup; +import android.util.Log; +import android.widget.FrameLayout; + +import java.io.File; + +public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelperListener { + // =========================================================== + // Constants + // =========================================================== + + private static final String TAG = Cocos2dxActivity.class.getSimpleName(); + + // =========================================================== + // Fields + // =========================================================== + + private Cocos2dxGLSurfaceView mGLSurfaceView; + private Cocos2dxHandler mHandler; + private static Context sContext = null; + + public static Context getContext() { + return sContext; + } + + // =========================================================== + // Constructors + // =========================================================== + + @Override + protected void onCreate(final Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + try { + ApplicationInfo ai = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA); + Bundle bundle = ai.metaData; + try { + String libName = bundle.getString("android.app.lib_name"); + System.loadLibrary(libName); + } catch (Exception e) { + // ERROR + } + } catch (PackageManager.NameNotFoundException e) { + // ERROR + } + + sContext = this; + this.mHandler = new Cocos2dxHandler(this); + + this.init(); + + Cocos2dxHelper.init(this); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + protected void onResume() { + super.onResume(); + + Cocos2dxHelper.onResume(); + this.mGLSurfaceView.onResume(); + } + + @Override + protected void onPause() { + super.onPause(); + + Cocos2dxHelper.onPause(); + this.mGLSurfaceView.onPause(); + } + + @Override + public void showDialog(final String pTitle, final String pMessage) { + Message msg = new Message(); + msg.what = Cocos2dxHandler.HANDLER_SHOW_DIALOG; + msg.obj = new Cocos2dxHandler.DialogMessage(pTitle, pMessage); + this.mHandler.sendMessage(msg); + } + + @Override + public void showEditTextDialog(final String pTitle, final String pContent, final int pInputMode, final int pInputFlag, final int pReturnType, final int pMaxLength) { + Message msg = new Message(); + msg.what = Cocos2dxHandler.HANDLER_SHOW_EDITBOX_DIALOG; + msg.obj = new Cocos2dxHandler.EditBoxMessage(pTitle, pContent, pInputMode, pInputFlag, pReturnType, pMaxLength); + this.mHandler.sendMessage(msg); + } + + @Override + public void runOnGLThread(final Runnable pRunnable) { + this.mGLSurfaceView.queueEvent(pRunnable); + } + + // =========================================================== + // Methods + // =========================================================== + public void init() { + + // FrameLayout + ViewGroup.LayoutParams framelayout_params = + new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, + ViewGroup.LayoutParams.FILL_PARENT); + FrameLayout framelayout = new FrameLayout(this); + framelayout.setLayoutParams(framelayout_params); + + // Cocos2dxEditText layout + ViewGroup.LayoutParams edittext_layout_params = + new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT); + Cocos2dxEditText edittext = new Cocos2dxEditText(this); + edittext.setLayoutParams(edittext_layout_params); + + // ...add to FrameLayout + framelayout.addView(edittext); + + // Cocos2dxGLSurfaceView + this.mGLSurfaceView = this.onCreateView(); + + // ...add to FrameLayout + framelayout.addView(this.mGLSurfaceView); + + // Switch to supported OpenGL (ARGB888) mode on emulator + if (isAndroidEmulator()) + this.mGLSurfaceView.setEGLConfigChooser(8 , 8, 8, 8, 16, 0); + + this.mGLSurfaceView.setCocos2dxRenderer(new Cocos2dxRenderer()); + this.mGLSurfaceView.setCocos2dxEditText(edittext); + + // Set framelayout as the content view + setContentView(framelayout); + } + + public Cocos2dxGLSurfaceView onCreateView() { + return new Cocos2dxGLSurfaceView(this); + } + + private final static boolean isAndroidEmulator() { + String model = Build.MODEL; + Log.d(TAG, "model=" + model); + String product = Build.PRODUCT; + Log.d(TAG, "product=" + product); + boolean isEmulator = false; + if (product != null) { + isEmulator = product.equals("sdk") || product.contains("_sdk") || product.contains("sdk_"); + } + Log.d(TAG, "isEmulator=" + isEmulator); + return isEmulator; + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxETCLoader.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxETCLoader.java new file mode 100644 index 0000000000..fd4cd81954 --- /dev/null +++ b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxETCLoader.java @@ -0,0 +1,109 @@ +/**************************************************************************** +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. + ****************************************************************************/ +package org.cocos2dx.lib; + +import java.io.FileInputStream; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import android.content.Context; +import android.content.res.AssetManager; +import android.opengl.ETC1Util; +import android.util.Log; + +public class Cocos2dxETCLoader { + private static final String ASSETS_PATH = "assets/"; + private static Context context; + + public static boolean loadTexture(String filePath) { + if (! ETC1Util.isETC1Supported()) { + return false; + } + + if (filePath.length() == 0) { + return false; + } + + // Create ETC1Texture + InputStream inputStream = null; + ETC1Util.ETC1Texture texture = null; + AssetManager assetManager = null; + try { + if (filePath.charAt(0) == '/') { + // absolute path + inputStream = new FileInputStream(filePath); + } else { + // remove prefix: "assets/" + if (filePath.startsWith(ASSETS_PATH)) { + filePath = filePath.substring(ASSETS_PATH.length()); + } + assetManager = context.getAssets(); + inputStream = assetManager.open(filePath); + } + + texture = ETC1Util.createTexture(inputStream); + inputStream.close(); + } catch (Exception e) { + Log.d("Cocos2dx", "Unable to create texture for " + filePath); + + texture = null; + } + + if (texture != null) { + boolean ret = true; + + try { + final int width = texture.getWidth(); + final int height = texture.getHeight(); + final int length = texture.getData().remaining(); + + final byte[] data = new byte[length]; + final ByteBuffer buf = ByteBuffer.wrap(data); + buf.order(ByteOrder.nativeOrder()); + buf.put(texture.getData()); + + nativeSetTextureInfo(width, + height, + data, + length); + } catch (Exception e) + { + Log.d("invoke native function error", e.toString()); + ret = false; + } + + return ret; + } else { + return false; + } + } + + public static void setContext(Context context) { + Cocos2dxETCLoader.context = context; + } + + private static native void nativeSetTextureInfo(final int width, final int height, final byte[] data, + final int dataLength); +} diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditText.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditText.java index 8c2fe378be..77a40bb053 100644 --- a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditText.java +++ b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditText.java @@ -26,15 +26,9 @@ package org.cocos2dx.lib; import android.app.Activity; import android.content.Context; -import android.text.Editable; -import android.text.TextWatcher; +import android.util.AttributeSet; import android.view.KeyEvent; -import android.view.ViewGroup; -import android.view.inputmethod.EditorInfo; -import android.view.inputmethod.InputMethodManager; import android.widget.EditText; -import android.widget.TextView; -import android.widget.TextView.OnEditorActionListener; public class Cocos2dxEditText extends EditText { // =========================================================== @@ -44,10 +38,8 @@ public class Cocos2dxEditText extends EditText { // =========================================================== // Fields // =========================================================== - - private Cocos2dxTextInputWraper mTextWatcher = null; - private Context mContext = null; - private static Cocos2dxEditText instance = null; + + private Cocos2dxGLSurfaceView mCocos2dxGLSurfaceView; // =========================================================== // Constructors @@ -55,61 +47,35 @@ public class Cocos2dxEditText extends EditText { public Cocos2dxEditText(final Context context) { super(context); - - this.mContext = context; - this.mTextWatcher = new Cocos2dxTextInputWraper(context, this); - this.setOnEditorActionListener(this.mTextWatcher); - - ViewGroup.LayoutParams layout = - new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT); - - Activity activity = (Activity)context; - activity.addContentView(this, layout); + } + + public Cocos2dxEditText(final Context context, final AttributeSet attrs) { + super(context, attrs); + } + + public Cocos2dxEditText(final Context context, final AttributeSet attrs, final int defStyle) { + super(context, attrs, defStyle); } // =========================================================== // Getter & Setter // =========================================================== + public void setCocos2dxGLSurfaceView(final Cocos2dxGLSurfaceView pCocos2dxGLSurfaceView) { + this.mCocos2dxGLSurfaceView = pCocos2dxGLSurfaceView; + } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== - - public static Cocos2dxEditText getInstance(final Context context) { - if (instance == null) { - instance = new Cocos2dxEditText(context); - } - return instance; - } - - public void closeIMEKeyboard() { - this.removeTextChangedListener(mTextWatcher); - final InputMethodManager imm = (InputMethodManager)mContext.getSystemService(Context.INPUT_METHOD_SERVICE); - imm.hideSoftInputFromWindow(this.getWindowToken(), 0); - //Cocos2dxHelper.nativeRequestFocus(); - } - - public void openIMEKeyboard() { - this.requestFocus(); - final String content = nativeGetContent(); - this.setText(content); - - mTextWatcher.setOriginText(content); - this.addTextChangedListener(mTextWatcher); - - final InputMethodManager imm = (InputMethodManager)mContext.getSystemService(Context.INPUT_METHOD_SERVICE); - imm.showSoftInput(this, InputMethodManager.SHOW_FORCED); - } @Override - public boolean onKeyDown(final int keyCode, final KeyEvent keyEvent) { - super.onKeyDown(keyCode, keyEvent); + public boolean onKeyDown(final int pKeyCode, final KeyEvent pKeyEvent) { + super.onKeyDown(pKeyCode, pKeyEvent); /* Let GlSurfaceView get focus if back key is input. */ - if (keyCode == KeyEvent.KEYCODE_BACK) { - //Cocos2dxHelper.nativeRequestFocus(); + if (pKeyCode == KeyEvent.KEYCODE_BACK) { + this.mCocos2dxGLSurfaceView.requestFocus(); } return true; @@ -118,133 +84,8 @@ public class Cocos2dxEditText extends EditText { // =========================================================== // Methods // =========================================================== - - private native static String nativeGetContent(); // =========================================================== // Inner and Anonymous Classes // =========================================================== } - -class Cocos2dxTextInputWraper implements TextWatcher, OnEditorActionListener { - // =========================================================== - // Constants - // =========================================================== - - private static final String TAG = Cocos2dxTextInputWraper.class.getSimpleName(); - - // =========================================================== - // Fields - // =========================================================== - - private String mText; - private String mOriginText; - private Context mContext; - private TextView mTextView; - - // =========================================================== - // Constructors - // =========================================================== - - public Cocos2dxTextInputWraper(Context context, TextView textView) { - this.mContext = context; - this.mTextView = textView; - } - - // =========================================================== - // Getter & Setter - // =========================================================== - - private boolean isFullScreenEdit() { - final InputMethodManager imm = (InputMethodManager) this.mContext.getSystemService(Context.INPUT_METHOD_SERVICE); - return imm.isFullscreenMode(); - } - - public void setOriginText(final String originText) { - this.mOriginText = originText; - } - - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== - - @Override - public void afterTextChanged(final Editable s) { - if (this.isFullScreenEdit()) { - return; - } - - int nModified = s.length() - this.mText.length(); - if (nModified > 0) { - final String insertText = s.subSequence(this.mText.length(), s.length()).toString(); - nativeInsertText(insertText); - } else { - for (; nModified < 0; ++nModified) { - nativeDeleteBackward(); - } - } - this.mText = s.toString(); - } - - @Override - public void beforeTextChanged(final CharSequence pCharSequence, final int start, final int count, final int after) { - this.mText = pCharSequence.toString(); - } - - @Override - public void onTextChanged(final CharSequence pCharSequence, final int start, final int before, final int count) { - } - - @Override - public boolean onEditorAction(final TextView pTextView, final int pActionID, final KeyEvent pKeyEvent) { - if (this.mTextView == pTextView && this.isFullScreenEdit()) { - // user press the action button, delete all old text and insert new text - for (int i = this.mOriginText.length(); i > 0; i--) { - Cocos2dxHelper.runOnGLThread(new Runnable() { - - @Override - public void run() { - nativeDeleteBackward(); - } - - }); - - } - String text = pTextView.getText().toString(); - - /* If user input nothing, translate "\n" to engine. */ - if (text.compareTo("") == 0) { - text = "\n"; - } - - if ('\n' != text.charAt(text.length() - 1)) { - text += '\n'; - } - - final String insertText = text; - Cocos2dxHelper.runOnGLThread(new Runnable() { - - @Override - public void run() { - nativeInsertText(insertText); - } - - }); - } - - if (pActionID == EditorInfo.IME_ACTION_DONE) { - //Cocos2dxHelper.nativeRequestFocus(); - } - return false; - } - - // =========================================================== - // Methods - // =========================================================== - - private native static void nativeInsertText(String text); - private native static void nativeDeleteBackward(); - // =========================================================== - // Inner and Anonymous Classes - // =========================================================== -} diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java new file mode 100644 index 0000000000..28a16a1dd0 --- /dev/null +++ b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java @@ -0,0 +1,370 @@ +/**************************************************************************** +Copyright (c) 2010-2011 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. + ****************************************************************************/ +package org.cocos2dx.lib; + +import android.content.Context; +import android.opengl.GLSurfaceView; +import android.os.Handler; +import android.os.Message; +import android.util.AttributeSet; +import android.util.Log; +import android.view.KeyEvent; +import android.view.MotionEvent; +import android.view.inputmethod.InputMethodManager; + +public class Cocos2dxGLSurfaceView extends GLSurfaceView { + // =========================================================== + // Constants + // =========================================================== + + private static final String TAG = Cocos2dxGLSurfaceView.class.getSimpleName(); + + private final static int HANDLER_OPEN_IME_KEYBOARD = 2; + private final static int HANDLER_CLOSE_IME_KEYBOARD = 3; + + // =========================================================== + // Fields + // =========================================================== + + // TODO Static handler -> Potential leak! + private static Handler sHandler; + + private static Cocos2dxGLSurfaceView mCocos2dxGLSurfaceView; + private static Cocos2dxTextInputWraper sCocos2dxTextInputWraper; + + private Cocos2dxRenderer mCocos2dxRenderer; + private Cocos2dxEditText mCocos2dxEditText; + + // =========================================================== + // Constructors + // =========================================================== + + public Cocos2dxGLSurfaceView(final Context context) { + super(context); + + this.initView(); + } + + public Cocos2dxGLSurfaceView(final Context context, final AttributeSet attrs) { + super(context, attrs); + + this.initView(); + } + + protected void initView() { + this.setEGLContextClientVersion(2); + this.setFocusableInTouchMode(true); + + Cocos2dxGLSurfaceView.mCocos2dxGLSurfaceView = this; + Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper = new Cocos2dxTextInputWraper(this); + + Cocos2dxGLSurfaceView.sHandler = new Handler() { + @Override + public void handleMessage(final Message msg) { + switch (msg.what) { + case HANDLER_OPEN_IME_KEYBOARD: + if (null != Cocos2dxGLSurfaceView.this.mCocos2dxEditText && Cocos2dxGLSurfaceView.this.mCocos2dxEditText.requestFocus()) { + Cocos2dxGLSurfaceView.this.mCocos2dxEditText.removeTextChangedListener(Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper); + Cocos2dxGLSurfaceView.this.mCocos2dxEditText.setText(""); + final String text = (String) msg.obj; + Cocos2dxGLSurfaceView.this.mCocos2dxEditText.append(text); + Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper.setOriginText(text); + Cocos2dxGLSurfaceView.this.mCocos2dxEditText.addTextChangedListener(Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper); + final InputMethodManager imm = (InputMethodManager) Cocos2dxGLSurfaceView.mCocos2dxGLSurfaceView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + imm.showSoftInput(Cocos2dxGLSurfaceView.this.mCocos2dxEditText, 0); + Log.d("GLSurfaceView", "showSoftInput"); + } + break; + + case HANDLER_CLOSE_IME_KEYBOARD: + if (null != Cocos2dxGLSurfaceView.this.mCocos2dxEditText) { + Cocos2dxGLSurfaceView.this.mCocos2dxEditText.removeTextChangedListener(Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper); + final InputMethodManager imm = (InputMethodManager) Cocos2dxGLSurfaceView.mCocos2dxGLSurfaceView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + imm.hideSoftInputFromWindow(Cocos2dxGLSurfaceView.this.mCocos2dxEditText.getWindowToken(), 0); + Cocos2dxGLSurfaceView.this.requestFocus(); + Log.d("GLSurfaceView", "HideSoftInput"); + } + break; + } + } + }; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + + public static Cocos2dxGLSurfaceView getInstance() { + return mCocos2dxGLSurfaceView; + } + + public static void queueAccelerometer(final float x, final float y, final float z, final long timestamp) { + mCocos2dxGLSurfaceView.queueEvent(new Runnable() { + @Override + public void run() { + Cocos2dxAccelerometer.onSensorChanged(x, y, z, timestamp); + } + }); + } + + public void setCocos2dxRenderer(final Cocos2dxRenderer renderer) { + this.mCocos2dxRenderer = renderer; + this.setRenderer(this.mCocos2dxRenderer); + } + + private String getContentText() { + return this.mCocos2dxRenderer.getContentText(); + } + + public Cocos2dxEditText getCocos2dxEditText() { + return this.mCocos2dxEditText; + } + + public void setCocos2dxEditText(final Cocos2dxEditText pCocos2dxEditText) { + this.mCocos2dxEditText = pCocos2dxEditText; + if (null != this.mCocos2dxEditText && null != Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper) { + this.mCocos2dxEditText.setOnEditorActionListener(Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper); + this.mCocos2dxEditText.setCocos2dxGLSurfaceView(this); + this.requestFocus(); + } + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void onResume() { + super.onResume(); + + this.queueEvent(new Runnable() { + @Override + public void run() { + Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleOnResume(); + } + }); + } + + @Override + public void onPause() { + this.queueEvent(new Runnable() { + @Override + public void run() { + Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleOnPause(); + } + }); + + //super.onPause(); + } + + @Override + public boolean onTouchEvent(final MotionEvent pMotionEvent) { + // these data are used in ACTION_MOVE and ACTION_CANCEL + final int pointerNumber = pMotionEvent.getPointerCount(); + final int[] ids = new int[pointerNumber]; + final float[] xs = new float[pointerNumber]; + final float[] ys = new float[pointerNumber]; + + for (int i = 0; i < pointerNumber; i++) { + ids[i] = pMotionEvent.getPointerId(i); + xs[i] = pMotionEvent.getX(i); + ys[i] = pMotionEvent.getY(i); + } + + switch (pMotionEvent.getAction() & MotionEvent.ACTION_MASK) { + case MotionEvent.ACTION_POINTER_DOWN: + final int indexPointerDown = pMotionEvent.getAction() >> MotionEvent.ACTION_POINTER_ID_SHIFT; + final int idPointerDown = pMotionEvent.getPointerId(indexPointerDown); + final float xPointerDown = pMotionEvent.getX(indexPointerDown); + final float yPointerDown = pMotionEvent.getY(indexPointerDown); + + this.queueEvent(new Runnable() { + @Override + public void run() { + Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleActionDown(idPointerDown, xPointerDown, yPointerDown); + } + }); + break; + + case MotionEvent.ACTION_DOWN: + // there are only one finger on the screen + final int idDown = pMotionEvent.getPointerId(0); + final float xDown = xs[0]; + final float yDown = ys[0]; + + this.queueEvent(new Runnable() { + @Override + public void run() { + Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleActionDown(idDown, xDown, yDown); + } + }); + break; + + case MotionEvent.ACTION_MOVE: + this.queueEvent(new Runnable() { + @Override + public void run() { + Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleActionMove(ids, xs, ys); + } + }); + break; + + case MotionEvent.ACTION_POINTER_UP: + final int indexPointUp = pMotionEvent.getAction() >> MotionEvent.ACTION_POINTER_ID_SHIFT; + final int idPointerUp = pMotionEvent.getPointerId(indexPointUp); + final float xPointerUp = pMotionEvent.getX(indexPointUp); + final float yPointerUp = pMotionEvent.getY(indexPointUp); + + this.queueEvent(new Runnable() { + @Override + public void run() { + Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleActionUp(idPointerUp, xPointerUp, yPointerUp); + } + }); + break; + + case MotionEvent.ACTION_UP: + // there are only one finger on the screen + final int idUp = pMotionEvent.getPointerId(0); + final float xUp = xs[0]; + final float yUp = ys[0]; + + this.queueEvent(new Runnable() { + @Override + public void run() { + Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleActionUp(idUp, xUp, yUp); + } + }); + break; + + case MotionEvent.ACTION_CANCEL: + this.queueEvent(new Runnable() { + @Override + public void run() { + Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleActionCancel(ids, xs, ys); + } + }); + break; + } + + /* + if (BuildConfig.DEBUG) { + Cocos2dxGLSurfaceView.dumpMotionEvent(pMotionEvent); + } + */ + return true; + } + + /* + * This function is called before Cocos2dxRenderer.nativeInit(), so the + * width and height is correct. + */ + @Override + protected void onSizeChanged(final int pNewSurfaceWidth, final int pNewSurfaceHeight, final int pOldSurfaceWidth, final int pOldSurfaceHeight) { + if(!this.isInEditMode()) { + this.mCocos2dxRenderer.setScreenWidthAndHeight(pNewSurfaceWidth, pNewSurfaceHeight); + } + } + + @Override + public boolean onKeyDown(final int pKeyCode, final KeyEvent pKeyEvent) { + switch (pKeyCode) { + case KeyEvent.KEYCODE_BACK: + case KeyEvent.KEYCODE_MENU: + this.queueEvent(new Runnable() { + @Override + public void run() { + Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleKeyDown(pKeyCode); + } + }); + return true; + default: + return super.onKeyDown(pKeyCode, pKeyEvent); + } + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static void openIMEKeyboard() { + final Message msg = new Message(); + msg.what = Cocos2dxGLSurfaceView.HANDLER_OPEN_IME_KEYBOARD; + msg.obj = Cocos2dxGLSurfaceView.mCocos2dxGLSurfaceView.getContentText(); + Cocos2dxGLSurfaceView.sHandler.sendMessage(msg); + } + + public static void closeIMEKeyboard() { + final Message msg = new Message(); + msg.what = Cocos2dxGLSurfaceView.HANDLER_CLOSE_IME_KEYBOARD; + Cocos2dxGLSurfaceView.sHandler.sendMessage(msg); + } + + public void insertText(final String pText) { + this.queueEvent(new Runnable() { + @Override + public void run() { + Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleInsertText(pText); + } + }); + } + + public void deleteBackward() { + this.queueEvent(new Runnable() { + @Override + public void run() { + Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleDeleteBackward(); + } + }); + } + + private static void dumpMotionEvent(final MotionEvent event) { + final String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE", "POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" }; + final StringBuilder sb = new StringBuilder(); + final int action = event.getAction(); + final int actionCode = action & MotionEvent.ACTION_MASK; + sb.append("event ACTION_").append(names[actionCode]); + if (actionCode == MotionEvent.ACTION_POINTER_DOWN || actionCode == MotionEvent.ACTION_POINTER_UP) { + sb.append("(pid ").append(action >> MotionEvent.ACTION_POINTER_ID_SHIFT); + sb.append(")"); + } + sb.append("["); + for (int i = 0; i < event.getPointerCount(); i++) { + sb.append("#").append(i); + sb.append("(pid ").append(event.getPointerId(i)); + sb.append(")=").append((int) event.getX(i)); + sb.append(",").append((int) event.getY(i)); + if (i + 1 < event.getPointerCount()) { + sb.append(";"); + } + } + sb.append("]"); + Log.d(Cocos2dxGLSurfaceView.TAG, sb.toString()); + } +} diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHandler.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHandler.java new file mode 100644 index 0000000000..47639afc5e --- /dev/null +++ b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHandler.java @@ -0,0 +1,135 @@ +/**************************************************************************** +Copyright (c) 2010-2011 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. + ****************************************************************************/ + +package org.cocos2dx.lib; + +import java.lang.ref.WeakReference; + +import android.app.AlertDialog; +import android.content.DialogInterface; +import android.os.Handler; +import android.os.Message; + +public class Cocos2dxHandler extends Handler { + // =========================================================== + // Constants + // =========================================================== + public final static int HANDLER_SHOW_DIALOG = 1; + public final static int HANDLER_SHOW_EDITBOX_DIALOG = 2; + + // =========================================================== + // Fields + // =========================================================== + private WeakReference mActivity; + + // =========================================================== + // Constructors + // =========================================================== + public Cocos2dxHandler(Cocos2dxActivity activity) { + this.mActivity = new WeakReference(activity); + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + // =========================================================== + // Methods + // =========================================================== + + public void handleMessage(Message msg) { + switch (msg.what) { + case Cocos2dxHandler.HANDLER_SHOW_DIALOG: + showDialog(msg); + break; + case Cocos2dxHandler.HANDLER_SHOW_EDITBOX_DIALOG: + showEditBoxDialog(msg); + break; + } + } + + private void showDialog(Message msg) { + Cocos2dxActivity theActivity = this.mActivity.get(); + DialogMessage dialogMessage = (DialogMessage)msg.obj; + new AlertDialog.Builder(theActivity) + .setTitle(dialogMessage.titile) + .setMessage(dialogMessage.message) + .setPositiveButton("Ok", + new DialogInterface.OnClickListener() { + + @Override + public void onClick(DialogInterface dialog, int which) { + // TODO Auto-generated method stub + + } + }).create().show(); + } + + private void showEditBoxDialog(Message msg) { + EditBoxMessage editBoxMessage = (EditBoxMessage)msg.obj; + new Cocos2dxEditBoxDialog(this.mActivity.get(), + editBoxMessage.title, + editBoxMessage.content, + editBoxMessage.inputMode, + editBoxMessage.inputFlag, + editBoxMessage.returnType, + editBoxMessage.maxLength).show(); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== + + public static class DialogMessage { + public String titile; + public String message; + + public DialogMessage(String title, String message) { + this.titile = title; + this.message = message; + } + } + + public static class EditBoxMessage { + public String title; + public String content; + public int inputMode; + public int inputFlag; + public int returnType; + public int maxLength; + + public EditBoxMessage(String title, String content, int inputMode, int inputFlag, int returnType, int maxLength){ + this.content = content; + this.title = title; + this.inputMode = inputMode; + this.inputFlag = inputFlag; + this.returnType = returnType; + this.maxLength = maxLength; + } + } +} diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java index f1e7afb0ed..a835119f02 100644 --- a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java +++ b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java @@ -31,6 +31,7 @@ import java.lang.Runnable; import android.app.Activity; import android.app.AlertDialog; +import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; @@ -56,6 +57,7 @@ public class Cocos2dxHelper { private static Cocos2dxMusic sCocos2dMusic; private static Cocos2dxSound sCocos2dSound; private static AssetManager sAssetManager; + private static Cocos2dxAccelerometer sCocos2dxAccelerometer; private static boolean sAccelerometerEnabled; private static String sPackageName; private static String sFileDirectory; @@ -94,7 +96,7 @@ public class Cocos2dxHelper { if (!sInited) { final ApplicationInfo applicationInfo = activity.getApplicationInfo(); - initListener(); + Cocos2dxHelper.sCocos2dxHelperListener = (Cocos2dxHelperListener)activity; try { // Get the lib_name from AndroidManifest.xml metadata @@ -114,87 +116,23 @@ public class Cocos2dxHelper { Cocos2dxHelper.sPackageName = applicationInfo.packageName; Cocos2dxHelper.sFileDirectory = activity.getFilesDir().getAbsolutePath(); - //Cocos2dxHelper.nativeSetApkPath(applicationInfo.sourceDir); + Cocos2dxHelper.nativeSetApkPath(applicationInfo.sourceDir); + Cocos2dxHelper.sCocos2dxAccelerometer = new Cocos2dxAccelerometer(activity); Cocos2dxHelper.sCocos2dMusic = new Cocos2dxMusic(activity); Cocos2dxHelper.sCocos2dSound = new Cocos2dxSound(activity); Cocos2dxHelper.sAssetManager = activity.getAssets(); + Cocos2dxHelper.nativeSetContext((Context)activity, Cocos2dxHelper.sAssetManager); - //Cocos2dxHelper.nativeSetAssetManager(sAssetManager); Cocos2dxBitmap.setContext(activity); + Cocos2dxETCLoader.setContext(activity); sActivity = activity; sInited = true; + } } - public static void initListener() { - Cocos2dxHelper.sCocos2dxHelperListener = new Cocos2dxHelperListener() { - - @Override - public void showEditTextDialog(final String title, final String message, - final int inputMode, final int inputFlag, final int returnType, final int maxLength) { - sActivity.runOnUiThread(new Runnable() { - @Override - public void run() { - new Cocos2dxEditBoxDialog(sActivity, - title, - message, - inputMode, - inputFlag, - returnType, - maxLength).show(); - } - }); - } - - @Override - public void openIMEKeyboard() { - sActivity.runOnUiThread(new Runnable() { - - @Override - public void run() { - Cocos2dxEditText.getInstance(sActivity).openIMEKeyboard(); - } - - }); - } - - @Override - public void closeIMEKeyboard() { - sActivity.runOnUiThread(new Runnable() { - - @Override - public void run() { - Cocos2dxEditText.getInstance(sActivity).closeIMEKeyboard(); - } - - }); - } - - @Override - public void showDialog(final String title, final String message) { - - sActivity.runOnUiThread(new Runnable() { - - @Override - public void run() { - new AlertDialog.Builder(sActivity) - .setTitle(title) - .setMessage(message) - .setPositiveButton("Ok", - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - // TODO Auto-generated method stub - } - }).create().show(); - } - }); - } - }; - } - public static Activity getActivity() { return sActivity; } @@ -211,8 +149,12 @@ public class Cocos2dxHelper { // Methods // =========================================================== + private static native void nativeSetApkPath(final String pApkPath); + private static native void nativeSetEditTextDialogResult(final byte[] pBytes); + private static native void nativeSetContext(final Context pContext, final AssetManager pAssetManager); + public static String getCocos2dxPackageName() { return Cocos2dxHelper.sPackageName; } @@ -233,6 +175,21 @@ public class Cocos2dxHelper { return Cocos2dxHelper.sAssetManager; } + public static void enableAccelerometer() { + Cocos2dxHelper.sAccelerometerEnabled = true; + Cocos2dxHelper.sCocos2dxAccelerometer.enable(); + } + + + public static void setAccelerometerInterval(float interval) { + Cocos2dxHelper.sCocos2dxAccelerometer.setInterval(interval); + } + + public static void disableAccelerometer() { + Cocos2dxHelper.sAccelerometerEnabled = false; + Cocos2dxHelper.sCocos2dxAccelerometer.disable(); + } + public static void preloadBackgroundMusic(final String pPath) { Cocos2dxHelper.sCocos2dMusic.preloadBackgroundMusic(pPath); } @@ -318,6 +275,18 @@ public class Cocos2dxHelper { Cocos2dxHelper.sCocos2dSound.end(); } + public static void onResume() { + if (Cocos2dxHelper.sAccelerometerEnabled) { + Cocos2dxHelper.sCocos2dxAccelerometer.enable(); + } + } + + public static void onPause() { + if (Cocos2dxHelper.sAccelerometerEnabled) { + Cocos2dxHelper.sCocos2dxAccelerometer.disable(); + } + } + public static void terminateProcess() { android.os.Process.killProcess(android.os.Process.myPid()); } @@ -333,19 +302,17 @@ public class Cocos2dxHelper { public static void setEditTextDialogResult(final String pResult) { try { final byte[] bytesUTF8 = pResult.getBytes("UTF8"); - Cocos2dxHelper.nativeSetEditTextDialogResult(bytesUTF8); + + Cocos2dxHelper.sCocos2dxHelperListener.runOnGLThread(new Runnable() { + @Override + public void run() { + Cocos2dxHelper.nativeSetEditTextDialogResult(bytesUTF8); + } + }); } catch (UnsupportedEncodingException pUnsupportedEncodingException) { /* Nothing. */ } } - - private static void openIMEKeyboard() { - sCocos2dxHelperListener.openIMEKeyboard(); - } - - private static void closeIMEKeyboard() { - sCocos2dxHelperListener.closeIMEKeyboard(); - } public static int getDPI() { @@ -431,17 +398,15 @@ public class Cocos2dxHelper { editor.putString(key, value); editor.commit(); } - - public static native void nativeRequestFocus(); // =========================================================== // Inner and Anonymous Classes // =========================================================== public static interface Cocos2dxHelperListener { - public void showDialog(final String title, final String message); - public void showEditTextDialog(final String title, final String message, final int inputMode, final int inputFlag, final int returnType, final int maxLength); - public void openIMEKeyboard(); - public void closeIMEKeyboard(); + public void showDialog(final String pTitle, final String pMessage); + public void showEditTextDialog(final String pTitle, final String pMessage, final int pInputMode, final int pInputFlag, final int pReturnType, final int pMaxLength); + + public void runOnGLThread(final Runnable pRunnable); } } diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxLocalStorage.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxLocalStorage.java index d6dd3dd135..04a1c9b3e6 100644 --- a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxLocalStorage.java +++ b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxLocalStorage.java @@ -46,10 +46,10 @@ public class Cocos2dxLocalStorage { * @return */ public static boolean init(String dbName, String tableName) { - if (Cocos2dxHelper.getActivity() != null) { + if (Cocos2dxActivity.getContext() != null) { DATABASE_NAME = dbName; TABLE_NAME = tableName; - mDatabaseOpenHelper = new DBOpenHelper(Cocos2dxHelper.getActivity()); + mDatabaseOpenHelper = new DBOpenHelper(Cocos2dxActivity.getContext()); mDatabase = mDatabaseOpenHelper.getWritableDatabase(); return true; } diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxRenderer.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxRenderer.java new file mode 100644 index 0000000000..787f954280 --- /dev/null +++ b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxRenderer.java @@ -0,0 +1,171 @@ +/**************************************************************************** +Copyright (c) 2010-2011 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. + ****************************************************************************/ +package org.cocos2dx.lib; + +import javax.microedition.khronos.egl.EGLConfig; +import javax.microedition.khronos.opengles.GL10; + +import android.opengl.GLSurfaceView; + +public class Cocos2dxRenderer implements GLSurfaceView.Renderer { + // =========================================================== + // Constants + // =========================================================== + + private final static long NANOSECONDSPERSECOND = 1000000000L; + private final static long NANOSECONDSPERMICROSECOND = 1000000; + + private static long sAnimationInterval = (long) (1.0 / 60 * Cocos2dxRenderer.NANOSECONDSPERSECOND); + + // =========================================================== + // Fields + // =========================================================== + + private long mLastTickInNanoSeconds; + private int mScreenWidth; + private int mScreenHeight; + + // =========================================================== + // Constructors + // =========================================================== + + // =========================================================== + // Getter & Setter + // =========================================================== + + public static void setAnimationInterval(final double pAnimationInterval) { + Cocos2dxRenderer.sAnimationInterval = (long) (pAnimationInterval * Cocos2dxRenderer.NANOSECONDSPERSECOND); + } + + public void setScreenWidthAndHeight(final int pSurfaceWidth, final int pSurfaceHeight) { + this.mScreenWidth = pSurfaceWidth; + this.mScreenHeight = pSurfaceHeight; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void onSurfaceCreated(final GL10 pGL10, final EGLConfig pEGLConfig) { + Cocos2dxRenderer.nativeInit(this.mScreenWidth, this.mScreenHeight); + this.mLastTickInNanoSeconds = System.nanoTime(); + } + + @Override + public void onSurfaceChanged(final GL10 pGL10, final int pWidth, final int pHeight) { + } + + @Override + public void onDrawFrame(final GL10 gl) { + /* + * FPS controlling algorithm is not accurate, and it will slow down FPS + * on some devices. So comment FPS controlling code. + */ + + /* + final long nowInNanoSeconds = System.nanoTime(); + final long interval = nowInNanoSeconds - this.mLastTickInNanoSeconds; + */ + + // should render a frame when onDrawFrame() is called or there is a + // "ghost" + Cocos2dxRenderer.nativeRender(); + + /* + // fps controlling + if (interval < Cocos2dxRenderer.sAnimationInterval) { + try { + // because we render it before, so we should sleep twice time interval + Thread.sleep((Cocos2dxRenderer.sAnimationInterval - interval) / Cocos2dxRenderer.NANOSECONDSPERMICROSECOND); + } catch (final Exception e) { + } + } + + this.mLastTickInNanoSeconds = nowInNanoSeconds; + */ + } + + // =========================================================== + // Methods + // =========================================================== + + private static native void nativeTouchesBegin(final int pID, final float pX, final float pY); + private static native void nativeTouchesEnd(final int pID, final float pX, final float pY); + private static native void nativeTouchesMove(final int[] pIDs, final float[] pXs, final float[] pYs); + private static native void nativeTouchesCancel(final int[] pIDs, final float[] pXs, final float[] pYs); + private static native boolean nativeKeyDown(final int pKeyCode); + private static native void nativeRender(); + private static native void nativeInit(final int pWidth, final int pHeight); + private static native void nativeOnPause(); + private static native void nativeOnResume(); + + public void handleActionDown(final int pID, final float pX, final float pY) { + Cocos2dxRenderer.nativeTouchesBegin(pID, pX, pY); + } + + public void handleActionUp(final int pID, final float pX, final float pY) { + Cocos2dxRenderer.nativeTouchesEnd(pID, pX, pY); + } + + public void handleActionCancel(final int[] pIDs, final float[] pXs, final float[] pYs) { + Cocos2dxRenderer.nativeTouchesCancel(pIDs, pXs, pYs); + } + + public void handleActionMove(final int[] pIDs, final float[] pXs, final float[] pYs) { + Cocos2dxRenderer.nativeTouchesMove(pIDs, pXs, pYs); + } + + public void handleKeyDown(final int pKeyCode) { + Cocos2dxRenderer.nativeKeyDown(pKeyCode); + } + + public void handleOnPause() { + Cocos2dxRenderer.nativeOnPause(); + } + + public void handleOnResume() { + Cocos2dxRenderer.nativeOnResume(); + } + + private static native void nativeInsertText(final String pText); + private static native void nativeDeleteBackward(); + private static native String nativeGetContentText(); + + public void handleInsertText(final String pText) { + Cocos2dxRenderer.nativeInsertText(pText); + } + + public void handleDeleteBackward() { + Cocos2dxRenderer.nativeDeleteBackward(); + } + + public String getContentText() { + return Cocos2dxRenderer.nativeGetContentText(); + } + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxTextInputWraper.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxTextInputWraper.java new file mode 100644 index 0000000000..654cf758be --- /dev/null +++ b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxTextInputWraper.java @@ -0,0 +1,168 @@ +/**************************************************************************** +Copyright (c) 2010-2011 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. + ****************************************************************************/ +package org.cocos2dx.lib; + +import android.content.Context; +import android.text.Editable; +import android.text.TextWatcher; +import android.util.Log; +import android.view.KeyEvent; +import android.view.inputmethod.EditorInfo; +import android.view.inputmethod.InputMethodManager; +import android.widget.TextView; +import android.widget.TextView.OnEditorActionListener; + +public class Cocos2dxTextInputWraper implements TextWatcher, OnEditorActionListener { + // =========================================================== + // Constants + // =========================================================== + + private static final String TAG = Cocos2dxTextInputWraper.class.getSimpleName(); + + // =========================================================== + // Fields + // =========================================================== + + private final Cocos2dxGLSurfaceView mCocos2dxGLSurfaceView; + private String mText; + private String mOriginText; + + // =========================================================== + // Constructors + // =========================================================== + + public Cocos2dxTextInputWraper(final Cocos2dxGLSurfaceView pCocos2dxGLSurfaceView) { + this.mCocos2dxGLSurfaceView = pCocos2dxGLSurfaceView; + } + + // =========================================================== + // Getter & Setter + // =========================================================== + + private boolean isFullScreenEdit() { + final TextView textField = this.mCocos2dxGLSurfaceView.getCocos2dxEditText(); + final InputMethodManager imm = (InputMethodManager) textField.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + return imm.isFullscreenMode(); + } + + public void setOriginText(final String pOriginText) { + this.mOriginText = pOriginText; + } + + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== + + @Override + public void afterTextChanged(final Editable s) { + if (this.isFullScreenEdit()) { + return; + } + + //if (BuildConfig.DEBUG) { + //Log.d(TAG, "afterTextChanged: " + s); + //} + int nModified = s.length() - this.mText.length(); + if (nModified > 0) { + final String insertText = s.subSequence(this.mText.length(), s.length()).toString(); + this.mCocos2dxGLSurfaceView.insertText(insertText); + /* + if (BuildConfig.DEBUG) { + Log.d(TAG, "insertText(" + insertText + ")"); + } + */ + } else { + for (; nModified < 0; ++nModified) { + this.mCocos2dxGLSurfaceView.deleteBackward(); + /* + if (BuildConfig.DEBUG) { + Log.d(TAG, "deleteBackward"); + } + */ + } + } + this.mText = s.toString(); + } + + @Override + public void beforeTextChanged(final CharSequence pCharSequence, final int start, final int count, final int after) { + /* + if (BuildConfig.DEBUG) { + Log.d(TAG, "beforeTextChanged(" + pCharSequence + ")start: " + start + ",count: " + count + ",after: " + after); + } + */ + this.mText = pCharSequence.toString(); + } + + @Override + public void onTextChanged(final CharSequence pCharSequence, final int start, final int before, final int count) { + + } + + @Override + public boolean onEditorAction(final TextView pTextView, final int pActionID, final KeyEvent pKeyEvent) { + if (this.mCocos2dxGLSurfaceView.getCocos2dxEditText() == pTextView && this.isFullScreenEdit()) { + // user press the action button, delete all old text and insert new text + for (int i = this.mOriginText.length(); i > 0; i--) { + this.mCocos2dxGLSurfaceView.deleteBackward(); + /* + if (BuildConfig.DEBUG) { + Log.d(TAG, "deleteBackward"); + } + */ + } + String text = pTextView.getText().toString(); + + /* If user input nothing, translate "\n" to engine. */ + if (text.compareTo("") == 0) { + text = "\n"; + } + + if ('\n' != text.charAt(text.length() - 1)) { + text += '\n'; + } + + final String insertText = text; + this.mCocos2dxGLSurfaceView.insertText(insertText); + /* + if (BuildConfig.DEBUG) { + Log.d(TAG, "insertText(" + insertText + ")"); + } + */ + } + + if (pActionID == EditorInfo.IME_ACTION_DONE) { + this.mCocos2dxGLSurfaceView.requestFocus(); + } + return false; + } + + // =========================================================== + // Methods + // =========================================================== + + // =========================================================== + // Inner and Anonymous Classes + // =========================================================== +} \ No newline at end of file diff --git a/cocos/2d/platform/android/javaactivity.cpp b/cocos/2d/platform/android/javaactivity.cpp new file mode 100644 index 0000000000..9e068d1f63 --- /dev/null +++ b/cocos/2d/platform/android/javaactivity.cpp @@ -0,0 +1,82 @@ +/**************************************************************************** +Copyright (c) 2013-2014 Chukong Technologies Inc. + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ + +#include "CCApplication.h" +#include "CCDirector.h" +#include "CCDrawingPrimitives.h" +#include "CCEventCustom.h" +#include "CCEventType.h" +#include "CCGLView.h" +#include "CCShaderCache.h" +#include "CCTextureCache.h" +#include "platform/android/jni/JniHelper.h" +#include +#include + +#define LOG_TAG "main" +#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) + +void cocos_android_app_init(JNIEnv* env, jobject thiz) __attribute__((weak)); + +using namespace cocos2d; + +extern "C" +{ + +jint JNI_OnLoad(JavaVM *vm, void *reserved) +{ + JniHelper::setJavaVM(vm); + + return JNI_VERSION_1_4; +} + +void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInit(JNIEnv* env, jobject thiz, jint w, jint h) +{ + auto director = cocos2d::Director::getInstance(); + auto glview = director->getOpenGLView(); + if (!glview) + { + glview = cocos2d::GLView::create("Android app"); + glview->setFrameSize(w, h); + director->setOpenGLView(glview); + + cocos_android_app_init(env, thiz); + + cocos2d::Application::getInstance()->run(); + } + else + { + cocos2d::GL::invalidateStateCache(); + cocos2d::ShaderCache::getInstance()->reloadDefaultShaders(); + cocos2d::DrawPrimitives::init(); + cocos2d::VolatileTextureMgr::reloadAllTextures(); + + cocos2d::EventCustom foregroundEvent(EVENT_COME_TO_FOREGROUND); + director->getEventDispatcher()->dispatchEvent(&foregroundEvent); + director->setGLDefaultValues(); + } + +} + +} diff --git a/cocos/2d/platform/android/jni/IMEJni.cpp b/cocos/2d/platform/android/jni/IMEJni.cpp index 892b003739..ea96931c28 100644 --- a/cocos/2d/platform/android/jni/IMEJni.cpp +++ b/cocos/2d/platform/android/jni/IMEJni.cpp @@ -44,7 +44,7 @@ extern "C" { void openKeyboardJNI() { JniMethodInfo t; - if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lib/Cocos2dxHelper", "openIMEKeyboard", "()V")) { + if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lib/Cocos2dxGLSurfaceView", "openIMEKeyboard", "()V")) { t.env->CallStaticVoidMethod(t.classID, t.methodID); t.env->DeleteLocalRef(t.classID); } @@ -53,29 +53,9 @@ extern "C" { void closeKeyboardJNI() { JniMethodInfo t; - if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lib/Cocos2dxHelper", "closeIMEKeyboard", "()V")) { + if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lib/Cocos2dxGLSurfaceView", "closeIMEKeyboard", "()V")) { t.env->CallStaticVoidMethod(t.classID, t.methodID); t.env->DeleteLocalRef(t.classID); } } - - JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxTextInputWraper_nativeInsertText(JNIEnv* env, jobject thiz, jstring text) { - const char* tmpText = env->GetStringUTFChars(text, nullptr); - cocos2d::IMEDispatcher::sharedDispatcher()->dispatchInsertText(tmpText, strlen(tmpText)); - env->ReleaseStringUTFChars(text, tmpText); - } - - JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxTextInputWraper_nativeDeleteBackward(JNIEnv* env, jobject thiz) { - cocos2d::IMEDispatcher::sharedDispatcher()->dispatchDeleteBackward(); - } - - JNIEXPORT jstring JNICALL Java_org_cocos2dx_lib_Cocos2dxEditText_nativeGetContent() { - JNIEnv * env = 0; - - if (JniHelper::getJavaVM()->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK || ! env) { - return 0; - } - const std::string& text = cocos2d::IMEDispatcher::sharedDispatcher()->getContentText(); - return env->NewStringUTF(text.c_str()); - } } diff --git a/cocos/2d/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxAccelerometer.cpp b/cocos/2d/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxAccelerometer.cpp new file mode 100644 index 0000000000..d61ddc4dc6 --- /dev/null +++ b/cocos/2d/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxAccelerometer.cpp @@ -0,0 +1,22 @@ +#include "JniHelper.h" +#include +#include "CCDirector.h" +#include "CCEventDispatcher.h" +#include "CCEventAcceleration.h" + +#define TG3_GRAVITY_EARTH (9.80665f) + +using namespace cocos2d; + +extern "C" { + JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxAccelerometer_onSensorChanged(JNIEnv* env, jobject thiz, jfloat x, jfloat y, jfloat z, jlong timeStamp) { + Acceleration a; + a.x = -((double)x / TG3_GRAVITY_EARTH); + a.y = -((double)y / TG3_GRAVITY_EARTH); + a.z = -((double)z / TG3_GRAVITY_EARTH); + a.timestamp = (double)timeStamp; + + EventAcceleration event(a); + Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); + } +} diff --git a/cocos/2d/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp b/cocos/2d/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp index 3d69827626..0f5cfa6b12 100644 --- a/cocos/2d/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp +++ b/cocos/2d/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp @@ -27,6 +27,8 @@ THE SOFTWARE. #include #include #include "JniHelper.h" +#include "CCFileUtilsAndroid.h" +#include "android/asset_manager_jni.h" #include "CCString.h" #include "Java_org_cocos2dx_lib_Cocos2dxHelper.h" @@ -48,6 +50,30 @@ extern "C" { JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetApkPath(JNIEnv* env, jobject thiz, jstring apkPath) { g_apkPath = JniHelper::jstring2string(apkPath); } + + JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetContext(JNIEnv* env, jobject thiz, jobject context, jobject assetManager) { + JniHelper::setClassLoaderFrom(context); + FileUtilsAndroid::setassetmanager(AAssetManager_fromJava(env, assetManager)); + } + + JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetEditTextDialogResult(JNIEnv * env, jobject obj, jbyteArray text) { + jsize size = env->GetArrayLength(text); + + if (size > 0) { + jbyte * data = (jbyte*)env->GetByteArrayElements(text, 0); + char* pBuf = (char*)malloc(size+1); + if (pBuf != NULL) { + memcpy(pBuf, data, size); + pBuf[size] = '\0'; + // pass data to edittext's delegate + if (s_pfEditTextCallback) s_pfEditTextCallback(pBuf, s_ctx); + free(pBuf); + } + env->ReleaseByteArrayElements(text, data, 0); + } else { + if (s_pfEditTextCallback) s_pfEditTextCallback("", s_ctx); + } + } } const char * getApkPath() { @@ -156,6 +182,33 @@ std::string getCurrentLanguageJNI() { return ret; } +void enableAccelerometerJni() { + JniMethodInfo t; + + if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "enableAccelerometer", "()V")) { + t.env->CallStaticVoidMethod(t.classID, t.methodID); + t.env->DeleteLocalRef(t.classID); + } +} + +void setAccelerometerIntervalJni(float interval) { + JniMethodInfo t; + + if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "setAccelerometerInterval", "(F)V")) { + t.env->CallStaticVoidMethod(t.classID, t.methodID, interval); + t.env->DeleteLocalRef(t.classID); + } +} + +void disableAccelerometerJni() { + JniMethodInfo t; + + if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "disableAccelerometer", "()V")) { + t.env->CallStaticVoidMethod(t.classID, t.methodID); + t.env->DeleteLocalRef(t.classID); + } +} + // functions for UserDefault bool getBoolForKeyJNI(const char* pKey, bool defaultValue) { diff --git a/cocos/2d/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h b/cocos/2d/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h index 4d3587a73e..0fea23b531 100644 --- a/cocos/2d/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h +++ b/cocos/2d/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h @@ -36,6 +36,9 @@ extern void terminateProcessJNI(); extern std::string getCurrentLanguageJNI(); extern std::string getPackageNameJNI(); extern std::string getFileDirectoryJNI(); +extern void enableAccelerometerJni(); +extern void disableAccelerometerJni(); +extern void setAccelerometerIntervalJni(float interval); // functions for UserDefault extern bool getBoolForKeyJNI(const char* pKey, bool defaultValue); extern int getIntegerForKeyJNI(const char* pKey, int defaultValue); diff --git a/cocos/2d/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp b/cocos/2d/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp new file mode 100644 index 0000000000..38886285df --- /dev/null +++ b/cocos/2d/platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp @@ -0,0 +1,46 @@ +#include "CCIMEDispatcher.h" +#include "CCDirector.h" +#include "../CCApplication.h" +#include "platform/CCFileUtils.h" +#include "CCEventType.h" +#include "JniHelper.h" +#include + +using namespace cocos2d; + +extern "C" { + + JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeRender(JNIEnv* env) { + cocos2d::Director::getInstance()->mainLoop(); + } + + JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeOnPause() { + Application::getInstance()->applicationDidEnterBackground(); + } + + JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeOnResume() { + if (Director::getInstance()->getOpenGLView()) { + Application::getInstance()->applicationWillEnterForeground(); + } + } + + JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInsertText(JNIEnv* env, jobject thiz, jstring text) { + const char* pszText = env->GetStringUTFChars(text, NULL); + cocos2d::IMEDispatcher::sharedDispatcher()->dispatchInsertText(pszText, strlen(pszText)); + env->ReleaseStringUTFChars(text, pszText); + } + + JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeDeleteBackward(JNIEnv* env, jobject thiz) { + cocos2d::IMEDispatcher::sharedDispatcher()->dispatchDeleteBackward(); + } + + JNIEXPORT jstring JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeGetContentText() { + JNIEnv * env = 0; + + if (JniHelper::getJavaVM()->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK || ! env) { + return 0; + } + std::string pszText = cocos2d::IMEDispatcher::sharedDispatcher()->getContentText(); + return env->NewStringUTF(pszText.c_str()); + } +} diff --git a/cocos/2d/platform/android/jni/JniHelper.cpp b/cocos/2d/platform/android/jni/JniHelper.cpp index 992e4ec2b8..b71b632f25 100644 --- a/cocos/2d/platform/android/jni/JniHelper.cpp +++ b/cocos/2d/platform/android/jni/JniHelper.cpp @@ -30,6 +30,8 @@ THE SOFTWARE. #define LOG_TAG "JniHelper" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) +static pthread_key_t g_key; + jclass _getClassID(const char *className) { if (NULL == className) { return NULL; @@ -57,29 +59,22 @@ namespace cocos2d { JavaVM* JniHelper::_psJavaVM = NULL; jmethodID JniHelper::loadclassMethod_methodID = NULL; jobject JniHelper::classloader = NULL; - JNIEnv* JniHelper::env = NULL; - - static pthread_key_t s_threadKey; JavaVM* JniHelper::getJavaVM() { pthread_t thisthread = pthread_self(); - LOGD("JniHelper::getJavaVM(), pthread_self() = %X", thisthread); + LOGD("JniHelper::getJavaVM(), pthread_self() = %ld", thisthread); return _psJavaVM; } void JniHelper::setJavaVM(JavaVM *javaVM) { pthread_t thisthread = pthread_self(); - LOGD("JniHelper::setJavaVM(%p), pthread_self() = %X", javaVM, thisthread); + LOGD("JniHelper::setJavaVM(%p), pthread_self() = %ld", javaVM, thisthread); _psJavaVM = javaVM; - JniHelper::cacheEnv(javaVM); + pthread_key_create(&g_key, NULL); } - void JniHelper::detach_current_thread (void *env) { - _psJavaVM->DetachCurrentThread(); - } - - bool JniHelper::cacheEnv(JavaVM* jvm) { + JNIEnv* JniHelper::cacheEnv(JavaVM* jvm) { JNIEnv* _env = NULL; // get jni environment jint ret = jvm->GetEnv((void**)&_env, JNI_VERSION_1_4); @@ -87,8 +82,8 @@ namespace cocos2d { switch (ret) { case JNI_OK : // Success! - JniHelper::env = _env; - return true; + pthread_setspecific(g_key, _env); + return _env; case JNI_EDETACHED : // Thread not attached @@ -96,20 +91,16 @@ namespace cocos2d { // TODO : If calling AttachCurrentThread() on a native thread // must call DetachCurrentThread() in future. // see: http://developer.android.com/guide/practices/design/jni.html - - pthread_key_create (&s_threadKey, JniHelper::detach_current_thread); + if (jvm->AttachCurrentThread(&_env, NULL) < 0) { LOGD("Failed to get the environment using AttachCurrentThread()"); - JniHelper::env = NULL; - return false; + return NULL; } else { // Success : Attached and obtained JNIEnv! - JniHelper::env = _env; - if (pthread_getspecific(s_threadKey) == NULL) - pthread_setspecific(s_threadKey, _env); - return true; + pthread_setspecific(g_key, _env); + return _env; } case JNI_EVERSION : @@ -117,25 +108,27 @@ namespace cocos2d { LOGD("JNI interface version 1.4 not supported"); default : LOGD("Failed to get the environment using GetEnv()"); - JniHelper::env = NULL; - return false; + return NULL; } } JNIEnv* JniHelper::getEnv() { - return JniHelper::env; + JNIEnv *_env = (JNIEnv *)pthread_getspecific(g_key); + if (_env == NULL) + _env = JniHelper::cacheEnv(_psJavaVM); + return _env; } - bool JniHelper::setClassLoaderFrom(jobject nativeactivityinstance) { + bool JniHelper::setClassLoaderFrom(jobject activityinstance) { JniMethodInfo _getclassloaderMethod; if (!JniHelper::getMethodInfo_DefaultClassLoader(_getclassloaderMethod, - "android/app/NativeActivity", + "android/content/Context", "getClassLoader", "()Ljava/lang/ClassLoader;")) { return false; } - jobject _c = cocos2d::JniHelper::getEnv()->CallObjectMethod(nativeactivityinstance, + jobject _c = cocos2d::JniHelper::getEnv()->CallObjectMethod(activityinstance, _getclassloaderMethod.methodID); if (NULL == _c) { @@ -214,7 +207,6 @@ namespace cocos2d { jmethodID methodID = pEnv->GetMethodID(classID, methodName, paramCode); if (! methodID) { LOGD("Failed to find method id of %s", methodName); - pEnv->ExceptionClear(); return false; } @@ -243,6 +235,7 @@ namespace cocos2d { jclass classID = _getClassID(className); if (! classID) { LOGD("Failed to find class %s", className); + pEnv->ExceptionClear(); return false; } diff --git a/cocos/2d/platform/android/jni/JniHelper.h b/cocos/2d/platform/android/jni/JniHelper.h index 3f57a85336..cbf95e8613 100644 --- a/cocos/2d/platform/android/jni/JniHelper.h +++ b/cocos/2d/platform/android/jni/JniHelper.h @@ -45,7 +45,7 @@ public: static JavaVM* getJavaVM(); static JNIEnv* getEnv(); - static bool setClassLoaderFrom(jobject nativeActivityInstance); + static bool setClassLoaderFrom(jobject activityInstance); static bool getStaticMethodInfo(JniMethodInfo &methodinfo, const char *className, const char *methodName, @@ -61,8 +61,7 @@ public: static jobject classloader; private: - static void detach_current_thread (void *env); - static bool cacheEnv(JavaVM* jvm); + static JNIEnv* cacheEnv(JavaVM* jvm); static bool getMethodInfo_DefaultClassLoader(JniMethodInfo &methodinfo, const char *className, @@ -70,7 +69,6 @@ private: const char *paramCode); static JavaVM* _psJavaVM; - static JNIEnv* env; }; NS_CC_END diff --git a/cocos/2d/platform/android/jni/TouchesJni.cpp b/cocos/2d/platform/android/jni/TouchesJni.cpp new file mode 100644 index 0000000000..296927f53b --- /dev/null +++ b/cocos/2d/platform/android/jni/TouchesJni.cpp @@ -0,0 +1,93 @@ +/**************************************************************************** +Copyright (c) 2010 cocos2d-x.org + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ +#include "CCSet.h" +#include "CCDirector.h" +#include "CCEventKeyboard.h" +#include "CCGLView.h" + +#include +#include + +using namespace cocos2d; + +extern "C" { + JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesBegin(JNIEnv * env, jobject thiz, jint id, jfloat x, jfloat y) { + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, &id, &x, &y); + } + + JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesEnd(JNIEnv * env, jobject thiz, jint id, jfloat x, jfloat y) { + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, &id, &x, &y); + } + + JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesMove(JNIEnv * env, jobject thiz, jintArray ids, jfloatArray xs, jfloatArray ys) { + int size = env->GetArrayLength(ids); + jint id[size]; + jfloat x[size]; + jfloat y[size]; + + env->GetIntArrayRegion(ids, 0, size, id); + env->GetFloatArrayRegion(xs, 0, size, x); + env->GetFloatArrayRegion(ys, 0, size, y); + + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(size, id, x, y); + } + + JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesCancel(JNIEnv * env, jobject thiz, jintArray ids, jfloatArray xs, jfloatArray ys) { + int size = env->GetArrayLength(ids); + jint id[size]; + jfloat x[size]; + jfloat y[size]; + + env->GetIntArrayRegion(ids, 0, size, id); + env->GetFloatArrayRegion(xs, 0, size, x); + env->GetFloatArrayRegion(ys, 0, size, y); + + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesCancel(size, id, x, y); + } + + #define KEYCODE_BACK 0x04 + #define KEYCODE_MENU 0x52 + + JNIEXPORT jboolean JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeKeyDown(JNIEnv * env, jobject thiz, jint keyCode) { + Director* pDirector = Director::getInstance(); + switch (keyCode) { + case KEYCODE_BACK: + { + cocos2d::EventKeyboard event(cocos2d::EventKeyboard::KeyCode::KEY_BACKSPACE, false); + cocos2d::Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); + return JNI_TRUE; + } + case KEYCODE_MENU: + { + cocos2d::EventKeyboard event(cocos2d::EventKeyboard::KeyCode::KEY_MENU, false); + cocos2d::Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); + + return JNI_TRUE; + } + default: + return JNI_FALSE; + } + return JNI_FALSE; + } +} diff --git a/cocos/2d/platform/android/nativeactivity.cpp b/cocos/2d/platform/android/nativeactivity.cpp deleted file mode 100644 index 25fd192e2a..0000000000 --- a/cocos/2d/platform/android/nativeactivity.cpp +++ /dev/null @@ -1,765 +0,0 @@ -/**************************************************************************** -Copyright (c) 2013-2014 Chukong Technologies Inc. - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#include "CCPlatformConfig.h" -#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID - -#include "nativeactivity.h" - -#include -#include - -#include -#include - -#include -#include -#include -#include - -#include -#include - -#include "CCDirector.h" -#include "CCApplication.h" -#include "CCEventType.h" -#include "CCFileUtilsAndroid.h" -#include "jni/JniHelper.h" - -#include "CCGLView.h" -#include "CCDrawingPrimitives.h" -#include "CCShaderCache.h" -#include "CCTextureCache.h" -#include "CCEventDispatcher.h" -#include "CCEventAcceleration.h" -#include "CCEventKeyboard.h" -#include "CCEventCustom.h" - -#include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h" - -#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 LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, "cocos2dx/nativeactivity.cpp", __VA_ARGS__)) - -#define LOG_RENDER_DEBUG(...) -// #define LOG_RENDER_DEBUG(...) ((void)__android_log_print(ANDROID_LOG_INFO, "cocos2dx/nativeactivity.cpp", __VA_ARGS__)) - -#define LOG_EVENTS_DEBUG(...) -// #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); - -/** - * Our saved state data. - */ -struct saved_state { - float angle; - int32_t x; - int32_t y; -}; - -/** - * Shared state for our app. - */ -struct engine { - struct android_app* app; - - ASensorManager* sensorManager; - const ASensor* accelerometerSensor; - ASensorEventQueue* sensorEventQueue; - - int animating; - EGLDisplay display; - EGLSurface surface; - EGLContext context; - int32_t width; - int32_t height; - struct saved_state state; -}; - -static bool isContentRectChanged = false; -static std::chrono::steady_clock::time_point timeRectChanged; - -static struct engine engine; - -static char* editboxText = NULL; -extern EditTextCallback s_pfEditTextCallback; -extern void* s_ctx; - -extern "C" { - JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetEditTextDialogResult(JNIEnv * env, jobject obj, jbyteArray text) { - jsize size = env->GetArrayLength(text); - pthread_mutex_lock(&(engine.app->mutex)); - if (size > 0) { - jbyte * data = (jbyte*)env->GetByteArrayElements(text, 0); - char* pBuf = (char*)malloc(size+1); - if (pBuf != NULL) { - memcpy(pBuf, data, size); - pBuf[size] = '\0'; - editboxText = pBuf; - } - env->ReleaseByteArrayElements(text, data, 0); - - } else { - char* pBuf = (char*)malloc(1); - pBuf[0] = '\0'; - editboxText = pBuf; - } - pthread_cond_broadcast(&engine.app->cond); - pthread_mutex_unlock(&(engine.app->mutex)); - } -} - -typedef struct cocos_dimensions { - int w; - int h; -} cocos_dimensions; - -static void cocos_init(cocos_dimensions d, struct android_app* app) -{ - LOGI("cocos_init(...)"); - pthread_t thisthread = pthread_self(); - LOGI("pthread_self() = %X", thisthread); - - cocos2d::FileUtilsAndroid::setassetmanager(app->activity->assetManager); - - auto director = cocos2d::Director::getInstance(); - auto glview = director->getOpenGLView(); - if (!glview) - { - glview = cocos2d::GLView::create("Android app"); - glview->setFrameSize(d.w, d.h); - director->setOpenGLView(glview); - - cocos_android_app_init(app); - - cocos2d::Application::getInstance()->run(); - } - else - { - cocos2d::GL::invalidateStateCache(); - cocos2d::ShaderCache::getInstance()->reloadDefaultShaders(); - cocos2d::DrawPrimitives::init(); - cocos2d::VolatileTextureMgr::reloadAllTextures(); - - cocos2d::EventCustom foregroundEvent(EVENT_COME_TO_FOREGROUND); - director->getEventDispatcher()->dispatchEvent(&foregroundEvent); - director->setGLDefaultValues(); - } -} - -/** - * Initialize an EGL context for the current display. - */ -static cocos_dimensions engine_init_display(struct engine* engine) -{ - cocos_dimensions r; - r.w = -1; - r.h = -1; - - // initialize OpenGL ES and EGL - - /* - * Here specify the attributes of the desired configuration. - * Below, we select an EGLConfig with at least 8 bits per color - * component compatible with on-screen windows - */ - const EGLint attribs[] = { - EGL_SURFACE_TYPE, EGL_WINDOW_BIT, - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - EGL_BLUE_SIZE, 5, - EGL_GREEN_SIZE, 6, - EGL_RED_SIZE, 5, - EGL_DEPTH_SIZE, 16, - EGL_STENCIL_SIZE, 8, - EGL_NONE - }; - EGLint w, h, dummy, format; - EGLint numConfigs; - EGLConfig config; - EGLSurface surface; - EGLContext context; - - EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); - - eglInitialize(display, 0, 0); - - /* Here, the application chooses the configuration it desires. In this - * sample, we have a very simplified selection process, where we pick - * the first EGLConfig that matches our criteria */ - eglChooseConfig(display, attribs, &config, 1, &numConfigs); - - /* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is - * guaranteed to be accepted by ANativeWindow_setBuffersGeometry(). - * As soon as we picked a EGLConfig, we can safely reconfigure the - * ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. */ - eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format); - - ANativeWindow_setBuffersGeometry(engine->app->window, 0, 0, format); - - surface = eglCreateWindowSurface(display, config, engine->app->window, NULL); - - const EGLint eglContextAttrs[] = - { - EGL_CONTEXT_CLIENT_VERSION, 2, - EGL_NONE - }; - - context = eglCreateContext(display, config, NULL, eglContextAttrs); - - if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) { - LOGW("Unable to eglMakeCurrent"); - return r; - } - - eglQuerySurface(display, surface, EGL_WIDTH, &w); - eglQuerySurface(display, surface, EGL_HEIGHT, &h); - - engine->display = display; - engine->context = context; - engine->surface = surface; - engine->width = w; - engine->height = h; - engine->state.angle = 0; - - r.w = w; - r.h = h; - - - return r; -} - -/** - * Invoke the dispatching of the next bunch of Runnables in the Java-Land - */ -static bool s_methodInitialized = false; -static void dispatch_pending_runnables() { - static cocos2d::JniMethodInfo info; - - if (!s_methodInitialized) { - s_methodInitialized = cocos2d::JniHelper::getStaticMethodInfo( - info, - "org/cocos2dx/lib/Cocos2dxHelper", - "dispatchPendingRunnables", - "()V" - ); - - if (!s_methodInitialized) { - LOGW("Unable to dispatch pending Runnables!"); - return; - } - } - - info.env->CallStaticVoidMethod(info.classID, info.methodID); -} - -/** - * Just the current frame in the display. - */ -static void engine_draw_frame(struct engine* engine) -{ - LOG_RENDER_DEBUG("engine_draw_frame(...)"); - pthread_t thisthread = pthread_self(); - LOG_RENDER_DEBUG("pthread_self() = %X", thisthread); - - if (engine->display == NULL) { - // No display. - LOGW("engine_draw_frame : No display."); - return; - } - - dispatch_pending_runnables(); - cocos2d::Director::getInstance()->mainLoop(); - LOG_RENDER_DEBUG("engine_draw_frame : just called cocos' mainLoop()"); - - /* // Just fill the screen with a color. */ - /* glClearColor(((float)engine->state.x)/engine->width, engine->state.angle, */ - /* ((float)engine->state.y)/engine->height, 1); */ - /* glClear(GL_COLOR_BUFFER_BIT); */ - - if (s_pfEditTextCallback && editboxText) - { - s_pfEditTextCallback(editboxText, s_ctx); - free(editboxText); - editboxText = NULL; - } - - eglSwapBuffers(engine->display, engine->surface); -} - -/** - * Tear down the EGL context currently associated with the display. - */ -static void engine_term_display(struct engine* engine) -{ - if (engine->display != EGL_NO_DISPLAY) { - eglMakeCurrent(engine->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); - if (engine->context != EGL_NO_CONTEXT) { - eglDestroyContext(engine->display, engine->context); - } - if (engine->surface != EGL_NO_SURFACE) { - eglDestroySurface(engine->display, engine->surface); - } - eglTerminate(engine->display); - } - engine->animating = 0; - engine->display = EGL_NO_DISPLAY; - engine->context = EGL_NO_CONTEXT; - engine->surface = EGL_NO_SURFACE; -} - -/* - * Get X, Y positions and ID's for all pointers - */ -static void getTouchPos(AInputEvent *event, int ids[], float xs[], float ys[]) { - int pointerCount = AMotionEvent_getPointerCount(event); - for(int i = 0; i < pointerCount; ++i) { - ids[i] = AMotionEvent_getPointerId(event, i); - xs[i] = AMotionEvent_getX(event, i); - ys[i] = AMotionEvent_getY(event, i); - } -} - -/* - * Handle Touch Inputs - */ -static int32_t handle_touch_input(AInputEvent *event) { - - pthread_t thisthread = pthread_self(); - LOG_EVENTS_DEBUG("handle_touch_input(%X), pthread_self() = %X", event, thisthread); - - switch(AMotionEvent_getAction(event) & - AMOTION_EVENT_ACTION_MASK) { - - case AMOTION_EVENT_ACTION_DOWN: - { - LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_DOWN"); - int pointerId = AMotionEvent_getPointerId(event, 0); - float xP = AMotionEvent_getX(event,0); - float yP = AMotionEvent_getY(event,0); - - LOG_EVENTS_DEBUG("Event: Action DOWN x=%f y=%f pointerID=%d\n", - xP, yP, pointerId); - float x = xP; - float y = yP; - - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, &pointerId, &x, &y); - return 1; - } - break; - - case AMOTION_EVENT_ACTION_POINTER_DOWN: - { - LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_POINTER_DOWN"); - int pointerIndex = AMotionEvent_getAction(event) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; - int pointerId = AMotionEvent_getPointerId(event, pointerIndex); - float xP = AMotionEvent_getX(event,pointerIndex); - float yP = AMotionEvent_getY(event,pointerIndex); - - LOG_EVENTS_DEBUG("Event: Action POINTER DOWN x=%f y=%f pointerID=%d\n", - xP, yP, pointerId); - float x = xP; - float y = yP; - - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, &pointerId, &x, &y); - return 1; - } - break; - - case AMOTION_EVENT_ACTION_MOVE: - { - LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_MOVE"); - int pointerCount = AMotionEvent_getPointerCount(event); - int ids[pointerCount]; - float xs[pointerCount], ys[pointerCount]; - getTouchPos(event, ids, xs, ys); - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(pointerCount, ids, xs, ys); - return 1; - } - break; - - case AMOTION_EVENT_ACTION_UP: - { - LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_UP"); - int pointerId = AMotionEvent_getPointerId(event, 0); - float xP = AMotionEvent_getX(event,0); - float yP = AMotionEvent_getY(event,0); - LOG_EVENTS_DEBUG("Event: Action UP x=%f y=%f pointerID=%d\n", - xP, yP, pointerId); - float x = xP; - float y = yP; - - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, &pointerId, &x, &y); - return 1; - } - break; - - case AMOTION_EVENT_ACTION_POINTER_UP: - { - LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_POINTER_UP"); - int pointerIndex = AMotionEvent_getAction(event) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; - int pointerId = AMotionEvent_getPointerId(event, pointerIndex); - float xP = AMotionEvent_getX(event,pointerIndex); - float yP = AMotionEvent_getY(event,pointerIndex); - LOG_EVENTS_DEBUG("Event: Action POINTER UP x=%f y=%f pointerID=%d\n", - xP, yP, pointerIndex); - float x = xP; - float y = yP; - - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, &pointerId, &x, &y); - return 1; - } - break; - - case AMOTION_EVENT_ACTION_CANCEL: - { - LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_CANCEL"); - int pointerCount = AMotionEvent_getPointerCount(event); - int ids[pointerCount]; - float xs[pointerCount], ys[pointerCount]; - getTouchPos(event, ids, xs, ys); - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesCancel(pointerCount, ids, xs, ys); - return 1; - } - break; - - default: - LOG_EVENTS_DEBUG("handle_touch_input() default case.... NOT HANDLE"); - return 0; - break; - } -} - -/* -* Handle Key Inputs -*/ -static int32_t handle_key_input(AInputEvent *event) -{ - if (AKeyEvent_getAction(event) == AKEY_EVENT_ACTION_UP) - { - auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher(); - - switch (AKeyEvent_getKeyCode(event)) - { - case AKEYCODE_BACK: - { - cocos2d::EventKeyboard event(cocos2d::EventKeyboard::KeyCode::KEY_BACKSPACE, false); - dispatcher->dispatchEvent(&event); - } - return 1; - case AKEYCODE_MENU: - { - cocos2d::EventKeyboard event(cocos2d::EventKeyboard::KeyCode::KEY_MENU, false); - dispatcher->dispatchEvent(&event); - } - return 1; - default: - break; - } - } - return 0; -} - -/** - * Process the next input event. - */ -static int32_t engine_handle_input(struct android_app* app, AInputEvent* event) { - - pthread_t thisthread = pthread_self(); - LOG_EVENTS_DEBUG("engine_handle_input(%X, %X), pthread_self() = %X", app, event, thisthread); - - struct engine* engine = (struct engine*)app->userData; - - if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) { - engine->animating = 1; - engine->state.x = AMotionEvent_getX(event, 0); - engine->state.y = AMotionEvent_getY(event, 0); - - return handle_touch_input(event); - } - else - return handle_key_input(event); - - return 0; -} - -void enableAccelerometerJni(void) { - LOGI("enableAccelerometerJni()"); - - if (engine.accelerometerSensor != NULL) { - ASensorEventQueue_enableSensor(engine.sensorEventQueue, - engine.accelerometerSensor); - - // Set a default sample rate - // We'd like to get 60 events per second (in us). - ASensorEventQueue_setEventRate(engine.sensorEventQueue, - engine.accelerometerSensor, (1000L/60)*1000); - } -} - -void disableAccelerometerJni(void) { - LOGI("disableAccelerometerJni()"); - - if (engine.accelerometerSensor != NULL) { - ASensorEventQueue_disableSensor(engine.sensorEventQueue, - engine.accelerometerSensor); - } -} - -void setAccelerometerIntervalJni(float interval) { - LOGI("setAccelerometerIntervalJni(%f)", interval); - // We'd like to get 60 events per second (in us). - ASensorEventQueue_setEventRate(engine.sensorEventQueue, - engine.accelerometerSensor, interval * 1000000L); -} - -/** - * Process the next main command. - */ -static void engine_handle_cmd(struct android_app* app, int32_t cmd) -{ - struct engine* engine = (struct engine*)app->userData; - switch (cmd) { - case APP_CMD_SAVE_STATE: - // The system has asked us to save our current state. Do so. - engine->app->savedState = malloc(sizeof(struct saved_state)); - *((struct saved_state*)engine->app->savedState) = engine->state; - engine->app->savedStateSize = sizeof(struct saved_state); - break; - case APP_CMD_INIT_WINDOW: - // The window is being shown, get it ready. - if (engine->app->window != NULL) { - cocos_dimensions d = engine_init_display(engine); - if ((d.w > 0) && - (d.h > 0)) { - cocos2d::JniHelper::setJavaVM(app->activity->vm); - cocos2d::JniHelper::setClassLoaderFrom(app->activity->clazz); - - // call Cocos2dxHelper.init() - cocos2d::JniMethodInfo ccxhelperInit; - if (!cocos2d::JniHelper::getStaticMethodInfo(ccxhelperInit, - "org/cocos2dx/lib/Cocos2dxHelper", - "init", - "(Landroid/app/Activity;)V")) { - LOGI("cocos2d::JniHelper::getStaticMethodInfo(ccxhelperInit) FAILED"); - } - ccxhelperInit.env->CallStaticVoidMethod(ccxhelperInit.classID, - ccxhelperInit.methodID, - app->activity->clazz); - - cocos_init(d, app); - } - engine->animating = 1; - engine_draw_frame(engine); - } - break; - case APP_CMD_TERM_WINDOW: - // The window is being hidden or closed, clean it up. - engine_term_display(engine); - break; - case APP_CMD_RESUME: - if (cocos2d::Director::getInstance()->getOpenGLView()) { - cocos2d::Application::getInstance()->applicationWillEnterForeground(); - if (engine->display != nullptr) - { - engine->animating = 1; - } - } - break; - case APP_CMD_PAUSE: - { - cocos2d::Application::getInstance()->applicationDidEnterBackground(); - cocos2d::EventCustom backgroundEvent(EVENT_COME_TO_BACKGROUND); - cocos2d::Director::getInstance()->getEventDispatcher()->dispatchEvent(&backgroundEvent); - // Also stop animating. - engine->animating = 0; - engine_draw_frame(engine); - } - break; - } -} - -static void onContentRectChanged(ANativeActivity* activity, const ARect* rect) { - timeRectChanged = std::chrono::steady_clock::now(); - isContentRectChanged = true; -} - -static void process_input(struct android_app* app, struct android_poll_source* source) -{ - AInputEvent* event = NULL; - while (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); - } -} -/** - * 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 - * event loop for receiving input events and doing other things. - */ -void android_main(struct android_app* state) { - - // Make sure glue isn't stripped. - app_dummy(); - - memset(&engine, 0, sizeof(engine)); - state->userData = &engine; - state->onAppCmd = engine_handle_cmd; - state->onInputEvent = engine_handle_input; - state->inputPollSource.process = process_input; - engine.app = state; - - // Prepare to monitor accelerometer - engine.sensorManager = ASensorManager_getInstance(); - engine.accelerometerSensor = ASensorManager_getDefaultSensor(engine.sensorManager, - ASENSOR_TYPE_ACCELEROMETER); - engine.sensorEventQueue = ASensorManager_createEventQueue(engine.sensorManager, - state->looper, LOOPER_ID_USER, NULL, NULL); - - if (state->savedState != NULL) { - // We are starting with a previous saved state; restore from it. - engine.state = *(struct saved_state*)state->savedState; - } - - // Screen size change support - state->activity->callbacks->onContentRectChanged = onContentRectChanged; - - // loop waiting for stuff to do. - - while (1) { - // Read all pending events. - int ident; - int events; - struct android_poll_source* source; - - // If not animating, we will block forever waiting for events. - // If animating, we loop until all events are read, then continue - // to draw the next frame of animation. - while ((ident=ALooper_pollAll(engine.animating ? 0 : -1, NULL, &events, - (void**)&source)) >= 0) { - - // Process this event. - if (source != NULL) { - source->process(state, source); - } - - // If a sensor has data, process it now. - if (ident == LOOPER_ID_USER) { - if (engine.accelerometerSensor != NULL) { - ASensorEvent event; - while (ASensorEventQueue_getEvents(engine.sensorEventQueue, - &event, 1) > 0) { - - LOG_EVENTS_DEBUG("accelerometer: x=%f y=%f z=%f", - event.acceleration.x, event.acceleration.y, - event.acceleration.z); - - AConfiguration* _currentconf = AConfiguration_new(); - AConfiguration_fromAssetManager(_currentconf, - state->activity->assetManager); - static int32_t _orientation = AConfiguration_getOrientation(_currentconf); - - if (ACONFIGURATION_ORIENTATION_LAND != _orientation) { - // ACONFIGURATION_ORIENTATION_ANY - // ACONFIGURATION_ORIENTATION_PORT - // ACONFIGURATION_ORIENTATION_SQUARE - cocos2d::Acceleration acc; - acc.x = -event.acceleration.x/10; - acc.y = -event.acceleration.y/10; - acc.z = event.acceleration.z/10; - acc.timestamp = 0; - cocos2d::EventAcceleration accEvent(acc); - auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher(); - dispatcher->dispatchEvent(&accEvent); - } else { - // ACONFIGURATION_ORIENTATION_LAND - // swap x and y parameters - cocos2d::Acceleration acc; - acc.x = event.acceleration.y/10; - acc.y = -event.acceleration.x/10; - acc.z = event.acceleration.z/10; - acc.timestamp = 0; - cocos2d::EventAcceleration accEvent(acc); - auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher(); - dispatcher->dispatchEvent(&accEvent); - } - } - } - } - - // Check if we are exiting. - if (state->destroyRequested != 0) { - engine_term_display(&engine); - - memset(&engine, 0, sizeof(engine)); - s_methodInitialized = false; - return; - } - } - - if (engine.animating) { - // Done with events; draw next animation frame. - engine.state.angle += .01f; - if (engine.state.angle > 1) { - engine.state.angle = 0; - } - - // Drawing is throttled to the screen update rate, so there - // is no need to do timing here. - LOG_RENDER_DEBUG("android_main : engine.animating"); - engine_draw_frame(&engine); - } else { - LOG_RENDER_DEBUG("android_main : !engine.animating"); - } - - // Check if screen size changed - if (isContentRectChanged) { - std::chrono::duration duration( - std::chrono::duration_cast>(std::chrono::steady_clock::now() - timeRectChanged)); - - // Wait about 30 ms to get new width and height. Without waiting we can get old values sometime - if (duration.count() > 30) { - isContentRectChanged = false; - - int32_t newWidth = ANativeWindow_getWidth(engine.app->window); - int32_t newHeight = ANativeWindow_getHeight(engine.app->window); - cocos2d::Application::getInstance()->applicationScreenSizeChanged(newWidth, newHeight); - } - } - } -} - -#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID diff --git a/tests/cpp-empty-test/proj.android/AndroidManifest.xml b/tests/cpp-empty-test/proj.android/AndroidManifest.xml index db79f67eca..d0853e6160 100644 --- a/tests/cpp-empty-test/proj.android/AndroidManifest.xml +++ b/tests/cpp-empty-test/proj.android/AndroidManifest.xml @@ -8,18 +8,18 @@ + android:icon="@drawable/icon"> - + + + - - - diff --git a/tests/cpp-empty-test/proj.android/jni/main.cpp b/tests/cpp-empty-test/proj.android/jni/main.cpp index 2b344d9e04..feab560c09 100644 --- a/tests/cpp-empty-test/proj.android/jni/main.cpp +++ b/tests/cpp-empty-test/proj.android/jni/main.cpp @@ -10,7 +10,7 @@ using namespace cocos2d; -void cocos_android_app_init (struct android_app* app) { +void cocos_android_app_init (JNIEnv* env, jobject thiz) { LOGD("cocos_android_app_init"); AppDelegate *pAppDelegate = new AppDelegate(); } diff --git a/cocos/2d/platform/android/nativeactivity.h b/tests/cpp-empty-test/proj.android/src/org/cocos2dx/cpp_empty_test/AppActivity.java similarity index 71% rename from cocos/2d/platform/android/nativeactivity.h rename to tests/cpp-empty-test/proj.android/src/org/cocos2dx/cpp_empty_test/AppActivity.java index ccd03cb149..3b0cbf5b8e 100644 --- a/cocos/2d/platform/android/nativeactivity.h +++ b/tests/cpp-empty-test/proj.android/src/org/cocos2dx/cpp_empty_test/AppActivity.java @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2013-2014 Chukong Technologies Inc. +Copyright (c) 2010-2012 cocos2d-x.org http://www.cocos2d-x.org @@ -21,20 +21,9 @@ 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 __COCOSNATIVEACTIVITY_H__ -#define __COCOSNATIVEACTIVITY_H__ +package org.cocos2dx.cpp_empty_test; -#include "CCPlatformConfig.h" -#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID +import org.cocos2dx.lib.Cocos2dxActivity; -/** - * This is the interface to the Android native activity - */ - -void enableAccelerometerJni(void); -void disableAccelerometerJni(void); -void setAccelerometerIntervalJni(float interval); - -#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID - -#endif // __COCOSNATIVEACTIVITY_H__ +public class AppActivity extends Cocos2dxActivity { +} diff --git a/tests/cpp-empty-test/proj.android/src/org/cocos2dx/cpp_empty_test/Cocos2dxActivity.java b/tests/cpp-empty-test/proj.android/src/org/cocos2dx/cpp_empty_test/Cocos2dxActivity.java deleted file mode 100644 index d2b8e642dd..0000000000 --- a/tests/cpp-empty-test/proj.android/src/org/cocos2dx/cpp_empty_test/Cocos2dxActivity.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.cocos2dx.cpp_empty_test; - -import android.app.NativeActivity; -import android.os.Bundle; - -public class Cocos2dxActivity extends NativeActivity{ - - @Override - protected void onCreate(Bundle savedInstanceState) { - // TODO Auto-generated method stub - super.onCreate(savedInstanceState); - - //For supports translucency - - //1.change "attribs" in cocos\2d\platform\android\nativeactivity.cpp - /*const EGLint attribs[] = { - EGL_SURFACE_TYPE, EGL_WINDOW_BIT, - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - //EGL_BLUE_SIZE, 5, -->delete - //EGL_GREEN_SIZE, 6, -->delete - //EGL_RED_SIZE, 5, -->delete - EGL_BUFFER_SIZE, 32, //-->new field - EGL_DEPTH_SIZE, 16, - EGL_STENCIL_SIZE, 8, - EGL_NONE - };*/ - - //2.Set the format of window - // getWindow().setFormat(PixelFormat.TRANSLUCENT); - - } -} diff --git a/tests/cpp-tests/proj.android/AndroidManifest.xml b/tests/cpp-tests/proj.android/AndroidManifest.xml index 36b422af01..f47f0c139f 100644 --- a/tests/cpp-tests/proj.android/AndroidManifest.xml +++ b/tests/cpp-tests/proj.android/AndroidManifest.xml @@ -9,18 +9,18 @@ + android:icon="@drawable/icon"> - + + + - - - diff --git a/tests/cpp-tests/proj.android/jni/main.cpp b/tests/cpp-tests/proj.android/jni/main.cpp index a8b36b317d..980411792f 100644 --- a/tests/cpp-tests/proj.android/jni/main.cpp +++ b/tests/cpp-tests/proj.android/jni/main.cpp @@ -10,7 +10,7 @@ using namespace cocos2d; -void cocos_android_app_init (struct android_app* app) { +void cocos_android_app_init (JNIEnv* env, jobject thiz) { LOGD("cocos_android_app_init"); AppDelegate *pAppDelegate = new AppDelegate(); } diff --git a/tests/cpp-tests/proj.android/src/org/cocos2dx/cpp_tests/AppActivity.java b/tests/cpp-tests/proj.android/src/org/cocos2dx/cpp_tests/AppActivity.java new file mode 100644 index 0000000000..0143698c6b --- /dev/null +++ b/tests/cpp-tests/proj.android/src/org/cocos2dx/cpp_tests/AppActivity.java @@ -0,0 +1,29 @@ +/**************************************************************************** +Copyright (c) 2010-2012 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. +****************************************************************************/ +package org.cocos2dx.cpp_tests; + +import org.cocos2dx.lib.Cocos2dxActivity; + +public class AppActivity extends Cocos2dxActivity { +} diff --git a/tests/cpp-tests/proj.android/src/org/cocos2dx/cpp_tests/Cocos2dxActivity.java b/tests/cpp-tests/proj.android/src/org/cocos2dx/cpp_tests/Cocos2dxActivity.java deleted file mode 100644 index 1367d2e7c6..0000000000 --- a/tests/cpp-tests/proj.android/src/org/cocos2dx/cpp_tests/Cocos2dxActivity.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.cocos2dx.cpp_tests; - -import android.app.NativeActivity; -import android.os.Bundle; - -public class Cocos2dxActivity extends NativeActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - // TODO Auto-generated method stub - super.onCreate(savedInstanceState); - - //For supports translucency - - //1.change "attribs" in cocos\2d\platform\android\nativeactivity.cpp - /*const EGLint attribs[] = { - EGL_SURFACE_TYPE, EGL_WINDOW_BIT, - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - //EGL_BLUE_SIZE, 5, -->delete - //EGL_GREEN_SIZE, 6, -->delete - //EGL_RED_SIZE, 5, -->delete - EGL_BUFFER_SIZE, 32, //-->new field - EGL_DEPTH_SIZE, 16, - EGL_STENCIL_SIZE, 8, - EGL_NONE - };*/ - - //2.Set the format of window - // getWindow().setFormat(PixelFormat.TRANSLUCENT); - - } -} From b074890b57f05c29aeab93a0178d5652632de103 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Tue, 25 Mar 2014 10:57:44 +0800 Subject: [PATCH 050/106] update test case --- .../Classes/LabelTest/LabelTestNew.cpp | 72 +++---------------- 1 file changed, 8 insertions(+), 64 deletions(-) diff --git a/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp b/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp index 01b5cb1335..07b99b5306 100644 --- a/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp +++ b/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp @@ -174,17 +174,14 @@ LabelTTFAlignmentNew::LabelTTFAlignmentNew() auto ttf0 = Label::createWithTTF(config,"Alignment 0\nnew line",TextHAlignment::LEFT); ttf0->setPosition(Point(s.width/2,(s.height/6)*2 - 30)); - ttf0->setAnchorPoint(Point::ANCHOR_MIDDLE); this->addChild(ttf0); auto ttf1 = Label::createWithTTF(config,"Alignment 1\nnew line",TextHAlignment::CENTER); ttf1->setPosition(Point(s.width/2,(s.height/6)*3 - 30)); - ttf1->setAnchorPoint(Point::ANCHOR_MIDDLE); this->addChild(ttf1); auto ttf2 = Label::createWithTTF(config,"Alignment 2\nnew line",TextHAlignment::RIGHT); ttf2->setPosition(Point(s.width/2,(s.height/6)*4 - 30)); - ttf2->setAnchorPoint(Point::ANCHOR_MIDDLE); this->addChild(ttf2); } @@ -216,7 +213,6 @@ LabelFNTColorAndOpacity::LabelFNTColorAndOpacity() label1->runAction(repeat); auto label2 = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "Test"); - label2->setAnchorPoint( Point::ANCHOR_MIDDLE ); label2->setColor( Color3B::RED ); addChild(label2, 0, kTagBitmapAtlas2); auto tint = Sequence::create(TintTo::create(1, 255, 0, 0), @@ -272,9 +268,7 @@ LabelFNTSpriteActions::LabelFNTSpriteActions() auto s = Director::getInstance()->getWinSize(); - label->setPosition( Point(s.width/2, s.height/2) ); - label->setAnchorPoint( Point::ANCHOR_MIDDLE ); - + label->setPosition( Point(s.width/2, s.height/2) ); auto BChar = (Sprite*) label->getLetter(0); auto FChar = (Sprite*) label->getLetter(7); @@ -307,7 +301,6 @@ LabelFNTSpriteActions::LabelFNTSpriteActions() auto label2 = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "00.0"); addChild(label2, 0, kTagBitmapAtlas2); label2->setPosition( Point(s.width/2.0f, 80) ); - label2->setAnchorPoint( Point::ANCHOR_MIDDLE ); auto lastChar = (Sprite*) label2->getLetter(3); lastChar->runAction( rot_4ever->clone() ); @@ -362,7 +355,6 @@ LabelFNTPadding::LabelFNTPadding() auto s = Director::getInstance()->getWinSize(); label->setPosition( Point(s.width/2, s.height/2) ); - label->setAnchorPoint( Point::ANCHOR_MIDDLE ); } std::string LabelFNTPadding::title() const @@ -379,21 +371,18 @@ LabelFNTOffset::LabelFNTOffset() { auto s = Director::getInstance()->getWinSize(); - Label* label = NULL; + Label* label = nullptr; label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "FaFeFiFoFu"); addChild(label); label->setPosition( Point(s.width/2, s.height/2+50) ); - label->setAnchorPoint( Point::ANCHOR_MIDDLE ) ; label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "fafefifofu"); addChild(label); label->setPosition( Point(s.width/2, s.height/2) ); - label->setAnchorPoint( Point::ANCHOR_MIDDLE ); label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "aeiou"); addChild(label); label->setPosition( Point(s.width/2, s.height/2-50) ); - label->setAnchorPoint( Point::ANCHOR_MIDDLE ); } std::string LabelFNTOffset::title() const @@ -410,23 +399,20 @@ LabelFNTColor::LabelFNTColor() { auto s = Director::getInstance()->getWinSize(); - Label* label = NULL; + Label* label = nullptr; label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "Blue"); label->setColor( Color3B::BLUE ); addChild(label); label->setPosition( Point(s.width/2, s.height/4) ); - label->setAnchorPoint( Point::ANCHOR_MIDDLE ); label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "Red"); addChild(label); label->setPosition( Point(s.width/2, 2*s.height/4) ); - label->setAnchorPoint( Point::ANCHOR_MIDDLE ); label->setColor( Color3B::RED ); label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "Green"); addChild(label); label->setPosition( Point(s.width/2, 3*s.height/4) ); - label->setAnchorPoint( Point::ANCHOR_MIDDLE ); label->setColor( Color3B::GREEN ); label->setString("Green"); } @@ -455,7 +441,6 @@ LabelFNTHundredLabels::LabelFNTHundredLabels() auto p = Point( CCRANDOM_0_1() * s.width, CCRANDOM_0_1() * s.height); label->setPosition( p ); - label->setAnchorPoint(Point::ANCHOR_MIDDLE); } } @@ -484,7 +469,6 @@ LabelFNTMultiLine::LabelFNTMultiLine() // Center auto label2 = Label::createWithBMFont( "fonts/bitmapFontTest3.fnt", "Multi line\nCenter"); - label2->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label2, 0, kTagBitmapAtlas2); s= label2->getContentSize(); @@ -520,18 +504,15 @@ LabelFNTandTTFEmpty::LabelFNTandTTFEmpty() // LabelBMFont auto label1 = Label::createWithBMFont("fonts/bitmapFontTest3.fnt", "", TextHAlignment::CENTER, s.width); addChild(label1, 0, kTagBitmapAtlas1); - label1->setAnchorPoint(Point::ANCHOR_MIDDLE); label1->setPosition(Point(s.width/2, s.height - 100)); // LabelTTF TTFConfig ttfConfig("fonts/arial.ttf",24); auto label2 = Label::createWithTTF(ttfConfig,"", TextHAlignment::CENTER,s.width); addChild(label2, 0, kTagBitmapAtlas2); - label2->setAnchorPoint(Point::ANCHOR_MIDDLE); label2->setPosition(Point(s.width/2, s.height / 2)); auto label3 = Label::createWithCharMap("fonts/tuffy_bold_italic-charmap.png", 48, 64, ' '); - label3->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label3, 0, kTagBitmapAtlas3); label3->setPosition(Point(s.width/2, 100)); @@ -580,7 +561,6 @@ LabelFNTRetina::LabelFNTRetina() // LabelBMFont auto label1 = Label::createWithBMFont("fonts/konqa32.fnt", "TESTING RETINA DISPLAY"); - label1->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label1); label1->setPosition(Point(s.width/2, s.height/2)); } @@ -604,7 +584,6 @@ LabelFNTGlyphDesigner::LabelFNTGlyphDesigner() // LabelBMFont auto label1 = Label::createWithBMFont("fonts/futura-48.fnt", "Testing Glyph Designer"); - label1->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label1); label1->setPosition(Point(s.width/2, s.height/2)); } @@ -626,7 +605,6 @@ LabelTTFUnicodeChinese::LabelTTFUnicodeChinese() // like "Error 3 error C2146: syntax error : missing ')' before identifier 'label'"; TTFConfig ttfConfig("fonts/wt021.ttf",28,GlyphCollection::CUSTOM, "美好的一天啊"); auto label = Label::createWithTTF(ttfConfig,"美好的一天啊", TextHAlignment::CENTER, size.width); - label->setAnchorPoint(Point::ANCHOR_MIDDLE); label->setPosition(Point(size.width / 2, size.height /2)); this->addChild(label); } @@ -645,7 +623,6 @@ LabelFNTUnicodeChinese::LabelFNTUnicodeChinese() { auto size = Director::getInstance()->getWinSize(); auto label = Label::createWithBMFont("fonts/bitmapFontChinese.fnt", "中国"); - label->setAnchorPoint(Point::ANCHOR_MIDDLE); label->setPosition(Point(size.width / 2, size.height /2)); this->addChild(label); } @@ -694,7 +671,6 @@ LabelFNTMultiLineAlignment::LabelFNTMultiLineAlignment() // create and initialize a Label this->_labelShouldRetain = Label::createWithBMFont("fonts/markerFelt.fnt", LongSentencesExample, TextHAlignment::CENTER, size.width/1.5); - this->_labelShouldRetain->setAnchorPoint(Point::ANCHOR_MIDDLE); this->_labelShouldRetain->retain(); this->_arrowsBarShouldRetain = Sprite::create("Images/arrowsBar.png"); @@ -878,22 +854,18 @@ LabelFNTUNICODELanguages::LabelFNTUNICODELanguages() auto label1 = Label::createWithBMFont("fonts/arial-unicode-26.fnt", spanish, TextHAlignment::CENTER, 200); addChild(label1); - label1->setAnchorPoint(Point::ANCHOR_MIDDLE); label1->setPosition(Point(s.width/2, s.height/5*3)); auto label2 = Label::createWithBMFont("fonts/arial-unicode-26.fnt", chinese); addChild(label2); - label2->setAnchorPoint(Point::ANCHOR_MIDDLE); label2->setPosition(Point(s.width/2, s.height/5*2.5)); auto label3 = Label::createWithBMFont("fonts/arial-26-en-ru.fnt", russian); addChild(label3); - label3->setAnchorPoint(Point::ANCHOR_MIDDLE); label3->setPosition(Point(s.width/2, s.height/5*2)); auto label4 = Label::createWithBMFont("fonts/arial-unicode-26.fnt", japanese); addChild(label4); - label4->setAnchorPoint(Point::ANCHOR_MIDDLE); label4->setPosition(Point(s.width/2, s.height/5*1.5)); } @@ -916,7 +888,6 @@ LabelFNTBounds::LabelFNTBounds() // LabelBMFont label1 = Label::createWithBMFont("fonts/boundsTestFont.fnt", "Testing Glyph Designer", TextHAlignment::CENTER,s.width); - label1->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label1); label1->setPosition(Point(s.width/2, s.height/2)); } @@ -992,7 +963,6 @@ LabelTTFLargeText::LabelTTFLargeText() std::string text = FileUtils::getInstance()->getStringFromFile("commonly_used_words.txt"); auto label = Label::createWithTTF(ttfConfig,text, TextHAlignment::CENTER, size.width); label->setPosition( Point(size.width/2, size.height/2) ); - label->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label); } @@ -1013,23 +983,20 @@ LabelTTFColor::LabelTTFColor() TTFConfig ttfConfig("fonts/arial.ttf", 18); // Green auto label1 = Label::createWithTTF(ttfConfig,"Green", TextHAlignment::CENTER, size.width); - label1->setPosition( Point(size.width/2, size.height/5 * 1.5) ); + label1->setPosition( Point(size.width/2, size.height * 0.3f) ); label1->setTextColor( Color4B::GREEN ); - label1->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label1); // Red auto label2 = Label::createWithTTF(ttfConfig,"Red", TextHAlignment::CENTER, size.width); - label2->setPosition( Point(size.width/2, size.height/5 * 2.0) ); + label2->setPosition( Point(size.width/2, size.height * 0.4f) ); label2->setTextColor( Color4B::RED ); - label2->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label2); // Blue auto label3 = Label::createWithTTF(ttfConfig,"Blue", TextHAlignment::CENTER, size.width); - label3->setPosition( Point(size.width/2, size.height/5 * 2.5) ); + label3->setPosition( Point(size.width/2, size.height * 0.5f) ); label3->setTextColor( Color4B::BLUE ); - label3->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label3); } @@ -1048,8 +1015,7 @@ LabelTTFDynamicAlignment::LabelTTFDynamicAlignment() auto size = Director::getInstance()->getWinSize(); TTFConfig ttfConfig("fonts/arial.ttf", 23); _label = Label::createWithTTF(ttfConfig,LongSentencesExample, TextHAlignment::CENTER, size.width); - _label->setPosition( Point(size.width/2, size.height/2) ); - _label->setAnchorPoint(Point::ANCHOR_MIDDLE); + _label->setPosition( Point(size.width/2, size.height/2) ); auto menu = Menu::create( MenuItemFont::create("Left", CC_CALLBACK_1(LabelTTFDynamicAlignment::setAlignmentLeft, this)), @@ -1171,13 +1137,11 @@ LabelTTFUnicodeNew::LabelTTFUnicodeNew() // Spanish auto label1 = Label::createWithTTF(ttfConfig,"Buen día, ¿cómo te llamas?", TextHAlignment::CENTER, size.width); label1->setPosition( Point(size.width/2, vSize - (vStep * 4.5)) ); - label1->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label1); // German auto label2 = Label::createWithTTF(ttfConfig,"In welcher Straße haben Sie gelebt?", TextHAlignment::CENTER,size.width); label2->setPosition( Point(size.width/2, vSize - (vStep * 5.5)) ); - label2->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label2); // chinese @@ -1186,7 +1150,6 @@ LabelTTFUnicodeNew::LabelTTFUnicodeNew() ttfConfig.customGlyphs = chinese.c_str(); auto label3 = Label::createWithTTF(ttfConfig,chinese, TextHAlignment::CENTER,size.width); label3->setPosition( Point(size.width/2, vSize - (vStep * 6.5)) ); - label3->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label3); } @@ -1218,12 +1181,9 @@ LabelTTFFontsTestNew::LabelTTFFontsTestNew() for(size_t i=0;i < arraysize(ttfpaths); ++i) { ttfConfig.fontFilePath = ttfpaths[i]; auto label = Label::createWithTTF(ttfConfig, ttfpaths[i], TextHAlignment::CENTER,0); - if( label ) { - + if( label ) { label->setPosition( Point(size.width/2, ((size.height * 0.6)/arraysize(ttfpaths) * i) + (size.height/5))); addChild(label); - - label->setAnchorPoint(Point::ANCHOR_MIDDLE); } else { log("ERROR: Cannot load: %s", ttfpaths[i]); } @@ -1246,7 +1206,6 @@ LabelBMFontTestNew::LabelBMFontTestNew() auto label1 = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "Hello World, this is testing the new Label using fnt file", TextHAlignment::CENTER, size.width); label1->setPosition( Point(size.width/2, size.height/2) ); - label1->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label1); } @@ -1268,7 +1227,6 @@ LabelTTFDistanceField::LabelTTFDistanceField() auto label1 = Label::createWithTTF(ttfConfig,"Distance Field",TextHAlignment::CENTER,size.width); label1->setPosition( Point(size.width/2, size.height * 0.6f) ); label1->setTextColor( Color4B::GREEN ); - label1->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label1); auto action = Sequence::create( @@ -1281,9 +1239,7 @@ LabelTTFDistanceField::LabelTTFDistanceField() auto label2 = Label::createWithTTF(ttfConfig,"Distance Field",TextHAlignment::CENTER,size.width); label2->setPosition( Point(size.width/2, size.height * 0.3f) ); label2->setTextColor( Color4B::RED ); - label2->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label2); - } std::string LabelTTFDistanceField::title() const @@ -1308,7 +1264,6 @@ LabelOutlineAndGlowTest::LabelOutlineAndGlowTest() auto label1 = Label::createWithTTF(ttfConfig,"Glow", TextHAlignment::CENTER, size.width); label1->setPosition( Point(size.width/2, size.height*0.7) ); label1->setTextColor( Color4B::GREEN ); - label1->setAnchorPoint(Point::ANCHOR_MIDDLE); label1->enableGlow(Color4B::YELLOW); addChild(label1); @@ -1316,7 +1271,6 @@ LabelOutlineAndGlowTest::LabelOutlineAndGlowTest() auto label2 = Label::createWithTTF(ttfConfig,"Outline", TextHAlignment::CENTER, size.width); label2->setPosition( Point(size.width/2, size.height*0.6) ); label2->setTextColor( Color4B::RED ); - label2->setAnchorPoint(Point::ANCHOR_MIDDLE); label2->enableOutline(Color4B::BLUE); addChild(label2); @@ -1324,7 +1278,6 @@ LabelOutlineAndGlowTest::LabelOutlineAndGlowTest() auto label3 = Label::createWithTTF(ttfConfig,"Outline", TextHAlignment::CENTER, size.width); label3->setPosition( Point(size.width/2, size.height*0.48) ); label3->setTextColor( Color4B::RED ); - label3->setAnchorPoint(Point::ANCHOR_MIDDLE); label3->enableOutline(Color4B::BLUE); addChild(label3); @@ -1332,7 +1285,6 @@ LabelOutlineAndGlowTest::LabelOutlineAndGlowTest() auto label4 = Label::createWithTTF(ttfConfig,"Outline", TextHAlignment::CENTER, size.width); label4->setPosition( Point(size.width/2, size.height*0.36) ); label4->setTextColor( Color4B::RED ); - label4->setAnchorPoint(Point::ANCHOR_MIDDLE); label4->enableOutline(Color4B::BLUE); addChild(label4); } @@ -1359,14 +1311,12 @@ LabelShadowTest::LabelShadowTest() shadowLabelTTF = Label::createWithTTF(ttfConfig,"TTF:Shadow", TextHAlignment::CENTER, size.width); shadowLabelTTF->setPosition( Point(size.width/2, size.height*0.6f) ); shadowLabelTTF->setTextColor( Color4B::RED ); - shadowLabelTTF->setAnchorPoint(Point::ANCHOR_MIDDLE); shadowLabelTTF->enableShadow(Color4B::BLACK); addChild(shadowLabelTTF); shadowLabelBMFont = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "BMFont:Shadow"); shadowLabelBMFont->setPosition( Point(size.width/2, size.height*0.4f) ); shadowLabelBMFont->setColor( Color3B::RED ); - shadowLabelBMFont->setAnchorPoint(Point::ANCHOR_MIDDLE); shadowLabelBMFont->enableShadow(Color4B::GREEN); addChild(shadowLabelBMFont); @@ -1523,7 +1473,6 @@ LabelCrashTest::LabelCrashTest() auto label1 = Label::createWithTTF(ttfConfig,"Test崩溃123", TextHAlignment::CENTER, size.width); label1->setPosition( Point(size.width/2, size.height/2) ); - label1->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label1); } @@ -1544,14 +1493,12 @@ LabelTTFOldNew::LabelTTFOldNew() auto label1 = LabelTTF::create("Cocos2d-x Label Test", "arial", 24); addChild(label1, 0, kTagBitmapAtlas1); - label1->setAnchorPoint(Point::ANCHOR_MIDDLE); label1->setPosition(Point(s.width/2, delta * 2)); label1->setColor(Color3B::RED); TTFConfig ttfConfig("fonts/arial.ttf", 24); auto label2 = Label::createWithTTF(ttfConfig, "Cocos2d-x Label Test"); addChild(label2, 0, kTagBitmapAtlas2); - label2->setAnchorPoint(Point::ANCHOR_MIDDLE); label2->setPosition(Point(s.width/2, delta * 2)); } @@ -1621,7 +1568,6 @@ LabelFontNameTest::LabelFontNameTest() auto label1 = Label::create(); label1->setString("Default Font"); label1->setPosition( Point(size.width/2, size.height * 0.7) ); - label1->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label1); FontDefinition fontDef; @@ -1629,12 +1575,10 @@ LabelFontNameTest::LabelFontNameTest() fontDef._fontSize = 32; auto label2 = Label::createWithFontDefinition("Create with FontDefinition",fontDef); label2->setPosition( Point(size.width/2, size.height * 0.6) ); - label2->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label2); auto label3 = Label::create("Marker Felt","Marker Felt",32); label3->setPosition( Point(size.width/2, size.height * 0.5) ); - label3->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label3); } From a3b83d68b200fc3aae096dff285d453050bc1875 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Tue, 25 Mar 2014 11:10:48 +0800 Subject: [PATCH 051/106] update test case. --- tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp b/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp index 07b99b5306..0dc64bee63 100644 --- a/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp +++ b/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp @@ -1373,11 +1373,13 @@ LabelCharMapTest::LabelCharMapTest() auto label1 = Label::createWithCharMap("fonts/tuffy_bold_italic-charmap.plist"); addChild(label1, 0, kTagSprite1); + label1->setAnchorPoint(Point::ANCHOR_BOTTOM_LEFT); label1->setPosition( Point(10,100) ); label1->setOpacity( 200 ); auto label2 = Label::createWithCharMap("fonts/tuffy_bold_italic-charmap.plist"); addChild(label2, 0, kTagSprite2); + label2->setAnchorPoint(Point::ANCHOR_BOTTOM_LEFT); label2->setPosition( Point(10,200) ); label2->setOpacity( 32 ); @@ -1417,11 +1419,13 @@ LabelCharMapColorTest::LabelCharMapColorTest() { auto label1 = Label::createWithCharMap( "fonts/tuffy_bold_italic-charmap.png", 48, 64, ' '); addChild(label1, 0, kTagSprite1); + label1->setAnchorPoint(Point::ANCHOR_BOTTOM_LEFT); label1->setPosition( Point(10,100) ); label1->setOpacity( 200 ); auto label2 = Label::createWithCharMap("fonts/tuffy_bold_italic-charmap.png", 48, 64, ' '); addChild(label2, 0, kTagSprite2); + label2->setAnchorPoint(Point::ANCHOR_BOTTOM_LEFT); label2->setPosition( Point(10,200) ); label2->setColor( Color3B::RED ); From db0fe6097457b63540cb24aad811e70434e4bead Mon Sep 17 00:00:00 2001 From: boyu0 Date: Tue, 25 Mar 2014 11:13:44 +0800 Subject: [PATCH 052/106] closed #3804: Change Image private function and variable to protected, for the subclasses can use them. --- cocos/2d/platform/CCImage.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/2d/platform/CCImage.h b/cocos/2d/platform/CCImage.h index 755c03bcec..2f0be6d8fa 100644 --- a/cocos/2d/platform/CCImage.h +++ b/cocos/2d/platform/CCImage.h @@ -155,7 +155,7 @@ protected: bool saveImageToPNG(const std::string& filePath, bool isToRGB = true); bool saveImageToJPG(const std::string& filePath); -private: +protected: /** @brief Determine how many mipmaps can we have. Its same as define but it respects namespaces @@ -175,7 +175,7 @@ private: std::string _filePath; -private: +protected: // noncopyable Image(const Image& rImg); Image & operator=(const Image&); From 289e632a40a8b9cf9898cdfa09f313c3fc05f48d Mon Sep 17 00:00:00 2001 From: boyu0 Date: Tue, 25 Mar 2014 11:36:35 +0800 Subject: [PATCH 053/106] closed #4513: change 1.0 to 1.0f to avoid the warning. --- tests/cpp-tests/Classes/ParticleTest/ParticleTest.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/cpp-tests/Classes/ParticleTest/ParticleTest.cpp b/tests/cpp-tests/Classes/ParticleTest/ParticleTest.cpp index 12063ca97b..86d0df0e79 100644 --- a/tests/cpp-tests/Classes/ParticleTest/ParticleTest.cpp +++ b/tests/cpp-tests/Classes/ParticleTest/ParticleTest.cpp @@ -1871,14 +1871,14 @@ void PremultipliedAlphaTest::onEnter() // Toggle next line to see old behavior // this->emitter.opacityModifyRGB = NO; - _emitter->setStartColor(Color4F(1, 1, 1, 1)); - _emitter->setEndColor(Color4F(1, 1, 1, 0)); - _emitter->setStartColorVar(Color4F(0, 0, 0, 0)); - _emitter->setEndColorVar(Color4F(0, 0, 0, 0)); + _emitter->setStartColor(Color4F(1.0f, 1.0f, 1.0f, 1.0f)); + _emitter->setEndColor(Color4F(1.0f, 1.0f, 1.0f, 0.0f)); + _emitter->setStartColorVar(Color4F(0.0f, 0.0f, 0.0f, 0.0f)); + _emitter->setEndColorVar(Color4F(0.0f, 0.0f, 0.0f, 0.0f)); this->addChild(_emitter, 10); - schedule(schedule_selector(PremultipliedAlphaTest::readdPaticle), 1.0); + schedule(schedule_selector(PremultipliedAlphaTest::readdPaticle), 1.0f); } // PremultipliedAlphaTest2 From 4edaa62ec778c38a3d74d031d4c9ad4bd40c0f42 Mon Sep 17 00:00:00 2001 From: aeonmine Date: Tue, 25 Mar 2014 12:41:16 +0900 Subject: [PATCH 054/106] Update CCActionManagerEx.cpp modify intent --- cocos/editor-support/cocostudio/CCActionManagerEx.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCActionManagerEx.cpp b/cocos/editor-support/cocostudio/CCActionManagerEx.cpp index 03617ca26a..a439f843cb 100644 --- a/cocos/editor-support/cocostudio/CCActionManagerEx.cpp +++ b/cocos/editor-support/cocostudio/CCActionManagerEx.cpp @@ -63,7 +63,7 @@ void ActionManagerEx::initWithDictionary(const char* jsonName,const rapidjson::V int actionCount = DICTOOL->getArrayCount_json(dic, "actionlist"); for (int i=0; iautorelease(); + action->autorelease(); const rapidjson::Value &actionDic = DICTOOL->getDictionaryFromArray_json(dic, "actionlist", i); action->initWithDictionary(actionDic,root); actionList.pushBack(action); @@ -123,4 +123,4 @@ void ActionManagerEx::releaseActions() _actionDic.clear(); } -} \ No newline at end of file +} From 5d2906ad8b1ee3b6815dd29d47bbfee961f56596 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Tue, 25 Mar 2014 05:50:20 +0000 Subject: [PATCH 055/106] [AUTO]: updating luabinding automatically --- .../lua-bindings/auto/api/ControlStepper.lua | 8 ++++---- .../lua-bindings/auto/api/ControlSwitch.lua | 12 ++++++------ .../lua_cocos2dx_extension_auto.cpp.REMOVED.git-id | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/cocos/scripting/lua-bindings/auto/api/ControlStepper.lua b/cocos/scripting/lua-bindings/auto/api/ControlStepper.lua index ac7a16f7fa..641665417f 100644 --- a/cocos/scripting/lua-bindings/auto/api/ControlStepper.lua +++ b/cocos/scripting/lua-bindings/auto/api/ControlStepper.lua @@ -11,7 +11,7 @@ -------------------------------- -- @function [parent=#ControlStepper] getMinusLabel -- @param self --- @return LabelTTF#LabelTTF ret (return value: cc.LabelTTF) +-- @return Label#Label ret (return value: cc.Label) -------------------------------- -- @function [parent=#ControlStepper] setWraps @@ -42,7 +42,7 @@ -------------------------------- -- @function [parent=#ControlStepper] getPlusLabel -- @param self --- @return LabelTTF#LabelTTF ret (return value: cc.LabelTTF) +-- @return Label#Label ret (return value: cc.Label) -------------------------------- -- @function [parent=#ControlStepper] stopAutorepeat @@ -66,7 +66,7 @@ -------------------------------- -- @function [parent=#ControlStepper] setMinusLabel -- @param self --- @param #cc.LabelTTF labelttf +-- @param #cc.Label label -------------------------------- -- @function [parent=#ControlStepper] setValue @@ -107,7 +107,7 @@ -------------------------------- -- @function [parent=#ControlStepper] setPlusLabel -- @param self --- @param #cc.LabelTTF labelttf +-- @param #cc.Label label -------------------------------- -- @function [parent=#ControlStepper] create diff --git a/cocos/scripting/lua-bindings/auto/api/ControlSwitch.lua b/cocos/scripting/lua-bindings/auto/api/ControlSwitch.lua index 25de51ff61..cfaa677647 100644 --- a/cocos/scripting/lua-bindings/auto/api/ControlSwitch.lua +++ b/cocos/scripting/lua-bindings/auto/api/ControlSwitch.lua @@ -24,7 +24,7 @@ -- @return bool#bool ret (return value: bool) -------------------------------- --- overload function: initWithMaskSprite(cc.Sprite, cc.Sprite, cc.Sprite, cc.Sprite, cc.LabelTTF, cc.LabelTTF) +-- overload function: initWithMaskSprite(cc.Sprite, cc.Sprite, cc.Sprite, cc.Sprite, cc.Label, cc.Label) -- -- overload function: initWithMaskSprite(cc.Sprite, cc.Sprite, cc.Sprite, cc.Sprite) -- @@ -34,8 +34,8 @@ -- @param #cc.Sprite sprite -- @param #cc.Sprite sprite -- @param #cc.Sprite sprite --- @param #cc.LabelTTF labelttf --- @param #cc.LabelTTF labelttf +-- @param #cc.Label label +-- @param #cc.Label label -- @return bool#bool ret (retunr value: bool) -------------------------------- @@ -52,7 +52,7 @@ -------------------------------- -- overload function: create(cc.Sprite, cc.Sprite, cc.Sprite, cc.Sprite) -- --- overload function: create(cc.Sprite, cc.Sprite, cc.Sprite, cc.Sprite, cc.LabelTTF, cc.LabelTTF) +-- overload function: create(cc.Sprite, cc.Sprite, cc.Sprite, cc.Sprite, cc.Label, cc.Label) -- -- @function [parent=#ControlSwitch] create -- @param self @@ -60,8 +60,8 @@ -- @param #cc.Sprite sprite -- @param #cc.Sprite sprite -- @param #cc.Sprite sprite --- @param #cc.LabelTTF labelttf --- @param #cc.LabelTTF labelttf +-- @param #cc.Label label +-- @param #cc.Label label -- @return ControlSwitch#ControlSwitch ret (retunr value: cc.ControlSwitch) -------------------------------- diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_extension_auto.cpp.REMOVED.git-id b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_extension_auto.cpp.REMOVED.git-id index 99aa8077bc..399ed60da1 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_extension_auto.cpp.REMOVED.git-id +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_extension_auto.cpp.REMOVED.git-id @@ -1 +1 @@ -cb29285429f792ed191dc2135b5f80ca5e52e9d1 \ No newline at end of file +28a6a3c5097941a6602ffedccf4d2a82f5b53389 \ No newline at end of file From d2044eeede9c3ff5ad11fce07a837984fbd460fa Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 25 Mar 2014 13:53:05 +0800 Subject: [PATCH 056/106] Update CHANGELOG [ci skip] --- CHANGELOG.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.REMOVED.git-id b/CHANGELOG.REMOVED.git-id index 99658a8dd4..c1b5176922 100644 --- a/CHANGELOG.REMOVED.git-id +++ b/CHANGELOG.REMOVED.git-id @@ -1 +1 @@ -a220377dfc7c4fce177d53c2fb3ab5baddf8e404 \ No newline at end of file +7934c43bdd8af0e6a865b982d37633b2d0838f91 \ No newline at end of file From e11e290d9f8a939b6db387a507dba6c56daf4fb1 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 25 Mar 2014 13:56:40 +0800 Subject: [PATCH 057/106] Update AUTHORS [ci skip] --- AUTHORS | 3 +++ 1 file changed, 3 insertions(+) diff --git a/AUTHORS b/AUTHORS index 343d846368..aa96926c85 100644 --- a/AUTHORS +++ b/AUTHORS @@ -787,6 +787,9 @@ Developers: youknowone Adds iOS-like elastic bounceback support for cocos2d::extension::ScrollView + + aeonmine + Fixed ActionObject memory leak in ActionManagerEx::initWithDictionary Retired Core Developers: WenSheng Yang From 2549368c623a348a3aff15d44ee85eb27315d4ed Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 25 Mar 2014 14:03:48 +0800 Subject: [PATCH 058/106] Update AUTHORS [ci skip] --- AUTHORS | 3 +++ 1 file changed, 3 insertions(+) diff --git a/AUTHORS b/AUTHORS index aa96926c85..af63114d5a 100644 --- a/AUTHORS +++ b/AUTHORS @@ -790,6 +790,9 @@ Developers: aeonmine Fixed ActionObject memory leak in ActionManagerEx::initWithDictionary + + LoungeKatt + Corrected a mistake of building android project in README.md Retired Core Developers: WenSheng Yang From d8793a87b99ea41bff99a5d4d2179add74e28426 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 25 Mar 2014 14:12:21 +0800 Subject: [PATCH 059/106] Update CHANGELOG [ci skip] --- CHANGELOG.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.REMOVED.git-id b/CHANGELOG.REMOVED.git-id index c1b5176922..4927d8c901 100644 --- a/CHANGELOG.REMOVED.git-id +++ b/CHANGELOG.REMOVED.git-id @@ -1 +1 @@ -7934c43bdd8af0e6a865b982d37633b2d0838f91 \ No newline at end of file +8346ec38d8e813be64d7d24636c2cea248b8bbfc \ No newline at end of file From beb6f7359c83c097c3e513ed047b4c1503d425bf Mon Sep 17 00:00:00 2001 From: zhangbin Date: Tue, 25 Mar 2014 14:19:46 +0800 Subject: [PATCH 060/106] Update the reference of submodule "cocos2d-console". --- tools/cocos2d-console | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/cocos2d-console b/tools/cocos2d-console index 368bd5dad6..735279c12c 160000 --- a/tools/cocos2d-console +++ b/tools/cocos2d-console @@ -1 +1 @@ -Subproject commit 368bd5dad61df0c7610479ac67513b450ba08b45 +Subproject commit 735279c12c71d72088887b472cefa7f3ad3ba669 From 2dffcb980865c0300dd7177d40451c325155b97f Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Mon, 24 Mar 2014 15:25:44 +0800 Subject: [PATCH 061/106] Add ProtectedNode and remove "addNode" --- .../project.pbxproj.REMOVED.git-id | 2 +- cocos/2d/CCScene.h | 1 + cocos/physics/CCPhysicsBody.h | 1 + cocos/ui/CCProtectedNode.cpp | 420 ++++++++++++++++++ cocos/ui/CCProtectedNode.h | 216 +++++++++ cocos/ui/UIButton.cpp | 20 +- cocos/ui/UICheckBox.cpp | 10 +- cocos/ui/UIHelper.cpp | 48 +- cocos/ui/UIImageView.cpp | 6 +- cocos/ui/UILayout.cpp | 232 +++++----- cocos/ui/UILoadingBar.cpp | 6 +- cocos/ui/UIRichText.cpp | 7 +- cocos/ui/UIRichText.h | 3 +- cocos/ui/UIScrollView.cpp | 40 -- cocos/ui/UIScrollView.h | 16 - cocos/ui/UISlider.cpp | 14 +- cocos/ui/UIText.cpp | 2 +- cocos/ui/UITextAtlas.cpp | 2 +- cocos/ui/UITextBMFont.cpp | 2 +- cocos/ui/UITextField.cpp | 2 +- cocos/ui/UIWidget.cpp | 231 ++-------- cocos/ui/UIWidget.h | 130 +----- .../UIWidgetAddNodeTest.cpp | 2 +- .../UIWidgetAddNodeTest_Editor.cpp | 2 +- 24 files changed, 878 insertions(+), 537 deletions(-) create mode 100644 cocos/ui/CCProtectedNode.cpp create mode 100644 cocos/ui/CCProtectedNode.h diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 8e489a0d1e..f0adc63a8a 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -68ac83318dc8df5fee3badc4eb3f0e75ee0a9ce0 \ No newline at end of file +ebeb897c2c3303710c06b9de3cb3d499f89fb78c \ No newline at end of file diff --git a/cocos/2d/CCScene.h b/cocos/2d/CCScene.h index 880d0c9946..45d35540d9 100644 --- a/cocos/2d/CCScene.h +++ b/cocos/2d/CCScene.h @@ -68,6 +68,7 @@ CC_CONSTRUCTOR_ACCESS: protected: friend class Node; + friend class ProtectedNode; friend class SpriteBatchNode; private: diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index 80cd31c041..d9ac83a12a 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -349,6 +349,7 @@ protected: friend class PhysicsShape; friend class PhysicsJoint; friend class Node; + friend class ProtectedNode; }; NS_CC_END diff --git a/cocos/ui/CCProtectedNode.cpp b/cocos/ui/CCProtectedNode.cpp new file mode 100644 index 0000000000..7a4abf44f4 --- /dev/null +++ b/cocos/ui/CCProtectedNode.cpp @@ -0,0 +1,420 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2009 Valentin Milea + Copyright (c) 2010-2012 cocos2d-x.org + Copyright (c) 2011 Zynga Inc. + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "CCProtectedNode.h" + +#include "kazmath/GL/matrix.h" + +#if CC_USE_PHYSICS +#include "CCPhysicsBody.h" +#endif +#include "CCScene.h" + +#include "CCNode.cpp" + +NS_CC_BEGIN + +// XXX: Yes, nodes might have a sort problem once every 15 days if the game runs at 60 FPS and each frame sprites are reordered. +//static int s_globalOrderOfArrival = 1; + +ProtectedNode::ProtectedNode() : _reorderProtectedChildDirty(false) +{ +} + +ProtectedNode::~ProtectedNode() +{ + + CCLOGINFO( "deallocing ProtectedNode: %p - tag: %i", this, _tag ); +} + +ProtectedNode * ProtectedNode::create(void) +{ + ProtectedNode * ret = new ProtectedNode(); + if (ret && ret->init()) + { + ret->autorelease(); + } + else + { + CC_SAFE_DELETE(ret); + } + return ret; +} + +void ProtectedNode::cleanup() +{ + Node::cleanup(); + // timers + for( const auto &child: _protectedChildren) + child->cleanup(); +} + +void ProtectedNode::addProtectedChild(cocos2d::Node *child) +{ + addProtectedChild(child, child->getLocalZOrder(), child->getTag()); +} + +void ProtectedNode::addProtectedChild(cocos2d::Node *child, int localZOrder) +{ + addProtectedChild(child, localZOrder, child->getTag()); +} + +/* "add" logic MUST only be on this method + * If a class want's to extend the 'addChild' behavior it only needs + * to override this method + */ +void ProtectedNode::addProtectedChild(Node *child, int zOrder, int tag) +{ + CCASSERT( child != nullptr, "Argument must be non-nil"); + CCASSERT( child->getParent() == nullptr, "child already added. It can't be added again"); + + if (_protectedChildren.empty()) + { + _protectedChildren.reserve(4); + } + + this->insertProtectedChild(child, zOrder); + +#if CC_USE_PHYSICS + if (child->getPhysicsBody() != nullptr) + { + child->getPhysicsBody()->setPosition(this->convertToWorldSpace(child->getPosition())); + } + + for (Node* node = this->getParent(); node != nullptr; node = node->getParent()) + { + if (dynamic_cast(node) != nullptr) + { + (dynamic_cast(node))->addChildToPhysicsWorld(child); + break; + } + } +#endif + + child->setTag(tag); + + child->setParent(this); + child->setOrderOfArrival(s_globalOrderOfArrival++); + + if( _running ) + { + child->onEnter(); + // prevent onEnterTransitionDidFinish to be called twice when a node is added in onEnter + if (_isTransitionFinished) { + child->onEnterTransitionDidFinish(); + } + } + + if (_cascadeColorEnabled) + { + updateCascadeColor(); + } + + if (_cascadeOpacityEnabled) + { + updateCascadeOpacity(); + } +} + +Node* ProtectedNode::getProtectedChildByTag(int tag) +{ + CCASSERT( tag != Node::INVALID_TAG, "Invalid tag"); + + for (auto& child : _protectedChildren) + { + if(child && child->getTag() == tag) + return child; + } + return nullptr; +} + +/* "remove" logic MUST only be on this method + * If a class want's to extend the 'removeChild' behavior it only needs + * to override this method + */ +void ProtectedNode::removeProtectedChild(cocos2d::Node *child, bool cleanup) +{ + // explicit nil handling + if (_protectedChildren.empty()) + { + return; + } + + ssize_t index = _protectedChildren.getIndex(child); + if( index != CC_INVALID_INDEX ) + { + + // IMPORTANT: + // -1st do onExit + // -2nd cleanup + if (_running) + { + child->onExitTransitionDidStart(); + child->onExit(); + } + +#if CC_USE_PHYSICS + if (child->getPhysicsBody() != nullptr) + { + child->getPhysicsBody()->removeFromWorld(); + } + +#endif + // If you don't do cleanup, the child's actions will not get removed and the + // its scheduledSelectors_ dict will not get released! + if (cleanup) + { + child->cleanup(); + } + + // set parent nil at the end + child->setParent(nullptr); + + _protectedChildren.erase(index); + } +} + +void ProtectedNode::removeAllProtectedChildren() +{ + removeAllProtectedChildrenWithCleanup(true); +} + +void ProtectedNode::removeAllProtectedChildrenWithCleanup(bool cleanup) +{ + // not using detachChild improves speed here + for (auto& child : _protectedChildren) + { + // IMPORTANT: + // -1st do onExit + // -2nd cleanup + if(_running) + { + child->onExitTransitionDidStart(); + child->onExit(); + } + +#if CC_USE_PHYSICS + if (child->getPhysicsBody() != nullptr) + { + child->getPhysicsBody()->removeFromWorld(); + } +#endif + + if (cleanup) + { + child->cleanup(); + } + // set parent nil at the end + child->setParent(nullptr); + } + + _protectedChildren.clear(); +} + +void ProtectedNode::removeProtectedChildByTag(int tag, bool cleanup) +{ + CCASSERT( tag != Node::INVALID_TAG, "Invalid tag"); + + Node *child = this->getProtectedChildByTag(tag); + + if (child == nullptr) + { + CCLOG("cocos2d: removeChildByTag(tag = %d): child not found!", tag); + } + else + { + this->removeProtectedChild(child, cleanup); + } +} + +// helper used by reorderChild & add +void ProtectedNode::insertProtectedChild(cocos2d::Node *child, int z) +{ + _reorderProtectedChildDirty = true; + _protectedChildren.pushBack(child); + child->_setLocalZOrder(z); +} + +void ProtectedNode::sortAllProtectedChildren() +{ + if( _reorderProtectedChildDirty ) { + std::sort( std::begin(_protectedChildren), std::end(_protectedChildren), nodeComparisonLess ); + _reorderProtectedChildDirty = false; + } +} + +void ProtectedNode::reorderProtectedChild(cocos2d::Node *child, int localZOrder) +{ + CCASSERT( child != nullptr, "Child must be non-nil"); + _reorderProtectedChildDirty = true; + child->setOrderOfArrival(s_globalOrderOfArrival++); + child->_setLocalZOrder(localZOrder); +} + +void ProtectedNode::visit(Renderer* renderer, const kmMat4 &parentTransform, bool parentTransformUpdated) +{ + // quick return if not visible. children won't be drawn. + if (!_visible) + { + return; + } + + bool dirty = _transformUpdated || parentTransformUpdated; + if(dirty) + _modelViewTransform = this->transform(parentTransform); + _transformUpdated = false; + + + // IMPORTANT: + // To ease the migration to v3.0, we still support the kmGL stack, + // but it is deprecated and your code should not rely on it + kmGLPushMatrix(); + kmGLLoadMatrix(&_modelViewTransform); + + int i = 0; // used by _children + int j = 0; // used by _protectedChildren + + sortAllChildren(); + sortAllProtectedChildren(); + + // + // draw children and protectedChildren zOrder < 0 + // + for( ; i < _children.size(); i++ ) + { + auto node = _children.at(i); + + if ( node && node->getZOrder() < 0 ) + node->visit(renderer, _modelViewTransform, dirty); + else + break; + } + + for( ; j < _protectedChildren.size(); j++ ) + { + auto node = _protectedChildren.at(j); + + if ( node && node->getZOrder() < 0 ) + node->visit(renderer, _modelViewTransform, dirty); + else + break; + } + + // + // draw self + // + this->draw(renderer, _modelViewTransform, dirty); + + // + // draw children and protectedChildren zOrder >= 0 + // + for(auto it=_protectedChildren.cbegin()+j; it != _protectedChildren.cend(); ++it) + (*it)->visit(renderer, _modelViewTransform, dirty); + + for(auto it=_children.cbegin()+i; it != _children.cend(); ++it) + (*it)->visit(renderer, _modelViewTransform, dirty); + + // reset for next frame + _orderOfArrival = 0; + + kmGLPopMatrix(); +} + +void ProtectedNode::onEnter() +{ + Node::onEnter(); + for( const auto &child: _protectedChildren) + child->onEnter(); +} + +void ProtectedNode::onEnterTransitionDidFinish() +{ + Node::onEnterTransitionDidFinish(); + for( const auto &child: _protectedChildren) + child->onEnterTransitionDidFinish(); +} + +void ProtectedNode::onExitTransitionDidStart() +{ + Node::onExitTransitionDidStart(); + for( const auto &child: _protectedChildren) + child->onExitTransitionDidStart(); +} + +void ProtectedNode::onExit() +{ + Node::onExit(); + for( const auto &child: _protectedChildren) + child->onExit(); +} + +void ProtectedNode::updateDisplayedOpacity(GLubyte parentOpacity) +{ + _displayedOpacity = _realOpacity * parentOpacity/255.0; + updateColor(); + + if (_cascadeOpacityEnabled) + { + for(auto child : _children){ + child->updateDisplayedOpacity(_displayedOpacity); + } + for(auto child : _protectedChildren){ + child->updateDisplayedOpacity(_displayedOpacity); + } + } +} + +void ProtectedNode::updateDisplayedColor(const Color3B& parentColor) +{ + _displayedColor.r = _realColor.r * parentColor.r/255.0; + _displayedColor.g = _realColor.g * parentColor.g/255.0; + _displayedColor.b = _realColor.b * parentColor.b/255.0; + updateColor(); + + if (_cascadeColorEnabled) + { + for(const auto &child : _children){ + child->updateDisplayedColor(_displayedColor); + } + for(const auto &child : _protectedChildren){ + child->updateDisplayedColor(_displayedColor); + } + } +} + +void ProtectedNode::disableCascadeColor() +{ + for(auto child : _children){ + child->updateDisplayedColor(Color3B::WHITE); + } + for(auto child : _protectedChildren){ + child->updateDisplayedColor(Color3B::WHITE); + } +} + +NS_CC_END \ No newline at end of file diff --git a/cocos/ui/CCProtectedNode.h b/cocos/ui/CCProtectedNode.h new file mode 100644 index 0000000000..7ff20e55b3 --- /dev/null +++ b/cocos/ui/CCProtectedNode.h @@ -0,0 +1,216 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2009 Valentin Milea + Copyright (c) 2010-2012 cocos2d-x.org + Copyright (c) 2011 Zynga Inc. + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __CPROTECTEDCNODE_H__ +#define __CPROTECTEDCNODE_H__ + + +#include "CCNode.h" + +NS_CC_BEGIN + + +/** + * @addtogroup base_nodes + * @{ + */ + +/** @brief Node is the base element of the Scene Graph. Elements of the Scene Graph must be Node objects or subclasses of it. + The most common Node objects are: Scene, Layer, Sprite, Menu, Label. + + The main features of a Node are: + - They can contain other Node objects (`addChild`, `getChildByTag`, `removeChild`, etc) + - They can schedule periodic callback (`schedule`, `unschedule`, etc) + - They can execute actions (`runAction`, `stopAction`, etc) + + Subclassing a Node usually means (one/all) of: + - overriding init to initialize resources and schedule callbacks + - create callbacks to handle the advancement of time + - overriding `draw` to render the node + + Properties of Node: + - position (default: x=0, y=0) + - scale (default: x=1, y=1) + - rotation (in degrees, clockwise) (default: 0) + - anchor point (default: x=0, y=0) + - contentSize (default: width=0, height=0) + - visible (default: true) + + Limitations: + - A Node is a "void" object. If you want to draw something on the screen, you should use a Sprite instead. Or subclass Node and override `draw`. + + */ + +class CC_DLL ProtectedNode : public Node +{ +public: + static ProtectedNode * create(void); + + /// @{ + /// @name Children and Parent + + /** + * Adds a child to the container with z-order as 0. + * + * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. + * + * @param child A child node + */ + virtual void addProtectedChild(Node * child); + /** + * Adds a child to the container with a local z-order + * + * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. + * + * @param child A child node + * @param zOrder Z order for drawing priority. Please refer to `setLocalZOrder(int)` + */ + virtual void addProtectedChild(Node * child, int localZOrder); + /** + * Adds a child to the container with z order and tag + * + * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. + * + * @param child A child node + * @param zOrder Z order for drawing priority. Please refer to `setLocalZOrder(int)` + * @param tag An integer to identify the node easily. Please refer to `setTag(int)` + */ + virtual void addProtectedChild(Node* child, int localZOrder, int tag); + /** + * Gets a child from the container with its tag + * + * @param tag An identifier to find the child node. + * + * @return a Node object whose tag equals to the input parameter + */ + virtual Node * getProtectedChildByTag(int tag); + + ////// REMOVES ////// + + /** + * Removes a child from the container. It will also cleanup all running actions depending on the cleanup parameter. + * + * @param child The child node which will be removed. + * @param cleanup true if all running actions and callbacks on the child node will be cleanup, false otherwise. + */ + virtual void removeProtectedChild(Node* child, bool cleanup = true); + + /** + * Removes a child from the container by tag value. It will also cleanup all running actions depending on the cleanup parameter + * + * @param tag An interger number that identifies a child node + * @param cleanup true if all running actions and callbacks on the child node will be cleanup, false otherwise. + */ + virtual void removeProtectedChildByTag(int tag, bool cleanup = true); + /** + * Removes all children from the container with a cleanup. + * + * @see `removeAllChildrenWithCleanup(bool)` + */ + virtual void removeAllProtectedChildren(); + /** + * Removes all children from the container, and do a cleanup to all running actions depending on the cleanup parameter. + * + * @param cleanup true if all running actions on all children nodes should be cleanup, false oterwise. + * @js removeAllChildren + * @lua removeAllChildren + */ + virtual void removeAllProtectedChildrenWithCleanup(bool cleanup); + + /** + * Reorders a child according to a new z value. + * + * @param child An already added child node. It MUST be already added. + * @param localZOrder Z order for drawing priority. Please refer to setLocalZOrder(int) + */ + virtual void reorderProtectedChild(Node * child, int localZOrder); + + /** + * Sorts the children array once before drawing, instead of every time when a child is added or reordered. + * This appraoch can improves the performance massively. + * @note Don't call this manually unless a child added needs to be removed in the same frame + */ + virtual void sortAllProtectedChildren(); + + /// @} end of Children and Parent + + virtual void visit(Renderer *renderer, const kmMat4 &parentTransform, bool transformUpdated) override; + + virtual void cleanup() override; + + virtual void onEnter() override; + + /** Event callback that is invoked when the Node enters in the 'stage'. + * If the Node enters the 'stage' with a transition, this event is called when the transition finishes. + * If you override onEnterTransitionDidFinish, you shall call its parent's one, e.g. Node::onEnterTransitionDidFinish() + * @js NA + * @lua NA + */ + virtual void onEnterTransitionDidFinish() override; + + /** + * Event callback that is invoked every time the Node leaves the 'stage'. + * If the Node leaves the 'stage' with a transition, this event is called when the transition finishes. + * During onExit you can't access a sibling node. + * If you override onExit, you shall call its parent's one, e.g., Node::onExit(). + * @js NA + * @lua NA + */ + virtual void onExit() override; + + /** + * Event callback that is called every time the Node leaves the 'stage'. + * If the Node leaves the 'stage' with a transition, this callback is called when the transition starts. + * @js NA + * @lua NA + */ + virtual void onExitTransitionDidStart() override; + + virtual void updateDisplayedOpacity(GLubyte parentOpacity) override; + virtual void updateDisplayedColor(const Color3B& parentColor) override; + virtual void disableCascadeColor() override; + +protected: + ProtectedNode(); + virtual ~ProtectedNode(); + + + /// helper that reorder a child + void insertProtectedChild(Node* child, int z); + + Vector _protectedChildren; ///< array of children nodes + bool _reorderProtectedChildDirty; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ProtectedNode); +}; + + +NS_CC_END + +#endif // __CPROTECTEDCNODE_H__ \ No newline at end of file diff --git a/cocos/ui/UIButton.cpp b/cocos/ui/UIButton.cpp index 114b73b419..8dac6ccf49 100644 --- a/cocos/ui/UIButton.cpp +++ b/cocos/ui/UIButton.cpp @@ -102,10 +102,10 @@ void Button::initRenderer() _titleRenderer = Label::create(); _titleRenderer->setAnchorPoint(Point::ANCHOR_MIDDLE); - Node::addChild(_buttonNormalRenderer, NORMAL_RENDERER_Z, -1); - Node::addChild(_buttonClickedRenderer, PRESSED_RENDERER_Z, -1); - Node::addChild(_buttonDisableRenderer, DISABLED_RENDERER_Z, -1); - Node::addChild(_titleRenderer, TITLE_RENDERER_Z, -1); + addProtectedChild(_buttonNormalRenderer, NORMAL_RENDERER_Z, -1); + addProtectedChild(_buttonClickedRenderer, PRESSED_RENDERER_Z, -1); + addProtectedChild(_buttonDisableRenderer, DISABLED_RENDERER_Z, -1); + addProtectedChild(_titleRenderer, TITLE_RENDERER_Z, -1); } void Button::setScale9Enabled(bool able) @@ -116,9 +116,9 @@ void Button::setScale9Enabled(bool able) } _brightStyle = BRIGHT_NONE; _scale9Enabled = able; - Node::removeChild(_buttonNormalRenderer); - Node::removeChild(_buttonClickedRenderer); - Node::removeChild(_buttonDisableRenderer); + removeProtectedChild(_buttonNormalRenderer); + removeProtectedChild(_buttonClickedRenderer); + removeProtectedChild(_buttonDisableRenderer); _buttonNormalRenderer = nullptr; _buttonClickedRenderer = nullptr; _buttonDisableRenderer = nullptr; @@ -138,9 +138,9 @@ void Button::setScale9Enabled(bool able) loadTextureNormal(_normalFileName.c_str(), _normalTexType); loadTexturePressed(_clickedFileName.c_str(), _pressedTexType); loadTextureDisabled(_disabledFileName.c_str(), _disabledTexType); - Node::addChild(_buttonNormalRenderer, NORMAL_RENDERER_Z, -1); - Node::addChild(_buttonClickedRenderer, PRESSED_RENDERER_Z, -1); - Node::addChild(_buttonDisableRenderer, DISABLED_RENDERER_Z, -1); + addProtectedChild(_buttonNormalRenderer, NORMAL_RENDERER_Z, -1); + addProtectedChild(_buttonClickedRenderer, PRESSED_RENDERER_Z, -1); + addProtectedChild(_buttonDisableRenderer, DISABLED_RENDERER_Z, -1); if (_scale9Enabled) { bool ignoreBefore = _ignoreSize; diff --git a/cocos/ui/UICheckBox.cpp b/cocos/ui/UICheckBox.cpp index 86cf8ed815..d24edfdacb 100644 --- a/cocos/ui/UICheckBox.cpp +++ b/cocos/ui/UICheckBox.cpp @@ -95,11 +95,11 @@ void CheckBox::initRenderer() _backGroundBoxDisabledRenderer = Sprite::create(); _frontCrossDisabledRenderer = Sprite::create(); - Node::addChild(_backGroundBoxRenderer, BACKGROUNDBOX_RENDERER_Z, -1); - Node::addChild(_backGroundSelectedBoxRenderer, BACKGROUNDSELECTEDBOX_RENDERER_Z, -1); - Node::addChild(_frontCrossRenderer, FRONTCROSS_RENDERER_Z, -1); - Node::addChild(_backGroundBoxDisabledRenderer, BACKGROUNDBOXDISABLED_RENDERER_Z, -1); - Node::addChild(_frontCrossDisabledRenderer, FRONTCROSSDISABLED_RENDERER_Z, -1); + addProtectedChild(_backGroundBoxRenderer, BACKGROUNDBOX_RENDERER_Z, -1); + addProtectedChild(_backGroundSelectedBoxRenderer, BACKGROUNDSELECTEDBOX_RENDERER_Z, -1); + addProtectedChild(_frontCrossRenderer, FRONTCROSS_RENDERER_Z, -1); + addProtectedChild(_backGroundBoxDisabledRenderer, BACKGROUNDBOXDISABLED_RENDERER_Z, -1); + addProtectedChild(_frontCrossDisabledRenderer, FRONTCROSSDISABLED_RENDERER_Z, -1); } void CheckBox::loadTextures(const char *backGround, const char *backGroundSelected, const char *cross,const char* backGroundDisabled,const char* frontCrossDisabled,TextureResType texType) diff --git a/cocos/ui/UIHelper.cpp b/cocos/ui/UIHelper.cpp index 4bb3d4ee8b..ebbf2c1265 100644 --- a/cocos/ui/UIHelper.cpp +++ b/cocos/ui/UIHelper.cpp @@ -42,11 +42,14 @@ Widget* Helper::seekWidgetByTag(Widget* root, int tag) ssize_t length = arrayRootChildren.size(); for (ssize_t i=0;i(arrayRootChildren.at(i)); - Widget* res = seekWidgetByTag(child,tag); - if (res != nullptr) + Widget* child = dynamic_cast(arrayRootChildren.at(i)); + if (child) { - return res; + Widget* res = seekWidgetByTag(child,tag); + if (res != nullptr) + { + return res; + } } } return nullptr; @@ -65,11 +68,14 @@ Widget* Helper::seekWidgetByName(Widget* root, const char *name) const auto& arrayRootChildren = root->getChildren(); for (auto& subWidget : arrayRootChildren) { - Widget* child = static_cast(subWidget); - Widget* res = seekWidgetByName(child,name); - if (res != nullptr) + Widget* child = dynamic_cast(subWidget); + if (child) { - return res; + Widget* res = seekWidgetByName(child,name); + if (res != nullptr) + { + return res; + } } } return nullptr; @@ -84,11 +90,14 @@ Widget* Helper::seekWidgetByRelativeName(Widget *root, const char *name) const auto& arrayRootChildren = root->getChildren(); for (auto& subWidget : arrayRootChildren) { - Widget* child = static_cast(subWidget); - RelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); - if (layoutParameter && strcmp(layoutParameter->getRelativeName(), name) == 0) + Widget* child = dynamic_cast(subWidget); + if (child) { - return child; + RelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); + if (layoutParameter && strcmp(layoutParameter->getRelativeName(), name) == 0) + { + return child; + } } } return nullptr; @@ -108,12 +117,15 @@ Widget* Helper::seekActionWidgetByActionTag(Widget* root, int tag) const auto& arrayRootChildren = root->getChildren(); for (auto& subWidget : arrayRootChildren) { - Widget* child = static_cast(subWidget); - Widget* res = seekActionWidgetByActionTag(child,tag); - if (res != nullptr) - { - return res; - } + Widget* child = dynamic_cast(subWidget); + if (child) + { + Widget* res = seekActionWidgetByActionTag(child,tag); + if (res != nullptr) + { + return res; + } + } } return nullptr; } diff --git a/cocos/ui/UIImageView.cpp b/cocos/ui/UIImageView.cpp index 83d93b06b3..097bc0ff7d 100644 --- a/cocos/ui/UIImageView.cpp +++ b/cocos/ui/UIImageView.cpp @@ -69,7 +69,7 @@ ImageView* ImageView::create() void ImageView::initRenderer() { _imageRenderer = Sprite::create(); - Node::addChild(_imageRenderer, IMAGE_RENDERER_Z, -1); + addProtectedChild(_imageRenderer, IMAGE_RENDERER_Z, -1); } void ImageView::loadTexture(const char *fileName, TextureResType texType) @@ -166,7 +166,7 @@ void ImageView::setScale9Enabled(bool able) _scale9Enabled = able; - Node::removeChild(_imageRenderer); + removeProtectedChild(_imageRenderer); _imageRenderer = nullptr; if (_scale9Enabled) { @@ -177,7 +177,7 @@ void ImageView::setScale9Enabled(bool able) _imageRenderer = Sprite::create(); } loadTexture(_textureFile.c_str(),_imageTexType); - Node::addChild(_imageRenderer, IMAGE_RENDERER_Z, -1); + addProtectedChild(_imageRenderer, IMAGE_RENDERER_Z, -1); if (_scale9Enabled) { bool ignoreBefore = _ignoreSize; diff --git a/cocos/ui/UILayout.cpp b/cocos/ui/UILayout.cpp index 1c488618d4..e2a8e53dad 100644 --- a/cocos/ui/UILayout.cpp +++ b/cocos/ui/UILayout.cpp @@ -127,7 +127,7 @@ Layout* Layout::create() bool Layout::init() { - if (Node::init()) + if (ProtectedNode::init()) { initRenderer(); setBright(true); @@ -211,7 +211,7 @@ void Layout::visit(Renderer *renderer, const kmMat4 &parentTransform, bool paren } else { - Node::visit(renderer, parentTransform, parentTransformUpdated); + ProtectedNode::visit(renderer, parentTransform, parentTransformUpdated); } } @@ -254,32 +254,50 @@ void Layout::stencilClippingVisit(Renderer *renderer, const kmMat4 &parentTransf _afterDrawStencilCmd.func = CC_CALLBACK_0(Layout::onAfterDrawStencil, this); renderer->addCommand(&_afterDrawStencilCmd); - int i = 0; + int i = 0; // used by _children + int j = 0; // used by _protectedChildren - if(!_children.empty()) + sortAllChildren(); + sortAllProtectedChildren(); + + // + // draw children and protectedChildren zOrder < 0 + // + for( ; i < _children.size(); i++ ) { - sortAllChildren(); - // draw children zOrder < 0 - for( ; i < _children.size(); i++ ) - { - auto node = _children.at(i); - - if ( node && node->getLocalZOrder() < 0 ) - node->visit(renderer, _modelViewTransform, dirty); - else - break; - } - // self draw - this->draw(renderer, _modelViewTransform, dirty); + auto node = _children.at(i); - for(auto it=_children.cbegin()+i; it != _children.cend(); ++it) - (*it)->visit(renderer, _modelViewTransform, dirty); + if ( node && node->getZOrder() < 0 ) + node->visit(renderer, _modelViewTransform, dirty); + else + break; } - else + + for( ; j < _protectedChildren.size(); j++ ) { - this->draw(renderer, _modelViewTransform, dirty); + auto node = _protectedChildren.at(j); + + if ( node && node->getZOrder() < 0 ) + node->visit(renderer, _modelViewTransform, dirty); + else + break; } + // + // draw self + // + this->draw(renderer, _modelViewTransform, dirty); + + // + // draw children and protectedChildren zOrder >= 0 + // + for(auto it=_protectedChildren.cbegin()+j; it != _protectedChildren.cend(); ++it) + (*it)->visit(renderer, _modelViewTransform, dirty); + + for(auto it=_children.cbegin()+i; it != _children.cend(); ++it) + (*it)->visit(renderer, _modelViewTransform, dirty); + + _afterVisitCmdStencil.init(_globalZOrder); _afterVisitCmdStencil.func = CC_CALLBACK_0(Layout::onAfterVisitStencil, this); renderer->addCommand(&_afterVisitCmdStencil); @@ -368,7 +386,7 @@ void Layout::scissorClippingVisit(Renderer *renderer, const kmMat4& parentTransf _beforeVisitCmdScissor.func = CC_CALLBACK_0(Layout::onBeforeVisitScissor, this); renderer->addCommand(&_beforeVisitCmdScissor); - Node::visit(renderer, parentTransform, parentTransformUpdated); + ProtectedNode::visit(renderer, parentTransform, parentTransformUpdated); _afterVisitCmdScissor.init(_globalZOrder); _afterVisitCmdScissor.func = CC_CALLBACK_0(Layout::onAfterVisitScissor, this); @@ -566,19 +584,10 @@ void Layout::setBackGroundImageScale9Enabled(bool able) { return; } - Node::removeChild(_backGroundImage); + removeProtectedChild(_backGroundImage); _backGroundImage = nullptr; _backGroundScale9Enabled = able; - if (_backGroundScale9Enabled) - { - _backGroundImage = extension::Scale9Sprite::create(); - Node::addChild(_backGroundImage, BACKGROUNDIMAGE_Z, -1); - } - else - { - _backGroundImage = Sprite::create(); - Node::addChild(_backGroundImage, BACKGROUNDIMAGE_Z, -1); - } + addBackGroundImage(); setBackGroundImage(_backGroundImageFileName.c_str(),_bgImageTexType); setBackGroundImageCapInsets(_backGroundImageCapInsets); } @@ -688,15 +697,13 @@ void Layout::addBackGroundImage() if (_backGroundScale9Enabled) { _backGroundImage = extension::Scale9Sprite::create(); - _backGroundImage->setLocalZOrder(-1); - Node::addChild(_backGroundImage, BACKGROUNDIMAGE_Z, -1); + addProtectedChild(_backGroundImage, BACKGROUNDIMAGE_Z, -1); static_cast(_backGroundImage)->setPreferredSize(_size); } else { _backGroundImage = Sprite::create(); - _backGroundImage->setLocalZOrder(-1); - Node::addChild(_backGroundImage, BACKGROUNDIMAGE_Z, -1); + addProtectedChild(_backGroundImage, BACKGROUNDIMAGE_Z, -1); } _backGroundImage->setPosition(Point(_size.width/2.0f, _size.height/2.0f)); } @@ -707,7 +714,7 @@ void Layout::removeBackGroundImage() { return; } - Node::removeChild(_backGroundImage); + removeProtectedChild(_backGroundImage); _backGroundImage = nullptr; _backGroundImageFileName = ""; _backGroundImageTextureSize = Size::ZERO; @@ -724,26 +731,26 @@ void Layout::setBackGroundColorType(LayoutBackGroundColorType type) case LAYOUT_COLOR_NONE: if (_colorRender) { - Node::removeChild(_colorRender); + removeProtectedChild(_colorRender); _colorRender = nullptr; } if (_gradientRender) { - Node::removeChild(_gradientRender); + removeProtectedChild(_gradientRender); _gradientRender = nullptr; } break; case LAYOUT_COLOR_SOLID: if (_colorRender) { - Node::removeChild(_colorRender); + removeProtectedChild(_colorRender); _colorRender = nullptr; } break; case LAYOUT_COLOR_GRADIENT: if (_gradientRender) { - Node::removeChild(_gradientRender); + removeProtectedChild(_gradientRender); _gradientRender = nullptr; } break; @@ -760,7 +767,7 @@ void Layout::setBackGroundColorType(LayoutBackGroundColorType type) _colorRender->setContentSize(_size); _colorRender->setOpacity(_cOpacity); _colorRender->setColor(_cColor); - Node::addChild(_colorRender, BCAKGROUNDCOLORRENDERER_Z, -1); + addProtectedChild(_colorRender, BCAKGROUNDCOLORRENDERER_Z, -1); break; case LAYOUT_COLOR_GRADIENT: _gradientRender = LayerGradient::create(); @@ -769,7 +776,7 @@ void Layout::setBackGroundColorType(LayoutBackGroundColorType type) _gradientRender->setStartColor(_gStartColor); _gradientRender->setEndColor(_gEndColor); _gradientRender->setVector(_alongVector); - Node::addChild(_gradientRender, BCAKGROUNDCOLORRENDERER_Z, -1); + addProtectedChild(_gradientRender, BCAKGROUNDCOLORRENDERER_Z, -1); break; default: break; @@ -911,9 +918,10 @@ const Size& Layout::getBackGroundImageTextureSize() const void Layout::setLayoutType(LayoutType type) { _layoutType = type; - for (auto& child : _widgetChildren) + for (auto& child : _children) { - if (child) + Widget* widgetChild = dynamic_cast(child); + if (widgetChild) { supplyTheLayoutParameterLackToChild(static_cast(child)); } @@ -946,37 +954,40 @@ void Layout::doLayout() Size layoutSize = getSize(); float topBoundary = layoutSize.height; - for (auto& subWidget : _widgetChildren) + for (auto& subWidget : _children) { - Widget* child = static_cast(subWidget); - LinearLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_LINEAR)); - - if (layoutParameter) + Widget* child = dynamic_cast(subWidget); + if (child) { - LinearGravity childGravity = layoutParameter->getGravity(); - Point ap = child->getAnchorPoint(); - Size cs = child->getSize(); - float finalPosX = ap.x * cs.width; - float finalPosY = topBoundary - ((1.0f-ap.y) * cs.height); - switch (childGravity) + LinearLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_LINEAR)); + + if (layoutParameter) { - case LINEAR_GRAVITY_NONE: - case LINEAR_GRAVITY_LEFT: - break; - case LINEAR_GRAVITY_RIGHT: - finalPosX = layoutSize.width - ((1.0f - ap.x) * cs.width); - break; - case LINEAR_GRAVITY_CENTER_HORIZONTAL: - finalPosX = layoutSize.width / 2.0f - cs.width * (0.5f-ap.x); - break; - default: - break; + LinearGravity childGravity = layoutParameter->getGravity(); + Point ap = child->getAnchorPoint(); + Size cs = child->getSize(); + float finalPosX = ap.x * cs.width; + float finalPosY = topBoundary - ((1.0f-ap.y) * cs.height); + switch (childGravity) + { + case LINEAR_GRAVITY_NONE: + case LINEAR_GRAVITY_LEFT: + break; + case LINEAR_GRAVITY_RIGHT: + finalPosX = layoutSize.width - ((1.0f - ap.x) * cs.width); + break; + case LINEAR_GRAVITY_CENTER_HORIZONTAL: + finalPosX = layoutSize.width / 2.0f - cs.width * (0.5f-ap.x); + break; + default: + break; + } + Margin mg = layoutParameter->getMargin(); + finalPosX += mg.left; + finalPosY -= mg.top; + child->setPosition(Point(finalPosX, finalPosY)); + topBoundary = child->getBottomInParent() - mg.bottom; } - Margin mg = layoutParameter->getMargin(); - finalPosX += mg.left; - finalPosY -= mg.top; - child->setPosition(Point(finalPosX, finalPosY)); - topBoundary = child->getBottomInParent() - mg.bottom; } } break; @@ -985,54 +996,62 @@ void Layout::doLayout() { Size layoutSize = getSize(); float leftBoundary = 0.0f; - for (auto& subWidget : _widgetChildren) + for (auto& subWidget : _children) { - Widget* child = static_cast(subWidget); - LinearLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_LINEAR)); - - if (layoutParameter) + Widget* child = dynamic_cast(subWidget); + if (child) { - LinearGravity childGravity = layoutParameter->getGravity(); - Point ap = child->getAnchorPoint(); - Size cs = child->getSize(); - float finalPosX = leftBoundary + (ap.x * cs.width); - float finalPosY = layoutSize.height - (1.0f - ap.y) * cs.height; - switch (childGravity) + LinearLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_LINEAR)); + if (layoutParameter) { - case LINEAR_GRAVITY_NONE: - case LINEAR_GRAVITY_TOP: - break; - case LINEAR_GRAVITY_BOTTOM: - finalPosY = ap.y * cs.height; - break; - case LINEAR_GRAVITY_CENTER_VERTICAL: - finalPosY = layoutSize.height / 2.0f - cs.height * (0.5f - ap.y); - break; - default: - break; + LinearGravity childGravity = layoutParameter->getGravity(); + Point ap = child->getAnchorPoint(); + Size cs = child->getSize(); + float finalPosX = leftBoundary + (ap.x * cs.width); + float finalPosY = layoutSize.height - (1.0f - ap.y) * cs.height; + switch (childGravity) + { + case LINEAR_GRAVITY_NONE: + case LINEAR_GRAVITY_TOP: + break; + case LINEAR_GRAVITY_BOTTOM: + finalPosY = ap.y * cs.height; + break; + case LINEAR_GRAVITY_CENTER_VERTICAL: + finalPosY = layoutSize.height / 2.0f - cs.height * (0.5f - ap.y); + break; + default: + break; + } + Margin mg = layoutParameter->getMargin(); + finalPosX += mg.left; + finalPosY -= mg.top; + child->setPosition(Point(finalPosX, finalPosY)); + leftBoundary = child->getRightInParent() + mg.right; } - Margin mg = layoutParameter->getMargin(); - finalPosX += mg.left; - finalPosY -= mg.top; - child->setPosition(Point(finalPosX, finalPosY)); - leftBoundary = child->getRightInParent() + mg.right; } } break; } case LAYOUT_RELATIVE: { - ssize_t unlayoutChildCount = _widgetChildren.size(); + ssize_t unlayoutChildCount = 0; Size layoutSize = getSize(); - for (auto& subWidget : _widgetChildren) + Vector widgetChildren; + for (auto& subWidget : _children) { - Widget* child = static_cast(subWidget); - RelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); - layoutParameter->_put = false; + Widget* child = dynamic_cast(subWidget); + if (child) + { + RelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); + layoutParameter->_put = false; + unlayoutChildCount++; + widgetChildren.pushBack(child); + } } while (unlayoutChildCount > 0) { - for (auto& subWidget : _widgetChildren) + for (auto& subWidget : widgetChildren) { Widget* child = static_cast(subWidget); RelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); @@ -1359,6 +1378,7 @@ void Layout::doLayout() } } } + widgetChildren.clear(); break; } default: diff --git a/cocos/ui/UILoadingBar.cpp b/cocos/ui/UILoadingBar.cpp index 643ff18a47..cefe8ed382 100644 --- a/cocos/ui/UILoadingBar.cpp +++ b/cocos/ui/UILoadingBar.cpp @@ -67,7 +67,7 @@ LoadingBar* LoadingBar::create() void LoadingBar::initRenderer() { _barRenderer = Sprite::create(); - Node::addChild(_barRenderer, BAR_RENDERER_Z, -1); + addProtectedChild(_barRenderer, BAR_RENDERER_Z, -1); _barRenderer->setAnchorPoint(Point(0.0,0.5)); } @@ -172,7 +172,7 @@ void LoadingBar::setScale9Enabled(bool enabled) return; } _scale9Enabled = enabled; - Node::removeChild(_barRenderer); + removeProtectedChild(_barRenderer); _barRenderer = nullptr; if (_scale9Enabled) { @@ -183,7 +183,7 @@ void LoadingBar::setScale9Enabled(bool enabled) _barRenderer = Sprite::create(); } loadTexture(_textureFile.c_str(),_renderBarTexType); - Node::addChild(_barRenderer, BAR_RENDERER_Z, -1); + addProtectedChild(_barRenderer, BAR_RENDERER_Z, -1); if (_scale9Enabled) { bool ignoreBefore = _ignoreSize; diff --git a/cocos/ui/UIRichText.cpp b/cocos/ui/UIRichText.cpp index dda09ed551..48a64f7c88 100644 --- a/cocos/ui/UIRichText.cpp +++ b/cocos/ui/UIRichText.cpp @@ -148,7 +148,7 @@ void RichText::initRenderer() { _elementRenderersContainer = Node::create(); _elementRenderersContainer->setAnchorPoint(Point(0.5f, 0.5f)); - Node::addChild(_elementRenderersContainer, 0, -1); + addProtectedChild(_elementRenderersContainer, 0, -1); } void RichText::insertElement(RichElement *element, int index) @@ -436,6 +436,11 @@ void RichText::ignoreContentAdaptWithSize(bool ignore) Widget::ignoreContentAdaptWithSize(ignore); } } + +std::string RichText::getDescription() const +{ + return "RichText"; +} } diff --git a/cocos/ui/UIRichText.h b/cocos/ui/UIRichText.h index 9cf21e3058..d5e0f176b2 100644 --- a/cocos/ui/UIRichText.h +++ b/cocos/ui/UIRichText.h @@ -108,7 +108,8 @@ public: virtual const Size& getContentSize() const; void formatText(); virtual void ignoreContentAdaptWithSize(bool ignore); - + virtual std::string getDescription() const override; + CC_CONSTRUCTOR_ACCESS: virtual bool init() override; diff --git a/cocos/ui/UIScrollView.cpp b/cocos/ui/UIScrollView.cpp index 3b6b4e4421..9d16aa3f80 100644 --- a/cocos/ui/UIScrollView.cpp +++ b/cocos/ui/UIScrollView.cpp @@ -311,46 +311,6 @@ Widget* ScrollView::getChildByName(const char *name) return _innerContainer->getChildByName(name); } -void ScrollView::addNode(Node* node) -{ - Layout::addNode(node); -} - -void ScrollView::addNode(Node * node, int zOrder) -{ - Layout::addNode(node, zOrder); -} - -void ScrollView::addNode(Node* node, int zOrder, int tag) -{ - _innerContainer->addNode(node, zOrder, tag); -} - -Node* ScrollView::getNodeByTag(int tag) -{ - return _innerContainer->getNodeByTag(tag); -} - -Vector& ScrollView::getNodes() -{ - return _innerContainer->getNodes(); -} - -void ScrollView::removeNode(Node* node) -{ - _innerContainer->removeNode(node); -} - -void ScrollView::removeNodeByTag(int tag) -{ - _innerContainer->removeNodeByTag(tag); -} - -void ScrollView::removeAllNodes() -{ - _innerContainer->removeAllNodes(); -} - void ScrollView::moveChildren(float offsetX, float offsetY) { _moveChildPoint = _innerContainer->getPosition() + Point(offsetX, offsetY); diff --git a/cocos/ui/UIScrollView.h b/cocos/ui/UIScrollView.h index 0099b103ca..382bf68533 100644 --- a/cocos/ui/UIScrollView.h +++ b/cocos/ui/UIScrollView.h @@ -286,22 +286,6 @@ public: virtual Widget* getChildByName(const char* name) override; - virtual void addNode(Node* node) override; - - virtual void addNode(Node * node, int zOrder) override; - - virtual void addNode(Node* node, int zOrder, int tag) override; - - virtual Node * getNodeByTag(int tag) override; - - virtual Vector& getNodes() override; - - virtual void removeNode(Node* node) override; - - virtual void removeNodeByTag(int tag) override; - - virtual void removeAllNodes() override; - virtual bool onTouchBegan(Touch *touch, Event *unusedEvent) override; virtual void onTouchMoved(Touch *touch, Event *unusedEvent) override; virtual void onTouchEnded(Touch *touch, Event *unusedEvent) override; diff --git a/cocos/ui/UISlider.cpp b/cocos/ui/UISlider.cpp index 3b0737ef0e..37d6845325 100644 --- a/cocos/ui/UISlider.cpp +++ b/cocos/ui/UISlider.cpp @@ -97,8 +97,8 @@ void Slider::initRenderer() _barRenderer = Sprite::create(); _progressBarRenderer = Sprite::create(); _progressBarRenderer->setAnchorPoint(Point(0.0f, 0.5f)); - Node::addChild(_barRenderer, BASEBAR_RENDERER_Z, -1); - Node::addChild(_progressBarRenderer, PROGRESSBAR_RENDERER_Z, -1); + addProtectedChild(_barRenderer, BASEBAR_RENDERER_Z, -1); + addProtectedChild(_progressBarRenderer, PROGRESSBAR_RENDERER_Z, -1); _slidBallNormalRenderer = Sprite::create(); _slidBallPressedRenderer = Sprite::create(); _slidBallPressedRenderer->setVisible(false); @@ -108,7 +108,7 @@ void Slider::initRenderer() _slidBallRenderer->addChild(_slidBallNormalRenderer); _slidBallRenderer->addChild(_slidBallPressedRenderer); _slidBallRenderer->addChild(_slidBallDisabledRenderer); - Node::addChild(_slidBallRenderer, SLIDBALL_RENDERER_Z, -1); + addProtectedChild(_slidBallRenderer, SLIDBALL_RENDERER_Z, -1); } void Slider::loadBarTexture(const char* fileName, TextureResType texType) @@ -196,8 +196,8 @@ void Slider::setScale9Enabled(bool able) } _scale9Enabled = able; - Node::removeChild(_barRenderer); - Node::removeChild(_progressBarRenderer); + removeProtectedChild(_barRenderer); + removeProtectedChild(_progressBarRenderer); _barRenderer = nullptr; _progressBarRenderer = nullptr; if (_scale9Enabled) @@ -212,8 +212,8 @@ void Slider::setScale9Enabled(bool able) } loadBarTexture(_textureFile.c_str(), _barTexType); loadProgressBarTexture(_progressBarTextureFile.c_str(), _progressBarTexType); - Node::addChild(_barRenderer, BASEBAR_RENDERER_Z, -1); - Node::addChild(_progressBarRenderer, PROGRESSBAR_RENDERER_Z, -1); + addProtectedChild(_barRenderer, BASEBAR_RENDERER_Z, -1); + addProtectedChild(_progressBarRenderer, PROGRESSBAR_RENDERER_Z, -1); if (_scale9Enabled) { bool ignoreBefore = _ignoreSize; diff --git a/cocos/ui/UIText.cpp b/cocos/ui/UIText.cpp index 6dae8a1970..15a021c15d 100644 --- a/cocos/ui/UIText.cpp +++ b/cocos/ui/UIText.cpp @@ -72,7 +72,7 @@ bool Text::init() void Text::initRenderer() { _labelRenderer = Label::create(); - Node::addChild(_labelRenderer, LABEL_RENDERER_Z, -1); + addProtectedChild(_labelRenderer, LABEL_RENDERER_Z, -1); } void Text::setText(const std::string& text) diff --git a/cocos/ui/UITextAtlas.cpp b/cocos/ui/UITextAtlas.cpp index 2258be841a..b3710def7a 100644 --- a/cocos/ui/UITextAtlas.cpp +++ b/cocos/ui/UITextAtlas.cpp @@ -62,7 +62,7 @@ TextAtlas* TextAtlas::create() void TextAtlas::initRenderer() { _labelAtlasRenderer = LabelAtlas::create(); - Node::addChild(_labelAtlasRenderer, LABELATLAS_RENDERER_Z, -1); + addProtectedChild(_labelAtlasRenderer, LABELATLAS_RENDERER_Z, -1); } void TextAtlas::setProperty(const std::string& stringValue, const std::string& charMapFile, int itemWidth, int itemHeight, const std::string& startCharMap) diff --git a/cocos/ui/UITextBMFont.cpp b/cocos/ui/UITextBMFont.cpp index 80906e85d2..d1e31379db 100644 --- a/cocos/ui/UITextBMFont.cpp +++ b/cocos/ui/UITextBMFont.cpp @@ -60,7 +60,7 @@ TextBMFont* TextBMFont::create() void TextBMFont::initRenderer() { _labelBMFontRenderer = cocos2d::LabelBMFont::create(); - Node::addChild(_labelBMFontRenderer, LABELBMFONT_RENDERER_Z, -1); + addProtectedChild(_labelBMFontRenderer, LABELBMFONT_RENDERER_Z, -1); } void TextBMFont::setFntFile(const char *fileName) diff --git a/cocos/ui/UITextField.cpp b/cocos/ui/UITextField.cpp index 41c3d6b583..36b95ff6e1 100644 --- a/cocos/ui/UITextField.cpp +++ b/cocos/ui/UITextField.cpp @@ -392,7 +392,7 @@ void TextField::onEnter() void TextField::initRenderer() { _textFieldRenderer = UICCTextField::create("input words here", "Thonburi", 20); - Node::addChild(_textFieldRenderer, TEXTFIELD_RENDERER_Z, -1); + addProtectedChild(_textFieldRenderer, TEXTFIELD_RENDERER_Z, -1); } void TextField::setTouchSize(const Size &size) diff --git a/cocos/ui/UIWidget.cpp b/cocos/ui/UIWidget.cpp index 9b0068f26f..d35c7b38a2 100644 --- a/cocos/ui/UIWidget.cpp +++ b/cocos/ui/UIWidget.cpp @@ -56,7 +56,6 @@ _positionPercent(Point::ZERO), _reorderWidgetChildDirty(true), _hitted(false), _touchListener(nullptr), -_nodes(NULL), _color(Color3B::WHITE), _opacity(255), _flippedX(false), @@ -69,9 +68,7 @@ Widget::~Widget() { _touchEventListener = nullptr; _touchEventSelector = nullptr; - _widgetChildren.clear(); setTouchEnabled(false); - _nodes.clear(); } Widget* Widget::create() @@ -88,7 +85,7 @@ Widget* Widget::create() bool Widget::init() { - if (Node::init()) + if (ProtectedNode::init()) { initRenderer(); setBright(true); @@ -102,229 +99,75 @@ bool Widget::init() void Widget::onEnter() { updateSizeAndPosition(); - Node::onEnter(); + ProtectedNode::onEnter(); } void Widget::onExit() { unscheduleUpdate(); - Node::onExit(); + ProtectedNode::onExit(); } void Widget::visit(Renderer *renderer, const kmMat4 &parentTransform, bool parentTransformUpdated) { if (_enabled) { - Node::visit(renderer, parentTransform, parentTransformUpdated); + ProtectedNode::visit(renderer, parentTransform, parentTransformUpdated); } } -void Widget::addChild(Node *child) -{ - Node::addChild(child); -} - -void Widget::addChild(Node * child, int zOrder) -{ - Node::addChild(child, zOrder); -} - -void Widget::addChild(Node* child, int zOrder, int tag) -{ - CCASSERT(dynamic_cast(child) != nullptr, "Widget only supports Widgets as children"); - Node::addChild(child, zOrder, tag); - _widgetChildren.pushBack(child); -} - -void Widget::sortAllChildren() -{ - _reorderWidgetChildDirty = _reorderChildDirty; - Node::sortAllChildren(); - if( _reorderWidgetChildDirty ) - { - std::sort( std::begin(_widgetChildren), std::end(_widgetChildren), nodeComparisonLess ); - _reorderWidgetChildDirty = false; - } -} - -Node* Widget::getChildByTag(int aTag) -{ - CCASSERT( aTag != Node::INVALID_TAG, "Invalid tag"); - - for (auto& child : _widgetChildren) - { - if(child && child->getTag() == aTag) - return child; - } - return nullptr; -} - -Vector& Widget::getChildren() -{ - return _widgetChildren; -} - -const Vector& Widget::getChildren() const -{ - return _widgetChildren; -} - -ssize_t Widget::getChildrenCount() const -{ - return _widgetChildren.size(); -} - Widget* Widget::getWidgetParent() { return dynamic_cast(getParent()); } -void Widget::removeFromParent() -{ - removeFromParentAndCleanup(true); -} - -void Widget::removeFromParentAndCleanup(bool cleanup) -{ - Node::removeFromParentAndCleanup(cleanup); -} - -void Widget::removeChild(Node *child, bool cleanup) -{ - Node::removeChild(child, cleanup); - _widgetChildren.eraseObject(child); -} - -void Widget::removeChildByTag(int tag, bool cleanup) -{ - CCASSERT( tag != Node::INVALID_TAG, "Invalid tag"); - - Node *child = getChildByTag(tag); - - if (child == nullptr) - { - CCLOG("cocos2d: removeChildByTag(tag = %d): child not found!", tag); - } - else - { - removeChild(child, cleanup); - } -} - -void Widget::removeAllChildren() -{ - removeAllChildrenWithCleanup(true); -} - -void Widget::removeAllChildrenWithCleanup(bool cleanup) -{ - for (auto& child : _widgetChildren) - { - if (child) - { - Node::removeChild(child); - } - } - _widgetChildren.clear(); -} - void Widget::setEnabled(bool enabled) { _enabled = enabled; - for (auto& child : _widgetChildren) + for (auto& child : _children) { if (child) { - static_cast(child)->setEnabled(enabled); + Widget* widgetChild = dynamic_cast(child); + if (widgetChild) + { + widgetChild->setEnabled(enabled); + } + } + } + + for (auto& child : _protectedChildren) + { + if (child) + { + Widget* widgetChild = dynamic_cast(child); + if (widgetChild) + { + widgetChild->setEnabled(enabled); + } } } } Widget* Widget::getChildByName(const char *name) { - for (auto& child : _widgetChildren) + for (auto& child : _children) { if (child) { - Widget* widgetChild = static_cast(child); - if (strcmp(widgetChild->getName(), name) == 0) + Widget* widgetChild = dynamic_cast(child); + if (widgetChild) { - return widgetChild; + if (strcmp(widgetChild->getName(), name) == 0) + { + return widgetChild; + } } } } return nullptr; } - -void Widget::addNode(Node* node) -{ - addNode(node, node->getLocalZOrder(), node->getTag()); -} - -void Widget::addNode(Node * node, int zOrder) -{ - addNode(node, zOrder, node->getTag()); -} - -void Widget::addNode(Node* node, int zOrder, int tag) -{ - CCAssert(dynamic_cast(node) == nullptr, "Widget only supports Nodes as renderer"); - Node::addChild(node, zOrder, tag); - _nodes.pushBack(node); -} - -Node* Widget::getNodeByTag(int tag) -{ - CCAssert( tag != Node::INVALID_TAG, "Invalid tag"); - - for (auto& node : _nodes) - { - if(node && node->getTag() == tag) - return node; - } - return nullptr; -} - -Vector& Widget::getNodes() -{ - return _nodes; -} - -void Widget::removeNode(Node* node) -{ - Node::removeChild(node); - _nodes.eraseObject(node); -} - -void Widget::removeNodeByTag(int tag) -{ - CCAssert( tag != Node::INVALID_TAG, "Invalid tag"); - - Node *node = this->getNodeByTag(tag); - - if (node == nullptr) - { - CCLOG("cocos2d: removeNodeByTag(tag = %d): child not found!", tag); - } - else - { - this->removeNode(node); - } -} - -void Widget::removeAllNodes() -{ - for (auto& node : _nodes) - { - if (node) - { - Node::removeChild(node); - } - } - _nodes.clear(); -} - - + void Widget::initRenderer() { } @@ -544,9 +387,10 @@ void Widget::onSizeChanged() { for (auto& child : getChildren()) { - if (child) + Widget* widgetChild = dynamic_cast(child); + if (widgetChild) { - static_cast(child)->updateSizeAndPosition(); + widgetChild->updateSizeAndPosition(); } } } @@ -850,7 +694,7 @@ void Widget::setPosition(const Point &pos) } } } - Node::setPosition(pos); + ProtectedNode::setPosition(pos); } void Widget::setPositionPercent(const Point &percent) @@ -986,8 +830,11 @@ void Widget::copyClonedWidgetChildren(Widget* model) for (auto& subWidget : modelChildren) { - Widget* child = static_cast(subWidget); - addChild(child->clone()); + Widget* child = dynamic_cast(subWidget); + if (child) + { + addChild(child->clone()); + } } } diff --git a/cocos/ui/UIWidget.h b/cocos/ui/UIWidget.h index 9e0f70e7db..fd08ce6d41 100644 --- a/cocos/ui/UIWidget.h +++ b/cocos/ui/UIWidget.h @@ -25,7 +25,7 @@ THE SOFTWARE. #ifndef __UIWIDGET_H__ #define __UIWIDGET_H__ -#include "CCNode.h" +#include "ui/CCProtectedNode.h" #include "ui/UILayoutDefine.h" #include "ui/UILayoutParameter.h" #include "ui/GUIDefine.h" @@ -79,7 +79,7 @@ typedef void (Ref::*SEL_TouchEvent)(Ref*,TouchEventType); * @js NA * @lua NA */ -class Widget : public Node +class Widget : public ProtectedNode { public: /** @@ -199,114 +199,6 @@ public: */ float getTopInParent(); - /** - * Adds a child to the container with z-order as 0. - * - * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. - * - * @param child A child node - */ - virtual void addChild(Node * child) override; - /** - * Adds a child to the container with a z-order - * - * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. - * - * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setLocalZOrder(int) - */ - virtual void addChild(Node * child, int zOrder) override; - /** - * Adds a child to the container with z order and tag - * - * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. - * - * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setLocalZOrder(int) - * @param tag A interger to identify the node easily. Please refer to setTag(int) - */ - virtual void addChild(Node* child, int zOrder, int tag) override; - /** - * Gets a child from the container with its tag - * - * @param tag An identifier to find the child node. - * - * @return a Node object whose tag equals to the input parameter - */ - virtual Node * getChildByTag(int tag) override; - - virtual void sortAllChildren() override; - /** - * Return an array of children - * - * Composing a "tree" structure is a very important feature of Node - * Here's a sample code of traversing children array: - @code - Node* node = NULL; - CCARRAY_FOREACH(parent->getChildren(), node) - { - node->setPosition(0,0); - } - @endcode - * This sample code traverses all children nodes, and set their position to (0,0) - * - * @return An array of children - */ - virtual Vector& getChildren() override; - virtual const Vector& getChildren() const override; - - /** - * Get the amount of children. - * - * @return The amount of children. - */ - virtual ssize_t getChildrenCount() const override; - - /** - * Removes this node itself from its parent node with a cleanup. - * If the node orphan, then nothing happens. - * @see `removeFromParentAndCleanup(bool)` - */ - virtual void removeFromParent() override; - /** - * Removes this node itself from its parent node. - * If the node orphan, then nothing happens. - * @param cleanup true if all actions and callbacks on this node should be removed, false otherwise. - * @js removeFromParent - * @lua removeFromParent - */ - virtual void removeFromParentAndCleanup(bool cleanup) override; - - /** - * Removes a child from the container. It will also cleanup all running actions depending on the cleanup parameter. - * - * @param child The child node which will be removed. - * @param cleanup true if all running actions and callbacks on the child node will be cleanup, false otherwise. - */ - virtual void removeChild(Node* child, bool cleanup = true) override; - - /** - * Removes a child from the container by tag value. It will also cleanup all running actions depending on the cleanup parameter - * - * @param tag An interger number that identifies a child node - * @param cleanup true if all running actions and callbacks on the child node will be cleanup, false otherwise. - */ - virtual void removeChildByTag(int tag, bool cleanup = true) override; - /** - * Removes all children from the container with a cleanup. - * - * @see `removeAllChildrenWithCleanup(bool)` - */ - virtual void removeAllChildren() override; - /** - * Removes all children from the container, and do a cleanup to all running actions depending on the cleanup parameter. - * - * @param cleanup true if all running actions on all children nodes should be cleanup, false oterwise. - * @js removeAllChildren - * @lua removeAllChildren - */ - virtual void removeAllChildrenWithCleanup(bool cleanup) override; - /** * Gets a child from the container with its name * @@ -316,22 +208,6 @@ public: */ virtual Widget* getChildByName(const char* name); - virtual void addNode(Node* node); - - virtual void addNode(Node * node, int zOrder); - - virtual void addNode(Node* node, int zOrder, int tag); - - virtual Node * getNodeByTag(int tag); - - virtual Vector& getNodes(); - - virtual void removeNode(Node* node); - - virtual void removeNodeByTag(int tag); - - virtual void removeAllNodes(); - virtual void visit(cocos2d::Renderer *renderer, const kmMat4 &parentTransform, bool parentTransformUpdated) override; /** @@ -713,13 +589,11 @@ protected: bool _reorderWidgetChildDirty; bool _hitted; EventListenerTouchOneByOne* _touchListener; - Vector _nodes; Color3B _color; GLubyte _opacity; bool _flippedX; bool _flippedY; Map _layoutParameterDictionary; - Vector _widgetChildren; }; } diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIWidgetAddNodeTest/UIWidgetAddNodeTest.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIWidgetAddNodeTest/UIWidgetAddNodeTest.cpp index b50be77f77..456abac008 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIWidgetAddNodeTest/UIWidgetAddNodeTest.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIWidgetAddNodeTest/UIWidgetAddNodeTest.cpp @@ -36,7 +36,7 @@ bool UIWidgetAddNodeTest::init() Sprite* sprite = Sprite::create("cocosui/ccicon.png"); sprite->setPosition(Point(0, sprite->getBoundingBox().size.height / 4)); - widget->addNode(sprite); + widget->addChild(sprite); return true; } diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIWidgetAddNodeTest/UIWidgetAddNodeTest_Editor.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIWidgetAddNodeTest/UIWidgetAddNodeTest_Editor.cpp index 6bc4101250..d4ad1b94f9 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIWidgetAddNodeTest/UIWidgetAddNodeTest_Editor.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/UIWidgetAddNodeTest/UIWidgetAddNodeTest_Editor.cpp @@ -41,7 +41,7 @@ bool UIWidgetAddNodeTest_Editor::init() _layout->addChild(widget); Sprite* sprite = Sprite::create("cocosui/ccicon.png"); - widget->addNode(sprite); + widget->addChild(sprite); return true; } From c0b67e6d1b4b11d1e508c5bb62e1c066ccf24006 Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Mon, 24 Mar 2014 15:43:18 +0800 Subject: [PATCH 062/106] Modify mk files --- cocos/ui/Android.mk | 3 ++- cocos/ui/CMakeLists.txt | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/cocos/ui/Android.mk b/cocos/ui/Android.mk index ed93d6060a..bf3e2ce5a5 100644 --- a/cocos/ui/Android.mk +++ b/cocos/ui/Android.mk @@ -24,7 +24,8 @@ UITextBMFont.cpp \ UILoadingBar.cpp \ UISlider.cpp \ UITextField.cpp \ -UIRichText.cpp +UIRichText.cpp \ +CCProtectedNode.cpp LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/.. \ diff --git a/cocos/ui/CMakeLists.txt b/cocos/ui/CMakeLists.txt index 8843bed83e..cc41a5f95b 100644 --- a/cocos/ui/CMakeLists.txt +++ b/cocos/ui/CMakeLists.txt @@ -18,6 +18,7 @@ set(GUI_SRC UISlider.cpp UITextField.cpp UIRichText.cpp + CCProtectedNode.cpp ) add_library(ui STATIC From 9a8cf6d81307791082ecb3ba5be108f83316bd97 Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Mon, 24 Mar 2014 16:22:44 +0800 Subject: [PATCH 063/106] Modify Windows Project --- cocos/ui/proj.win32/libGUI.vcxproj | 2 ++ cocos/ui/proj.win32/libGUI.vcxproj.filters | 6 ++++++ 2 files changed, 8 insertions(+) diff --git a/cocos/ui/proj.win32/libGUI.vcxproj b/cocos/ui/proj.win32/libGUI.vcxproj index 3dad252cfe..7d5aa4d0e6 100644 --- a/cocos/ui/proj.win32/libGUI.vcxproj +++ b/cocos/ui/proj.win32/libGUI.vcxproj @@ -11,6 +11,7 @@ + @@ -33,6 +34,7 @@ + diff --git a/cocos/ui/proj.win32/libGUI.vcxproj.filters b/cocos/ui/proj.win32/libGUI.vcxproj.filters index d79c8a4a8d..a01b4594d2 100644 --- a/cocos/ui/proj.win32/libGUI.vcxproj.filters +++ b/cocos/ui/proj.win32/libGUI.vcxproj.filters @@ -78,6 +78,9 @@ UIWidgets + + BaseClasses + @@ -137,5 +140,8 @@ UIWidgets + + BaseClasses + \ No newline at end of file From 19341ceaf42fe3bbb8fed7e9ca8a6f08d58bab8c Mon Sep 17 00:00:00 2001 From: LinWenhai Date: Tue, 25 Mar 2014 14:54:42 +0800 Subject: [PATCH 064/106] add getter of ClipMarginEnabled. --- cocos/2d/CCLabel.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/CCLabel.h b/cocos/2d/CCLabel.h index dc9271d8ab..c453112cb4 100644 --- a/cocos/2d/CCLabel.h +++ b/cocos/2d/CCLabel.h @@ -220,7 +220,7 @@ public: /** clip upper and lower margin for reduce height of label. */ void setClipMarginEnabled(bool clipEnabled) { _clipEnabled = clipEnabled; } - + bool getClipMarginEnabled() const { return _clipEnabled; } // font related stuff int getCommonLineHeight() const; From 45b98e7dc01bd3904119b7d973482cf2ab6772f8 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 25 Mar 2014 15:07:11 +0800 Subject: [PATCH 065/106] issue #4541: s_globalOrderOfArrival is an static variable of Node class. --- cocos/2d/CCNode.cpp | 2 +- cocos/2d/CCNode.h | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 9125d50393..b086275606 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -72,7 +72,7 @@ bool nodeComparisonLess(Node* n1, Node* n2) } // XXX: Yes, nodes might have a sort problem once every 15 days if the game runs at 60 FPS and each frame sprites are reordered. -static int s_globalOrderOfArrival = 1; +int Node::s_globalOrderOfArrival = 1; Node::Node(void) : _rotationX(0.0f) diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index 249ef11de9..d1f6859315 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -1452,6 +1452,8 @@ protected: bool _cascadeColorEnabled; bool _cascadeOpacityEnabled; + static int s_globalOrderOfArrival; + private: CC_DISALLOW_COPY_AND_ASSIGN(Node); }; From 91347aca0c80ae631a112434c393d535314c6a88 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 25 Mar 2014 15:07:46 +0800 Subject: [PATCH 066/106] closed #4541: Removes wrong coments in CCProtectedNode.h. --- cocos/ui/CCProtectedNode.h | 32 -------------------------------- 1 file changed, 32 deletions(-) diff --git a/cocos/ui/CCProtectedNode.h b/cocos/ui/CCProtectedNode.h index 7ff20e55b3..f2b297d430 100644 --- a/cocos/ui/CCProtectedNode.h +++ b/cocos/ui/CCProtectedNode.h @@ -34,38 +34,6 @@ NS_CC_BEGIN - -/** - * @addtogroup base_nodes - * @{ - */ - -/** @brief Node is the base element of the Scene Graph. Elements of the Scene Graph must be Node objects or subclasses of it. - The most common Node objects are: Scene, Layer, Sprite, Menu, Label. - - The main features of a Node are: - - They can contain other Node objects (`addChild`, `getChildByTag`, `removeChild`, etc) - - They can schedule periodic callback (`schedule`, `unschedule`, etc) - - They can execute actions (`runAction`, `stopAction`, etc) - - Subclassing a Node usually means (one/all) of: - - overriding init to initialize resources and schedule callbacks - - create callbacks to handle the advancement of time - - overriding `draw` to render the node - - Properties of Node: - - position (default: x=0, y=0) - - scale (default: x=1, y=1) - - rotation (in degrees, clockwise) (default: 0) - - anchor point (default: x=0, y=0) - - contentSize (default: width=0, height=0) - - visible (default: true) - - Limitations: - - A Node is a "void" object. If you want to draw something on the screen, you should use a Sprite instead. Or subclass Node and override `draw`. - - */ - class CC_DLL ProtectedNode : public Node { public: From b40127ea995a9817e79e37c195cf408291f73a9d Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 25 Mar 2014 15:32:14 +0800 Subject: [PATCH 067/106] Never include '.cpp' files. --- cocos/ui/CCProtectedNode.cpp | 5 ----- 1 file changed, 5 deletions(-) diff --git a/cocos/ui/CCProtectedNode.cpp b/cocos/ui/CCProtectedNode.cpp index 7a4abf44f4..d8a12940ec 100644 --- a/cocos/ui/CCProtectedNode.cpp +++ b/cocos/ui/CCProtectedNode.cpp @@ -35,13 +35,8 @@ #endif #include "CCScene.h" -#include "CCNode.cpp" - NS_CC_BEGIN -// XXX: Yes, nodes might have a sort problem once every 15 days if the game runs at 60 FPS and each frame sprites are reordered. -//static int s_globalOrderOfArrival = 1; - ProtectedNode::ProtectedNode() : _reorderProtectedChildDirty(false) { } From 86f69a0b4ebf5ec7db8a9c1f662472a7b9cd871f Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Tue, 25 Mar 2014 07:39:29 +0000 Subject: [PATCH 068/106] [AUTO]: updating luabinding automatically --- cocos/scripting/lua-bindings/auto/api/ParticleSystem.lua | 8 ++++---- .../auto/lua_cocos2dx_auto.cpp.REMOVED.git-id | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/cocos/scripting/lua-bindings/auto/api/ParticleSystem.lua b/cocos/scripting/lua-bindings/auto/api/ParticleSystem.lua index 4c463ae45f..62d6e4eacc 100644 --- a/cocos/scripting/lua-bindings/auto/api/ParticleSystem.lua +++ b/cocos/scripting/lua-bindings/auto/api/ParticleSystem.lua @@ -406,9 +406,9 @@ -- @return color4F_table#color4F_table ret (return value: color4F_table) -------------------------------- --- @function [parent=#ParticleSystem] getRotationIsDir +-- @function [parent=#ParticleSystem] getEndColor -- @param self --- @return bool#bool ret (return value: bool) +-- @return color4F_table#color4F_table ret (return value: color4F_table) -------------------------------- -- @function [parent=#ParticleSystem] setScale @@ -421,9 +421,9 @@ -- @return float#float ret (return value: float) -------------------------------- --- @function [parent=#ParticleSystem] getEndColor +-- @function [parent=#ParticleSystem] getRotationIsDir -- @param self --- @return color4F_table#color4F_table ret (return value: color4F_table) +-- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#ParticleSystem] getLifeVar diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_auto.cpp.REMOVED.git-id b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_auto.cpp.REMOVED.git-id index 0c4a69c0cc..4131e54b6b 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_auto.cpp.REMOVED.git-id +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_auto.cpp.REMOVED.git-id @@ -1 +1 @@ -adb82cd767b31065425c12591d380c419a3d88ae \ No newline at end of file +83d9fece450a67211518c287e9ecf99ce122c142 \ No newline at end of file From c642d4d4c469018bb16855da0e2f1e491c26e93c Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Tue, 25 Mar 2014 15:43:42 +0800 Subject: [PATCH 069/106] update templates for remove native activity --- .../proj.android/AndroidManifest.xml | 2 +- .../proj.android/jni/hellocpp/main.cpp | 2 +- .../src/org/cocos2dx/cpp/AppActivity.java | 32 +++++++++++++ .../org/cocos2dx/cpp/Cocos2dxActivity.java | 35 -------------- .../proj.android/AndroidManifest.xml | 2 +- .../proj.android/jni/hellolua/main.cpp | 2 +- .../src/org/cocos2dx/lua/AppActivity.java | 32 +++++++++++++ .../org/cocos2dx/lua/Cocos2dxActivity.java | 35 -------------- .../proj.android/AndroidManifest.xml | 2 +- .../jni/hellolua/Runtime_android.cpp | 4 +- .../proj.android/jni/hellolua/main.cpp | 2 +- ...Cocos2dxActivity.java => AppActivity.java} | 46 ++++++++++++------- 12 files changed, 101 insertions(+), 95 deletions(-) create mode 100644 templates/cpp-template-default/proj.android/src/org/cocos2dx/cpp/AppActivity.java delete mode 100644 templates/cpp-template-default/proj.android/src/org/cocos2dx/cpp/Cocos2dxActivity.java create mode 100644 templates/lua-template-default/frameworks/runtime-src/proj.android/src/org/cocos2dx/lua/AppActivity.java delete mode 100644 templates/lua-template-default/frameworks/runtime-src/proj.android/src/org/cocos2dx/lua/Cocos2dxActivity.java rename templates/lua-template-runtime/frameworks/runtime-src/proj.android/src/org/cocos2dx/lua/{Cocos2dxActivity.java => AppActivity.java} (61%) diff --git a/templates/cpp-template-default/proj.android/AndroidManifest.xml b/templates/cpp-template-default/proj.android/AndroidManifest.xml index fc2ab5cfd2..03b6257326 100644 --- a/templates/cpp-template-default/proj.android/AndroidManifest.xml +++ b/templates/cpp-template-default/proj.android/AndroidManifest.xml @@ -11,7 +11,7 @@ android:icon="@drawable/icon"> - delete - //EGL_GREEN_SIZE, 6, -->delete - //EGL_RED_SIZE, 5, -->delete - EGL_BUFFER_SIZE, 32, //-->new field - EGL_DEPTH_SIZE, 16, - EGL_STENCIL_SIZE, 8, - EGL_NONE - };*/ - - //2.Set the format of window - // getWindow().setFormat(PixelFormat.TRANSLUCENT); - - } -} diff --git a/templates/lua-template-default/frameworks/runtime-src/proj.android/AndroidManifest.xml b/templates/lua-template-default/frameworks/runtime-src/proj.android/AndroidManifest.xml index 706278b3a6..d83b700b63 100644 --- a/templates/lua-template-default/frameworks/runtime-src/proj.android/AndroidManifest.xml +++ b/templates/lua-template-default/frameworks/runtime-src/proj.android/AndroidManifest.xml @@ -10,7 +10,7 @@ - delete - //EGL_GREEN_SIZE, 6, -->delete - //EGL_RED_SIZE, 5, -->delete - EGL_BUFFER_SIZE, 32, //-->new field - EGL_DEPTH_SIZE, 16, - EGL_STENCIL_SIZE, 8, - EGL_NONE - };*/ - - //2.Set the format of window - // getWindow().setFormat(PixelFormat.TRANSLUCENT); - } - -} diff --git a/templates/lua-template-runtime/frameworks/runtime-src/proj.android/AndroidManifest.xml b/templates/lua-template-runtime/frameworks/runtime-src/proj.android/AndroidManifest.xml index 706278b3a6..d83b700b63 100644 --- a/templates/lua-template-runtime/frameworks/runtime-src/proj.android/AndroidManifest.xml +++ b/templates/lua-template-runtime/frameworks/runtime-src/proj.android/AndroidManifest.xml @@ -10,7 +10,7 @@ - CallStaticObjectMethod(t.classID, t.methodID); t.env->DeleteLocalRef(t.classID); sdcardPath = JniHelper::jstring2string(str); @@ -26,7 +26,7 @@ string getIPAddress() JniMethodInfo t; string IPAddress(""); - if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lua/Cocos2dxActivity", "getLocalIpAddress", "()Ljava/lang/String;")) { + if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lua/AppActivity", "getLocalIpAddress", "()Ljava/lang/String;")) { jstring str = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID); t.env->DeleteLocalRef(t.classID); IPAddress = JniHelper::jstring2string(str); diff --git a/templates/lua-template-runtime/frameworks/runtime-src/proj.android/jni/hellolua/main.cpp b/templates/lua-template-runtime/frameworks/runtime-src/proj.android/jni/hellolua/main.cpp index a8b36b317d..980411792f 100644 --- a/templates/lua-template-runtime/frameworks/runtime-src/proj.android/jni/hellolua/main.cpp +++ b/templates/lua-template-runtime/frameworks/runtime-src/proj.android/jni/hellolua/main.cpp @@ -10,7 +10,7 @@ using namespace cocos2d; -void cocos_android_app_init (struct android_app* app) { +void cocos_android_app_init (JNIEnv* env, jobject thiz) { LOGD("cocos_android_app_init"); AppDelegate *pAppDelegate = new AppDelegate(); } diff --git a/templates/lua-template-runtime/frameworks/runtime-src/proj.android/src/org/cocos2dx/lua/Cocos2dxActivity.java b/templates/lua-template-runtime/frameworks/runtime-src/proj.android/src/org/cocos2dx/lua/AppActivity.java similarity index 61% rename from templates/lua-template-runtime/frameworks/runtime-src/proj.android/src/org/cocos2dx/lua/Cocos2dxActivity.java rename to templates/lua-template-runtime/frameworks/runtime-src/proj.android/src/org/cocos2dx/lua/AppActivity.java index 76e0797690..0a013e908c 100644 --- a/templates/lua-template-runtime/frameworks/runtime-src/proj.android/src/org/cocos2dx/lua/Cocos2dxActivity.java +++ b/templates/lua-template-runtime/frameworks/runtime-src/proj.android/src/org/cocos2dx/lua/AppActivity.java @@ -1,3 +1,29 @@ +/**************************************************************************** +Copyright (c) 2008-2010 Ricardo Quesada +Copyright (c) 2010-2012 cocos2d-x.org +Copyright (c) 2011 Zynga Inc. +Copyright (c) 2013-2014 Chukong Technologies Inc. + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************/ package org.cocos2dx.lua; import java.net.InetAddress; @@ -5,7 +31,7 @@ import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; -import android.app.NativeActivity; +import org.cocos2dx.lib.Cocos2dxActivity; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; @@ -19,28 +45,13 @@ import android.widget.Toast; // The name of .so is specified in AndroidMenifest.xml. NativityActivity will load it automatically for you. // You can use "System.loadLibrary()" to load other .so files. -public class Cocos2dxActivity extends NativeActivity{ +public class AppActivity extends Cocos2dxActivity{ @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); - //For supports translucency - - //1.change "attribs" in cocos\2d\platform\android\nativeactivity.cpp - /*const EGLint attribs[] = { - EGL_SURFACE_TYPE, EGL_WINDOW_BIT, - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - //EGL_BLUE_SIZE, 5, -->delete - //EGL_GREEN_SIZE, 6, -->delete - //EGL_RED_SIZE, 5, -->delete - EGL_BUFFER_SIZE, 32, //-->new field - EGL_DEPTH_SIZE, 16, - EGL_STENCIL_SIZE, 8, - EGL_NONE - };*/ - //2.Set the format of window // getWindow().setFormat(PixelFormat.TRANSLUCENT); if(!isWifiConnected()) @@ -89,3 +100,4 @@ public class Cocos2dxActivity extends NativeActivity{ } } + From 933d9c047605ce4f2a694668e92315e91e96fdac Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Tue, 25 Mar 2014 07:49:38 +0000 Subject: [PATCH 070/106] [AUTO][ci skip]: updating cocos2dx_files.json --- templates/cocos2dx_files.json.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates/cocos2dx_files.json.REMOVED.git-id b/templates/cocos2dx_files.json.REMOVED.git-id index 1c31d78c7e..5a0b0a9028 100644 --- a/templates/cocos2dx_files.json.REMOVED.git-id +++ b/templates/cocos2dx_files.json.REMOVED.git-id @@ -1 +1 @@ -9be9de64b36c123c9aba99c3149937136749b712 \ No newline at end of file +fa70974de744fb12ec4f753989e6e0a7eb9fc73a \ No newline at end of file From 27d25a38f18eedb0b7ba02f7ff2cc08f059700f1 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 25 Mar 2014 15:49:56 +0800 Subject: [PATCH 071/106] Update CHANGELOG [ci skip] --- CHANGELOG.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.REMOVED.git-id b/CHANGELOG.REMOVED.git-id index 4927d8c901..af31d79c6e 100644 --- a/CHANGELOG.REMOVED.git-id +++ b/CHANGELOG.REMOVED.git-id @@ -1 +1 @@ -8346ec38d8e813be64d7d24636c2cea248b8bbfc \ No newline at end of file +819b72559f8be48c41958b0afb4c6513207b453a \ No newline at end of file From bdcd6ea198117700d6183bc1593896fcd62bbc4f Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Tue, 25 Mar 2014 08:13:42 +0000 Subject: [PATCH 072/106] [AUTO]: updating luabinding automatically --- .../lua-bindings/auto/api/RichText.lua | 5 + .../lua-bindings/auto/api/ScrollView.lua | 86 +++------- .../lua-bindings/auto/api/Widget.lua | 159 +++--------------- .../lua_cocos2dx_ui_auto.cpp.REMOVED.git-id | 2 +- .../auto/lua_cocos2dx_ui_auto.hpp | 6 - 5 files changed, 57 insertions(+), 201 deletions(-) diff --git a/cocos/scripting/lua-bindings/auto/api/RichText.lua b/cocos/scripting/lua-bindings/auto/api/RichText.lua index 3c181b3a2d..b14dcddf9e 100644 --- a/cocos/scripting/lua-bindings/auto/api/RichText.lua +++ b/cocos/scripting/lua-bindings/auto/api/RichText.lua @@ -52,6 +52,11 @@ -- @param self -- @return RichText#RichText ret (return value: ccui.RichText) +-------------------------------- +-- @function [parent=#RichText] getDescription +-- @param self +-- @return string#string ret (return value: string) + -------------------------------- -- @function [parent=#RichText] RichText -- @param self diff --git a/cocos/scripting/lua-bindings/auto/api/ScrollView.lua b/cocos/scripting/lua-bindings/auto/api/ScrollView.lua index 66b3f739f6..b5532e0192 100644 --- a/cocos/scripting/lua-bindings/auto/api/ScrollView.lua +++ b/cocos/scripting/lua-bindings/auto/api/ScrollView.lua @@ -187,58 +187,22 @@ -- @param #int int -- @param #int int +-------------------------------- +-- @function [parent=#ScrollView] getChildByName +-- @param self +-- @param #char char +-- @return Widget#Widget ret (return value: ccui.Widget) + -------------------------------- -- @function [parent=#ScrollView] getDescription -- @param self -- @return string#string ret (return value: string) -------------------------------- --- @function [parent=#ScrollView] removeAllChildren +-- @function [parent=#ScrollView] update -- @param self +-- @param #float float --------------------------------- --- overload function: getChildren() --- --- overload function: getChildren() --- --- @function [parent=#ScrollView] getChildren --- @param self --- @return array_table#array_table ret (retunr value: array_table) - --------------------------------- --- @function [parent=#ScrollView] getNodes --- @param self --- @return array_table#array_table ret (return value: array_table) - --------------------------------- --- @function [parent=#ScrollView] getChildByTag --- @param self --- @param #int int --- @return Node#Node ret (return value: cc.Node) - --------------------------------- --- @function [parent=#ScrollView] removeNode --- @param self --- @param #cc.Node node - --------------------------------- --- @function [parent=#ScrollView] removeNodeByTag --- @param self --- @param #int int - --------------------------------- --- overload function: addNode(cc.Node, int) --- --- overload function: addNode(cc.Node) --- --- overload function: addNode(cc.Node, int, int) --- --- @function [parent=#ScrollView] addNode --- @param self --- @param #cc.Node node --- @param #int int --- @param #int int - -------------------------------- -- @function [parent=#ScrollView] getLayoutType -- @param self @@ -250,24 +214,7 @@ -- @param #bool bool -------------------------------- --- @function [parent=#ScrollView] update --- @param self --- @param #float float - --------------------------------- --- @function [parent=#ScrollView] getNodeByTag --- @param self --- @param #int int --- @return Node#Node ret (return value: cc.Node) - --------------------------------- --- @function [parent=#ScrollView] getChildByName --- @param self --- @param #char char --- @return Widget#Widget ret (return value: ccui.Widget) - --------------------------------- --- @function [parent=#ScrollView] removeAllNodes +-- @function [parent=#ScrollView] removeAllChildren -- @param self -------------------------------- @@ -276,6 +223,21 @@ -- @param #cc.Node node -- @param #bool bool +-------------------------------- +-- overload function: getChildren() +-- +-- overload function: getChildren() +-- +-- @function [parent=#ScrollView] getChildren +-- @param self +-- @return array_table#array_table ret (retunr value: array_table) + +-------------------------------- +-- @function [parent=#ScrollView] getChildByTag +-- @param self +-- @param #int int +-- @return Node#Node ret (return value: cc.Node) + -------------------------------- -- @function [parent=#ScrollView] getChildrenCount -- @param self diff --git a/cocos/scripting/lua-bindings/auto/api/Widget.lua b/cocos/scripting/lua-bindings/auto/api/Widget.lua index 5bea038c34..1f97832c9f 100644 --- a/cocos/scripting/lua-bindings/auto/api/Widget.lua +++ b/cocos/scripting/lua-bindings/auto/api/Widget.lua @@ -1,18 +1,13 @@ -------------------------------- -- @module Widget --- @extend Node +-- @extend ProtectedNode -------------------------------- -- @function [parent=#Widget] setSizePercent -- @param self -- @param #point_table point --------------------------------- --- @function [parent=#Widget] isFlippedX --- @param self --- @return bool#bool ret (return value: bool) - -------------------------------- -- @function [parent=#Widget] getCustomSize -- @param self @@ -29,10 +24,9 @@ -- @param #bool bool -------------------------------- --- @function [parent=#Widget] getNodeByTag +-- @function [parent=#Widget] getLeftInParent -- @param self --- @param #int int --- @return Node#Node ret (return value: cc.Node) +-- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#Widget] getTouchEndPos @@ -44,11 +38,6 @@ -- @param self -- @param #point_table point --------------------------------- --- @function [parent=#Widget] getNodes --- @param self --- @return array_table#array_table ret (return value: array_table) - -------------------------------- -- @function [parent=#Widget] getLayoutSize -- @param self @@ -69,15 +58,6 @@ -- @param self -- @return bool#bool ret (return value: bool) --------------------------------- --- overload function: updateSizeAndPosition(size_table) --- --- overload function: updateSizeAndPosition() --- --- @function [parent=#Widget] updateSizeAndPosition --- @param self --- @param #size_table size - -------------------------------- -- @function [parent=#Widget] getBottomInParent -- @param self @@ -100,9 +80,9 @@ -- @return PositionType#PositionType ret (return value: ccui.PositionType) -------------------------------- --- @function [parent=#Widget] setName +-- @function [parent=#Widget] getWidgetType -- @param self --- @param #char char +-- @return WidgetType#WidgetType ret (return value: ccui.WidgetType) -------------------------------- -- @function [parent=#Widget] getChildByName @@ -116,9 +96,9 @@ -- @return bool#bool ret (return value: bool) -------------------------------- --- @function [parent=#Widget] removeNodeByTag +-- @function [parent=#Widget] isFocused -- @param self --- @param #int int +-- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#Widget] isTouchEnabled @@ -175,18 +155,10 @@ -- @param #ccui.BrightStyle brightstyle -------------------------------- --- overload function: addNode(cc.Node, int) --- --- overload function: addNode(cc.Node) --- --- overload function: addNode(cc.Node, int, int) --- --- @function [parent=#Widget] addNode +-- @function [parent=#Widget] setName -- @param self --- @param #cc.Node node --- @param #int int --- @param #int int - +-- @param #char char + -------------------------------- -- @function [parent=#Widget] setLayoutParameter -- @param self @@ -202,21 +174,11 @@ -- @param self -- @return point_table#point_table ret (return value: point_table) --------------------------------- --- @function [parent=#Widget] getLeftInParent --- @param self --- @return float#float ret (return value: float) - -------------------------------- -- @function [parent=#Widget] setActionTag -- @param self -- @param #int int --------------------------------- --- @function [parent=#Widget] ignoreContentAdaptWithSize --- @param self --- @param #bool bool - -------------------------------- -- @function [parent=#Widget] isBright -- @param self @@ -234,10 +196,14 @@ -- @return float#float ret (return value: float) -------------------------------- --- @function [parent=#Widget] getWidgetType +-- overload function: updateSizeAndPosition(size_table) +-- +-- overload function: updateSizeAndPosition() +-- +-- @function [parent=#Widget] updateSizeAndPosition -- @param self --- @return WidgetType#WidgetType ret (return value: ccui.WidgetType) - +-- @param #size_table size + -------------------------------- -- @function [parent=#Widget] getSize -- @param self @@ -254,13 +220,9 @@ -- @return SizeType#SizeType ret (return value: ccui.SizeType) -------------------------------- --- @function [parent=#Widget] removeNode --- @param self --- @param #cc.Node node - --------------------------------- --- @function [parent=#Widget] removeAllNodes +-- @function [parent=#Widget] ignoreContentAdaptWithSize -- @param self +-- @param #bool bool -------------------------------- -- @function [parent=#Widget] getPositionPercent @@ -274,7 +236,7 @@ -- @return bool#bool ret (return value: bool) -------------------------------- --- @function [parent=#Widget] isFocused +-- @function [parent=#Widget] isFlippedX -- @param self -- @return bool#bool ret (return value: bool) @@ -310,72 +272,11 @@ -- @param self -- @return Widget#Widget ret (return value: ccui.Widget) --------------------------------- --- overload function: addChild(cc.Node, int) --- --- overload function: addChild(cc.Node) --- --- overload function: addChild(cc.Node, int, int) --- --- @function [parent=#Widget] addChild --- @param self --- @param #cc.Node node --- @param #int int --- @param #int int - -------------------------------- -- @function [parent=#Widget] setColor -- @param self -- @param #color3B_table color3b --------------------------------- --- @function [parent=#Widget] removeFromParent --- @param self - --------------------------------- --- @function [parent=#Widget] removeAllChildrenWithCleanup --- @param self --- @param #bool bool - --------------------------------- --- @function [parent=#Widget] removeAllChildren --- @param self - --------------------------------- --- @function [parent=#Widget] sortAllChildren --- @param self - --------------------------------- --- @function [parent=#Widget] removeChild --- @param self --- @param #cc.Node node --- @param #bool bool - --------------------------------- --- overload function: getChildren() --- --- overload function: getChildren() --- --- @function [parent=#Widget] getChildren --- @param self --- @return array_table#array_table ret (retunr value: array_table) - --------------------------------- --- @function [parent=#Widget] getDescription --- @param self --- @return string#string ret (return value: string) - --------------------------------- --- @function [parent=#Widget] getChildByTag --- @param self --- @param #int int --- @return Node#Node ret (return value: cc.Node) - --------------------------------- --- @function [parent=#Widget] removeFromParentAndCleanup --- @param self --- @param #bool bool - -------------------------------- -- @function [parent=#Widget] getColor -- @param self @@ -386,26 +287,20 @@ -- @param self -- @param #unsigned char char --------------------------------- --- @function [parent=#Widget] setPosition --- @param self --- @param #point_table point - --------------------------------- --- @function [parent=#Widget] removeChildByTag --- @param self --- @param #int int --- @param #bool bool - -------------------------------- -- @function [parent=#Widget] getOpacity -- @param self -- @return unsigned char#unsigned char ret (return value: unsigned char) -------------------------------- --- @function [parent=#Widget] getChildrenCount +-- @function [parent=#Widget] setPosition -- @param self --- @return long#long ret (return value: long) +-- @param #point_table point + +-------------------------------- +-- @function [parent=#Widget] getDescription +-- @param self +-- @return string#string ret (return value: string) -------------------------------- -- @function [parent=#Widget] Widget diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp.REMOVED.git-id b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp.REMOVED.git-id index 104c65729e..e024e99b59 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp.REMOVED.git-id +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp.REMOVED.git-id @@ -1 +1 @@ -11bba6be0cebc89eb4c7195a61d021e51719468f \ No newline at end of file +19adb2eb5a08b20b670b77975f7e30c08bbac2d6 \ No newline at end of file diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.hpp b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.hpp index 1e576402ce..3a1b0bb858 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.hpp +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.hpp @@ -362,12 +362,6 @@ int register_all_cocos2dx_ui(lua_State* tolua_S); - - - - - - From c37584ee5c4b568598f5ff11298a7019399d887b Mon Sep 17 00:00:00 2001 From: koowolf <450928375@qq.com> Date: Tue, 25 Mar 2014 16:14:21 +0800 Subject: [PATCH 073/106] closed #4542: fix crash in win32(delete mutex while still lock) --- cocos/network/WebSocket.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/cocos/network/WebSocket.cpp b/cocos/network/WebSocket.cpp index 4ba4b708a0..4e98591d24 100644 --- a/cocos/network/WebSocket.cpp +++ b/cocos/network/WebSocket.cpp @@ -187,16 +187,19 @@ void WsThreadHelper::update(float dt) WsMessage *msg = nullptr; // Returns quickly if no message - std::lock_guard lk(_UIWsMessageQueueMutex); + _UIWsMessageQueueMutex.lock(); if (0 == _UIWsMessageQueue->size()) { + _UIWsMessageQueueMutex.unlock(); return; } // Gets message msg = *(_UIWsMessageQueue->begin()); _UIWsMessageQueue->pop_front(); + + _UIWsMessageQueueMutex.unlock(); if (_ws) { From d6ad9274c4341fac0f7581cfd10853dca026b3f7 Mon Sep 17 00:00:00 2001 From: zhangbin Date: Tue, 25 Mar 2014 16:19:34 +0800 Subject: [PATCH 074/106] closed #2880, Generate mipmap for the texture has mipmaps when reload textures. --- cocos/2d/CCTexture2D.cpp | 3 +++ cocos/2d/CCTextureCache.cpp | 9 +++++++++ cocos/2d/CCTextureCache.h | 2 ++ tests/cpp-tests/Classes/Texture2dTest/Texture2dTest.cpp | 1 + 4 files changed, 15 insertions(+) diff --git a/cocos/2d/CCTexture2D.cpp b/cocos/2d/CCTexture2D.cpp index a43563d862..564298eca3 100644 --- a/cocos/2d/CCTexture2D.cpp +++ b/cocos/2d/CCTexture2D.cpp @@ -1199,6 +1199,9 @@ void Texture2D::generateMipmap() GL::bindTexture2D( _name ); glGenerateMipmap(GL_TEXTURE_2D); _hasMipmaps = true; +#if CC_ENABLE_CACHE_TEXTURE_DATA + VolatileTextureMgr::setHasMipmaps(this, _hasMipmaps); +#endif } bool Texture2D::hasMipmaps() const diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index 0e7bd4f647..38ef71f31a 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -635,6 +635,12 @@ void VolatileTextureMgr::addStringTexture(Texture2D *tt, const char* text, const vt->_fontDefinition = fontDefinition; } +void VolatileTextureMgr::setHasMipmaps(Texture2D *t, bool hasMipmaps) +{ + VolatileTexture *vt = findVolotileTexture(t); + vt->_hasMipmaps = hasMipmaps; +} + void VolatileTextureMgr::setTexParameters(Texture2D *t, const Texture2D::TexParams &texParams) { VolatileTexture *vt = findVolotileTexture(t); @@ -717,6 +723,9 @@ void VolatileTextureMgr::reloadAllTextures() default: break; } + if (vt->_hasMipmaps) { + vt->_texture->generateMipmap(); + } vt->_texture->setTexParameters(vt->_texParams); } diff --git a/cocos/2d/CCTextureCache.h b/cocos/2d/CCTextureCache.h index 8ebd4821b5..39b1a8e957 100644 --- a/cocos/2d/CCTextureCache.h +++ b/cocos/2d/CCTextureCache.h @@ -251,6 +251,7 @@ protected: std::string _fileName; + bool _hasMipmaps; Texture2D::TexParams _texParams; std::string _text; FontDefinition _fontDefinition; @@ -264,6 +265,7 @@ public: static void addDataTexture(Texture2D *tt, void* data, int dataLen, Texture2D::PixelFormat pixelFormat, const Size& contentSize); static void addImage(Texture2D *tt, Image *image); + static void setHasMipmaps(Texture2D *t, bool hasMipmaps); static void setTexParameters(Texture2D *t, const Texture2D::TexParams &texParams); static void removeTexture(Texture2D *t); static void reloadAllTextures(); diff --git a/tests/cpp-tests/Classes/Texture2dTest/Texture2dTest.cpp b/tests/cpp-tests/Classes/Texture2dTest/Texture2dTest.cpp index 4f80334657..05e2fc128a 100644 --- a/tests/cpp-tests/Classes/Texture2dTest/Texture2dTest.cpp +++ b/tests/cpp-tests/Classes/Texture2dTest/Texture2dTest.cpp @@ -38,6 +38,7 @@ static std::function createFunctions[] = { CL(TexturePVRv3Premult), + CL(TextureMipMap), CL(TextureMemoryAlloc), CL(TextureAlias), CL(TexturePVRMipMap), From e65315d01e2617653afb177dfe61ba3a4c7ab004 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Tue, 25 Mar 2014 08:22:13 +0000 Subject: [PATCH 075/106] [AUTO][ci skip]: updating cocos2dx_files.json --- templates/cocos2dx_files.json.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates/cocos2dx_files.json.REMOVED.git-id b/templates/cocos2dx_files.json.REMOVED.git-id index 1c31d78c7e..089a8e7561 100644 --- a/templates/cocos2dx_files.json.REMOVED.git-id +++ b/templates/cocos2dx_files.json.REMOVED.git-id @@ -1 +1 @@ -9be9de64b36c123c9aba99c3149937136749b712 \ No newline at end of file +d53bc7d6e68a49984c5971344f59bba8414d142b \ No newline at end of file From bb190fe78ac2fdb7343f0cadfe7dcfcda9d92724 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 25 Mar 2014 16:24:08 +0800 Subject: [PATCH 076/106] [ci] Updates travis scripts. --- tools/travis-scripts/generate-bindings.sh | 7 +++++-- tools/travis-scripts/generate-cocosfiles.sh | 7 +++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/tools/travis-scripts/generate-bindings.sh b/tools/travis-scripts/generate-bindings.sh index 19978804e3..d586e61d09 100755 --- a/tools/travis-scripts/generate-bindings.sh +++ b/tools/travis-scripts/generate-bindings.sh @@ -23,6 +23,7 @@ ELAPSEDSECS=`date +%s` COCOS_BRANCH="update_lua_bindings_$ELAPSEDSECS" COCOS_ROBOT_REMOTE="https://${GH_USER}:${GH_PASSWORD}@github.com/${GH_USER}/cocos2d-x.git" PULL_REQUEST_REPO="https://api.github.com/repos/cocos2d/cocos2d-x/pulls" +FETCH_REMOTE_BRANCH="develop" # Exit on error set -e @@ -88,12 +89,14 @@ pushd "$PROJECT_ROOT" git status echo -echo Comparing with HEAD ... +echo Comparing with origin HEAD ... echo +git fetch origin ${FETCH_REMOTE_BRANCH} + # Don't exit on non-zero return value set +e -git diff --stat --exit-code +git diff FETCH_HEAD --stat --exit-code DIFF_RETVAL=$? if [ $DIFF_RETVAL -eq 0 ] diff --git a/tools/travis-scripts/generate-cocosfiles.sh b/tools/travis-scripts/generate-cocosfiles.sh index 1014bc303e..ec43dc8300 100755 --- a/tools/travis-scripts/generate-cocosfiles.sh +++ b/tools/travis-scripts/generate-cocosfiles.sh @@ -6,6 +6,7 @@ PROJECT_ROOT="$DIR"/../.. COMMITTAG="[AUTO][ci skip]: updating cocos2dx_files.json" PUSH_REPO="https://api.github.com/repos/cocos2d/cocos2d-x/pulls" OUTPUT_FILE_PATH="${PROJECT_ROOT}/templates/cocos2dx_files.json" +FETCH_REMOTE_BRANCH="develop" # Exit on error set -e @@ -51,12 +52,14 @@ pushd "$PROJECT_ROOT" git status echo -echo Comparing with HEAD ... +echo Comparing with origin HEAD ... echo +git fetch origin ${FETCH_REMOTE_BRANCH} + # Don't exit on non-zero return value set +e -git diff --stat --exit-code +git diff FETCH_HEAD --stat --exit-code DIFF_RETVAL=$? if [ $DIFF_RETVAL -eq 0 ] From 81cc05729c28eb492c58f1b28a4624efbc0b704c Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Tue, 25 Mar 2014 08:26:13 +0000 Subject: [PATCH 077/106] [AUTO]: updating luabinding automatically --- .../lua-bindings/auto/api/RichText.lua | 5 + .../lua-bindings/auto/api/ScrollView.lua | 86 +++------- .../lua-bindings/auto/api/Widget.lua | 159 +++--------------- .../lua_cocos2dx_ui_auto.cpp.REMOVED.git-id | 2 +- .../auto/lua_cocos2dx_ui_auto.hpp | 6 - 5 files changed, 57 insertions(+), 201 deletions(-) diff --git a/cocos/scripting/lua-bindings/auto/api/RichText.lua b/cocos/scripting/lua-bindings/auto/api/RichText.lua index 3c181b3a2d..b14dcddf9e 100644 --- a/cocos/scripting/lua-bindings/auto/api/RichText.lua +++ b/cocos/scripting/lua-bindings/auto/api/RichText.lua @@ -52,6 +52,11 @@ -- @param self -- @return RichText#RichText ret (return value: ccui.RichText) +-------------------------------- +-- @function [parent=#RichText] getDescription +-- @param self +-- @return string#string ret (return value: string) + -------------------------------- -- @function [parent=#RichText] RichText -- @param self diff --git a/cocos/scripting/lua-bindings/auto/api/ScrollView.lua b/cocos/scripting/lua-bindings/auto/api/ScrollView.lua index 66b3f739f6..b5532e0192 100644 --- a/cocos/scripting/lua-bindings/auto/api/ScrollView.lua +++ b/cocos/scripting/lua-bindings/auto/api/ScrollView.lua @@ -187,58 +187,22 @@ -- @param #int int -- @param #int int +-------------------------------- +-- @function [parent=#ScrollView] getChildByName +-- @param self +-- @param #char char +-- @return Widget#Widget ret (return value: ccui.Widget) + -------------------------------- -- @function [parent=#ScrollView] getDescription -- @param self -- @return string#string ret (return value: string) -------------------------------- --- @function [parent=#ScrollView] removeAllChildren +-- @function [parent=#ScrollView] update -- @param self +-- @param #float float --------------------------------- --- overload function: getChildren() --- --- overload function: getChildren() --- --- @function [parent=#ScrollView] getChildren --- @param self --- @return array_table#array_table ret (retunr value: array_table) - --------------------------------- --- @function [parent=#ScrollView] getNodes --- @param self --- @return array_table#array_table ret (return value: array_table) - --------------------------------- --- @function [parent=#ScrollView] getChildByTag --- @param self --- @param #int int --- @return Node#Node ret (return value: cc.Node) - --------------------------------- --- @function [parent=#ScrollView] removeNode --- @param self --- @param #cc.Node node - --------------------------------- --- @function [parent=#ScrollView] removeNodeByTag --- @param self --- @param #int int - --------------------------------- --- overload function: addNode(cc.Node, int) --- --- overload function: addNode(cc.Node) --- --- overload function: addNode(cc.Node, int, int) --- --- @function [parent=#ScrollView] addNode --- @param self --- @param #cc.Node node --- @param #int int --- @param #int int - -------------------------------- -- @function [parent=#ScrollView] getLayoutType -- @param self @@ -250,24 +214,7 @@ -- @param #bool bool -------------------------------- --- @function [parent=#ScrollView] update --- @param self --- @param #float float - --------------------------------- --- @function [parent=#ScrollView] getNodeByTag --- @param self --- @param #int int --- @return Node#Node ret (return value: cc.Node) - --------------------------------- --- @function [parent=#ScrollView] getChildByName --- @param self --- @param #char char --- @return Widget#Widget ret (return value: ccui.Widget) - --------------------------------- --- @function [parent=#ScrollView] removeAllNodes +-- @function [parent=#ScrollView] removeAllChildren -- @param self -------------------------------- @@ -276,6 +223,21 @@ -- @param #cc.Node node -- @param #bool bool +-------------------------------- +-- overload function: getChildren() +-- +-- overload function: getChildren() +-- +-- @function [parent=#ScrollView] getChildren +-- @param self +-- @return array_table#array_table ret (retunr value: array_table) + +-------------------------------- +-- @function [parent=#ScrollView] getChildByTag +-- @param self +-- @param #int int +-- @return Node#Node ret (return value: cc.Node) + -------------------------------- -- @function [parent=#ScrollView] getChildrenCount -- @param self diff --git a/cocos/scripting/lua-bindings/auto/api/Widget.lua b/cocos/scripting/lua-bindings/auto/api/Widget.lua index 5bea038c34..1f97832c9f 100644 --- a/cocos/scripting/lua-bindings/auto/api/Widget.lua +++ b/cocos/scripting/lua-bindings/auto/api/Widget.lua @@ -1,18 +1,13 @@ -------------------------------- -- @module Widget --- @extend Node +-- @extend ProtectedNode -------------------------------- -- @function [parent=#Widget] setSizePercent -- @param self -- @param #point_table point --------------------------------- --- @function [parent=#Widget] isFlippedX --- @param self --- @return bool#bool ret (return value: bool) - -------------------------------- -- @function [parent=#Widget] getCustomSize -- @param self @@ -29,10 +24,9 @@ -- @param #bool bool -------------------------------- --- @function [parent=#Widget] getNodeByTag +-- @function [parent=#Widget] getLeftInParent -- @param self --- @param #int int --- @return Node#Node ret (return value: cc.Node) +-- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#Widget] getTouchEndPos @@ -44,11 +38,6 @@ -- @param self -- @param #point_table point --------------------------------- --- @function [parent=#Widget] getNodes --- @param self --- @return array_table#array_table ret (return value: array_table) - -------------------------------- -- @function [parent=#Widget] getLayoutSize -- @param self @@ -69,15 +58,6 @@ -- @param self -- @return bool#bool ret (return value: bool) --------------------------------- --- overload function: updateSizeAndPosition(size_table) --- --- overload function: updateSizeAndPosition() --- --- @function [parent=#Widget] updateSizeAndPosition --- @param self --- @param #size_table size - -------------------------------- -- @function [parent=#Widget] getBottomInParent -- @param self @@ -100,9 +80,9 @@ -- @return PositionType#PositionType ret (return value: ccui.PositionType) -------------------------------- --- @function [parent=#Widget] setName +-- @function [parent=#Widget] getWidgetType -- @param self --- @param #char char +-- @return WidgetType#WidgetType ret (return value: ccui.WidgetType) -------------------------------- -- @function [parent=#Widget] getChildByName @@ -116,9 +96,9 @@ -- @return bool#bool ret (return value: bool) -------------------------------- --- @function [parent=#Widget] removeNodeByTag +-- @function [parent=#Widget] isFocused -- @param self --- @param #int int +-- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#Widget] isTouchEnabled @@ -175,18 +155,10 @@ -- @param #ccui.BrightStyle brightstyle -------------------------------- --- overload function: addNode(cc.Node, int) --- --- overload function: addNode(cc.Node) --- --- overload function: addNode(cc.Node, int, int) --- --- @function [parent=#Widget] addNode +-- @function [parent=#Widget] setName -- @param self --- @param #cc.Node node --- @param #int int --- @param #int int - +-- @param #char char + -------------------------------- -- @function [parent=#Widget] setLayoutParameter -- @param self @@ -202,21 +174,11 @@ -- @param self -- @return point_table#point_table ret (return value: point_table) --------------------------------- --- @function [parent=#Widget] getLeftInParent --- @param self --- @return float#float ret (return value: float) - -------------------------------- -- @function [parent=#Widget] setActionTag -- @param self -- @param #int int --------------------------------- --- @function [parent=#Widget] ignoreContentAdaptWithSize --- @param self --- @param #bool bool - -------------------------------- -- @function [parent=#Widget] isBright -- @param self @@ -234,10 +196,14 @@ -- @return float#float ret (return value: float) -------------------------------- --- @function [parent=#Widget] getWidgetType +-- overload function: updateSizeAndPosition(size_table) +-- +-- overload function: updateSizeAndPosition() +-- +-- @function [parent=#Widget] updateSizeAndPosition -- @param self --- @return WidgetType#WidgetType ret (return value: ccui.WidgetType) - +-- @param #size_table size + -------------------------------- -- @function [parent=#Widget] getSize -- @param self @@ -254,13 +220,9 @@ -- @return SizeType#SizeType ret (return value: ccui.SizeType) -------------------------------- --- @function [parent=#Widget] removeNode --- @param self --- @param #cc.Node node - --------------------------------- --- @function [parent=#Widget] removeAllNodes +-- @function [parent=#Widget] ignoreContentAdaptWithSize -- @param self +-- @param #bool bool -------------------------------- -- @function [parent=#Widget] getPositionPercent @@ -274,7 +236,7 @@ -- @return bool#bool ret (return value: bool) -------------------------------- --- @function [parent=#Widget] isFocused +-- @function [parent=#Widget] isFlippedX -- @param self -- @return bool#bool ret (return value: bool) @@ -310,72 +272,11 @@ -- @param self -- @return Widget#Widget ret (return value: ccui.Widget) --------------------------------- --- overload function: addChild(cc.Node, int) --- --- overload function: addChild(cc.Node) --- --- overload function: addChild(cc.Node, int, int) --- --- @function [parent=#Widget] addChild --- @param self --- @param #cc.Node node --- @param #int int --- @param #int int - -------------------------------- -- @function [parent=#Widget] setColor -- @param self -- @param #color3B_table color3b --------------------------------- --- @function [parent=#Widget] removeFromParent --- @param self - --------------------------------- --- @function [parent=#Widget] removeAllChildrenWithCleanup --- @param self --- @param #bool bool - --------------------------------- --- @function [parent=#Widget] removeAllChildren --- @param self - --------------------------------- --- @function [parent=#Widget] sortAllChildren --- @param self - --------------------------------- --- @function [parent=#Widget] removeChild --- @param self --- @param #cc.Node node --- @param #bool bool - --------------------------------- --- overload function: getChildren() --- --- overload function: getChildren() --- --- @function [parent=#Widget] getChildren --- @param self --- @return array_table#array_table ret (retunr value: array_table) - --------------------------------- --- @function [parent=#Widget] getDescription --- @param self --- @return string#string ret (return value: string) - --------------------------------- --- @function [parent=#Widget] getChildByTag --- @param self --- @param #int int --- @return Node#Node ret (return value: cc.Node) - --------------------------------- --- @function [parent=#Widget] removeFromParentAndCleanup --- @param self --- @param #bool bool - -------------------------------- -- @function [parent=#Widget] getColor -- @param self @@ -386,26 +287,20 @@ -- @param self -- @param #unsigned char char --------------------------------- --- @function [parent=#Widget] setPosition --- @param self --- @param #point_table point - --------------------------------- --- @function [parent=#Widget] removeChildByTag --- @param self --- @param #int int --- @param #bool bool - -------------------------------- -- @function [parent=#Widget] getOpacity -- @param self -- @return unsigned char#unsigned char ret (return value: unsigned char) -------------------------------- --- @function [parent=#Widget] getChildrenCount +-- @function [parent=#Widget] setPosition -- @param self --- @return long#long ret (return value: long) +-- @param #point_table point + +-------------------------------- +-- @function [parent=#Widget] getDescription +-- @param self +-- @return string#string ret (return value: string) -------------------------------- -- @function [parent=#Widget] Widget diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp.REMOVED.git-id b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp.REMOVED.git-id index 104c65729e..e024e99b59 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp.REMOVED.git-id +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp.REMOVED.git-id @@ -1 +1 @@ -11bba6be0cebc89eb4c7195a61d021e51719468f \ No newline at end of file +19adb2eb5a08b20b670b77975f7e30c08bbac2d6 \ No newline at end of file diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.hpp b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.hpp index 1e576402ce..3a1b0bb858 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.hpp +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.hpp @@ -362,12 +362,6 @@ int register_all_cocos2dx_ui(lua_State* tolua_S); - - - - - - From f672f3153ec3ef93aa8f2ad16ae32ce2a579e6ab Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 25 Mar 2014 16:30:00 +0800 Subject: [PATCH 078/106] Update CHANGELOG [ci skip] --- CHANGELOG.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.REMOVED.git-id b/CHANGELOG.REMOVED.git-id index af31d79c6e..f99513ccea 100644 --- a/CHANGELOG.REMOVED.git-id +++ b/CHANGELOG.REMOVED.git-id @@ -1 +1 @@ -819b72559f8be48c41958b0afb4c6513207b453a \ No newline at end of file +f25c155ba7b72acabb5314391df45df00f582ca3 \ No newline at end of file From 4b454fe7bbb5a067dda9d4305912d4d8a078d183 Mon Sep 17 00:00:00 2001 From: LinWenhai Date: Tue, 25 Mar 2014 16:37:34 +0800 Subject: [PATCH 079/106] Update getter of ClipMarginEnabled. --- cocos/2d/CCLabel.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/CCLabel.h b/cocos/2d/CCLabel.h index c453112cb4..c2e2be23b8 100644 --- a/cocos/2d/CCLabel.h +++ b/cocos/2d/CCLabel.h @@ -220,7 +220,7 @@ public: /** clip upper and lower margin for reduce height of label. */ void setClipMarginEnabled(bool clipEnabled) { _clipEnabled = clipEnabled; } - bool getClipMarginEnabled() const { return _clipEnabled; } + bool isClipMarginEnabled() const { return _clipEnabled; } // font related stuff int getCommonLineHeight() const; From fe89291be64450e24ec1956956bac3a854c574c1 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 25 Mar 2014 16:47:59 +0800 Subject: [PATCH 080/106] Update CHANGELOG [ci skip] --- CHANGELOG.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.REMOVED.git-id b/CHANGELOG.REMOVED.git-id index f99513ccea..04713d44d3 100644 --- a/CHANGELOG.REMOVED.git-id +++ b/CHANGELOG.REMOVED.git-id @@ -1 +1 @@ -f25c155ba7b72acabb5314391df45df00f582ca3 \ No newline at end of file +185679986c46f4ecc4cb98f4fc014a8e9a42a88f \ No newline at end of file From dda53f26d487e4621594cac51a5f58fe31137800 Mon Sep 17 00:00:00 2001 From: minggo Date: Tue, 25 Mar 2014 16:50:36 +0800 Subject: [PATCH 081/106] [ci skip] --- CHANGELOG.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.REMOVED.git-id b/CHANGELOG.REMOVED.git-id index 04713d44d3..73a33eb03f 100644 --- a/CHANGELOG.REMOVED.git-id +++ b/CHANGELOG.REMOVED.git-id @@ -1 +1 @@ -185679986c46f4ecc4cb98f4fc014a8e9a42a88f \ No newline at end of file +5b8d2ae9f19e1ca958245cf11e144d18d6ee3f89 \ No newline at end of file From b8eee8e1a4a2b26d312070e408a1096f7e511b86 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 25 Mar 2014 17:07:15 +0800 Subject: [PATCH 082/106] [ci] Updates travis scripts. only commit relevant folder. --- tools/travis-scripts/generate-bindings.sh | 3 ++- tools/travis-scripts/generate-cocosfiles.sh | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/tools/travis-scripts/generate-bindings.sh b/tools/travis-scripts/generate-bindings.sh index d586e61d09..0a2b428b57 100755 --- a/tools/travis-scripts/generate-bindings.sh +++ b/tools/travis-scripts/generate-bindings.sh @@ -24,6 +24,7 @@ COCOS_BRANCH="update_lua_bindings_$ELAPSEDSECS" COCOS_ROBOT_REMOTE="https://${GH_USER}:${GH_PASSWORD}@github.com/${GH_USER}/cocos2d-x.git" PULL_REQUEST_REPO="https://api.github.com/repos/cocos2d/cocos2d-x/pulls" FETCH_REMOTE_BRANCH="develop" +COMMIT_PATH="cocos/scripting/lua-bindings/auto" # Exit on error set -e @@ -96,7 +97,7 @@ git fetch origin ${FETCH_REMOTE_BRANCH} # Don't exit on non-zero return value set +e -git diff FETCH_HEAD --stat --exit-code +git diff FETCH_HEAD --stat --exit-code ${COMMIT_PATH} DIFF_RETVAL=$? if [ $DIFF_RETVAL -eq 0 ] diff --git a/tools/travis-scripts/generate-cocosfiles.sh b/tools/travis-scripts/generate-cocosfiles.sh index ec43dc8300..82837b2a6d 100755 --- a/tools/travis-scripts/generate-cocosfiles.sh +++ b/tools/travis-scripts/generate-cocosfiles.sh @@ -7,6 +7,7 @@ COMMITTAG="[AUTO][ci skip]: updating cocos2dx_files.json" PUSH_REPO="https://api.github.com/repos/cocos2d/cocos2d-x/pulls" OUTPUT_FILE_PATH="${PROJECT_ROOT}/templates/cocos2dx_files.json" FETCH_REMOTE_BRANCH="develop" +COMMIT_PATH="templates/cocos2dx_files.json" # Exit on error set -e @@ -59,7 +60,7 @@ git fetch origin ${FETCH_REMOTE_BRANCH} # Don't exit on non-zero return value set +e -git diff FETCH_HEAD --stat --exit-code +git diff FETCH_HEAD --stat --exit-code ${COMMIT_PATH} DIFF_RETVAL=$? if [ $DIFF_RETVAL -eq 0 ] From 243b7e5822daf591795236797789e8c23d6e83fb Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Tue, 25 Mar 2014 17:15:54 +0800 Subject: [PATCH 083/106] Modify layout and add Boxes --- .../project.pbxproj.REMOVED.git-id | 2 +- cocos/ui/Android.mk | 6 +- cocos/ui/CMakeLists.txt | 3 + cocos/ui/CocosGUI.h | 3 + cocos/ui/UIHBox.cpp | 85 ++ cocos/ui/UIHBox.h | 66 ++ cocos/ui/UIHelper.cpp | 22 - cocos/ui/UIHelper.h | 13 - cocos/ui/UILayout.cpp | 951 ++++++++++-------- cocos/ui/UILayout.h | 40 + cocos/ui/UILayoutParameter.h | 2 +- cocos/ui/UIRelativeBox.cpp | 85 ++ cocos/ui/UIRelativeBox.h | 66 ++ cocos/ui/UIVBox.cpp | 85 ++ cocos/ui/UIVBox.h | 66 ++ cocos/ui/proj.win32/libGUI.vcxproj | 6 + cocos/ui/proj.win32/libGUI.vcxproj.filters | 18 + 17 files changed, 1043 insertions(+), 476 deletions(-) create mode 100644 cocos/ui/UIHBox.cpp create mode 100644 cocos/ui/UIHBox.h create mode 100644 cocos/ui/UIRelativeBox.cpp create mode 100644 cocos/ui/UIRelativeBox.h create mode 100644 cocos/ui/UIVBox.cpp create mode 100644 cocos/ui/UIVBox.h diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index f0adc63a8a..6cc12b110a 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -ebeb897c2c3303710c06b9de3cb3d499f89fb78c \ No newline at end of file +bdcba92fe68d80bd996d1c61e15ea07397895549 \ No newline at end of file diff --git a/cocos/ui/Android.mk b/cocos/ui/Android.mk index bf3e2ce5a5..bda747bcdf 100644 --- a/cocos/ui/Android.mk +++ b/cocos/ui/Android.mk @@ -25,7 +25,11 @@ UILoadingBar.cpp \ UISlider.cpp \ UITextField.cpp \ UIRichText.cpp \ -CCProtectedNode.cpp +CCProtectedNode.cpp \ +UIHBox.cpp \ +UIVBox.cpp \ +UIRelativeBox.cpp + LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/.. \ diff --git a/cocos/ui/CMakeLists.txt b/cocos/ui/CMakeLists.txt index cc41a5f95b..b56f995b54 100644 --- a/cocos/ui/CMakeLists.txt +++ b/cocos/ui/CMakeLists.txt @@ -19,6 +19,9 @@ set(GUI_SRC UITextField.cpp UIRichText.cpp CCProtectedNode.cpp + UIHBox.cpp + UIVBox.cpp + UIRelativeBox.cpp ) add_library(ui STATIC diff --git a/cocos/ui/CocosGUI.h b/cocos/ui/CocosGUI.h index a4e6ac7ce8..296f0508fb 100644 --- a/cocos/ui/CocosGUI.h +++ b/cocos/ui/CocosGUI.h @@ -42,6 +42,9 @@ THE SOFTWARE. #include "ui/UIPageView.h" #include "ui/UIHelper.h" #include "ui/UIRichText.h" +#include "ui/UIHBox.h" +#include "ui/UIVBox.h" +#include "ui/UIRelativeBox.h" NS_CC_BEGIN namespace ui { diff --git a/cocos/ui/UIHBox.cpp b/cocos/ui/UIHBox.cpp new file mode 100644 index 0000000000..08fc052a14 --- /dev/null +++ b/cocos/ui/UIHBox.cpp @@ -0,0 +1,85 @@ +/**************************************************************************** + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "ui/UIHBox.h" + +NS_CC_BEGIN + +namespace ui{ + +HBox::HBox() +{ +} + +HBox::~HBox() +{ +} + +HBox* HBox::create() +{ + HBox* widget = new HBox(); + if (widget && widget->init()) + { + widget->autorelease(); + return widget; + } + CC_SAFE_DELETE(widget); + return nullptr; +} + +HBox* HBox::create(const cocos2d::Size &size) +{ + HBox* widget = new HBox(); + if (widget && widget->initWithSize(size)) + { + widget->autorelease(); + return widget; + } + CC_SAFE_DELETE(widget); + return nullptr; +} + +bool HBox::init() +{ + if (Layout::init()) + { + setLayoutType(LAYOUT_LINEAR_HORIZONTAL); + return true; + } + return false; +} + +bool HBox::initWithSize(const Size& size) +{ + if (init()) + { + setSize(size); + return true; + } + return false; +} + +} + +NS_CC_END \ No newline at end of file diff --git a/cocos/ui/UIHBox.h b/cocos/ui/UIHBox.h new file mode 100644 index 0000000000..1b6cf95ae9 --- /dev/null +++ b/cocos/ui/UIHBox.h @@ -0,0 +1,66 @@ +/**************************************************************************** + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __UIHBox_H__ +#define __UIHBox_H__ + +#include "ui/UILayout.h" + +NS_CC_BEGIN + +namespace ui { + +class HBox : public Layout{ + + +public: + + /** + * Default constructor + */ + HBox(); + + /** + * Default destructor + */ + virtual ~HBox(); + + /** + * Allocates and initializes a HBox. + */ + static HBox* create(); + + static HBox* create(const Size& size); + +CC_CONSTRUCTOR_ACCESS: + //initializes state of widget. + virtual bool init() override; + virtual bool initWithSize(const Size& size); +}; + +} + +NS_CC_END + +#endif /* defined(__UIHBox__) */ diff --git a/cocos/ui/UIHelper.cpp b/cocos/ui/UIHelper.cpp index ebbf2c1265..140f9003b3 100644 --- a/cocos/ui/UIHelper.cpp +++ b/cocos/ui/UIHelper.cpp @@ -81,28 +81,6 @@ Widget* Helper::seekWidgetByName(Widget* root, const char *name) return nullptr; } -Widget* Helper::seekWidgetByRelativeName(Widget *root, const char *name) -{ - if (!root) - { - return nullptr; - } - const auto& arrayRootChildren = root->getChildren(); - for (auto& subWidget : arrayRootChildren) - { - Widget* child = dynamic_cast(subWidget); - if (child) - { - RelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); - if (layoutParameter && strcmp(layoutParameter->getRelativeName(), name) == 0) - { - return child; - } - } - } - return nullptr; -} - /*temp action*/ Widget* Helper::seekActionWidgetByActionTag(Widget* root, int tag) { diff --git a/cocos/ui/UIHelper.h b/cocos/ui/UIHelper.h index 035df13cdb..e12fc0dfc7 100644 --- a/cocos/ui/UIHelper.h +++ b/cocos/ui/UIHelper.h @@ -58,19 +58,6 @@ public: */ static Widget* seekWidgetByName(Widget* root, const char* name); - /** - * Finds a widget whose name equals to param name from root widget. - * - * RelativeLayout will call this method to find the widget witch is needed. - * - * @param root widget which will be seeked. - * - * @name name value. - * - * @return finded result. - */ - static Widget* seekWidgetByRelativeName(Widget* root, const char* name); - /*temp action*/ static Widget* seekActionWidgetByActionTag(Widget* root, int tag); }; diff --git a/cocos/ui/UILayout.cpp b/cocos/ui/UILayout.cpp index e2a8e53dad..96402dd4d9 100644 --- a/cocos/ui/UILayout.cpp +++ b/cocos/ui/UILayout.cpp @@ -38,6 +38,491 @@ NS_CC_BEGIN namespace ui { +LayoutExecutant* LayoutExecutant::create() +{ + LayoutExecutant* exe = new LayoutExecutant(); + if (exe) + { + exe->autorelease(); + return exe; + } + CC_SAFE_DELETE(exe); + return nullptr; +} + +LinearVerticalLayoutExecutant* LinearVerticalLayoutExecutant::create() +{ + LinearVerticalLayoutExecutant* exe = new LinearVerticalLayoutExecutant(); + if (exe) + { + exe->autorelease(); + return exe; + } + CC_SAFE_DELETE(exe); + return nullptr; +} + +LinearHorizontalLayoutExecutant* LinearHorizontalLayoutExecutant::create() +{ + LinearHorizontalLayoutExecutant* exe = new LinearHorizontalLayoutExecutant(); + if (exe) + { + exe->autorelease(); + return exe; + } + CC_SAFE_DELETE(exe); + return nullptr; +} + +RelativeLayoutExecutant* RelativeLayoutExecutant::create() +{ + RelativeLayoutExecutant* exe = new RelativeLayoutExecutant(); + if (exe) + { + exe->autorelease(); + return exe; + } + CC_SAFE_DELETE(exe); + return nullptr; +} + +void LinearVerticalLayoutExecutant::doLayout(const cocos2d::Size &layoutSize, Vector container) +{ + float topBoundary = layoutSize.height; + + for (auto& subWidget : container) + { + Widget* child = dynamic_cast(subWidget); + if (child) + { + LinearLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_LINEAR)); + + if (layoutParameter) + { + LinearGravity childGravity = layoutParameter->getGravity(); + Point ap = child->getAnchorPoint(); + Size cs = child->getSize(); + float finalPosX = ap.x * cs.width; + float finalPosY = topBoundary - ((1.0f-ap.y) * cs.height); + switch (childGravity) + { + case LINEAR_GRAVITY_NONE: + case LINEAR_GRAVITY_LEFT: + break; + case LINEAR_GRAVITY_RIGHT: + finalPosX = layoutSize.width - ((1.0f - ap.x) * cs.width); + break; + case LINEAR_GRAVITY_CENTER_HORIZONTAL: + finalPosX = layoutSize.width / 2.0f - cs.width * (0.5f-ap.x); + break; + default: + break; + } + Margin mg = layoutParameter->getMargin(); + finalPosX += mg.left; + finalPosY -= mg.top; + child->setPosition(Point(finalPosX, finalPosY)); + topBoundary = child->getBottomInParent() - mg.bottom; + } + } + } +} + +void LinearHorizontalLayoutExecutant::doLayout(const cocos2d::Size &layoutSize, Vector container) +{ + float leftBoundary = 0.0f; + for (auto& subWidget : container) + { + Widget* child = dynamic_cast(subWidget); + if (child) + { + LinearLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_LINEAR)); + if (layoutParameter) + { + LinearGravity childGravity = layoutParameter->getGravity(); + Point ap = child->getAnchorPoint(); + Size cs = child->getSize(); + float finalPosX = leftBoundary + (ap.x * cs.width); + float finalPosY = layoutSize.height - (1.0f - ap.y) * cs.height; + switch (childGravity) + { + case LINEAR_GRAVITY_NONE: + case LINEAR_GRAVITY_TOP: + break; + case LINEAR_GRAVITY_BOTTOM: + finalPosY = ap.y * cs.height; + break; + case LINEAR_GRAVITY_CENTER_VERTICAL: + finalPosY = layoutSize.height / 2.0f - cs.height * (0.5f - ap.y); + break; + default: + break; + } + Margin mg = layoutParameter->getMargin(); + finalPosX += mg.left; + finalPosY -= mg.top; + child->setPosition(Point(finalPosX, finalPosY)); + leftBoundary = child->getRightInParent() + mg.right; + } + } + } +} + +void RelativeLayoutExecutant::doLayout(const cocos2d::Size &layoutSize, Vector container) +{ + ssize_t unlayoutChildCount = 0; + Vector widgetChildren; + for (auto& subWidget : container) + { + Widget* child = dynamic_cast(subWidget); + if (child) + { + RelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); + layoutParameter->_put = false; + unlayoutChildCount++; + widgetChildren.pushBack(child); + } + } + while (unlayoutChildCount > 0) + { + for (auto& subWidget : widgetChildren) + { + Widget* child = static_cast(subWidget); + RelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); + + if (layoutParameter) + { + if (layoutParameter->_put) + { + continue; + } + Point ap = child->getAnchorPoint(); + Size cs = child->getSize(); + RelativeAlign align = layoutParameter->getAlign(); + const char* relativeName = layoutParameter->getRelativeToWidgetName(); + Widget* relativeWidget = nullptr; + RelativeLayoutParameter* relativeWidgetLP = nullptr; + float finalPosX = 0.0f; + float finalPosY = 0.0f; + if (relativeName && strcmp(relativeName, "")) + { + for (auto& sWidget : widgetChildren) + { + if (sWidget) + { + RelativeLayoutParameter* rlayoutParameter = dynamic_cast(sWidget->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); + if (rlayoutParameter && strcmp(rlayoutParameter->getRelativeName(), relativeName) == 0) + { + relativeWidget = sWidget; + relativeWidgetLP = rlayoutParameter; + break; + } + } + } + } + switch (align) + { + case RELATIVE_ALIGN_NONE: + case RELATIVE_ALIGN_PARENT_TOP_LEFT: + finalPosX = ap.x * cs.width; + finalPosY = layoutSize.height - ((1.0f - ap.y) * cs.height); + break; + case RELATIVE_ALIGN_PARENT_TOP_CENTER_HORIZONTAL: + finalPosX = layoutSize.width * 0.5f - cs.width * (0.5f - ap.x); + finalPosY = layoutSize.height - ((1.0f - ap.y) * cs.height); + break; + case RELATIVE_ALIGN_PARENT_TOP_RIGHT: + finalPosX = layoutSize.width - ((1.0f - ap.x) * cs.width); + finalPosY = layoutSize.height - ((1.0f - ap.y) * cs.height); + break; + case RELATIVE_ALIGN_PARENT_LEFT_CENTER_VERTICAL: + finalPosX = ap.x * cs.width; + finalPosY = layoutSize.height * 0.5f - cs.height * (0.5f - ap.y); + break; + case RELATIVE_CENTER_IN_PARENT: + finalPosX = layoutSize.width * 0.5f - cs.width * (0.5f - ap.x); + finalPosY = layoutSize.height * 0.5f - cs.height * (0.5f - ap.y); + break; + case RELATIVE_ALIGN_PARENT_RIGHT_CENTER_VERTICAL: + finalPosX = layoutSize.width - ((1.0f - ap.x) * cs.width); + finalPosY = layoutSize.height * 0.5f - cs.height * (0.5f - ap.y); + break; + case RELATIVE_ALIGN_PARENT_LEFT_BOTTOM: + finalPosX = ap.x * cs.width; + finalPosY = ap.y * cs.height; + break; + case RELATIVE_ALIGN_PARENT_BOTTOM_CENTER_HORIZONTAL: + finalPosX = layoutSize.width * 0.5f - cs.width * (0.5f - ap.x); + finalPosY = ap.y * cs.height; + break; + case RELATIVE_ALIGN_PARENT_RIGHT_BOTTOM: + finalPosX = layoutSize.width - ((1.0f - ap.x) * cs.width); + finalPosY = ap.y * cs.height; + break; + + case RELATIVE_LOCATION_ABOVE_LEFTALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationBottom = relativeWidget->getTopInParent(); + float locationLeft = relativeWidget->getLeftInParent(); + finalPosY = locationBottom + ap.y * cs.height; + finalPosX = locationLeft + ap.x * cs.width; + } + break; + case RELATIVE_LOCATION_ABOVE_CENTER: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + Size rbs = relativeWidget->getSize(); + float locationBottom = relativeWidget->getTopInParent(); + + finalPosY = locationBottom + ap.y * cs.height; + finalPosX = relativeWidget->getLeftInParent() + rbs.width * 0.5f + ap.x * cs.width - cs.width * 0.5f; + } + break; + case RELATIVE_LOCATION_ABOVE_RIGHTALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationBottom = relativeWidget->getTopInParent(); + float locationRight = relativeWidget->getRightInParent(); + finalPosY = locationBottom + ap.y * cs.height; + finalPosX = locationRight - (1.0f - ap.x) * cs.width; + } + break; + case RELATIVE_LOCATION_LEFT_OF_TOPALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationTop = relativeWidget->getTopInParent(); + float locationRight = relativeWidget->getLeftInParent(); + finalPosY = locationTop - (1.0f - ap.y) * cs.height; + finalPosX = locationRight - (1.0f - ap.x) * cs.width; + } + break; + case RELATIVE_LOCATION_LEFT_OF_CENTER: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + Size rbs = relativeWidget->getSize(); + float locationRight = relativeWidget->getLeftInParent(); + finalPosX = locationRight - (1.0f - ap.x) * cs.width; + + finalPosY = relativeWidget->getBottomInParent() + rbs.height * 0.5f + ap.y * cs.height - cs.height * 0.5f; + } + break; + case RELATIVE_LOCATION_LEFT_OF_BOTTOMALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationBottom = relativeWidget->getBottomInParent(); + float locationRight = relativeWidget->getLeftInParent(); + finalPosY = locationBottom + ap.y * cs.height; + finalPosX = locationRight - (1.0f - ap.x) * cs.width; + } + break; + case RELATIVE_LOCATION_RIGHT_OF_TOPALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationTop = relativeWidget->getTopInParent(); + float locationLeft = relativeWidget->getRightInParent(); + finalPosY = locationTop - (1.0f - ap.y) * cs.height; + finalPosX = locationLeft + ap.x * cs.width; + } + break; + case RELATIVE_LOCATION_RIGHT_OF_CENTER: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + Size rbs = relativeWidget->getSize(); + float locationLeft = relativeWidget->getRightInParent(); + finalPosX = locationLeft + ap.x * cs.width; + + finalPosY = relativeWidget->getBottomInParent() + rbs.height * 0.5f + ap.y * cs.height - cs.height * 0.5f; + } + break; + case RELATIVE_LOCATION_RIGHT_OF_BOTTOMALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationBottom = relativeWidget->getBottomInParent(); + float locationLeft = relativeWidget->getRightInParent(); + finalPosY = locationBottom + ap.y * cs.height; + finalPosX = locationLeft + ap.x * cs.width; + } + break; + case RELATIVE_LOCATION_BELOW_LEFTALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationTop = relativeWidget->getBottomInParent(); + float locationLeft = relativeWidget->getLeftInParent(); + finalPosY = locationTop - (1.0f - ap.y) * cs.height; + finalPosX = locationLeft + ap.x * cs.width; + } + break; + case RELATIVE_LOCATION_BELOW_CENTER: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + Size rbs = relativeWidget->getSize(); + float locationTop = relativeWidget->getBottomInParent(); + + finalPosY = locationTop - (1.0f - ap.y) * cs.height; + finalPosX = relativeWidget->getLeftInParent() + rbs.width * 0.5f + ap.x * cs.width - cs.width * 0.5f; + } + break; + case RELATIVE_LOCATION_BELOW_RIGHTALIGN: + if (relativeWidget) + { + if (relativeWidgetLP && !relativeWidgetLP->_put) + { + continue; + } + float locationTop = relativeWidget->getBottomInParent(); + float locationRight = relativeWidget->getRightInParent(); + finalPosY = locationTop - (1.0f - ap.y) * cs.height; + finalPosX = locationRight - (1.0f - ap.x) * cs.width; + } + break; + default: + break; + } + Margin relativeWidgetMargin; + Margin mg = layoutParameter->getMargin(); + if (relativeWidgetLP) + { + relativeWidgetMargin = relativeWidgetLP->getMargin(); + } + //handle margin + switch (align) + { + case RELATIVE_ALIGN_NONE: + case RELATIVE_ALIGN_PARENT_TOP_LEFT: + finalPosX += mg.left; + finalPosY -= mg.top; + break; + case RELATIVE_ALIGN_PARENT_TOP_CENTER_HORIZONTAL: + finalPosY -= mg.top; + break; + case RELATIVE_ALIGN_PARENT_TOP_RIGHT: + finalPosX -= mg.right; + finalPosY -= mg.top; + break; + case RELATIVE_ALIGN_PARENT_LEFT_CENTER_VERTICAL: + finalPosX += mg.left; + break; + case RELATIVE_CENTER_IN_PARENT: + break; + case RELATIVE_ALIGN_PARENT_RIGHT_CENTER_VERTICAL: + finalPosX -= mg.right; + break; + case RELATIVE_ALIGN_PARENT_LEFT_BOTTOM: + finalPosX += mg.left; + finalPosY += mg.bottom; + break; + case RELATIVE_ALIGN_PARENT_BOTTOM_CENTER_HORIZONTAL: + finalPosY += mg.bottom; + break; + case RELATIVE_ALIGN_PARENT_RIGHT_BOTTOM: + finalPosX -= mg.right; + finalPosY += mg.bottom; + break; + + case RELATIVE_LOCATION_ABOVE_LEFTALIGN: + finalPosY += mg.bottom; + finalPosX += mg.left; + break; + case RELATIVE_LOCATION_ABOVE_RIGHTALIGN: + finalPosY += mg.bottom; + finalPosX -= mg.right; + break; + case RELATIVE_LOCATION_ABOVE_CENTER: + finalPosY += mg.bottom; + break; + + case RELATIVE_LOCATION_LEFT_OF_TOPALIGN: + finalPosX -= mg.right; + finalPosY -= mg.top; + break; + case RELATIVE_LOCATION_LEFT_OF_BOTTOMALIGN: + finalPosX -= mg.right; + finalPosY += mg.bottom; + break; + case RELATIVE_LOCATION_LEFT_OF_CENTER: + finalPosX -= mg.right; + break; + + case RELATIVE_LOCATION_RIGHT_OF_TOPALIGN: + finalPosX += mg.left; + finalPosY -= mg.top; + break; + case RELATIVE_LOCATION_RIGHT_OF_BOTTOMALIGN: + finalPosX += mg.left; + finalPosY += mg.bottom; + break; + case RELATIVE_LOCATION_RIGHT_OF_CENTER: + finalPosX += mg.left; + break; + + case RELATIVE_LOCATION_BELOW_LEFTALIGN: + finalPosY -= mg.top; + finalPosX += mg.left; + break; + case RELATIVE_LOCATION_BELOW_RIGHTALIGN: + finalPosY -= mg.top; + finalPosX -= mg.right; + break; + case RELATIVE_LOCATION_BELOW_CENTER: + finalPosY -= mg.top; + break; + default: + break; + } + child->setPosition(Point(finalPosX, finalPosY)); + layoutParameter->_put = true; + unlayoutChildCount--; + } + } + } + widgetChildren.clear(); +} + static const int BACKGROUNDIMAGE_Z = (-1); static const int BCAKGROUNDCOLORRENDERER_Z = (-2); @@ -83,7 +568,8 @@ _currentAlphaTestEnabled(GL_FALSE), _currentAlphaTestFunc(GL_ALWAYS), _currentAlphaTestRef(1), _backGroundImageColor(Color3B::WHITE), -_backGroundImageOpacity(255) +_backGroundImageOpacity(255), +_curLayoutExecutant(nullptr) { _widgetType = WidgetTypeContainer; } @@ -91,6 +577,7 @@ _backGroundImageOpacity(255) Layout::~Layout() { CC_SAFE_RELEASE(_clippingStencil); + CC_SAFE_RELEASE(_curLayoutExecutant); } void Layout::onEnter() @@ -918,6 +1405,9 @@ const Size& Layout::getBackGroundImageTextureSize() const void Layout::setLayoutType(LayoutType type) { _layoutType = type; + CC_SAFE_RELEASE_NULL(_curLayoutExecutant); + _curLayoutExecutant = createCurrentLayoutExecutant(); + CC_SAFE_RETAIN(_curLayoutExecutant); for (auto& child : _children) { Widget* widgetChild = dynamic_cast(child); @@ -928,6 +1418,26 @@ void Layout::setLayoutType(LayoutType type) } _doLayoutDirty = true; } + +LayoutExecutant* Layout::createCurrentLayoutExecutant() +{ + LayoutExecutant* exe = nullptr; + switch (_layoutType) + { + case LAYOUT_LINEAR_VERTICAL: + exe = LinearVerticalLayoutExecutant::create(); + break; + case LAYOUT_LINEAR_HORIZONTAL: + exe = LinearHorizontalLayoutExecutant::create(); + break; + case LAYOUT_RELATIVE: + exe = RelativeLayoutExecutant::create(); + break; + default: + break; + } + return exe; +} LayoutType Layout::getLayoutType() const { @@ -945,444 +1455,9 @@ void Layout::doLayout() { return; } - switch (_layoutType) + if (_curLayoutExecutant) { - case LAYOUT_ABSOLUTE: - break; - case LAYOUT_LINEAR_VERTICAL: - { - Size layoutSize = getSize(); - float topBoundary = layoutSize.height; - - for (auto& subWidget : _children) - { - Widget* child = dynamic_cast(subWidget); - if (child) - { - LinearLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_LINEAR)); - - if (layoutParameter) - { - LinearGravity childGravity = layoutParameter->getGravity(); - Point ap = child->getAnchorPoint(); - Size cs = child->getSize(); - float finalPosX = ap.x * cs.width; - float finalPosY = topBoundary - ((1.0f-ap.y) * cs.height); - switch (childGravity) - { - case LINEAR_GRAVITY_NONE: - case LINEAR_GRAVITY_LEFT: - break; - case LINEAR_GRAVITY_RIGHT: - finalPosX = layoutSize.width - ((1.0f - ap.x) * cs.width); - break; - case LINEAR_GRAVITY_CENTER_HORIZONTAL: - finalPosX = layoutSize.width / 2.0f - cs.width * (0.5f-ap.x); - break; - default: - break; - } - Margin mg = layoutParameter->getMargin(); - finalPosX += mg.left; - finalPosY -= mg.top; - child->setPosition(Point(finalPosX, finalPosY)); - topBoundary = child->getBottomInParent() - mg.bottom; - } - } - } - break; - } - case LAYOUT_LINEAR_HORIZONTAL: - { - Size layoutSize = getSize(); - float leftBoundary = 0.0f; - for (auto& subWidget : _children) - { - Widget* child = dynamic_cast(subWidget); - if (child) - { - LinearLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_LINEAR)); - if (layoutParameter) - { - LinearGravity childGravity = layoutParameter->getGravity(); - Point ap = child->getAnchorPoint(); - Size cs = child->getSize(); - float finalPosX = leftBoundary + (ap.x * cs.width); - float finalPosY = layoutSize.height - (1.0f - ap.y) * cs.height; - switch (childGravity) - { - case LINEAR_GRAVITY_NONE: - case LINEAR_GRAVITY_TOP: - break; - case LINEAR_GRAVITY_BOTTOM: - finalPosY = ap.y * cs.height; - break; - case LINEAR_GRAVITY_CENTER_VERTICAL: - finalPosY = layoutSize.height / 2.0f - cs.height * (0.5f - ap.y); - break; - default: - break; - } - Margin mg = layoutParameter->getMargin(); - finalPosX += mg.left; - finalPosY -= mg.top; - child->setPosition(Point(finalPosX, finalPosY)); - leftBoundary = child->getRightInParent() + mg.right; - } - } - } - break; - } - case LAYOUT_RELATIVE: - { - ssize_t unlayoutChildCount = 0; - Size layoutSize = getSize(); - Vector widgetChildren; - for (auto& subWidget : _children) - { - Widget* child = dynamic_cast(subWidget); - if (child) - { - RelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); - layoutParameter->_put = false; - unlayoutChildCount++; - widgetChildren.pushBack(child); - } - } - while (unlayoutChildCount > 0) - { - for (auto& subWidget : widgetChildren) - { - Widget* child = static_cast(subWidget); - RelativeLayoutParameter* layoutParameter = dynamic_cast(child->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); - - if (layoutParameter) - { - if (layoutParameter->_put) - { - continue; - } - Point ap = child->getAnchorPoint(); - Size cs = child->getSize(); - RelativeAlign align = layoutParameter->getAlign(); - const char* relativeName = layoutParameter->getRelativeToWidgetName(); - Widget* relativeWidget = nullptr; - RelativeLayoutParameter* relativeWidgetLP = nullptr; - float finalPosX = 0.0f; - float finalPosY = 0.0f; - if (relativeName && strcmp(relativeName, "")) - { - relativeWidget = Helper::seekWidgetByRelativeName(this, relativeName); - if (relativeWidget) - { - relativeWidgetLP = dynamic_cast(relativeWidget->getLayoutParameter(LAYOUT_PARAMETER_RELATIVE)); - } - } - switch (align) - { - case RELATIVE_ALIGN_NONE: - case RELATIVE_ALIGN_PARENT_TOP_LEFT: - finalPosX = ap.x * cs.width; - finalPosY = layoutSize.height - ((1.0f - ap.y) * cs.height); - break; - case RELATIVE_ALIGN_PARENT_TOP_CENTER_HORIZONTAL: - finalPosX = layoutSize.width * 0.5f - cs.width * (0.5f - ap.x); - finalPosY = layoutSize.height - ((1.0f - ap.y) * cs.height); - break; - case RELATIVE_ALIGN_PARENT_TOP_RIGHT: - finalPosX = layoutSize.width - ((1.0f - ap.x) * cs.width); - finalPosY = layoutSize.height - ((1.0f - ap.y) * cs.height); - break; - case RELATIVE_ALIGN_PARENT_LEFT_CENTER_VERTICAL: - finalPosX = ap.x * cs.width; - finalPosY = layoutSize.height * 0.5f - cs.height * (0.5f - ap.y); - break; - case RELATIVE_CENTER_IN_PARENT: - finalPosX = layoutSize.width * 0.5f - cs.width * (0.5f - ap.x); - finalPosY = layoutSize.height * 0.5f - cs.height * (0.5f - ap.y); - break; - case RELATIVE_ALIGN_PARENT_RIGHT_CENTER_VERTICAL: - finalPosX = layoutSize.width - ((1.0f - ap.x) * cs.width); - finalPosY = layoutSize.height * 0.5f - cs.height * (0.5f - ap.y); - break; - case RELATIVE_ALIGN_PARENT_LEFT_BOTTOM: - finalPosX = ap.x * cs.width; - finalPosY = ap.y * cs.height; - break; - case RELATIVE_ALIGN_PARENT_BOTTOM_CENTER_HORIZONTAL: - finalPosX = layoutSize.width * 0.5f - cs.width * (0.5f - ap.x); - finalPosY = ap.y * cs.height; - break; - case RELATIVE_ALIGN_PARENT_RIGHT_BOTTOM: - finalPosX = layoutSize.width - ((1.0f - ap.x) * cs.width); - finalPosY = ap.y * cs.height; - break; - - case RELATIVE_LOCATION_ABOVE_LEFTALIGN: - if (relativeWidget) - { - if (relativeWidgetLP && !relativeWidgetLP->_put) - { - continue; - } - float locationBottom = relativeWidget->getTopInParent(); - float locationLeft = relativeWidget->getLeftInParent(); - finalPosY = locationBottom + ap.y * cs.height; - finalPosX = locationLeft + ap.x * cs.width; - } - break; - case RELATIVE_LOCATION_ABOVE_CENTER: - if (relativeWidget) - { - if (relativeWidgetLP && !relativeWidgetLP->_put) - { - continue; - } - Size rbs = relativeWidget->getSize(); - float locationBottom = relativeWidget->getTopInParent(); - - finalPosY = locationBottom + ap.y * cs.height; - finalPosX = relativeWidget->getLeftInParent() + rbs.width * 0.5f + ap.x * cs.width - cs.width * 0.5f; - } - break; - case RELATIVE_LOCATION_ABOVE_RIGHTALIGN: - if (relativeWidget) - { - if (relativeWidgetLP && !relativeWidgetLP->_put) - { - continue; - } - float locationBottom = relativeWidget->getTopInParent(); - float locationRight = relativeWidget->getRightInParent(); - finalPosY = locationBottom + ap.y * cs.height; - finalPosX = locationRight - (1.0f - ap.x) * cs.width; - } - break; - case RELATIVE_LOCATION_LEFT_OF_TOPALIGN: - if (relativeWidget) - { - if (relativeWidgetLP && !relativeWidgetLP->_put) - { - continue; - } - float locationTop = relativeWidget->getTopInParent(); - float locationRight = relativeWidget->getLeftInParent(); - finalPosY = locationTop - (1.0f - ap.y) * cs.height; - finalPosX = locationRight - (1.0f - ap.x) * cs.width; - } - break; - case RELATIVE_LOCATION_LEFT_OF_CENTER: - if (relativeWidget) - { - if (relativeWidgetLP && !relativeWidgetLP->_put) - { - continue; - } - Size rbs = relativeWidget->getSize(); - float locationRight = relativeWidget->getLeftInParent(); - finalPosX = locationRight - (1.0f - ap.x) * cs.width; - - finalPosY = relativeWidget->getBottomInParent() + rbs.height * 0.5f + ap.y * cs.height - cs.height * 0.5f; - } - break; - case RELATIVE_LOCATION_LEFT_OF_BOTTOMALIGN: - if (relativeWidget) - { - if (relativeWidgetLP && !relativeWidgetLP->_put) - { - continue; - } - float locationBottom = relativeWidget->getBottomInParent(); - float locationRight = relativeWidget->getLeftInParent(); - finalPosY = locationBottom + ap.y * cs.height; - finalPosX = locationRight - (1.0f - ap.x) * cs.width; - } - break; - case RELATIVE_LOCATION_RIGHT_OF_TOPALIGN: - if (relativeWidget) - { - if (relativeWidgetLP && !relativeWidgetLP->_put) - { - continue; - } - float locationTop = relativeWidget->getTopInParent(); - float locationLeft = relativeWidget->getRightInParent(); - finalPosY = locationTop - (1.0f - ap.y) * cs.height; - finalPosX = locationLeft + ap.x * cs.width; - } - break; - case RELATIVE_LOCATION_RIGHT_OF_CENTER: - if (relativeWidget) - { - if (relativeWidgetLP && !relativeWidgetLP->_put) - { - continue; - } - Size rbs = relativeWidget->getSize(); - float locationLeft = relativeWidget->getRightInParent(); - finalPosX = locationLeft + ap.x * cs.width; - - finalPosY = relativeWidget->getBottomInParent() + rbs.height * 0.5f + ap.y * cs.height - cs.height * 0.5f; - } - break; - case RELATIVE_LOCATION_RIGHT_OF_BOTTOMALIGN: - if (relativeWidget) - { - if (relativeWidgetLP && !relativeWidgetLP->_put) - { - continue; - } - float locationBottom = relativeWidget->getBottomInParent(); - float locationLeft = relativeWidget->getRightInParent(); - finalPosY = locationBottom + ap.y * cs.height; - finalPosX = locationLeft + ap.x * cs.width; - } - break; - case RELATIVE_LOCATION_BELOW_LEFTALIGN: - if (relativeWidget) - { - if (relativeWidgetLP && !relativeWidgetLP->_put) - { - continue; - } - float locationTop = relativeWidget->getBottomInParent(); - float locationLeft = relativeWidget->getLeftInParent(); - finalPosY = locationTop - (1.0f - ap.y) * cs.height; - finalPosX = locationLeft + ap.x * cs.width; - } - break; - case RELATIVE_LOCATION_BELOW_CENTER: - if (relativeWidget) - { - if (relativeWidgetLP && !relativeWidgetLP->_put) - { - continue; - } - Size rbs = relativeWidget->getSize(); - float locationTop = relativeWidget->getBottomInParent(); - - finalPosY = locationTop - (1.0f - ap.y) * cs.height; - finalPosX = relativeWidget->getLeftInParent() + rbs.width * 0.5f + ap.x * cs.width - cs.width * 0.5f; - } - break; - case RELATIVE_LOCATION_BELOW_RIGHTALIGN: - if (relativeWidget) - { - if (relativeWidgetLP && !relativeWidgetLP->_put) - { - continue; - } - float locationTop = relativeWidget->getBottomInParent(); - float locationRight = relativeWidget->getRightInParent(); - finalPosY = locationTop - (1.0f - ap.y) * cs.height; - finalPosX = locationRight - (1.0f - ap.x) * cs.width; - } - break; - default: - break; - } - Margin relativeWidgetMargin; - Margin mg = layoutParameter->getMargin(); - if (relativeWidgetLP) - { - relativeWidgetMargin = relativeWidgetLP->getMargin(); - } - //handle margin - switch (align) - { - case RELATIVE_ALIGN_NONE: - case RELATIVE_ALIGN_PARENT_TOP_LEFT: - finalPosX += mg.left; - finalPosY -= mg.top; - break; - case RELATIVE_ALIGN_PARENT_TOP_CENTER_HORIZONTAL: - finalPosY -= mg.top; - break; - case RELATIVE_ALIGN_PARENT_TOP_RIGHT: - finalPosX -= mg.right; - finalPosY -= mg.top; - break; - case RELATIVE_ALIGN_PARENT_LEFT_CENTER_VERTICAL: - finalPosX += mg.left; - break; - case RELATIVE_CENTER_IN_PARENT: - break; - case RELATIVE_ALIGN_PARENT_RIGHT_CENTER_VERTICAL: - finalPosX -= mg.right; - break; - case RELATIVE_ALIGN_PARENT_LEFT_BOTTOM: - finalPosX += mg.left; - finalPosY += mg.bottom; - break; - case RELATIVE_ALIGN_PARENT_BOTTOM_CENTER_HORIZONTAL: - finalPosY += mg.bottom; - break; - case RELATIVE_ALIGN_PARENT_RIGHT_BOTTOM: - finalPosX -= mg.right; - finalPosY += mg.bottom; - break; - - case RELATIVE_LOCATION_ABOVE_LEFTALIGN: - finalPosY += mg.bottom; - finalPosX += mg.left; - break; - case RELATIVE_LOCATION_ABOVE_RIGHTALIGN: - finalPosY += mg.bottom; - finalPosX -= mg.right; - break; - case RELATIVE_LOCATION_ABOVE_CENTER: - finalPosY += mg.bottom; - break; - - case RELATIVE_LOCATION_LEFT_OF_TOPALIGN: - finalPosX -= mg.right; - finalPosY -= mg.top; - break; - case RELATIVE_LOCATION_LEFT_OF_BOTTOMALIGN: - finalPosX -= mg.right; - finalPosY += mg.bottom; - break; - case RELATIVE_LOCATION_LEFT_OF_CENTER: - finalPosX -= mg.right; - break; - - case RELATIVE_LOCATION_RIGHT_OF_TOPALIGN: - finalPosX += mg.left; - finalPosY -= mg.top; - break; - case RELATIVE_LOCATION_RIGHT_OF_BOTTOMALIGN: - finalPosX += mg.left; - finalPosY += mg.bottom; - break; - case RELATIVE_LOCATION_RIGHT_OF_CENTER: - finalPosX += mg.left; - break; - - case RELATIVE_LOCATION_BELOW_LEFTALIGN: - finalPosY -= mg.top; - finalPosX += mg.left; - break; - case RELATIVE_LOCATION_BELOW_RIGHTALIGN: - finalPosY -= mg.top; - finalPosX -= mg.right; - break; - case RELATIVE_LOCATION_BELOW_CENTER: - finalPosY -= mg.top; - break; - default: - break; - } - child->setPosition(Point(finalPosX, finalPosY)); - layoutParameter->_put = true; - unlayoutChildCount--; - } - } - } - widgetChildren.clear(); - break; - } - default: - break; + _curLayoutExecutant->doLayout(getSize(), getChildren()); } _doLayoutDirty = false; } diff --git a/cocos/ui/UILayout.h b/cocos/ui/UILayout.h index 9933292252..6c76089f3f 100644 --- a/cocos/ui/UILayout.h +++ b/cocos/ui/UILayout.h @@ -50,6 +50,43 @@ typedef enum { LAYOUT_CLIPPING_STENCIL, LAYOUT_CLIPPING_SCISSOR }LayoutClippingType; + + +class LayoutExecutant : public Ref +{ +public: + LayoutExecutant(){}; + virtual ~LayoutExecutant(){}; + static LayoutExecutant* create(); + virtual void doLayout(const Size& layoutSize, Vector container){}; +}; + +class LinearVerticalLayoutExecutant : public LayoutExecutant +{ +public: + LinearVerticalLayoutExecutant(){}; + virtual ~LinearVerticalLayoutExecutant(){}; + static LinearVerticalLayoutExecutant* create(); + virtual void doLayout(const Size& layoutSize, Vector container); +}; + +class LinearHorizontalLayoutExecutant : public LayoutExecutant +{ +public: + LinearHorizontalLayoutExecutant(){}; + virtual ~LinearHorizontalLayoutExecutant(){}; + static LinearHorizontalLayoutExecutant* create(); + virtual void doLayout(const Size& layoutSize, Vector container); +}; + +class RelativeLayoutExecutant : public LayoutExecutant +{ +public: + RelativeLayoutExecutant(){}; + virtual ~RelativeLayoutExecutant(){}; + static RelativeLayoutExecutant* create(); + virtual void doLayout(const Size& layoutSize, Vector container); +}; /** * @js NA @@ -299,6 +336,7 @@ protected: void updateBackGroundImageColor(); void updateBackGroundImageOpacity(); void updateBackGroundImageRGBA(); + LayoutExecutant* createCurrentLayoutExecutant(); protected: bool _clippingEnabled; @@ -346,6 +384,8 @@ protected: Color3B _backGroundImageColor; GLubyte _backGroundImageOpacity; + LayoutExecutant* _curLayoutExecutant; + GLint _mask_layer_le; GroupCommand _groupCommand; CustomCommand _beforeVisitCmdStencil; diff --git a/cocos/ui/UILayoutParameter.h b/cocos/ui/UILayoutParameter.h index c0f0f5dea6..c087d8bde3 100644 --- a/cocos/ui/UILayoutParameter.h +++ b/cocos/ui/UILayoutParameter.h @@ -216,7 +216,7 @@ protected: std::string _relativeWidgetName; std::string _relativeLayoutName; bool _put; - friend class Layout; + friend class RelativeLayoutExecutant; }; } diff --git a/cocos/ui/UIRelativeBox.cpp b/cocos/ui/UIRelativeBox.cpp new file mode 100644 index 0000000000..ccad3f62cf --- /dev/null +++ b/cocos/ui/UIRelativeBox.cpp @@ -0,0 +1,85 @@ +/**************************************************************************** + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "ui/UIRelativeBox.h" + +NS_CC_BEGIN + +namespace ui{ + +RelativeBox::RelativeBox() +{ +} + +RelativeBox::~RelativeBox() +{ +} + +RelativeBox* RelativeBox::create() +{ + RelativeBox* widget = new RelativeBox(); + if (widget && widget->init()) + { + widget->autorelease(); + return widget; + } + CC_SAFE_DELETE(widget); + return nullptr; +} + +RelativeBox* RelativeBox::create(const cocos2d::Size &size) +{ + RelativeBox* widget = new RelativeBox(); + if (widget && widget->initWithSize(size)) + { + widget->autorelease(); + return widget; + } + CC_SAFE_DELETE(widget); + return nullptr; +} + +bool RelativeBox::init() +{ + if (Layout::init()) + { + setLayoutType(LAYOUT_RELATIVE); + return true; + } + return false; +} + +bool RelativeBox::initWithSize(const Size& size) +{ + if (init()) + { + setSize(size); + return true; + } + return false; +} + +} + +NS_CC_END \ No newline at end of file diff --git a/cocos/ui/UIRelativeBox.h b/cocos/ui/UIRelativeBox.h new file mode 100644 index 0000000000..b4e7082b6d --- /dev/null +++ b/cocos/ui/UIRelativeBox.h @@ -0,0 +1,66 @@ +/**************************************************************************** + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __UIRelativeBox_H__ +#define __UIRelativeBox_H__ + +#include "ui/UILayout.h" + +NS_CC_BEGIN + +namespace ui { + +class RelativeBox : public Layout{ + + +public: + + /** + * Default constructor + */ + RelativeBox(); + + /** + * Default destructor + */ + virtual ~RelativeBox(); + + /** + * Allocates and initializes a RelativeBox. + */ + static RelativeBox* create(); + + static RelativeBox* create(const Size& size); + +CC_CONSTRUCTOR_ACCESS: + //initializes state of widget. + virtual bool init() override; + virtual bool initWithSize(const Size& size); +}; + +} + +NS_CC_END + +#endif /* defined(__UIRelativeBox__) */ diff --git a/cocos/ui/UIVBox.cpp b/cocos/ui/UIVBox.cpp new file mode 100644 index 0000000000..86a832c7d3 --- /dev/null +++ b/cocos/ui/UIVBox.cpp @@ -0,0 +1,85 @@ +/**************************************************************************** + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "ui/UIVBox.h" + +NS_CC_BEGIN + +namespace ui{ + +VBox::VBox() +{ +} + +VBox::~VBox() +{ +} + +VBox* VBox::create() +{ + VBox* widget = new VBox(); + if (widget && widget->init()) + { + widget->autorelease(); + return widget; + } + CC_SAFE_DELETE(widget); + return nullptr; +} + +VBox* VBox::create(const cocos2d::Size &size) +{ + VBox* widget = new VBox(); + if (widget && widget->initWithSize(size)) + { + widget->autorelease(); + return widget; + } + CC_SAFE_DELETE(widget); + return nullptr; +} + +bool VBox::init() +{ + if (Layout::init()) + { + setLayoutType(LAYOUT_LINEAR_VERTICAL); + return true; + } + return false; +} + +bool VBox::initWithSize(const Size& size) +{ + if (init()) + { + setSize(size); + return true; + } + return false; +} + +} + +NS_CC_END \ No newline at end of file diff --git a/cocos/ui/UIVBox.h b/cocos/ui/UIVBox.h new file mode 100644 index 0000000000..216234f47f --- /dev/null +++ b/cocos/ui/UIVBox.h @@ -0,0 +1,66 @@ +/**************************************************************************** + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __UIVBox_H__ +#define __UIVBox_H__ + +#include "ui/UILayout.h" + +NS_CC_BEGIN + +namespace ui { + +class VBox : public Layout{ + + +public: + + /** + * Default constructor + */ + VBox(); + + /** + * Default destructor + */ + virtual ~VBox(); + + /** + * Allocates and initializes a VBox. + */ + static VBox* create(); + + static VBox* create(const Size& size); + +CC_CONSTRUCTOR_ACCESS: + //initializes state of widget. + virtual bool init() override; + virtual bool initWithSize(const Size& size); +}; + +} + +NS_CC_END + +#endif /* defined(__UIVBox__) */ diff --git a/cocos/ui/proj.win32/libGUI.vcxproj b/cocos/ui/proj.win32/libGUI.vcxproj index 7d5aa4d0e6..e977a36ead 100644 --- a/cocos/ui/proj.win32/libGUI.vcxproj +++ b/cocos/ui/proj.win32/libGUI.vcxproj @@ -15,6 +15,7 @@ + @@ -23,6 +24,7 @@ + @@ -31,6 +33,7 @@ + @@ -38,6 +41,7 @@ + @@ -46,6 +50,7 @@ + @@ -53,6 +58,7 @@ + diff --git a/cocos/ui/proj.win32/libGUI.vcxproj.filters b/cocos/ui/proj.win32/libGUI.vcxproj.filters index a01b4594d2..e6aec63af9 100644 --- a/cocos/ui/proj.win32/libGUI.vcxproj.filters +++ b/cocos/ui/proj.win32/libGUI.vcxproj.filters @@ -81,6 +81,15 @@ BaseClasses + + Layouts + + + Layouts + + + Layouts + @@ -143,5 +152,14 @@ BaseClasses + + Layouts + + + Layouts + + + Layouts + \ No newline at end of file From c5d6e83673e9d729fdcf754877eeab90691d7714 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Tue, 25 Mar 2014 09:30:11 +0000 Subject: [PATCH 084/106] [AUTO]: updating luabinding automatically --- cocos/scripting/lua-bindings/auto/api/Label.lua | 10 ++++++++++ .../auto/lua_cocos2dx_auto.cpp.REMOVED.git-id | 2 +- .../scripting/lua-bindings/auto/lua_cocos2dx_auto.hpp | 2 ++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/cocos/scripting/lua-bindings/auto/api/Label.lua b/cocos/scripting/lua-bindings/auto/api/Label.lua index cd439ef1bf..f46a580dc0 100644 --- a/cocos/scripting/lua-bindings/auto/api/Label.lua +++ b/cocos/scripting/lua-bindings/auto/api/Label.lua @@ -3,6 +3,11 @@ -- @module Label -- @extend SpriteBatchNode,LabelProtocol, +-------------------------------- +-- @function [parent=#Label] isClipMarginEnabled +-- @param self +-- @return bool#bool ret (return value: bool) + -------------------------------- -- @function [parent=#Label] enableShadow -- @param self @@ -57,6 +62,11 @@ -- @param self -- @return TextHAlignment#TextHAlignment ret (return value: cc.TextHAlignment) +-------------------------------- +-- @function [parent=#Label] setClipMarginEnabled +-- @param self +-- @param #bool bool + -------------------------------- -- @function [parent=#Label] setString -- @param self diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_auto.cpp.REMOVED.git-id b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_auto.cpp.REMOVED.git-id index 4131e54b6b..ce6e4ecd48 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_auto.cpp.REMOVED.git-id +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_auto.cpp.REMOVED.git-id @@ -1 +1 @@ -83d9fece450a67211518c287e9ecf99ce122c142 \ No newline at end of file +bb331bf4e55b4ca2f5b12c75e6c3e638ae3367d0 \ No newline at end of file diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_auto.hpp b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_auto.hpp index b7ba04e76c..5eeff5ebfd 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_auto.hpp +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_auto.hpp @@ -1544,6 +1544,8 @@ int register_all_cocos2dx(lua_State* tolua_S); + + From 473a6b19ee1cffdd5caa6f8b8126318fd3f58ed1 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Tue, 25 Mar 2014 10:37:35 -0700 Subject: [PATCH 085/106] Upgrades to Chipmunk 6.2.1 --- CHANGELOG.REMOVED.git-id | 2 +- external/chipmunk/include/chipmunk/chipmunk.h | 10 +- .../include/chipmunk/chipmunk_private.h | 73 +- .../include/chipmunk/chipmunk_types.h | 7 + .../include/chipmunk/chipmunk_unsafe.h | 2 + .../chipmunk/include/chipmunk/cpArbiter.h | 2 +- external/chipmunk/include/chipmunk/cpBB.h | 7 + .../chipmunk/include/chipmunk/cpPolyShape.h | 20 +- external/chipmunk/include/chipmunk/cpShape.h | 4 + .../include/chipmunk/cpSpatialIndex.h | 2 +- external/chipmunk/include/chipmunk/cpVect.h | 7 +- external/chipmunk/src/CMakeLists.txt | 18 +- external/chipmunk/src/chipmunk.c | 2 + .../src/constraints/cpRotaryLimitJoint.c | 2 +- external/chipmunk/src/cpBBTree.c | 37 +- external/chipmunk/src/cpCollision.c | 999 ++++++++++++------ external/chipmunk/src/cpPolyShape.c | 89 +- external/chipmunk/src/cpShape.c | 41 +- external/chipmunk/src/cpSpaceHash.c | 2 +- external/chipmunk/src/cpSpaceQuery.c | 38 +- external/chipmunk/src/cpSpaceStep.c | 16 +- external/chipmunk/src/cpSweep1D.c | 4 +- .../Classes/ChipmunkTest/ChipmunkTest.cpp | 14 +- .../Classes/ChipmunkTest/ChipmunkTest.h | 2 +- tests/cpp-tests/Classes/VisibleRect.cpp | 2 + tests/cpp-tests/Classes/VisibleRect.h | 23 +- 26 files changed, 914 insertions(+), 511 deletions(-) diff --git a/CHANGELOG.REMOVED.git-id b/CHANGELOG.REMOVED.git-id index 73a33eb03f..1703c79ebf 100644 --- a/CHANGELOG.REMOVED.git-id +++ b/CHANGELOG.REMOVED.git-id @@ -1 +1 @@ -5b8d2ae9f19e1ca958245cf11e144d18d6ee3f89 \ No newline at end of file +8141cfdd7d973fa5a4c189a72c2fd6cac8eb95ae \ No newline at end of file diff --git a/external/chipmunk/include/chipmunk/chipmunk.h b/external/chipmunk/include/chipmunk/chipmunk.h index f0e4282f7e..6337fb1a13 100644 --- a/external/chipmunk/include/chipmunk/chipmunk.h +++ b/external/chipmunk/include/chipmunk/chipmunk.h @@ -23,9 +23,7 @@ #define CHIPMUNK_HEADER #ifdef _MSC_VER - #ifndef _USE_MATH_DEFINES - #define _USE_MATH_DEFINES - #endif + #define _USE_MATH_DEFINES #endif #include @@ -112,10 +110,10 @@ typedef struct cpSpace cpSpace; #include "cpSpace.h" -// Chipmunk 6.1.5 +// Chipmunk 6.2.1 #define CP_VERSION_MAJOR 6 -#define CP_VERSION_MINOR 1 -#define CP_VERSION_RELEASE 5 +#define CP_VERSION_MINOR 2 +#define CP_VERSION_RELEASE 1 /// Version string. extern const char *cpVersionString; diff --git a/external/chipmunk/include/chipmunk/chipmunk_private.h b/external/chipmunk/include/chipmunk/chipmunk_private.h index 3353292262..f676345bc9 100644 --- a/external/chipmunk/include/chipmunk/chipmunk_private.h +++ b/external/chipmunk/include/chipmunk/chipmunk_private.h @@ -25,6 +25,9 @@ #define CP_HASH_COEF (3344921057ul) #define CP_HASH_PAIR(A, B) ((cpHashValue)(A)*CP_HASH_COEF ^ (cpHashValue)(B)*CP_HASH_COEF) +// TODO: Eww. Magic numbers. +#define MAGIC_EPSILON 1e-5 + //MARK: cpArray struct cpArray { @@ -43,6 +46,7 @@ cpBool cpArrayContains(cpArray *arr, void *ptr); void cpArrayFreeEach(cpArray *arr, void (freeFunc)(void*)); + //MARK: Foreach loops static inline cpConstraint * @@ -69,6 +73,7 @@ cpArbiterNext(cpArbiter *node, cpBody *body) #define CP_BODY_FOREACH_COMPONENT(root, var)\ for(cpBody *var = root; var; var = var->node.next) + //MARK: cpHashSet typedef cpBool (*cpHashSetEqlFunc)(void *ptr, void *elt); @@ -90,6 +95,7 @@ void cpHashSetEach(cpHashSet *set, cpHashSetIteratorFunc func, void *data); typedef cpBool (*cpHashSetFilterFunc)(void *elt, void *data); void cpHashSetFilter(cpHashSet *set, cpHashSetFilterFunc func, void *data); + //MARK: Body Functions void cpBodyAddShape(cpBody *body, cpShape *shape); @@ -116,7 +122,29 @@ cpShapeActive(cpShape *shape) return shape->prev || (shape->body && shape->body->shapeList == shape); } -int cpCollideShapes(const cpShape *a, const cpShape *b, cpContact *arr); +int cpCollideShapes(const cpShape *a, const cpShape *b, cpCollisionID *id, cpContact *arr); + +static inline void +CircleSegmentQuery(cpShape *shape, cpVect center, cpFloat r, cpVect a, cpVect b, cpSegmentQueryInfo *info) +{ + cpVect da = cpvsub(a, center); + cpVect db = cpvsub(b, center); + + cpFloat qa = cpvdot(da, da) - 2.0f*cpvdot(da, db) + cpvdot(db, db); + cpFloat qb = -2.0f*cpvdot(da, da) + 2.0f*cpvdot(da, db); + cpFloat qc = cpvdot(da, da) - r*r; + + cpFloat det = qb*qb - 4.0f*qa*qc; + + if(det >= 0.0f){ + cpFloat t = (-qb - cpfsqrt(det))/(2.0f*qa); + if(0.0f<= t && t <= 1.0f){ + info->shape = shape; + info->t = t; + info->n = cpvnormalize(cpvlerp(da, db, t)); + } + } +} // TODO doesn't really need to be inline, but need a better place to put this function static inline cpSplittingPlane @@ -135,50 +163,12 @@ cpSplittingPlaneCompare(cpSplittingPlane plane, cpVect v) void cpLoopIndexes(cpVect *verts, int count, int *start, int *end); -static inline cpFloat -cpPolyShapeValueOnAxis(const cpPolyShape *poly, const cpVect n, const cpFloat d) -{ - cpVect *verts = poly->tVerts; - cpFloat min = cpvdot(n, verts[0]); - - for(int i=1; inumVerts; i++){ - min = cpfmin(min, cpvdot(n, verts[i])); - } - - return min - d; -} - -static inline cpBool -cpPolyShapeContainsVert(const cpPolyShape *poly, const cpVect v) -{ - cpSplittingPlane *planes = poly->tPlanes; - - for(int i=0; inumVerts; i++){ - cpFloat dist = cpSplittingPlaneCompare(planes[i], v); - if(dist > 0.0f) return cpFalse; - } - - return cpTrue; -} - -static inline cpBool -cpPolyShapeContainsVertPartial(const cpPolyShape *poly, const cpVect v, const cpVect n) -{ - cpSplittingPlane *planes = poly->tPlanes; - - for(int i=0; inumVerts; i++){ - if(cpvdot(planes[i].n, n) < 0.0f) continue; - cpFloat dist = cpSplittingPlaneCompare(planes[i], v); - if(dist > 0.0f) return cpFalse; - } - - return cpTrue; -} //MARK: Spatial Index Functions cpSpatialIndex *cpSpatialIndexInit(cpSpatialIndex *index, cpSpatialIndexClass *klass, cpSpatialIndexBBFunc bbfunc, cpSpatialIndex *staticIndex); + //MARK: Space Functions extern cpCollisionHandler cpDefaultCollisionHandler; @@ -221,8 +211,7 @@ cpSpaceUncacheArbiter(cpSpace *space, cpArbiter *arb) } void cpShapeUpdateFunc(cpShape *shape, void *unused); -void cpSpaceCollideShapes(cpShape *a, cpShape *b, cpSpace *space); - +cpCollisionID cpSpaceCollideShapes(cpShape *a, cpShape *b, cpCollisionID id, cpSpace *space); //MARK: Arbiters diff --git a/external/chipmunk/include/chipmunk/chipmunk_types.h b/external/chipmunk/include/chipmunk/chipmunk_types.h index a4c21899db..fdfb6d1eef 100644 --- a/external/chipmunk/include/chipmunk/chipmunk_types.h +++ b/external/chipmunk/include/chipmunk/chipmunk_types.h @@ -1,4 +1,5 @@ #include +#include #ifdef __APPLE__ #include "TargetConditionals.h" @@ -45,6 +46,7 @@ #define cpfpow pow #define cpffloor floor #define cpfceil ceil + #define CPFLOAT_MIN DBL_MIN #else typedef float cpFloat; #define cpfsqrt sqrtf @@ -57,6 +59,7 @@ #define cpfpow powf #define cpffloor floorf #define cpfceil ceilf + #define CPFLOAT_MIN FLT_MIN #endif #ifndef INFINITY @@ -135,6 +138,10 @@ static inline cpFloat cpflerpconst(cpFloat f1, cpFloat f2, cpFloat d) /// Hash value type. typedef uintptr_t cpHashValue; +/// Type used internally to cache colliding object info for cpCollideShapes(). +/// Should be at least 32 bits. +typedef uint32_t cpCollisionID; + // Oh C, how we love to define our own boolean types to get compiler compatibility /// Chipmunk's boolean type. #ifdef CP_BOOL_TYPE diff --git a/external/chipmunk/include/chipmunk/chipmunk_unsafe.h b/external/chipmunk/include/chipmunk/chipmunk_unsafe.h index 637e33670c..4428814c07 100644 --- a/external/chipmunk/include/chipmunk/chipmunk_unsafe.h +++ b/external/chipmunk/include/chipmunk/chipmunk_unsafe.h @@ -55,6 +55,8 @@ void cpSegmentShapeSetRadius(cpShape *shape, cpFloat radius); /// Set the vertexes of a poly shape. void cpPolyShapeSetVerts(cpShape *shape, int numVerts, cpVect *verts, cpVect offset); +/// Set the radius of a poly shape. +void cpPolyShapeSetRadius(cpShape *shape, cpFloat radius); #ifdef __cplusplus } diff --git a/external/chipmunk/include/chipmunk/cpArbiter.h b/external/chipmunk/include/chipmunk/cpArbiter.h index 4891948184..1ccb693d3a 100644 --- a/external/chipmunk/include/chipmunk/cpArbiter.h +++ b/external/chipmunk/include/chipmunk/cpArbiter.h @@ -50,7 +50,7 @@ struct cpCollisionHandler { typedef struct cpContact cpContact; -#define CP_MAX_CONTACTS_PER_ARBITER 4 +#define CP_MAX_CONTACTS_PER_ARBITER 2 /// @private typedef enum cpArbiterState { diff --git a/external/chipmunk/include/chipmunk/cpBB.h b/external/chipmunk/include/chipmunk/cpBB.h index 320a1af358..4e59c2d495 100644 --- a/external/chipmunk/include/chipmunk/cpBB.h +++ b/external/chipmunk/include/chipmunk/cpBB.h @@ -79,6 +79,13 @@ static inline cpBB cpBBExpand(const cpBB bb, const cpVect v){ ); } +/// Returns the center of a bounding box. +static inline cpVect +cpBBCenter(cpBB bb) +{ + return cpvlerp(cpv(bb.l, bb.b), cpv(bb.r, bb.t), 0.5f); +} + /// Returns the area of the bounding box. static inline cpFloat cpBBArea(cpBB bb) { diff --git a/external/chipmunk/include/chipmunk/cpPolyShape.h b/external/chipmunk/include/chipmunk/cpPolyShape.h index 40ecd8b472..a5587ba250 100644 --- a/external/chipmunk/include/chipmunk/cpPolyShape.h +++ b/external/chipmunk/include/chipmunk/cpPolyShape.h @@ -35,6 +35,8 @@ typedef struct cpPolyShape { int numVerts; cpVect *verts, *tVerts; cpSplittingPlane *planes, *tPlanes; + + cpFloat r; } cpPolyShape; /// Allocate a polygon shape. @@ -42,26 +44,38 @@ cpPolyShape* cpPolyShapeAlloc(void); /// Initialize a polygon shape. /// A convex hull will be created from the vertexes. cpPolyShape* cpPolyShapeInit(cpPolyShape *poly, cpBody *body, int numVerts, const cpVect *verts, cpVect offset); +/// Initialize a polygon shape. +/// A convex hull will be created from the vertexes. +cpPolyShape* cpPolyShapeInit2(cpPolyShape *poly, cpBody *body, int numVerts, const cpVect *verts, cpVect offset, cpFloat radius); /// Allocate and initialize a polygon shape. /// A convex hull will be created from the vertexes. -cpShape* cpPolyShapeNew(cpBody *body, int numVerts, cpVect *verts, cpVect offset); +cpShape* cpPolyShapeNew(cpBody *body, int numVerts, const cpVect *verts, cpVect offset); +/// Allocate and initialize a polygon shape. +/// A convex hull will be created from the vertexes. +cpShape* cpPolyShapeNew2(cpBody *body, int numVerts, const cpVect *verts, cpVect offset, cpFloat radius); /// Initialize a box shaped polygon shape. cpPolyShape* cpBoxShapeInit(cpPolyShape *poly, cpBody *body, cpFloat width, cpFloat height); /// Initialize an offset box shaped polygon shape. cpPolyShape* cpBoxShapeInit2(cpPolyShape *poly, cpBody *body, cpBB box); +/// Initialize an offset box shaped polygon shape. +cpPolyShape* cpBoxShapeInit3(cpPolyShape *poly, cpBody *body, cpBB box, cpFloat radius); /// Allocate and initialize a box shaped polygon shape. cpShape* cpBoxShapeNew(cpBody *body, cpFloat width, cpFloat height); /// Allocate and initialize an offset box shaped polygon shape. cpShape* cpBoxShapeNew2(cpBody *body, cpBB box); +/// Allocate and initialize an offset box shaped polygon shape. +cpShape* cpBoxShapeNew3(cpBody *body, cpBB box, cpFloat radius); /// Check that a set of vertexes is convex and has a clockwise winding. /// NOTE: Due to floating point precision issues, hulls created with cpQuickHull() are not guaranteed to validate! cpBool cpPolyValidate(const cpVect *verts, const int numVerts); /// Get the number of verts in a polygon shape. -int cpPolyShapeGetNumVerts(cpShape *shape); +int cpPolyShapeGetNumVerts(const cpShape *shape); /// Get the @c ith vertex of a polygon shape. -cpVect cpPolyShapeGetVert(cpShape *shape, int idx); +cpVect cpPolyShapeGetVert(const cpShape *shape, int idx); +/// Get the radius of a polygon shape. +cpFloat cpPolyShapeGetRadius(const cpShape *shape); /// @} diff --git a/external/chipmunk/include/chipmunk/cpShape.h b/external/chipmunk/include/chipmunk/cpShape.h index 0d927a69b6..62920c371c 100644 --- a/external/chipmunk/include/chipmunk/cpShape.h +++ b/external/chipmunk/include/chipmunk/cpShape.h @@ -33,6 +33,9 @@ typedef struct cpNearestPointQueryInfo { cpVect p; /// The distance to the point. The distance is negative if the point is inside the shape. cpFloat d; + /// The gradient of the signed distance function. + /// The same as info.p/info.d, but accurate even for very small values of info.d. + cpVect g; } cpNearestPointQueryInfo; /// Segment query info struct. @@ -218,6 +221,7 @@ cpSegmentShape* cpSegmentShapeInit(cpSegmentShape *seg, cpBody *body, cpVect a, /// Allocate and initialize a segment shape. cpShape* cpSegmentShapeNew(cpBody *body, cpVect a, cpVect b, cpFloat radius); +/// Let Chipmunk know about the geometry of adjacent segments to avoid colliding with endcaps. void cpSegmentShapeSetNeighbors(cpShape *shape, cpVect prev, cpVect next); CP_DeclareShapeGetter(cpSegmentShape, cpVect, A); diff --git a/external/chipmunk/include/chipmunk/cpSpatialIndex.h b/external/chipmunk/include/chipmunk/cpSpatialIndex.h index bf3d0da397..c279cad063 100644 --- a/external/chipmunk/include/chipmunk/cpSpatialIndex.h +++ b/external/chipmunk/include/chipmunk/cpSpatialIndex.h @@ -46,7 +46,7 @@ typedef cpBB (*cpSpatialIndexBBFunc)(void *obj); /// Spatial index/object iterator callback function type. typedef void (*cpSpatialIndexIteratorFunc)(void *obj, void *data); /// Spatial query callback function type. -typedef void (*cpSpatialIndexQueryFunc)(void *obj1, void *obj2, void *data); +typedef cpCollisionID (*cpSpatialIndexQueryFunc)(void *obj1, void *obj2, cpCollisionID id, void *data); /// Spatial segment query callback function type. typedef cpFloat (*cpSpatialIndexSegmentQueryFunc)(void *obj1, void *obj2, void *data); diff --git a/external/chipmunk/include/chipmunk/cpVect.h b/external/chipmunk/include/chipmunk/cpVect.h index a59a361e84..90855e56e2 100644 --- a/external/chipmunk/include/chipmunk/cpVect.h +++ b/external/chipmunk/include/chipmunk/cpVect.h @@ -151,13 +151,14 @@ static inline cpVect cpvlerp(const cpVect v1, const cpVect v2, const cpFloat t) /// Returns a normalized copy of v. static inline cpVect cpvnormalize(const cpVect v) { - return cpvmult(v, 1.0f/cpvlength(v)); + // Neat trick I saw somewhere to avoid div/0. + return cpvmult(v, 1.0f/(cpvlength(v) + CPFLOAT_MIN)); } -/// Returns a normalized copy of v or cpvzero if v was already cpvzero. Protects against divide by zero errors. +/// @deprecated Just an alias for cpvnormalize() now. static inline cpVect cpvnormalize_safe(const cpVect v) { - return (v.x == 0.0f && v.y == 0.0f ? cpvzero : cpvnormalize(v)); + return cpvnormalize(v); } /// Clamp v to length len. diff --git a/external/chipmunk/src/CMakeLists.txt b/external/chipmunk/src/CMakeLists.txt index 45c855e838..2e817ea717 100644 --- a/external/chipmunk/src/CMakeLists.txt +++ b/external/chipmunk/src/CMakeLists.txt @@ -1,5 +1,3 @@ -set(BUILD_STATIC 1) - file(GLOB chipmunk_source_files "*.c" "constraints/*.c") file(GLOB chipmunk_public_header "${chipmunk_SOURCE_DIR}/include/chipmunk/*.h") file(GLOB chipmunk_constraint_header "${chipmunk_SOURCE_DIR}/include/chipmunk/constraints/*.h") @@ -16,7 +14,14 @@ if(BUILD_SHARED) set_target_properties(chipmunk PROPERTIES LINKER_LANGUAGE CXX) endif(MSVC) # set the lib's version number - set_target_properties(chipmunk PROPERTIES VERSION 6.1.5) + # But avoid on Android because symlinks to version numbered .so's don't work with Android's Java-side loadLibrary. + if(NOT ANDROID) + set_target_properties(chipmunk PROPERTIES VERSION 6.2.1) + endif(NOT ANDROID) + if(ANDROID) + # need to explicitly link to the math library because the CMake/Android toolchains may not do it automatically + target_link_libraries(chipmunk m) + endif(ANDROID) install(TARGETS chipmunk RUNTIME DESTINATION lib LIBRARY DESTINATION lib) endif(BUILD_SHARED) @@ -41,10 +46,3 @@ if(BUILD_SHARED OR INSTALL_STATIC) install(FILES ${chipmunk_public_header} DESTINATION include/chipmunk) install(FILES ${chipmunk_constraint_header} DESTINATION include/chipmunk/constraints) endif(BUILD_SHARED OR INSTALL_STATIC) - -set_target_properties(chipmunk_static - PROPERTIES - ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib" - LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib" -) - diff --git a/external/chipmunk/src/chipmunk.c b/external/chipmunk/src/chipmunk.c index 8487dd0b7f..2c098df4f6 100644 --- a/external/chipmunk/src/chipmunk.c +++ b/external/chipmunk/src/chipmunk.c @@ -83,6 +83,8 @@ cpAreaForSegment(cpVect a, cpVect b, cpFloat r) cpFloat cpMomentForPoly(cpFloat m, const int numVerts, const cpVect *verts, cpVect offset) { + if(numVerts == 2) return cpMomentForSegment(m, verts[0], verts[1]); + cpFloat sum1 = 0.0f; cpFloat sum2 = 0.0f; for(int i=0; iiSum = 1.0f/(1.0f/a->i + 1.0f/b->i); + joint->iSum = 1.0f/(a->i_inv + b->i_inv); // calculate bias velocity cpFloat maxBias = joint->constraint.maxBias; diff --git a/external/chipmunk/src/cpBBTree.c b/external/chipmunk/src/cpBBTree.c index 757606e797..6d347e4d60 100644 --- a/external/chipmunk/src/cpBBTree.c +++ b/external/chipmunk/src/cpBBTree.c @@ -72,7 +72,10 @@ typedef struct Thread { Pair *next; } Thread; -struct Pair { Thread a, b; }; +struct Pair { + Thread a, b; + cpCollisionID id; +}; //MARK: Misc Functions @@ -205,7 +208,7 @@ PairInsert(Node *a, Node *b, cpBBTree *tree) { Pair *nextA = a->PAIRS, *nextB = b->PAIRS; Pair *pair = PairFromPool(tree); - Pair temp = {{NULL, a, nextA},{NULL, b, nextB}}; + Pair temp = {{NULL, a, nextA},{NULL, b, nextB}, 0}; a->PAIRS = b->PAIRS = pair; *pair = temp; @@ -351,7 +354,7 @@ SubtreeQuery(Node *subtree, void *obj, cpBB bb, cpSpatialIndexQueryFunc func, vo { if(cpBBIntersects(subtree->bb, bb)){ if(NodeIsLeaf(subtree)){ - func(obj, subtree->obj, data); + func(obj, subtree->obj, 0, data); } else { SubtreeQuery(subtree->A, obj, bb, func, data); SubtreeQuery(subtree->B, obj, bb, func, data); @@ -428,7 +431,7 @@ MarkLeafQuery(Node *subtree, Node *leaf, cpBool left, MarkContext *context) PairInsert(leaf, subtree, context->tree); } else { if(subtree->STAMP < leaf->STAMP) PairInsert(subtree, leaf, context->tree); - context->func(leaf->obj, subtree->obj, context->data); + context->func(leaf->obj, subtree->obj, 0, context->data); } } else { MarkLeafQuery(subtree->A, leaf, left, context); @@ -456,7 +459,7 @@ MarkLeaf(Node *leaf, MarkContext *context) Pair *pair = leaf->PAIRS; while(pair){ if(leaf == pair->b.leaf){ - context->func(pair->a.leaf->obj, leaf->obj, context->data); + pair->id = context->func(pair->a.leaf->obj, leaf->obj, pair->id, context->data); pair = pair->b.next; } else { pair = pair->a.next; @@ -472,7 +475,7 @@ MarkSubtree(Node *subtree, MarkContext *context) MarkLeaf(subtree, context); } else { MarkSubtree(subtree->A, context); - MarkSubtree(subtree->B, context); + MarkSubtree(subtree->B, context); // TODO Force TCO here? } } @@ -508,12 +511,12 @@ LeafUpdate(Node *leaf, cpBBTree *tree) leaf->STAMP = GetMasterTree(tree)->stamp; return cpTrue; + } else { + return cpFalse; } - - return cpFalse; } -static void VoidQueryFunc(void *obj1, void *obj2, void *data){} +static cpCollisionID VoidQueryFunc(void *obj1, void *obj2, cpCollisionID id, void *data){return id;} static void LeafAddPairs(Node *leaf, cpBBTree *tree) @@ -864,17 +867,17 @@ NodeRender(Node *node, int depth) // glColor3f(1.0f - v, v, 0.0f); glLineWidth(cpfmax(5.0f - depth, 1.0f)); glBegin(GL_LINES); { - glVertex2F(bb.l, bb.b); - glVertex2F(bb.l, bb.t); + glVertex2f(bb.l, bb.b); + glVertex2f(bb.l, bb.t); - glVertex2F(bb.l, bb.t); - glVertex2F(bb.r, bb.t); + glVertex2f(bb.l, bb.t); + glVertex2f(bb.r, bb.t); - glVertex2F(bb.r, bb.t); - glVertex2F(bb.r, bb.b); + glVertex2f(bb.r, bb.t); + glVertex2f(bb.r, bb.b); - glVertex2F(bb.r, bb.b); - glVertex2F(bb.l, bb.b); + glVertex2f(bb.r, bb.b); + glVertex2f(bb.l, bb.b); }; glEnd(); } diff --git a/external/chipmunk/src/cpCollision.c b/external/chipmunk/src/cpCollision.c index 78798116a9..e29e4bf82e 100644 --- a/external/chipmunk/src/cpCollision.c +++ b/external/chipmunk/src/cpCollision.c @@ -18,47 +18,538 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ - + +#include +#include + #include "chipmunk_private.h" -typedef int (*collisionFunc)(const cpShape *, const cpShape *, cpContact *); +#if DEBUG && 0 +#include "ChipmunkDemo.h" +#define DRAW_ALL 0 +#define DRAW_GJK (0 || DRAW_ALL) +#define DRAW_EPA (0 || DRAW_ALL) +#define DRAW_CLOSEST (0 || DRAW_ALL) +#define DRAW_CLIP (0 || DRAW_ALL) + +#define PRINT_LOG 0 +#endif + +#define ENABLE_CACHING 1 + +#define MAX_GJK_ITERATIONS 30 +#define MAX_EPA_ITERATIONS 30 +#define WARN_GJK_ITERATIONS 20 +#define WARN_EPA_ITERATIONS 20 // Add contact points for circle to circle collisions. // Used by several collision tests. +// TODO should accept hash parameter static int -circle2circleQuery(const cpVect p1, const cpVect p2, const cpFloat r1, const cpFloat r2, cpContact *con) +CircleToCircleQuery(const cpVect p1, const cpVect p2, const cpFloat r1, const cpFloat r2, cpHashValue hash, cpContact *con) { cpFloat mindist = r1 + r2; cpVect delta = cpvsub(p2, p1); cpFloat distsq = cpvlengthsq(delta); - if(distsq >= mindist*mindist) return 0; - cpFloat dist = cpfsqrt(distsq); - - // Allocate and initialize the contact. - cpContactInit( - con, - cpvadd(p1, cpvmult(delta, 0.5f + (r1 - 0.5f*mindist)/(dist ? dist : INFINITY))), - (dist ? cpvmult(delta, 1.0f/dist) : cpv(1.0f, 0.0f)), - dist - mindist, - 0 - ); - - return 1; + if(distsq < mindist*mindist){ + cpFloat dist = cpfsqrt(distsq); + cpVect n = (dist ? cpvmult(delta, 1.0f/dist) : cpv(1.0f, 0.0f)); + cpContactInit(con, cpvlerp(p1, p2, r1/(r1 + r2)), n, dist - mindist, hash); + + return 1; + } else { + return 0; + } } +//MARK: Support Points and Edges: + +static inline int +PolySupportPointIndex(const int count, const cpVect *verts, const cpVect n) +{ + cpFloat max = -INFINITY; + int index = 0; + + for(int i=0; i max){ + max = d; + index = i; + } + } + + return index; +} + +struct SupportPoint { + cpVect p; + cpCollisionID id; +}; + +static inline struct SupportPoint +SupportPointNew(cpVect p, cpCollisionID id) +{ + struct SupportPoint point = {p, id}; + return point; +} + +typedef struct SupportPoint (*SupportPointFunc)(const cpShape *shape, const cpVect n); + +static inline struct SupportPoint +CircleSupportPoint(const cpCircleShape *circle, const cpVect n) +{ + return SupportPointNew(circle->tc, 0); +} + +static inline struct SupportPoint +SegmentSupportPoint(const cpSegmentShape *seg, const cpVect n) +{ + if(cpvdot(seg->ta, n) > cpvdot(seg->tb, n)){ + return SupportPointNew(seg->ta, 0); + } else { + return SupportPointNew(seg->tb, 1); + } +} + +static inline struct SupportPoint +PolySupportPoint(const cpPolyShape *poly, const cpVect n) +{ + const cpVect *verts = poly->tVerts; + int i = PolySupportPointIndex(poly->numVerts, verts, n); + return SupportPointNew(verts[i], i); +} + +struct MinkowskiPoint { + cpVect a, b; + cpVect ab; + cpCollisionID id; +}; + +static inline struct MinkowskiPoint +MinkowskiPointNew(const struct SupportPoint a, const struct SupportPoint b) +{ + struct MinkowskiPoint point = {a.p, b.p, cpvsub(b.p, a.p), (a.id & 0xFF)<<8 | (b.id & 0xFF)}; + return point; +} + +struct SupportContext { + const cpShape *shape1, *shape2; + SupportPointFunc func1, func2; +}; + +static inline struct MinkowskiPoint +Support(const struct SupportContext *ctx, const cpVect n) +{ + struct SupportPoint a = ctx->func1(ctx->shape1, cpvneg(n)); + struct SupportPoint b = ctx->func2(ctx->shape2, n); + return MinkowskiPointNew(a, b); +} + +struct EdgePoint { + cpVect p; + cpHashValue hash; +}; + +struct Edge { + struct EdgePoint a, b; + cpFloat r; + cpVect n; +}; + +static inline struct Edge +EdgeNew(cpVect va, cpVect vb, cpHashValue ha, cpHashValue hb, cpFloat r) +{ + struct Edge edge = {{va, ha}, {vb, hb}, r, cpvnormalize(cpvperp(cpvsub(vb, va)))}; + return edge; +} + +static struct Edge +SupportEdgeForPoly(const cpPolyShape *poly, const cpVect n) +{ + int numVerts = poly->numVerts; + int i1 = PolySupportPointIndex(poly->numVerts, poly->tVerts, n); + + // TODO get rid of mod eventually, very expensive on ARM + int i0 = (i1 - 1 + numVerts)%numVerts; + int i2 = (i1 + 1)%numVerts; + + cpVect *verts = poly->tVerts; + if(cpvdot(n, poly->tPlanes[i1].n) > cpvdot(n, poly->tPlanes[i2].n)){ + struct Edge edge = {{verts[i0], CP_HASH_PAIR(poly, i0)}, {verts[i1], CP_HASH_PAIR(poly, i1)}, poly->r, poly->tPlanes[i1].n}; + return edge; + } else { + struct Edge edge = {{verts[i1], CP_HASH_PAIR(poly, i1)}, {verts[i2], CP_HASH_PAIR(poly, i2)}, poly->r, poly->tPlanes[i2].n}; + return edge; + } +} + +static struct Edge +SupportEdgeForSegment(const cpSegmentShape *seg, const cpVect n) +{ + if(cpvdot(seg->tn, n) > 0.0){ + struct Edge edge = {{seg->ta, CP_HASH_PAIR(seg, 0)}, {seg->tb, CP_HASH_PAIR(seg, 1)}, seg->r, seg->tn}; + return edge; + } else { + struct Edge edge = {{seg->tb, CP_HASH_PAIR(seg, 1)}, {seg->ta, CP_HASH_PAIR(seg, 0)}, seg->r, cpvneg(seg->tn)}; + return edge; + } +} + +static inline cpFloat +ClosestT(const cpVect a, const cpVect b) +{ + cpVect delta = cpvsub(b, a); + return -cpfclamp(cpvdot(delta, cpvadd(a, b))/cpvlengthsq(delta), -1.0f, 1.0f); +} + +static inline cpVect +LerpT(const cpVect a, const cpVect b, const cpFloat t) +{ + cpFloat ht = 0.5f*t; + return cpvadd(cpvmult(a, 0.5f - ht), cpvmult(b, 0.5f + ht)); +} + +struct ClosestPoints { + cpVect a, b; + cpVect n; + cpFloat d; + cpCollisionID id; +}; + +static inline struct ClosestPoints +ClosestPointsNew(const struct MinkowskiPoint v0, const struct MinkowskiPoint v1) +{ + cpFloat t = ClosestT(v0.ab, v1.ab); + cpVect p = LerpT(v0.ab, v1.ab, t); + + cpVect pa = LerpT(v0.a, v1.a, t); + cpVect pb = LerpT(v0.b, v1.b, t); + cpCollisionID id = (v0.id & 0xFFFF)<<16 | (v1.id & 0xFFFF); + + cpVect delta = cpvsub(v1.ab, v0.ab); + cpVect n = cpvnormalize(cpvperp(delta)); + cpFloat d = -cpvdot(n, p); + + if(d <= 0.0f || (0.0f < t && t < 1.0f)){ + struct ClosestPoints points = {pa, pb, cpvneg(n), d, id}; + return points; + } else { + cpFloat d2 = cpvlength(p); + cpVect n = cpvmult(p, 1.0f/(d2 + CPFLOAT_MIN)); + + struct ClosestPoints points = {pa, pb, n, d2, id}; + return points; + } +} + +//MARK: EPA Functions + +static inline cpFloat +ClosestDist(const cpVect v0,const cpVect v1) +{ + return cpvlengthsq(LerpT(v0, v1, ClosestT(v0, v1))); +} + +static struct ClosestPoints +EPARecurse(const struct SupportContext *ctx, const int count, const struct MinkowskiPoint *hull, const int iteration) +{ + int mini = 0; + cpFloat minDist = INFINITY; + + // TODO: precalculate this when building the hull and save a step. + for(int j=0, i=count-1; j 0.0f && iteration < MAX_EPA_ITERATIONS){ + int count2 = 1; + struct MinkowskiPoint *hull2 = (struct MinkowskiPoint *)alloca((count + 1)*sizeof(struct MinkowskiPoint)); + hull2[0] = p; + + for(int i=0; i 0.0f){ + hull2[count2] = hull[index]; + count2++; + } + } + + return EPARecurse(ctx, count2, hull2, iteration + 1); + } else { + cpAssertWarn(iteration < WARN_EPA_ITERATIONS, "High EPA iterations: %d", iteration); + return ClosestPointsNew(v0, v1); + } +} + +static struct ClosestPoints +EPA(const struct SupportContext *ctx, const struct MinkowskiPoint v0, const struct MinkowskiPoint v1, const struct MinkowskiPoint v2) +{ + // TODO: allocate a NxM array here and do an in place convex hull reduction in EPARecurse + struct MinkowskiPoint hull[3] = {v0, v1, v2}; + return EPARecurse(ctx, 3, hull, 1); +} + +//MARK: GJK Functions. + +static inline struct ClosestPoints +GJKRecurse(const struct SupportContext *ctx, const struct MinkowskiPoint v0, const struct MinkowskiPoint v1, const int iteration) +{ + if(iteration > MAX_GJK_ITERATIONS){ + cpAssertWarn(iteration < WARN_GJK_ITERATIONS, "High GJK iterations: %d", iteration); + return ClosestPointsNew(v0, v1); + } + + cpVect delta = cpvsub(v1.ab, v0.ab); + if(cpvcross(delta, cpvadd(v0.ab, v1.ab)) > 0.0f){ + // Origin is behind axis. Flip and try again. + return GJKRecurse(ctx, v1, v0, iteration + 1); + } else { + cpFloat t = ClosestT(v0.ab, v1.ab); + cpVect n = (-1.0f < t && t < 1.0f ? cpvperp(delta) : cpvneg(LerpT(v0.ab, v1.ab, t))); + struct MinkowskiPoint p = Support(ctx, n); + +#if DRAW_GJK + ChipmunkDebugDrawSegment(v0.ab, v1.ab, RGBAColor(1, 1, 1, 1)); + cpVect c = cpvlerp(v0.ab, v1.ab, 0.5); + ChipmunkDebugDrawSegment(c, cpvadd(c, cpvmult(cpvnormalize(n), 5.0)), RGBAColor(1, 0, 0, 1)); + + ChipmunkDebugDrawPoints(5.0, 1, &p.ab, RGBAColor(1, 1, 1, 1)); +#endif + + if( + cpvcross(cpvsub(v1.ab, p.ab), cpvadd(v1.ab, p.ab)) > 0.0f && + cpvcross(cpvsub(v0.ab, p.ab), cpvadd(v0.ab, p.ab)) < 0.0f + ){ + cpAssertWarn(iteration < WARN_GJK_ITERATIONS, "High GJK->EPA iterations: %d", iteration); + // The triangle v0, p, v1 contains the origin. Use EPA to find the MSA. + return EPA(ctx, v0, p, v1); + } else { + // The new point must be farther along the normal than the existing points. + if(cpvdot(p.ab, n) <= cpfmax(cpvdot(v0.ab, n), cpvdot(v1.ab, n))){ + cpAssertWarn(iteration < WARN_GJK_ITERATIONS, "High GJK iterations: %d", iteration); + return ClosestPointsNew(v0, v1); + } else { + if(ClosestDist(v0.ab, p.ab) < ClosestDist(p.ab, v1.ab)){ + return GJKRecurse(ctx, v0, p, iteration + 1); + } else { + return GJKRecurse(ctx, p, v1, iteration + 1); + } + } + } + } +} + +static struct SupportPoint +ShapePoint(const cpShape *shape, const int i) +{ + switch(shape->klass->type){ + case CP_CIRCLE_SHAPE: { + return SupportPointNew(((cpCircleShape *)shape)->tc, 0); + } case CP_SEGMENT_SHAPE: { + cpSegmentShape *seg = (cpSegmentShape *)shape; + return SupportPointNew(i == 0 ? seg->ta : seg->tb, i); + } case CP_POLY_SHAPE: { + cpPolyShape *poly = (cpPolyShape *)shape; + // Poly shapes may change vertex count. + int index = (i < poly->numVerts ? i : 0); + return SupportPointNew(poly->tVerts[index], index); + } default: { + return SupportPointNew(cpvzero, 0); + } + } +} + +static struct ClosestPoints +GJK(const struct SupportContext *ctx, cpCollisionID *id) +{ +#if DRAW_GJK || DRAW_EPA + // draw the minkowski difference origin + cpVect origin = cpvzero; + ChipmunkDebugDrawPoints(5.0, 1, &origin, RGBAColor(1,0,0,1)); + + int mdiffCount = ctx->count1*ctx->count2; + cpVect *mdiffVerts = alloca(mdiffCount*sizeof(cpVect)); + + for(int i=0; icount1; i++){ + for(int j=0; jcount2; j++){ + cpVect v1 = ShapePoint(ctx->count1, ctx->verts1, i).p; + cpVect v2 = ShapePoint(ctx->count2, ctx->verts2, j).p; + mdiffVerts[i*ctx->count2 + j] = cpvsub(v2, v1); + } + } + + cpVect *hullVerts = alloca(mdiffCount*sizeof(cpVect)); + int hullCount = cpConvexHull(mdiffCount, mdiffVerts, hullVerts, NULL, 0.0); + + ChipmunkDebugDrawPolygon(hullCount, hullVerts, RGBAColor(1, 0, 0, 1), RGBAColor(1, 0, 0, 0.25)); + ChipmunkDebugDrawPoints(2.0, mdiffCount, mdiffVerts, RGBAColor(1, 0, 0, 1)); +#endif + + struct MinkowskiPoint v0, v1; + if(*id && ENABLE_CACHING){ + v0 = MinkowskiPointNew(ShapePoint(ctx->shape1, (*id>>24)&0xFF), ShapePoint(ctx->shape2, (*id>>16)&0xFF)); + v1 = MinkowskiPointNew(ShapePoint(ctx->shape1, (*id>> 8)&0xFF), ShapePoint(ctx->shape2, (*id )&0xFF)); + } else { + cpVect axis = cpvperp(cpvsub(cpBBCenter(ctx->shape1->bb), cpBBCenter(ctx->shape2->bb))); + v0 = Support(ctx, axis); + v1 = Support(ctx, cpvneg(axis)); + } + + struct ClosestPoints points = GJKRecurse(ctx, v0, v1, 1); + *id = points.id; + return points; +} + +//MARK: Contact Clipping + +static inline void +Contact1(cpFloat dist, cpVect a, cpVect b, cpFloat refr, cpFloat incr, cpVect n, cpHashValue hash, cpContact *arr) +{ + cpFloat rsum = refr + incr; + cpFloat alpha = (rsum > 0.0f ? refr/rsum : 0.5f); + cpVect point = cpvlerp(a, b, alpha); + + cpContactInit(arr, point, n, dist - rsum, hash); +} + +static inline int +Contact2(cpVect refp, cpVect inca, cpVect incb, cpFloat refr, cpFloat incr, cpVect refn, cpVect n, cpHashValue hash, cpContact *arr) +{ + cpFloat cian = cpvcross(inca, refn); + cpFloat cibn = cpvcross(incb, refn); + cpFloat crpn = cpvcross(refp, refn); + cpFloat t = 1.0f - cpfclamp01((cibn - crpn)/(cibn - cian)); + + cpVect point = cpvlerp(inca, incb, t); + cpFloat pd = cpvdot(cpvsub(point, refp), refn); + + if(t > 0.0f && pd <= 0.0f){ + cpFloat rsum = refr + incr; + cpFloat alpha = (rsum > 0.0f ? incr*(1.0f - (rsum + pd)/rsum) : -0.5f*pd); + + cpContactInit(arr, cpvadd(point, cpvmult(refn, alpha)), n, pd, hash); + return 1; + } else { + return 0; + } +} + +static inline int +ClipContacts(const struct Edge ref, const struct Edge inc, const struct ClosestPoints points, const cpFloat nflip, cpContact *arr) +{ + cpVect inc_offs = cpvmult(inc.n, inc.r); + cpVect ref_offs = cpvmult(ref.n, ref.r); + + cpVect inca = cpvadd(inc.a.p, inc_offs); + cpVect incb = cpvadd(inc.b.p, inc_offs); + + cpVect closest_inca = cpClosetPointOnSegment(inc.a.p, ref.a.p, ref.b.p); + cpVect closest_incb = cpClosetPointOnSegment(inc.b.p, ref.a.p, ref.b.p); + + cpVect msa = cpvmult(points.n, nflip*points.d); + cpFloat cost_a = cpvdistsq(cpvsub(inc.a.p, closest_inca), msa); + cpFloat cost_b = cpvdistsq(cpvsub(inc.b.p, closest_incb), msa); + +#if DRAW_CLIP + ChipmunkDebugDrawSegment(ref.a.p, ref.b.p, RGBAColor(1, 0, 0, 1)); + ChipmunkDebugDrawSegment(inc.a.p, inc.b.p, RGBAColor(0, 1, 0, 1)); + ChipmunkDebugDrawSegment(inca, incb, RGBAColor(0, 1, 0, 1)); + + cpVect cref = cpvlerp(ref.a.p, ref.b.p, 0.5); + ChipmunkDebugDrawSegment(cref, cpvadd(cref, cpvmult(ref.n, 5.0)), RGBAColor(1, 0, 0, 1)); + + cpVect cinc = cpvlerp(inc.a.p, inc.b.p, 0.5); + ChipmunkDebugDrawSegment(cinc, cpvadd(cinc, cpvmult(inc.n, 5.0)), RGBAColor(1, 0, 0, 1)); + + ChipmunkDebugDrawPoints(5.0, 2, (cpVect[]){ref.a.p, inc.a.p}, RGBAColor(1, 1, 0, 1)); + ChipmunkDebugDrawPoints(5.0, 2, (cpVect[]){ref.b.p, inc.b.p}, RGBAColor(0, 1, 1, 1)); + + if(cost_a < cost_b){ + ChipmunkDebugDrawSegment(closest_inca, inc.a.p, RGBAColor(1, 0, 1, 1)); + } else { + ChipmunkDebugDrawSegment(closest_incb, inc.b.p, RGBAColor(1, 0, 1, 1)); + } +#endif + + cpHashValue hash_iarb = CP_HASH_PAIR(inc.a.hash, ref.b.hash); + cpHashValue hash_ibra = CP_HASH_PAIR(inc.b.hash, ref.a.hash); + + if(cost_a < cost_b){ + cpVect refp = cpvadd(ref.a.p, ref_offs); + Contact1(points.d, closest_inca, inc.a.p, ref.r, inc.r, points.n, hash_iarb, arr); + return Contact2(refp, inca, incb, ref.r, inc.r, ref.n, points.n, hash_ibra, arr + 1) + 1; + } else { + cpVect refp = cpvadd(ref.b.p, ref_offs); + Contact1(points.d, closest_incb, inc.b.p, ref.r, inc.r, points.n, hash_ibra, arr); + return Contact2(refp, incb, inca, ref.r, inc.r, ref.n, points.n, hash_iarb, arr + 1) + 1; + } +} + +static inline int +ContactPoints(const struct Edge e1, const struct Edge e2, const struct ClosestPoints points, cpContact *arr) +{ + cpFloat mindist = e1.r + e2.r; + if(points.d <= mindist){ + cpFloat pick = cpvdot(e1.n, points.n) + cpvdot(e2.n, points.n); + + if( + (pick != 0.0f && pick > 0.0f) || + // If the edges are both perfectly aligned weird things happen. + // This is *very* common at the start of a simulation. + // Pick the longest edge as the reference to break the tie. + (pick == 0.0f && (cpvdistsq(e1.a.p, e1.b.p) > cpvdistsq(e2.a.p, e2.b.p))) + ){ + return ClipContacts(e1, e2, points, 1.0f, arr); + } else { + return ClipContacts(e2, e1, points, -1.0f, arr); + } + } else { + return 0; + } +} + +//MARK: Collision Functions + +typedef int (*CollisionFunc)(const cpShape *a, const cpShape *b, cpCollisionID *id, cpContact *arr); + // Collide circle shapes. static int -circle2circle(const cpShape *shape1, const cpShape *shape2, cpContact *arr) +CircleToCircle(const cpCircleShape *c1, const cpCircleShape *c2, cpCollisionID *id, cpContact *arr) { - cpCircleShape *circ1 = (cpCircleShape *)shape1; //TODO - cpCircleShape *circ2 = (cpCircleShape *)shape2; - - return circle2circleQuery(circ1->tc, circ2->tc, circ1->r, circ2->r, arr); + return CircleToCircleQuery(c1->tc, c2->tc, c1->r, c2->r, 0, arr); } static int -circle2segment(const cpCircleShape *circleShape, const cpSegmentShape *segmentShape, cpContact *con) +CircleToSegment(const cpCircleShape *circleShape, const cpSegmentShape *segmentShape, cpCollisionID *id, cpContact *con) { cpVect seg_a = segmentShape->ta; cpVect seg_b = segmentShape->tb; @@ -68,341 +559,161 @@ circle2segment(const cpCircleShape *circleShape, const cpSegmentShape *segmentSh cpFloat closest_t = cpfclamp01(cpvdot(seg_delta, cpvsub(center, seg_a))/cpvlengthsq(seg_delta)); cpVect closest = cpvadd(seg_a, cpvmult(seg_delta, closest_t)); - if(circle2circleQuery(center, closest, circleShape->r, segmentShape->r, con)){ + if(CircleToCircleQuery(center, closest, circleShape->r, segmentShape->r, 0, con)){ cpVect n = con[0].n; // Reject endcap collisions if tangents are provided. if( - (closest_t == 0.0f && cpvdot(n, segmentShape->a_tangent) < 0.0) || - (closest_t == 1.0f && cpvdot(n, segmentShape->b_tangent) < 0.0) - ) return 0; - + (closest_t != 0.0f || cpvdot(n, cpvrotate(segmentShape->a_tangent, segmentShape->shape.body->rot)) >= 0.0) && + (closest_t != 1.0f || cpvdot(n, cpvrotate(segmentShape->b_tangent, segmentShape->shape.body->rot)) >= 0.0) + ){ + return 1; + } + } + + return 0; +} + +static int +SegmentToSegment(const cpSegmentShape *seg1, const cpSegmentShape *seg2, cpCollisionID *id, cpContact *arr) +{ + struct SupportContext context = {(cpShape *)seg1, (cpShape *)seg2, (SupportPointFunc)SegmentSupportPoint, (SupportPointFunc)SegmentSupportPoint}; + struct ClosestPoints points = GJK(&context, id); + +#if DRAW_CLOSEST +#if PRINT_LOG +// ChipmunkDemoPrintString("Distance: %.2f\n", points.d); +#endif + + ChipmunkDebugDrawDot(6.0, points.a, RGBAColor(1, 1, 1, 1)); + ChipmunkDebugDrawDot(6.0, points.b, RGBAColor(1, 1, 1, 1)); + ChipmunkDebugDrawSegment(points.a, points.b, RGBAColor(1, 1, 1, 1)); + ChipmunkDebugDrawSegment(points.a, cpvadd(points.a, cpvmult(points.n, 10.0)), RGBAColor(1, 0, 0, 1)); +#endif + + cpVect n = points.n; + cpVect rot1 = seg1->shape.body->rot; + cpVect rot2 = seg2->shape.body->rot; + if( + points.d <= (seg1->r + seg2->r) && + ( + (!cpveql(points.a, seg1->ta) || cpvdot(n, cpvrotate(seg1->a_tangent, rot1)) <= 0.0) && + (!cpveql(points.a, seg1->tb) || cpvdot(n, cpvrotate(seg1->b_tangent, rot1)) <= 0.0) && + (!cpveql(points.b, seg2->ta) || cpvdot(n, cpvrotate(seg2->a_tangent, rot2)) >= 0.0) && + (!cpveql(points.b, seg2->tb) || cpvdot(n, cpvrotate(seg2->b_tangent, rot2)) >= 0.0) + ) + ){ + return ContactPoints(SupportEdgeForSegment(seg1, n), SupportEdgeForSegment(seg2, cpvneg(n)), points, arr); + } else { + return 0; + } +} + +static int +PolyToPoly(const cpPolyShape *poly1, const cpPolyShape *poly2, cpCollisionID *id, cpContact *arr) +{ + struct SupportContext context = {(cpShape *)poly1, (cpShape *)poly2, (SupportPointFunc)PolySupportPoint, (SupportPointFunc)PolySupportPoint}; + struct ClosestPoints points = GJK(&context, id); + +#if DRAW_CLOSEST +#if PRINT_LOG +// ChipmunkDemoPrintString("Distance: %.2f\n", points.d); +#endif + + ChipmunkDebugDrawDot(3.0, points.a, RGBAColor(1, 1, 1, 1)); + ChipmunkDebugDrawDot(3.0, points.b, RGBAColor(1, 1, 1, 1)); + ChipmunkDebugDrawSegment(points.a, points.b, RGBAColor(1, 1, 1, 1)); + ChipmunkDebugDrawSegment(points.a, cpvadd(points.a, cpvmult(points.n, 10.0)), RGBAColor(1, 0, 0, 1)); +#endif + + if(points.d - poly1->r - poly2->r <= 0.0){ + return ContactPoints(SupportEdgeForPoly(poly1, points.n), SupportEdgeForPoly(poly2, cpvneg(points.n)), points, arr); + } else { + return 0; + } +} + +static int +SegmentToPoly(const cpSegmentShape *seg, const cpPolyShape *poly, cpCollisionID *id, cpContact *arr) +{ + struct SupportContext context = {(cpShape *)seg, (cpShape *)poly, (SupportPointFunc)SegmentSupportPoint, (SupportPointFunc)PolySupportPoint}; + struct ClosestPoints points = GJK(&context, id); + +#if DRAW_CLOSEST +#if PRINT_LOG +// ChipmunkDemoPrintString("Distance: %.2f\n", points.d); +#endif + + ChipmunkDebugDrawDot(3.0, points.a, RGBAColor(1, 1, 1, 1)); + ChipmunkDebugDrawDot(3.0, points.b, RGBAColor(1, 1, 1, 1)); + ChipmunkDebugDrawSegment(points.a, points.b, RGBAColor(1, 1, 1, 1)); + ChipmunkDebugDrawSegment(points.a, cpvadd(points.a, cpvmult(points.n, 10.0)), RGBAColor(1, 0, 0, 1)); +#endif + + // Reject endcap collisions if tangents are provided. + cpVect n = points.n; + cpVect rot = seg->shape.body->rot; + if( + points.d - seg->r - poly->r <= 0.0 && + ( + (!cpveql(points.a, seg->ta) || cpvdot(n, cpvrotate(seg->a_tangent, rot)) <= 0.0) && + (!cpveql(points.a, seg->tb) || cpvdot(n, cpvrotate(seg->b_tangent, rot)) <= 0.0) + ) + ){ + return ContactPoints(SupportEdgeForSegment(seg, n), SupportEdgeForPoly(poly, cpvneg(n)), points, arr); + } else { + return 0; + } +} + +// This one is less gross, but still gross. +// TODO: Comment me! +static int +CircleToPoly(const cpCircleShape *circle, const cpPolyShape *poly, cpCollisionID *id, cpContact *con) +{ + struct SupportContext context = {(cpShape *)circle, (cpShape *)poly, (SupportPointFunc)CircleSupportPoint, (SupportPointFunc)PolySupportPoint}; + struct ClosestPoints points = GJK(&context, id); + +#if DRAW_CLOSEST + ChipmunkDebugDrawDot(3.0, points.a, RGBAColor(1, 1, 1, 1)); + ChipmunkDebugDrawDot(3.0, points.b, RGBAColor(1, 1, 1, 1)); + ChipmunkDebugDrawSegment(points.a, points.b, RGBAColor(1, 1, 1, 1)); + ChipmunkDebugDrawSegment(points.a, cpvadd(points.a, cpvmult(points.n, 10.0)), RGBAColor(1, 0, 0, 1)); +#endif + + cpFloat mindist = circle->r + poly->r; + if(points.d - mindist <= 0.0){ + cpVect p = cpvlerp(points.a, points.b, circle->r/(mindist)); + cpContactInit(con, p, points.n, points.d - mindist, 0); return 1; } else { return 0; } } -// Helper function for working with contact buffers -// This used to malloc/realloc memory on the fly but was repurposed. -static cpContact * -nextContactPoint(cpContact *arr, int *numPtr) -{ - int index = *numPtr; - - if(index < CP_MAX_CONTACTS_PER_ARBITER){ - (*numPtr) = index + 1; - return &arr[index]; - } else { - return &arr[CP_MAX_CONTACTS_PER_ARBITER - 1]; - } -} - -// Find the minimum separating axis for the give poly and axis list. -static inline int -findMSA(const cpPolyShape *poly, const cpSplittingPlane *planes, const int num, cpFloat *min_out) -{ - int min_index = 0; - cpFloat min = cpPolyShapeValueOnAxis(poly, planes->n, planes->d); - if(min > 0.0f) return -1; - - for(int i=1; i 0.0f) { - return -1; - } else if(dist > min){ - min = dist; - min_index = i; - } - } - - (*min_out) = min; - return min_index; -} - -// Add contacts for probably penetrating vertexes. -// This handles the degenerate case where an overlap was detected, but no vertexes fall inside -// the opposing polygon. (like a star of david) -static inline int -findVertsFallback(cpContact *arr, const cpPolyShape *poly1, const cpPolyShape *poly2, const cpVect n, const cpFloat dist) -{ - int num = 0; - - for(int i=0; inumVerts; i++){ - cpVect v = poly1->tVerts[i]; - if(cpPolyShapeContainsVertPartial(poly2, v, cpvneg(n))) - cpContactInit(nextContactPoint(arr, &num), v, n, dist, CP_HASH_PAIR(poly1->shape.hashid, i)); - } - - for(int i=0; inumVerts; i++){ - cpVect v = poly2->tVerts[i]; - if(cpPolyShapeContainsVertPartial(poly1, v, n)) - cpContactInit(nextContactPoint(arr, &num), v, n, dist, CP_HASH_PAIR(poly2->shape.hashid, i)); - } - - return num; -} - -// Add contacts for penetrating vertexes. -static inline int -findVerts(cpContact *arr, const cpPolyShape *poly1, const cpPolyShape *poly2, const cpVect n, const cpFloat dist) -{ - int num = 0; - - for(int i=0; inumVerts; i++){ - cpVect v = poly1->tVerts[i]; - if(cpPolyShapeContainsVert(poly2, v)) - cpContactInit(nextContactPoint(arr, &num), v, n, dist, CP_HASH_PAIR(poly1->shape.hashid, i)); - } - - for(int i=0; inumVerts; i++){ - cpVect v = poly2->tVerts[i]; - if(cpPolyShapeContainsVert(poly1, v)) - cpContactInit(nextContactPoint(arr, &num), v, n, dist, CP_HASH_PAIR(poly2->shape.hashid, i)); - } - - return (num ? num : findVertsFallback(arr, poly1, poly2, n, dist)); -} - -// Collide poly shapes together. -static int -poly2poly(const cpShape *shape1, const cpShape *shape2, cpContact *arr) -{ - cpPolyShape *poly1 = (cpPolyShape *)shape1; - cpPolyShape *poly2 = (cpPolyShape *)shape2; - - cpFloat min1; - int mini1 = findMSA(poly2, poly1->tPlanes, poly1->numVerts, &min1); - if(mini1 == -1) return 0; - - cpFloat min2; - int mini2 = findMSA(poly1, poly2->tPlanes, poly2->numVerts, &min2); - if(mini2 == -1) return 0; - - // There is overlap, find the penetrating verts - if(min1 > min2) - return findVerts(arr, poly1, poly2, poly1->tPlanes[mini1].n, min1); - else - return findVerts(arr, poly1, poly2, cpvneg(poly2->tPlanes[mini2].n), min2); -} - -// Like cpPolyValueOnAxis(), but for segments. -static inline cpFloat -segValueOnAxis(const cpSegmentShape *seg, const cpVect n, const cpFloat d) -{ - cpFloat a = cpvdot(n, seg->ta) - seg->r; - cpFloat b = cpvdot(n, seg->tb) - seg->r; - return cpfmin(a, b) - d; -} - -// Identify vertexes that have penetrated the segment. -static inline void -findPointsBehindSeg(cpContact *arr, int *num, const cpSegmentShape *seg, const cpPolyShape *poly, const cpFloat pDist, const cpFloat coef) -{ - cpFloat dta = cpvcross(seg->tn, seg->ta); - cpFloat dtb = cpvcross(seg->tn, seg->tb); - cpVect n = cpvmult(seg->tn, coef); - - for(int i=0; inumVerts; i++){ - cpVect v = poly->tVerts[i]; - if(cpvdot(v, n) < cpvdot(seg->tn, seg->ta)*coef + seg->r){ - cpFloat dt = cpvcross(seg->tn, v); - if(dta >= dt && dt >= dtb){ - cpContactInit(nextContactPoint(arr, num), v, n, pDist, CP_HASH_PAIR(poly->shape.hashid, i)); - } - } - } -} - -// This one is complicated and gross. Just don't go there... -// TODO: Comment me! -static int -seg2poly(const cpShape *shape1, const cpShape *shape2, cpContact *arr) -{ - cpSegmentShape *seg = (cpSegmentShape *)shape1; - cpPolyShape *poly = (cpPolyShape *)shape2; - cpSplittingPlane *planes = poly->tPlanes; - - cpFloat segD = cpvdot(seg->tn, seg->ta); - cpFloat minNorm = cpPolyShapeValueOnAxis(poly, seg->tn, segD) - seg->r; - cpFloat minNeg = cpPolyShapeValueOnAxis(poly, cpvneg(seg->tn), -segD) - seg->r; - if(minNeg > 0.0f || minNorm > 0.0f) return 0; - - int mini = 0; - cpFloat poly_min = segValueOnAxis(seg, planes->n, planes->d); - if(poly_min > 0.0f) return 0; - for(int i=0; inumVerts; i++){ - cpFloat dist = segValueOnAxis(seg, planes[i].n, planes[i].d); - if(dist > 0.0f){ - return 0; - } else if(dist > poly_min){ - poly_min = dist; - mini = i; - } - } - - int num = 0; - - cpVect poly_n = cpvneg(planes[mini].n); - - cpVect va = cpvadd(seg->ta, cpvmult(poly_n, seg->r)); - cpVect vb = cpvadd(seg->tb, cpvmult(poly_n, seg->r)); - if(cpPolyShapeContainsVert(poly, va)) - cpContactInit(nextContactPoint(arr, &num), va, poly_n, poly_min, CP_HASH_PAIR(seg->shape.hashid, 0)); - if(cpPolyShapeContainsVert(poly, vb)) - cpContactInit(nextContactPoint(arr, &num), vb, poly_n, poly_min, CP_HASH_PAIR(seg->shape.hashid, 1)); - - // Floating point precision problems here. - // This will have to do for now. -// poly_min -= cp_collision_slop; // TODO is this needed anymore? - - if(minNorm >= poly_min || minNeg >= poly_min) { - if(minNorm > minNeg) - findPointsBehindSeg(arr, &num, seg, poly, minNorm, 1.0f); - else - findPointsBehindSeg(arr, &num, seg, poly, minNeg, -1.0f); - } - - // If no other collision points are found, try colliding endpoints. - if(num == 0){ - cpVect poly_a = poly->tVerts[mini]; - cpVect poly_b = poly->tVerts[(mini + 1)%poly->numVerts]; - - if(circle2circleQuery(seg->ta, poly_a, seg->r, 0.0f, arr)) return 1; - if(circle2circleQuery(seg->tb, poly_a, seg->r, 0.0f, arr)) return 1; - if(circle2circleQuery(seg->ta, poly_b, seg->r, 0.0f, arr)) return 1; - if(circle2circleQuery(seg->tb, poly_b, seg->r, 0.0f, arr)) return 1; - } - - return num; -} - -// This one is less gross, but still gross. -// TODO: Comment me! -static int -circle2poly(const cpShape *shape1, const cpShape *shape2, cpContact *con) -{ - cpCircleShape *circ = (cpCircleShape *)shape1; - cpPolyShape *poly = (cpPolyShape *)shape2; - cpSplittingPlane *planes = poly->tPlanes; - - int mini = 0; - cpFloat min = cpSplittingPlaneCompare(planes[0], circ->tc) - circ->r; - for(int i=0; inumVerts; i++){ - cpFloat dist = cpSplittingPlaneCompare(planes[i], circ->tc) - circ->r; - if(dist > 0.0f){ - return 0; - } else if(dist > min) { - min = dist; - mini = i; - } - } - - cpVect n = planes[mini].n; - cpVect a = poly->tVerts[mini]; - cpVect b = poly->tVerts[(mini + 1)%poly->numVerts]; - cpFloat dta = cpvcross(n, a); - cpFloat dtb = cpvcross(n, b); - cpFloat dt = cpvcross(n, circ->tc); - - if(dt < dtb){ - return circle2circleQuery(circ->tc, b, circ->r, 0.0f, con); - } else if(dt < dta) { - cpContactInit( - con, - cpvsub(circ->tc, cpvmult(n, circ->r + min/2.0f)), - cpvneg(n), - min, - 0 - ); - - return 1; - } else { - return circle2circleQuery(circ->tc, a, circ->r, 0.0f, con); - } -} - -// Submitted by LegoCyclon -static int -seg2seg(const cpShape* shape1, const cpShape* shape2, cpContact* con) -{ - cpSegmentShape* seg1 = (cpSegmentShape *)shape1; - cpSegmentShape* seg2 = (cpSegmentShape *)shape2; - - cpVect v1 = cpvsub(seg1->tb, seg1->ta); - cpVect v2 = cpvsub(seg2->tb, seg2->ta); - cpFloat v1lsq = cpvlengthsq(v1); - cpFloat v2lsq = cpvlengthsq(v2); - // project seg2 onto seg1 - cpVect p1a = cpvproject(cpvsub(seg2->ta, seg1->ta), v1); - cpVect p1b = cpvproject(cpvsub(seg2->tb, seg1->ta), v1); - // project seg1 onto seg2 - cpVect p2a = cpvproject(cpvsub(seg1->ta, seg2->ta), v2); - cpVect p2b = cpvproject(cpvsub(seg1->tb, seg2->ta), v2); - - // clamp projections to segment endcaps - if (cpvdot(p1a, v1) < 0.0f) - p1a = cpvzero; - else if (cpvdot(p1a, v1) > 0.0f && cpvlengthsq(p1a) > v1lsq) - p1a = v1; - if (cpvdot(p1b, v1) < 0.0f) - p1b = cpvzero; - else if (cpvdot(p1b, v1) > 0.0f && cpvlengthsq(p1b) > v1lsq) - p1b = v1; - if (cpvdot(p2a, v2) < 0.0f) - p2a = cpvzero; - else if (cpvdot(p2a, v2) > 0.0f && cpvlengthsq(p2a) > v2lsq) - p2a = v2; - if (cpvdot(p2b, v2) < 0.0f) - p2b = cpvzero; - else if (cpvdot(p2b, v2) > 0.0f && cpvlengthsq(p2b) > v2lsq) - p2b = v2; - - p1a = cpvadd(p1a, seg1->ta); - p1b = cpvadd(p1b, seg1->ta); - p2a = cpvadd(p2a, seg2->ta); - p2b = cpvadd(p2b, seg2->ta); - - int num = 0; - - if (!circle2circleQuery(p1a, p2a, seg1->r, seg2->r, nextContactPoint(con, &num))) - --num; - - if (!circle2circleQuery(p1b, p2b, seg1->r, seg2->r, nextContactPoint(con, &num))) - --num; - - if (!circle2circleQuery(p1a, p2b, seg1->r, seg2->r, nextContactPoint(con, &num))) - --num; - - if (!circle2circleQuery(p1b, p2a, seg1->r, seg2->r, nextContactPoint(con, &num))) - --num; - - return num; -} - -static const collisionFunc builtinCollisionFuncs[9] = { - circle2circle, +static const CollisionFunc builtinCollisionFuncs[9] = { + (CollisionFunc)CircleToCircle, NULL, NULL, - (collisionFunc)circle2segment, + (CollisionFunc)CircleToSegment, NULL, NULL, - circle2poly, - seg2poly, - poly2poly, + (CollisionFunc)CircleToPoly, + (CollisionFunc)SegmentToPoly, + (CollisionFunc)PolyToPoly, }; -static const collisionFunc *colfuncs = builtinCollisionFuncs; +static const CollisionFunc *colfuncs = builtinCollisionFuncs; -static const collisionFunc segmentCollisions[9] = { - circle2circle, +static const CollisionFunc segmentCollisions[9] = { + (CollisionFunc)CircleToCircle, NULL, NULL, - (collisionFunc)circle2segment, - seg2seg, + (CollisionFunc)CircleToSegment, + (CollisionFunc)SegmentToSegment, NULL, - circle2poly, - seg2poly, - poly2poly, + (CollisionFunc)CircleToPoly, + (CollisionFunc)SegmentToPoly, + (CollisionFunc)PolyToPoly, }; void @@ -412,11 +723,15 @@ cpEnableSegmentToSegmentCollisions(void) } int -cpCollideShapes(const cpShape *a, const cpShape *b, cpContact *arr) +cpCollideShapes(const cpShape *a, const cpShape *b, cpCollisionID *id, cpContact *arr) { // Their shape types must be in order. - cpAssertSoft(a->klass->type <= b->klass->type, "Collision shapes passed to cpCollideShapes() are not sorted."); + cpAssertSoft(a->klass->type <= b->klass->type, "Internal Error: Collision shapes passed to cpCollideShapes() are not sorted."); - collisionFunc cfunc = colfuncs[a->klass->type + b->klass->type*CP_NUM_SHAPES]; - return (cfunc) ? cfunc(a, b, arr) : 0; + CollisionFunc cfunc = colfuncs[a->klass->type + b->klass->type*CP_NUM_SHAPES]; + + int numContacts = (cfunc? cfunc(a, b, id, arr) : 0); + cpAssertSoft(numContacts <= CP_MAX_CONTACTS_PER_ARBITER, "Internal error: Too many contact points returned."); + + return numContacts; } diff --git a/external/chipmunk/src/cpPolyShape.c b/external/chipmunk/src/cpPolyShape.c index 8250cbd514..12f2168c9a 100644 --- a/external/chipmunk/src/cpPolyShape.c +++ b/external/chipmunk/src/cpPolyShape.c @@ -47,7 +47,8 @@ cpPolyShapeTransformVerts(cpPolyShape *poly, cpVect p, cpVect rot) t = cpfmax(t, v.y); } - return cpBBNew(l, b, r, t); + cpFloat radius = poly->r; + return cpBBNew(l - radius, b - radius, r + radius, t + radius); } static void @@ -84,10 +85,12 @@ cpPolyShapeNearestPointQuery(cpPolyShape *poly, cpVect p, cpNearestPointQueryInf int count = poly->numVerts; cpSplittingPlane *planes = poly->tPlanes; cpVect *verts = poly->tVerts; + cpFloat r = poly->r; cpVect v0 = verts[count - 1]; cpFloat minDist = INFINITY; cpVect closestPoint = cpvzero; + cpVect closestNormal = cpvzero; cpBool outside = cpFalse; for(int i=0; ishape = (cpShape *)poly; - info->p = closestPoint; // TODO div/0 - info->d = (outside ? minDist : -minDist); + info->p = cpvadd(closestPoint, cpvmult(g, r)); + info->d = dist - r; + + // Use the normal of the closest segment if the distance is small. + info->g = (minDist > MAGIC_EPSILON ? g : closestNormal); } static void @@ -116,20 +126,22 @@ cpPolyShapeSegmentQuery(cpPolyShape *poly, cpVect a, cpVect b, cpSegmentQueryInf cpSplittingPlane *axes = poly->tPlanes; cpVect *verts = poly->tVerts; int numVerts = poly->numVerts; + cpFloat r = poly->r; for(int i=0; i an) continue; + cpFloat d = axes[i].d + r - an; + if(d > 0.0f) continue; cpFloat bn = cpvdot(b, n); - cpFloat t = (axes[i].d - an)/(bn - an); + cpFloat t = d/(bn - an); if(t < 0.0f || 1.0f < t) continue; cpVect point = cpvlerp(a, b, t); cpFloat dt = -cpvcross(n, point); - cpFloat dtMin = -cpvcross(n, verts[i]); - cpFloat dtMax = -cpvcross(n, verts[(i+1)%numVerts]); + cpFloat dtMin = -cpvcross(n, verts[(i - 1 + numVerts)%numVerts]); + cpFloat dtMax = -cpvcross(n, verts[i]); if(dtMin <= dt && dt <= dtMax){ info->shape = (cpShape *)poly; @@ -137,6 +149,15 @@ cpPolyShapeSegmentQuery(cpPolyShape *poly, cpVect a, cpVect b, cpSegmentQueryInf info->n = n; } } + + // Also check against the beveled vertexes. + if(r > 0.0f){ + for(int i=0; ishape, verts[i], r, a, b, &circle_info); + if(circle_info.t < info->t) (*info) = circle_info; + } + } } static const cpShapeClass polyClass = { @@ -164,14 +185,14 @@ cpPolyValidate(const cpVect *verts, const int numVerts) } int -cpPolyShapeGetNumVerts(cpShape *shape) +cpPolyShapeGetNumVerts(const cpShape *shape) { cpAssertHard(shape->klass == &polyClass, "Shape is not a poly shape."); return ((cpPolyShape *)shape)->numVerts; } cpVect -cpPolyShapeGetVert(cpShape *shape, int idx) +cpPolyShapeGetVert(const cpShape *shape, int idx) { cpAssertHard(shape->klass == &polyClass, "Shape is not a poly shape."); cpAssertHard(0 <= idx && idx < cpPolyShapeGetNumVerts(shape), "Index out of range."); @@ -179,6 +200,13 @@ cpPolyShapeGetVert(cpShape *shape, int idx) return ((cpPolyShape *)shape)->verts[idx]; } +cpFloat +cpPolyShapeGetRadius(const cpShape *shape) +{ + cpAssertHard(shape->klass == &polyClass, "Shape is not a poly shape."); + return ((cpPolyShape *)shape)->r; +} + static void setUpVerts(cpPolyShape *poly, int numVerts, const cpVect *verts, cpVect offset) @@ -202,21 +230,39 @@ setUpVerts(cpPolyShape *poly, int numVerts, const cpVect *verts, cpVect offset) poly->planes[i].d = cpvdot(n, a); } + // TODO: Why did I add this? It duplicates work from above. + for(int i=0; iplanes[i] = cpSplittingPlaneNew(poly->verts[(i - 1 + numVerts)%numVerts], poly->verts[i]); + } } cpPolyShape * cpPolyShapeInit(cpPolyShape *poly, cpBody *body, int numVerts, const cpVect *verts, cpVect offset) +{ + return cpPolyShapeInit2(poly, body, numVerts, verts, offset, 0.0f); +} + +cpPolyShape * +cpPolyShapeInit2(cpPolyShape *poly, cpBody *body, int numVerts, const cpVect *verts, cpVect offset, cpFloat radius) { setUpVerts(poly, numVerts, verts, offset); cpShapeInit((cpShape *)poly, &polyClass, body); + poly->r = radius; return poly; } + cpShape * -cpPolyShapeNew(cpBody *body, int numVerts, cpVect *verts, cpVect offset) +cpPolyShapeNew(cpBody *body, int numVerts, const cpVect *verts, cpVect offset) { - return (cpShape *)cpPolyShapeInit(cpPolyShapeAlloc(), body, numVerts, verts, offset); + return cpPolyShapeNew2(body, numVerts, verts, offset, 0.0f); +} + +cpShape * +cpPolyShapeNew2(cpBody *body, int numVerts, const cpVect *verts, cpVect offset, cpFloat radius) +{ + return (cpShape *)cpPolyShapeInit2(cpPolyShapeAlloc(), body, numVerts, verts, offset, radius); } cpPolyShape * @@ -230,6 +276,12 @@ cpBoxShapeInit(cpPolyShape *poly, cpBody *body, cpFloat width, cpFloat height) cpPolyShape * cpBoxShapeInit2(cpPolyShape *poly, cpBody *body, cpBB box) +{ + return cpBoxShapeInit3(poly, body, box, 0.0f); +} + +cpPolyShape * +cpBoxShapeInit3(cpPolyShape *poly, cpBody *body, cpBB box, cpFloat radius) { cpVect verts[] = { cpv(box.l, box.b), @@ -238,7 +290,7 @@ cpBoxShapeInit2(cpPolyShape *poly, cpBody *body, cpBB box) cpv(box.r, box.b), }; - return cpPolyShapeInit(poly, body, 4, verts, cpvzero); + return cpPolyShapeInit2(poly, body, 4, verts, cpvzero, radius); } cpShape * @@ -253,6 +305,12 @@ cpBoxShapeNew2(cpBody *body, cpBB box) return (cpShape *)cpBoxShapeInit2(cpPolyShapeAlloc(), body, box); } +cpShape * +cpBoxShapeNew3(cpBody *body, cpBB box, cpFloat radius) +{ + return (cpShape *)cpBoxShapeInit3(cpPolyShapeAlloc(), body, box, radius); +} + // Unsafe API (chipmunk_unsafe.h) void @@ -262,3 +320,10 @@ cpPolyShapeSetVerts(cpShape *shape, int numVerts, cpVect *verts, cpVect offset) cpPolyShapeDestroy((cpPolyShape *)shape); setUpVerts((cpPolyShape *)shape, numVerts, verts, offset); } + +void +cpPolyShapeSetRadius(cpShape *shape, cpFloat radius) +{ + cpAssertHard(shape->klass == &polyClass, "Shape is not a poly shape."); + ((cpPolyShape *)shape)->r = radius; +} diff --git a/external/chipmunk/src/cpShape.c b/external/chipmunk/src/cpShape.c index a07cc5da75..56f00b066a 100644 --- a/external/chipmunk/src/cpShape.c +++ b/external/chipmunk/src/cpShape.c @@ -103,7 +103,7 @@ cpShapeUpdate(cpShape *shape, cpVect pos, cpVect rot) cpBool cpShapePointQuery(cpShape *shape, cpVect p){ - cpNearestPointQueryInfo info = {NULL, cpvzero, INFINITY}; + cpNearestPointQueryInfo info = {NULL, cpvzero, INFINITY, cpvzero}; cpShapeNearestPointQuery(shape, p, &info); return (info.d < 0.0f); @@ -112,7 +112,7 @@ cpShapePointQuery(cpShape *shape, cpVect p){ cpFloat cpShapeNearestPointQuery(cpShape *shape, cpVect p, cpNearestPointQueryInfo *info) { - cpNearestPointQueryInfo blank = {NULL, cpvzero, INFINITY}; + cpNearestPointQueryInfo blank = {NULL, cpvzero, INFINITY, cpvzero}; if(info){ (*info) = blank; } else { @@ -126,7 +126,7 @@ cpShapeNearestPointQuery(cpShape *shape, cpVect p, cpNearestPointQueryInfo *info cpBool cpShapeSegmentQuery(cpShape *shape, cpVect a, cpVect b, cpSegmentQueryInfo *info){ - cpSegmentQueryInfo blank = {NULL, 0.0f, cpvzero}; + cpSegmentQueryInfo blank = {NULL, 1.0f, cpvzero}; if(info){ (*info) = blank; } else { @@ -169,34 +169,15 @@ cpCicleShapeNearestPointQuery(cpCircleShape *circle, cpVect p, cpNearestPointQue info->shape = (cpShape *)circle; info->p = cpvadd(circle->tc, cpvmult(delta, r/d)); // TODO div/0 info->d = d - r; -} - -static void -circleSegmentQuery(cpShape *shape, cpVect center, cpFloat r, cpVect a, cpVect b, cpSegmentQueryInfo *info) -{ - cpVect da = cpvsub(a, center); - cpVect db = cpvsub(b, center); - cpFloat qa = cpvdot(da, da) - 2.0f*cpvdot(da, db) + cpvdot(db, db); - cpFloat qb = -2.0f*cpvdot(da, da) + 2.0f*cpvdot(da, db); - cpFloat qc = cpvdot(da, da) - r*r; - - cpFloat det = qb*qb - 4.0f*qa*qc; - - if(det >= 0.0f){ - cpFloat t = (-qb - cpfsqrt(det))/(2.0f*qa); - if(0.0f<= t && t <= 1.0f){ - info->shape = shape; - info->t = t; - info->n = cpvnormalize(cpvlerp(da, db, t)); - } - } + // Use up for the gradient if the distance is very small. + info->g = (d > MAGIC_EPSILON ? cpvmult(delta, 1.0f/d) : cpv(0.0f, 1.0f)); } static void cpCircleShapeSegmentQuery(cpCircleShape *circle, cpVect a, cpVect b, cpSegmentQueryInfo *info) { - circleSegmentQuery((cpShape *)circle, circle->tc, circle->r, a, b, info); + CircleSegmentQuery((cpShape *)circle, circle->tc, circle->r, a, b, info); } static const cpShapeClass cpCircleShapeClass = { @@ -270,10 +251,14 @@ cpSegmentShapeNearestPointQuery(cpSegmentShape *seg, cpVect p, cpNearestPointQue cpVect delta = cpvsub(p, closest); cpFloat d = cpvlength(delta); cpFloat r = seg->r; + cpVect g = cpvmult(delta, 1.0f/d); info->shape = (cpShape *)seg; - info->p = (d ? cpvadd(closest, cpvmult(delta, r/d)) : closest); + info->p = (d ? cpvadd(closest, cpvmult(g, r)) : closest); info->d = d - r; + + // Use the segment's normal if the distance is very small. + info->g = (d > MAGIC_EPSILON ? g : seg->n); } static void @@ -304,8 +289,8 @@ cpSegmentShapeSegmentQuery(cpSegmentShape *seg, cpVect a, cpVect b, cpSegmentQue } else if(r != 0.0f){ cpSegmentQueryInfo info1 = {NULL, 1.0f, cpvzero}; cpSegmentQueryInfo info2 = {NULL, 1.0f, cpvzero}; - circleSegmentQuery((cpShape *)seg, seg->ta, seg->r, a, b, &info1); - circleSegmentQuery((cpShape *)seg, seg->tb, seg->r, a, b, &info2); + CircleSegmentQuery((cpShape *)seg, seg->ta, seg->r, a, b, &info1); + CircleSegmentQuery((cpShape *)seg, seg->tb, seg->r, a, b, &info2); if(info1.t < info2.t){ (*info) = info1; diff --git a/external/chipmunk/src/cpSpaceHash.c b/external/chipmunk/src/cpSpaceHash.c index 7479e9d3b1..9e20715e69 100644 --- a/external/chipmunk/src/cpSpaceHash.c +++ b/external/chipmunk/src/cpSpaceHash.c @@ -362,7 +362,7 @@ query_helper(cpSpaceHash *hash, cpSpaceHashBin **bin_ptr, void *obj, cpSpatialIn if(hand->stamp == hash->stamp || obj == other){ continue; } else if(other){ - func(obj, other, data); + func(obj, other, 0, data); hand->stamp = hash->stamp; } else { // The object for this handle has been removed diff --git a/external/chipmunk/src/cpSpaceQuery.c b/external/chipmunk/src/cpSpaceQuery.c index bf977dc28a..944bc4cec1 100644 --- a/external/chipmunk/src/cpSpaceQuery.c +++ b/external/chipmunk/src/cpSpaceQuery.c @@ -31,8 +31,8 @@ struct PointQueryContext { void *data; }; -static void -PointQuery(struct PointQueryContext *context, cpShape *shape, void *data) +static cpCollisionID +PointQuery(struct PointQueryContext *context, cpShape *shape, cpCollisionID id, void *data) { if( !(shape->group && context->group == shape->group) && (context->layers&shape->layers) && @@ -40,6 +40,8 @@ PointQuery(struct PointQueryContext *context, cpShape *shape, void *data) ){ context->func(shape, context->data); } + + return id; } void @@ -79,8 +81,8 @@ struct NearestPointQueryContext { cpSpaceNearestPointQueryFunc func; }; -static void -NearestPointQuery(struct NearestPointQueryContext *context, cpShape *shape, void *data) +static cpCollisionID +NearestPointQuery(struct NearestPointQueryContext *context, cpShape *shape, cpCollisionID id, void *data) { if( !(shape->group && context->group == shape->group) && (context->layers&shape->layers) @@ -90,6 +92,8 @@ NearestPointQuery(struct NearestPointQueryContext *context, cpShape *shape, void if(info.shape && info.d < context->maxDistance) context->func(shape, info.d, info.p, data); } + + return id; } void @@ -104,8 +108,8 @@ cpSpaceNearestPointQuery(cpSpace *space, cpVect point, cpFloat maxDistance, cpLa } cpSpaceUnlock(space, cpTrue); } -static void -NearestPointQueryNearest(struct NearestPointQueryContext *context, cpShape *shape, cpNearestPointQueryInfo *out) +static cpCollisionID +NearestPointQueryNearest(struct NearestPointQueryContext *context, cpShape *shape, cpCollisionID id, cpNearestPointQueryInfo *out) { if( !(shape->group && context->group == shape->group) && (context->layers&shape->layers) && !shape->sensor @@ -115,12 +119,14 @@ NearestPointQueryNearest(struct NearestPointQueryContext *context, cpShape *shap if(info.d < out->d) (*out) = info; } + + return id; } cpShape * cpSpaceNearestPointQueryNearest(cpSpace *space, cpVect point, cpFloat maxDistance, cpLayers layers, cpGroup group, cpNearestPointQueryInfo *out) { - cpNearestPointQueryInfo info = {NULL, cpvzero, maxDistance}; + cpNearestPointQueryInfo info = {NULL, cpvzero, maxDistance, cpvzero}; if(out){ (*out) = info; } else { @@ -228,8 +234,8 @@ struct BBQueryContext { cpSpaceBBQueryFunc func; }; -static void -BBQuery(struct BBQueryContext *context, cpShape *shape, void *data) +static cpCollisionID +BBQuery(struct BBQueryContext *context, cpShape *shape, cpCollisionID id, void *data) { if( !(shape->group && context->group == shape->group) && (context->layers&shape->layers) && @@ -237,6 +243,8 @@ BBQuery(struct BBQueryContext *context, cpShape *shape, void *data) ){ context->func(shape, data); } + + return id; } void @@ -259,24 +267,24 @@ struct ShapeQueryContext { }; // Callback from the spatial hash. -static void -ShapeQuery(cpShape *a, cpShape *b, struct ShapeQueryContext *context) +static cpCollisionID +ShapeQuery(cpShape *a, cpShape *b, cpCollisionID id, struct ShapeQueryContext *context) { // Reject any of the simple cases if( (a->group && a->group == b->group) || !(a->layers & b->layers) || a == b - ) return; + ) return id; cpContact contacts[CP_MAX_CONTACTS_PER_ARBITER]; int numContacts = 0; // Shape 'a' should have the lower shape type. (required by cpCollideShapes() ) if(a->klass->type <= b->klass->type){ - numContacts = cpCollideShapes(a, b, contacts); + numContacts = cpCollideShapes(a, b, &id, contacts); } else { - numContacts = cpCollideShapes(b, a, contacts); + numContacts = cpCollideShapes(b, a, &id, contacts); for(int i=0; ifunc(b, &set, context->data); } } + + return id; } cpBool diff --git a/external/chipmunk/src/cpSpaceStep.c b/external/chipmunk/src/cpSpaceStep.c index f80b8d0e6a..f6f6d050f0 100644 --- a/external/chipmunk/src/cpSpaceStep.c +++ b/external/chipmunk/src/cpSpaceStep.c @@ -219,19 +219,20 @@ queryReject(cpShape *a, cpShape *b) } // Callback from the spatial hash. -void -cpSpaceCollideShapes(cpShape *a, cpShape *b, cpSpace *space) +cpCollisionID +cpSpaceCollideShapes(cpShape *a, cpShape *b, cpCollisionID id, cpSpace *space) { // Reject any of the simple cases - if(queryReject(a,b)) return; + if(queryReject(a,b)) return id; cpCollisionHandler *handler = cpSpaceLookupHandler(space, a->collision_type, b->collision_type); cpBool sensor = a->sensor || b->sensor; - if(sensor && handler == &cpDefaultCollisionHandler) return; + if(sensor && handler == &cpDefaultCollisionHandler) return id; // Shape 'a' should have the lower shape type. (required by cpCollideShapes() ) - if(a->klass->type > b->klass->type){ + // TODO remove me: a < b comparison is for debugging collisions + if(a->klass->type > b->klass->type || (a->klass->type == b->klass->type && a < b)){ cpShape *temp = a; a = b; b = temp; @@ -239,8 +240,8 @@ cpSpaceCollideShapes(cpShape *a, cpShape *b, cpSpace *space) // Narrow-phase collision detection. cpContact *contacts = cpContactBufferGetArray(space); - int numContacts = cpCollideShapes(a, b, contacts); - if(!numContacts) return; // Shapes are not colliding. + int numContacts = cpCollideShapes(a, b, &id, contacts); + if(!numContacts) return id; // Shapes are not colliding. cpSpacePushContacts(space, numContacts); // Get an arbiter from space->arbiterSet for the two shapes. @@ -277,6 +278,7 @@ cpSpaceCollideShapes(cpShape *a, cpShape *b, cpSpace *space) // Time stamp the arbiter so we know it was used recently. arb->stamp = space->stamp; + return id; } // Hashset filter func to throw away old arbiters. diff --git a/external/chipmunk/src/cpSweep1D.c b/external/chipmunk/src/cpSweep1D.c index f617bce021..80b9a4ac53 100644 --- a/external/chipmunk/src/cpSweep1D.c +++ b/external/chipmunk/src/cpSweep1D.c @@ -183,7 +183,7 @@ cpSweep1DQuery(cpSweep1D *sweep, void *obj, cpBB bb, cpSpatialIndexQueryFunc fun TableCell *table = sweep->table; for(int i=0, count=sweep->num; isetPosition(Point( VisibleRect::center().x, VisibleRect::top().y - 30)); + label->setPosition(cocos2d::Point( VisibleRect::center().x, VisibleRect::top().y - 30)); this->addChild(label, -1); // reset button @@ -52,7 +52,7 @@ ChipmunkTestLayer::ChipmunkTestLayer() #endif addChild(parent, 0, kTagParentNode); - addNewSpriteAtPosition(Point(200,200)); + addNewSpriteAtPosition(cocos2d::Point(200,200)); // menu for debug layer MenuItemFont::setFontSize(18); @@ -60,7 +60,7 @@ ChipmunkTestLayer::ChipmunkTestLayer() auto menu = Menu::create(item, NULL); this->addChild(menu); - menu->setPosition(Point(VisibleRect::right().x-100, VisibleRect::top().y-60)); + menu->setPosition(cocos2d::Point(VisibleRect::right().x-100, VisibleRect::top().y-60)); scheduleUpdate(); #else @@ -160,7 +160,7 @@ void ChipmunkTestLayer::createResetButton() auto menu = Menu::create(reset, NULL); - menu->setPosition(Point(VisibleRect::center().x, VisibleRect::bottom().y + 30)); + menu->setPosition(cocos2d::Point(VisibleRect::center().x, VisibleRect::bottom().y + 30)); this->addChild(menu, -1); } @@ -174,7 +174,7 @@ void ChipmunkTestLayer::reset(Ref* sender) s->release(); } -void ChipmunkTestLayer::addNewSpriteAtPosition(Point pos) +void ChipmunkTestLayer::addNewSpriteAtPosition(cocos2d::Point pos) { #if CC_ENABLE_CHIPMUNK_INTEGRATION int posx, posy; @@ -205,7 +205,7 @@ void ChipmunkTestLayer::addNewSpriteAtPosition(Point pos) shape->e = 0.5f; shape->u = 0.5f; cpSpaceAddShape(_space, shape); - auto sprite = PhysicsSprite::createWithTexture(_spriteTexture, Rect(posx, posy, 85, 121)); + auto sprite = PhysicsSprite::createWithTexture(_spriteTexture, cocos2d::Rect(posx, posy, 85, 121)); parent->addChild(sprite); sprite->setCPBody(body); @@ -242,7 +242,7 @@ void ChipmunkTestLayer::onAcceleration(Acceleration* acc, Event* event) prevX = accelX; prevY = accelY; - auto v = Point( accelX, accelY); + auto v = cocos2d::Point( accelX, accelY); v = v * 200; _space->gravity = cpv(v.x, v.y); } diff --git a/tests/cpp-tests/Classes/ChipmunkTest/ChipmunkTest.h b/tests/cpp-tests/Classes/ChipmunkTest/ChipmunkTest.h index 13d216c359..52f7295ee4 100644 --- a/tests/cpp-tests/Classes/ChipmunkTest/ChipmunkTest.h +++ b/tests/cpp-tests/Classes/ChipmunkTest/ChipmunkTest.h @@ -21,7 +21,7 @@ public: void createResetButton(); void reset(Ref* sender); - void addNewSpriteAtPosition(Point p); + void addNewSpriteAtPosition(cocos2d::Point p); void update(float dt); void toggleDebugCallback(Ref* sender); void onTouchesEnded(const std::vector& touches, Event* event); diff --git a/tests/cpp-tests/Classes/VisibleRect.cpp b/tests/cpp-tests/Classes/VisibleRect.cpp index 917de81d73..06d185695c 100644 --- a/tests/cpp-tests/Classes/VisibleRect.cpp +++ b/tests/cpp-tests/Classes/VisibleRect.cpp @@ -24,6 +24,8 @@ #include "VisibleRect.h" +USING_NS_CC; + Rect VisibleRect::s_visibleRect; void VisibleRect::lazyInit() diff --git a/tests/cpp-tests/Classes/VisibleRect.h b/tests/cpp-tests/Classes/VisibleRect.h index 67b7e1fa1b..e88b91bf23 100644 --- a/tests/cpp-tests/Classes/VisibleRect.h +++ b/tests/cpp-tests/Classes/VisibleRect.h @@ -2,25 +2,24 @@ #define __VISIBLERECT_H__ #include "cocos2d.h" -USING_NS_CC; class VisibleRect { public: - static Rect getVisibleRect(); + static cocos2d::Rect getVisibleRect(); - static Point left(); - static Point right(); - static Point top(); - static Point bottom(); - static Point center(); - static Point leftTop(); - static Point rightTop(); - static Point leftBottom(); - static Point rightBottom(); + static cocos2d::Point left(); + static cocos2d::Point right(); + static cocos2d::Point top(); + static cocos2d::Point bottom(); + static cocos2d::Point center(); + static cocos2d::Point leftTop(); + static cocos2d::Point rightTop(); + static cocos2d::Point leftBottom(); + static cocos2d::Point rightBottom(); private: static void lazyInit(); - static Rect s_visibleRect; + static cocos2d::Rect s_visibleRect; }; #endif /* __VISIBLERECT_H__ */ From c82933e3c45e64fae3291e753419b57c951323b7 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Tue, 25 Mar 2014 16:46:10 -0700 Subject: [PATCH 086/106] chipmunk fixes for Linux --- external/chipmunk/src/CMakeLists.txt | 9 +++++++++ external/chipmunk/src/cpCollision.c | 1 + 2 files changed, 10 insertions(+) diff --git a/external/chipmunk/src/CMakeLists.txt b/external/chipmunk/src/CMakeLists.txt index 2e817ea717..4005c750f4 100644 --- a/external/chipmunk/src/CMakeLists.txt +++ b/external/chipmunk/src/CMakeLists.txt @@ -1,3 +1,5 @@ +set(BUILD_STATIC 1) + file(GLOB chipmunk_source_files "*.c" "constraints/*.c") file(GLOB chipmunk_public_header "${chipmunk_SOURCE_DIR}/include/chipmunk/*.h") file(GLOB chipmunk_constraint_header "${chipmunk_SOURCE_DIR}/include/chipmunk/constraints/*.h") @@ -46,3 +48,10 @@ if(BUILD_SHARED OR INSTALL_STATIC) install(FILES ${chipmunk_public_header} DESTINATION include/chipmunk) install(FILES ${chipmunk_constraint_header} DESTINATION include/chipmunk/constraints) endif(BUILD_SHARED OR INSTALL_STATIC) + +set_target_properties(chipmunk_static + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib" +) + diff --git a/external/chipmunk/src/cpCollision.c b/external/chipmunk/src/cpCollision.c index e29e4bf82e..e96738808b 100644 --- a/external/chipmunk/src/cpCollision.c +++ b/external/chipmunk/src/cpCollision.c @@ -21,6 +21,7 @@ #include #include +#include #include "chipmunk_private.h" From 41ffa372e8e0f4f4765c55d121ce33599eb9b496 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Wed, 26 Mar 2014 11:09:16 +0800 Subject: [PATCH 087/106] label: Refactor implementation of shadow. --- cocos/2d/CCLabel.cpp | 144 +++++++++++++++++++++++++++++-------------- cocos/2d/CCLabel.h | 5 ++ 2 files changed, 102 insertions(+), 47 deletions(-) diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index 55220b4df4..03c1d3c63f 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -334,12 +334,14 @@ void Label::reset() Node::removeAllChildrenWithCleanup(true); _textSprite = nullptr; + _shadowNode = nullptr; CC_SAFE_RELEASE_NULL(_reusedLetter); _textColor = Color4B::WHITE; _textColorF = Color4F::WHITE; setColor(Color3B::WHITE); + _shadowEnabled = false; } void Label::updateShaderProgram() @@ -347,7 +349,6 @@ void Label::updateShaderProgram() switch (_currLabelEffect) { case cocos2d::LabelEffect::NORMAL: - case cocos2d::LabelEffect::SHADOW: if (_useDistanceField) setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_LABEL_DISTANCEFIELD_NORMAL)); else if (_useA8Shader) @@ -478,6 +479,13 @@ void Label::setFontDefinition(const FontDefinition& textDefinition) _fontDefinition = textDefinition; _fontName = textDefinition._fontName; _fontSize = textDefinition._fontSize; + + _shadowEnabled = textDefinition._shadow._shadowEnabled; + if (_shadowEnabled) + { + enableShadow(Color4B::BLACK,_fontDefinition._shadow._shadowOffset,_fontDefinition._shadow._shadowBlur); + } + _textColor = Color4B(_fontDefinition._fontFillColor); _textColorF.r = _textColor.r / 255.0f; _textColorF.g = _textColor.g / 255.0f; @@ -832,24 +840,31 @@ void Label::enableOutline(const Color4B& outlineColor,int outlineSize /* = -1 */ void Label::enableShadow(const Color4B& shadowColor /* = Color4B::BLACK */,const Size &offset /* = Size(2 ,-2)*/, int blurRadius /* = 0 */) { + _shadowEnabled = true; + _fontDefinition._shadow._shadowEnabled = false; + _effectColor = shadowColor; _effectColorF.r = _effectColor.r / 255.0f; _effectColorF.g = _effectColor.g / 255.0f; _effectColorF.b = _effectColor.b / 255.0f; _effectColorF.a = _effectColor.a / 255.0f; + + _shadowColor.r = _effectColor.r; + _shadowColor.g = _effectColor.g; + _shadowColor.b = _effectColor.b; + auto contentScaleFactor = CC_CONTENT_SCALE_FACTOR(); _shadowOffset.width = offset.width * contentScaleFactor; _shadowOffset.height = offset.height * contentScaleFactor; //todo:support blur for shadow _shadowBlurRadius = 0; - _currLabelEffect = LabelEffect::SHADOW; - _fontDefinition._shadow._shadowEnabled = true; - _fontDefinition._shadow._shadowBlur = blurRadius; - _fontDefinition._shadow._shadowOffset = _shadowOffset; - _fontDefinition._shadow._shadowOpacity = shadowColor.a / 255.0f; - - _contentDirty = true; + if (_textSprite && _shadowNode) + { + _shadowNode->setColor(_shadowColor); + _shadowNode->setOpacity(_effectColorF.a * _displayedOpacity); + _shadowNode->setPosition(_shadowOffset.width, _shadowOffset.height); + } } void Label::disableEffect() @@ -862,6 +877,12 @@ void Label::disableEffect() _currLabelEffect = LabelEffect::NORMAL; updateShaderProgram(); _contentDirty = true; + _shadowEnabled = false; + if (_shadowNode) + { + Node::removeChild(_shadowNode,true); + _shadowNode = nullptr; + } } void Label::setFontScale(float fontScale) @@ -884,24 +905,25 @@ void Label::onDraw(const kmMat4& transform, bool transformUpdated) GL::blendFunc( _blendFunc.src, _blendFunc.dst ); bool trans = false; - if (_currLabelEffect == LabelEffect::OUTLINE || _currLabelEffect == LabelEffect::GLOW) - { - _shaderProgram->setUniformLocationWith4f(_uniformEffectColor, - _effectColorF.r,_effectColorF.g,_effectColorF.b,_effectColorF.a); - } - else if(_currLabelEffect == LabelEffect::SHADOW && _shadowBlurRadius <= 0) - { - trans = true; - drawShadowWithoutBlur(); - } - - _shaderProgram->setUniformsForBuiltins(transform); - if (_currentLabelType == LabelType::TTF) { _shaderProgram->setUniformLocationWith4f(_uniformTextColor, _textColorF.r,_textColorF.g,_textColorF.b,_textColorF.a); } + + if (_currLabelEffect == LabelEffect::OUTLINE || _currLabelEffect == LabelEffect::GLOW) + { + _shaderProgram->setUniformLocationWith4f(_uniformEffectColor, + _effectColorF.r,_effectColorF.g,_effectColorF.b,_effectColorF.a); + } + else if(_shadowEnabled && _shadowBlurRadius <= 0) + { + trans = true; + kmGLPushMatrix(); + drawShadowWithoutBlur(); + } + + _shaderProgram->setUniformsForBuiltins(transform); for(const auto &child: _children) { @@ -930,19 +952,10 @@ void Label::drawShadowWithoutBlur() Color3B oldColor = _realColor; GLubyte oldOPacity = _displayedOpacity; - if (_currentLabelType == LabelType::TTF) - { - _shaderProgram->setUniformLocationWith4f(_uniformTextColor, - _effectColorF.r,_effectColorF.g,_effectColorF.b,_effectColorF.a); - } - else - { - _displayedOpacity = _effectColorF.a * _displayedOpacity; - setColor(Color3B(_effectColor)); - } + _displayedOpacity = _effectColorF.a * _displayedOpacity; + setColor(_shadowColor); _modelViewTransform = transform(_parentTransform); - kmGLPushMatrix(); kmGLLoadMatrix(&_modelViewTransform); _shaderProgram->setUniformsForBuiltins(_modelViewTransform); @@ -959,11 +972,9 @@ void Label::drawShadowWithoutBlur() _position.y -= _shadowOffset.height; _transformDirty = _inverseDirty = true; - if (_currentLabelType != LabelType::TTF) - { - _displayedOpacity = oldOPacity; - setColor(oldColor); - } + _displayedOpacity = oldOPacity; + setColor(oldColor); + _modelViewTransform = transform(_parentTransform); kmGLLoadMatrix(&_modelViewTransform); } @@ -1008,6 +1019,11 @@ void Label::updateContent() { Node::removeChild(_textSprite,true); _textSprite = nullptr; + if (_shadowNode) + { + Node::removeChild(_shadowNode,true); + _shadowNode = nullptr; + } } if (_fontAtlas) { @@ -1038,6 +1054,40 @@ void Label::updateFont() _fontDirty = false; } +void Label::drawTextSprite(Renderer *renderer, bool parentTransformUpdated) +{ + if (_fontDefinition._fontFillColor != _textColor) + { + Node::removeChild(_textSprite,true); + _textSprite = nullptr; + if (_shadowNode) + { + Node::removeChild(_shadowNode,true); + _shadowNode = nullptr; + } + + _fontDefinition._fontFillColor.r = _textColor.r; + _fontDefinition._fontFillColor.g = _textColor.g; + _fontDefinition._fontFillColor.b = _textColor.b; + createSpriteWithFontDefinition(); + } + + if (_shadowEnabled && _shadowNode == nullptr) + { + _shadowNode = Sprite::createWithTexture(_textSprite->getTexture()); + _shadowNode->setAnchorPoint(Point::ANCHOR_BOTTOM_LEFT); + _shadowNode->setColor(_shadowColor); + _shadowNode->setOpacity(_effectColorF.a * _displayedOpacity); + _shadowNode->setPosition(_shadowOffset.width, _shadowOffset.height); + Node::addChild(_shadowNode,0,Node::INVALID_TAG); + } + if (_shadowNode) + { + _shadowNode->visit(renderer, _modelViewTransform, parentTransformUpdated); + } + _textSprite->visit(renderer, _modelViewTransform, parentTransformUpdated); +} + void Label::visit(Renderer *renderer, const kmMat4 &parentTransform, bool parentTransformUpdated) { if (! _visible || _originalUTF8String.empty()) @@ -1053,7 +1103,7 @@ void Label::visit(Renderer *renderer, const kmMat4 &parentTransform, bool parent updateContent(); } - if (! _textSprite && _currLabelEffect == LabelEffect::SHADOW && _shadowBlurRadius <= 0) + if (! _textSprite && _shadowEnabled && _shadowBlurRadius <= 0) { _parentTransform = parentTransform; draw(renderer, _modelViewTransform, true); @@ -1074,15 +1124,7 @@ void Label::visit(Renderer *renderer, const kmMat4 &parentTransform, bool parent if (_textSprite) { - if (_fontDefinition._fontFillColor != _textColor) - { - Node::removeChild(_textSprite,true); - _fontDefinition._fontFillColor.r = _textColor.r; - _fontDefinition._fontFillColor.g = _textColor.g; - _fontDefinition._fontFillColor.b = _textColor.b; - createSpriteWithFontDefinition(); - } - _textSprite->visit(renderer, _modelViewTransform, dirty); + drawTextSprite(renderer,dirty); } else { @@ -1226,6 +1268,10 @@ void Label::updateDisplayedColor(const Color3B& parentColor) if (_textSprite) { _textSprite->updateDisplayedColor(_displayedColor); + if (_shadowNode) + { + _shadowNode->updateDisplayedColor(_displayedColor); + } } } @@ -1237,6 +1283,10 @@ void Label::updateDisplayedOpacity(GLubyte parentOpacity) if (_textSprite) { _textSprite->updateDisplayedOpacity(_displayedOpacity); + if (_shadowNode) + { + _shadowNode->updateDisplayedOpacity(_displayedOpacity); + } } } diff --git a/cocos/2d/CCLabel.h b/cocos/2d/CCLabel.h index 93130c4e10..09212820b9 100644 --- a/cocos/2d/CCLabel.h +++ b/cocos/2d/CCLabel.h @@ -300,6 +300,8 @@ protected: void drawShadowWithoutBlur(); + void drawTextSprite(Renderer *renderer, bool parentTransformUpdated); + void createSpriteWithFontDefinition(); void updateFont(); @@ -358,9 +360,12 @@ protected: GLuint _uniformTextColor; CustomCommand _customCommand; + bool _shadowEnabled; Size _shadowOffset; int _shadowBlurRadius; kmMat4 _parentTransform; + Color3B _shadowColor; + Node* _shadowNode; Color4B _textColor; Color4F _textColorF; From ec8de6b4025d7f9790ed156ec8613bc342941b51 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 26 Mar 2014 11:50:22 +0800 Subject: [PATCH 088/106] Update CHANGELOG [ci skip] --- CHANGELOG.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.REMOVED.git-id b/CHANGELOG.REMOVED.git-id index 1703c79ebf..1234ebc717 100644 --- a/CHANGELOG.REMOVED.git-id +++ b/CHANGELOG.REMOVED.git-id @@ -1 +1 @@ -8141cfdd7d973fa5a4c189a72c2fd6cac8eb95ae \ No newline at end of file +7a4a3717b22578e2529226a4384ca423229137e7 \ No newline at end of file From 674bce677db715f9443a70a55aec52ccf7413183 Mon Sep 17 00:00:00 2001 From: samuele3hu Date: Wed, 26 Mar 2014 12:56:29 +0800 Subject: [PATCH 089/106] update `bindings-generator` submoudle --- tools/bindings-generator | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/bindings-generator b/tools/bindings-generator index 4e49198989..83818aec3c 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit 4e49198989adf8e55ac70756a035fc7f195e8e36 +Subproject commit 83818aec3cbe1ecf2db5380df254bab489d44f46 From ac0ad544334e60d06fae9b19c4674ffa9017c064 Mon Sep 17 00:00:00 2001 From: samuele3hu Date: Wed, 26 Mar 2014 12:58:33 +0800 Subject: [PATCH 090/106] =?UTF-8?q?Modify=20the=20config=20files=20for=20b?= =?UTF-8?q?indings-generator=20to=20fix=20the=20error=20about=20=E2=80=9Ci?= =?UTF-8?q?s=5Fref=5Fclass=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/tolua/cocos2dx_extension.ini | 2 +- tools/tolua/cocos2dx_spine.ini | 2 +- tools/tolua/cocos2dx_studio.ini | 4 ++-- tools/tolua/cocos2dx_ui.ini | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/tools/tolua/cocos2dx_extension.ini b/tools/tolua/cocos2dx_extension.ini index 81d0072607..8c7de812c8 100644 --- a/tools/tolua/cocos2dx_extension.ini +++ b/tools/tolua/cocos2dx_extension.ini @@ -63,7 +63,7 @@ remove_prefix = classes_have_no_parents = # base classes which will be skipped when their sub-classes found them. -base_classes_to_skip = Ref ProcessBase +base_classes_to_skip = # classes that create no constructor # Set is special and we will use a hand-written constructor diff --git a/tools/tolua/cocos2dx_spine.ini b/tools/tolua/cocos2dx_spine.ini index 6fce549122..796c766406 100644 --- a/tools/tolua/cocos2dx_spine.ini +++ b/tools/tolua/cocos2dx_spine.ini @@ -50,7 +50,7 @@ remove_prefix = classes_have_no_parents = # base classes which will be skipped when their sub-classes found them. -base_classes_to_skip = Ref ProcessBase +base_classes_to_skip = # classes that create no constructor # Set is special and we will use a hand-written constructor diff --git a/tools/tolua/cocos2dx_studio.ini b/tools/tolua/cocos2dx_studio.ini index 38136febfd..76553f7dda 100644 --- a/tools/tolua/cocos2dx_studio.ini +++ b/tools/tolua/cocos2dx_studio.ini @@ -68,11 +68,11 @@ remove_prefix = classes_have_no_parents = # base classes which will be skipped when their sub-classes found them. -base_classes_to_skip = Ref ProcessBase +base_classes_to_skip = # classes that create no constructor # Set is special and we will use a hand-written constructor -abstract_classes = ArmatureDataManager ComAttribute ComRender ComAudio ActionManagerEx SceneReader GUIReader BatchNode +abstract_classes = ArmatureDataManager ComAttribute ComRender ComAudio ActionManagerEx SceneReader GUIReader BatchNode ProcessBase # Determining whether to use script object(js object) to control the lifecycle of native(cpp) object or the other way around. Supported values are 'yes' or 'no'. script_control_cpp = no diff --git a/tools/tolua/cocos2dx_ui.ini b/tools/tolua/cocos2dx_ui.ini index 68e1978ca5..0703e76093 100644 --- a/tools/tolua/cocos2dx_ui.ini +++ b/tools/tolua/cocos2dx_ui.ini @@ -57,7 +57,7 @@ remove_prefix = classes_have_no_parents = Helper # base classes which will be skipped when their sub-classes found them. -base_classes_to_skip = Ref +base_classes_to_skip = # classes that create no constructor # Set is special and we will use a hand-written constructor From 0140d6d3f7b48370dcfcda61b778bc3ff2dbb427 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Wed, 26 Mar 2014 06:03:04 +0000 Subject: [PATCH 091/106] [AUTO]: updating luabinding automatically --- cocos/scripting/lua-bindings/auto/api/ActionManagerEx.lua | 1 + cocos/scripting/lua-bindings/auto/api/ActionObject.lua | 1 + cocos/scripting/lua-bindings/auto/api/AnimationData.lua | 1 + cocos/scripting/lua-bindings/auto/api/Armature.lua | 2 +- cocos/scripting/lua-bindings/auto/api/ArmatureAnimation.lua | 1 + cocos/scripting/lua-bindings/auto/api/ArmatureData.lua | 1 + cocos/scripting/lua-bindings/auto/api/ArmatureDataManager.lua | 1 + cocos/scripting/lua-bindings/auto/api/AtlasNode.lua | 2 +- cocos/scripting/lua-bindings/auto/api/BaseData.lua | 1 + cocos/scripting/lua-bindings/auto/api/CCBAnimationManager.lua | 1 + cocos/scripting/lua-bindings/auto/api/CCBReader.lua | 1 + cocos/scripting/lua-bindings/auto/api/ComController.lua | 2 +- cocos/scripting/lua-bindings/auto/api/ContourData.lua | 1 + cocos/scripting/lua-bindings/auto/api/DisplayData.lua | 1 + cocos/scripting/lua-bindings/auto/api/DisplayManager.lua | 1 + cocos/scripting/lua-bindings/auto/api/EditBox.lua | 2 +- cocos/scripting/lua-bindings/auto/api/GLView.lua | 2 +- cocos/scripting/lua-bindings/auto/api/GUIReader.lua | 1 + cocos/scripting/lua-bindings/auto/api/Label.lua | 2 +- cocos/scripting/lua-bindings/auto/api/LabelAtlas.lua | 2 +- cocos/scripting/lua-bindings/auto/api/LabelBMFont.lua | 2 +- cocos/scripting/lua-bindings/auto/api/LabelTTF.lua | 2 +- cocos/scripting/lua-bindings/auto/api/LayerColor.lua | 2 +- cocos/scripting/lua-bindings/auto/api/LayoutParameter.lua | 1 + cocos/scripting/lua-bindings/auto/api/MotionStreak.lua | 2 +- cocos/scripting/lua-bindings/auto/api/MovementBoneData.lua | 1 + cocos/scripting/lua-bindings/auto/api/MovementData.lua | 1 + cocos/scripting/lua-bindings/auto/api/PageView.lua | 2 +- cocos/scripting/lua-bindings/auto/api/ParticleBatchNode.lua | 2 +- cocos/scripting/lua-bindings/auto/api/ParticleSystem.lua | 2 +- cocos/scripting/lua-bindings/auto/api/RichElement.lua | 1 + cocos/scripting/lua-bindings/auto/api/ScrollView.lua | 2 +- cocos/scripting/lua-bindings/auto/api/Skeleton.lua | 2 +- cocos/scripting/lua-bindings/auto/api/Sprite.lua | 2 +- cocos/scripting/lua-bindings/auto/api/SpriteBatchNode.lua | 2 +- cocos/scripting/lua-bindings/auto/api/TableView.lua | 2 +- cocos/scripting/lua-bindings/auto/api/TextureData.lua | 1 + cocos/scripting/lua-bindings/auto/api/TransitionFadeTR.lua | 2 +- cocos/scripting/lua-bindings/auto/api/TransitionMoveInL.lua | 2 +- cocos/scripting/lua-bindings/auto/api/TransitionShrinkGrow.lua | 2 +- cocos/scripting/lua-bindings/auto/api/TransitionSlideInL.lua | 2 +- cocos/scripting/lua-bindings/auto/api/TransitionSplitCols.lua | 2 +- .../scripting/lua-bindings/auto/api/TransitionTurnOffTiles.lua | 2 +- cocos/scripting/lua-bindings/auto/api/Tween.lua | 1 + .../auto/lua_cocos2dx_extension_auto.cpp.REMOVED.git-id | 2 +- .../auto/lua_cocos2dx_studio_auto.cpp.REMOVED.git-id | 2 +- .../lua-bindings/auto/lua_cocos2dx_ui_auto.cpp.REMOVED.git-id | 2 +- 47 files changed, 47 insertions(+), 28 deletions(-) diff --git a/cocos/scripting/lua-bindings/auto/api/ActionManagerEx.lua b/cocos/scripting/lua-bindings/auto/api/ActionManagerEx.lua index 4bc3a5a97c..3592d682f3 100644 --- a/cocos/scripting/lua-bindings/auto/api/ActionManagerEx.lua +++ b/cocos/scripting/lua-bindings/auto/api/ActionManagerEx.lua @@ -1,6 +1,7 @@ -------------------------------- -- @module ActionManagerEx +-- @extend Ref -------------------------------- -- overload function: playActionByName(char, char, cc.CallFunc) diff --git a/cocos/scripting/lua-bindings/auto/api/ActionObject.lua b/cocos/scripting/lua-bindings/auto/api/ActionObject.lua index c61a546386..ec83feaa15 100644 --- a/cocos/scripting/lua-bindings/auto/api/ActionObject.lua +++ b/cocos/scripting/lua-bindings/auto/api/ActionObject.lua @@ -1,6 +1,7 @@ -------------------------------- -- @module ActionObject +-- @extend Ref -------------------------------- -- @function [parent=#ActionObject] setCurrentTime diff --git a/cocos/scripting/lua-bindings/auto/api/AnimationData.lua b/cocos/scripting/lua-bindings/auto/api/AnimationData.lua index 80d6482163..71af4a264f 100644 --- a/cocos/scripting/lua-bindings/auto/api/AnimationData.lua +++ b/cocos/scripting/lua-bindings/auto/api/AnimationData.lua @@ -1,6 +1,7 @@ -------------------------------- -- @module AnimationData +-- @extend Ref -------------------------------- -- @function [parent=#AnimationData] getMovement diff --git a/cocos/scripting/lua-bindings/auto/api/Armature.lua b/cocos/scripting/lua-bindings/auto/api/Armature.lua index c4c3a31527..4643bf562d 100644 --- a/cocos/scripting/lua-bindings/auto/api/Armature.lua +++ b/cocos/scripting/lua-bindings/auto/api/Armature.lua @@ -1,7 +1,7 @@ -------------------------------- -- @module Armature --- @extend Node,BlendProtocol, +-- @extend Node,BlendProtocol -------------------------------- -- @function [parent=#Armature] getBone diff --git a/cocos/scripting/lua-bindings/auto/api/ArmatureAnimation.lua b/cocos/scripting/lua-bindings/auto/api/ArmatureAnimation.lua index 00ed9e21fa..9a42e11f08 100644 --- a/cocos/scripting/lua-bindings/auto/api/ArmatureAnimation.lua +++ b/cocos/scripting/lua-bindings/auto/api/ArmatureAnimation.lua @@ -1,6 +1,7 @@ -------------------------------- -- @module ArmatureAnimation +-- @extend ProcessBase -------------------------------- -- @function [parent=#ArmatureAnimation] getSpeedScale diff --git a/cocos/scripting/lua-bindings/auto/api/ArmatureData.lua b/cocos/scripting/lua-bindings/auto/api/ArmatureData.lua index 503eee97ac..0c193bd777 100644 --- a/cocos/scripting/lua-bindings/auto/api/ArmatureData.lua +++ b/cocos/scripting/lua-bindings/auto/api/ArmatureData.lua @@ -1,6 +1,7 @@ -------------------------------- -- @module ArmatureData +-- @extend Ref -------------------------------- -- @function [parent=#ArmatureData] addBoneData diff --git a/cocos/scripting/lua-bindings/auto/api/ArmatureDataManager.lua b/cocos/scripting/lua-bindings/auto/api/ArmatureDataManager.lua index 099bdf9600..2af4790834 100644 --- a/cocos/scripting/lua-bindings/auto/api/ArmatureDataManager.lua +++ b/cocos/scripting/lua-bindings/auto/api/ArmatureDataManager.lua @@ -1,6 +1,7 @@ -------------------------------- -- @module ArmatureDataManager +-- @extend Ref -------------------------------- -- @function [parent=#ArmatureDataManager] getAnimationDatas diff --git a/cocos/scripting/lua-bindings/auto/api/AtlasNode.lua b/cocos/scripting/lua-bindings/auto/api/AtlasNode.lua index f4b0dee453..990c15e19f 100644 --- a/cocos/scripting/lua-bindings/auto/api/AtlasNode.lua +++ b/cocos/scripting/lua-bindings/auto/api/AtlasNode.lua @@ -1,7 +1,7 @@ -------------------------------- -- @module AtlasNode --- @extend Node,TextureProtocol, +-- @extend Node,TextureProtocol -------------------------------- -- @function [parent=#AtlasNode] updateAtlasValues diff --git a/cocos/scripting/lua-bindings/auto/api/BaseData.lua b/cocos/scripting/lua-bindings/auto/api/BaseData.lua index f674d532a4..b6084d2971 100644 --- a/cocos/scripting/lua-bindings/auto/api/BaseData.lua +++ b/cocos/scripting/lua-bindings/auto/api/BaseData.lua @@ -1,6 +1,7 @@ -------------------------------- -- @module BaseData +-- @extend Ref -------------------------------- -- @function [parent=#BaseData] getColor diff --git a/cocos/scripting/lua-bindings/auto/api/CCBAnimationManager.lua b/cocos/scripting/lua-bindings/auto/api/CCBAnimationManager.lua index 30874c8dab..a796979bfd 100644 --- a/cocos/scripting/lua-bindings/auto/api/CCBAnimationManager.lua +++ b/cocos/scripting/lua-bindings/auto/api/CCBAnimationManager.lua @@ -1,6 +1,7 @@ -------------------------------- -- @module CCBAnimationManager +-- @extend Ref -------------------------------- -- @function [parent=#CCBAnimationManager] moveAnimationsFromNode diff --git a/cocos/scripting/lua-bindings/auto/api/CCBReader.lua b/cocos/scripting/lua-bindings/auto/api/CCBReader.lua index add2dd0fb0..144e0da234 100644 --- a/cocos/scripting/lua-bindings/auto/api/CCBReader.lua +++ b/cocos/scripting/lua-bindings/auto/api/CCBReader.lua @@ -1,6 +1,7 @@ -------------------------------- -- @module CCBReader +-- @extend Ref -------------------------------- -- @function [parent=#CCBReader] addOwnerOutletName diff --git a/cocos/scripting/lua-bindings/auto/api/ComController.lua b/cocos/scripting/lua-bindings/auto/api/ComController.lua index 0b0ec31ee3..6f374349fc 100644 --- a/cocos/scripting/lua-bindings/auto/api/ComController.lua +++ b/cocos/scripting/lua-bindings/auto/api/ComController.lua @@ -1,7 +1,7 @@ -------------------------------- -- @module ComController --- @extend Component,InputDelegate, +-- @extend Component,InputDelegate -------------------------------- -- @function [parent=#ComController] create diff --git a/cocos/scripting/lua-bindings/auto/api/ContourData.lua b/cocos/scripting/lua-bindings/auto/api/ContourData.lua index f16c786881..02b079799d 100644 --- a/cocos/scripting/lua-bindings/auto/api/ContourData.lua +++ b/cocos/scripting/lua-bindings/auto/api/ContourData.lua @@ -1,6 +1,7 @@ -------------------------------- -- @module ContourData +-- @extend Ref -------------------------------- -- @function [parent=#ContourData] init diff --git a/cocos/scripting/lua-bindings/auto/api/DisplayData.lua b/cocos/scripting/lua-bindings/auto/api/DisplayData.lua index a61d32bab2..d7643c79ea 100644 --- a/cocos/scripting/lua-bindings/auto/api/DisplayData.lua +++ b/cocos/scripting/lua-bindings/auto/api/DisplayData.lua @@ -1,6 +1,7 @@ -------------------------------- -- @module DisplayData +-- @extend Ref -------------------------------- -- @function [parent=#DisplayData] copy diff --git a/cocos/scripting/lua-bindings/auto/api/DisplayManager.lua b/cocos/scripting/lua-bindings/auto/api/DisplayManager.lua index 035244b5ec..56874b0b88 100644 --- a/cocos/scripting/lua-bindings/auto/api/DisplayManager.lua +++ b/cocos/scripting/lua-bindings/auto/api/DisplayManager.lua @@ -1,6 +1,7 @@ -------------------------------- -- @module DisplayManager +-- @extend Ref -------------------------------- -- @function [parent=#DisplayManager] getDisplayRenderNode diff --git a/cocos/scripting/lua-bindings/auto/api/EditBox.lua b/cocos/scripting/lua-bindings/auto/api/EditBox.lua index 2485ed45a3..a6e915373e 100644 --- a/cocos/scripting/lua-bindings/auto/api/EditBox.lua +++ b/cocos/scripting/lua-bindings/auto/api/EditBox.lua @@ -1,7 +1,7 @@ -------------------------------- -- @module EditBox --- @extend ControlButton,IMEDelegate, +-- @extend ControlButton,IMEDelegate -------------------------------- -- @function [parent=#EditBox] getText diff --git a/cocos/scripting/lua-bindings/auto/api/GLView.lua b/cocos/scripting/lua-bindings/auto/api/GLView.lua index 851e449e01..9969b04b39 100644 --- a/cocos/scripting/lua-bindings/auto/api/GLView.lua +++ b/cocos/scripting/lua-bindings/auto/api/GLView.lua @@ -1,7 +1,7 @@ -------------------------------- -- @module GLView --- @extend GLViewProtocol,Ref, +-- @extend GLViewProtocol,Ref -------------------------------- -- @function [parent=#GLView] createWithRect diff --git a/cocos/scripting/lua-bindings/auto/api/GUIReader.lua b/cocos/scripting/lua-bindings/auto/api/GUIReader.lua index 0c182ddde9..5e9509e0e2 100644 --- a/cocos/scripting/lua-bindings/auto/api/GUIReader.lua +++ b/cocos/scripting/lua-bindings/auto/api/GUIReader.lua @@ -1,6 +1,7 @@ -------------------------------- -- @module GUIReader +-- @extend Ref -------------------------------- -- @function [parent=#GUIReader] widgetFromJsonFile diff --git a/cocos/scripting/lua-bindings/auto/api/Label.lua b/cocos/scripting/lua-bindings/auto/api/Label.lua index f46a580dc0..fd8aece932 100644 --- a/cocos/scripting/lua-bindings/auto/api/Label.lua +++ b/cocos/scripting/lua-bindings/auto/api/Label.lua @@ -1,7 +1,7 @@ -------------------------------- -- @module Label --- @extend SpriteBatchNode,LabelProtocol, +-- @extend SpriteBatchNode,LabelProtocol -------------------------------- -- @function [parent=#Label] isClipMarginEnabled diff --git a/cocos/scripting/lua-bindings/auto/api/LabelAtlas.lua b/cocos/scripting/lua-bindings/auto/api/LabelAtlas.lua index 816ed5a333..069801b9fd 100644 --- a/cocos/scripting/lua-bindings/auto/api/LabelAtlas.lua +++ b/cocos/scripting/lua-bindings/auto/api/LabelAtlas.lua @@ -1,7 +1,7 @@ -------------------------------- -- @module LabelAtlas --- @extend AtlasNode,LabelProtocol, +-- @extend AtlasNode,LabelProtocol -------------------------------- -- @function [parent=#LabelAtlas] setString diff --git a/cocos/scripting/lua-bindings/auto/api/LabelBMFont.lua b/cocos/scripting/lua-bindings/auto/api/LabelBMFont.lua index 5733e69560..825ce15f51 100644 --- a/cocos/scripting/lua-bindings/auto/api/LabelBMFont.lua +++ b/cocos/scripting/lua-bindings/auto/api/LabelBMFont.lua @@ -1,7 +1,7 @@ -------------------------------- -- @module LabelBMFont --- @extend Node,LabelProtocol,BlendProtocol, +-- @extend Node,LabelProtocol,BlendProtocol -------------------------------- -- @function [parent=#LabelBMFont] setLineBreakWithoutSpace diff --git a/cocos/scripting/lua-bindings/auto/api/LabelTTF.lua b/cocos/scripting/lua-bindings/auto/api/LabelTTF.lua index 6de559381e..a6a0ab9aa1 100644 --- a/cocos/scripting/lua-bindings/auto/api/LabelTTF.lua +++ b/cocos/scripting/lua-bindings/auto/api/LabelTTF.lua @@ -1,7 +1,7 @@ -------------------------------- -- @module LabelTTF --- @extend Node,LabelProtocol,BlendProtocol, +-- @extend Node,LabelProtocol,BlendProtocol -------------------------------- -- @function [parent=#LabelTTF] enableShadow diff --git a/cocos/scripting/lua-bindings/auto/api/LayerColor.lua b/cocos/scripting/lua-bindings/auto/api/LayerColor.lua index bdc2d44b4e..28dbebe461 100644 --- a/cocos/scripting/lua-bindings/auto/api/LayerColor.lua +++ b/cocos/scripting/lua-bindings/auto/api/LayerColor.lua @@ -1,7 +1,7 @@ -------------------------------- -- @module LayerColor --- @extend Layer,BlendProtocol, +-- @extend Layer,BlendProtocol -------------------------------- -- @function [parent=#LayerColor] changeWidthAndHeight diff --git a/cocos/scripting/lua-bindings/auto/api/LayoutParameter.lua b/cocos/scripting/lua-bindings/auto/api/LayoutParameter.lua index d46a0af912..0bd0036f4e 100644 --- a/cocos/scripting/lua-bindings/auto/api/LayoutParameter.lua +++ b/cocos/scripting/lua-bindings/auto/api/LayoutParameter.lua @@ -1,6 +1,7 @@ -------------------------------- -- @module LayoutParameter +-- @extend Ref -------------------------------- -- @function [parent=#LayoutParameter] clone diff --git a/cocos/scripting/lua-bindings/auto/api/MotionStreak.lua b/cocos/scripting/lua-bindings/auto/api/MotionStreak.lua index dd7b6a5621..582fd41980 100644 --- a/cocos/scripting/lua-bindings/auto/api/MotionStreak.lua +++ b/cocos/scripting/lua-bindings/auto/api/MotionStreak.lua @@ -1,7 +1,7 @@ -------------------------------- -- @module MotionStreak --- @extend Node,TextureProtocol, +-- @extend Node,TextureProtocol -------------------------------- -- @function [parent=#MotionStreak] reset diff --git a/cocos/scripting/lua-bindings/auto/api/MovementBoneData.lua b/cocos/scripting/lua-bindings/auto/api/MovementBoneData.lua index b9c3f826b6..da1f325e0c 100644 --- a/cocos/scripting/lua-bindings/auto/api/MovementBoneData.lua +++ b/cocos/scripting/lua-bindings/auto/api/MovementBoneData.lua @@ -1,6 +1,7 @@ -------------------------------- -- @module MovementBoneData +-- @extend Ref -------------------------------- -- @function [parent=#MovementBoneData] init diff --git a/cocos/scripting/lua-bindings/auto/api/MovementData.lua b/cocos/scripting/lua-bindings/auto/api/MovementData.lua index 11e59e7e66..c16cd19d61 100644 --- a/cocos/scripting/lua-bindings/auto/api/MovementData.lua +++ b/cocos/scripting/lua-bindings/auto/api/MovementData.lua @@ -1,6 +1,7 @@ -------------------------------- -- @module MovementData +-- @extend Ref -------------------------------- -- @function [parent=#MovementData] getMovementBoneData diff --git a/cocos/scripting/lua-bindings/auto/api/PageView.lua b/cocos/scripting/lua-bindings/auto/api/PageView.lua index eb3dea7b08..222d6ec258 100644 --- a/cocos/scripting/lua-bindings/auto/api/PageView.lua +++ b/cocos/scripting/lua-bindings/auto/api/PageView.lua @@ -1,7 +1,7 @@ -------------------------------- -- @module PageView --- @extend Layout,UIScrollInterface, +-- @extend Layout,UIScrollInterface -------------------------------- -- @function [parent=#PageView] getCurPageIndex diff --git a/cocos/scripting/lua-bindings/auto/api/ParticleBatchNode.lua b/cocos/scripting/lua-bindings/auto/api/ParticleBatchNode.lua index 4e894df073..40201230c9 100644 --- a/cocos/scripting/lua-bindings/auto/api/ParticleBatchNode.lua +++ b/cocos/scripting/lua-bindings/auto/api/ParticleBatchNode.lua @@ -1,7 +1,7 @@ -------------------------------- -- @module ParticleBatchNode --- @extend Node,TextureProtocol, +-- @extend Node,TextureProtocol -------------------------------- -- @function [parent=#ParticleBatchNode] setTexture diff --git a/cocos/scripting/lua-bindings/auto/api/ParticleSystem.lua b/cocos/scripting/lua-bindings/auto/api/ParticleSystem.lua index 62d6e4eacc..471cf7a52e 100644 --- a/cocos/scripting/lua-bindings/auto/api/ParticleSystem.lua +++ b/cocos/scripting/lua-bindings/auto/api/ParticleSystem.lua @@ -1,7 +1,7 @@ -------------------------------- -- @module ParticleSystem --- @extend Node,TextureProtocol, +-- @extend Node,TextureProtocol -------------------------------- -- @function [parent=#ParticleSystem] getStartSizeVar diff --git a/cocos/scripting/lua-bindings/auto/api/RichElement.lua b/cocos/scripting/lua-bindings/auto/api/RichElement.lua index 762d7b6480..c90261c788 100644 --- a/cocos/scripting/lua-bindings/auto/api/RichElement.lua +++ b/cocos/scripting/lua-bindings/auto/api/RichElement.lua @@ -1,6 +1,7 @@ -------------------------------- -- @module RichElement +-- @extend Ref -------------------------------- -- @function [parent=#RichElement] init diff --git a/cocos/scripting/lua-bindings/auto/api/ScrollView.lua b/cocos/scripting/lua-bindings/auto/api/ScrollView.lua index b5532e0192..c3855a2244 100644 --- a/cocos/scripting/lua-bindings/auto/api/ScrollView.lua +++ b/cocos/scripting/lua-bindings/auto/api/ScrollView.lua @@ -1,7 +1,7 @@ -------------------------------- -- @module ScrollView --- @extend Layout,UIScrollInterface, +-- @extend Layout,UIScrollInterface -------------------------------- -- @function [parent=#ScrollView] scrollToTop diff --git a/cocos/scripting/lua-bindings/auto/api/Skeleton.lua b/cocos/scripting/lua-bindings/auto/api/Skeleton.lua index 6037658be9..0d92f2c0b0 100644 --- a/cocos/scripting/lua-bindings/auto/api/Skeleton.lua +++ b/cocos/scripting/lua-bindings/auto/api/Skeleton.lua @@ -1,7 +1,7 @@ -------------------------------- -- @module Skeleton --- @extend Node,BlendProtocol, +-- @extend Node,BlendProtocol -------------------------------- -- @function [parent=#Skeleton] setToSetupPose diff --git a/cocos/scripting/lua-bindings/auto/api/Sprite.lua b/cocos/scripting/lua-bindings/auto/api/Sprite.lua index a08c3271d1..0fffcc711e 100644 --- a/cocos/scripting/lua-bindings/auto/api/Sprite.lua +++ b/cocos/scripting/lua-bindings/auto/api/Sprite.lua @@ -1,7 +1,7 @@ -------------------------------- -- @module Sprite --- @extend Node,TextureProtocol, +-- @extend Node,TextureProtocol -------------------------------- -- overload function: setSpriteFrame(cc.SpriteFrame) diff --git a/cocos/scripting/lua-bindings/auto/api/SpriteBatchNode.lua b/cocos/scripting/lua-bindings/auto/api/SpriteBatchNode.lua index dc1429b7e0..2a7a74fef6 100644 --- a/cocos/scripting/lua-bindings/auto/api/SpriteBatchNode.lua +++ b/cocos/scripting/lua-bindings/auto/api/SpriteBatchNode.lua @@ -1,7 +1,7 @@ -------------------------------- -- @module SpriteBatchNode --- @extend Node,TextureProtocol, +-- @extend Node,TextureProtocol -------------------------------- -- @function [parent=#SpriteBatchNode] appendChild diff --git a/cocos/scripting/lua-bindings/auto/api/TableView.lua b/cocos/scripting/lua-bindings/auto/api/TableView.lua index 07e8ca642a..59e66bb3c7 100644 --- a/cocos/scripting/lua-bindings/auto/api/TableView.lua +++ b/cocos/scripting/lua-bindings/auto/api/TableView.lua @@ -1,7 +1,7 @@ -------------------------------- -- @module TableView --- @extend ScrollView,ScrollViewDelegate, +-- @extend ScrollView,ScrollViewDelegate -------------------------------- -- @function [parent=#TableView] updateCellAtIndex diff --git a/cocos/scripting/lua-bindings/auto/api/TextureData.lua b/cocos/scripting/lua-bindings/auto/api/TextureData.lua index 5b21e3b26d..a464247efd 100644 --- a/cocos/scripting/lua-bindings/auto/api/TextureData.lua +++ b/cocos/scripting/lua-bindings/auto/api/TextureData.lua @@ -1,6 +1,7 @@ -------------------------------- -- @module TextureData +-- @extend Ref -------------------------------- -- @function [parent=#TextureData] getContourData diff --git a/cocos/scripting/lua-bindings/auto/api/TransitionFadeTR.lua b/cocos/scripting/lua-bindings/auto/api/TransitionFadeTR.lua index 59744392bc..6f582c7fa1 100644 --- a/cocos/scripting/lua-bindings/auto/api/TransitionFadeTR.lua +++ b/cocos/scripting/lua-bindings/auto/api/TransitionFadeTR.lua @@ -1,7 +1,7 @@ -------------------------------- -- @module TransitionFadeTR --- @extend TransitionScene,TransitionEaseScene, +-- @extend TransitionScene,TransitionEaseScene -------------------------------- -- @function [parent=#TransitionFadeTR] easeActionWithAction diff --git a/cocos/scripting/lua-bindings/auto/api/TransitionMoveInL.lua b/cocos/scripting/lua-bindings/auto/api/TransitionMoveInL.lua index c5477217df..e840b322ac 100644 --- a/cocos/scripting/lua-bindings/auto/api/TransitionMoveInL.lua +++ b/cocos/scripting/lua-bindings/auto/api/TransitionMoveInL.lua @@ -1,7 +1,7 @@ -------------------------------- -- @module TransitionMoveInL --- @extend TransitionScene,TransitionEaseScene, +-- @extend TransitionScene,TransitionEaseScene -------------------------------- -- @function [parent=#TransitionMoveInL] action diff --git a/cocos/scripting/lua-bindings/auto/api/TransitionShrinkGrow.lua b/cocos/scripting/lua-bindings/auto/api/TransitionShrinkGrow.lua index db992667ee..8bc1092aab 100644 --- a/cocos/scripting/lua-bindings/auto/api/TransitionShrinkGrow.lua +++ b/cocos/scripting/lua-bindings/auto/api/TransitionShrinkGrow.lua @@ -1,7 +1,7 @@ -------------------------------- -- @module TransitionShrinkGrow --- @extend TransitionScene,TransitionEaseScene, +-- @extend TransitionScene,TransitionEaseScene -------------------------------- -- @function [parent=#TransitionShrinkGrow] easeActionWithAction diff --git a/cocos/scripting/lua-bindings/auto/api/TransitionSlideInL.lua b/cocos/scripting/lua-bindings/auto/api/TransitionSlideInL.lua index 1cccd6b89b..b6a91016b8 100644 --- a/cocos/scripting/lua-bindings/auto/api/TransitionSlideInL.lua +++ b/cocos/scripting/lua-bindings/auto/api/TransitionSlideInL.lua @@ -1,7 +1,7 @@ -------------------------------- -- @module TransitionSlideInL --- @extend TransitionScene,TransitionEaseScene, +-- @extend TransitionScene,TransitionEaseScene -------------------------------- -- @function [parent=#TransitionSlideInL] action diff --git a/cocos/scripting/lua-bindings/auto/api/TransitionSplitCols.lua b/cocos/scripting/lua-bindings/auto/api/TransitionSplitCols.lua index c4b181288a..f766781989 100644 --- a/cocos/scripting/lua-bindings/auto/api/TransitionSplitCols.lua +++ b/cocos/scripting/lua-bindings/auto/api/TransitionSplitCols.lua @@ -1,7 +1,7 @@ -------------------------------- -- @module TransitionSplitCols --- @extend TransitionScene,TransitionEaseScene, +-- @extend TransitionScene,TransitionEaseScene -------------------------------- -- @function [parent=#TransitionSplitCols] action diff --git a/cocos/scripting/lua-bindings/auto/api/TransitionTurnOffTiles.lua b/cocos/scripting/lua-bindings/auto/api/TransitionTurnOffTiles.lua index 13a684a494..55ed83be61 100644 --- a/cocos/scripting/lua-bindings/auto/api/TransitionTurnOffTiles.lua +++ b/cocos/scripting/lua-bindings/auto/api/TransitionTurnOffTiles.lua @@ -1,7 +1,7 @@ -------------------------------- -- @module TransitionTurnOffTiles --- @extend TransitionScene,TransitionEaseScene, +-- @extend TransitionScene,TransitionEaseScene -------------------------------- -- @function [parent=#TransitionTurnOffTiles] easeActionWithAction diff --git a/cocos/scripting/lua-bindings/auto/api/Tween.lua b/cocos/scripting/lua-bindings/auto/api/Tween.lua index 249559b14f..268085092d 100644 --- a/cocos/scripting/lua-bindings/auto/api/Tween.lua +++ b/cocos/scripting/lua-bindings/auto/api/Tween.lua @@ -1,6 +1,7 @@ -------------------------------- -- @module Tween +-- @extend ProcessBase -------------------------------- -- @function [parent=#Tween] getAnimation diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_extension_auto.cpp.REMOVED.git-id b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_extension_auto.cpp.REMOVED.git-id index 399ed60da1..599ec47f51 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_extension_auto.cpp.REMOVED.git-id +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_extension_auto.cpp.REMOVED.git-id @@ -1 +1 @@ -28a6a3c5097941a6602ffedccf4d2a82f5b53389 \ No newline at end of file +cfd5546826cceb88f4a37396516b6863abb122c6 \ No newline at end of file diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.cpp.REMOVED.git-id b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.cpp.REMOVED.git-id index bcd5a80a5a..3b4b93f298 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.cpp.REMOVED.git-id +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.cpp.REMOVED.git-id @@ -1 +1 @@ -0a46232432ba108d165f69ca9435f3ae0e911a27 \ No newline at end of file +8e3775605af6999dbbb0a7535b329c78366dba89 \ No newline at end of file diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp.REMOVED.git-id b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp.REMOVED.git-id index e024e99b59..96b25dd5ca 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp.REMOVED.git-id +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp.REMOVED.git-id @@ -1 +1 @@ -19adb2eb5a08b20b670b77975f7e30c08bbac2d6 \ No newline at end of file +4fac42101ef2fb9622f22ccabc18c918622908ad \ No newline at end of file From fa91bf116784584d2f14924099965dc2fcdbcb95 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Wed, 26 Mar 2014 14:11:40 +0800 Subject: [PATCH 092/106] remove unused code and fixed warning. --- cocos/2d/CCTexture2D.cpp | 7 ++--- .../org/cocos2dx/lib/Cocos2dxActivity.java | 8 ++---- .../src/org/cocos2dx/lib/Cocos2dxBitmap.java | 28 +++---------------- .../cocos2dx/lib/Cocos2dxEditBoxDialog.java | 4 +-- .../org/cocos2dx/lib/Cocos2dxEditText.java | 1 - .../cocos2dx/lib/Cocos2dxGLSurfaceView.java | 6 ++-- .../src/org/cocos2dx/lib/Cocos2dxHelper.java | 2 -- .../cocos2dx/lib/Cocos2dxTextInputWraper.java | 1 - cocos/2d/platform/ios/CCDevice.mm | 24 +--------------- 9 files changed, 15 insertions(+), 66 deletions(-) diff --git a/cocos/2d/CCTexture2D.cpp b/cocos/2d/CCTexture2D.cpp index f5c85f43a9..f79bbe10b3 100644 --- a/cocos/2d/CCTexture2D.cpp +++ b/cocos/2d/CCTexture2D.cpp @@ -1072,9 +1072,7 @@ bool Texture2D::initWithString(const char *text, const FontDefinition& textDefin } #if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) && (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) - bool requestUnsupported = textDefinition._shadow._shadowEnabled || textDefinition._stroke._strokeEnabled; - - CCASSERT(requestUnsupported == false, "Currently shadow and stroke only supported on iOS and Android!"); + CCASSERT(textDefinition._stroke._strokeEnabled == false, "Currently stroke only supported on iOS and Android!"); #endif PixelFormat pixelFormat = g_defaultAlphaPixelFormat; @@ -1089,8 +1087,7 @@ bool Texture2D::initWithString(const char *text, const FontDefinition& textDefin textDef._dimensions.width *= contentScaleFactor; textDef._dimensions.height *= contentScaleFactor; textDef._stroke._strokeSize *= contentScaleFactor; - textDef._shadow._shadowOffset.width *= contentScaleFactor; - textDef._shadow._shadowOffset.height *= contentScaleFactor; + textDef._shadow._shadowEnabled = false; Data outData = Device::getTextureDataForText(text,textDef,align,imageWidth,imageHeight); if(outData.isNull()) diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java index 445fe2875d..8193538ae3 100644 --- a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java +++ b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java @@ -36,8 +36,6 @@ import android.view.ViewGroup; import android.util.Log; import android.widget.FrameLayout; -import java.io.File; - public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelperListener { // =========================================================== // Constants @@ -138,14 +136,14 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe // FrameLayout ViewGroup.LayoutParams framelayout_params = - new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, - ViewGroup.LayoutParams.FILL_PARENT); + new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.MATCH_PARENT); FrameLayout framelayout = new FrameLayout(this); framelayout.setLayoutParams(framelayout_params); // Cocos2dxEditText layout ViewGroup.LayoutParams edittext_layout_params = - new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, + new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); Cocos2dxEditText edittext = new Cocos2dxEditText(this); edittext.setLayoutParams(edittext_layout_params); diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxBitmap.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxBitmap.java index fd32a0682b..b110922c74 100644 --- a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxBitmap.java +++ b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxBitmap.java @@ -39,7 +39,6 @@ import android.graphics.Rect; import android.graphics.Typeface; import android.text.TextPaint; import android.text.TextUtils; -import android.util.FloatMath; import android.util.Log; public class Cocos2dxBitmap { @@ -119,7 +118,7 @@ public class Cocos2dxBitmap { */ if(0 != width) { - final int firstWordWidth = (int) FloatMath.ceil(paint.measureText(string, 0,1)); + final int firstWordWidth = (int) Math.ceil(paint.measureText(string, 0,1)); if ( firstWordWidth > width) { Log.w("createTextBitmapShadowStroke warning:","the input width is less than the width of the pString's first word\n"); @@ -140,25 +139,6 @@ public class Cocos2dxBitmap { float renderTextDeltaX = 0.0f; float renderTextDeltaY = 0.0f; - if ( shadow ) { - - int shadowColor = ((int)(255 * shadowOpacity) & 0xff) << 24; - paint.setShadowLayer(shadowBlur, shadowDX, shadowDY, shadowColor); - - bitmapPaddingX = Math.abs(shadowDX); - bitmapPaddingY = Math.abs(shadowDY); - - if ( shadowDX < 0.0 ) - { - renderTextDeltaX = bitmapPaddingX; - } - - if ( shadowDY < 0.0 ) - { - renderTextDeltaY = bitmapPaddingY; - } - } - if (0 == textProperty.mMaxWidth || 0 == bitmapTotalHeight) { Log.w("createTextBitmapShadowStroke warning:","textProperty MaxWidth is 0 or bitMapTotalHeight is 0\n"); @@ -272,7 +252,7 @@ public class Cocos2dxBitmap { /* Compute the max width. */ int temp = 0; for (final String line : lines) { - temp = (int) FloatMath.ceil(paint.measureText(line, 0, + temp = (int) Math.ceil(paint.measureText(line, 0, line.length())); if (temp > maxContentWidth) { maxContentWidth = temp; @@ -346,7 +326,7 @@ public class Cocos2dxBitmap { * The width of line is exceed maxWidth, should divide it into * two or more lines. */ - final int lineWidth = (int) FloatMath.ceil(paint + final int lineWidth = (int) Math.ceil(paint .measureText(line)); if (lineWidth > maxWidth) { strList.addAll(Cocos2dxBitmap.divideStringWithMaxWidth( @@ -394,7 +374,7 @@ public class Cocos2dxBitmap { /* Break a String into String[] by the width & should wrap the word. */ for (int i = 1; i <= charLength; ++i) { - tempWidth = (int) FloatMath.ceil(paint.measureText(string, start, + tempWidth = (int) Math.ceil(paint.measureText(string, start, i)); if (tempWidth >= maxWidth) { final int lastIndexOfSpace = string.substring(0, i) diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java index afebee4260..cf153ce623 100644 --- a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java +++ b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxDialog.java @@ -157,7 +157,7 @@ public class Cocos2dxEditBoxDialog extends Dialog { final LinearLayout layout = new LinearLayout(this.getContext()); layout.setOrientation(LinearLayout.VERTICAL); - final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT); + final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); this.mTextViewTitle = new TextView(this.getContext()); final LinearLayout.LayoutParams textviewParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); @@ -166,7 +166,7 @@ public class Cocos2dxEditBoxDialog extends Dialog { layout.addView(this.mTextViewTitle, textviewParams); this.mInputEditText = new EditText(this.getContext()); - final LinearLayout.LayoutParams editTextParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); + final LinearLayout.LayoutParams editTextParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); editTextParams.leftMargin = editTextParams.rightMargin = this.convertDipsToPixels(10); layout.addView(this.mInputEditText, editTextParams); diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditText.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditText.java index 77a40bb053..1702a8cd1d 100644 --- a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditText.java +++ b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditText.java @@ -24,7 +24,6 @@ THE SOFTWARE. ****************************************************************************/ package org.cocos2dx.lib; -import android.app.Activity; import android.content.Context; import android.util.AttributeSet; import android.view.KeyEvent; diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java index 28a16a1dd0..47d6a48120 100644 --- a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java +++ b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java @@ -195,7 +195,7 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView { switch (pMotionEvent.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_POINTER_DOWN: - final int indexPointerDown = pMotionEvent.getAction() >> MotionEvent.ACTION_POINTER_ID_SHIFT; + final int indexPointerDown = pMotionEvent.getAction() >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; final int idPointerDown = pMotionEvent.getPointerId(indexPointerDown); final float xPointerDown = pMotionEvent.getX(indexPointerDown); final float yPointerDown = pMotionEvent.getY(indexPointerDown); @@ -232,7 +232,7 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView { break; case MotionEvent.ACTION_POINTER_UP: - final int indexPointUp = pMotionEvent.getAction() >> MotionEvent.ACTION_POINTER_ID_SHIFT; + final int indexPointUp = pMotionEvent.getAction() >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; final int idPointerUp = pMotionEvent.getPointerId(indexPointUp); final float xPointerUp = pMotionEvent.getX(indexPointUp); final float yPointerUp = pMotionEvent.getY(indexPointUp); @@ -351,7 +351,7 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView { final int actionCode = action & MotionEvent.ACTION_MASK; sb.append("event ACTION_").append(names[actionCode]); if (actionCode == MotionEvent.ACTION_POINTER_DOWN || actionCode == MotionEvent.ACTION_POINTER_UP) { - sb.append("(pid ").append(action >> MotionEvent.ACTION_POINTER_ID_SHIFT); + sb.append("(pid ").append(action >> MotionEvent.ACTION_POINTER_INDEX_SHIFT); sb.append(")"); } sb.append("["); diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java index a835119f02..56de5c9775 100644 --- a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java +++ b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java @@ -30,9 +30,7 @@ import java.util.Locale; import java.lang.Runnable; import android.app.Activity; -import android.app.AlertDialog; import android.content.Context; -import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxTextInputWraper.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxTextInputWraper.java index 654cf758be..bbf2a038a7 100644 --- a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxTextInputWraper.java +++ b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxTextInputWraper.java @@ -26,7 +26,6 @@ package org.cocos2dx.lib; import android.content.Context; import android.text.Editable; import android.text.TextWatcher; -import android.util.Log; import android.view.KeyEvent; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; diff --git a/cocos/2d/platform/ios/CCDevice.mm b/cocos/2d/platform/ios/CCDevice.mm index a2ff8e64c6..1529750760 100644 --- a/cocos/2d/platform/ios/CCDevice.mm +++ b/cocos/2d/platform/ios/CCDevice.mm @@ -315,12 +315,6 @@ static bool _initWithString(const char * text, cocos2d::Device::TextAlign align, shadowStrokePaddingY = ceilf(info->strokeSize); } - if ( info->hasShadow ) - { - shadowStrokePaddingX = std::max(shadowStrokePaddingX, (float)fabs(info->shadowOffset.width)); - shadowStrokePaddingY = std::max(shadowStrokePaddingY, (float)fabs(info->shadowOffset.height)); - } - // add the padding (this could be 0 if no shadow and no stroke) dim.width += shadowStrokePaddingX*2; dim.height += shadowStrokePaddingY*2; @@ -359,26 +353,10 @@ static bool _initWithString(const char * text, cocos2d::Device::TextAlign align, NSTextAlignment nsAlign = (2 == uHoriFlag) ? NSTextAlignmentRight : (3 == uHoriFlag) ? NSTextAlignmentCenter : NSTextAlignmentLeft; - - - // take care of shadow if needed - if ( info->hasShadow ) - { - CGSize offset; - offset.height = info->shadowOffset.height; - offset.width = info->shadowOffset.width; - CGFloat shadowColorValues[] = {0, 0, 0, info->shadowOpacity}; - CGColorRef shadowColor = CGColorCreate (colorSpace, shadowColorValues); - - CGContextSetShadowWithColor(context, offset, info->shadowBlur, shadowColor); - - CGColorRelease (shadowColor); - } + CGColorSpaceRelease(colorSpace); - - // compute the rect used for rendering the text // based on wether shadows or stroke are enabled From 640a82c2ab5da01ececbaebcdc8340d4fd42df0b Mon Sep 17 00:00:00 2001 From: lm Date: Wed, 26 Mar 2014 14:29:53 +0800 Subject: [PATCH 093/106] [Jenkins] Make build as failed when git fetch is failed --- tools/jenkins-scripts/pull-request-builder.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tools/jenkins-scripts/pull-request-builder.py b/tools/jenkins-scripts/pull-request-builder.py index 270dd2e8ed..c9d753bffe 100755 --- a/tools/jenkins-scripts/pull-request-builder.py +++ b/tools/jenkins-scripts/pull-request-builder.py @@ -83,7 +83,9 @@ def main(): os.system("git clean -xdf -f") #fetch pull request to local repo git_fetch_pr = "git fetch origin pull/" + str(pr_num) + "/merge" - os.system(git_fetch_pr) + ret = os.system(git_fetch_pr) + if(ret != 0): + return(1) #checkout git_checkout = "git checkout -b " + "pull" + str(pr_num) + " FETCH_HEAD" From 57d8f155df9716dd1ec9060e021e70ccca16c43f Mon Sep 17 00:00:00 2001 From: andyque Date: Wed, 26 Mar 2014 14:54:50 +0800 Subject: [PATCH 094/106] issue #4401. resolve conflicts --- cocos/2d/CCNode.h | 4 +- cocos/2d/CCProfiling.cpp | 5 +-- cocos/2d/CCScriptSupport.cpp | 25 ++++------- cocos/2d/ccCArray.cpp | 6 +-- cocos/2d/ccCArray.h | 6 +-- cocos/2d/ccGLStateCache.cpp | 9 ++-- cocos/ui/GUIDefine.h | 18 +++----- .../CCControlExtension/CCControlStepper.cpp | 11 ++--- .../Classes/ActionsTest/ActionsTest.cpp | 25 ++++------- .../ClippingNodeTest/ClippingNodeTest.cpp | 43 ++++++------------- .../CustomImageTest/CustomImageTest.cpp | 16 +++---- .../CustomParticleWidgetTest.cpp | 16 +++---- .../Classes/FileUtilsTest/FileUtilsTest.cpp | 24 +++-------- .../cpp-tests/Classes/LayerTest/LayerTest.cpp | 6 +-- tests/lua-tests/src/LayerTest/LayerTest.lua | 4 +- 15 files changed, 70 insertions(+), 148 deletions(-) diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index 52d9d19c95..8ed0a06032 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -1458,9 +1458,7 @@ private: CC_DISALLOW_COPY_AND_ASSIGN(Node); }; -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -//#pragma mark - NodeRGBA -#endif +// NodeRGBA /** NodeRGBA is a subclass of Node that implements the RGBAProtocol protocol. diff --git a/cocos/2d/CCProfiling.cpp b/cocos/2d/CCProfiling.cpp index 11ee529ce6..cea6852876 100644 --- a/cocos/2d/CCProfiling.cpp +++ b/cocos/2d/CCProfiling.cpp @@ -31,10 +31,7 @@ using namespace std; NS_CC_BEGIN -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -//#pragma mark - Profiling Categories -#endif - +// Profiling Categories /* set to false the categories that you don't want to profile */ bool kProfilerCategorySprite = false; bool kProfilerCategoryBatchSprite = false; diff --git a/cocos/2d/CCScriptSupport.cpp b/cocos/2d/CCScriptSupport.cpp index ccc8ed48a5..5dfa69913e 100644 --- a/cocos/2d/CCScriptSupport.cpp +++ b/cocos/2d/CCScriptSupport.cpp @@ -41,10 +41,8 @@ bool CC_DLL cc_assert_script_compatible(const char *msg) NS_CC_BEGIN -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -// #pragma mark - -// #pragma mark ScriptHandlerEntry -#endif +// +// // ScriptHandlerEntry ScriptHandlerEntry* ScriptHandlerEntry::create(int handler) { @@ -63,10 +61,8 @@ ScriptHandlerEntry::~ScriptHandlerEntry(void) } } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -// #pragma mark - -// #pragma mark SchedulerScriptHandlerEntry -#endif +// +// // SchedulerScriptHandlerEntry SchedulerScriptHandlerEntry* SchedulerScriptHandlerEntry::create(int handler, float interval, bool paused) { @@ -91,10 +87,9 @@ SchedulerScriptHandlerEntry::~SchedulerScriptHandlerEntry(void) LUALOG("[LUA] DEL script schedule %d, entryID: %d", _handler, _entryId); } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -// #pragma mark - -// #pragma mark TouchScriptHandlerEntry -#endif + +// +// // TouchScriptHandlerEntry TouchScriptHandlerEntry* TouchScriptHandlerEntry::create(int handler, bool isMultiTouches, @@ -120,10 +115,8 @@ bool TouchScriptHandlerEntry::init(bool isMultiTouches, int priority, bool swall return true; } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -// #pragma mark - -// #pragma mark ScriptEngineManager -#endif +// +// // ScriptEngineManager static ScriptEngineManager* s_pSharedScriptEngineManager = nullptr; diff --git a/cocos/2d/ccCArray.cpp b/cocos/2d/ccCArray.cpp index a25a636239..c73a0ced26 100644 --- a/cocos/2d/ccCArray.cpp +++ b/cocos/2d/ccCArray.cpp @@ -278,10 +278,8 @@ void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr) arr->num -= back; } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -// #pragma mark - -// #pragma mark ccCArray for Values (c structures) -#endif +// +// // ccCArray for Values (c structures) /** Allocates and initializes a new C array with specified capacity */ ccCArray* ccCArrayNew(ssize_t capacity) diff --git a/cocos/2d/ccCArray.h b/cocos/2d/ccCArray.h index 0529d83ac3..a40f696d79 100644 --- a/cocos/2d/ccCArray.h +++ b/cocos/2d/ccCArray.h @@ -130,10 +130,8 @@ void ccArrayRemoveArray(ccArray *arr, ccArray *minusArr); matching instances in arr will be removed. */ void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr); -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -// #pragma mark - -// #pragma mark ccCArray for Values (c structures) -#endif +// +// // ccCArray for Values (c structures) typedef struct _ccCArray { ssize_t num, max; diff --git a/cocos/2d/ccGLStateCache.cpp b/cocos/2d/ccGLStateCache.cpp index cb0c5bc56c..987f30b709 100644 --- a/cocos/2d/ccGLStateCache.cpp +++ b/cocos/2d/ccGLStateCache.cpp @@ -217,9 +217,7 @@ void bindVAO(GLuint vaoId) } } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -//#pragma mark - GL Vertex Attrib functions -#endif +// GL Vertex Attrib functions void enableVertexAttribs( unsigned int flags ) { @@ -262,9 +260,8 @@ void enableVertexAttribs( unsigned int flags ) } } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -//#pragma mark - GL Uniforms functions -#endif +// GL Uniforms functions + void setProjectionMatrixDirty( void ) { s_currentProjectionMatrix = -1; diff --git a/cocos/ui/GUIDefine.h b/cocos/ui/GUIDefine.h index 59d36a0b34..58fd787fbc 100644 --- a/cocos/ui/GUIDefine.h +++ b/cocos/ui/GUIDefine.h @@ -30,12 +30,9 @@ #include #include "cocostudio/ObjectFactory.h" -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -#pragma mark - -#pragma mark Widget macro -#pragma mark - -#endif - +// +//// Widget macro +// #define DECLARE_CLASS_GUI_INFO \ public: \ @@ -53,12 +50,9 @@ cocostudio::ObjectFactory::TInfo(#className, &className::createInstance) \ -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -#pragma mark - -#pragma mark Reader macro -#pragma mark - -#endif - +// +//// Reader macro +// #define DECLARE_CLASS_WIDGET_READER_INFO \ public: \ diff --git a/extensions/GUI/CCControlExtension/CCControlStepper.cpp b/extensions/GUI/CCControlExtension/CCControlStepper.cpp index 099b02bcc2..f299cc0bc9 100644 --- a/extensions/GUI/CCControlExtension/CCControlStepper.cpp +++ b/extensions/GUI/CCControlExtension/CCControlStepper.cpp @@ -129,7 +129,7 @@ ControlStepper* ControlStepper::create(Sprite *minusSprite, Sprite *plusSprite) return pRet; } -//#pragma mark Properties +//// Properties void ControlStepper::setWraps(bool wraps) { @@ -190,11 +190,8 @@ bool ControlStepper::isContinuous() const { return _continuous; } - -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -//#pragma mark - -//#pragma mark ControlStepper Public Methods -#endif +// +//// ControlStepper Public Methods void ControlStepper::setValueWithSendingEvent(double value, bool send) { @@ -249,7 +246,7 @@ void ControlStepper::update(float dt) } } -//#pragma mark ControlStepper Private Methods +//// ControlStepper Private Methods void ControlStepper::updateLayoutUsingTouchLocation(Point location) { diff --git a/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp b/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp index fbf786ec22..a33e36c76a 100644 --- a/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp +++ b/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp @@ -1432,9 +1432,7 @@ std::string ActionTargetedReverse::subtitle() const return "Action that runs reversely on another target. Useful for sequences"; } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -//#pragma mark - ActionStacked -#endif +// ActionStacked void ActionStacked::onEnter() { @@ -1488,9 +1486,8 @@ std::string ActionStacked::subtitle() const return "Tap screen"; } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -//#pragma mark - ActionMoveStacked -#endif +// ActionMoveStacked + void ActionMoveStacked::runActionsInSprite(Sprite *sprite) { @@ -1516,9 +1513,7 @@ std::string ActionMoveStacked::title() const return "Stacked MoveBy/To actions"; } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -//#pragma mark - ActionMoveJumpStacked -#endif +// ActionMoveJumpStacked void ActionMoveJumpStacked::runActionsInSprite(Sprite *sprite) { @@ -1543,9 +1538,7 @@ std::string ActionMoveJumpStacked::title() const return "tacked Move + Jump actions"; } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -//#pragma mark - ActionMoveBezierStacked -#endif +// ActionMoveBezierStacked void ActionMoveBezierStacked::runActionsInSprite(Sprite *sprite) { @@ -1577,7 +1570,7 @@ std::string ActionMoveBezierStacked::title() const } -//#pragma mark - ActionCatmullRomStacked +// ActionCatmullRomStacked void ActionCatmullRomStacked::onEnter() { @@ -1699,9 +1692,7 @@ std::string ActionCatmullRomStacked::subtitle() const } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -//#pragma mark - ActionCardinalSplineStacked -#endif +// ActionCardinalSplineStacked void ActionCardinalSplineStacked::onEnter() { @@ -2354,4 +2345,4 @@ void ActionRemoveSelf::onEnter() std::string ActionRemoveSelf::subtitle() const { return "Sequence: Move + Rotate + Scale + RemoveSelf"; -} +i diff --git a/tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.cpp b/tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.cpp index 301e397be1..dd76d1c4e1 100644 --- a/tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.cpp +++ b/tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.cpp @@ -66,7 +66,7 @@ static Layer* restartAction() return layer; } -//#pragma mark Demo examples start here +//// Demo examples start here //@implementation BaseClippingNodeTest @@ -130,9 +130,7 @@ void BaseClippingNodeTest::setup() } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -//#pragma mark - BasicTest -#endif +// BasicTest std::string BasicTest::title() const { @@ -211,9 +209,7 @@ Node* BasicTest::content() } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -//#pragma mark - ShapeTest -#endif +// ShapeTest std::string ShapeTest::title() const { @@ -239,9 +235,8 @@ Node* ShapeTest::content() return node; } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -//#pragma mark - ShapeInvertedTest -#endif + +// ShapeInvertedTest std::string ShapeInvertedTest::title() const { @@ -260,9 +255,7 @@ ClippingNode* ShapeInvertedTest::clipper() return clipper; } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -//#pragma mark - SpriteTest -#endif +// SpriteTest std::string SpriteTest::title() const { @@ -295,9 +288,7 @@ Node* SpriteTest::content() return node; } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -//#pragma mark - SpriteNoAlphaTest -#endif +// SpriteNoAlphaTest std::string SpriteNoAlphaTest::title() const { @@ -316,9 +307,7 @@ ClippingNode* SpriteNoAlphaTest::clipper() return clipper; } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -//#pragma mark - SpriteInvertedTest -#endif +// SpriteInvertedTest std::string SpriteInvertedTest::title() const { @@ -338,9 +327,7 @@ ClippingNode* SpriteInvertedTest::clipper() return clipper; } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -//#pragma mark - NestedTest -#endif +// NestedTest std::string NestedTest::title() const { @@ -385,9 +372,7 @@ void NestedTest::setup() } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -//#pragma mark - HoleDemo -#endif +// HoleDemo HoleDemo::~HoleDemo() { @@ -482,9 +467,7 @@ void HoleDemo::onTouchesBegan(const std::vector& touches, Event* event) this->pokeHoleAtPoint(point); } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -//#pragma mark - ScrollViewDemo -#endif +// ScrollViewDemo std::string ScrollViewDemo::title() const { @@ -560,9 +543,7 @@ void ScrollViewDemo::onTouchesEnded(const std::vector& touches, Event * _scrolling = false; } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -//#pragma mark - RawStencilBufferTests -#endif +// RawStencilBufferTests //#if COCOS2D_DEBUG > 1 diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/CustomTest/CustomImageTest/CustomImageTest.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/CustomTest/CustomImageTest/CustomImageTest.cpp index e32efbf736..f44298c9e4 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/CustomTest/CustomImageTest/CustomImageTest.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/CustomTest/CustomImageTest/CustomImageTest.cpp @@ -10,11 +10,9 @@ USING_NS_CC; USING_NS_CC_EXT; -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -#pragma mark - -#pragma mark CustomImageLayer -#pragma mark - -#endif + +// CustomImageLayer + void CustomImageLayer::onEnter() { @@ -30,11 +28,9 @@ void CustomImageLayer::onEnter() addChild(layout); } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -#pragma mark - -#pragma mark CustomImageScene -#pragma mark - -#endif + +// CustomImageScene + void CustomImageScene::onEnter() { diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/CustomTest/CustomParticleWidgetTest/CustomParticleWidgetTest.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/CustomTest/CustomParticleWidgetTest/CustomParticleWidgetTest.cpp index ae956b8097..b40b72167c 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/CustomTest/CustomParticleWidgetTest/CustomParticleWidgetTest.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioGUITest/CustomTest/CustomParticleWidgetTest/CustomParticleWidgetTest.cpp @@ -18,11 +18,9 @@ USING_NS_CC_EXT; using namespace ui; using namespace cocostudio; -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -#pragma mark - -#pragma mark CustomParticleWidgetLayer -#pragma mark - -#endif + +// CustomParticleWidgetLayer + void CustomParticleWidgetLayer::onEnter() { @@ -40,11 +38,9 @@ void CustomParticleWidgetLayer::onEnter() addChild(custom, 10, -1); } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -#pragma mark - -#pragma mark CustomImageScene -#pragma mark - -#endif + +// CustomImageScene + void CustomParticleWidgetScene::onEnter() { diff --git a/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp b/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp index 856350b2e7..b3a2aff200 100644 --- a/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp +++ b/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp @@ -45,9 +45,7 @@ void FileUtilsTestScene::runThisTest() Director::getInstance()->replaceScene(this); } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -// #pragma mark - FileUtilsDemo -#endif +// FileUtilsDemo void FileUtilsDemo::onEnter() { @@ -94,9 +92,7 @@ std::string FileUtilsDemo::subtitle() const return ""; } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -//#pragma mark - TestResolutionDirectories -#endif +// TestResolutionDirectories void TestResolutionDirectories::onEnter() { @@ -150,9 +146,7 @@ std::string TestResolutionDirectories::subtitle() const return "See the console"; } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -//#pragma mark - TestSearchPath -#endif +// TestSearchPath void TestSearchPath::onEnter() { @@ -231,9 +225,7 @@ std::string TestSearchPath::subtitle() const return "See the console"; } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -//#pragma mark - TestFilenameLookup -#endif +// TestFilenameLookup void TestFilenameLookup::onEnter() { @@ -271,9 +263,7 @@ std::string TestFilenameLookup::title() const return "FileUtils: filename lookup"; } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -//#pragma mark - TestIsFileExist -#endif +// TestIsFileExist void TestIsFileExist::onEnter() { @@ -317,9 +307,7 @@ std::string TestIsFileExist::subtitle() const return ""; } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -//#pragma mark - TestWritePlist -#endif +// TestWritePlist void TextWritePlist::onEnter() { diff --git a/tests/cpp-tests/Classes/LayerTest/LayerTest.cpp b/tests/cpp-tests/Classes/LayerTest/LayerTest.cpp index a3c82737c8..8087e7e9e1 100644 --- a/tests/cpp-tests/Classes/LayerTest/LayerTest.cpp +++ b/tests/cpp-tests/Classes/LayerTest/LayerTest.cpp @@ -111,9 +111,7 @@ void LayerTest::backCallback(Ref* sender) s->release(); } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -//#pragma mark - Cascading support extensions -#endif +// Cascading support extensions static void setEnableRecursiveCascading(Node* node, bool enable) { @@ -277,7 +275,7 @@ std::string LayerTestCascadingOpacityC::subtitle() const } -//#pragma mark Example LayerTestCascadingColor +//// Example LayerTestCascadingColor // LayerTestCascadingColorA void LayerTestCascadingColorA::onEnter() diff --git a/tests/lua-tests/src/LayerTest/LayerTest.lua b/tests/lua-tests/src/LayerTest/LayerTest.lua index 1e360038bf..b0516e6ba0 100644 --- a/tests/lua-tests/src/LayerTest/LayerTest.lua +++ b/tests/lua-tests/src/LayerTest/LayerTest.lua @@ -32,7 +32,7 @@ local function createLayerDemoLayer(title, subtitle) return layer end ---#pragma mark - Cascading support extensions +-- Cascading support extensions local function setEnableRecursiveCascading(node, enable) if node == nil then @@ -164,7 +164,7 @@ local function LayerTestCascadingOpacityC() return ret end ---#pragma mark Example LayerTestCascadingColor +--// Example LayerTestCascadingColor -- LayerTestCascadingColorA local function LayerTestCascadingColorA() From 691442d80d1554ac88382bab8a821df04ca5402c Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 26 Mar 2014 15:04:11 +0800 Subject: [PATCH 095/106] closed #4559: Wrong behavior of multi-touch on iphone5s/ipadAir (arm64 arch) --- cocos/2d/platform/CCGLViewProtocol.cpp | 22 +++++++++++----------- cocos/2d/platform/CCGLViewProtocol.h | 10 +++++----- cocos/2d/platform/ios/CCEAGLView.mm | 8 ++++---- cocos/base/CCConsole.h | 2 +- 4 files changed, 21 insertions(+), 21 deletions(-) diff --git a/cocos/2d/platform/CCGLViewProtocol.cpp b/cocos/2d/platform/CCGLViewProtocol.cpp index fc3283ad55..a04f67a020 100644 --- a/cocos/2d/platform/CCGLViewProtocol.cpp +++ b/cocos/2d/platform/CCGLViewProtocol.cpp @@ -37,7 +37,7 @@ namespace { static Touch* g_touches[EventTouch::MAX_TOUCHES] = { nullptr }; static unsigned int g_indexBitsUsed = 0; // System touch pointer ID (It may not be ascending order number) <-> Ascending order number from 0 - static std::map g_touchIdReorderMap; + static std::map g_touchIdReorderMap; static int getUnUsedIndex() { @@ -235,9 +235,9 @@ const std::string& GLViewProtocol::getViewName() const return _viewName; } -void GLViewProtocol::handleTouchesBegin(int num, int ids[], float xs[], float ys[]) +void GLViewProtocol::handleTouchesBegin(int num, intptr_t ids[], float xs[], float ys[]) { - int id = 0; + intptr_t id = 0; float x = 0.0f; float y = 0.0f; int unusedIndex = 0; @@ -285,9 +285,9 @@ void GLViewProtocol::handleTouchesBegin(int num, int ids[], float xs[], float ys dispatcher->dispatchEvent(&touchEvent); } -void GLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys[]) +void GLViewProtocol::handleTouchesMove(int num, intptr_t ids[], float xs[], float ys[]) { - int id = 0; + intptr_t id = 0; float x = 0.0f; float y = 0.0f; EventTouch touchEvent; @@ -317,7 +317,7 @@ void GLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys[ else { // It is error, should return. - CCLOG("Moving touches with id: %d error", id); + CCLOG("Moving touches with id: %ld error", id); return; } } @@ -333,9 +333,9 @@ void GLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys[ dispatcher->dispatchEvent(&touchEvent); } -void GLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, int ids[], float xs[], float ys[]) +void GLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, intptr_t ids[], float xs[], float ys[]) { - int id = 0; + intptr_t id = 0; float x = 0.0f; float y = 0.0f; EventTouch touchEvent; @@ -370,7 +370,7 @@ void GLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, } else { - CCLOG("Ending touches with id: %d error", id); + CCLOG("Ending touches with id: %ld error", id); return; } @@ -393,12 +393,12 @@ void GLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, } } -void GLViewProtocol::handleTouchesEnd(int num, int ids[], float xs[], float ys[]) +void GLViewProtocol::handleTouchesEnd(int num, intptr_t ids[], float xs[], float ys[]) { handleTouchesOfEndOrCancel(EventTouch::EventCode::ENDED, num, ids, xs, ys); } -void GLViewProtocol::handleTouchesCancel(int num, int ids[], float xs[], float ys[]) +void GLViewProtocol::handleTouchesCancel(int num, intptr_t ids[], float xs[], float ys[]) { handleTouchesOfEndOrCancel(EventTouch::EventCode::CANCELLED, num, ids, xs, ys); } diff --git a/cocos/2d/platform/CCGLViewProtocol.h b/cocos/2d/platform/CCGLViewProtocol.h index 6fae1fc546..5b5d349db5 100644 --- a/cocos/2d/platform/CCGLViewProtocol.h +++ b/cocos/2d/platform/CCGLViewProtocol.h @@ -160,10 +160,10 @@ public: const std::string& getViewName() const; /** Touch events are handled by default; if you want to customize your handlers, please override these functions: */ - virtual void handleTouchesBegin(int num, int ids[], float xs[], float ys[]); - virtual void handleTouchesMove(int num, int ids[], float xs[], float ys[]); - virtual void handleTouchesEnd(int num, int ids[], float xs[], float ys[]); - virtual void handleTouchesCancel(int num, int ids[], float xs[], float ys[]); + virtual void handleTouchesBegin(int num, intptr_t ids[], float xs[], float ys[]); + virtual void handleTouchesMove(int num, intptr_t ids[], float xs[], float ys[]); + virtual void handleTouchesEnd(int num, intptr_t ids[], float xs[], float ys[]); + virtual void handleTouchesCancel(int num, intptr_t ids[], float xs[], float ys[]); /** * Get the opengl view port rectangle. @@ -186,7 +186,7 @@ public: protected: void updateDesignResolutionSize(); - void handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, int ids[], float xs[], float ys[]); + void handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, intptr_t ids[], float xs[], float ys[]); // real screen size Size _screenSize; diff --git a/cocos/2d/platform/ios/CCEAGLView.mm b/cocos/2d/platform/ios/CCEAGLView.mm index dcae32d0ea..7d9c4df604 100644 --- a/cocos/2d/platform/ios/CCEAGLView.mm +++ b/cocos/2d/platform/ios/CCEAGLView.mm @@ -408,7 +408,7 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. } auto glview = cocos2d::Director::getInstance()->getOpenGLView(); - glview->handleTouchesBegin(i, (int*)ids, xs, ys); + glview->handleTouchesBegin(i, (intptr_t*)ids, xs, ys); } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event @@ -430,7 +430,7 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. } auto glview = cocos2d::Director::getInstance()->getOpenGLView(); - glview->handleTouchesMove(i, (int*)ids, xs, ys); + glview->handleTouchesMove(i, (intptr_t*)ids, xs, ys); } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event @@ -453,7 +453,7 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. } auto glview = cocos2d::Director::getInstance()->getOpenGLView(); - glview->handleTouchesEnd(i, (int*)ids, xs, ys); + glview->handleTouchesEnd(i, (intptr_t*)ids, xs, ys); } - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event @@ -476,7 +476,7 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. } auto glview = cocos2d::Director::getInstance()->getOpenGLView(); - glview->handleTouchesCancel(i, (int*)ids, xs, ys); + glview->handleTouchesCancel(i, (intptr_t*)ids, xs, ys); } #pragma mark - UIView - Responder diff --git a/cocos/base/CCConsole.h b/cocos/base/CCConsole.h index 66ae38e54e..5f1794363a 100644 --- a/cocos/base/CCConsole.h +++ b/cocos/base/CCConsole.h @@ -137,7 +137,7 @@ protected: std::mutex _DebugStringsMutex; std::vector _DebugStrings; - int _touchId; + intptr_t _touchId; private: CC_DISALLOW_COPY_AND_ASSIGN(Console); }; From c1faad7e2cd9ae6f7db4f84f0222ca22fd1c1fb9 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 26 Mar 2014 15:04:45 +0800 Subject: [PATCH 096/106] Warning fixes in SocketIOTest.cpp/ FileUtilsTest.cpp. --- .../ExtensionsTest/NetworkTest/SocketIOTest.cpp | 4 ++-- .../Classes/FileUtilsTest/FileUtilsTest.cpp | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/tests/cpp-tests/Classes/ExtensionsTest/NetworkTest/SocketIOTest.cpp b/tests/cpp-tests/Classes/ExtensionsTest/NetworkTest/SocketIOTest.cpp index 54b46a2c6d..1f10001da1 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/NetworkTest/SocketIOTest.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/NetworkTest/SocketIOTest.cpp @@ -138,7 +138,7 @@ void SocketIOTestLayer::toExtensionsMainLayer(cocos2d::Ref *sender) void SocketIOTestLayer::onMenuSIOClientClicked(cocos2d::Ref *sender) { //create a client by using this static method, url does not need to contain the protocol - _sioClient = SocketIO::connect(*this, "ws://channon.us:3000"); + _sioClient = SocketIO::connect("ws://channon.us:3000", *this); //you may set a tag for the client for reference in callbacks _sioClient->setTag("Test Client"); @@ -151,7 +151,7 @@ void SocketIOTestLayer::onMenuSIOClientClicked(cocos2d::Ref *sender) void SocketIOTestLayer::onMenuSIOEndpointClicked(cocos2d::Ref *sender) { //repeat the same connection steps for the namespace "testpoint" - _sioEndpoint = SocketIO::connect(*this, "ws://channon.us:3000/testpoint"); + _sioEndpoint = SocketIO::connect("ws://channon.us:3000/testpoint", *this); //a tag to differentiate in shared callbacks _sioEndpoint->setTag("Test Endpoint"); diff --git a/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp b/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp index 140371d63f..df1a8f54c1 100644 --- a/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp +++ b/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp @@ -368,15 +368,15 @@ void TextWritePlist::onEnter() auto winSize = Director::getInstance()->getWinSize(); label->setPosition(Point(winSize.width/2, winSize.height/3)); - auto loadDict = Dictionary::createWithContentsOfFile(fullPath.c_str()); - auto loadDictInDict = (Dictionary*)loadDict->objectForKey("dictInDict, Hello World"); - auto boolValue = (String*)loadDictInDict->objectForKey("bool"); + auto loadDict = __Dictionary::createWithContentsOfFile(fullPath.c_str()); + auto loadDictInDict = (__Dictionary*)loadDict->objectForKey("dictInDict, Hello World"); + auto boolValue = (__String*)loadDictInDict->objectForKey("bool"); CCLOG("%s",boolValue->getCString()); - auto floatValue = (String*)loadDictInDict->objectForKey("float"); + auto floatValue = (__String*)loadDictInDict->objectForKey("float"); CCLOG("%s",floatValue->getCString()); - auto intValue = (String*)loadDictInDict->objectForKey("integer"); + auto intValue = (__String*)loadDictInDict->objectForKey("integer"); CCLOG("%s",intValue->getCString()); - auto doubleValue = (String*)loadDictInDict->objectForKey("double"); + auto doubleValue = (__String*)loadDictInDict->objectForKey("double"); CCLOG("%s",doubleValue->getCString()); } From 1003847cd1bb8ddd9af87388fb8c2270cbef98fc Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 26 Mar 2014 15:44:38 +0800 Subject: [PATCH 097/106] Mac build fix after merging https://github.com/cocos2d/cocos2d-x/pull/5989 --- cocos/2d/platform/desktop/CCGLView.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos/2d/platform/desktop/CCGLView.cpp b/cocos/2d/platform/desktop/CCGLView.cpp index aea8f87d8a..91d4b6e000 100644 --- a/cocos/2d/platform/desktop/CCGLView.cpp +++ b/cocos/2d/platform/desktop/CCGLView.cpp @@ -523,7 +523,7 @@ void GLView::onGLFWMouseCallBack(GLFWwindow* window, int button, int action, int _captured = true; if (this->getViewPortRect().equals(Rect::ZERO) || this->getViewPortRect().containsPoint(Point(_mouseX,_mouseY))) { - int id = 0; + intptr_t id = 0; this->handleTouchesBegin(1, &id, &_mouseX, &_mouseY); } } @@ -532,7 +532,7 @@ void GLView::onGLFWMouseCallBack(GLFWwindow* window, int button, int action, int if (_captured) { _captured = false; - int id = 0; + intptr_t id = 0; this->handleTouchesEnd(1, &id, &_mouseX, &_mouseY); } } @@ -575,7 +575,7 @@ void GLView::onGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y) if (_captured) { - int id = 0; + intptr_t id = 0; this->handleTouchesMove(1, &id, &_mouseX, &_mouseY); } From 876f643bc44fd24a2d7eb36706fc8d3f0ad652e5 Mon Sep 17 00:00:00 2001 From: andyque Date: Wed, 26 Mar 2014 16:00:55 +0800 Subject: [PATCH 098/106] issue #4401, fix a typo --- tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp b/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp index a33e36c76a..7f5a5fd1be 100644 --- a/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp +++ b/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp @@ -2345,4 +2345,4 @@ void ActionRemoveSelf::onEnter() std::string ActionRemoveSelf::subtitle() const { return "Sequence: Move + Rotate + Scale + RemoveSelf"; -i +} From faa815eee2d546e634a787a863f15e4b60102e99 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 26 Mar 2014 16:36:04 +0800 Subject: [PATCH 099/106] Update CHANGELOG [ci skip] --- CHANGELOG.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.REMOVED.git-id b/CHANGELOG.REMOVED.git-id index 1234ebc717..309aeeddfc 100644 --- a/CHANGELOG.REMOVED.git-id +++ b/CHANGELOG.REMOVED.git-id @@ -1 +1 @@ -7a4a3717b22578e2529226a4384ca423229137e7 \ No newline at end of file +059d91131441d588739301f802453f63f913f27a \ No newline at end of file From 58a61d94fb5d42006e11d3625cc3e57e1e2c959d Mon Sep 17 00:00:00 2001 From: zhangcheng Date: Wed, 26 Mar 2014 16:39:32 +0800 Subject: [PATCH 100/106] add use CCComRender as parent for attaching component --- cocos/2d/CCComponent.cpp | 6 ++ cocos/2d/CCComponent.h | 3 + cocos/2d/CCComponentContainer.cpp | 1 - .../cocostudio/CCComController.cpp | 4 ++ .../editor-support/cocostudio/CCComRender.cpp | 32 ++++++++-- .../cocostudio/CCSSceneReader.cpp | 60 +++++++++++++------ .../cocostudio/CCSSceneReader.h | 36 ++++++++--- external/chipmunk/src/cpCollision.c | 2 +- .../Classes/ActionsTest/ActionsTest.cpp | 2 +- .../EnemyController.cpp | 1 + .../PlayerController.cpp | 1 + .../ProjectileController.cpp | 1 + .../SceneController.cpp | 1 + 13 files changed, 118 insertions(+), 32 deletions(-) diff --git a/cocos/2d/CCComponent.cpp b/cocos/2d/CCComponent.cpp index 8f91cd764d..8cc22a8910 100644 --- a/cocos/2d/CCComponent.cpp +++ b/cocos/2d/CCComponent.cpp @@ -31,6 +31,7 @@ NS_CC_BEGIN Component::Component(void) : _owner(nullptr) , _enabled(true) +, _isRenderer(false) { #if CC_ENABLE_SCRIPT_BINDING ScriptEngineProtocol* engine = ScriptEngineManager::getInstance()->getScriptEngine(); @@ -152,4 +153,9 @@ void Component::setEnabled(bool b) _enabled = b; } +bool Component::isRenderer() const +{ + return _isRenderer; +} + NS_CC_END diff --git a/cocos/2d/CCComponent.h b/cocos/2d/CCComponent.h index 97d652a940..ada88ca1a0 100644 --- a/cocos/2d/CCComponent.h +++ b/cocos/2d/CCComponent.h @@ -68,10 +68,13 @@ public: void setOwner(Node *pOwner); Node* getOwner() const; + bool isRenderer() const; + protected: Node *_owner; std::string _name; bool _enabled; + bool _isRenderer; #if CC_ENABLE_SCRIPT_BINDING ccScriptType _scriptType; ///< type of script binding, lua or javascript diff --git a/cocos/2d/CCComponentContainer.cpp b/cocos/2d/CCComponentContainer.cpp index 02d0f2959d..bf97c0b9a6 100644 --- a/cocos/2d/CCComponentContainer.cpp +++ b/cocos/2d/CCComponentContainer.cpp @@ -61,7 +61,6 @@ bool ComponentContainer::add(Component *com) if (_components == nullptr) { _components = new Map(); - _owner->scheduleUpdate(); } Component *component = _components->at(com->getName()); diff --git a/cocos/editor-support/cocostudio/CCComController.cpp b/cocos/editor-support/cocostudio/CCComController.cpp index 0cba200351..c69ca0e314 100644 --- a/cocos/editor-support/cocostudio/CCComController.cpp +++ b/cocos/editor-support/cocostudio/CCComController.cpp @@ -43,6 +43,10 @@ bool ComController::init() void ComController::onEnter() { + if (_owner != nullptr) + { + _owner->scheduleUpdate(); + } } void ComController::onExit() diff --git a/cocos/editor-support/cocostudio/CCComRender.cpp b/cocos/editor-support/cocostudio/CCComRender.cpp index 29fc62c098..2a2c15c003 100644 --- a/cocos/editor-support/cocostudio/CCComRender.cpp +++ b/cocos/editor-support/cocostudio/CCComRender.cpp @@ -34,18 +34,24 @@ ComRender::ComRender(void) : _render(nullptr) { _name = "CCComRender"; + _isRenderer = true; } ComRender::ComRender(cocos2d::Node *node, const char *comName) { - _render = node; + if (node != nullptr) + { + _render = node; + _render->retain(); + } _name.assign(comName); + _isRenderer = true; } ComRender::~ComRender(void) { - _render = nullptr; + CC_SAFE_RELEASE_NULL(_render); } void ComRender::onEnter() @@ -58,7 +64,10 @@ void ComRender::onEnter() void ComRender::onExit() { - _render = nullptr; + if (_owner != nullptr) + { + _owner->removeChild(_render, true); + } } cocos2d::Node* ComRender::getNode() @@ -68,7 +77,16 @@ cocos2d::Node* ComRender::getNode() void ComRender::setNode(cocos2d::Node *node) { - _render = node; + if (_render != nullptr) + { + _render->release(); + _render = nullptr; + } + if (node != nullptr) + { + _render = node; + _render->retain(); + } } @@ -111,15 +129,18 @@ bool ComRender::serialize(void* r) if (strcmp(className, "CCSprite") == 0 && filePath.find(".png") != std::string::npos) { _render = Sprite::create(filePath.c_str()); + _render->retain(); } else if(strcmp(className, "CCTMXTiledMap") == 0 && filePath.find(".tmx") != std::string::npos) { _render = TMXTiledMap::create(filePath.c_str()); + _render->retain(); } else if(strcmp(className, "CCParticleSystemQuad") == 0 && filePath.find(".plist") != std::string::npos) { _render = ParticleSystemQuad::create(filePath.c_str()); _render->setPosition(Point(0.0f, 0.0f)); + _render->retain(); } else if(strcmp(className, "CCArmature") == 0) { @@ -141,6 +162,7 @@ bool ComRender::serialize(void* r) ArmatureDataManager::getInstance()->addArmatureFileInfo(filePath.c_str()); Armature *pAr = Armature::create(name); _render = pAr; + _render->retain(); const char *actionName = DICTOOL->getStringValue_json(*v, "selectedactionname"); if (actionName != nullptr && pAr->getAnimation() != nullptr) { @@ -151,6 +173,7 @@ bool ComRender::serialize(void* r) { cocos2d::ui::Widget* widget = GUIReader::getInstance()->widgetFromJsonFile(filePath.c_str()); _render = widget; + _render->retain(); } else { @@ -170,6 +193,7 @@ bool ComRender::serialize(void* r) strPngFile.replace(pos, strPngFile.length(), ".png"); SpriteFrameCache::getInstance()->addSpriteFramesWithFile(plistPath.c_str(), strPngFile.c_str()); _render = Sprite::createWithSpriteFrameName(filePath.c_str()); + _render->retain(); } else { diff --git a/cocos/editor-support/cocostudio/CCSSceneReader.cpp b/cocos/editor-support/cocostudio/CCSSceneReader.cpp index 9d92d25e5d..8548c4c754 100644 --- a/cocos/editor-support/cocostudio/CCSSceneReader.cpp +++ b/cocos/editor-support/cocostudio/CCSSceneReader.cpp @@ -37,6 +37,7 @@ SceneReader* SceneReader::s_sharedReader = nullptr; SceneReader::SceneReader() : _fnSelector(nullptr) , _node(nullptr) +, _attachComponent(AttachComponentType::_EmptyNode) { ObjectFactory::getInstance()->registerType(CREATE_CLASS_COMPONENT_INFO(ComAttribute)); ObjectFactory::getInstance()->registerType(CREATE_CLASS_COMPONENT_INFO(ComRender)); @@ -53,12 +54,12 @@ const char* SceneReader::sceneReaderVersion() return "1.0.0.0"; } -cocos2d::Node* SceneReader::createNodeWithSceneFile(const std::string &fileName) +cocos2d::Node* SceneReader::createNodeWithSceneFile(const std::string &fileName, AttachComponentType attachComponent /*= AttachComponentType::_EmptyNode*/) { rapidjson::Document jsonDict; do { CC_BREAK_IF(!readJson(fileName, jsonDict)); - _node = createObject(jsonDict, nullptr); + _node = createObject(jsonDict, nullptr, attachComponent); TriggerMng::getInstance()->parse(jsonDict); } while (0); @@ -110,7 +111,7 @@ Node* SceneReader::nodeByTag(Node *parent, int tag) } -Node* SceneReader::createObject(const rapidjson::Value &dict, cocos2d::Node* parent) +Node* SceneReader::createObject(const rapidjson::Value &dict, cocos2d::Node* parent, AttachComponentType attachComponent) { const char *className = DICTOOL->getStringValue_json(dict, "classname"); if(strcmp(className, "CCNode") == 0) @@ -120,14 +121,9 @@ Node* SceneReader::createObject(const rapidjson::Value &dict, cocos2d::Node* par { gb = Node::create(); } - else - { - gb = Node::create(); - parent->addChild(gb); - } - - setPropertyFromJsonDict(dict, gb); + std::vector vecComs; + ComRender *render = nullptr; int count = DICTOOL->getArrayCount_json(dict, "components"); for (int i = 0; i < count; i++) { @@ -138,23 +134,51 @@ Node* SceneReader::createObject(const rapidjson::Value &dict, cocos2d::Node* par } const char *comName = DICTOOL->getStringValue_json(subDict, "classname"); Component *com = ObjectFactory::getInstance()->createComponent(comName); - if (com != NULL) + if (com != nullptr) { if (com->serialize((void*)(&subDict))) { - gb->addComponent(com); - } - else - { - com = nullptr; + if (com->isRenderer()) + { + render = (ComRender*)com; + } + else + { + vecComs.push_back(com); + } } - } + } if(_fnSelector != nullptr) { _fnSelector(com, (void*)(&subDict)); } } + if (parent != nullptr) + { + if (render == nullptr || attachComponent == AttachComponentType::_EmptyNode) + { + gb = Node::create(); + if (render != nullptr) + { + vecComs.push_back(render); + } + } + else + { + gb = render->getNode(); + gb->retain(); + render->setNode(nullptr); + } + parent->addChild(gb); + } + + setPropertyFromJsonDict(dict, gb); + for (std::vector::iterator iter = vecComs.begin(); iter != vecComs.end(); ++iter) + { + gb->addComponent(*iter); + } + int length = DICTOOL->getArrayCount_json(dict, "gameobjects"); for (int i = 0; i < length; ++i) { @@ -163,7 +187,7 @@ Node* SceneReader::createObject(const rapidjson::Value &dict, cocos2d::Node* par { break; } - createObject(subDict, gb); + createObject(subDict, gb, attachComponent); } return gb; diff --git a/cocos/editor-support/cocostudio/CCSSceneReader.h b/cocos/editor-support/cocostudio/CCSSceneReader.h index f604d1429e..91e26840ef 100644 --- a/cocos/editor-support/cocostudio/CCSSceneReader.h +++ b/cocos/editor-support/cocostudio/CCSSceneReader.h @@ -30,9 +30,30 @@ THE SOFTWARE. namespace cocostudio { + class SceneReader { public: + + enum class AttachComponentType + { + ///parent: Empty Node + /// ComRender(Spirte, Armature, TMXTiledMap, ParticleSystemQuad, GUIComponent) + /// ComAttribute + /// ComAudio + /// .... + _EmptyNode, + + ///parent: ComRender(Spirte, Armature, TMXTiledMap, ParticleSystemQuad, GUIComponent) + /// ComAttribute + /// ComAudio + /// ..... + _RenderNode, + + /// Default AttachComponentType is _EmptyNode + DEFAULT = _EmptyNode, + }; + static SceneReader* getInstance(); /** * @js purge @@ -40,22 +61,23 @@ public: */ static void destroyInstance(); static const char* sceneReaderVersion(); - cocos2d::Node* createNodeWithSceneFile(const std::string &fileName); - void setTarget(const std::function& selector); - cocos2d::Node* getNodeByTag(int nTag); - + cocos2d::Node* createNodeWithSceneFile(const std::string &fileName, AttachComponentType attachComponent = AttachComponentType::_EmptyNode); + void setTarget(const std::function& selector); + cocos2d::Node* getNodeByTag(int nTag); + inline AttachComponentType getAttachComponentType(){return _attachComponent;} private: SceneReader(void); virtual ~SceneReader(void); - cocos2d::Node* createObject(const rapidjson::Value& dict, cocos2d::Node* parent); + cocos2d::Node* createObject(const rapidjson::Value& dict, cocos2d::Node* parent, AttachComponentType attachComponent); void setPropertyFromJsonDict(const rapidjson::Value& dict, cocos2d::Node *node); bool readJson(const std::string &fileName, rapidjson::Document& doc); - cocos2d::Node* nodeByTag(cocos2d::Node *parent, int tag); + cocos2d::Node* nodeByTag(cocos2d::Node *parent, int tag); private: static SceneReader* s_sharedReader; std::function _fnSelector; - cocos2d::Node* _node; + cocos2d::Node* _node; + AttachComponentType _attachComponent; }; diff --git a/external/chipmunk/src/cpCollision.c b/external/chipmunk/src/cpCollision.c index e96738808b..439314efb6 100644 --- a/external/chipmunk/src/cpCollision.c +++ b/external/chipmunk/src/cpCollision.c @@ -21,7 +21,7 @@ #include #include -#include +#include #include "chipmunk_private.h" diff --git a/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp b/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp index a33e36c76a..7f5a5fd1be 100644 --- a/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp +++ b/tests/cpp-tests/Classes/ActionsTest/ActionsTest.cpp @@ -2345,4 +2345,4 @@ void ActionRemoveSelf::onEnter() std::string ActionRemoveSelf::subtitle() const { return "Sequence: Move + Rotate + Scale + RemoveSelf"; -i +} diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp index c866ff4cdd..289385a4be 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp @@ -20,6 +20,7 @@ bool EnemyController::init() void EnemyController::onEnter() { + ComController::onEnter(); // Determine where to spawn the target along the Y axis Size winSize = Director::getInstance()->getVisibleSize(); float minY = getOwner()->getContentSize().height/2; diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.cpp index 83cb56d7df..6245fee058 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.cpp @@ -22,6 +22,7 @@ bool PlayerController::init() void PlayerController::onEnter() { + ComController::onEnter(); setTouchEnabled(true); } diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.cpp index e40fd99802..4f1d3452cd 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.cpp @@ -21,6 +21,7 @@ bool ProjectileController::init() void ProjectileController::onEnter() { + ComController::onEnter(); auto winSize = Director::getInstance()->getVisibleSize(); auto origin = Director::getInstance()->getVisibleOrigin(); _owner->setPosition( Point(origin.x+20, origin.y+winSize.height/2) ); diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.cpp index 1511b8193f..a12756a1b6 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.cpp @@ -26,6 +26,7 @@ bool SceneController::init() void SceneController::onEnter() { + ComController::onEnter(); _fAddTargetTime = 1.0f; static_cast(_owner->getComponent("Audio"))->playBackgroundMusic("background-music-aac.wav", true); From 1e6b9f7d9f3ccdf33aabb16ed38cf9dd4578e820 Mon Sep 17 00:00:00 2001 From: zhangcheng Date: Wed, 26 Mar 2014 17:02:37 +0800 Subject: [PATCH 101/106] remove isRenderer. --- cocos/2d/CCComponent.cpp | 6 ------ cocos/2d/CCComponent.h | 3 --- cocos/editor-support/cocostudio/CCComRender.cpp | 2 -- cocos/editor-support/cocostudio/CCSSceneReader.cpp | 7 ++----- 4 files changed, 2 insertions(+), 16 deletions(-) diff --git a/cocos/2d/CCComponent.cpp b/cocos/2d/CCComponent.cpp index 8cc22a8910..8f91cd764d 100644 --- a/cocos/2d/CCComponent.cpp +++ b/cocos/2d/CCComponent.cpp @@ -31,7 +31,6 @@ NS_CC_BEGIN Component::Component(void) : _owner(nullptr) , _enabled(true) -, _isRenderer(false) { #if CC_ENABLE_SCRIPT_BINDING ScriptEngineProtocol* engine = ScriptEngineManager::getInstance()->getScriptEngine(); @@ -153,9 +152,4 @@ void Component::setEnabled(bool b) _enabled = b; } -bool Component::isRenderer() const -{ - return _isRenderer; -} - NS_CC_END diff --git a/cocos/2d/CCComponent.h b/cocos/2d/CCComponent.h index ada88ca1a0..371657587a 100644 --- a/cocos/2d/CCComponent.h +++ b/cocos/2d/CCComponent.h @@ -67,14 +67,11 @@ public: void setOwner(Node *pOwner); Node* getOwner() const; - - bool isRenderer() const; protected: Node *_owner; std::string _name; bool _enabled; - bool _isRenderer; #if CC_ENABLE_SCRIPT_BINDING ccScriptType _scriptType; ///< type of script binding, lua or javascript diff --git a/cocos/editor-support/cocostudio/CCComRender.cpp b/cocos/editor-support/cocostudio/CCComRender.cpp index 2a2c15c003..5744927563 100644 --- a/cocos/editor-support/cocostudio/CCComRender.cpp +++ b/cocos/editor-support/cocostudio/CCComRender.cpp @@ -34,7 +34,6 @@ ComRender::ComRender(void) : _render(nullptr) { _name = "CCComRender"; - _isRenderer = true; } @@ -46,7 +45,6 @@ ComRender::ComRender(cocos2d::Node *node, const char *comName) _render->retain(); } _name.assign(comName); - _isRenderer = true; } ComRender::~ComRender(void) diff --git a/cocos/editor-support/cocostudio/CCSSceneReader.cpp b/cocos/editor-support/cocostudio/CCSSceneReader.cpp index 8548c4c754..7c8860b62c 100644 --- a/cocos/editor-support/cocostudio/CCSSceneReader.cpp +++ b/cocos/editor-support/cocostudio/CCSSceneReader.cpp @@ -138,11 +138,8 @@ Node* SceneReader::createObject(const rapidjson::Value &dict, cocos2d::Node* par { if (com->serialize((void*)(&subDict))) { - if (com->isRenderer()) - { - render = (ComRender*)com; - } - else + render = dynamic_cast(com); + if (render == nullptr) { vecComs.push_back(com); } From c1ff610277469ba97a48ac1376ac50f6c614f8df Mon Sep 17 00:00:00 2001 From: zhangcheng Date: Wed, 26 Mar 2014 17:21:09 +0800 Subject: [PATCH 102/106] use capital letters for enum. --- cocos/editor-support/cocostudio/CCSSceneReader.cpp | 12 ++++++------ cocos/editor-support/cocostudio/CCSSceneReader.h | 8 ++++---- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCSSceneReader.cpp b/cocos/editor-support/cocostudio/CCSSceneReader.cpp index 7c8860b62c..af0f104e17 100644 --- a/cocos/editor-support/cocostudio/CCSSceneReader.cpp +++ b/cocos/editor-support/cocostudio/CCSSceneReader.cpp @@ -37,7 +37,7 @@ SceneReader* SceneReader::s_sharedReader = nullptr; SceneReader::SceneReader() : _fnSelector(nullptr) , _node(nullptr) -, _attachComponent(AttachComponentType::_EmptyNode) +, _attachComponent(AttachComponentType::_EMPTYNODE) { ObjectFactory::getInstance()->registerType(CREATE_CLASS_COMPONENT_INFO(ComAttribute)); ObjectFactory::getInstance()->registerType(CREATE_CLASS_COMPONENT_INFO(ComRender)); @@ -134,10 +134,10 @@ Node* SceneReader::createObject(const rapidjson::Value &dict, cocos2d::Node* par } const char *comName = DICTOOL->getStringValue_json(subDict, "classname"); Component *com = ObjectFactory::getInstance()->createComponent(comName); - if (com != nullptr) - { - if (com->serialize((void*)(&subDict))) - { + if (com != nullptr) + { + if (com->serialize((void*)(&subDict))) + { render = dynamic_cast(com); if (render == nullptr) { @@ -153,7 +153,7 @@ Node* SceneReader::createObject(const rapidjson::Value &dict, cocos2d::Node* par if (parent != nullptr) { - if (render == nullptr || attachComponent == AttachComponentType::_EmptyNode) + if (render == nullptr || attachComponent == AttachComponentType::_EMPTYNODE) { gb = Node::create(); if (render != nullptr) diff --git a/cocos/editor-support/cocostudio/CCSSceneReader.h b/cocos/editor-support/cocostudio/CCSSceneReader.h index 91e26840ef..4d14989a51 100644 --- a/cocos/editor-support/cocostudio/CCSSceneReader.h +++ b/cocos/editor-support/cocostudio/CCSSceneReader.h @@ -42,16 +42,16 @@ public: /// ComAttribute /// ComAudio /// .... - _EmptyNode, + _EMPTYNODE, ///parent: ComRender(Spirte, Armature, TMXTiledMap, ParticleSystemQuad, GUIComponent) /// ComAttribute /// ComAudio /// ..... - _RenderNode, + _RENDERNODE, /// Default AttachComponentType is _EmptyNode - DEFAULT = _EmptyNode, + DEFAULT = _EMPTYNODE, }; static SceneReader* getInstance(); @@ -61,7 +61,7 @@ public: */ static void destroyInstance(); static const char* sceneReaderVersion(); - cocos2d::Node* createNodeWithSceneFile(const std::string &fileName, AttachComponentType attachComponent = AttachComponentType::_EmptyNode); + cocos2d::Node* createNodeWithSceneFile(const std::string &fileName, AttachComponentType attachComponent = AttachComponentType::_EMPTYNODE); void setTarget(const std::function& selector); cocos2d::Node* getNodeByTag(int nTag); inline AttachComponentType getAttachComponentType(){return _attachComponent;} From f564c4e34a77984979a34064eb62cc1e282e128f Mon Sep 17 00:00:00 2001 From: zhangcheng Date: Wed, 26 Mar 2014 17:55:35 +0800 Subject: [PATCH 103/106] 1. Spirte -> Sprite. 2. _EMPTYNODE -> EMPTY_NODE. --- cocos/editor-support/cocostudio/CCSSceneReader.cpp | 14 +++++++++----- cocos/editor-support/cocostudio/CCSSceneReader.h | 12 ++++++------ 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCSSceneReader.cpp b/cocos/editor-support/cocostudio/CCSSceneReader.cpp index af0f104e17..c46c5c6c1e 100644 --- a/cocos/editor-support/cocostudio/CCSSceneReader.cpp +++ b/cocos/editor-support/cocostudio/CCSSceneReader.cpp @@ -37,7 +37,7 @@ SceneReader* SceneReader::s_sharedReader = nullptr; SceneReader::SceneReader() : _fnSelector(nullptr) , _node(nullptr) -, _attachComponent(AttachComponentType::_EMPTYNODE) +, _attachComponent(AttachComponentType::EMPTY_NODE) { ObjectFactory::getInstance()->registerType(CREATE_CLASS_COMPONENT_INFO(ComAttribute)); ObjectFactory::getInstance()->registerType(CREATE_CLASS_COMPONENT_INFO(ComRender)); @@ -54,7 +54,7 @@ const char* SceneReader::sceneReaderVersion() return "1.0.0.0"; } -cocos2d::Node* SceneReader::createNodeWithSceneFile(const std::string &fileName, AttachComponentType attachComponent /*= AttachComponentType::_EmptyNode*/) +cocos2d::Node* SceneReader::createNodeWithSceneFile(const std::string &fileName, AttachComponentType attachComponent /*= AttachComponentType::EMPTY_NODE*/) { rapidjson::Document jsonDict; do { @@ -138,11 +138,15 @@ Node* SceneReader::createObject(const rapidjson::Value &dict, cocos2d::Node* par { if (com->serialize((void*)(&subDict))) { - render = dynamic_cast(com); - if (render == nullptr) + ComRender *tRender = dynamic_cast(com); + if (tRender == nullptr) { vecComs.push_back(com); } + else + { + render = tRender; + } } } if(_fnSelector != nullptr) @@ -153,7 +157,7 @@ Node* SceneReader::createObject(const rapidjson::Value &dict, cocos2d::Node* par if (parent != nullptr) { - if (render == nullptr || attachComponent == AttachComponentType::_EMPTYNODE) + if (render == nullptr || attachComponent == AttachComponentType::EMPTY_NODE) { gb = Node::create(); if (render != nullptr) diff --git a/cocos/editor-support/cocostudio/CCSSceneReader.h b/cocos/editor-support/cocostudio/CCSSceneReader.h index 4d14989a51..e61ffff3c0 100644 --- a/cocos/editor-support/cocostudio/CCSSceneReader.h +++ b/cocos/editor-support/cocostudio/CCSSceneReader.h @@ -38,20 +38,20 @@ public: enum class AttachComponentType { ///parent: Empty Node - /// ComRender(Spirte, Armature, TMXTiledMap, ParticleSystemQuad, GUIComponent) + /// ComRender(Sprite, Armature, TMXTiledMap, ParticleSystemQuad, GUIComponent) /// ComAttribute /// ComAudio /// .... - _EMPTYNODE, + EMPTY_NODE, - ///parent: ComRender(Spirte, Armature, TMXTiledMap, ParticleSystemQuad, GUIComponent) + ///parent: ComRender(Sprite, Armature, TMXTiledMap, ParticleSystemQuad, GUIComponent) /// ComAttribute /// ComAudio /// ..... - _RENDERNODE, + RENDER_NODE, /// Default AttachComponentType is _EmptyNode - DEFAULT = _EMPTYNODE, + DEFAULT = EMPTY_NODE, }; static SceneReader* getInstance(); @@ -61,7 +61,7 @@ public: */ static void destroyInstance(); static const char* sceneReaderVersion(); - cocos2d::Node* createNodeWithSceneFile(const std::string &fileName, AttachComponentType attachComponent = AttachComponentType::_EMPTYNODE); + cocos2d::Node* createNodeWithSceneFile(const std::string &fileName, AttachComponentType attachComponent = AttachComponentType::EMPTY_NODE); void setTarget(const std::function& selector); cocos2d::Node* getNodeByTag(int nTag); inline AttachComponentType getAttachComponentType(){return _attachComponent;} From a05969c39571595ecfca11a567a6ebef9b99d5e0 Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Wed, 26 Mar 2014 17:58:53 +0800 Subject: [PATCH 104/106] Move layout "exe" to cpp --- cocos/ui/UILayout.cpp | 36 ++++++++++++++++++++++++++++++++++++ cocos/ui/UILayout.h | 39 ++------------------------------------- 2 files changed, 38 insertions(+), 37 deletions(-) diff --git a/cocos/ui/UILayout.cpp b/cocos/ui/UILayout.cpp index 96402dd4d9..9808553d62 100644 --- a/cocos/ui/UILayout.cpp +++ b/cocos/ui/UILayout.cpp @@ -38,6 +38,42 @@ NS_CC_BEGIN namespace ui { +class LayoutExecutant : public Ref +{ +public: + LayoutExecutant(){}; + virtual ~LayoutExecutant(){}; + static LayoutExecutant* create(); + virtual void doLayout(const Size& layoutSize, Vector container){}; +}; + +class LinearVerticalLayoutExecutant : public LayoutExecutant +{ +public: + LinearVerticalLayoutExecutant(){}; + virtual ~LinearVerticalLayoutExecutant(){}; + static LinearVerticalLayoutExecutant* create(); + virtual void doLayout(const Size& layoutSize, Vector container); +}; + +class LinearHorizontalLayoutExecutant : public LayoutExecutant +{ +public: + LinearHorizontalLayoutExecutant(){}; + virtual ~LinearHorizontalLayoutExecutant(){}; + static LinearHorizontalLayoutExecutant* create(); + virtual void doLayout(const Size& layoutSize, Vector container); +}; + +class RelativeLayoutExecutant : public LayoutExecutant +{ +public: + RelativeLayoutExecutant(){}; + virtual ~RelativeLayoutExecutant(){}; + static RelativeLayoutExecutant* create(); + virtual void doLayout(const Size& layoutSize, Vector container); +}; + LayoutExecutant* LayoutExecutant::create() { LayoutExecutant* exe = new LayoutExecutant(); diff --git a/cocos/ui/UILayout.h b/cocos/ui/UILayout.h index 6c76089f3f..3155332793 100644 --- a/cocos/ui/UILayout.h +++ b/cocos/ui/UILayout.h @@ -50,48 +50,13 @@ typedef enum { LAYOUT_CLIPPING_STENCIL, LAYOUT_CLIPPING_SCISSOR }LayoutClippingType; - - -class LayoutExecutant : public Ref -{ -public: - LayoutExecutant(){}; - virtual ~LayoutExecutant(){}; - static LayoutExecutant* create(); - virtual void doLayout(const Size& layoutSize, Vector container){}; -}; - -class LinearVerticalLayoutExecutant : public LayoutExecutant -{ -public: - LinearVerticalLayoutExecutant(){}; - virtual ~LinearVerticalLayoutExecutant(){}; - static LinearVerticalLayoutExecutant* create(); - virtual void doLayout(const Size& layoutSize, Vector container); -}; - -class LinearHorizontalLayoutExecutant : public LayoutExecutant -{ -public: - LinearHorizontalLayoutExecutant(){}; - virtual ~LinearHorizontalLayoutExecutant(){}; - static LinearHorizontalLayoutExecutant* create(); - virtual void doLayout(const Size& layoutSize, Vector container); -}; - -class RelativeLayoutExecutant : public LayoutExecutant -{ -public: - RelativeLayoutExecutant(){}; - virtual ~RelativeLayoutExecutant(){}; - static RelativeLayoutExecutant* create(); - virtual void doLayout(const Size& layoutSize, Vector container); -}; /** * @js NA * @lua NA */ +class LayoutExecutant; + class Layout : public Widget { From 6e86e650384e60c00804125e81c36a71ea4d374a Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Wed, 26 Mar 2014 10:25:55 +0000 Subject: [PATCH 105/106] [AUTO]: updating luabinding automatically --- cocos/scripting/lua-bindings/auto/api/SceneReader.lua | 6 ++++++ .../auto/lua_cocos2dx_studio_auto.cpp.REMOVED.git-id | 2 +- .../lua-bindings/auto/lua_cocos2dx_studio_auto.hpp | 1 + 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/cocos/scripting/lua-bindings/auto/api/SceneReader.lua b/cocos/scripting/lua-bindings/auto/api/SceneReader.lua index af4616454d..6ecd715489 100644 --- a/cocos/scripting/lua-bindings/auto/api/SceneReader.lua +++ b/cocos/scripting/lua-bindings/auto/api/SceneReader.lua @@ -11,8 +11,14 @@ -- @function [parent=#SceneReader] createNodeWithSceneFile -- @param self -- @param #string str +-- @param #ccs.SceneReader::AttachComponentType attachcomponenttype -- @return Node#Node ret (return value: cc.Node) +-------------------------------- +-- @function [parent=#SceneReader] getAttachComponentType +-- @param self +-- @return SceneReader::AttachComponentType#SceneReader::AttachComponentType ret (return value: ccs.SceneReader::AttachComponentType) + -------------------------------- -- @function [parent=#SceneReader] getNodeByTag -- @param self diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.cpp.REMOVED.git-id b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.cpp.REMOVED.git-id index 3b4b93f298..a47209d790 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.cpp.REMOVED.git-id +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.cpp.REMOVED.git-id @@ -1 +1 @@ -8e3775605af6999dbbb0a7535b329c78366dba89 \ No newline at end of file +b038b989790dbaa2f6c46e1313006d6ee1bdffdc \ No newline at end of file diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.hpp b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.hpp index 34f648f832..7fca8134bc 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.hpp +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.hpp @@ -305,6 +305,7 @@ int register_all_cocos2dx_studio(lua_State* tolua_S); + #endif // __cocos2dx_studio_h__ From 8d035f43333b9ff24f08bbafb434548e5fc49301 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 26 Mar 2014 18:31:53 +0800 Subject: [PATCH 106/106] Update CHANGELOG [ci skip] --- CHANGELOG.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.REMOVED.git-id b/CHANGELOG.REMOVED.git-id index 309aeeddfc..3d57132a8f 100644 --- a/CHANGELOG.REMOVED.git-id +++ b/CHANGELOG.REMOVED.git-id @@ -1 +1 @@ -059d91131441d588739301f802453f63f913f27a \ No newline at end of file +24725aaaf53bbf506d1ea378c6af1d9ff1e61c12 \ No newline at end of file