diff --git a/.travis.yml b/.travis.yml index 758f46af9d..86a98e8e24 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,17 +1,20 @@ language: cpp script: - - export NACL_SDK_ROOT=$PWD/nacl_sdk/pepper_canary + - export NACL_SDK_ROOT=$HOME/bin/nacl_sdk/pepper_canary - export PATH=$PATH:$NACL_SDK_ROOT/toolchain/linux_x86_newlib/bin - - make -j4 -install: - - "if [ \"$PLATFORM\" != nacl ]; then ./install-deps-linux.sh; fi" - - "if [ \"$PLATFORM\" = nacl ]; then sudo apt-get update; fi" - - "if [ \"$PLATFORM\" = nacl ]; then sudo apt-get install libc6:i386; fi" - - "if [ \"$PLATFORM\" = nacl ]; then wget http://storage.googleapis.com/nativeclient-mirror/nacl/nacl_sdk/nacl_sdk.zip; fi" - - "if [ \"$PLATFORM\" = nacl ]; then unzip nacl_sdk.zip; fi" - - "if [ \"$PLATFORM\" = nacl ]; then nacl_sdk/naclsdk update --force pepper_canary; fi" + - export NDK_ROOT=$HOME/bin/android-ndk + - ./tools/travis-scripts/run-script.sh +before_install: + - ./tools/travis-scripts/before-install.sh env: - - PLATFORM=nacl DEBUG=1 - - PLATFORM=nacl DEBUG=0 - - PLATFORM=linux DEBUG=1 - - PLATFORM=linux DEBUG=0 + global: + - secure: "XvKfZu6ePLYH6nWwF6YrDMQLCfABOtyzac0JDwgYr7m1f5WH1nYQ7Hgv+pjq\nnJs+A5wdXJ6f6jRvgrgQ1T9UvY0ckR9HIXYmGtg2bd+IjJmDh0gwZMz+OFq4\nQ+Wsj9wxu9LsEAt/CosQvk3r2AoMpIY98a864b0EquZH+zzdzgA=" + - secure: "iEFKwSz4IlQ9EfAL8c/1MwU6Ti1IrNtG0YUi3TWdf6sCMglXaRICSJTCY9Hz\nXLYYvp5lPo5FQsqxpMBhkm2Zpitd4zZq+r62P9e2b4P9svAxapOQdYRh9Cjc\nN3eUyQTslMVPE9zsWIJmQbIlDk18X246Izo353UI7mmJ8WRAoNE=" + matrix: + # - GEN_JSB=YES + - PLATFORM=linux DEBUG=1 + - PLATFORM=nacl DEBUG=1 + - PLATFORM=android +branches: + only: + - master diff --git a/AUTHORS b/AUTHORS index 8c296121e4..a5bcf8077e 100644 --- a/AUTHORS +++ b/AUTHORS @@ -12,6 +12,12 @@ Developers: Rolando Abarca Javascript Binding and testjs + silverscania + Pass correct parameter to glPixelStorei when creating a texture + + FlagellumDei + Center the window correctly on windows + ggggamer fixed memory leak of preloadEffect on windows @@ -62,6 +68,7 @@ Developers: Fix CCUserDefault.cpp compiling on Android. Fixing CCFileUtils 'createXXXXWithContentsOfFile' path lookup issue. Add CCDirector::popToSceneStackLevel(int level). + Fixing a bug that custom font can't be loaded correctly if using full path of filename on android. Waiter fix an error that OpenSLEngine can't load resources from SD card @@ -115,6 +122,8 @@ Developers: CCTableView crashes if a CCTableViewDelegate is not provided. Fixing a bug that _realOpacity isn't assigned in CCLayerColor::initWithColor. CCScrollView TouchPriority Fix + Add encrypted PVR.CCZ support to ZipUtils + Tests + Fix for broken of ccArrayGetIndexOfObject after merging this commit(076f38c). Weeds (Andre Rudlaff) Used fontconfig to enhance font rendering on linux. @@ -369,6 +378,7 @@ Developers: jotel (Jaroslaw Lewandowski) Fixing a bug that wrong type of argument signature is used in setAccelerometerIntervalJNI function. + Fix for broken of ccArrayGetIndexOfObject after merging this commit(076f38c). MarcelBloemendaal Adding secureTextEntry property to CCTextFieldTTF. @@ -390,6 +400,21 @@ Developers: coolengineer (Hojin Choi) Refactoring callback selector for HttpResponse. + djh- + Fixing a bug that displayed color of CCDrawNode is incorrect when VAO is disabled. + + acai (beingstudio) + Fix of null pointer access in CCBAnimationManager::getRunningSequenceName. + + metalgit92 + Adding const qualification to some CCNode's getters + + Clarinexus + Fixing a bug that setColor and setOpacity of CCControlButton and CCScale9Sprite are broken. + + Xander84 + Fixing a bug in CCBValue::getByteValue. + Retired Core Developers: WenSheng Yang Author of windows port, CCTextField, diff --git a/Emscripten.TODO b/Emscripten.TODO index da9f00fc28..a00ca3ce9e 100644 --- a/Emscripten.TODO +++ b/Emscripten.TODO @@ -2,8 +2,6 @@ * Touch handler screwed up after TouchesTest? MenuTest? (TestCpp sample) -* Add linkage to libjpeg to get RenderTexture test to work. - * TTF Font rendering is slow and seems to wrap around by a few pixels horizontally. Need to investigate here, but I suspect the right answer is to offload font rendering to an offscreen canvas and let the browser handle it. @@ -58,3 +56,5 @@ DONE: Failed condition: moment > 0.0f Source:../src/cpBody.c:151 +* Add linkage to libjpeg to get RenderTexture test to work. + diff --git a/README.mdown b/README.mdown index 63672aa3f2..e50bc2bf8e 100644 --- a/README.mdown +++ b/README.mdown @@ -1,7 +1,7 @@ cocos2d-x ========= -[![Build Status](https://travis-ci.org/sbc100/cocos2d-x.png?branch=travis)](https://travis-ci.org/sbc100/cocos2d-x) +[![Build Status](https://travis-ci.org/cocos2d/cocos2d-x.png?branch=master)](https://travis-ci.org/cocos2d/cocos2d-x) [cocos2d-x][1] is a multi-platform 2D game framework in C++, branched on [cocos2d-iphone][2] and licensed under MIT. The master branch on github uses diff --git a/cocos2dx/Android.mk b/cocos2dx/Android.mk index 7f53d20bbd..40cb3274a3 100644 --- a/cocos2dx/Android.mk +++ b/cocos2dx/Android.mk @@ -35,6 +35,7 @@ cocoa/CCSet.cpp \ cocoa/CCString.cpp \ cocoa/CCZone.cpp \ cocoa/CCArray.cpp \ +cocoa/CCDataVisitor.cpp \ cocos2d.cpp \ CCDirector.cpp \ draw_nodes/CCDrawingPrimitives.cpp \ diff --git a/cocos2dx/base_nodes/CCNode.cpp b/cocos2dx/base_nodes/CCNode.cpp index 31aed1c1ef..19b1c1239a 100644 --- a/cocos2dx/base_nodes/CCNode.cpp +++ b/cocos2dx/base_nodes/CCNode.cpp @@ -326,7 +326,7 @@ CCArray* CCNode::getChildren() return m_pChildren; } -unsigned int CCNode::getChildrenCount(void) +unsigned int CCNode::getChildrenCount(void) const { return m_pChildren ? m_pChildren->count() : 0; } @@ -392,7 +392,7 @@ void CCNode::setAnchorPoint(const CCPoint& point) } /// contentSize getter -const CCSize& CCNode::getContentSize() +const CCSize& CCNode::getContentSize() const { return m_obContentSize; } @@ -441,7 +441,7 @@ void CCNode::ignoreAnchorPointForPosition(bool newValue) } /// tag getter -int CCNode::getTag() +int CCNode::getTag() const { return m_nTag; } diff --git a/cocos2dx/base_nodes/CCNode.h b/cocos2dx/base_nodes/CCNode.h index 1ecb0fa412..75c72dc59b 100644 --- a/cocos2dx/base_nodes/CCNode.h +++ b/cocos2dx/base_nodes/CCNode.h @@ -412,7 +412,7 @@ public: * * @return The untransformed size of the node. */ - virtual const CCSize& getContentSize(); + virtual const CCSize& getContentSize() const; /** @@ -608,7 +608,7 @@ public: * * @return The amount of children. */ - unsigned int getChildrenCount(void); + unsigned int getChildrenCount(void) const; /** * Sets the parent node @@ -757,7 +757,7 @@ public: * * @return A interger that identifies the node. */ - virtual int getTag(); + virtual int getTag() const; /** * Changes the tag that is used to identify the node easily. * diff --git a/cocos2dx/cocoa/CCArray.cpp b/cocos2dx/cocoa/CCArray.cpp index 42574fa41d..12e5bb2971 100644 --- a/cocos2dx/cocoa/CCArray.cpp +++ b/cocos2dx/cocoa/CCArray.cpp @@ -391,4 +391,9 @@ CCObject* CCArray::copyWithZone(CCZone* pZone) return pArray; } +void CCArray::acceptVisitor(CCDataVisitor &visitor) +{ + visitor.visit(this); +} + NS_CC_END diff --git a/cocos2dx/cocoa/CCArray.h b/cocos2dx/cocoa/CCArray.h index 55baeaf375..01c196f9b1 100644 --- a/cocos2dx/cocoa/CCArray.h +++ b/cocos2dx/cocoa/CCArray.h @@ -210,6 +210,9 @@ public: /* override functions */ virtual CCObject* copyWithZone(CCZone* pZone); + /* override functions */ + virtual void acceptVisitor(CCDataVisitor &visitor); + public: ccArray* data; CCArray(); diff --git a/cocos2dx/cocoa/CCBool.h b/cocos2dx/cocoa/CCBool.h index 7f49e03a80..e2a172c519 100755 --- a/cocos2dx/cocoa/CCBool.h +++ b/cocos2dx/cocoa/CCBool.h @@ -50,6 +50,10 @@ public: } return pRet; } + + /* override functions */ + virtual void acceptVisitor(CCDataVisitor &visitor) { visitor.visit(this); } + private: bool m_bValue; }; diff --git a/cocos2dx/cocoa/CCDataVisitor.cpp b/cocos2dx/cocoa/CCDataVisitor.cpp new file mode 100644 index 0000000000..9282c234e2 --- /dev/null +++ b/cocos2dx/cocoa/CCDataVisitor.cpp @@ -0,0 +1,227 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "CCObject.h" +#include "CCBool.h" +#include "CCInteger.h" +#include "CCFloat.h" +#include "CCDouble.h" +#include "CCString.h" +#include "CCArray.h" +#include "CCDictionary.h" +#include "CCSet.h" + +NS_CC_BEGIN + +void CCDataVisitor::visit(const CCBool *value) +{ + visitObject(value); +} + +void CCDataVisitor::visit(const CCInteger *value) +{ + visitObject(value); +} + +void CCDataVisitor::visit(const CCFloat *value) +{ + visitObject(value); +} + +void CCDataVisitor::visit(const CCDouble *value) +{ + visitObject(value); +} + +void CCDataVisitor::visit(const CCString *value) +{ + visitObject(value); +} + +void CCDataVisitor::visit(const CCArray *value) +{ + visitObject(value); +} + +void CCDataVisitor::visit(const CCDictionary *value) +{ + visitObject(value); +} + +void CCDataVisitor::visit(const CCSet *value) +{ + visitObject(value); +} + +// CCPrettyPrinter +CCPrettyPrinter::CCPrettyPrinter(int indentLevel/* = 0 */) +{ + setIndentLevel(indentLevel); +} + +void CCPrettyPrinter::clear() +{ + _result.clear(); +} + +std::string CCPrettyPrinter::getResult() +{ + return _result; +} + +void CCPrettyPrinter::visitObject(const CCObject *p) +{ + char buf[50] = {0}; + sprintf(buf, "%p", p); + _result += buf; +} + +void CCPrettyPrinter::visit(const CCBool * p) +{ + char buf[50] = {0}; + sprintf(buf, "%s", p->getValue() ? "true" : "false"); +} + +void CCPrettyPrinter::visit(const CCInteger *p) +{ + char buf[50] = {0}; + sprintf(buf, "%d", p->getValue()); + _result += buf; +} + +void CCPrettyPrinter::visit(const CCFloat *p) +{ + char buf[50] = {0}; + sprintf(buf, "%f", p->getValue()); + _result += buf; +} + +void CCPrettyPrinter::visit(const CCDouble *p) +{ + char buf[50] = {0}; + sprintf(buf, "%lf", p->getValue()); + _result += buf; +} + +void CCPrettyPrinter::visit(const CCString *p) +{ + _result += p->getCString(); +} + +void CCPrettyPrinter::visit(const CCArray *p) +{ + _result += "\n"; + _result += _indentStr; + _result += "\n"; + + setIndentLevel(_indentLevel+1); + CCObject* obj; + int i = 0; + char buf[50] = {0}; + CCARRAY_FOREACH(p, obj) + { + if (i > 0) { + _result += "\n"; + } + sprintf(buf, "%s%02d: ", _indentStr.c_str(), i); + _result += buf; + CCPrettyPrinter v(_indentLevel); + obj->acceptVisitor(v); + _result += v.getResult(); + i++; + } + setIndentLevel(_indentLevel-1); + + _result += "\n"; + _result += _indentStr; + _result += ""; +} + +void CCPrettyPrinter::visit(const CCDictionary *p) +{ + _result += "\n"; + _result += _indentStr; + _result += "\n"; + + setIndentLevel(_indentLevel+1); + CCDictElement* element; + bool bFirstElement = true; + char buf[1000] = {0}; + CCDICT_FOREACH(p, element) + { + if (!bFirstElement) { + _result += "\n"; + } + sprintf(buf, "%s%s: ", _indentStr.c_str(),element->getStrKey()); + _result += buf; + CCPrettyPrinter v(_indentLevel); + element->getObject()->acceptVisitor(v); + _result += v.getResult(); + bFirstElement = false; + } + setIndentLevel(_indentLevel-1); + + _result += "\n"; + _result += _indentStr; + _result += ""; +} + +void CCPrettyPrinter::visit(const CCSet *p) +{ + _result += "\n"; + _result += _indentStr; + _result += "\n"; + + setIndentLevel(_indentLevel+1); + + int i = 0; + CCSet* tmp = const_cast(p); + CCSetIterator it = tmp->begin(); + + for (; it != tmp->end(); ++it, ++i) { + if (i > 0) { + _result += "\n"; + } + _result += _indentStr.c_str(); + CCPrettyPrinter v(_indentLevel); + (*it)->acceptVisitor(v); + _result += v.getResult(); + } + setIndentLevel(_indentLevel-1); + + _result += "\n"; + _result += _indentStr; + _result += "\n"; +} + +void CCPrettyPrinter::setIndentLevel(int indentLevel) +{ + _indentLevel = indentLevel; + _indentStr.clear(); + for (int i = 0; i < _indentLevel; ++i) { + _indentStr += "\t"; + } +} + +NS_CC_END diff --git a/cocos2dx/cocoa/CCDataVisitor.h b/cocos2dx/cocoa/CCDataVisitor.h new file mode 100644 index 0000000000..636021d971 --- /dev/null +++ b/cocos2dx/cocoa/CCDataVisitor.h @@ -0,0 +1,110 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef __CCDATAVISITOR_H__ +#define __CCDATAVISITOR_H__ + +#include "platform/CCPlatformMacros.h" +#include + +NS_CC_BEGIN + +class CCObject; +class CCBool; +class CCInteger; +class CCFloat; +class CCDouble; +class CCString; +class CCArray; +class CCDictionary; +class CCSet; + +/** + * @addtogroup data_structures + * @{ + */ + +/** + * Visitor that helps to perform action that depends on polymorphic object type + * + * Use cases: + * - data serialization, + * - pretty printing of \a CCObject * + * - safe value reading from \a CCArray, \a CCDictionary, \a CCSet + * + * Usage: + * 1. subclass CCDataVisitor + * 2. overload visit() methods for object that you need to handle + * 3. handle other objects in \a visitObject() + * 4. pass your visitor to \a CCObject::acceptVisitor() + */ +class CC_DLL CCDataVisitor +{ +public: + virtual ~CCDataVisitor() {} + + /** default method, called from non-overloaded methods and for unrecognized objects */ + virtual void visitObject(const CCObject *p) = 0; + + virtual void visit(const CCBool *p); + virtual void visit(const CCInteger *p); + virtual void visit(const CCFloat *p); + virtual void visit(const CCDouble *p); + virtual void visit(const CCString *p); + virtual void visit(const CCArray *p); + virtual void visit(const CCDictionary *p); + virtual void visit(const CCSet *p); +}; + + +class CC_DLL CCPrettyPrinter : public CCDataVisitor +{ +public: + CCPrettyPrinter(int indentLevel = 0); + + virtual void clear(); + virtual std::string getResult(); + + virtual void visitObject(const CCObject *p); + virtual void visit(const CCBool * p); + virtual void visit(const CCInteger *p); + virtual void visit(const CCFloat *p); + virtual void visit(const CCDouble *p); + virtual void visit(const CCString *p); + virtual void visit(const CCArray *p); + virtual void visit(const CCDictionary *p); + virtual void visit(const CCSet *p); +private: + void setIndentLevel(int indentLevel); + int _indentLevel; + std::string _indentStr; + std::string _result; +}; + +// end of data_structure group +/// @} + +NS_CC_END + +#endif // __CCDATAVISITOR_H__ diff --git a/cocos2dx/cocoa/CCDictionary.cpp b/cocos2dx/cocoa/CCDictionary.cpp index 1e534578a9..b7f15d3a84 100644 --- a/cocos2dx/cocoa/CCDictionary.cpp +++ b/cocos2dx/cocoa/CCDictionary.cpp @@ -408,6 +408,11 @@ CCDictionary* CCDictionary::createWithContentsOfFileThreadSafe(const char *pFile return CCFileUtils::sharedFileUtils()->createCCDictionaryWithContentsOfFile(pFileName); } +void CCDictionary::acceptVisitor(CCDataVisitor &visitor) +{ + return visitor.visit(this); +} + CCDictionary* CCDictionary::createWithContentsOfFile(const char *pFileName) { CCDictionary* pRet = createWithContentsOfFileThreadSafe(pFileName); diff --git a/cocos2dx/cocoa/CCDictionary.h b/cocos2dx/cocoa/CCDictionary.h index 7dba087dc9..2d76a0249a 100644 --- a/cocos2dx/cocoa/CCDictionary.h +++ b/cocos2dx/cocoa/CCDictionary.h @@ -382,6 +382,9 @@ public: */ static CCDictionary* createWithContentsOfFileThreadSafe(const char *pFileName); + /* override functions */ + virtual void acceptVisitor(CCDataVisitor &visitor); + private: /** * For internal usage, invoked by setObject. diff --git a/cocos2dx/cocoa/CCDouble.h b/cocos2dx/cocoa/CCDouble.h index e1f3101e08..920b228baa 100755 --- a/cocos2dx/cocoa/CCDouble.h +++ b/cocos2dx/cocoa/CCDouble.h @@ -50,6 +50,10 @@ public: } return pRet; } + + /* override functions */ + virtual void acceptVisitor(CCDataVisitor &visitor) { visitor.visit(this); } + private: double m_dValue; }; diff --git a/cocos2dx/cocoa/CCFloat.h b/cocos2dx/cocoa/CCFloat.h index 37433c82e7..36c9642951 100755 --- a/cocos2dx/cocoa/CCFloat.h +++ b/cocos2dx/cocoa/CCFloat.h @@ -50,6 +50,10 @@ public: } return pRet; } + + /* override functions */ + virtual void acceptVisitor(CCDataVisitor &visitor) { visitor.visit(this); } + private: float m_fValue; }; diff --git a/cocos2dx/cocoa/CCObject.cpp b/cocos2dx/cocoa/CCObject.cpp index eb818cee28..dd74c695a3 100644 --- a/cocos2dx/cocoa/CCObject.cpp +++ b/cocos2dx/cocoa/CCObject.cpp @@ -115,4 +115,9 @@ bool CCObject::isEqual(const CCObject *pObject) return this == pObject; } +void CCObject::acceptVisitor(CCDataVisitor &visitor) +{ + visitor.visitObject(this); +} + NS_CC_END diff --git a/cocos2dx/cocoa/CCObject.h b/cocos2dx/cocoa/CCObject.h index 8c17c45ff3..d79224848b 100644 --- a/cocos2dx/cocoa/CCObject.h +++ b/cocos2dx/cocoa/CCObject.h @@ -25,7 +25,7 @@ THE SOFTWARE. #ifndef __CCOBJECT_H__ #define __CCOBJECT_H__ -#include "platform/CCPlatformMacros.h" +#include "CCDataVisitor.h" #ifdef EMSCRIPTEN #include @@ -73,6 +73,8 @@ public: unsigned int retainCount(void) const; virtual bool isEqual(const CCObject* pObject); + virtual void acceptVisitor(CCDataVisitor &visitor); + virtual void update(float dt) {CC_UNUSED_PARAM(dt);}; friend class CCAutoreleasePool; diff --git a/cocos2dx/cocoa/CCSet.cpp b/cocos2dx/cocoa/CCSet.cpp index cb6f654992..8de3b02e2d 100644 --- a/cocos2dx/cocoa/CCSet.cpp +++ b/cocos2dx/cocoa/CCSet.cpp @@ -56,6 +56,11 @@ CCSet::~CCSet(void) CC_SAFE_DELETE(m_pSet); } +void CCSet::acceptVisitor(CCDataVisitor &visitor) +{ + visitor.visit(this); +} + CCSet * CCSet::create() { CCSet * pRet = new CCSet(); diff --git a/cocos2dx/cocoa/CCSet.h b/cocos2dx/cocoa/CCSet.h index 042ee71c83..85d36d6d9d 100644 --- a/cocos2dx/cocoa/CCSet.h +++ b/cocos2dx/cocoa/CCSet.h @@ -90,6 +90,8 @@ public: */ CCObject* anyObject(); + virtual void acceptVisitor(CCDataVisitor &visitor); + private: std::set *m_pSet; }; diff --git a/cocos2dx/cocoa/CCString.cpp b/cocos2dx/cocoa/CCString.cpp index d22f5724ad..caf320b26a 100644 --- a/cocos2dx/cocoa/CCString.cpp +++ b/cocos2dx/cocoa/CCString.cpp @@ -200,4 +200,9 @@ CCString* CCString::createWithContentsOfFile(const char* pszFileName) return pRet; } +void CCString::acceptVisitor(CCDataVisitor &visitor) +{ + visitor.visit(this); +} + NS_CC_END diff --git a/cocos2dx/cocoa/CCString.h b/cocos2dx/cocoa/CCString.h index 13a63884af..9548a0e63c 100644 --- a/cocos2dx/cocoa/CCString.h +++ b/cocos2dx/cocoa/CCString.h @@ -109,6 +109,8 @@ public: */ static CCString* createWithContentsOfFile(const char* pszFileName); + virtual void acceptVisitor(CCDataVisitor &visitor); + private: /** only for internal use */ diff --git a/cocos2dx/draw_nodes/CCDrawNode.cpp b/cocos2dx/draw_nodes/CCDrawNode.cpp index cd53c9db77..36584e573e 100644 --- a/cocos2dx/draw_nodes/CCDrawNode.cpp +++ b/cocos2dx/draw_nodes/CCDrawNode.cpp @@ -201,7 +201,7 @@ void CCDrawNode::render() glVertexAttribPointer(kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, sizeof(ccV2F_C4B_T2F), (GLvoid *)offsetof(ccV2F_C4B_T2F, vertices)); // color - glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_FALSE, sizeof(ccV2F_C4B_T2F), (GLvoid *)offsetof(ccV2F_C4B_T2F, colors)); + glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ccV2F_C4B_T2F), (GLvoid *)offsetof(ccV2F_C4B_T2F, colors)); // texcood glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, sizeof(ccV2F_C4B_T2F), (GLvoid *)offsetof(ccV2F_C4B_T2F, texCoords)); diff --git a/cocos2dx/platform/CCFileUtils.cpp b/cocos2dx/platform/CCFileUtils.cpp index 9107af53fc..0b5f7c74dd 100644 --- a/cocos2dx/platform/CCFileUtils.cpp +++ b/cocos2dx/platform/CCFileUtils.cpp @@ -636,8 +636,8 @@ std::string CCFileUtils::fullPathForFilename(const char* pszFileName) } } - CCLOG("cocos2d: fullPathForFilename: No file found at %s. Possible missing file.", pszFileName); - + //CCLOG("cocos2d: fullPathForFilename: No file found at %s. Possible missing file.", pszFileName); + // The file wasn't found, return the file name passed in. return pszFileName; } diff --git a/cocos2dx/platform/CCImageCommonWebp.cpp b/cocos2dx/platform/CCImageCommonWebp.cpp index ba0480e7ff..878b8408b3 100644 --- a/cocos2dx/platform/CCImageCommonWebp.cpp +++ b/cocos2dx/platform/CCImageCommonWebp.cpp @@ -24,7 +24,7 @@ #include "platform/CCImage.h" #include "textures/CCTexture2D.h" -#ifdef __native_client__ +#if defined(__native_client__) || defined(EMSCRIPTEN) // TODO(sbc): I'm pretty sure all platforms should be including // webph headers in this way. #include "webp/decode.h" diff --git a/cocos2dx/platform/CCImageCommon_cpp.h b/cocos2dx/platform/CCImageCommon_cpp.h index 1153eef191..d07281a174 100644 --- a/cocos2dx/platform/CCImageCommon_cpp.h +++ b/cocos2dx/platform/CCImageCommon_cpp.h @@ -288,7 +288,12 @@ bool CCImage::_initWithJpgData(void * data, int nSize) jpeg_mem_src( &cinfo, (unsigned char *) data, nSize ); /* reading the image header which contains image information */ +#if (JPEG_LIB_VERSION >= 90) + // libjpeg 0.9 adds stricter types. + jpeg_read_header( &cinfo, TRUE ); +#else jpeg_read_header( &cinfo, true ); +#endif // we only support RGB or grayscale if (cinfo.jpeg_color_space != JCS_RGB) diff --git a/cocos2dx/platform/android/CCImage.cpp b/cocos2dx/platform/android/CCImage.cpp index c02d72e419..03955040e2 100644 --- a/cocos2dx/platform/android/CCImage.cpp +++ b/cocos2dx/platform/android/CCImage.cpp @@ -28,6 +28,7 @@ THE SOFTWARE. #include "platform/CCImageCommon_cpp.h" #include "platform/CCPlatformMacros.h" #include "platform/CCImage.h" +#include "platform/CCFileUtils.h" #include "jni/JniHelper.h" #include @@ -65,6 +66,17 @@ public: return false; } + // Do a full lookup for the font path using CCFileUtils in case the given font name is a relative path to a font file asset, + // or the path has been mapped to a different location in the app package: + std::string fullPathOrFontName = CCFileUtils::sharedFileUtils()->fullPathForFilename(pFontName); + + // If the path name returned includes the 'assets' dir then that needs to be removed, because the android.content.Context + // requires this portion of the path to be omitted for assets inside the app package. + if (fullPathOrFontName.find("assets/") == 0) + { + fullPathOrFontName = fullPathOrFontName.substr(strlen("assets/")); // Chop out the 'assets/' portion of the path. + } + /**create bitmap * this method call Cococs2dx.createBitmap()(java code) to create the bitmap, the java code * will call Java_org_cocos2dx_lib_Cocos2dxBitmap_nativeInitBitmapDC() to init the width, height @@ -72,7 +84,7 @@ public: * use this approach to decrease the jni call number */ jstring jstrText = methodInfo.env->NewStringUTF(text); - jstring jstrFont = methodInfo.env->NewStringUTF(pFontName); + jstring jstrFont = methodInfo.env->NewStringUTF(fullPathOrFontName.c_str()); methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, jstrText, jstrFont, (int)fontSize, eAlignMask, nWidth, nHeight); diff --git a/cocos2dx/platform/android/java/src/org/cocos2dx/lib/Cocos2dxTypefaces.java b/cocos2dx/platform/android/java/src/org/cocos2dx/lib/Cocos2dxTypefaces.java index 901b38153b..b7495fba90 100644 --- a/cocos2dx/platform/android/java/src/org/cocos2dx/lib/Cocos2dxTypefaces.java +++ b/cocos2dx/platform/android/java/src/org/cocos2dx/lib/Cocos2dxTypefaces.java @@ -57,7 +57,15 @@ public class Cocos2dxTypefaces { public static synchronized Typeface get(final Context pContext, final String pAssetName) { if (!Cocos2dxTypefaces.sTypefaceCache.containsKey(pAssetName)) { - final Typeface typeface = Typeface.createFromAsset(pContext.getAssets(), pAssetName); + Typeface typeface = null; + if (pAssetName.startsWith("/")) + { + typeface = Typeface.createFromFile(pAssetName); + } + else + { + typeface = Typeface.createFromAsset(pContext.getAssets(), pAssetName); + } Cocos2dxTypefaces.sTypefaceCache.put(pAssetName, typeface); } diff --git a/cocos2dx/platform/emscripten/CCEGLView.cpp b/cocos2dx/platform/emscripten/CCEGLView.cpp index 0f2d81dd71..42454db362 100644 --- a/cocos2dx/platform/emscripten/CCEGLView.cpp +++ b/cocos2dx/platform/emscripten/CCEGLView.cpp @@ -167,8 +167,6 @@ void CCEGLView::release() m_eglDisplay = EGL_NO_DISPLAY; } - eglReleaseThread(); - m_isGLInitialized = false; exit(0); diff --git a/cocos2dx/platform/nacl/CCEGLView.cpp b/cocos2dx/platform/nacl/CCEGLView.cpp index 1177f40fd4..954dd5751b 100644 --- a/cocos2dx/platform/nacl/CCEGLView.cpp +++ b/cocos2dx/platform/nacl/CCEGLView.cpp @@ -108,7 +108,7 @@ bool OpenGLContext::MakeContextCurrent() return false; } - CCLOG("glSetCurrentContextPPAPI: %p", m_graphics3d.pp_resource()); + CCLOG("glSetCurrentContextPPAPI: %p", (void*)m_graphics3d.pp_resource()); glSetCurrentContextPPAPI(m_graphics3d.pp_resource()); return true; } diff --git a/cocos2dx/platform/nacl/CCInstance.cpp b/cocos2dx/platform/nacl/CCInstance.cpp index 4d997ee328..44ef996c0f 100644 --- a/cocos2dx/platform/nacl/CCInstance.cpp +++ b/cocos2dx/platform/nacl/CCInstance.cpp @@ -82,7 +82,7 @@ bool CocosPepperInstance::Init(uint32_t argc, const char* argn[], const char* ar #ifdef OLD_NACL_MOUNTS m_runner = new MainThreadRunner(this); #else - CCLOG("%p %p", pp_instance(), pp::Module::Get()->get_browser_interface()); + CCLOG("%p %p", (void*)pp_instance(), (void*)pp::Module::Get()->get_browser_interface()); nacl_io_init_ppapi(pp_instance(), pp::Module::Get()->get_browser_interface()); CCLOG("done nacl_mounts_init_ppapi"); diff --git a/cocos2dx/platform/third_party/emscripten/libjpeg/jconfig.h b/cocos2dx/platform/third_party/emscripten/libjpeg/jconfig.h new file mode 100644 index 0000000000..966b1d5149 --- /dev/null +++ b/cocos2dx/platform/third_party/emscripten/libjpeg/jconfig.h @@ -0,0 +1,54 @@ +/* jconfig.h. Generated from jconfig.cfg by configure. */ +/* jconfig.cfg --- source file edited by configure script */ +/* see jconfig.txt for explanations */ + +#define HAVE_PROTOTYPES 1 +#define HAVE_UNSIGNED_CHAR 1 +#define HAVE_UNSIGNED_SHORT 1 +/* #undef void */ +/* #undef const */ +/* #undef CHAR_IS_UNSIGNED */ +#define HAVE_STDDEF_H 1 +#define HAVE_STDLIB_H 1 +#define HAVE_LOCALE_H 1 +/* #undef NEED_BSD_STRINGS */ +/* #undef NEED_SYS_TYPES_H */ +/* #undef NEED_FAR_POINTERS */ +/* #undef NEED_SHORT_EXTERNAL_NAMES */ +/* Define this if you get warnings about undefined structures. */ +/* #undef INCOMPLETE_TYPES_BROKEN */ + +/* Define "boolean" as unsigned char, not int, on Windows systems. */ +#ifdef _WIN32 +#ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */ +typedef unsigned char boolean; +#endif +#define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */ +#endif + +#ifdef JPEG_INTERNALS + +/* #undef RIGHT_SHIFT_IS_UNSIGNED */ +#define INLINE __inline__ +/* These are for configuring the JPEG memory manager. */ +/* #undef DEFAULT_MAX_MEM */ +/* #undef NO_MKTEMP */ + +#endif /* JPEG_INTERNALS */ + +#ifdef JPEG_CJPEG_DJPEG + +#define BMP_SUPPORTED /* BMP image file format */ +#define GIF_SUPPORTED /* GIF image file format */ +#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */ +/* #undef RLE_SUPPORTED */ +#define TARGA_SUPPORTED /* Targa image file format */ + +/* #undef TWO_FILE_COMMANDLINE */ +/* #undef NEED_SIGNAL_CATCHER */ +/* #undef DONT_USE_B_MODE */ + +/* Define this if you want percent-done progress reports from cjpeg/djpeg. */ +/* #undef PROGRESS_REPORT */ + +#endif /* JPEG_CJPEG_DJPEG */ diff --git a/cocos2dx/platform/third_party/emscripten/libjpeg/jerror.h b/cocos2dx/platform/third_party/emscripten/libjpeg/jerror.h new file mode 100644 index 0000000000..a4b661f716 --- /dev/null +++ b/cocos2dx/platform/third_party/emscripten/libjpeg/jerror.h @@ -0,0 +1,304 @@ +/* + * jerror.h + * + * Copyright (C) 1994-1997, Thomas G. Lane. + * Modified 1997-2012 by Guido Vollbeding. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file defines the error and message codes for the JPEG library. + * Edit this file to add new codes, or to translate the message strings to + * some other language. + * A set of error-reporting macros are defined too. Some applications using + * the JPEG library may wish to include this file to get the error codes + * and/or the macros. + */ + +/* + * To define the enum list of message codes, include this file without + * defining macro JMESSAGE. To create a message string table, include it + * again with a suitable JMESSAGE definition (see jerror.c for an example). + */ +#ifndef JMESSAGE +#ifndef JERROR_H +/* First time through, define the enum list */ +#define JMAKE_ENUM_LIST +#else +/* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */ +#define JMESSAGE(code,string) +#endif /* JERROR_H */ +#endif /* JMESSAGE */ + +#ifdef JMAKE_ENUM_LIST + +typedef enum { + +#define JMESSAGE(code,string) code , + +#endif /* JMAKE_ENUM_LIST */ + +JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */ + +/* For maintenance convenience, list is alphabetical by message code name */ +JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix") +JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix") +JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode") +JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS") +JMESSAGE(JERR_BAD_CROP_SPEC, "Invalid crop request") +JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range") +JMESSAGE(JERR_BAD_DCTSIZE, "DCT scaled block size %dx%d not supported") +JMESSAGE(JERR_BAD_DROP_SAMPLING, + "Component index %d: mismatching sampling ratio %d:%d, %d:%d, %c") +JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition") +JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace") +JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace") +JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length") +JMESSAGE(JERR_BAD_LIB_VERSION, + "Wrong JPEG library version: library is %d, caller expects %d") +JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan") +JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d") +JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d") +JMESSAGE(JERR_BAD_PROGRESSION, + "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d") +JMESSAGE(JERR_BAD_PROG_SCRIPT, + "Invalid progressive parameters at scan script entry %d") +JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors") +JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d") +JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d") +JMESSAGE(JERR_BAD_STRUCT_SIZE, + "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u") +JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access") +JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small") +JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here") +JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet") +JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d") +JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request") +JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d") +JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x") +JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d") +JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d") +JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)") +JMESSAGE(JERR_EMS_READ, "Read from EMS failed") +JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed") +JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan") +JMESSAGE(JERR_FILE_READ, "Input file read error") +JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?") +JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet") +JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow") +JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry") +JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels") +JMESSAGE(JERR_INPUT_EMPTY, "Empty input file") +JMESSAGE(JERR_INPUT_EOF, "Premature end of input file") +JMESSAGE(JERR_MISMATCHED_QUANT_TABLE, + "Cannot transcode due to multiple use of quantization table %d") +JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data") +JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change") +JMESSAGE(JERR_NOTIMPL, "Not implemented yet") +JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time") +JMESSAGE(JERR_NO_ARITH_TABLE, "Arithmetic table 0x%02x was not defined") +JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported") +JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined") +JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image") +JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined") +JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x") +JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)") +JMESSAGE(JERR_QUANT_COMPONENTS, + "Cannot quantize more than %d color components") +JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors") +JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors") +JMESSAGE(JERR_SOF_BEFORE, "Invalid JPEG file structure: %s before SOF") +JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers") +JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker") +JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x") +JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers") +JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s") +JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file") +JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file") +JMESSAGE(JERR_TFILE_WRITE, + "Write failed on temporary file --- out of disk space?") +JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines") +JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x") +JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up") +JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation") +JMESSAGE(JERR_XMS_READ, "Read from XMS failed") +JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed") +JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT) +JMESSAGE(JMSG_VERSION, JVERSION) +JMESSAGE(JTRC_16BIT_TABLES, + "Caution: quantization tables are too coarse for baseline JPEG") +JMESSAGE(JTRC_ADOBE, + "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d") +JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u") +JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u") +JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x") +JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x") +JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d") +JMESSAGE(JTRC_DRI, "Define Restart Interval %u") +JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u") +JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u") +JMESSAGE(JTRC_EOI, "End Of Image") +JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d") +JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d") +JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE, + "Warning: thumbnail image size does not match data length %u") +JMESSAGE(JTRC_JFIF_EXTENSION, + "JFIF extension marker: type 0x%02x, length %u") +JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image") +JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u") +JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x") +JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u") +JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors") +JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors") +JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization") +JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d") +JMESSAGE(JTRC_RST, "RST%d") +JMESSAGE(JTRC_SMOOTH_NOTIMPL, + "Smoothing not supported with nonstandard sampling ratios") +JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d") +JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d") +JMESSAGE(JTRC_SOI, "Start of Image") +JMESSAGE(JTRC_SOS, "Start Of Scan: %d components") +JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d") +JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d") +JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s") +JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s") +JMESSAGE(JTRC_THUMB_JPEG, + "JFIF extension marker: JPEG-compressed thumbnail image, length %u") +JMESSAGE(JTRC_THUMB_PALETTE, + "JFIF extension marker: palette thumbnail image, length %u") +JMESSAGE(JTRC_THUMB_RGB, + "JFIF extension marker: RGB thumbnail image, length %u") +JMESSAGE(JTRC_UNKNOWN_IDS, + "Unrecognized component IDs %d %d %d, assuming YCbCr") +JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u") +JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u") +JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d") +JMESSAGE(JWRN_ARITH_BAD_CODE, "Corrupt JPEG data: bad arithmetic code") +JMESSAGE(JWRN_BOGUS_PROGRESSION, + "Inconsistent progression sequence for component %d coefficient %d") +JMESSAGE(JWRN_EXTRANEOUS_DATA, + "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x") +JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment") +JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code") +JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d") +JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file") +JMESSAGE(JWRN_MUST_RESYNC, + "Corrupt JPEG data: found marker 0x%02x instead of RST%d") +JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG") +JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines") + +#ifdef JMAKE_ENUM_LIST + + JMSG_LASTMSGCODE +} J_MESSAGE_CODE; + +#undef JMAKE_ENUM_LIST +#endif /* JMAKE_ENUM_LIST */ + +/* Zap JMESSAGE macro so that future re-inclusions do nothing by default */ +#undef JMESSAGE + + +#ifndef JERROR_H +#define JERROR_H + +/* Macros to simplify using the error and trace message stuff */ +/* The first parameter is either type of cinfo pointer */ + +/* Fatal errors (print message and exit) */ +#define ERREXIT(cinfo,code) \ + ((cinfo)->err->msg_code = (code), \ + (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) +#define ERREXIT1(cinfo,code,p1) \ + ((cinfo)->err->msg_code = (code), \ + (cinfo)->err->msg_parm.i[0] = (p1), \ + (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) +#define ERREXIT2(cinfo,code,p1,p2) \ + ((cinfo)->err->msg_code = (code), \ + (cinfo)->err->msg_parm.i[0] = (p1), \ + (cinfo)->err->msg_parm.i[1] = (p2), \ + (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) +#define ERREXIT3(cinfo,code,p1,p2,p3) \ + ((cinfo)->err->msg_code = (code), \ + (cinfo)->err->msg_parm.i[0] = (p1), \ + (cinfo)->err->msg_parm.i[1] = (p2), \ + (cinfo)->err->msg_parm.i[2] = (p3), \ + (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) +#define ERREXIT4(cinfo,code,p1,p2,p3,p4) \ + ((cinfo)->err->msg_code = (code), \ + (cinfo)->err->msg_parm.i[0] = (p1), \ + (cinfo)->err->msg_parm.i[1] = (p2), \ + (cinfo)->err->msg_parm.i[2] = (p3), \ + (cinfo)->err->msg_parm.i[3] = (p4), \ + (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) +#define ERREXIT6(cinfo,code,p1,p2,p3,p4,p5,p6) \ + ((cinfo)->err->msg_code = (code), \ + (cinfo)->err->msg_parm.i[0] = (p1), \ + (cinfo)->err->msg_parm.i[1] = (p2), \ + (cinfo)->err->msg_parm.i[2] = (p3), \ + (cinfo)->err->msg_parm.i[3] = (p4), \ + (cinfo)->err->msg_parm.i[4] = (p5), \ + (cinfo)->err->msg_parm.i[5] = (p6), \ + (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) +#define ERREXITS(cinfo,code,str) \ + ((cinfo)->err->msg_code = (code), \ + strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \ + (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) + +#define MAKESTMT(stuff) do { stuff } while (0) + +/* Nonfatal errors (we can keep going, but the data is probably corrupt) */ +#define WARNMS(cinfo,code) \ + ((cinfo)->err->msg_code = (code), \ + (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1)) +#define WARNMS1(cinfo,code,p1) \ + ((cinfo)->err->msg_code = (code), \ + (cinfo)->err->msg_parm.i[0] = (p1), \ + (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1)) +#define WARNMS2(cinfo,code,p1,p2) \ + ((cinfo)->err->msg_code = (code), \ + (cinfo)->err->msg_parm.i[0] = (p1), \ + (cinfo)->err->msg_parm.i[1] = (p2), \ + (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1)) + +/* Informational/debugging messages */ +#define TRACEMS(cinfo,lvl,code) \ + ((cinfo)->err->msg_code = (code), \ + (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl))) +#define TRACEMS1(cinfo,lvl,code,p1) \ + ((cinfo)->err->msg_code = (code), \ + (cinfo)->err->msg_parm.i[0] = (p1), \ + (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl))) +#define TRACEMS2(cinfo,lvl,code,p1,p2) \ + ((cinfo)->err->msg_code = (code), \ + (cinfo)->err->msg_parm.i[0] = (p1), \ + (cinfo)->err->msg_parm.i[1] = (p2), \ + (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl))) +#define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \ + MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \ + _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \ + (cinfo)->err->msg_code = (code); \ + (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); ) +#define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \ + MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \ + _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \ + (cinfo)->err->msg_code = (code); \ + (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); ) +#define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \ + MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \ + _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \ + _mp[4] = (p5); \ + (cinfo)->err->msg_code = (code); \ + (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); ) +#define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \ + MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \ + _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \ + _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \ + (cinfo)->err->msg_code = (code); \ + (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); ) +#define TRACEMSS(cinfo,lvl,code,str) \ + ((cinfo)->err->msg_code = (code), \ + strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \ + (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl))) + +#endif /* JERROR_H */ diff --git a/cocos2dx/platform/third_party/emscripten/libjpeg/jmorecfg.h b/cocos2dx/platform/third_party/emscripten/libjpeg/jmorecfg.h new file mode 100644 index 0000000000..2407edbef8 --- /dev/null +++ b/cocos2dx/platform/third_party/emscripten/libjpeg/jmorecfg.h @@ -0,0 +1,390 @@ +/* + * jmorecfg.h + * + * Copyright (C) 1991-1997, Thomas G. Lane. + * Modified 1997-2012 by Guido Vollbeding. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains additional configuration options that customize the + * JPEG software for special applications or support machine-dependent + * optimizations. Most users will not need to touch this file. + */ + + +/* + * Define BITS_IN_JSAMPLE as either + * 8 for 8-bit sample values (the usual setting) + * 12 for 12-bit sample values + * Only 8 and 12 are legal data precisions for lossy JPEG according to the + * JPEG standard, and the IJG code does not support anything else! + * We do not support run-time selection of data precision, sorry. + */ + +#define BITS_IN_JSAMPLE 8 /* use 8 or 12 */ + + +/* + * Maximum number of components (color channels) allowed in JPEG image. + * To meet the letter of the JPEG spec, set this to 255. However, darn + * few applications need more than 4 channels (maybe 5 for CMYK + alpha + * mask). We recommend 10 as a reasonable compromise; use 4 if you are + * really short on memory. (Each allowed component costs a hundred or so + * bytes of storage, whether actually used in an image or not.) + */ + +#define MAX_COMPONENTS 10 /* maximum number of image components */ + + +/* + * Basic data types. + * You may need to change these if you have a machine with unusual data + * type sizes; for example, "char" not 8 bits, "short" not 16 bits, + * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits, + * but it had better be at least 16. + */ + +/* Representation of a single sample (pixel element value). + * We frequently allocate large arrays of these, so it's important to keep + * them small. But if you have memory to burn and access to char or short + * arrays is very slow on your hardware, you might want to change these. + */ + +#if BITS_IN_JSAMPLE == 8 +/* JSAMPLE should be the smallest type that will hold the values 0..255. + * You can use a signed char by having GETJSAMPLE mask it with 0xFF. + */ + +#ifdef HAVE_UNSIGNED_CHAR + +typedef unsigned char JSAMPLE; +#define GETJSAMPLE(value) ((int) (value)) + +#else /* not HAVE_UNSIGNED_CHAR */ + +typedef char JSAMPLE; +#ifdef CHAR_IS_UNSIGNED +#define GETJSAMPLE(value) ((int) (value)) +#else +#define GETJSAMPLE(value) ((int) (value) & 0xFF) +#endif /* CHAR_IS_UNSIGNED */ + +#endif /* HAVE_UNSIGNED_CHAR */ + +#define MAXJSAMPLE 255 +#define CENTERJSAMPLE 128 + +#endif /* BITS_IN_JSAMPLE == 8 */ + + +#if BITS_IN_JSAMPLE == 12 +/* JSAMPLE should be the smallest type that will hold the values 0..4095. + * On nearly all machines "short" will do nicely. + */ + +typedef short JSAMPLE; +#define GETJSAMPLE(value) ((int) (value)) + +#define MAXJSAMPLE 4095 +#define CENTERJSAMPLE 2048 + +#endif /* BITS_IN_JSAMPLE == 12 */ + + +/* Representation of a DCT frequency coefficient. + * This should be a signed value of at least 16 bits; "short" is usually OK. + * Again, we allocate large arrays of these, but you can change to int + * if you have memory to burn and "short" is really slow. + */ + +typedef short JCOEF; + + +/* Compressed datastreams are represented as arrays of JOCTET. + * These must be EXACTLY 8 bits wide, at least once they are written to + * external storage. Note that when using the stdio data source/destination + * managers, this is also the data type passed to fread/fwrite. + */ + +#ifdef HAVE_UNSIGNED_CHAR + +typedef unsigned char JOCTET; +#define GETJOCTET(value) (value) + +#else /* not HAVE_UNSIGNED_CHAR */ + +typedef char JOCTET; +#ifdef CHAR_IS_UNSIGNED +#define GETJOCTET(value) (value) +#else +#define GETJOCTET(value) ((value) & 0xFF) +#endif /* CHAR_IS_UNSIGNED */ + +#endif /* HAVE_UNSIGNED_CHAR */ + + +/* These typedefs are used for various table entries and so forth. + * They must be at least as wide as specified; but making them too big + * won't cost a huge amount of memory, so we don't provide special + * extraction code like we did for JSAMPLE. (In other words, these + * typedefs live at a different point on the speed/space tradeoff curve.) + */ + +/* UINT8 must hold at least the values 0..255. */ + +#ifdef HAVE_UNSIGNED_CHAR +typedef unsigned char UINT8; +#else /* not HAVE_UNSIGNED_CHAR */ +#ifdef CHAR_IS_UNSIGNED +typedef char UINT8; +#else /* not CHAR_IS_UNSIGNED */ +typedef short UINT8; +#endif /* CHAR_IS_UNSIGNED */ +#endif /* HAVE_UNSIGNED_CHAR */ + +/* UINT16 must hold at least the values 0..65535. */ + +#ifdef HAVE_UNSIGNED_SHORT +typedef unsigned short UINT16; +#else /* not HAVE_UNSIGNED_SHORT */ +typedef unsigned int UINT16; +#endif /* HAVE_UNSIGNED_SHORT */ + +/* INT16 must hold at least the values -32768..32767. */ + +#ifndef XMD_H /* X11/xmd.h correctly defines INT16 */ +typedef short INT16; +#endif + +/* INT32 must hold at least signed 32-bit values. */ + +#ifndef XMD_H /* X11/xmd.h correctly defines INT32 */ +#ifndef _BASETSD_H_ /* Microsoft defines it in basetsd.h */ +#ifndef _BASETSD_H /* MinGW is slightly different */ +#ifndef QGLOBAL_H /* Qt defines it in qglobal.h */ +typedef long INT32; +#endif +#endif +#endif +#endif + +/* Datatype used for image dimensions. The JPEG standard only supports + * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore + * "unsigned int" is sufficient on all machines. However, if you need to + * handle larger images and you don't mind deviating from the spec, you + * can change this datatype. + */ + +typedef unsigned int JDIMENSION; + +#define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */ + + +/* These macros are used in all function definitions and extern declarations. + * You could modify them if you need to change function linkage conventions; + * in particular, you'll need to do that to make the library a Windows DLL. + * Another application is to make all functions global for use with debuggers + * or code profilers that require it. + */ + +/* a function called through method pointers: */ +#define METHODDEF(type) static type +/* a function used only in its module: */ +#define LOCAL(type) static type +/* a function referenced thru EXTERNs: */ +#define GLOBAL(type) type +/* a reference to a GLOBAL function: */ +#define EXTERN(type) extern type + + +/* This macro is used to declare a "method", that is, a function pointer. + * We want to supply prototype parameters if the compiler can cope. + * Note that the arglist parameter must be parenthesized! + * Again, you can customize this if you need special linkage keywords. + */ + +#ifdef HAVE_PROTOTYPES +#define JMETHOD(type,methodname,arglist) type (*methodname) arglist +#else +#define JMETHOD(type,methodname,arglist) type (*methodname) () +#endif + + +/* The noreturn type identifier is used to declare functions + * which cannot return. + * Compilers can thus create more optimized code and perform + * better checks for warnings and errors. + * Static analyzer tools can make improved inferences about + * execution paths and are prevented from giving false alerts. + * + * Unfortunately, the proposed specifications of corresponding + * extensions in the Dec 2011 ISO C standard revision (C11), + * GCC, MSVC, etc. are not viable. + * Thus we introduce a user defined type to declare noreturn + * functions at least for clarity. A proper compiler would + * have a suitable noreturn type to match in place of void. + */ + +#ifndef HAVE_NORETURN_T +typedef void noreturn_t; +#endif + + +/* Here is the pseudo-keyword for declaring pointers that must be "far" + * on 80x86 machines. Most of the specialized coding for 80x86 is handled + * by just saying "FAR *" where such a pointer is needed. In a few places + * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol. + */ + +#ifndef FAR +#ifdef NEED_FAR_POINTERS +#define FAR far +#else +#define FAR +#endif +#endif + + +/* + * On a few systems, type boolean and/or its values FALSE, TRUE may appear + * in standard header files. Or you may have conflicts with application- + * specific header files that you want to include together with these files. + * Defining HAVE_BOOLEAN before including jpeglib.h should make it work. + */ + +#ifdef HAVE_BOOLEAN +#ifndef FALSE /* in case these macros already exist */ +#define FALSE 0 /* values of boolean */ +#endif +#ifndef TRUE +#define TRUE 1 +#endif +#else +typedef enum { FALSE = 0, TRUE = 1 } boolean; +#endif + + +/* + * The remaining options affect code selection within the JPEG library, + * but they don't need to be visible to most applications using the library. + * To minimize application namespace pollution, the symbols won't be + * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined. + */ + +#ifdef JPEG_INTERNALS +#define JPEG_INTERNAL_OPTIONS +#endif + +#ifdef JPEG_INTERNAL_OPTIONS + + +/* + * These defines indicate whether to include various optional functions. + * Undefining some of these symbols will produce a smaller but less capable + * library. Note that you can leave certain source files out of the + * compilation/linking process if you've #undef'd the corresponding symbols. + * (You may HAVE to do that if your compiler doesn't like null source files.) + */ + +/* Capability options common to encoder and decoder: */ + +#define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */ +#define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */ +#define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */ + +/* Encoder capability options: */ + +#define C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */ +#define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */ +#define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/ +#define DCT_SCALING_SUPPORTED /* Input rescaling via DCT? (Requires DCT_ISLOW)*/ +#define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */ +/* Note: if you selected 12-bit data precision, it is dangerous to turn off + * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit + * precision, so jchuff.c normally uses entropy optimization to compute + * usable tables for higher precision. If you don't want to do optimization, + * you'll have to supply different default Huffman tables. + * The exact same statements apply for progressive JPEG: the default tables + * don't work for progressive mode. (This may get fixed, however.) + */ +#define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */ + +/* Decoder capability options: */ + +#define D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */ +#define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */ +#define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/ +#define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */ +#define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */ +#define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */ +#undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */ +#define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */ +#define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */ +#define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */ + +/* more capability options later, no doubt */ + + +/* + * Ordering of RGB data in scanlines passed to or from the application. + * If your application wants to deal with data in the order B,G,R, just + * change these macros. You can also deal with formats such as R,G,B,X + * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing + * the offsets will also change the order in which colormap data is organized. + * RESTRICTIONS: + * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats. + * 2. The color quantizer modules will not behave desirably if RGB_PIXELSIZE + * is not 3 (they don't understand about dummy color components!). So you + * can't use color quantization if you change that value. + */ + +#define RGB_RED 0 /* Offset of Red in an RGB scanline element */ +#define RGB_GREEN 1 /* Offset of Green */ +#define RGB_BLUE 2 /* Offset of Blue */ +#define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */ + + +/* Definitions for speed-related optimizations. */ + + +/* If your compiler supports inline functions, define INLINE + * as the inline keyword; otherwise define it as empty. + */ + +#ifndef INLINE +#ifdef __GNUC__ /* for instance, GNU C knows about inline */ +#define INLINE __inline__ +#endif +#ifndef INLINE +#define INLINE /* default is to define it as empty */ +#endif +#endif + + +/* On some machines (notably 68000 series) "int" is 32 bits, but multiplying + * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER + * as short on such a machine. MULTIPLIER must be at least 16 bits wide. + */ + +#ifndef MULTIPLIER +#define MULTIPLIER int /* type for fastest integer multiply */ +#endif + + +/* FAST_FLOAT should be either float or double, whichever is done faster + * by your compiler. (Note that this type is only used in the floating point + * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.) + * Typically, float is faster in ANSI C compilers, while double is faster in + * pre-ANSI compilers (because they insist on converting to double anyway). + * The code below therefore chooses float if we have ANSI-style prototypes. + */ + +#ifndef FAST_FLOAT +#ifdef HAVE_PROTOTYPES +#define FAST_FLOAT float +#else +#define FAST_FLOAT double +#endif +#endif + +#endif /* JPEG_INTERNAL_OPTIONS */ diff --git a/cocos2dx/platform/third_party/emscripten/libjpeg/jpeglib.h b/cocos2dx/platform/third_party/emscripten/libjpeg/jpeglib.h new file mode 100644 index 0000000000..0a6dac44c3 --- /dev/null +++ b/cocos2dx/platform/third_party/emscripten/libjpeg/jpeglib.h @@ -0,0 +1,1173 @@ +/* + * jpeglib.h + * + * Copyright (C) 1991-1998, Thomas G. Lane. + * Modified 2002-2012 by Guido Vollbeding. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file defines the application interface for the JPEG library. + * Most applications using the library need only include this file, + * and perhaps jerror.h if they want to know the exact error codes. + */ + +#ifndef JPEGLIB_H +#define JPEGLIB_H + +/* + * First we include the configuration files that record how this + * installation of the JPEG library is set up. jconfig.h can be + * generated automatically for many systems. jmorecfg.h contains + * manual configuration options that most people need not worry about. + */ + +#ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */ +#include "jconfig.h" /* widely used configuration options */ +#endif +#include "jmorecfg.h" /* seldom changed options */ + + +#ifdef __cplusplus +#ifndef DONT_USE_EXTERN_C +extern "C" { +#endif +#endif + +/* Version IDs for the JPEG library. + * Might be useful for tests like "#if JPEG_LIB_VERSION >= 90". + */ + +#define JPEG_LIB_VERSION 90 /* Compatibility version 9.0 */ +#define JPEG_LIB_VERSION_MAJOR 9 +#define JPEG_LIB_VERSION_MINOR 0 + + +/* Various constants determining the sizes of things. + * All of these are specified by the JPEG standard, so don't change them + * if you want to be compatible. + */ + +#define DCTSIZE 8 /* The basic DCT block is 8x8 coefficients */ +#define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */ +#define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */ +#define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */ +#define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */ +#define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */ +#define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */ +/* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard; + * the PostScript DCT filter can emit files with many more than 10 blocks/MCU. + * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU + * to handle it. We even let you do this from the jconfig.h file. However, + * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe + * sometimes emits noncompliant files doesn't mean you should too. + */ +#define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */ +#ifndef D_MAX_BLOCKS_IN_MCU +#define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */ +#endif + + +/* Data structures for images (arrays of samples and of DCT coefficients). + * On 80x86 machines, the image arrays are too big for near pointers, + * but the pointer arrays can fit in near memory. + */ + +typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */ +typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */ +typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */ + +typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */ +typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */ +typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */ +typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */ + +typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */ + + +/* Types for JPEG compression parameters and working tables. */ + + +/* DCT coefficient quantization tables. */ + +typedef struct { + /* This array gives the coefficient quantizers in natural array order + * (not the zigzag order in which they are stored in a JPEG DQT marker). + * CAUTION: IJG versions prior to v6a kept this array in zigzag order. + */ + UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */ + /* This field is used only during compression. It's initialized FALSE when + * the table is created, and set TRUE when it's been output to the file. + * You could suppress output of a table by setting this to TRUE. + * (See jpeg_suppress_tables for an example.) + */ + boolean sent_table; /* TRUE when table has been output */ +} JQUANT_TBL; + + +/* Huffman coding tables. */ + +typedef struct { + /* These two fields directly represent the contents of a JPEG DHT marker */ + UINT8 bits[17]; /* bits[k] = # of symbols with codes of */ + /* length k bits; bits[0] is unused */ + UINT8 huffval[256]; /* The symbols, in order of incr code length */ + /* This field is used only during compression. It's initialized FALSE when + * the table is created, and set TRUE when it's been output to the file. + * You could suppress output of a table by setting this to TRUE. + * (See jpeg_suppress_tables for an example.) + */ + boolean sent_table; /* TRUE when table has been output */ +} JHUFF_TBL; + + +/* Basic info about one component (color channel). */ + +typedef struct { + /* These values are fixed over the whole image. */ + /* For compression, they must be supplied by parameter setup; */ + /* for decompression, they are read from the SOF marker. */ + int component_id; /* identifier for this component (0..255) */ + int component_index; /* its index in SOF or cinfo->comp_info[] */ + int h_samp_factor; /* horizontal sampling factor (1..4) */ + int v_samp_factor; /* vertical sampling factor (1..4) */ + int quant_tbl_no; /* quantization table selector (0..3) */ + /* These values may vary between scans. */ + /* For compression, they must be supplied by parameter setup; */ + /* for decompression, they are read from the SOS marker. */ + /* The decompressor output side may not use these variables. */ + int dc_tbl_no; /* DC entropy table selector (0..3) */ + int ac_tbl_no; /* AC entropy table selector (0..3) */ + + /* Remaining fields should be treated as private by applications. */ + + /* These values are computed during compression or decompression startup: */ + /* Component's size in DCT blocks. + * Any dummy blocks added to complete an MCU are not counted; therefore + * these values do not depend on whether a scan is interleaved or not. + */ + JDIMENSION width_in_blocks; + JDIMENSION height_in_blocks; + /* Size of a DCT block in samples, + * reflecting any scaling we choose to apply during the DCT step. + * Values from 1 to 16 are supported. + * Note that different components may receive different DCT scalings. + */ + int DCT_h_scaled_size; + int DCT_v_scaled_size; + /* The downsampled dimensions are the component's actual, unpadded number + * of samples at the main buffer (preprocessing/compression interface); + * DCT scaling is included, so + * downsampled_width = ceil(image_width * Hi/Hmax * DCT_h_scaled_size/DCTSIZE) + * and similarly for height. + */ + JDIMENSION downsampled_width; /* actual width in samples */ + JDIMENSION downsampled_height; /* actual height in samples */ + /* This flag is used only for decompression. In cases where some of the + * components will be ignored (eg grayscale output from YCbCr image), + * we can skip most computations for the unused components. + */ + boolean component_needed; /* do we need the value of this component? */ + + /* These values are computed before starting a scan of the component. */ + /* The decompressor output side may not use these variables. */ + int MCU_width; /* number of blocks per MCU, horizontally */ + int MCU_height; /* number of blocks per MCU, vertically */ + int MCU_blocks; /* MCU_width * MCU_height */ + int MCU_sample_width; /* MCU width in samples: MCU_width * DCT_h_scaled_size */ + int last_col_width; /* # of non-dummy blocks across in last MCU */ + int last_row_height; /* # of non-dummy blocks down in last MCU */ + + /* Saved quantization table for component; NULL if none yet saved. + * See jdinput.c comments about the need for this information. + * This field is currently used only for decompression. + */ + JQUANT_TBL * quant_table; + + /* Private per-component storage for DCT or IDCT subsystem. */ + void * dct_table; +} jpeg_component_info; + + +/* The script for encoding a multiple-scan file is an array of these: */ + +typedef struct { + int comps_in_scan; /* number of components encoded in this scan */ + int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */ + int Ss, Se; /* progressive JPEG spectral selection parms */ + int Ah, Al; /* progressive JPEG successive approx. parms */ +} jpeg_scan_info; + +/* The decompressor can save APPn and COM markers in a list of these: */ + +typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr; + +struct jpeg_marker_struct { + jpeg_saved_marker_ptr next; /* next in list, or NULL */ + UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */ + unsigned int original_length; /* # bytes of data in the file */ + unsigned int data_length; /* # bytes of data saved at data[] */ + JOCTET FAR * data; /* the data contained in the marker */ + /* the marker length word is not counted in data_length or original_length */ +}; + +/* Known color spaces. */ + +typedef enum { + JCS_UNKNOWN, /* error/unspecified */ + JCS_GRAYSCALE, /* monochrome */ + JCS_RGB, /* red/green/blue */ + JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */ + JCS_CMYK, /* C/M/Y/K */ + JCS_YCCK /* Y/Cb/Cr/K */ +} J_COLOR_SPACE; + +/* Supported color transforms. */ + +typedef enum { + JCT_NONE = 0, + JCT_SUBTRACT_GREEN = 1 +} J_COLOR_TRANSFORM; + +/* DCT/IDCT algorithm options. */ + +typedef enum { + JDCT_ISLOW, /* slow but accurate integer algorithm */ + JDCT_IFAST, /* faster, less accurate integer method */ + JDCT_FLOAT /* floating-point: accurate, fast on fast HW */ +} J_DCT_METHOD; + +#ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */ +#define JDCT_DEFAULT JDCT_ISLOW +#endif +#ifndef JDCT_FASTEST /* may be overridden in jconfig.h */ +#define JDCT_FASTEST JDCT_IFAST +#endif + +/* Dithering options for decompression. */ + +typedef enum { + JDITHER_NONE, /* no dithering */ + JDITHER_ORDERED, /* simple ordered dither */ + JDITHER_FS /* Floyd-Steinberg error diffusion dither */ +} J_DITHER_MODE; + + +/* Common fields between JPEG compression and decompression master structs. */ + +#define jpeg_common_fields \ + struct jpeg_error_mgr * err; /* Error handler module */\ + struct jpeg_memory_mgr * mem; /* Memory manager module */\ + struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\ + void * client_data; /* Available for use by application */\ + boolean is_decompressor; /* So common code can tell which is which */\ + int global_state /* For checking call sequence validity */ + +/* Routines that are to be used by both halves of the library are declared + * to receive a pointer to this structure. There are no actual instances of + * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct. + */ +struct jpeg_common_struct { + jpeg_common_fields; /* Fields common to both master struct types */ + /* Additional fields follow in an actual jpeg_compress_struct or + * jpeg_decompress_struct. All three structs must agree on these + * initial fields! (This would be a lot cleaner in C++.) + */ +}; + +typedef struct jpeg_common_struct * j_common_ptr; +typedef struct jpeg_compress_struct * j_compress_ptr; +typedef struct jpeg_decompress_struct * j_decompress_ptr; + + +/* Master record for a compression instance */ + +struct jpeg_compress_struct { + jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */ + + /* Destination for compressed data */ + struct jpeg_destination_mgr * dest; + + /* Description of source image --- these fields must be filled in by + * outer application before starting compression. in_color_space must + * be correct before you can even call jpeg_set_defaults(). + */ + + JDIMENSION image_width; /* input image width */ + JDIMENSION image_height; /* input image height */ + int input_components; /* # of color components in input image */ + J_COLOR_SPACE in_color_space; /* colorspace of input image */ + + double input_gamma; /* image gamma of input image */ + + /* Compression parameters --- these fields must be set before calling + * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to + * initialize everything to reasonable defaults, then changing anything + * the application specifically wants to change. That way you won't get + * burnt when new parameters are added. Also note that there are several + * helper routines to simplify changing parameters. + */ + + unsigned int scale_num, scale_denom; /* fraction by which to scale image */ + + JDIMENSION jpeg_width; /* scaled JPEG image width */ + JDIMENSION jpeg_height; /* scaled JPEG image height */ + /* Dimensions of actual JPEG image that will be written to file, + * derived from input dimensions by scaling factors above. + * These fields are computed by jpeg_start_compress(). + * You can also use jpeg_calc_jpeg_dimensions() to determine these values + * in advance of calling jpeg_start_compress(). + */ + + int data_precision; /* bits of precision in image data */ + + int num_components; /* # of color components in JPEG image */ + J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */ + + jpeg_component_info * comp_info; + /* comp_info[i] describes component that appears i'th in SOF */ + + JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS]; + int q_scale_factor[NUM_QUANT_TBLS]; + /* ptrs to coefficient quantization tables, or NULL if not defined, + * and corresponding scale factors (percentage, initialized 100). + */ + + JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS]; + JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS]; + /* ptrs to Huffman coding tables, or NULL if not defined */ + + UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */ + UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */ + UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */ + + int num_scans; /* # of entries in scan_info array */ + const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */ + /* The default value of scan_info is NULL, which causes a single-scan + * sequential JPEG file to be emitted. To create a multi-scan file, + * set num_scans and scan_info to point to an array of scan definitions. + */ + + boolean raw_data_in; /* TRUE=caller supplies downsampled data */ + boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */ + boolean optimize_coding; /* TRUE=optimize entropy encoding parms */ + boolean CCIR601_sampling; /* TRUE=first samples are cosited */ + boolean do_fancy_downsampling; /* TRUE=apply fancy downsampling */ + int smoothing_factor; /* 1..100, or 0 for no input smoothing */ + J_DCT_METHOD dct_method; /* DCT algorithm selector */ + + /* The restart interval can be specified in absolute MCUs by setting + * restart_interval, or in MCU rows by setting restart_in_rows + * (in which case the correct restart_interval will be figured + * for each scan). + */ + unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */ + int restart_in_rows; /* if > 0, MCU rows per restart interval */ + + /* Parameters controlling emission of special markers. */ + + boolean write_JFIF_header; /* should a JFIF marker be written? */ + UINT8 JFIF_major_version; /* What to write for the JFIF version number */ + UINT8 JFIF_minor_version; + /* These three values are not used by the JPEG code, merely copied */ + /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */ + /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */ + /* ratio is defined by X_density/Y_density even when density_unit=0. */ + UINT8 density_unit; /* JFIF code for pixel size units */ + UINT16 X_density; /* Horizontal pixel density */ + UINT16 Y_density; /* Vertical pixel density */ + boolean write_Adobe_marker; /* should an Adobe marker be written? */ + + J_COLOR_TRANSFORM color_transform; + /* Color transform identifier, writes LSE marker if nonzero */ + + /* State variable: index of next scanline to be written to + * jpeg_write_scanlines(). Application may use this to control its + * processing loop, e.g., "while (next_scanline < image_height)". + */ + + JDIMENSION next_scanline; /* 0 .. image_height-1 */ + + /* Remaining fields are known throughout compressor, but generally + * should not be touched by a surrounding application. + */ + + /* + * These fields are computed during compression startup + */ + boolean progressive_mode; /* TRUE if scan script uses progressive mode */ + int max_h_samp_factor; /* largest h_samp_factor */ + int max_v_samp_factor; /* largest v_samp_factor */ + + int min_DCT_h_scaled_size; /* smallest DCT_h_scaled_size of any component */ + int min_DCT_v_scaled_size; /* smallest DCT_v_scaled_size of any component */ + + JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */ + /* The coefficient controller receives data in units of MCU rows as defined + * for fully interleaved scans (whether the JPEG file is interleaved or not). + * There are v_samp_factor * DCTSIZE sample rows of each component in an + * "iMCU" (interleaved MCU) row. + */ + + /* + * These fields are valid during any one scan. + * They describe the components and MCUs actually appearing in the scan. + */ + int comps_in_scan; /* # of JPEG components in this scan */ + jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN]; + /* *cur_comp_info[i] describes component that appears i'th in SOS */ + + JDIMENSION MCUs_per_row; /* # of MCUs across the image */ + JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */ + + int blocks_in_MCU; /* # of DCT blocks per MCU */ + int MCU_membership[C_MAX_BLOCKS_IN_MCU]; + /* MCU_membership[i] is index in cur_comp_info of component owning */ + /* i'th block in an MCU */ + + int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */ + + int block_size; /* the basic DCT block size: 1..16 */ + const int * natural_order; /* natural-order position array */ + int lim_Se; /* min( Se, DCTSIZE2-1 ) */ + + /* + * Links to compression subobjects (methods and private variables of modules) + */ + struct jpeg_comp_master * master; + struct jpeg_c_main_controller * main; + struct jpeg_c_prep_controller * prep; + struct jpeg_c_coef_controller * coef; + struct jpeg_marker_writer * marker; + struct jpeg_color_converter * cconvert; + struct jpeg_downsampler * downsample; + struct jpeg_forward_dct * fdct; + struct jpeg_entropy_encoder * entropy; + jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */ + int script_space_size; +}; + + +/* Master record for a decompression instance */ + +struct jpeg_decompress_struct { + jpeg_common_fields; /* Fields shared with jpeg_compress_struct */ + + /* Source of compressed data */ + struct jpeg_source_mgr * src; + + /* Basic description of image --- filled in by jpeg_read_header(). */ + /* Application may inspect these values to decide how to process image. */ + + JDIMENSION image_width; /* nominal image width (from SOF marker) */ + JDIMENSION image_height; /* nominal image height */ + int num_components; /* # of color components in JPEG image */ + J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */ + + /* Decompression processing parameters --- these fields must be set before + * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes + * them to default values. + */ + + J_COLOR_SPACE out_color_space; /* colorspace for output */ + + unsigned int scale_num, scale_denom; /* fraction by which to scale image */ + + double output_gamma; /* image gamma wanted in output */ + + boolean buffered_image; /* TRUE=multiple output passes */ + boolean raw_data_out; /* TRUE=downsampled data wanted */ + + J_DCT_METHOD dct_method; /* IDCT algorithm selector */ + boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */ + boolean do_block_smoothing; /* TRUE=apply interblock smoothing */ + + boolean quantize_colors; /* TRUE=colormapped output wanted */ + /* the following are ignored if not quantize_colors: */ + J_DITHER_MODE dither_mode; /* type of color dithering to use */ + boolean two_pass_quantize; /* TRUE=use two-pass color quantization */ + int desired_number_of_colors; /* max # colors to use in created colormap */ + /* these are significant only in buffered-image mode: */ + boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */ + boolean enable_external_quant;/* enable future use of external colormap */ + boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */ + + /* Description of actual output image that will be returned to application. + * These fields are computed by jpeg_start_decompress(). + * You can also use jpeg_calc_output_dimensions() to determine these values + * in advance of calling jpeg_start_decompress(). + */ + + JDIMENSION output_width; /* scaled image width */ + JDIMENSION output_height; /* scaled image height */ + int out_color_components; /* # of color components in out_color_space */ + int output_components; /* # of color components returned */ + /* output_components is 1 (a colormap index) when quantizing colors; + * otherwise it equals out_color_components. + */ + int rec_outbuf_height; /* min recommended height of scanline buffer */ + /* If the buffer passed to jpeg_read_scanlines() is less than this many rows + * high, space and time will be wasted due to unnecessary data copying. + * Usually rec_outbuf_height will be 1 or 2, at most 4. + */ + + /* When quantizing colors, the output colormap is described by these fields. + * The application can supply a colormap by setting colormap non-NULL before + * calling jpeg_start_decompress; otherwise a colormap is created during + * jpeg_start_decompress or jpeg_start_output. + * The map has out_color_components rows and actual_number_of_colors columns. + */ + int actual_number_of_colors; /* number of entries in use */ + JSAMPARRAY colormap; /* The color map as a 2-D pixel array */ + + /* State variables: these variables indicate the progress of decompression. + * The application may examine these but must not modify them. + */ + + /* Row index of next scanline to be read from jpeg_read_scanlines(). + * Application may use this to control its processing loop, e.g., + * "while (output_scanline < output_height)". + */ + JDIMENSION output_scanline; /* 0 .. output_height-1 */ + + /* Current input scan number and number of iMCU rows completed in scan. + * These indicate the progress of the decompressor input side. + */ + int input_scan_number; /* Number of SOS markers seen so far */ + JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */ + + /* The "output scan number" is the notional scan being displayed by the + * output side. The decompressor will not allow output scan/row number + * to get ahead of input scan/row, but it can fall arbitrarily far behind. + */ + int output_scan_number; /* Nominal scan number being displayed */ + JDIMENSION output_iMCU_row; /* Number of iMCU rows read */ + + /* Current progression status. coef_bits[c][i] indicates the precision + * with which component c's DCT coefficient i (in zigzag order) is known. + * It is -1 when no data has yet been received, otherwise it is the point + * transform (shift) value for the most recent scan of the coefficient + * (thus, 0 at completion of the progression). + * This pointer is NULL when reading a non-progressive file. + */ + int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */ + + /* Internal JPEG parameters --- the application usually need not look at + * these fields. Note that the decompressor output side may not use + * any parameters that can change between scans. + */ + + /* Quantization and Huffman tables are carried forward across input + * datastreams when processing abbreviated JPEG datastreams. + */ + + JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS]; + /* ptrs to coefficient quantization tables, or NULL if not defined */ + + JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS]; + JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS]; + /* ptrs to Huffman coding tables, or NULL if not defined */ + + /* These parameters are never carried across datastreams, since they + * are given in SOF/SOS markers or defined to be reset by SOI. + */ + + int data_precision; /* bits of precision in image data */ + + jpeg_component_info * comp_info; + /* comp_info[i] describes component that appears i'th in SOF */ + + boolean is_baseline; /* TRUE if Baseline SOF0 encountered */ + boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */ + boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */ + + UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */ + UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */ + UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */ + + unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */ + + /* These fields record data obtained from optional markers recognized by + * the JPEG library. + */ + boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */ + /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */ + UINT8 JFIF_major_version; /* JFIF version number */ + UINT8 JFIF_minor_version; + UINT8 density_unit; /* JFIF code for pixel size units */ + UINT16 X_density; /* Horizontal pixel density */ + UINT16 Y_density; /* Vertical pixel density */ + boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */ + UINT8 Adobe_transform; /* Color transform code from Adobe marker */ + + J_COLOR_TRANSFORM color_transform; + /* Color transform identifier derived from LSE marker, otherwise zero */ + + boolean CCIR601_sampling; /* TRUE=first samples are cosited */ + + /* Aside from the specific data retained from APPn markers known to the + * library, the uninterpreted contents of any or all APPn and COM markers + * can be saved in a list for examination by the application. + */ + jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */ + + /* Remaining fields are known throughout decompressor, but generally + * should not be touched by a surrounding application. + */ + + /* + * These fields are computed during decompression startup + */ + int max_h_samp_factor; /* largest h_samp_factor */ + int max_v_samp_factor; /* largest v_samp_factor */ + + int min_DCT_h_scaled_size; /* smallest DCT_h_scaled_size of any component */ + int min_DCT_v_scaled_size; /* smallest DCT_v_scaled_size of any component */ + + JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */ + /* The coefficient controller's input and output progress is measured in + * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows + * in fully interleaved JPEG scans, but are used whether the scan is + * interleaved or not. We define an iMCU row as v_samp_factor DCT block + * rows of each component. Therefore, the IDCT output contains + * v_samp_factor*DCT_v_scaled_size sample rows of a component per iMCU row. + */ + + JSAMPLE * sample_range_limit; /* table for fast range-limiting */ + + /* + * These fields are valid during any one scan. + * They describe the components and MCUs actually appearing in the scan. + * Note that the decompressor output side must not use these fields. + */ + int comps_in_scan; /* # of JPEG components in this scan */ + jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN]; + /* *cur_comp_info[i] describes component that appears i'th in SOS */ + + JDIMENSION MCUs_per_row; /* # of MCUs across the image */ + JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */ + + int blocks_in_MCU; /* # of DCT blocks per MCU */ + int MCU_membership[D_MAX_BLOCKS_IN_MCU]; + /* MCU_membership[i] is index in cur_comp_info of component owning */ + /* i'th block in an MCU */ + + int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */ + + /* These fields are derived from Se of first SOS marker. + */ + int block_size; /* the basic DCT block size: 1..16 */ + const int * natural_order; /* natural-order position array for entropy decode */ + int lim_Se; /* min( Se, DCTSIZE2-1 ) for entropy decode */ + + /* This field is shared between entropy decoder and marker parser. + * It is either zero or the code of a JPEG marker that has been + * read from the data source, but has not yet been processed. + */ + int unread_marker; + + /* + * Links to decompression subobjects (methods, private variables of modules) + */ + struct jpeg_decomp_master * master; + struct jpeg_d_main_controller * main; + struct jpeg_d_coef_controller * coef; + struct jpeg_d_post_controller * post; + struct jpeg_input_controller * inputctl; + struct jpeg_marker_reader * marker; + struct jpeg_entropy_decoder * entropy; + struct jpeg_inverse_dct * idct; + struct jpeg_upsampler * upsample; + struct jpeg_color_deconverter * cconvert; + struct jpeg_color_quantizer * cquantize; +}; + + +/* "Object" declarations for JPEG modules that may be supplied or called + * directly by the surrounding application. + * As with all objects in the JPEG library, these structs only define the + * publicly visible methods and state variables of a module. Additional + * private fields may exist after the public ones. + */ + + +/* Error handler object */ + +struct jpeg_error_mgr { + /* Error exit handler: does not return to caller */ + JMETHOD(noreturn_t, error_exit, (j_common_ptr cinfo)); + /* Conditionally emit a trace or warning message */ + JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level)); + /* Routine that actually outputs a trace or error message */ + JMETHOD(void, output_message, (j_common_ptr cinfo)); + /* Format a message string for the most recent JPEG error or message */ + JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer)); +#define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */ + /* Reset error state variables at start of a new image */ + JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo)); + + /* The message ID code and any parameters are saved here. + * A message can have one string parameter or up to 8 int parameters. + */ + int msg_code; +#define JMSG_STR_PARM_MAX 80 + union { + int i[8]; + char s[JMSG_STR_PARM_MAX]; + } msg_parm; + + /* Standard state variables for error facility */ + + int trace_level; /* max msg_level that will be displayed */ + + /* For recoverable corrupt-data errors, we emit a warning message, + * but keep going unless emit_message chooses to abort. emit_message + * should count warnings in num_warnings. The surrounding application + * can check for bad data by seeing if num_warnings is nonzero at the + * end of processing. + */ + long num_warnings; /* number of corrupt-data warnings */ + + /* These fields point to the table(s) of error message strings. + * An application can change the table pointer to switch to a different + * message list (typically, to change the language in which errors are + * reported). Some applications may wish to add additional error codes + * that will be handled by the JPEG library error mechanism; the second + * table pointer is used for this purpose. + * + * First table includes all errors generated by JPEG library itself. + * Error code 0 is reserved for a "no such error string" message. + */ + const char * const * jpeg_message_table; /* Library errors */ + int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */ + /* Second table can be added by application (see cjpeg/djpeg for example). + * It contains strings numbered first_addon_message..last_addon_message. + */ + const char * const * addon_message_table; /* Non-library errors */ + int first_addon_message; /* code for first string in addon table */ + int last_addon_message; /* code for last string in addon table */ +}; + + +/* Progress monitor object */ + +struct jpeg_progress_mgr { + JMETHOD(void, progress_monitor, (j_common_ptr cinfo)); + + long pass_counter; /* work units completed in this pass */ + long pass_limit; /* total number of work units in this pass */ + int completed_passes; /* passes completed so far */ + int total_passes; /* total number of passes expected */ +}; + + +/* Data destination object for compression */ + +struct jpeg_destination_mgr { + JOCTET * next_output_byte; /* => next byte to write in buffer */ + size_t free_in_buffer; /* # of byte spaces remaining in buffer */ + + JMETHOD(void, init_destination, (j_compress_ptr cinfo)); + JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo)); + JMETHOD(void, term_destination, (j_compress_ptr cinfo)); +}; + + +/* Data source object for decompression */ + +struct jpeg_source_mgr { + const JOCTET * next_input_byte; /* => next byte to read from buffer */ + size_t bytes_in_buffer; /* # of bytes remaining in buffer */ + + JMETHOD(void, init_source, (j_decompress_ptr cinfo)); + JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo)); + JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes)); + JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired)); + JMETHOD(void, term_source, (j_decompress_ptr cinfo)); +}; + + +/* Memory manager object. + * Allocates "small" objects (a few K total), "large" objects (tens of K), + * and "really big" objects (virtual arrays with backing store if needed). + * The memory manager does not allow individual objects to be freed; rather, + * each created object is assigned to a pool, and whole pools can be freed + * at once. This is faster and more convenient than remembering exactly what + * to free, especially where malloc()/free() are not too speedy. + * NB: alloc routines never return NULL. They exit to error_exit if not + * successful. + */ + +#define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */ +#define JPOOL_IMAGE 1 /* lasts until done with image/datastream */ +#define JPOOL_NUMPOOLS 2 + +typedef struct jvirt_sarray_control * jvirt_sarray_ptr; +typedef struct jvirt_barray_control * jvirt_barray_ptr; + + +struct jpeg_memory_mgr { + /* Method pointers */ + JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id, + size_t sizeofobject)); + JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id, + size_t sizeofobject)); + JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id, + JDIMENSION samplesperrow, + JDIMENSION numrows)); + JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id, + JDIMENSION blocksperrow, + JDIMENSION numrows)); + JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo, + int pool_id, + boolean pre_zero, + JDIMENSION samplesperrow, + JDIMENSION numrows, + JDIMENSION maxaccess)); + JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo, + int pool_id, + boolean pre_zero, + JDIMENSION blocksperrow, + JDIMENSION numrows, + JDIMENSION maxaccess)); + JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo)); + JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo, + jvirt_sarray_ptr ptr, + JDIMENSION start_row, + JDIMENSION num_rows, + boolean writable)); + JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo, + jvirt_barray_ptr ptr, + JDIMENSION start_row, + JDIMENSION num_rows, + boolean writable)); + JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id)); + JMETHOD(void, self_destruct, (j_common_ptr cinfo)); + + /* Limit on memory allocation for this JPEG object. (Note that this is + * merely advisory, not a guaranteed maximum; it only affects the space + * used for virtual-array buffers.) May be changed by outer application + * after creating the JPEG object. + */ + long max_memory_to_use; + + /* Maximum allocation request accepted by alloc_large. */ + long max_alloc_chunk; +}; + + +/* Routine signature for application-supplied marker processing methods. + * Need not pass marker code since it is stored in cinfo->unread_marker. + */ +typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo)); + + +/* Declarations for routines called by application. + * The JPP macro hides prototype parameters from compilers that can't cope. + * Note JPP requires double parentheses. + */ + +#ifdef HAVE_PROTOTYPES +#define JPP(arglist) arglist +#else +#define JPP(arglist) () +#endif + + +/* Short forms of external names for systems with brain-damaged linkers. + * We shorten external names to be unique in the first six letters, which + * is good enough for all known systems. + * (If your compiler itself needs names to be unique in less than 15 + * characters, you are out of luck. Get a better compiler.) + */ + +#ifdef NEED_SHORT_EXTERNAL_NAMES +#define jpeg_std_error jStdError +#define jpeg_CreateCompress jCreaCompress +#define jpeg_CreateDecompress jCreaDecompress +#define jpeg_destroy_compress jDestCompress +#define jpeg_destroy_decompress jDestDecompress +#define jpeg_stdio_dest jStdDest +#define jpeg_stdio_src jStdSrc +#define jpeg_mem_dest jMemDest +#define jpeg_mem_src jMemSrc +#define jpeg_set_defaults jSetDefaults +#define jpeg_set_colorspace jSetColorspace +#define jpeg_default_colorspace jDefColorspace +#define jpeg_set_quality jSetQuality +#define jpeg_set_linear_quality jSetLQuality +#define jpeg_default_qtables jDefQTables +#define jpeg_add_quant_table jAddQuantTable +#define jpeg_quality_scaling jQualityScaling +#define jpeg_simple_progression jSimProgress +#define jpeg_suppress_tables jSuppressTables +#define jpeg_alloc_quant_table jAlcQTable +#define jpeg_alloc_huff_table jAlcHTable +#define jpeg_start_compress jStrtCompress +#define jpeg_write_scanlines jWrtScanlines +#define jpeg_finish_compress jFinCompress +#define jpeg_calc_jpeg_dimensions jCjpegDimensions +#define jpeg_write_raw_data jWrtRawData +#define jpeg_write_marker jWrtMarker +#define jpeg_write_m_header jWrtMHeader +#define jpeg_write_m_byte jWrtMByte +#define jpeg_write_tables jWrtTables +#define jpeg_read_header jReadHeader +#define jpeg_start_decompress jStrtDecompress +#define jpeg_read_scanlines jReadScanlines +#define jpeg_finish_decompress jFinDecompress +#define jpeg_read_raw_data jReadRawData +#define jpeg_has_multiple_scans jHasMultScn +#define jpeg_start_output jStrtOutput +#define jpeg_finish_output jFinOutput +#define jpeg_input_complete jInComplete +#define jpeg_new_colormap jNewCMap +#define jpeg_consume_input jConsumeInput +#define jpeg_core_output_dimensions jCoreDimensions +#define jpeg_calc_output_dimensions jCalcDimensions +#define jpeg_save_markers jSaveMarkers +#define jpeg_set_marker_processor jSetMarker +#define jpeg_read_coefficients jReadCoefs +#define jpeg_write_coefficients jWrtCoefs +#define jpeg_copy_critical_parameters jCopyCrit +#define jpeg_abort_compress jAbrtCompress +#define jpeg_abort_decompress jAbrtDecompress +#define jpeg_abort jAbort +#define jpeg_destroy jDestroy +#define jpeg_resync_to_restart jResyncRestart +#endif /* NEED_SHORT_EXTERNAL_NAMES */ + + +/* Default error-management setup */ +EXTERN(struct jpeg_error_mgr *) jpeg_std_error + JPP((struct jpeg_error_mgr * err)); + +/* Initialization of JPEG compression objects. + * jpeg_create_compress() and jpeg_create_decompress() are the exported + * names that applications should call. These expand to calls on + * jpeg_CreateCompress and jpeg_CreateDecompress with additional information + * passed for version mismatch checking. + * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx. + */ +#define jpeg_create_compress(cinfo) \ + jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \ + (size_t) sizeof(struct jpeg_compress_struct)) +#define jpeg_create_decompress(cinfo) \ + jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \ + (size_t) sizeof(struct jpeg_decompress_struct)) +EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo, + int version, size_t structsize)); +EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo, + int version, size_t structsize)); +/* Destruction of JPEG compression objects */ +EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo)); +EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo)); + +/* Standard data source and destination managers: stdio streams. */ +/* Caller is responsible for opening the file before and closing after. */ +EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile)); +EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile)); + +/* Data source and destination managers: memory buffers. */ +EXTERN(void) jpeg_mem_dest JPP((j_compress_ptr cinfo, + unsigned char ** outbuffer, + unsigned long * outsize)); +EXTERN(void) jpeg_mem_src JPP((j_decompress_ptr cinfo, + unsigned char * inbuffer, + unsigned long insize)); + +/* Default parameter setup for compression */ +EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo)); +/* Compression parameter setup aids */ +EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo, + J_COLOR_SPACE colorspace)); +EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo)); +EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality, + boolean force_baseline)); +EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo, + int scale_factor, + boolean force_baseline)); +EXTERN(void) jpeg_default_qtables JPP((j_compress_ptr cinfo, + boolean force_baseline)); +EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl, + const unsigned int *basic_table, + int scale_factor, + boolean force_baseline)); +EXTERN(int) jpeg_quality_scaling JPP((int quality)); +EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo)); +EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo, + boolean suppress)); +EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo)); +EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo)); + +/* Main entry points for compression */ +EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo, + boolean write_all_tables)); +EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo, + JSAMPARRAY scanlines, + JDIMENSION num_lines)); +EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo)); + +/* Precalculate JPEG dimensions for current compression parameters. */ +EXTERN(void) jpeg_calc_jpeg_dimensions JPP((j_compress_ptr cinfo)); + +/* Replaces jpeg_write_scanlines when writing raw downsampled data. */ +EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo, + JSAMPIMAGE data, + JDIMENSION num_lines)); + +/* Write a special marker. See libjpeg.txt concerning safe usage. */ +EXTERN(void) jpeg_write_marker + JPP((j_compress_ptr cinfo, int marker, + const JOCTET * dataptr, unsigned int datalen)); +/* Same, but piecemeal. */ +EXTERN(void) jpeg_write_m_header + JPP((j_compress_ptr cinfo, int marker, unsigned int datalen)); +EXTERN(void) jpeg_write_m_byte + JPP((j_compress_ptr cinfo, int val)); + +/* Alternate compression function: just write an abbreviated table file */ +EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo)); + +/* Decompression startup: read start of JPEG datastream to see what's there */ +EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo, + boolean require_image)); +/* Return value is one of: */ +#define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */ +#define JPEG_HEADER_OK 1 /* Found valid image datastream */ +#define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */ +/* If you pass require_image = TRUE (normal case), you need not check for + * a TABLES_ONLY return code; an abbreviated file will cause an error exit. + * JPEG_SUSPENDED is only possible if you use a data source module that can + * give a suspension return (the stdio source module doesn't). + */ + +/* Main entry points for decompression */ +EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo)); +EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo, + JSAMPARRAY scanlines, + JDIMENSION max_lines)); +EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo)); + +/* Replaces jpeg_read_scanlines when reading raw downsampled data. */ +EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo, + JSAMPIMAGE data, + JDIMENSION max_lines)); + +/* Additional entry points for buffered-image mode. */ +EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo)); +EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo, + int scan_number)); +EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo)); +EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo)); +EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo)); +EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo)); +/* Return value is one of: */ +/* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */ +#define JPEG_REACHED_SOS 1 /* Reached start of new scan */ +#define JPEG_REACHED_EOI 2 /* Reached end of image */ +#define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */ +#define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */ + +/* Precalculate output dimensions for current decompression parameters. */ +EXTERN(void) jpeg_core_output_dimensions JPP((j_decompress_ptr cinfo)); +EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo)); + +/* Control saving of COM and APPn markers into marker_list. */ +EXTERN(void) jpeg_save_markers + JPP((j_decompress_ptr cinfo, int marker_code, + unsigned int length_limit)); + +/* Install a special processing method for COM or APPn markers. */ +EXTERN(void) jpeg_set_marker_processor + JPP((j_decompress_ptr cinfo, int marker_code, + jpeg_marker_parser_method routine)); + +/* Read or write raw DCT coefficients --- useful for lossless transcoding. */ +EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo)); +EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo, + jvirt_barray_ptr * coef_arrays)); +EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo, + j_compress_ptr dstinfo)); + +/* If you choose to abort compression or decompression before completing + * jpeg_finish_(de)compress, then you need to clean up to release memory, + * temporary files, etc. You can just call jpeg_destroy_(de)compress + * if you're done with the JPEG object, but if you want to clean it up and + * reuse it, call this: + */ +EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo)); +EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo)); + +/* Generic versions of jpeg_abort and jpeg_destroy that work on either + * flavor of JPEG object. These may be more convenient in some places. + */ +EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo)); +EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo)); + +/* Default restart-marker-resync procedure for use by data source modules */ +EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo, + int desired)); + + +/* These marker codes are exported since applications and data source modules + * are likely to want to use them. + */ + +#define JPEG_RST0 0xD0 /* RST0 marker code */ +#define JPEG_EOI 0xD9 /* EOI marker code */ +#define JPEG_APP0 0xE0 /* APP0 marker code */ +#define JPEG_COM 0xFE /* COM marker code */ + + +/* If we have a brain-damaged compiler that emits warnings (or worse, errors) + * for structure definitions that are never filled in, keep it quiet by + * supplying dummy definitions for the various substructures. + */ + +#ifdef INCOMPLETE_TYPES_BROKEN +#ifndef JPEG_INTERNALS /* will be defined in jpegint.h */ +struct jvirt_sarray_control { long dummy; }; +struct jvirt_barray_control { long dummy; }; +struct jpeg_comp_master { long dummy; }; +struct jpeg_c_main_controller { long dummy; }; +struct jpeg_c_prep_controller { long dummy; }; +struct jpeg_c_coef_controller { long dummy; }; +struct jpeg_marker_writer { long dummy; }; +struct jpeg_color_converter { long dummy; }; +struct jpeg_downsampler { long dummy; }; +struct jpeg_forward_dct { long dummy; }; +struct jpeg_entropy_encoder { long dummy; }; +struct jpeg_decomp_master { long dummy; }; +struct jpeg_d_main_controller { long dummy; }; +struct jpeg_d_coef_controller { long dummy; }; +struct jpeg_d_post_controller { long dummy; }; +struct jpeg_input_controller { long dummy; }; +struct jpeg_marker_reader { long dummy; }; +struct jpeg_entropy_decoder { long dummy; }; +struct jpeg_inverse_dct { long dummy; }; +struct jpeg_upsampler { long dummy; }; +struct jpeg_color_deconverter { long dummy; }; +struct jpeg_color_quantizer { long dummy; }; +#endif /* JPEG_INTERNALS */ +#endif /* INCOMPLETE_TYPES_BROKEN */ + + +/* + * The JPEG library modules define JPEG_INTERNALS before including this file. + * The internal structure declarations are read only when that is true. + * Applications using the library should not include jpegint.h, but may wish + * to include jerror.h. + */ + +#ifdef JPEG_INTERNALS +#include "jpegint.h" /* fetch private declarations */ +#include "jerror.h" /* fetch error codes too */ +#endif + +#ifdef __cplusplus +#ifndef DONT_USE_EXTERN_C +} +#endif +#endif + +#endif /* JPEGLIB_H */ diff --git a/cocos2dx/platform/third_party/emscripten/libraries/README b/cocos2dx/platform/third_party/emscripten/libraries/README index 44fabfeb9d..e7e6ca1a4d 100644 --- a/cocos2dx/platform/third_party/emscripten/libraries/README +++ b/cocos2dx/platform/third_party/emscripten/libraries/README @@ -1,4 +1,6 @@ libfreetype.a from Emscripten test-suite libpng.a from https://github.com/hachque-Emscripten/libpng-1.2.49.git libz.a from https://github.com/hachque-Emscripten/zlib-1.2.5.git -libxml2.z from https://github.com/kripken/xml.js -- configure flags: emconfigure ./configure --with-http=no --with-ftp=no --prefix=/tmp/lx --with-python=no --with-threads=no +libxml2.a from https://github.com/kripken/xml.js -- configure flags: emconfigure ./configure --with-http=no --with-ftp=no --prefix=/tmp/lx --with-python=no --with-threads=no +libwebp.a from https://code.google.com/p/webp/downloads/detail?name=libwebp-0.3.0.tar.gz -- configure with ./configure --disable-threading --prefix=/tmp/libwebp + diff --git a/cocos2dx/platform/third_party/emscripten/libraries/libjpeg.a.REMOVED.git-id b/cocos2dx/platform/third_party/emscripten/libraries/libjpeg.a.REMOVED.git-id new file mode 100644 index 0000000000..1fd6c3fe1d --- /dev/null +++ b/cocos2dx/platform/third_party/emscripten/libraries/libjpeg.a.REMOVED.git-id @@ -0,0 +1 @@ +aae3f71d9c2edfe0ea1879a923faf2f656791de1 \ No newline at end of file diff --git a/cocos2dx/platform/third_party/emscripten/libraries/libwebp.a.REMOVED.git-id b/cocos2dx/platform/third_party/emscripten/libraries/libwebp.a.REMOVED.git-id new file mode 100644 index 0000000000..cbd761aa07 --- /dev/null +++ b/cocos2dx/platform/third_party/emscripten/libraries/libwebp.a.REMOVED.git-id @@ -0,0 +1 @@ +1bb3fc4bf9525afd8919ad7493e76dd208f48064 \ No newline at end of file diff --git a/cocos2dx/platform/third_party/emscripten/libwebp/webp/decode.h b/cocos2dx/platform/third_party/emscripten/libwebp/webp/decode.h new file mode 100644 index 0000000000..181eb18605 --- /dev/null +++ b/cocos2dx/platform/third_party/emscripten/libwebp/webp/decode.h @@ -0,0 +1,482 @@ +// Copyright 2010 Google Inc. All Rights Reserved. +// +// This code is licensed under the same terms as WebM: +// Software License Agreement: http://www.webmproject.org/license/software/ +// Additional IP Rights Grant: http://www.webmproject.org/license/additional/ +// ----------------------------------------------------------------------------- +// +// Main decoding functions for WebP images. +// +// Author: Skal (pascal.massimino@gmail.com) + +#ifndef WEBP_WEBP_DECODE_H_ +#define WEBP_WEBP_DECODE_H_ + +#include "./types.h" + +#if defined(__cplusplus) || defined(c_plusplus) +extern "C" { +#endif + +#define WEBP_DECODER_ABI_VERSION 0x0201 // MAJOR(8b) + MINOR(8b) + +typedef struct WebPRGBABuffer WebPRGBABuffer; +typedef struct WebPYUVABuffer WebPYUVABuffer; +typedef struct WebPDecBuffer WebPDecBuffer; +#if !(defined(__cplusplus) || defined(c_plusplus)) +typedef enum VP8StatusCode VP8StatusCode; +typedef enum WEBP_CSP_MODE WEBP_CSP_MODE; +#endif +typedef struct WebPIDecoder WebPIDecoder; +typedef struct WebPBitstreamFeatures WebPBitstreamFeatures; +typedef struct WebPDecoderOptions WebPDecoderOptions; +typedef struct WebPDecoderConfig WebPDecoderConfig; + +// Return the decoder's version number, packed in hexadecimal using 8bits for +// each of major/minor/revision. E.g: v2.5.7 is 0x020507. +WEBP_EXTERN(int) WebPGetDecoderVersion(void); + +// Retrieve basic header information: width, height. +// This function will also validate the header and return 0 in +// case of formatting error. +// Pointers 'width' and 'height' can be passed NULL if deemed irrelevant. +WEBP_EXTERN(int) WebPGetInfo(const uint8_t* data, size_t data_size, + int* width, int* height); + +// Decodes WebP images pointed to by 'data' and returns RGBA samples, along +// with the dimensions in *width and *height. The ordering of samples in +// memory is R, G, B, A, R, G, B, A... in scan order (endian-independent). +// The returned pointer should be deleted calling free(). +// Returns NULL in case of error. +WEBP_EXTERN(uint8_t*) WebPDecodeRGBA(const uint8_t* data, size_t data_size, + int* width, int* height); + +// Same as WebPDecodeRGBA, but returning A, R, G, B, A, R, G, B... ordered data. +WEBP_EXTERN(uint8_t*) WebPDecodeARGB(const uint8_t* data, size_t data_size, + int* width, int* height); + +// Same as WebPDecodeRGBA, but returning B, G, R, A, B, G, R, A... ordered data. +WEBP_EXTERN(uint8_t*) WebPDecodeBGRA(const uint8_t* data, size_t data_size, + int* width, int* height); + +// Same as WebPDecodeRGBA, but returning R, G, B, R, G, B... ordered data. +// If the bitstream contains transparency, it is ignored. +WEBP_EXTERN(uint8_t*) WebPDecodeRGB(const uint8_t* data, size_t data_size, + int* width, int* height); + +// Same as WebPDecodeRGB, but returning B, G, R, B, G, R... ordered data. +WEBP_EXTERN(uint8_t*) WebPDecodeBGR(const uint8_t* data, size_t data_size, + int* width, int* height); + + +// Decode WebP images pointed to by 'data' to Y'UV format(*). The pointer +// returned is the Y samples buffer. Upon return, *u and *v will point to +// the U and V chroma data. These U and V buffers need NOT be free()'d, +// unlike the returned Y luma one. The dimension of the U and V planes +// are both (*width + 1) / 2 and (*height + 1)/ 2. +// Upon return, the Y buffer has a stride returned as '*stride', while U and V +// have a common stride returned as '*uv_stride'. +// Return NULL in case of error. +// (*) Also named Y'CbCr. See: http://en.wikipedia.org/wiki/YCbCr +WEBP_EXTERN(uint8_t*) WebPDecodeYUV(const uint8_t* data, size_t data_size, + int* width, int* height, + uint8_t** u, uint8_t** v, + int* stride, int* uv_stride); + +// These five functions are variants of the above ones, that decode the image +// directly into a pre-allocated buffer 'output_buffer'. The maximum storage +// available in this buffer is indicated by 'output_buffer_size'. If this +// storage is not sufficient (or an error occurred), NULL is returned. +// Otherwise, output_buffer is returned, for convenience. +// The parameter 'output_stride' specifies the distance (in bytes) +// between scanlines. Hence, output_buffer_size is expected to be at least +// output_stride x picture-height. +WEBP_EXTERN(uint8_t*) WebPDecodeRGBAInto( + const uint8_t* data, size_t data_size, + uint8_t* output_buffer, size_t output_buffer_size, int output_stride); +WEBP_EXTERN(uint8_t*) WebPDecodeARGBInto( + const uint8_t* data, size_t data_size, + uint8_t* output_buffer, size_t output_buffer_size, int output_stride); +WEBP_EXTERN(uint8_t*) WebPDecodeBGRAInto( + const uint8_t* data, size_t data_size, + uint8_t* output_buffer, size_t output_buffer_size, int output_stride); + +// RGB and BGR variants. Here too the transparency information, if present, +// will be dropped and ignored. +WEBP_EXTERN(uint8_t*) WebPDecodeRGBInto( + const uint8_t* data, size_t data_size, + uint8_t* output_buffer, size_t output_buffer_size, int output_stride); +WEBP_EXTERN(uint8_t*) WebPDecodeBGRInto( + const uint8_t* data, size_t data_size, + uint8_t* output_buffer, size_t output_buffer_size, int output_stride); + +// WebPDecodeYUVInto() is a variant of WebPDecodeYUV() that operates directly +// into pre-allocated luma/chroma plane buffers. This function requires the +// strides to be passed: one for the luma plane and one for each of the +// chroma ones. The size of each plane buffer is passed as 'luma_size', +// 'u_size' and 'v_size' respectively. +// Pointer to the luma plane ('*luma') is returned or NULL if an error occurred +// during decoding (or because some buffers were found to be too small). +WEBP_EXTERN(uint8_t*) WebPDecodeYUVInto( + const uint8_t* data, size_t data_size, + uint8_t* luma, size_t luma_size, int luma_stride, + uint8_t* u, size_t u_size, int u_stride, + uint8_t* v, size_t v_size, int v_stride); + +//------------------------------------------------------------------------------ +// Output colorspaces and buffer + +// Colorspaces +// Note: the naming describes the byte-ordering of packed samples in memory. +// For instance, MODE_BGRA relates to samples ordered as B,G,R,A,B,G,R,A,... +// Non-capital names (e.g.:MODE_Argb) relates to pre-multiplied RGB channels. +// RGBA-4444 and RGB-565 colorspaces are represented by following byte-order: +// RGBA-4444: [r3 r2 r1 r0 g3 g2 g1 g0], [b3 b2 b1 b0 a3 a2 a1 a0], ... +// RGB-565: [r4 r3 r2 r1 r0 g5 g4 g3], [g2 g1 g0 b4 b3 b2 b1 b0], ... +// In the case WEBP_SWAP_16BITS_CSP is defined, the bytes are swapped for +// these two modes: +// RGBA-4444: [b3 b2 b1 b0 a3 a2 a1 a0], [r3 r2 r1 r0 g3 g2 g1 g0], ... +// RGB-565: [g2 g1 g0 b4 b3 b2 b1 b0], [r4 r3 r2 r1 r0 g5 g4 g3], ... + +enum WEBP_CSP_MODE { + MODE_RGB = 0, MODE_RGBA = 1, + MODE_BGR = 2, MODE_BGRA = 3, + MODE_ARGB = 4, MODE_RGBA_4444 = 5, + MODE_RGB_565 = 6, + // RGB-premultiplied transparent modes (alpha value is preserved) + MODE_rgbA = 7, + MODE_bgrA = 8, + MODE_Argb = 9, + MODE_rgbA_4444 = 10, + // YUV modes must come after RGB ones. + MODE_YUV = 11, MODE_YUVA = 12, // yuv 4:2:0 + MODE_LAST = 13 +}; + +// Some useful macros: +static WEBP_INLINE int WebPIsPremultipliedMode(WEBP_CSP_MODE mode) { + return (mode == MODE_rgbA || mode == MODE_bgrA || mode == MODE_Argb || + mode == MODE_rgbA_4444); +} + +static WEBP_INLINE int WebPIsAlphaMode(WEBP_CSP_MODE mode) { + return (mode == MODE_RGBA || mode == MODE_BGRA || mode == MODE_ARGB || + mode == MODE_RGBA_4444 || mode == MODE_YUVA || + WebPIsPremultipliedMode(mode)); +} + +static WEBP_INLINE int WebPIsRGBMode(WEBP_CSP_MODE mode) { + return (mode < MODE_YUV); +} + +//------------------------------------------------------------------------------ +// WebPDecBuffer: Generic structure for describing the output sample buffer. + +struct WebPRGBABuffer { // view as RGBA + uint8_t* rgba; // pointer to RGBA samples + int stride; // stride in bytes from one scanline to the next. + size_t size; // total size of the *rgba buffer. +}; + +struct WebPYUVABuffer { // view as YUVA + uint8_t* y, *u, *v, *a; // pointer to luma, chroma U/V, alpha samples + int y_stride; // luma stride + int u_stride, v_stride; // chroma strides + int a_stride; // alpha stride + size_t y_size; // luma plane size + size_t u_size, v_size; // chroma planes size + size_t a_size; // alpha-plane size +}; + +// Output buffer +struct WebPDecBuffer { + WEBP_CSP_MODE colorspace; // Colorspace. + int width, height; // Dimensions. + int is_external_memory; // If true, 'internal_memory' pointer is not used. + union { + WebPRGBABuffer RGBA; + WebPYUVABuffer YUVA; + } u; // Nameless union of buffer parameters. + uint32_t pad[4]; // padding for later use + + uint8_t* private_memory; // Internally allocated memory (only when + // is_external_memory is false). Should not be used + // externally, but accessed via the buffer union. +}; + +// Internal, version-checked, entry point +WEBP_EXTERN(int) WebPInitDecBufferInternal(WebPDecBuffer*, int); + +// Initialize the structure as empty. Must be called before any other use. +// Returns false in case of version mismatch +static WEBP_INLINE int WebPInitDecBuffer(WebPDecBuffer* buffer) { + return WebPInitDecBufferInternal(buffer, WEBP_DECODER_ABI_VERSION); +} + +// Free any memory associated with the buffer. Must always be called last. +// Note: doesn't free the 'buffer' structure itself. +WEBP_EXTERN(void) WebPFreeDecBuffer(WebPDecBuffer* buffer); + +//------------------------------------------------------------------------------ +// Enumeration of the status codes + +enum VP8StatusCode { + VP8_STATUS_OK = 0, + VP8_STATUS_OUT_OF_MEMORY, + VP8_STATUS_INVALID_PARAM, + VP8_STATUS_BITSTREAM_ERROR, + VP8_STATUS_UNSUPPORTED_FEATURE, + VP8_STATUS_SUSPENDED, + VP8_STATUS_USER_ABORT, + VP8_STATUS_NOT_ENOUGH_DATA +}; + +//------------------------------------------------------------------------------ +// Incremental decoding +// +// This API allows streamlined decoding of partial data. +// Picture can be incrementally decoded as data become available thanks to the +// WebPIDecoder object. This object can be left in a SUSPENDED state if the +// picture is only partially decoded, pending additional input. +// Code example: +// +// WebPInitDecBuffer(&buffer); +// buffer.colorspace = mode; +// ... +// WebPIDecoder* idec = WebPINewDecoder(&buffer); +// while (has_more_data) { +// // ... (get additional data) +// status = WebPIAppend(idec, new_data, new_data_size); +// if (status != VP8_STATUS_SUSPENDED || +// break; +// } +// +// // The above call decodes the current available buffer. +// // Part of the image can now be refreshed by calling to +// // WebPIDecGetRGB()/WebPIDecGetYUVA() etc. +// } +// WebPIDelete(idec); + +// Creates a new incremental decoder with the supplied buffer parameter. +// This output_buffer can be passed NULL, in which case a default output buffer +// is used (with MODE_RGB). Otherwise, an internal reference to 'output_buffer' +// is kept, which means that the lifespan of 'output_buffer' must be larger than +// that of the returned WebPIDecoder object. +// Returns NULL if the allocation failed. +WEBP_EXTERN(WebPIDecoder*) WebPINewDecoder(WebPDecBuffer* output_buffer); + +// This function allocates and initializes an incremental-decoder object, which +// will output the RGB/A samples specified by 'csp' into a preallocated +// buffer 'output_buffer'. The size of this buffer is at least +// 'output_buffer_size' and the stride (distance in bytes between two scanlines) +// is specified by 'output_stride'. +// Additionally, output_buffer can be passed NULL in which case the output +// buffer will be allocated automatically when the decoding starts. The +// colorspace 'csp' is taken into account for allocating this buffer. All other +// parameters are ignored. +// Returns NULL if the allocation failed, or if some parameters are invalid. +WEBP_EXTERN(WebPIDecoder*) WebPINewRGB( + WEBP_CSP_MODE csp, + uint8_t* output_buffer, size_t output_buffer_size, int output_stride); + +// This function allocates and initializes an incremental-decoder object, which +// will output the raw luma/chroma samples into a preallocated planes if +// supplied. The luma plane is specified by its pointer 'luma', its size +// 'luma_size' and its stride 'luma_stride'. Similarly, the chroma-u plane +// is specified by the 'u', 'u_size' and 'u_stride' parameters, and the chroma-v +// plane by 'v' and 'v_size'. And same for the alpha-plane. The 'a' pointer +// can be pass NULL in case one is not interested in the transparency plane. +// Conversely, 'luma' can be passed NULL if no preallocated planes are supplied. +// In this case, the output buffer will be automatically allocated (using +// MODE_YUVA) when decoding starts. All parameters are then ignored. +// Returns NULL if the allocation failed or if a parameter is invalid. +WEBP_EXTERN(WebPIDecoder*) WebPINewYUVA( + uint8_t* luma, size_t luma_size, int luma_stride, + uint8_t* u, size_t u_size, int u_stride, + uint8_t* v, size_t v_size, int v_stride, + uint8_t* a, size_t a_size, int a_stride); + +// Deprecated version of the above, without the alpha plane. +// Kept for backward compatibility. +WEBP_EXTERN(WebPIDecoder*) WebPINewYUV( + uint8_t* luma, size_t luma_size, int luma_stride, + uint8_t* u, size_t u_size, int u_stride, + uint8_t* v, size_t v_size, int v_stride); + +// Deletes the WebPIDecoder object and associated memory. Must always be called +// if WebPINewDecoder, WebPINewRGB or WebPINewYUV succeeded. +WEBP_EXTERN(void) WebPIDelete(WebPIDecoder* idec); + +// Copies and decodes the next available data. Returns VP8_STATUS_OK when +// the image is successfully decoded. Returns VP8_STATUS_SUSPENDED when more +// data is expected. Returns error in other cases. +WEBP_EXTERN(VP8StatusCode) WebPIAppend( + WebPIDecoder* idec, const uint8_t* data, size_t data_size); + +// A variant of the above function to be used when data buffer contains +// partial data from the beginning. In this case data buffer is not copied +// to the internal memory. +// Note that the value of the 'data' pointer can change between calls to +// WebPIUpdate, for instance when the data buffer is resized to fit larger data. +WEBP_EXTERN(VP8StatusCode) WebPIUpdate( + WebPIDecoder* idec, const uint8_t* data, size_t data_size); + +// Returns the RGB/A image decoded so far. Returns NULL if output params +// are not initialized yet. The RGB/A output type corresponds to the colorspace +// specified during call to WebPINewDecoder() or WebPINewRGB(). +// *last_y is the index of last decoded row in raster scan order. Some pointers +// (*last_y, *width etc.) can be NULL if corresponding information is not +// needed. +WEBP_EXTERN(uint8_t*) WebPIDecGetRGB( + const WebPIDecoder* idec, int* last_y, + int* width, int* height, int* stride); + +// Same as above function to get a YUVA image. Returns pointer to the luma +// plane or NULL in case of error. If there is no alpha information +// the alpha pointer '*a' will be returned NULL. +WEBP_EXTERN(uint8_t*) WebPIDecGetYUVA( + const WebPIDecoder* idec, int* last_y, + uint8_t** u, uint8_t** v, uint8_t** a, + int* width, int* height, int* stride, int* uv_stride, int* a_stride); + +// Deprecated alpha-less version of WebPIDecGetYUVA(): it will ignore the +// alpha information (if present). Kept for backward compatibility. +static WEBP_INLINE uint8_t* WebPIDecGetYUV( + const WebPIDecoder* idec, int* last_y, uint8_t** u, uint8_t** v, + int* width, int* height, int* stride, int* uv_stride) { + return WebPIDecGetYUVA(idec, last_y, u, v, NULL, width, height, + stride, uv_stride, NULL); +} + +// Generic call to retrieve information about the displayable area. +// If non NULL, the left/right/width/height pointers are filled with the visible +// rectangular area so far. +// Returns NULL in case the incremental decoder object is in an invalid state. +// Otherwise returns the pointer to the internal representation. This structure +// is read-only, tied to WebPIDecoder's lifespan and should not be modified. +WEBP_EXTERN(const WebPDecBuffer*) WebPIDecodedArea( + const WebPIDecoder* idec, int* left, int* top, int* width, int* height); + +//------------------------------------------------------------------------------ +// Advanced decoding parametrization +// +// Code sample for using the advanced decoding API +/* + // A) Init a configuration object + WebPDecoderConfig config; + CHECK(WebPInitDecoderConfig(&config)); + + // B) optional: retrieve the bitstream's features. + CHECK(WebPGetFeatures(data, data_size, &config.input) == VP8_STATUS_OK); + + // C) Adjust 'config', if needed + config.no_fancy_upsampling = 1; + config.output.colorspace = MODE_BGRA; + // etc. + + // Note that you can also make config.output point to an externally + // supplied memory buffer, provided it's big enough to store the decoded + // picture. Otherwise, config.output will just be used to allocate memory + // and store the decoded picture. + + // D) Decode! + CHECK(WebPDecode(data, data_size, &config) == VP8_STATUS_OK); + + // E) Decoded image is now in config.output (and config.output.u.RGBA) + + // F) Reclaim memory allocated in config's object. It's safe to call + // this function even if the memory is external and wasn't allocated + // by WebPDecode(). + WebPFreeDecBuffer(&config.output); +*/ + +// Features gathered from the bitstream +struct WebPBitstreamFeatures { + int width; // Width in pixels, as read from the bitstream. + int height; // Height in pixels, as read from the bitstream. + int has_alpha; // True if the bitstream contains an alpha channel. + int has_animation; // True if the bitstream is an animation. + + // Unused for now: + int bitstream_version; // should be 0 for now. TODO(later) + int no_incremental_decoding; // if true, using incremental decoding is not + // recommended. + int rotate; // TODO(later) + int uv_sampling; // should be 0 for now. TODO(later) + uint32_t pad[2]; // padding for later use +}; + +// Internal, version-checked, entry point +WEBP_EXTERN(VP8StatusCode) WebPGetFeaturesInternal( + const uint8_t*, size_t, WebPBitstreamFeatures*, int); + +// Retrieve features from the bitstream. The *features structure is filled +// with information gathered from the bitstream. +// Returns VP8_STATUS_OK when the features are successfully retrieved. Returns +// VP8_STATUS_NOT_ENOUGH_DATA when more data is needed to retrieve the +// features from headers. Returns error in other cases. +static WEBP_INLINE VP8StatusCode WebPGetFeatures( + const uint8_t* data, size_t data_size, + WebPBitstreamFeatures* features) { + return WebPGetFeaturesInternal(data, data_size, features, + WEBP_DECODER_ABI_VERSION); +} + +// Decoding options +struct WebPDecoderOptions { + int bypass_filtering; // if true, skip the in-loop filtering + int no_fancy_upsampling; // if true, use faster pointwise upsampler + int use_cropping; // if true, cropping is applied _first_ + int crop_left, crop_top; // top-left position for cropping. + // Will be snapped to even values. + int crop_width, crop_height; // dimension of the cropping area + int use_scaling; // if true, scaling is applied _afterward_ + int scaled_width, scaled_height; // final resolution + int use_threads; // if true, use multi-threaded decoding + + // Unused for now: + int force_rotation; // forced rotation (to be applied _last_) + int no_enhancement; // if true, discard enhancement layer + uint32_t pad[6]; // padding for later use +}; + +// Main object storing the configuration for advanced decoding. +struct WebPDecoderConfig { + WebPBitstreamFeatures input; // Immutable bitstream features (optional) + WebPDecBuffer output; // Output buffer (can point to external mem) + WebPDecoderOptions options; // Decoding options +}; + +// Internal, version-checked, entry point +WEBP_EXTERN(int) WebPInitDecoderConfigInternal(WebPDecoderConfig*, int); + +// Initialize the configuration as empty. This function must always be +// called first, unless WebPGetFeatures() is to be called. +// Returns false in case of mismatched version. +static WEBP_INLINE int WebPInitDecoderConfig(WebPDecoderConfig* config) { + return WebPInitDecoderConfigInternal(config, WEBP_DECODER_ABI_VERSION); +} + +// Instantiate a new incremental decoder object with the requested +// configuration. The bitstream can be passed using 'data' and 'data_size' +// parameter, in which case the features will be parsed and stored into +// config->input. Otherwise, 'data' can be NULL and no parsing will occur. +// Note that 'config' can be NULL too, in which case a default configuration +// is used. +// The return WebPIDecoder object must always be deleted calling WebPIDelete(). +// Returns NULL in case of error (and config->status will then reflect +// the error condition). +WEBP_EXTERN(WebPIDecoder*) WebPIDecode(const uint8_t* data, size_t data_size, + WebPDecoderConfig* config); + +// Non-incremental version. This version decodes the full data at once, taking +// 'config' into account. Returns decoding status (which should be VP8_STATUS_OK +// if the decoding was successful). +WEBP_EXTERN(VP8StatusCode) WebPDecode(const uint8_t* data, size_t data_size, + WebPDecoderConfig* config); + +#if defined(__cplusplus) || defined(c_plusplus) +} // extern "C" +#endif + +#endif /* WEBP_WEBP_DECODE_H_ */ diff --git a/cocos2dx/platform/third_party/emscripten/libwebp/webp/encode.h b/cocos2dx/platform/third_party/emscripten/libwebp/webp/encode.h new file mode 100644 index 0000000000..fea8ee428d --- /dev/null +++ b/cocos2dx/platform/third_party/emscripten/libwebp/webp/encode.h @@ -0,0 +1,480 @@ +// Copyright 2011 Google Inc. All Rights Reserved. +// +// This code is licensed under the same terms as WebM: +// Software License Agreement: http://www.webmproject.org/license/software/ +// Additional IP Rights Grant: http://www.webmproject.org/license/additional/ +// ----------------------------------------------------------------------------- +// +// WebP encoder: main interface +// +// Author: Skal (pascal.massimino@gmail.com) + +#ifndef WEBP_WEBP_ENCODE_H_ +#define WEBP_WEBP_ENCODE_H_ + +#include "./types.h" + +#if defined(__cplusplus) || defined(c_plusplus) +extern "C" { +#endif + +#define WEBP_ENCODER_ABI_VERSION 0x0201 // MAJOR(8b) + MINOR(8b) + +#if !(defined(__cplusplus) || defined(c_plusplus)) +typedef enum WebPImageHint WebPImageHint; +typedef enum WebPEncCSP WebPEncCSP; +typedef enum WebPPreset WebPPreset; +typedef enum WebPEncodingError WebPEncodingError; +#endif +typedef struct WebPConfig WebPConfig; +typedef struct WebPPicture WebPPicture; // main structure for I/O +typedef struct WebPAuxStats WebPAuxStats; +typedef struct WebPMemoryWriter WebPMemoryWriter; + +// Return the encoder's version number, packed in hexadecimal using 8bits for +// each of major/minor/revision. E.g: v2.5.7 is 0x020507. +WEBP_EXTERN(int) WebPGetEncoderVersion(void); + +//------------------------------------------------------------------------------ +// One-stop-shop call! No questions asked: + +// Returns the size of the compressed data (pointed to by *output), or 0 if +// an error occurred. The compressed data must be released by the caller +// using the call 'free(*output)'. +// These functions compress using the lossy format, and the quality_factor +// can go from 0 (smaller output, lower quality) to 100 (best quality, +// larger output). +WEBP_EXTERN(size_t) WebPEncodeRGB(const uint8_t* rgb, + int width, int height, int stride, + float quality_factor, uint8_t** output); +WEBP_EXTERN(size_t) WebPEncodeBGR(const uint8_t* bgr, + int width, int height, int stride, + float quality_factor, uint8_t** output); +WEBP_EXTERN(size_t) WebPEncodeRGBA(const uint8_t* rgba, + int width, int height, int stride, + float quality_factor, uint8_t** output); +WEBP_EXTERN(size_t) WebPEncodeBGRA(const uint8_t* bgra, + int width, int height, int stride, + float quality_factor, uint8_t** output); + +// These functions are the equivalent of the above, but compressing in a +// lossless manner. Files are usually larger than lossy format, but will +// not suffer any compression loss. +WEBP_EXTERN(size_t) WebPEncodeLosslessRGB(const uint8_t* rgb, + int width, int height, int stride, + uint8_t** output); +WEBP_EXTERN(size_t) WebPEncodeLosslessBGR(const uint8_t* bgr, + int width, int height, int stride, + uint8_t** output); +WEBP_EXTERN(size_t) WebPEncodeLosslessRGBA(const uint8_t* rgba, + int width, int height, int stride, + uint8_t** output); +WEBP_EXTERN(size_t) WebPEncodeLosslessBGRA(const uint8_t* bgra, + int width, int height, int stride, + uint8_t** output); + +//------------------------------------------------------------------------------ +// Coding parameters + +// Image characteristics hint for the underlying encoder. +enum WebPImageHint { + WEBP_HINT_DEFAULT = 0, // default preset. + WEBP_HINT_PICTURE, // digital picture, like portrait, inner shot + WEBP_HINT_PHOTO, // outdoor photograph, with natural lighting + WEBP_HINT_GRAPH, // Discrete tone image (graph, map-tile etc). + WEBP_HINT_LAST +}; + +// Compression parameters. +struct WebPConfig { + int lossless; // Lossless encoding (0=lossy(default), 1=lossless). + float quality; // between 0 (smallest file) and 100 (biggest) + int method; // quality/speed trade-off (0=fast, 6=slower-better) + + WebPImageHint image_hint; // Hint for image type (lossless only for now). + + // Parameters related to lossy compression only: + int target_size; // if non-zero, set the desired target size in bytes. + // Takes precedence over the 'compression' parameter. + float target_PSNR; // if non-zero, specifies the minimal distortion to + // try to achieve. Takes precedence over target_size. + int segments; // maximum number of segments to use, in [1..4] + int sns_strength; // Spatial Noise Shaping. 0=off, 100=maximum. + int filter_strength; // range: [0 = off .. 100 = strongest] + int filter_sharpness; // range: [0 = off .. 7 = least sharp] + int filter_type; // filtering type: 0 = simple, 1 = strong (only used + // if filter_strength > 0 or autofilter > 0) + int autofilter; // Auto adjust filter's strength [0 = off, 1 = on] + int alpha_compression; // Algorithm for encoding the alpha plane (0 = none, + // 1 = compressed with WebP lossless). Default is 1. + int alpha_filtering; // Predictive filtering method for alpha plane. + // 0: none, 1: fast, 2: best. Default if 1. + int alpha_quality; // Between 0 (smallest size) and 100 (lossless). + // Default is 100. + int pass; // number of entropy-analysis passes (in [1..10]). + + int show_compressed; // if true, export the compressed picture back. + // In-loop filtering is not applied. + int preprocessing; // preprocessing filter (0=none, 1=segment-smooth) + int partitions; // log2(number of token partitions) in [0..3]. Default + // is set to 0 for easier progressive decoding. + int partition_limit; // quality degradation allowed to fit the 512k limit + // on prediction modes coding (0: no degradation, + // 100: maximum possible degradation). + int emulate_jpeg_size; // If true, compression parameters will be remapped + // to better match the expected output size from + // JPEG compression. Generally, the output size will + // be similar but the degradation will be lower. + int thread_level; // If non-zero, try and use multi-threaded encoding. + int low_memory; // If set, reduce memory usage (but increase CPU use). + + uint32_t pad[5]; // padding for later use +}; + +// Enumerate some predefined settings for WebPConfig, depending on the type +// of source picture. These presets are used when calling WebPConfigPreset(). +enum WebPPreset { + WEBP_PRESET_DEFAULT = 0, // default preset. + WEBP_PRESET_PICTURE, // digital picture, like portrait, inner shot + WEBP_PRESET_PHOTO, // outdoor photograph, with natural lighting + WEBP_PRESET_DRAWING, // hand or line drawing, with high-contrast details + WEBP_PRESET_ICON, // small-sized colorful images + WEBP_PRESET_TEXT // text-like +}; + +// Internal, version-checked, entry point +WEBP_EXTERN(int) WebPConfigInitInternal(WebPConfig*, WebPPreset, float, int); + +// Should always be called, to initialize a fresh WebPConfig structure before +// modification. Returns false in case of version mismatch. WebPConfigInit() +// must have succeeded before using the 'config' object. +// Note that the default values are lossless=0 and quality=75. +static WEBP_INLINE int WebPConfigInit(WebPConfig* config) { + return WebPConfigInitInternal(config, WEBP_PRESET_DEFAULT, 75.f, + WEBP_ENCODER_ABI_VERSION); +} + +// This function will initialize the configuration according to a predefined +// set of parameters (referred to by 'preset') and a given quality factor. +// This function can be called as a replacement to WebPConfigInit(). Will +// return false in case of error. +static WEBP_INLINE int WebPConfigPreset(WebPConfig* config, + WebPPreset preset, float quality) { + return WebPConfigInitInternal(config, preset, quality, + WEBP_ENCODER_ABI_VERSION); +} + +// Returns true if 'config' is non-NULL and all configuration parameters are +// within their valid ranges. +WEBP_EXTERN(int) WebPValidateConfig(const WebPConfig* config); + +//------------------------------------------------------------------------------ +// Input / Output +// Structure for storing auxiliary statistics (mostly for lossy encoding). + +struct WebPAuxStats { + int coded_size; // final size + + float PSNR[5]; // peak-signal-to-noise ratio for Y/U/V/All/Alpha + int block_count[3]; // number of intra4/intra16/skipped macroblocks + int header_bytes[2]; // approximate number of bytes spent for header + // and mode-partition #0 + int residual_bytes[3][4]; // approximate number of bytes spent for + // DC/AC/uv coefficients for each (0..3) segments. + int segment_size[4]; // number of macroblocks in each segments + int segment_quant[4]; // quantizer values for each segments + int segment_level[4]; // filtering strength for each segments [0..63] + + int alpha_data_size; // size of the transparency data + int layer_data_size; // size of the enhancement layer data + + // lossless encoder statistics + uint32_t lossless_features; // bit0:predictor bit1:cross-color transform + // bit2:subtract-green bit3:color indexing + int histogram_bits; // number of precision bits of histogram + int transform_bits; // precision bits for transform + int cache_bits; // number of bits for color cache lookup + int palette_size; // number of color in palette, if used + int lossless_size; // final lossless size + + uint32_t pad[4]; // padding for later use +}; + +// Signature for output function. Should return true if writing was successful. +// data/data_size is the segment of data to write, and 'picture' is for +// reference (and so one can make use of picture->custom_ptr). +typedef int (*WebPWriterFunction)(const uint8_t* data, size_t data_size, + const WebPPicture* picture); + +// WebPMemoryWrite: a special WebPWriterFunction that writes to memory using +// the following WebPMemoryWriter object (to be set as a custom_ptr). +struct WebPMemoryWriter { + uint8_t* mem; // final buffer (of size 'max_size', larger than 'size'). + size_t size; // final size + size_t max_size; // total capacity + uint32_t pad[1]; // padding for later use +}; + +// The following must be called first before any use. +WEBP_EXTERN(void) WebPMemoryWriterInit(WebPMemoryWriter* writer); + +// The custom writer to be used with WebPMemoryWriter as custom_ptr. Upon +// completion, writer.mem and writer.size will hold the coded data. +// writer.mem must be freed using the call 'free(writer.mem)'. +WEBP_EXTERN(int) WebPMemoryWrite(const uint8_t* data, size_t data_size, + const WebPPicture* picture); + +// Progress hook, called from time to time to report progress. It can return +// false to request an abort of the encoding process, or true otherwise if +// everything is OK. +typedef int (*WebPProgressHook)(int percent, const WebPPicture* picture); + +// Color spaces. +enum WebPEncCSP { + // chroma sampling + WEBP_YUV420 = 0, // 4:2:0 + WEBP_YUV422 = 1, // 4:2:2 + WEBP_YUV444 = 2, // 4:4:4 + WEBP_YUV400 = 3, // grayscale + WEBP_CSP_UV_MASK = 3, // bit-mask to get the UV sampling factors + // alpha channel variants + WEBP_YUV420A = 4, + WEBP_YUV422A = 5, + WEBP_YUV444A = 6, + WEBP_YUV400A = 7, // grayscale + alpha + WEBP_CSP_ALPHA_BIT = 4 // bit that is set if alpha is present +}; + +// Encoding error conditions. +enum WebPEncodingError { + VP8_ENC_OK = 0, + VP8_ENC_ERROR_OUT_OF_MEMORY, // memory error allocating objects + VP8_ENC_ERROR_BITSTREAM_OUT_OF_MEMORY, // memory error while flushing bits + VP8_ENC_ERROR_NULL_PARAMETER, // a pointer parameter is NULL + VP8_ENC_ERROR_INVALID_CONFIGURATION, // configuration is invalid + VP8_ENC_ERROR_BAD_DIMENSION, // picture has invalid width/height + VP8_ENC_ERROR_PARTITION0_OVERFLOW, // partition is bigger than 512k + VP8_ENC_ERROR_PARTITION_OVERFLOW, // partition is bigger than 16M + VP8_ENC_ERROR_BAD_WRITE, // error while flushing bytes + VP8_ENC_ERROR_FILE_TOO_BIG, // file is bigger than 4G + VP8_ENC_ERROR_USER_ABORT, // abort request by user + VP8_ENC_ERROR_LAST // list terminator. always last. +}; + +// maximum width/height allowed (inclusive), in pixels +#define WEBP_MAX_DIMENSION 16383 + +// Main exchange structure (input samples, output bytes, statistics) +struct WebPPicture { + // INPUT + ////////////// + // Main flag for encoder selecting between ARGB or YUV input. + // It is recommended to use ARGB input (*argb, argb_stride) for lossless + // compression, and YUV input (*y, *u, *v, etc.) for lossy compression + // since these are the respective native colorspace for these formats. + int use_argb; + + // YUV input (mostly used for input to lossy compression) + WebPEncCSP colorspace; // colorspace: should be YUV420 for now (=Y'CbCr). + int width, height; // dimensions (less or equal to WEBP_MAX_DIMENSION) + uint8_t *y, *u, *v; // pointers to luma/chroma planes. + int y_stride, uv_stride; // luma/chroma strides. + uint8_t* a; // pointer to the alpha plane + int a_stride; // stride of the alpha plane + uint32_t pad1[2]; // padding for later use + + // ARGB input (mostly used for input to lossless compression) + uint32_t* argb; // Pointer to argb (32 bit) plane. + int argb_stride; // This is stride in pixels units, not bytes. + uint32_t pad2[3]; // padding for later use + + // OUTPUT + /////////////// + // Byte-emission hook, to store compressed bytes as they are ready. + WebPWriterFunction writer; // can be NULL + void* custom_ptr; // can be used by the writer. + + // map for extra information (only for lossy compression mode) + int extra_info_type; // 1: intra type, 2: segment, 3: quant + // 4: intra-16 prediction mode, + // 5: chroma prediction mode, + // 6: bit cost, 7: distortion + uint8_t* extra_info; // if not NULL, points to an array of size + // ((width + 15) / 16) * ((height + 15) / 16) that + // will be filled with a macroblock map, depending + // on extra_info_type. + + // STATS AND REPORTS + /////////////////////////// + // Pointer to side statistics (updated only if not NULL) + WebPAuxStats* stats; + + // Error code for the latest error encountered during encoding + WebPEncodingError error_code; + + // If not NULL, report progress during encoding. + WebPProgressHook progress_hook; + + void* user_data; // this field is free to be set to any value and + // used during callbacks (like progress-report e.g.). + + uint32_t pad3[3]; // padding for later use + + // Unused for now: original samples (for non-YUV420 modes) + uint8_t *u0, *v0; + int uv0_stride; + + uint32_t pad4[7]; // padding for later use + + // PRIVATE FIELDS + //////////////////// + void* memory_; // row chunk of memory for yuva planes + void* memory_argb_; // and for argb too. + void* pad5[2]; // padding for later use +}; + +// Internal, version-checked, entry point +WEBP_EXTERN(int) WebPPictureInitInternal(WebPPicture*, int); + +// Should always be called, to initialize the structure. Returns false in case +// of version mismatch. WebPPictureInit() must have succeeded before using the +// 'picture' object. +// Note that, by default, use_argb is false and colorspace is WEBP_YUV420. +static WEBP_INLINE int WebPPictureInit(WebPPicture* picture) { + return WebPPictureInitInternal(picture, WEBP_ENCODER_ABI_VERSION); +} + +//------------------------------------------------------------------------------ +// WebPPicture utils + +// Convenience allocation / deallocation based on picture->width/height: +// Allocate y/u/v buffers as per colorspace/width/height specification. +// Note! This function will free the previous buffer if needed. +// Returns false in case of memory error. +WEBP_EXTERN(int) WebPPictureAlloc(WebPPicture* picture); + +// Release the memory allocated by WebPPictureAlloc() or WebPPictureImport*(). +// Note that this function does _not_ free the memory used by the 'picture' +// object itself. +// Besides memory (which is reclaimed) all other fields of 'picture' are +// preserved. +WEBP_EXTERN(void) WebPPictureFree(WebPPicture* picture); + +// Copy the pixels of *src into *dst, using WebPPictureAlloc. Upon return, +// *dst will fully own the copied pixels (this is not a view). +// Returns false in case of memory allocation error. +WEBP_EXTERN(int) WebPPictureCopy(const WebPPicture* src, WebPPicture* dst); + +// Compute PSNR, SSIM or LSIM distortion metric between two pictures. +// Result is in dB, stores in result[] in the Y/U/V/Alpha/All order. +// Returns false in case of error (src and ref don't have same dimension, ...) +// Warning: this function is rather CPU-intensive. +WEBP_EXTERN(int) WebPPictureDistortion( + const WebPPicture* src, const WebPPicture* ref, + int metric_type, // 0 = PSNR, 1 = SSIM, 2 = LSIM + float result[5]); + +// self-crops a picture to the rectangle defined by top/left/width/height. +// Returns false in case of memory allocation error, or if the rectangle is +// outside of the source picture. +// The rectangle for the view is defined by the top-left corner pixel +// coordinates (left, top) as well as its width and height. This rectangle +// must be fully be comprised inside the 'src' source picture. If the source +// picture uses the YUV420 colorspace, the top and left coordinates will be +// snapped to even values. +WEBP_EXTERN(int) WebPPictureCrop(WebPPicture* picture, + int left, int top, int width, int height); + +// Extracts a view from 'src' picture into 'dst'. The rectangle for the view +// is defined by the top-left corner pixel coordinates (left, top) as well +// as its width and height. This rectangle must be fully be comprised inside +// the 'src' source picture. If the source picture uses the YUV420 colorspace, +// the top and left coordinates will be snapped to even values. +// Picture 'src' must out-live 'dst' picture. Self-extraction of view is allowed +// ('src' equal to 'dst') as a mean of fast-cropping (but note that doing so, +// the original dimension will be lost). +// Returns false in case of memory allocation error or invalid parameters. +WEBP_EXTERN(int) WebPPictureView(const WebPPicture* src, + int left, int top, int width, int height, + WebPPicture* dst); + +// Returns true if the 'picture' is actually a view and therefore does +// not own the memory for pixels. +WEBP_EXTERN(int) WebPPictureIsView(const WebPPicture* picture); + +// Rescale a picture to new dimension width x height. +// Now gamma correction is applied. +// Returns false in case of error (invalid parameter or insufficient memory). +WEBP_EXTERN(int) WebPPictureRescale(WebPPicture* pic, int width, int height); + +// Colorspace conversion function to import RGB samples. +// Previous buffer will be free'd, if any. +// *rgb buffer should have a size of at least height * rgb_stride. +// Returns false in case of memory error. +WEBP_EXTERN(int) WebPPictureImportRGB( + WebPPicture* picture, const uint8_t* rgb, int rgb_stride); +// Same, but for RGBA buffer. +WEBP_EXTERN(int) WebPPictureImportRGBA( + WebPPicture* picture, const uint8_t* rgba, int rgba_stride); +// Same, but for RGBA buffer. Imports the RGB direct from the 32-bit format +// input buffer ignoring the alpha channel. Avoids needing to copy the data +// to a temporary 24-bit RGB buffer to import the RGB only. +WEBP_EXTERN(int) WebPPictureImportRGBX( + WebPPicture* picture, const uint8_t* rgbx, int rgbx_stride); + +// Variants of the above, but taking BGR(A|X) input. +WEBP_EXTERN(int) WebPPictureImportBGR( + WebPPicture* picture, const uint8_t* bgr, int bgr_stride); +WEBP_EXTERN(int) WebPPictureImportBGRA( + WebPPicture* picture, const uint8_t* bgra, int bgra_stride); +WEBP_EXTERN(int) WebPPictureImportBGRX( + WebPPicture* picture, const uint8_t* bgrx, int bgrx_stride); + +// Converts picture->argb data to the YUVA format specified by 'colorspace'. +// Upon return, picture->use_argb is set to false. The presence of real +// non-opaque transparent values is detected, and 'colorspace' will be +// adjusted accordingly. Note that this method is lossy. +// Returns false in case of error. +WEBP_EXTERN(int) WebPPictureARGBToYUVA(WebPPicture* picture, + WebPEncCSP colorspace); + +// Converts picture->yuv to picture->argb and sets picture->use_argb to true. +// The input format must be YUV_420 or YUV_420A. +// Note that the use of this method is discouraged if one has access to the +// raw ARGB samples, since using YUV420 is comparatively lossy. Also, the +// conversion from YUV420 to ARGB incurs a small loss too. +// Returns false in case of error. +WEBP_EXTERN(int) WebPPictureYUVAToARGB(WebPPicture* picture); + +// Helper function: given a width x height plane of YUV(A) samples +// (with stride 'stride'), clean-up the YUV samples under fully transparent +// area, to help compressibility (no guarantee, though). +WEBP_EXTERN(void) WebPCleanupTransparentArea(WebPPicture* picture); + +// Scan the picture 'picture' for the presence of non fully opaque alpha values. +// Returns true in such case. Otherwise returns false (indicating that the +// alpha plane can be ignored altogether e.g.). +WEBP_EXTERN(int) WebPPictureHasTransparency(const WebPPicture* picture); + +//------------------------------------------------------------------------------ +// Main call + +// Main encoding call, after config and picture have been initialized. +// 'picture' must be less than 16384x16384 in dimension (cf WEBP_MAX_DIMENSION), +// and the 'config' object must be a valid one. +// Returns false in case of error, true otherwise. +// In case of error, picture->error_code is updated accordingly. +// 'picture' can hold the source samples in both YUV(A) or ARGB input, depending +// on the value of 'picture->use_argb'. It is highly recommended to use +// the former for lossy encoding, and the latter for lossless encoding +// (when config.lossless is true). Automatic conversion from one format to +// another is provided but they both incur some loss. +WEBP_EXTERN(int) WebPEncode(const WebPConfig* config, WebPPicture* picture); + +//------------------------------------------------------------------------------ + +#if defined(__cplusplus) || defined(c_plusplus) +} // extern "C" +#endif + +#endif /* WEBP_WEBP_ENCODE_H_ */ diff --git a/cocos2dx/platform/third_party/emscripten/libwebp/webp/types.h b/cocos2dx/platform/third_party/emscripten/libwebp/webp/types.h new file mode 100644 index 0000000000..3e27190bef --- /dev/null +++ b/cocos2dx/platform/third_party/emscripten/libwebp/webp/types.h @@ -0,0 +1,45 @@ +// Copyright 2010 Google Inc. All Rights Reserved. +// +// This code is licensed under the same terms as WebM: +// Software License Agreement: http://www.webmproject.org/license/software/ +// Additional IP Rights Grant: http://www.webmproject.org/license/additional/ +// ----------------------------------------------------------------------------- +// +// Common types +// +// Author: Skal (pascal.massimino@gmail.com) + +#ifndef WEBP_WEBP_TYPES_H_ +#define WEBP_WEBP_TYPES_H_ + +#include // for size_t + +#ifndef _MSC_VER +#include +#ifdef __STRICT_ANSI__ +#define WEBP_INLINE +#else /* __STRICT_ANSI__ */ +#define WEBP_INLINE inline +#endif +#else +typedef signed char int8_t; +typedef unsigned char uint8_t; +typedef signed short int16_t; +typedef unsigned short uint16_t; +typedef signed int int32_t; +typedef unsigned int uint32_t; +typedef unsigned long long int uint64_t; +typedef long long int int64_t; +#define WEBP_INLINE __forceinline +#endif /* _MSC_VER */ + +#ifndef WEBP_EXTERN +// This explicitly marks library functions and allows for changing the +// signature for e.g., Windows DLL builds. +#define WEBP_EXTERN(type) extern type +#endif /* WEBP_EXTERN */ + +// Macro to check ABI compatibility (same major revision number) +#define WEBP_ABI_IS_INCOMPATIBLE(a, b) (((a) >> 8) != ((b) >> 8)) + +#endif /* WEBP_WEBP_TYPES_H_ */ diff --git a/cocos2dx/platform/win32/CCEGLView.cpp b/cocos2dx/platform/win32/CCEGLView.cpp index ddc79748fa..4136694e6d 100644 --- a/cocos2dx/platform/win32/CCEGLView.cpp +++ b/cocos2dx/platform/win32/CCEGLView.cpp @@ -693,9 +693,9 @@ void CCEGLView::centerWindow() } GetWindowRect(m_hWnd, &rcWindow); - int offsetX = (rcDesktop.right - rcDesktop.left - (rcWindow.right - rcWindow.left)) / 2; + int offsetX = rcDesktop.left + (rcDesktop.right - rcDesktop.left - (rcWindow.right - rcWindow.left)) / 2; offsetX = (offsetX > 0) ? offsetX : rcDesktop.left; - int offsetY = (rcDesktop.bottom - rcDesktop.top - (rcWindow.bottom - rcWindow.top)) / 2; + int offsetY = rcDesktop.top + (rcDesktop.bottom - rcDesktop.top - (rcWindow.bottom - rcWindow.top)) / 2; offsetY = (offsetY > 0) ? offsetY : rcDesktop.top; SetWindowPos(m_hWnd, 0, offsetX, offsetY, 0, 0, SWP_NOCOPYBITS | SWP_NOSIZE | SWP_NOOWNERZORDER | SWP_NOZORDER); diff --git a/cocos2dx/proj.emscripten/Makefile b/cocos2dx/proj.emscripten/Makefile index 06d991fb49..01a305b584 100644 --- a/cocos2dx/proj.emscripten/Makefile +++ b/cocos2dx/proj.emscripten/Makefile @@ -38,6 +38,7 @@ SOURCES = ../actions/CCAction.cpp \ ../cocoa/CCArray.cpp \ ../cocoa/CCDictionary.cpp \ ../cocoa/CCString.cpp \ +../cocoa/CCDataVisitor.cpp \ ../draw_nodes/CCDrawingPrimitives.cpp \ ../draw_nodes/CCDrawNode.cpp \ ../effects/CCGrabber.cpp \ diff --git a/cocos2dx/proj.emscripten/cocos2dx.mk b/cocos2dx/proj.emscripten/cocos2dx.mk index b40e465844..8b4d6bc372 100644 --- a/cocos2dx/proj.emscripten/cocos2dx.mk +++ b/cocos2dx/proj.emscripten/cocos2dx.mk @@ -35,8 +35,8 @@ INCLUDES += \ -I$(COCOS_SRC)/platform/third_party/emscripten/libz \ -I$(COCOS_SRC)/platform/third_party/emscripten/libfreetype2 \ -I$(COCOS_SRC)/platform/third_party/emscripten/libtiff/include \ - -I$(COCOS_SRC)/platform/third_party/linux/libjpeg \ - -I$(COCOS_SRC)/platform/third_party/linux/libwebp + -I$(COCOS_SRC)/platform/third_party/emscripten/libjpeg \ + -I$(COCOS_SRC)/platform/third_party/emscripten/libwebp LBITS := $(shell getconf LONG_BIT) INCLUDES += -I$(COCOS_SRC)/platform/third_party/linux @@ -49,8 +49,8 @@ OBJ_DIR := $(OBJ_DIR)/debug LIB_DIR := $(LIB_DIR)/debug BIN_DIR := $(BIN_DIR)/debug else -CCFLAGS += -O2 --jcache -s GL_UNSAFE_OPTS=0 -CXXFLAGS += -O2 --jcache -s GL_UNSAFE_OPTS=0 +CCFLAGS += -O2 --jcache -s GL_UNSAFE_OPTS=0 -s ASM_JS=1 +CXXFLAGS += -O2 --jcache -s GL_UNSAFE_OPTS=0 -s ASM_JS=1 DEFINES += -DNDEBUG -DCP_USE_DOUBLES=0 OBJ_DIR := $(OBJ_DIR)/release LIB_DIR := $(LIB_DIR)/release @@ -77,7 +77,7 @@ STATICLIBS_DIR = $(COCOS_SRC)/platform/third_party/emscripten/libraries STATICLIBS = $(STATICLIBS_DIR)/libfreetype.a \ $(STATICLIBS_DIR)/libpng.a \ $(STATICLIBS_DIR)/zlib.a \ - $(STATICLIBS_DIR)/libtiff.a #\ + $(STATICLIBS_DIR)/libtiff.a \ $(STATICLIBS_DIR)/libjpeg.a \ $(STATICLIBS_DIR)/libwebp.a diff --git a/cocos2dx/proj.ios/cocos2dx.xcodeproj/project.pbxproj.REMOVED.git-id b/cocos2dx/proj.ios/cocos2dx.xcodeproj/project.pbxproj.REMOVED.git-id index 0e78a50863..c5f3e0dc2b 100644 --- a/cocos2dx/proj.ios/cocos2dx.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/cocos2dx/proj.ios/cocos2dx.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -ab1a108831dfdc88ca340350536987da48bccfdc \ No newline at end of file +89741f647de6b40616d5c45625fcd3c2d8e9d20a \ No newline at end of file diff --git a/cocos2dx/proj.linux/Makefile b/cocos2dx/proj.linux/Makefile index 3549cf946e..4ce130fb93 100644 --- a/cocos2dx/proj.linux/Makefile +++ b/cocos2dx/proj.linux/Makefile @@ -34,6 +34,7 @@ SOURCES = ../actions/CCAction.cpp \ ../cocoa/CCArray.cpp \ ../cocoa/CCDictionary.cpp \ ../cocoa/CCString.cpp \ +../cocoa/CCDataVisitor.cpp \ ../draw_nodes/CCDrawingPrimitives.cpp \ ../draw_nodes/CCDrawNode.cpp \ ../effects/CCGrabber.cpp \ diff --git a/cocos2dx/proj.mac/cocos2dx.xcodeproj/project.pbxproj.REMOVED.git-id b/cocos2dx/proj.mac/cocos2dx.xcodeproj/project.pbxproj.REMOVED.git-id index cdb0cac2cf..b4c415dff2 100644 --- a/cocos2dx/proj.mac/cocos2dx.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/cocos2dx/proj.mac/cocos2dx.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -593eeddbb616c30af1167e9add361f1cd8e7996e \ No newline at end of file +703f1f571cf577296708f26a90de6288773b8db5 \ No newline at end of file diff --git a/cocos2dx/proj.nacl/Makefile b/cocos2dx/proj.nacl/Makefile index cb75af8dc4..6c9871ff72 100644 --- a/cocos2dx/proj.nacl/Makefile +++ b/cocos2dx/proj.nacl/Makefile @@ -34,6 +34,7 @@ SOURCES = ../actions/CCAction.cpp \ ../cocoa/CCArray.cpp \ ../cocoa/CCDictionary.cpp \ ../cocoa/CCString.cpp \ +../cocoa/CCDataVisitor.cpp \ ../draw_nodes/CCDrawingPrimitives.cpp \ ../draw_nodes/CCDrawNode.cpp \ ../effects/CCGrabber.cpp \ diff --git a/cocos2dx/proj.win32/cocos2d.vcxproj b/cocos2dx/proj.win32/cocos2d.vcxproj index 2dcf7b5514..79f6a7b904 100644 --- a/cocos2dx/proj.win32/cocos2d.vcxproj +++ b/cocos2dx/proj.win32/cocos2d.vcxproj @@ -144,6 +144,7 @@ xcopy /Y /Q "$(ProjectDir)..\platform\third_party\win32\libraries\*.*" "$(OutDir + @@ -268,7 +269,11 @@ xcopy /Y /Q "$(ProjectDir)..\platform\third_party\win32\libraries\*.*" "$(OutDir + + + + diff --git a/cocos2dx/proj.win32/cocos2d.vcxproj.filters b/cocos2dx/proj.win32/cocos2d.vcxproj.filters index 1b1dacc681..20c672dc8c 100644 --- a/cocos2dx/proj.win32/cocos2d.vcxproj.filters +++ b/cocos2dx/proj.win32/cocos2d.vcxproj.filters @@ -458,6 +458,9 @@ support\tinyxml2 + + cocoa + @@ -914,5 +917,17 @@ support\tinyxml2 + + cocoa + + + cocoa + + + cocoa + + + cocoa + \ No newline at end of file diff --git a/cocos2dx/support/data_support/ccCArray.cpp b/cocos2dx/support/data_support/ccCArray.cpp index c0fe8ebd17..580bfa96d3 100644 --- a/cocos2dx/support/data_support/ccCArray.cpp +++ b/cocos2dx/support/data_support/ccCArray.cpp @@ -101,12 +101,12 @@ void ccArrayShrink(ccArray *arr) unsigned int ccArrayGetIndexOfObject(ccArray *arr, CCObject* object) { const unsigned int arrNum = arr->num; - const CCObject* ptr = arr->arr[0]; + CCObject** ptr = arr->arr; for(unsigned int i = 0; i < arrNum; ++i, ++ptr) { - if( ptr == object ) return i; + if( *ptr == object ) return i; } - + return CC_INVALID_INDEX; } diff --git a/cocos2dx/support/zip_support/ZipUtils.cpp b/cocos2dx/support/zip_support/ZipUtils.cpp index 425fa520cb..e177c8ef7f 100644 --- a/cocos2dx/support/zip_support/ZipUtils.cpp +++ b/cocos2dx/support/zip_support/ZipUtils.cpp @@ -1,26 +1,26 @@ /**************************************************************************** -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. -****************************************************************************/ + 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 #include #include @@ -33,8 +33,96 @@ THE SOFTWARE. NS_CC_BEGIN +unsigned int ZipUtils::s_uEncryptedPvrKeyParts[4] = {0,0,0,0}; +unsigned int ZipUtils::s_uEncryptionKey[1024]; +bool ZipUtils::s_bEncryptionKeyIsValid = false; + // --------------------- ZipUtils --------------------- +inline void ZipUtils::ccDecodeEncodedPvr(unsigned int *data, int len) +{ + const int enclen = 1024; + const int securelen = 512; + const int distance = 64; + + // check if key was set + // make sure to call caw_setkey_part() for all 4 key parts + CCAssert(s_uEncryptedPvrKeyParts[0] != 0, "Cocos2D: CCZ file is encrypted but key part 0 is not set. Did you call ZipUtils::ccSetPvrEncryptionKeyPart(...)?"); + CCAssert(s_uEncryptedPvrKeyParts[1] != 0, "Cocos2D: CCZ file is encrypted but key part 1 is not set. Did you call ZipUtils::ccSetPvrEncryptionKeyPart(...)?"); + CCAssert(s_uEncryptedPvrKeyParts[2] != 0, "Cocos2D: CCZ file is encrypted but key part 2 is not set. Did you call ZipUtils::ccSetPvrEncryptionKeyPart(...)?"); + CCAssert(s_uEncryptedPvrKeyParts[3] != 0, "Cocos2D: CCZ file is encrypted but key part 3 is not set. Did you call ZipUtils::ccSetPvrEncryptionKeyPart(...)?"); + + // create long key + if(!s_bEncryptionKeyIsValid) + { + unsigned int y, p, e; + unsigned int rounds = 6; + unsigned int sum = 0; + unsigned int z = s_uEncryptionKey[enclen-1]; + + do + { +#define DELTA 0x9e3779b9 +#define MX (((z>>5^y<<2) + (y>>3^z<<4)) ^ ((sum^y) + (s_uEncryptedPvrKeyParts[(p&3)^e] ^ z))) + + sum += DELTA; + e = (sum >> 2) & 3; + + for (p = 0; p < enclen - 1; p++) + { + y = s_uEncryptionKey[p + 1]; + z = s_uEncryptionKey[p] += MX; + } + + y = s_uEncryptionKey[0]; + z = s_uEncryptionKey[enclen - 1] += MX; + + } while (--rounds); + + s_bEncryptionKeyIsValid = true; + } + + int b = 0; + int i = 0; + + // encrypt first part completely + for(; i < len && i < securelen; i++) + { + data[i] ^= s_uEncryptionKey[b++]; + + if(b >= enclen) + { + b = 0; + } + } + + // encrypt second section partially + for(; i < len; i += distance) + { + data[i] ^= s_uEncryptionKey[b++]; + + if(b >= enclen) + { + b = 0; + } + } +} + +inline unsigned int ZipUtils::ccChecksumPvr(const unsigned int *data, int len) +{ + unsigned int cs = 0; + const int cslen = 128; + + len = (len < cslen) ? len : cslen; + + for(int i = 0; i < len; i++) + { + cs = cs ^ data[i]; + } + + return cs; +} + // memory in iPhone is precious // Should buffer factor be 1.5 instead of 2 ? #define BUFFER_INC_FACTOR (2) @@ -43,63 +131,63 @@ int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, { /* ret value */ int err = Z_OK; - + int bufferSize = outLenghtHint; *out = new unsigned char[bufferSize]; - - z_stream d_stream; /* decompression stream */ + + z_stream d_stream; /* decompression stream */ d_stream.zalloc = (alloc_func)0; d_stream.zfree = (free_func)0; d_stream.opaque = (voidpf)0; - + d_stream.next_in = in; d_stream.avail_in = inLength; d_stream.next_out = *out; d_stream.avail_out = bufferSize; - + /* window size to hold 256k */ if( (err = inflateInit2(&d_stream, 15 + 32)) != Z_OK ) return err; - - for (;;) + + for (;;) { err = inflate(&d_stream, Z_NO_FLUSH); - + if (err == Z_STREAM_END) { break; } - - switch (err) + + switch (err) { - case Z_NEED_DICT: - err = Z_DATA_ERROR; - case Z_DATA_ERROR: - case Z_MEM_ERROR: - inflateEnd(&d_stream); - return err; + case Z_NEED_DICT: + err = Z_DATA_ERROR; + case Z_DATA_ERROR: + case Z_MEM_ERROR: + inflateEnd(&d_stream); + return err; } - + // not enough memory ? - if (err != Z_STREAM_END) + if (err != Z_STREAM_END) { delete [] *out; *out = new unsigned char[bufferSize * BUFFER_INC_FACTOR]; - + /* not enough memory, ouch */ - if (! *out ) + if (! *out ) { CCLOG("cocos2d: ZipUtils: realloc failed"); inflateEnd(&d_stream); return Z_MEM_ERROR; } - + d_stream.next_out = *out + bufferSize; d_stream.avail_out = bufferSize; bufferSize *= BUFFER_INC_FACTOR; } } - + *outLength = bufferSize - d_stream.avail_out; err = inflateEnd(&d_stream); return err; @@ -109,30 +197,30 @@ int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, { unsigned int outLength = 0; int err = ccInflateMemoryWithHint(in, inLength, out, &outLength, outLengthHint); - + if (err != Z_OK || *out == NULL) { if (err == Z_MEM_ERROR) { CCLOG("cocos2d: ZipUtils: Out of memory while decompressing map data!"); - } else - if (err == Z_VERSION_ERROR) - { - CCLOG("cocos2d: ZipUtils: Incompatible zlib version!"); - } else - if (err == Z_DATA_ERROR) - { - CCLOG("cocos2d: ZipUtils: Incorrect zlib compressed data!"); - } - else - { - CCLOG("cocos2d: ZipUtils: Unknown error while decompressing map data!"); - } - + } else + if (err == Z_VERSION_ERROR) + { + CCLOG("cocos2d: ZipUtils: Incompatible zlib version!"); + } else + if (err == Z_DATA_ERROR) + { + CCLOG("cocos2d: ZipUtils: Incorrect zlib compressed data!"); + } + else + { + CCLOG("cocos2d: ZipUtils: Unknown error while decompressing map data!"); + } + delete[] *out; *out = NULL; outLength = 0; } - + return outLength; } @@ -146,30 +234,30 @@ int ZipUtils::ccInflateGZipFile(const char *path, unsigned char **out) { int len; unsigned int offset = 0; - + CCAssert(out, ""); CCAssert(&*out, ""); - + gzFile inFile = gzopen(path, "rb"); if( inFile == NULL ) { CCLOG("cocos2d: ZipUtils: error open gzip file: %s", path); return -1; } - + /* 512k initial decompress buffer */ unsigned int bufferSize = 512 * 1024; unsigned int totalBufferSize = bufferSize; - + *out = (unsigned char*)malloc( bufferSize ); - if( ! out ) + if( ! out ) { CCLOG("cocos2d: ZipUtils: out of memory"); return -1; } - + for (;;) { len = gzread(inFile, *out + offset, bufferSize); - if (len < 0) + if (len < 0) { CCLOG("cocos2d: ZipUtils: error in gzread"); free( *out ); @@ -180,108 +268,170 @@ int ZipUtils::ccInflateGZipFile(const char *path, unsigned char **out) { break; } - + offset += len; - + // finish reading the file if( (unsigned int)len < bufferSize ) { break; } - + bufferSize *= BUFFER_INC_FACTOR; totalBufferSize += bufferSize; unsigned char *tmp = (unsigned char*)realloc(*out, totalBufferSize ); - - if( ! tmp ) + + if( ! tmp ) { CCLOG("cocos2d: ZipUtils: out of memory"); free( *out ); *out = NULL; return -1; } - + *out = tmp; } - + if (gzclose(inFile) != Z_OK) { CCLOG("cocos2d: ZipUtils: gzclose failed"); } - + return offset; } int ZipUtils::ccInflateCCZFile(const char *path, unsigned char **out) { - CCAssert(out, ""); - CCAssert(&*out, ""); - - // load file into memory - unsigned char* compressed = NULL; + CCAssert(out, ""); + CCAssert(&*out, ""); - unsigned long fileLen = 0; - compressed = CCFileUtils::sharedFileUtils()->getFileData(path, "rb", &fileLen); + // load file into memory + unsigned char* compressed = NULL; + + unsigned long fileLen = 0; + compressed = CCFileUtils::sharedFileUtils()->getFileData(path, "rb", &fileLen); + + if(NULL == compressed || 0 == fileLen) + { + CCLOG("cocos2d: Error loading CCZ compressed file"); + return -1; + } + + struct CCZHeader *header = (struct CCZHeader*) compressed; + + // verify header + if( header->sig[0] == 'C' && header->sig[1] == 'C' && header->sig[2] == 'Z' && header->sig[3] == '!' ) + { + // verify header version + unsigned int version = CC_SWAP_INT16_BIG_TO_HOST( header->version ); + if( version > 2 ) + { + CCLOG("cocos2d: Unsupported CCZ header format"); + delete [] compressed; + return -1; + } + + // verify compression format + if( CC_SWAP_INT16_BIG_TO_HOST(header->compression_type) != CCZ_COMPRESSION_ZLIB ) + { + CCLOG("cocos2d: CCZ Unsupported compression method"); + delete [] compressed; + return -1; + } + } + else if( header->sig[0] == 'C' && header->sig[1] == 'C' && header->sig[2] == 'Z' && header->sig[3] == 'p' ) + { + // encrypted ccz file + header = (struct CCZHeader*) compressed; + + // verify header version + unsigned int version = CC_SWAP_INT16_BIG_TO_HOST( header->version ); + if( version > 0 ) + { + CCLOG("cocos2d: Unsupported CCZ header format"); + delete [] compressed; + return -1; + } + + // verify compression format + if( CC_SWAP_INT16_BIG_TO_HOST(header->compression_type) != CCZ_COMPRESSION_ZLIB ) + { + CCLOG("cocos2d: CCZ Unsupported compression method"); + delete [] compressed; + return -1; + } + + // decrypt + unsigned int* ints = (unsigned int*)(compressed+12); + int enclen = (fileLen-12)/4; + + ccDecodeEncodedPvr(ints, enclen); + +#if COCOS2D_DEBUG > 0 + // verify checksum in debug mode + unsigned int calculated = ccChecksumPvr(ints, enclen); + unsigned int required = CC_SWAP_INT32_BIG_TO_HOST( header->reserved ); + + if(calculated != required) + { + CCLOG("cocos2d: Can't decrypt image file. Is the decryption key valid?"); + delete [] compressed; + return -1; + } +#endif + } + else + { + CCLOG("cocos2d: Invalid CCZ file"); + delete [] compressed; + return -1; + } + + unsigned int len = CC_SWAP_INT32_BIG_TO_HOST( header->len ); + + *out = (unsigned char*)malloc( len ); + if(! *out ) + { + CCLOG("cocos2d: CCZ: Failed to allocate memory for texture"); + delete [] compressed; + return -1; + } + + unsigned long destlen = len; + unsigned long source = (unsigned long) compressed + sizeof(*header); + int ret = uncompress(*out, &destlen, (Bytef*)source, fileLen - sizeof(*header) ); + + delete [] compressed; + + if( ret != Z_OK ) + { + CCLOG("cocos2d: CCZ: Failed to uncompress data"); + free( *out ); + *out = NULL; + return -1; + } + + return len; +} - if(NULL == compressed || 0 == fileLen) - { - CCLOG("cocos2d: Error loading CCZ compressed file"); - return -1; - } +void ZipUtils::ccSetPvrEncryptionKeyPart(int index, unsigned int value) +{ + CCAssert(index >= 0, "Cocos2d: key part index cannot be less than 0"); + CCAssert(index <= 3, "Cocos2d: key part index cannot be greater than 3"); + + if(s_uEncryptedPvrKeyParts[index] != value) + { + s_uEncryptedPvrKeyParts[index] = value; + s_bEncryptionKeyIsValid = false; + } +} - struct CCZHeader *header = (struct CCZHeader*) compressed; - - // verify header - if( header->sig[0] != 'C' || header->sig[1] != 'C' || header->sig[2] != 'Z' || header->sig[3] != '!' ) - { - CCLOG("cocos2d: Invalid CCZ file"); - delete [] compressed; - return -1; - } - - // verify header version - unsigned int version = CC_SWAP_INT16_BIG_TO_HOST( header->version ); - if( version > 2 ) - { - CCLOG("cocos2d: Unsupported CCZ header format"); - delete [] compressed; - return -1; - } - - // verify compression format - if( CC_SWAP_INT16_BIG_TO_HOST(header->compression_type) != CCZ_COMPRESSION_ZLIB ) - { - CCLOG("cocos2d: CCZ Unsupported compression method"); - delete [] compressed; - return -1; - } - - unsigned int len = CC_SWAP_INT32_BIG_TO_HOST( header->len ); - - *out = (unsigned char*)malloc( len ); - if(! *out ) - { - CCLOG("cocos2d: CCZ: Failed to allocate memory for texture"); - delete [] compressed; - return -1; - } - - - unsigned long destlen = len; - unsigned long source = (unsigned long) compressed + sizeof(*header); - int ret = uncompress(*out, &destlen, (Bytef*)source, fileLen - sizeof(*header) ); - - delete [] compressed; - - if( ret != Z_OK ) - { - CCLOG("cocos2d: CCZ: Failed to uncompress data"); - free( *out ); - *out = NULL; - return -1; - } - - return len; +void ZipUtils::ccSetPvrEncryptionKey(unsigned int keyPart1, unsigned int keyPart2, unsigned int keyPart3, unsigned int keyPart4) +{ + ccSetPvrEncryptionKeyPart(0, keyPart1); + ccSetPvrEncryptionKeyPart(1, keyPart2); + ccSetPvrEncryptionKeyPart(2, keyPart3); + ccSetPvrEncryptionKeyPart(3, keyPart4); } // --------------------- ZipFile --------------------- @@ -298,14 +448,14 @@ class ZipFilePrivate { public: unzFile zipFile; - + // std::unordered_map is faster if available on the platform typedef std::map FileListContainer; FileListContainer fileList; }; ZipFile::ZipFile(const std::string &zipFile, const std::string &filter) - : m_data(new ZipFilePrivate) +: m_data(new ZipFilePrivate) { m_data->zipFile = unzOpen(zipFile.c_str()); if (m_data->zipFile) @@ -330,17 +480,17 @@ bool ZipFile::setFilter(const std::string &filter) { CC_BREAK_IF(!m_data); CC_BREAK_IF(!m_data->zipFile); - + // clear existing file list m_data->fileList.clear(); - + // UNZ_MAXFILENAMEINZIP + 1 - it is done so in unzLocateFile char szCurrentFileName[UNZ_MAXFILENAMEINZIP + 1]; unz_file_info64 fileInfo; - + // go through all files and store position information about the required files int err = unzGoToFirstFile64(m_data->zipFile, &fileInfo, - szCurrentFileName, sizeof(szCurrentFileName) - 1); + szCurrentFileName, sizeof(szCurrentFileName) - 1); while (err == UNZ_OK) { unz_file_pos posInfo; @@ -360,12 +510,12 @@ bool ZipFile::setFilter(const std::string &filter) } // next file - also get the information about it err = unzGoToNextFile64(m_data->zipFile, &fileInfo, - szCurrentFileName, sizeof(szCurrentFileName) - 1); + szCurrentFileName, sizeof(szCurrentFileName) - 1); } ret = true; - + } while(false); - + return ret; } @@ -375,10 +525,10 @@ bool ZipFile::fileExists(const std::string &fileName) const do { CC_BREAK_IF(!m_data); - + ret = m_data->fileList.find(fileName) != m_data->fileList.end(); } while(false); - + return ret; } @@ -389,34 +539,34 @@ unsigned char *ZipFile::getFileData(const std::string &fileName, unsigned long * { *pSize = 0; } - + do { CC_BREAK_IF(!m_data->zipFile); CC_BREAK_IF(fileName.empty()); - + ZipFilePrivate::FileListContainer::const_iterator it = m_data->fileList.find(fileName); CC_BREAK_IF(it == m_data->fileList.end()); - + ZipEntryInfo fileInfo = it->second; - + int nRet = unzGoToFilePos(m_data->zipFile, &fileInfo.pos); CC_BREAK_IF(UNZ_OK != nRet); - + nRet = unzOpenCurrentFile(m_data->zipFile); CC_BREAK_IF(UNZ_OK != nRet); - + pBuffer = new unsigned char[fileInfo.uncompressed_size]; int CC_UNUSED nSize = unzReadCurrentFile(m_data->zipFile, pBuffer, fileInfo.uncompressed_size); CCAssert(nSize == 0 || nSize == (int)fileInfo.uncompressed_size, "the file size is wrong"); - + if (pSize) { *pSize = fileInfo.uncompressed_size; } unzCloseCurrentFile(m_data->zipFile); } while (0); - + return pBuffer; } diff --git a/cocos2dx/support/zip_support/ZipUtils.h b/cocos2dx/support/zip_support/ZipUtils.h index 3acf8a6aa5..3824cb0d5e 100644 --- a/cocos2dx/support/zip_support/ZipUtils.h +++ b/cocos2dx/support/zip_support/ZipUtils.h @@ -25,6 +25,7 @@ THE SOFTWARE. #define __SUPPORT_ZIPUTILS_H__ #include +#include "CCPlatformDefine.h" namespace cocos2d { @@ -32,21 +33,21 @@ namespace cocos2d /** @struct CCZHeader */ struct CCZHeader { - unsigned char sig[4]; // signature. Should be 'CCZ!' 4 bytes - unsigned short compression_type; // should 0 - unsigned short version; // should be 2 (although version type==1 is also supported) - unsigned int reserved; // Reserved for users. - unsigned int len; // size of the uncompressed file + unsigned char sig[4]; // signature. Should be 'CCZ!' 4 bytes + unsigned short compression_type; // should 0 + unsigned short version; // should be 2 (although version type==1 is also supported) + unsigned int reserved; // Reserved for users. + unsigned int len; // size of the uncompressed file }; enum { - CCZ_COMPRESSION_ZLIB, // zlib format. - CCZ_COMPRESSION_BZIP2, // bzip2 format (not supported yet) - CCZ_COMPRESSION_GZIP, // gzip format (not supported yet) - CCZ_COMPRESSION_NONE, // plain (not supported yet) + CCZ_COMPRESSION_ZLIB, // zlib format. + CCZ_COMPRESSION_BZIP2, // bzip2 format (not supported yet) + CCZ_COMPRESSION_GZIP, // gzip format (not supported yet) + CCZ_COMPRESSION_NONE, // plain (not supported yet) }; - class ZipUtils + class CC_DLL ZipUtils { public: /** @@ -88,9 +89,67 @@ namespace cocos2d */ static int ccInflateCCZFile(const char *filename, unsigned char **out); + /** Sets the pvr.ccz encryption key parts separately for added + * security. + * + * Example: If the key used to encrypt the pvr.ccz file is + * 0xaaaaaaaabbbbbbbbccccccccdddddddd you will call this function 4 + * different times, preferably from 4 different source files, as follows + * + * ZipUtils::ccSetPvrEncryptionKeyPart(0, 0xaaaaaaaa); + * ZipUtils::ccSetPvrEncryptionKeyPart(1, 0xbbbbbbbb); + * ZipUtils::ccSetPvrEncryptionKeyPart(2, 0xcccccccc); + * ZipUtils::ccSetPvrEncryptionKeyPart(3, 0xdddddddd); + * + * Splitting the key into 4 parts and calling the function + * from 4 different source files increases the difficulty to + * reverse engineer the encryption key. Be aware that encrpytion + * is *never* 100% secure and the key code can be cracked by + * knowledgable persons. + * + * IMPORTANT: Be sure to call ccSetPvrEncryptionKey or + * ccSetPvrEncryptionKeyPart with all of the key parts *before* loading + * the spritesheet or decryption will fail and the spritesheet + * will fail to load. + * + * @param index part of the key [0..3] + * @param value value of the key part + */ + static void ccSetPvrEncryptionKeyPart(int index, unsigned int value); + + /** Sets the pvr.ccz encryption key. + * + * Example: If the key used to encrypt the pvr.ccz file is + * 0xaaaaaaaabbbbbbbbccccccccdddddddd you will call this function with + * the key split into 4 parts as follows + * + * ZipUtils::ccSetPvrEncryptionKey(0xaaaaaaaa, 0xbbbbbbbb, 0xcccccccc, 0xdddddddd); + * + * Note that using this function makes it easier to reverse engineer and + * discover the complete key because the key parts are present in one + * function call. + * + * IMPORTANT: Be sure to call ccSetPvrEncryptionKey or + * ccSetPvrEncryptionKeyPart with all of the key parts *before* loading + * the spritesheet or decryption will fail and the spritesheet + * will fail to load. + * + * @param keyPart1 the key value part 1. + * @param keyPart2 the key value part 2. + * @param keyPart3 the key value part 3. + * @param keyPart4 the key value part 4. + */ + static void ccSetPvrEncryptionKey(unsigned int keyPart1, unsigned int keyPart2, unsigned int keyPart3, unsigned int keyPart4); + private: static int ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, unsigned char **out, unsigned int *outLength, - unsigned int outLenghtHint); + unsigned int outLenghtHint); + static inline void ccDecodeEncodedPvr (unsigned int *data, int len); + static inline unsigned int ccChecksumPvr(const unsigned int *data, int len); + + static unsigned int s_uEncryptedPvrKeyParts[4]; + static unsigned int s_uEncryptionKey[1024]; + static bool s_bEncryptionKeyIsValid; }; // forward declaration diff --git a/cocos2dx/textures/CCTexture2D.cpp b/cocos2dx/textures/CCTexture2D.cpp index 234f0c8c1b..ddeafb4f81 100644 --- a/cocos2dx/textures/CCTexture2D.cpp +++ b/cocos2dx/textures/CCTexture2D.cpp @@ -174,14 +174,23 @@ bool CCTexture2D::hasPremultipliedAlpha() bool CCTexture2D::initWithData(const void *data, CCTexture2DPixelFormat pixelFormat, unsigned int pixelsWide, unsigned int pixelsHigh, const CCSize& contentSize) { - // XXX: 32 bits or POT textures uses UNPACK of 4 (is this correct ??? ) - if( pixelFormat == kCCTexture2DPixelFormat_RGBA8888 || ( ccNextPOT(pixelsWide)==pixelsWide && ccNextPOT(pixelsHigh)==pixelsHigh) ) + unsigned int bytesPerRow = pixelsWide * bitsPerPixelForFormat(pixelFormat) / 8; + + if(bytesPerRow % 8 == 0) { - glPixelStorei(GL_UNPACK_ALIGNMENT,4); + glPixelStorei(GL_UNPACK_ALIGNMENT, 8); + } + else if(bytesPerRow % 4 == 0) + { + glPixelStorei(GL_UNPACK_ALIGNMENT, 4); + } + else if(bytesPerRow % 2 == 0) + { + glPixelStorei(GL_UNPACK_ALIGNMENT, 2); } else { - glPixelStorei(GL_UNPACK_ALIGNMENT,1); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); } glGenTextures(1, &m_uName); diff --git a/cocos2dx/textures/CCTextureCache.cpp b/cocos2dx/textures/CCTextureCache.cpp index c5b43ae678..cb6f25caa3 100644 --- a/cocos2dx/textures/CCTextureCache.cpp +++ b/cocos2dx/textures/CCTextureCache.cpp @@ -69,6 +69,10 @@ static pthread_cond_t s_SleepCondition; static pthread_mutex_t s_asyncStructQueueMutex; static pthread_mutex_t s_ImageInfoMutex; +#ifdef EMSCRIPTEN +// Hack to get ASM.JS validation (no undefined symbols allowed). +#define pthread_cond_signal(_) +#endif // EMSCRIPTEN static unsigned long s_nAsyncRefCount = 0; @@ -233,6 +237,11 @@ CCDictionary* CCTextureCache::snapshotTextures() void CCTextureCache::addImageAsync(const char *path, CCObject *target, SEL_CallFuncO selector) { +#ifdef EMSCRIPTEN + CCLOGWARN("Cannot load image %s asynchronously in Emscripten builds.", path); + return; +#endif // EMSCRIPTEN + CCAssert(path != NULL, "TextureCache: fileimage MUST not be NULL"); CCTexture2D *texture = NULL; diff --git a/cocos2dx/textures/CCTexturePVR.cpp b/cocos2dx/textures/CCTexturePVR.cpp index 926a6c1499..73282426c8 100644 --- a/cocos2dx/textures/CCTexturePVR.cpp +++ b/cocos2dx/textures/CCTexturePVR.cpp @@ -443,7 +443,7 @@ bool CCTexturePVR::unpackPVRv3Data(unsigned char* dataPointer, unsigned int data // unsupported / bad pixel format if (! infoValid) { - CCLOG("cocos2d: WARNING: unsupported pvr pixelformat: %lx", pixelFormat ); + CCLOG("cocos2d: WARNING: unsupported pvr pixelformat: %lx", (unsigned long)pixelFormat ); return false; } diff --git a/extensions/CCBReader/CCBAnimationManager.cpp b/extensions/CCBReader/CCBAnimationManager.cpp index fd8d88e3af..9c76ce4a6b 100644 --- a/extensions/CCBReader/CCBAnimationManager.cpp +++ b/extensions/CCBReader/CCBAnimationManager.cpp @@ -185,7 +185,11 @@ void CCBAnimationManager::setDelegate(CCBAnimationManagerDelegate *pDelegate) const char* CCBAnimationManager::getRunningSequenceName() { - return mRunningSequence->getName(); + if (mRunningSequence) + { + return mRunningSequence->getName(); + } + return NULL; } const CCSize& CCBAnimationManager::getContainerSize(CCNode *pNode) diff --git a/extensions/CCBReader/CCBValue.cpp b/extensions/CCBReader/CCBValue.cpp index 21ffdef8c9..cff2f80739 100644 --- a/extensions/CCBReader/CCBValue.cpp +++ b/extensions/CCBReader/CCBValue.cpp @@ -131,7 +131,7 @@ bool CCBValue::getBoolValue() unsigned char CCBValue::getByteValue() { - assert(mType = kUnsignedCharValue); + assert(mType == kUnsignedCharValue); return (unsigned char)(mValue.nValue); } diff --git a/extensions/GUI/CCControlExtension/CCControlButton.cpp b/extensions/GUI/CCControlExtension/CCControlButton.cpp index f3b2065417..97df19c495 100644 --- a/extensions/GUI/CCControlExtension/CCControlButton.cpp +++ b/extensions/GUI/CCControlExtension/CCControlButton.cpp @@ -721,6 +721,23 @@ GLubyte CCControlButton::getOpacity() return _realOpacity; } +void CCControlButton::setColor(const ccColor3B & color) +{ + CCControl::setColor(color); + + CCDictElement * item = NULL; + CCDICT_FOREACH(m_backgroundSpriteDispatchTable, item) + { + CCScale9Sprite* sprite = (CCScale9Sprite*)item->getObject(); + sprite->setColor(color); + } +} + +const ccColor3B& CCControlButton::getColor() +{ + return _realColor; +} + void CCControlButton::ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent) { m_isPushed = false; diff --git a/extensions/GUI/CCControlExtension/CCControlButton.h b/extensions/GUI/CCControlExtension/CCControlButton.h index 062bef22ab..046f87aab8 100644 --- a/extensions/GUI/CCControlExtension/CCControlButton.h +++ b/extensions/GUI/CCControlExtension/CCControlButton.h @@ -93,6 +93,8 @@ protected: /* Override setter to affect a background sprite too */ virtual GLubyte getOpacity(void); virtual void setOpacity(GLubyte var); + virtual const ccColor3B& getColor(void); + virtual void setColor(const ccColor3B&); /** Flag to know if the button is currently pushed. */ protected: diff --git a/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp b/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp index 67354dc17c..1c29cc8a1d 100644 --- a/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp +++ b/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp @@ -805,6 +805,11 @@ void CCScale9Sprite::setColor(const ccColor3B& color) } } +const ccColor3B& CCScale9Sprite::getColor() +{ + return _color; +} + void CCScale9Sprite::setOpacity(GLubyte opacity) { _opacity = opacity; @@ -821,4 +826,9 @@ void CCScale9Sprite::setOpacity(GLubyte opacity) } } +GLubyte CCScale9Sprite::getOpacity() +{ + return _opacity; +} + NS_CC_EXT_END diff --git a/extensions/GUI/CCControlExtension/CCScale9Sprite.h b/extensions/GUI/CCControlExtension/CCScale9Sprite.h index 437ba9a9d2..09a65b66b5 100644 --- a/extensions/GUI/CCControlExtension/CCScale9Sprite.h +++ b/extensions/GUI/CCControlExtension/CCScale9Sprite.h @@ -308,7 +308,9 @@ public: */ virtual bool isOpacityModifyRGB(void); virtual void setOpacity(GLubyte opacity); + virtual GLubyte getOpacity(); virtual void setColor(const ccColor3B& color); + virtual const ccColor3B& getColor(); virtual bool updateWithBatchNode(CCSpriteBatchNode* batchnode, CCRect rect, bool rotated, CCRect capInsets); diff --git a/extensions/GUI/CCScrollView/CCScrollView.cpp b/extensions/GUI/CCScrollView/CCScrollView.cpp index 24b450c618..b27b375f8a 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.cpp +++ b/extensions/GUI/CCScrollView/CCScrollView.cpp @@ -436,7 +436,7 @@ void CCScrollView::performedAnimatedScroll(float dt) } -const CCSize& CCScrollView::getContentSize() +const CCSize& CCScrollView::getContentSize() const { return m_pContainer->getContentSize(); } diff --git a/extensions/GUI/CCScrollView/CCScrollView.h b/extensions/GUI/CCScrollView/CCScrollView.h index 00602374ac..23cf2a9e2a 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.h +++ b/extensions/GUI/CCScrollView/CCScrollView.h @@ -187,7 +187,7 @@ public: virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent); virtual void setContentSize(const CCSize & size); - virtual const CCSize& getContentSize(); + virtual const CCSize& getContentSize() const; void updateInset(); /** diff --git a/samples/Cpp/TestCpp/Android.mk b/samples/Cpp/TestCpp/Android.mk index 10c180ccfd..1bb55f60bc 100644 --- a/samples/Cpp/TestCpp/Android.mk +++ b/samples/Cpp/TestCpp/Android.mk @@ -85,6 +85,7 @@ Classes/SpineTest/SpineTest.cpp \ Classes/SpriteTest/SpriteTest.cpp \ Classes/TextureCacheTest/TextureCacheTest.cpp \ Classes/Texture2dTest/Texture2dTest.cpp \ +Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp \ Classes/TileMapTest/TileMapTest.cpp \ Classes/TouchesTest/Ball.cpp \ Classes/TouchesTest/Paddle.cpp \ @@ -93,6 +94,7 @@ Classes/TransitionsTest/TransitionsTest.cpp \ Classes/UserDefaultTest/UserDefaultTest.cpp \ Classes/ZwoptexTest/ZwoptexTest.cpp \ Classes/FileUtilsTest/FileUtilsTest.cpp \ +Classes/DataVisitorTest/DataVisitorTest.cpp \ Classes/controller.cpp \ Classes/testBasic.cpp \ Classes/AppDelegate.cpp \ diff --git a/samples/Cpp/TestCpp/Classes/DataVisitorTest/DataVisitorTest.cpp b/samples/Cpp/TestCpp/Classes/DataVisitorTest/DataVisitorTest.cpp new file mode 100644 index 0000000000..d753490ff7 --- /dev/null +++ b/samples/Cpp/TestCpp/Classes/DataVisitorTest/DataVisitorTest.cpp @@ -0,0 +1,86 @@ +#include "DataVisitorTest.h" +#include "../testResource.h" + +std::string PrettyPrinterDemo::title() +{ + return "PrettyPrinter Test"; +} + +std::string PrettyPrinterDemo::subtitle() +{ + return "Please see log!"; +} + +void PrettyPrinterDemo::addSprite() +{ + // create sprites + + CCSprite *s1 = CCSprite::create("Images/grossini.png"); + CCSprite *s2 = CCSprite::create("Images/grossini_dance_01.png"); + CCSprite *s3 = CCSprite::create("Images/grossini_dance_02.png"); + CCSprite *s4 = CCSprite::create("Images/grossini_dance_03.png"); + CCSprite *s5 = CCSprite::create("Images/grossini_dance_04.png"); + + s1->setPosition(ccp(50, 50)); + s2->setPosition(ccp(60, 50)); + s3->setPosition(ccp(70, 50)); + s4->setPosition(ccp(80, 50)); + s5->setPosition(ccp(90, 50)); + + this->addChild(s1); + this->addChild(s2); + this->addChild(s3); + this->addChild(s4); + this->addChild(s5); +} + +void PrettyPrinterDemo::onEnter() +{ + CCLayer::onEnter(); + CCSize s = CCDirector::sharedDirector()->getWinSize(); + + CCLabelTTF* label = CCLabelTTF::create(title().c_str(), "Arial", 28); + label->setPosition( ccp(s.width/2, s.height * 4/5) ); + this->addChild(label, 1); + + std::string strSubtitle = subtitle(); + if(strSubtitle.empty() == false) + { + CCLabelTTF* subLabel = CCLabelTTF::create(strSubtitle.c_str(), "Thonburi", 16); + subLabel->setPosition( ccp(s.width/2, s.height * 3/5) ); + this->addChild(subLabel, 1); + } + + // Test code + CCPrettyPrinter vistor; + + // print dictionary + CCDictionary* pDict = CCDictionary::createWithContentsOfFile("animations/animations.plist"); + pDict->acceptVisitor(vistor); + CCLog("%s", vistor.getResult().c_str()); + CCLog("-------------------------------"); + + CCSet myset; + for (int i = 0; i < 30; ++i) { + myset.addObject(CCString::createWithFormat("str: %d", i)); + } + vistor.clear(); + myset.acceptVisitor(vistor); + CCLog("%s", vistor.getResult().c_str()); + CCLog("-------------------------------"); + + vistor.clear(); + addSprite(); + pDict = CCTextureCache::sharedTextureCache()->snapshotTextures(); + pDict->acceptVisitor(vistor); + CCLog("%s", vistor.getResult().c_str()); +} + +void DataVisitorTestScene::runThisTest() +{ + CCLayer *layer = new PrettyPrinterDemo(); + layer->autorelease(); + addChild(layer); + + CCDirector::sharedDirector()->replaceScene(this); +} diff --git a/samples/Cpp/TestCpp/Classes/DataVisitorTest/DataVisitorTest.h b/samples/Cpp/TestCpp/Classes/DataVisitorTest/DataVisitorTest.h new file mode 100644 index 0000000000..e5d3c0258d --- /dev/null +++ b/samples/Cpp/TestCpp/Classes/DataVisitorTest/DataVisitorTest.h @@ -0,0 +1,27 @@ +#ifndef __DATAVISITOR_TEST_H__ +#define __DATAVISITOR_TEST_H__ + +#include "../testBasic.h" + +#include + +class PrettyPrinterDemo : public CCLayer +{ +public: + virtual std::string title(); + virtual std::string subtitle(); + virtual void onEnter(); + void addSprite(); +protected: + std::string m_strTitle; +}; + +class DataVisitorTestScene : public TestScene +{ +public: + virtual void runThisTest(); + + CREATE_FUNC(DataVisitorTestScene); +}; + +#endif // __DATAVISITOR_TEST_H__ diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp index 896eb50acb..34b5f15cfa 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp @@ -46,17 +46,35 @@ bool CCControlButtonTest_HelloVariableSize::init() // For each title in the array CCObject* pObj = NULL; + int i = 0; CCARRAY_FOREACH(stringArray, pObj) { CCString* title = (CCString*)pObj; // Creates a button with this string as title CCControlButton *button = standardButtonWithTitle(title->getCString()); + if (i == 0) + { + button->setOpacity(50); + button->setColor(ccc3(0, 255, 0)); + } + else if (i == 1) + { + button->setOpacity(200); + button->setColor(ccc3(0, 255, 0)); + } + else if (i == 2) + { + button->setOpacity(100); + button->setColor(ccc3(0, 0, 255)); + } + button->setPosition(ccp (total_width + button->getContentSize().width / 2, button->getContentSize().height / 2)); layer->addChild(button); // Compute the size of the layer height = button->getContentSize().height; total_width += button->getContentSize().width; + i++; } layer->setAnchorPoint(ccp (0.5, 0.5)); @@ -86,7 +104,7 @@ CCControlButton *CCControlButtonTest_HelloVariableSize::standardButtonWithTitle( CCControlButton *button = CCControlButton::create(titleButton, backgroundButton); button->setBackgroundSpriteForState(backgroundHighlightedButton, CCControlStateHighlighted); button->setTitleColorForState(ccWHITE, CCControlStateHighlighted); - + return button; } diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ExtensionsTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ExtensionsTest.cpp index 5c7354ee0e..1e4d50aaab 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ExtensionsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/ExtensionsTest.cpp @@ -3,7 +3,9 @@ #include "NotificationCenterTest/NotificationCenterTest.h" #include "ControlExtensionTest/CCControlSceneManager.h" #include "CocosBuilderTest/CocosBuilderTest.h" +#if (CC_TARGET_PLATFORM != CC_PLATFORM_EMSCRIPTEN) #include "NetworkTest/HttpClientTest.h" +#endif #include "TableViewTest/TableViewTestScene.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) @@ -34,7 +36,9 @@ static const std::string testsName[TEST_MAX_COUNT] = "NotificationCenterTest", "CCControlButtonTest", "CocosBuilderTest", +#if (CC_TARGET_PLATFORM != CC_PLATFORM_EMSCRIPTEN) "HttpClientTest", +#endif #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) "EditBoxTest", #endif @@ -98,7 +102,7 @@ void ExtensionsMainLayer::menuCallback(CCObject* pSender) } } break; -#if (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE && CC_TARGET_PLATFORM != CC_PLATFORM_NACL) +#if (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE && CC_TARGET_PLATFORM != CC_PLATFORM_NACL && CC_TARGET_PLATFORM != CC_PLATFORM_EMSCRIPTEN) case TEST_HTTPCLIENT: { runHttpClientTest(); diff --git a/samples/Cpp/TestCpp/Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp b/samples/Cpp/TestCpp/Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp new file mode 100644 index 0000000000..62697755dc --- /dev/null +++ b/samples/Cpp/TestCpp/Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp @@ -0,0 +1,82 @@ +#include "TextureAtlasEncryptionTest.h" +#include "../testResource.h" +#include "support/zip_support/ZipUtils.h" + +std::string TextureAtlasEncryptionDemo::title() +{ + return "Texture Atlas Encryption"; +} + +std::string TextureAtlasEncryptionDemo::subtitle() +{ + return ""; +} + +void TextureAtlasEncryptionDemo::onEnter() +{ + CCLayer::onEnter(); + + CCSize s = CCDirector::sharedDirector()->getWinSize(); + + CCLabelTTF* label = CCLabelTTF::create(title().c_str(), "Arial", 28); + label->setPosition( ccp(s.width/2, s.height * 0.75f) ); + this->addChild(label, 1); + + std::string strSubtitle = subtitle(); + if(strSubtitle.empty() == false) + { + CCLabelTTF* subLabel = CCLabelTTF::create(strSubtitle.c_str(), "Thonburi", 16); + subLabel->setPosition( ccp(s.width/2, s.height-80) ); + this->addChild(subLabel, 1); + } + + // Load the non-encrypted atlas + CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("Images/nonencryptedAtlas.plist", "Images/nonencryptedAtlas.pvr.ccz"); + + // Create a sprite from the non-encrypted atlas + CCSprite *nonencryptedSprite = CCSprite::createWithSpriteFrameName("Icon.png"); + nonencryptedSprite->setPosition(ccp(s.width * 0.25f, s.height * 0.5f)); + this->addChild(nonencryptedSprite); + + CCLabelTTF* nonencryptedSpriteLabel = CCLabelTTF::create("non-encrypted", "Arial", 28); + nonencryptedSpriteLabel->setPosition(ccp(s.width * 0.25f, nonencryptedSprite->boundingBox().getMinY() - nonencryptedSprite->getContentSize().height/2)); + this->addChild(nonencryptedSpriteLabel, 1); + + // Load the encrypted atlas + // 1) Set the encryption keys or step 2 will fail + // In this case the encryption key 0xaaaaaaaabbbbbbbbccccccccdddddddd is + // split into four parts. See the header docs for more information. + ZipUtils::ccSetPvrEncryptionKeyPart(0, 0xaaaaaaaa); + ZipUtils::ccSetPvrEncryptionKeyPart(1, 0xbbbbbbbb); + ZipUtils::ccSetPvrEncryptionKeyPart(2, 0xcccccccc); + ZipUtils::ccSetPvrEncryptionKeyPart(3, 0xdddddddd); + + // Alternatively, you can call the function that accepts the key in a single + // function call. + // This is slightly less secure because the entire key is more easily + // found in the compiled source. See the header docs for more information. + // ZipUtils::ccSetPvrEncryptionKey(0xaaaaaaaa, 0xbbbbbbbb, 0xcccccccc, 0xdddddddd); + + // 2) Load the encrypted atlas + CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("Images/encryptedAtlas.plist", "Images/encryptedAtlas.pvr.ccz"); + + // 3) Create a sprite from the encrypted atlas + CCSprite *encryptedSprite = CCSprite::createWithSpriteFrameName("powered.png"); + encryptedSprite->setPosition(ccp(s.width * 0.75f, s.height * 0.5f)); + this->addChild(encryptedSprite); + + CCLabelTTF* encryptedSpriteLabel = CCLabelTTF::create("encrypted", "Arial", 28); + encryptedSpriteLabel->setPosition(ccp(s.width * 0.75f, encryptedSprite->boundingBox().getMinY() - encryptedSpriteLabel->getContentSize().height/2)); + this->addChild(encryptedSpriteLabel, 1); +} + +void TextureAtlasEncryptionTestScene::runThisTest() +{ + CCLayer *layer = new TextureAtlasEncryptionDemo; + layer->autorelease(); + + addChild(layer); + + CCDirector::sharedDirector()->replaceScene(this); +} + diff --git a/samples/Cpp/TestCpp/Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.h b/samples/Cpp/TestCpp/Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.h new file mode 100644 index 0000000000..9aeac154f3 --- /dev/null +++ b/samples/Cpp/TestCpp/Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.h @@ -0,0 +1,25 @@ +#ifndef _TextureAtlasEncryption_TEST_H_ +#define _TextureAtlasEncryption_TEST_H_ + +#include "cocos2d.h" +#include "../testBasic.h" +#include + +class TextureAtlasEncryptionDemo : public CCLayer +{ +public: + virtual std::string title(); + virtual std::string subtitle(); + virtual void onEnter(); + +protected: + std::string m_strTitle; +}; + +class TextureAtlasEncryptionTestScene : public TestScene +{ +public: + virtual void runThisTest(); +}; + +#endif diff --git a/samples/Cpp/TestCpp/Classes/controller.cpp b/samples/Cpp/TestCpp/Classes/controller.cpp index cd349fbe67..ff2dde8779 100644 --- a/samples/Cpp/TestCpp/Classes/controller.cpp +++ b/samples/Cpp/TestCpp/Classes/controller.cpp @@ -122,6 +122,12 @@ static TestScene* CreateTestScene(int nIdx) case TEST_SPINE: pScene = new SpineTestScene(); break; + case TEST_TEXTUREPACKER_ENCRYPTION: + pScene = new TextureAtlasEncryptionTestScene(); + break; + case TEST_DATAVISTOR: + pScene = new DataVisitorTestScene(); + break; default: break; } diff --git a/samples/Cpp/TestCpp/Classes/tests.h b/samples/Cpp/TestCpp/Classes/tests.h index 03cd2ef5c4..7ddbcdd6c8 100644 --- a/samples/Cpp/TestCpp/Classes/tests.h +++ b/samples/Cpp/TestCpp/Classes/tests.h @@ -56,6 +56,8 @@ #endif #include "FileUtilsTest/FileUtilsTest.h" #include "SpineTest/SpineTest.h" +#include "TexturePackerEncryptionTest/TextureAtlasEncryptionTest.h" +#include "DataVisitorTest/DataVisitorTest.h" enum { @@ -113,6 +115,8 @@ enum #endif TEST_FILEUTILS, TEST_SPINE, + TEST_TEXTUREPACKER_ENCRYPTION, + TEST_DATAVISTOR, TESTS_COUNT, }; @@ -172,7 +176,9 @@ const std::string g_aTestNames[TESTS_COUNT] = { "ClippingNodeTest", #endif "FileUtilsTest", - "SpineTest" + "SpineTest", + "TexturePackerEncryption", + "DataVistorTest" }; #endif diff --git a/samples/Cpp/TestCpp/proj.emscripten/Makefile b/samples/Cpp/TestCpp/proj.emscripten/Makefile index fa80d06d32..c6fa4bbe74 100644 --- a/samples/Cpp/TestCpp/proj.emscripten/Makefile +++ b/samples/Cpp/TestCpp/proj.emscripten/Makefile @@ -83,6 +83,7 @@ SOURCES = ../Classes/AccelerometerTest/AccelerometerTest.cpp \ ../Classes/UserDefaultTest/UserDefaultTest.cpp \ ../Classes/ZwoptexTest/ZwoptexTest.cpp \ ../Classes/FileUtilsTest/FileUtilsTest.cpp \ + ../Classes/DataVisitorTest/DataVisitorTest.cpp \ ../Classes/controller.cpp \ ../Classes/testBasic.cpp \ ../Classes/AppDelegate.cpp \ diff --git a/samples/Cpp/TestCpp/proj.ios/TestCpp.xcodeproj/project.pbxproj.REMOVED.git-id b/samples/Cpp/TestCpp/proj.ios/TestCpp.xcodeproj/project.pbxproj.REMOVED.git-id index 077c23ee8c..435c2f310c 100644 --- a/samples/Cpp/TestCpp/proj.ios/TestCpp.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/samples/Cpp/TestCpp/proj.ios/TestCpp.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -f4a587eb683fe30c950bf226a756c77d25c06468 \ No newline at end of file +6b5e473d37f1653e3e4098f7a69cd6be2b4bc4b4 \ No newline at end of file diff --git a/samples/Cpp/TestCpp/proj.linux/Makefile b/samples/Cpp/TestCpp/proj.linux/Makefile index 79dd9fa7fd..94f79cfd7a 100644 --- a/samples/Cpp/TestCpp/proj.linux/Makefile +++ b/samples/Cpp/TestCpp/proj.linux/Makefile @@ -75,6 +75,7 @@ SOURCES = ../Classes/AccelerometerTest/AccelerometerTest.cpp \ ../Classes/SpriteTest/SpriteTest.cpp \ ../Classes/TextInputTest/TextInputTest.cpp \ ../Classes/Texture2dTest/Texture2dTest.cpp \ + ../Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp \ ../Classes/TextureCacheTest/TextureCacheTest.cpp \ ../Classes/TileMapTest/TileMapTest.cpp \ ../Classes/TouchesTest/Ball.cpp \ @@ -85,6 +86,7 @@ SOURCES = ../Classes/AccelerometerTest/AccelerometerTest.cpp \ ../Classes/ZwoptexTest/ZwoptexTest.cpp \ ../Classes/FileUtilsTest/FileUtilsTest.cpp \ ../Classes/SpineTest/SpineTest.cpp \ + ../Classes/DataVisitorTest/DataVisitorTest.cpp \ ../Classes/controller.cpp \ ../Classes/testBasic.cpp \ ../Classes/AppDelegate.cpp \ diff --git a/samples/Cpp/TestCpp/proj.mac/TestCpp.xcodeproj/project.pbxproj.REMOVED.git-id b/samples/Cpp/TestCpp/proj.mac/TestCpp.xcodeproj/project.pbxproj.REMOVED.git-id index 6eb519d852..dda145c726 100644 --- a/samples/Cpp/TestCpp/proj.mac/TestCpp.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/samples/Cpp/TestCpp/proj.mac/TestCpp.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -ff7a1763f32d0d088fa1e219e5737fdc9cc2c1c8 \ No newline at end of file +90d267b6c461f771978ca8a8d23c6e688cfa7077 \ No newline at end of file diff --git a/samples/Cpp/TestCpp/proj.marmalade/TestCPP.mkb b/samples/Cpp/TestCpp/proj.marmalade/TestCPP.mkb index d9be066083..0b73cf3867 100644 --- a/samples/Cpp/TestCpp/proj.marmalade/TestCPP.mkb +++ b/samples/Cpp/TestCpp/proj.marmalade/TestCPP.mkb @@ -432,6 +432,11 @@ files TextureCacheTest.cpp TextureCacheTest.h + [Test/TexturePackerEncryptionTest] + [../Classes/TexturePackerEncryptionTest] + TexturePackerEncryptionTest.cpp + TexturePackerEncryptionTest.h + [Test/TileMapTest] (../Classes/TileMapTest) TileMapTest.cpp @@ -470,6 +475,11 @@ files (../Classes/SpineTest) SpineTest.cpp SpineTest.h + + [Test/DataVisitorTest] + (../Classes/DataVisitorTest) + DataVisitorTest.cpp + DataVisitorTest.h } diff --git a/samples/Cpp/TestCpp/proj.nacl/Makefile b/samples/Cpp/TestCpp/proj.nacl/Makefile index 603eefe4a7..2df7cc44d5 100644 --- a/samples/Cpp/TestCpp/proj.nacl/Makefile +++ b/samples/Cpp/TestCpp/proj.nacl/Makefile @@ -82,6 +82,7 @@ SOURCES = ../Classes/AccelerometerTest/AccelerometerTest.cpp \ ../Classes/TextInputTest/TextInputTest.cpp \ ../Classes/Texture2dTest/Texture2dTest.cpp \ ../Classes/TextureCacheTest/TextureCacheTest.cpp \ + ../Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp \ ../Classes/TileMapTest/TileMapTest.cpp \ ../Classes/TouchesTest/Ball.cpp \ ../Classes/TouchesTest/Paddle.cpp \ @@ -90,6 +91,7 @@ SOURCES = ../Classes/AccelerometerTest/AccelerometerTest.cpp \ ../Classes/UserDefaultTest/UserDefaultTest.cpp \ ../Classes/ZwoptexTest/ZwoptexTest.cpp \ ../Classes/SpineTest/SpineTest.cpp \ + ../Classes/DataVisitorTest/DataVisitorTest.cpp \ ../Classes/controller.cpp \ ../Classes/testBasic.cpp \ ../Classes/AppDelegate.cpp \ diff --git a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj index 3bb95d0f2d..3565b3bea3 100644 --- a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj +++ b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj @@ -121,6 +121,7 @@ + @@ -131,6 +132,7 @@ + @@ -214,6 +216,7 @@ + @@ -226,6 +229,7 @@ + diff --git a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters index 6a453f61c8..bcf9517792 100644 --- a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters +++ b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters @@ -217,6 +217,12 @@ {60df7835-5770-44bb-b5c7-24c9aa34da88} + + {4031c3bb-97f8-4b43-91e5-48dd94ca2d24} + + + {8049d378-12f7-46ba-ba96-091f3c0a4600} + @@ -492,6 +498,12 @@ Classes\SpineTest + + Classes\TexturePackerEncryptionTest + + + Classes\DataVisitorTest + @@ -947,5 +959,11 @@ Classes\SpineTest + + Classes\TexturePackerEncryptionTest + + + Classes\DataVisitorTest + \ No newline at end of file diff --git a/samples/Lua/TestLua/Resources/luaScript/PerformanceTest/PerformanceTest.lua b/samples/Lua/TestLua/Resources/luaScript/PerformanceTest/PerformanceTest.lua index 857dab121c..9a1f18ba4f 100644 --- a/samples/Lua/TestLua/Resources/luaScript/PerformanceTest/PerformanceTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/PerformanceTest/PerformanceTest.lua @@ -1,41 +1,1683 @@ require "luaScript/PerformanceTest/PerformanceSpriteTest" -local MAX_COUNT = 1 +local MAX_COUNT = 5 local LINE_SPACE = 40 local kItemTagBasic = 1000 local testsName = { - [0] = "PerformanceSpriteTest", - "PerformanceParticleTest", "PerformanceNodeChildrenTest", + "PerformanceParticleTest", + "PerformanceSpriteTest", "PerformanceTextureTest", "PerformanceTouchesTest" } local s = CCDirector:sharedDirector():getWinSize() +--Create toMainLayr MenuItem +function CreatePerfomBasicLayerMenu(pMenu) + if nil == pMenu then + return + end + local function toMainLayer() + local pScene = PerformanceTestMain() + if pScene ~= nil then + CCDirector:sharedDirector():replaceScene(pScene) + end + end + --Create BackMneu + CCMenuItemFont:setFontName("Arial") + CCMenuItemFont:setFontSize(24) + local pMenuItemFont = CCMenuItemFont:create("Back") + pMenuItemFont:setPosition(ccp(VisibleRect:rightBottom().x - 50, VisibleRect:rightBottom().y + 25)) + pMenuItemFont:registerScriptTapHandler(toMainLayer) + pMenu:addChild(pMenuItemFont) +end + ---------------------------------- --- PerformanceMainLayer +--PerformanceNodeChildrenTest ---------------------------------- -local function menuCallback(tag) +local NodeChildrenTestParam = +{ + kTagInfoLayer = 1, + kTagMainLayer = 2, + kTagLabelAtlas = 3, + kTagBase = 20000, + TEST_COUNT = 4, + kMaxNodes = 15000, + kNodesIncrease = 500, +} + +local function runNodeChildrenTest() + --NodeChildrenMainScene + local nLastRenderedCount = 0 + local nQuantityOfNodes = 0 + local nCurrentQuantityOfNodes = 0 + --IterateSpriteSheet + local pBatchNode = nil + + --BasiceLayer param + local bControlMenuVisible = false + local nMaxCases = 0 + local nCurCase = 0 + + local pNewscene = CCScene:create() + + local function GetTitle() + if 0 == nCurCase then + return "B - Iterate SpriteSheet" + elseif 1 == nCurCase then + return "C - Add to spritesheet" + elseif 2 == nCurCase then + return "D - Del from spritesheet" + elseif 3 == nCurCase then + return "E - Reorder from spritesheet" + end + end + + local function GetSubTitle() + if 0 == nCurCase then + return "Iterate children using C Array API. See console" + elseif 1 == nCurCase then + return "Adds %10 of total sprites with random z. See console" + elseif 2 == nCurCase then + return "Remove %10 of total sprites placed randomly. See console" + elseif 3 == nCurCase then + return "Reorder %10 of total sprites placed randomly. See console" + end + end + + local function GetProfilerName() + if 0 == nCurCase then + return "iter c-array" + elseif 1 == nCurCase then + return "add sprites" + elseif 2 == nCurCase then + return "remove sprites" + elseif 3 == nCurCase then + return "reorder sprites" + end + end + + local function CreateBasicLayerMenuItem(pMenu,bMenuVisible,nMaxCasesNum,nCurCaseIndex) + if nil ~= pMenu then + bControlMenuVisible = bMenuVisible + nMaxCases = nMaxCasesNum + nCurCase = nCurCaseIndex + if true == bControlMenuVisible then + local function backCallback() + nCurCase = nCurCase - 1 + if nCurCase < 0 then + nCurCase = nCurCase + nMaxCases + end + ShowCurrentTest() + end + + local function restartCallback() + ShowCurrentTest() + end + + local function nextCallback() + nCurCase = nCurCase + 1 + --No check nMaxCases + nCurCase = nCurCase % nMaxCases + ShowCurrentTest() + end + + local size = CCDirector:sharedDirector():getWinSize() + local item1 = CCMenuItemImage:create(s_pPathB1, s_pPathB2) + item1:registerScriptTapHandler(backCallback) + pMenu:addChild(item1,kItemTagBasic) + local item2 = CCMenuItemImage:create(s_pPathR1, s_pPathR2) + item2:registerScriptTapHandler(restartCallback) + pMenu:addChild(item2,kItemTagBasic) + local item3 = CCMenuItemImage:create(s_pPathF1, s_pPathF2) + pMenu:addChild(item3,kItemTagBasic) + item3:registerScriptTapHandler(nextCallback) + + local size = CCDirector:sharedDirector():getWinSize() + item1:setPosition(CCPointMake(size.width / 2 - item2:getContentSize().width * 2, item2:getContentSize().height / 2)) + item2:setPosition(CCPointMake(size.width / 2, item2:getContentSize().height / 2)) + item3:setPosition(CCPointMake(size.width / 2 + item2:getContentSize().width * 2, item2:getContentSize().height / 2)) + end + end + end + + local function updateQuantityLabel() + if nQuantityOfNodes ~= nLastRenderedCount then + -- local pInfoLabel = pNewscene:getChildByTag(NodeChildrenTestParam.kTagInfoLayer) + local pInfoLabel = tolua.cast(pNewscene:getChildByTag(NodeChildrenTestParam.kTagInfoLayer), "CCLabelTTF") + local strNode = nQuantityOfNodes.." nodes" + pInfoLabel:setString(strNode) + nLastRenderedCount = nQuantityOfNodes + end + end + + local function IterateSpriteSheetCArrayUpdate(t) + if nil == pBatchNode then + return + end + local pChildren = pBatchNode:getChildren() + local pObject = nil + if nil == pChildren then + return + end + local i = 0 + local len = pChildren:count() + for i = 0, len - 1, 1 do + local child = tolua.cast(pChildren:objectAtIndex(i), "CCSprite") + child:setVisible(false) + end + end + + local function AddSpriteSheetUpdate(t) + if nil == pBatchNode then + return + end + + --15 percent + local nTotalToAdd = nCurrentQuantityOfNodes * 0.15 + local zs = {} + if nTotalToAdd > 0 then + local pSprites = CCArray:createWithCapacity(nTotalToAdd) + local i = 0 + for i = 0 , nTotalToAdd - 1 do + local pSprite = CCSprite:createWithTexture(pBatchNode:getTexture(), CCRectMake(0,0,32,32)) + pSprites:addObject(pSprite) + zs[i] = math.random(-1,1) * 50 + end + + for i = 0 , nTotalToAdd - 1 do + local pChild = tolua.cast(pSprites:objectAtIndex(i),"CCNode") + pBatchNode:addChild(pChild, zs[i], NodeChildrenTestParam.kTagBase + i) + end + + pBatchNode:sortAllChildren() + + for i = 0 , nTotalToAdd - 1 do + pBatchNode:removeChildByTag( NodeChildrenTestParam.kTagBase + i, true) + end + end + end + + local function RemoveSpriteSheetUpdate(t) + if nil == pBatchNode then + return + end + local nTotalToAdd = nCurrentQuantityOfNodes * 0.15 + if nTotalToAdd > 0 then + local pSprites = CCArray:createWithCapacity(nTotalToAdd) + + -- Don't include the sprite creation time as part of the profiling + local i = 0 + for i = 0, nTotalToAdd - 1 do + local pSprite = CCSprite:createWithTexture(pBatchNode:getTexture(), CCRectMake(0,0,32,32)) + pSprites:addObject(pSprite) + end + -- add them with random Z (very important!) + for i=0, nTotalToAdd - 1 do + local pChild = tolua.cast(pSprites:objectAtIndex(i),"CCNode") + pBatchNode:addChild(pChild, math.random(-1,1) * 50, NodeChildrenTestParam.kTagBase + i) + end + + for i = 0, nTotalToAdd - 1 do + pBatchNode:removeChildByTag( NodeChildrenTestParam.kTagBase + i, true) + end + end + end + + local function ReorderSpriteSheetUpdate(t) + if nil == pBatchNode then + return + end + -- 15 percent + local nTotalToAdd = nCurrentQuantityOfNodes * 0.15 + + if nTotalToAdd > 0 then + local pSprites = CCArray:createWithCapacity(nTotalToAdd) + + -- Don't include the sprite creation time as part of the profiling + local i = 0 + for i = 0,nTotalToAdd - 1 do + local pSprite = CCSprite:createWithTexture(pBatchNode:getTexture(), CCRectMake(0,0,32,32)) + pSprites:addObject(pSprite) + end + + --dd them with random Z (very important!) + for i = 0, nTotalToAdd - 1 do + local pChild = tolua.cast(pSprites:objectAtIndex(i),"CCNode") + pBatchNode:addChild(pChild, math.random(-1,1) * 50, NodeChildrenTestParam.kTagBase + i) + end + + pBatchNode:sortAllChildren() + + -- reorder them + for i = 0, nTotalToAdd - 1 do + local pNode = tolua.cast(pBatchNode:getChildren():objectAtIndex(i),"CCNode") + pBatchNode:reorderChild(pNode, math.random(-1,1) * 50) + end + pBatchNode:sortAllChildren() + --remove them + for i = 0, nTotalToAdd - 1 do + pBatchNode:removeChildByTag( NodeChildrenTestParam.kTagBase+i, true) + end + end + end + + local function NodeChildrenScheduleUpdate() + if 0 == nCurCase then + pNewscene:scheduleUpdateWithPriorityLua(IterateSpriteSheetCArrayUpdate,0) + elseif 1 == nCurCase then + pNewscene:scheduleUpdateWithPriorityLua(AddSpriteSheetUpdate,0) + elseif 2 == nCurCase then + pNewscene:scheduleUpdateWithPriorityLua(RemoveSpriteSheetUpdate,0) + elseif 3 == nCurCase then + pNewscene:scheduleUpdateWithPriorityLua(ReorderSpriteSheetUpdate,0) + end + end + + local function updateQuantityOfNodes() + local s = CCDirector:sharedDirector():getWinSize() + --increase nodes + if( nCurrentQuantityOfNodes < nQuantityOfNodes ) then + local i = 0 + for i = 0,nQuantityOfNodes - nCurrentQuantityOfNodes - 1 do + local sprite = CCSprite:createWithTexture(pBatchNode:getTexture(), CCRectMake(0, 0, 32, 32)) + pBatchNode:addChild(sprite) + sprite:setPosition(ccp( math.random() * s.width, math.random() * s.height)) + if 0 ~= nCurCase then + sprite:setVisible(false) + end + end + elseif (nCurrentQuantityOfNodes > nQuantityOfNodes ) then + i = 0 + for i = 0, nCurrentQuantityOfNodes - nQuantityOfNodes - 1 do + local index = nCurrentQuantityOfNodes - i - 1 + pBatchNode:removeChildAtIndex(index, true) + end + end + + + nCurrentQuantityOfNodes = nQuantityOfNodes + end + + local function onDecrease() + nQuantityOfNodes = nQuantityOfNodes - NodeChildrenTestParam.kNodesIncrease + if nQuantityOfNodes < 0 then + nQuantityOfNodes = 0 + end + + updateQuantityLabel() + updateQuantityOfNodes() + end + + local function onIncrease() + nQuantityOfNodes = nQuantityOfNodes + NodeChildrenTestParam.kNodesIncrease + if nQuantityOfNodes > NodeChildrenTestParam.kMaxNodes then + nQuantityOfNodes = NodeChildrenTestParam.kMaxNodes + end + + updateQuantityLabel() + updateQuantityOfNodes() + end + + + local function SpecialInitWithQuantityOfNodes() + -- if 0 == nCurCase then + pBatchNode = CCSpriteBatchNode:create("Images/spritesheet1.png") + pNewscene:addChild(pBatchNode) + --[[ + else + pBatchNode = CCSpriteBatchNode:create("Images/spritesheet1.png") + pNewscene:addChild(pBatchNode) + end + ]]-- + end + + local function MainSceneInitWithQuantityOfNodes(nNodes) + local s = CCDirector:sharedDirector():getWinSize() + + --Title + local pLabel = CCLabelTTF:create(GetTitle(), "Arial", 40) + pNewscene:addChild(pLabel, 1) + pLabel:setPosition(ccp(s.width/2, s.height-32)) + pLabel:setColor(ccc3(255,255,40)) + + if (nil ~= GetSubTitle()) and ("" ~= GetSubTitle()) then + local pSubLabel = CCLabelTTF:create(GetSubTitle(), "Thonburi", 16) + pNewscene:addChild(pSubLabel, 1) + pSubLabel:setPosition(ccp(s.width/2, s.height-80)) + end + + nLastRenderedCount = 0 + nCurrentQuantityOfNodes = 0 + nQuantityOfNodes = nNodes + + --"+","-" Menu + CCMenuItemFont:setFontSize(65) + local pDecrease = CCMenuItemFont:create(" - ") + pDecrease:registerScriptTapHandler(onDecrease) + pDecrease:setColor(ccc3(0,200,20)) + local pIncrease = CCMenuItemFont:create(" + ") + pIncrease:registerScriptTapHandler(onIncrease) + pIncrease:setColor(ccc3(0,200,20)) + + local pMenuAddOrSub = CCMenu:create() + pMenuAddOrSub:addChild(pDecrease) + pMenuAddOrSub:addChild(pIncrease) + pMenuAddOrSub:alignItemsHorizontally() + pMenuAddOrSub:setPosition(ccp(s.width/2, s.height/2+15)) + pNewscene:addChild(pMenuAddOrSub,1) + + --InfoLayer + local pInfoLabel = CCLabelTTF:create("0 nodes", "Marker Felt", 30) + pInfoLabel:setColor(ccc3(0,200,20)) + pInfoLabel:setPosition(ccp(s.width/2, s.height/2-15)) + pNewscene:addChild(pInfoLabel, 1, NodeChildrenTestParam.kTagInfoLayer) + + --NodeChildrenMenuLayer + local pNodeChildrenMenuLayer = CCLayer:create() + local pNodeChildrenMenuMenu = CCMenu:create() + CreatePerfomBasicLayerMenu(pNodeChildrenMenuMenu) + CreateBasicLayerMenuItem(pNodeChildrenMenuMenu,true,NodeChildrenTestParam.TEST_COUNT,nCurCase) + pNodeChildrenMenuMenu:setPosition(ccp(0, 0)) + pNodeChildrenMenuLayer:addChild(pNodeChildrenMenuMenu) + pNewscene:addChild(pNodeChildrenMenuLayer) + + updateQuantityLabel() + updateQuantityOfNodes() + + end + + function ShowCurrentTest() + if nil ~= pNewscene then + pNewscene:unscheduleUpdate() + end + + pNewscene = CCScene:create() + if nil ~= pNewscene then + SpecialInitWithQuantityOfNodes() + MainSceneInitWithQuantityOfNodes(nQuantityOfNodes) +-- pNewscene:registerScriptHandler(onNodeEvent) + NodeChildrenScheduleUpdate() + CCDirector:sharedDirector():replaceScene(pNewscene) + end + end + + SpecialInitWithQuantityOfNodes() + MainSceneInitWithQuantityOfNodes(NodeChildrenTestParam.kNodesIncrease) +-- pNewscene:registerScriptHandler(onNodeEvent) + NodeChildrenScheduleUpdate() + + return pNewscene +end +---------------------------------- +--PerformanceParticleTest +---------------------------------- +local ParticleTestParam = +{ + kTagInfoLayer = 1, + kTagMainLayer = 2, + kTagParticleSystem = 3, + kTagLabelAtlas = 4, + kTagMenuLayer = 1000, + + TEST_COUNT = 4, + kMaxParticles = 14000, + kNodesIncrease = 500, + + kSubMenuBasicZOrder = 10 +} + +local function runParticleTest() + --PerformanceParticle param + local nLastRenderedCount = 0 + local nQuantityParticles = 0 + local nSubtestNumber = 0 + --BasiceLayer param + local bControlMenuVisible = false + local nMaxCases = 0 + local nCurCase = 0 + + local ScheduleSelector = nil + + local pNewScene = CCScene:create() + + local function GetTitle() + local strTitle = nil + if 0 == nCurCase then + strTitle = string.format("A (%d) size=4",nSubtestNumber) + elseif 1 == nCurCase then + strTitle = string.format("B (%d) size=8",nSubtestNumber) + elseif 2 == nCurCase then + strTitle = string.format("C (%d) size=32",nSubtestNumber) + elseif 3 == nCurCase then + strTitle = string.format("D (%d) size=64",nSubtestNumber) + end + return strTitle + end + + local function CreateBasicLayerMenuItem(pMenu,bMenuVisible,nMaxCasesNum,nCurCaseIndex) + if nil ~= pMenu then + bControlMenuVisible = bMenuVisible + nMaxCases = nMaxCasesNum + nCurCase = nCurCaseIndex + if true == bControlMenuVisible then + local function backCallback() + nCurCase = nCurCase - 1 + if nCurCase < 0 then + nCurCase = nCurCase + nMaxCases + end + ShowCurrentTest() + end + + local function restartCallback() + ShowCurrentTest() + end + + local function nextCallback() + nCurCase = nCurCase + 1 + --No check nMaxCases + nCurCase = nCurCase % nMaxCases + ShowCurrentTest() + end + + local size = CCDirector:sharedDirector():getWinSize() + local item1 = CCMenuItemImage:create(s_pPathB1, s_pPathB2) + item1:registerScriptTapHandler(backCallback) + pMenu:addChild(item1,kItemTagBasic) + local item2 = CCMenuItemImage:create(s_pPathR1, s_pPathR2) + item2:registerScriptTapHandler(restartCallback) + pMenu:addChild(item2,kItemTagBasic) + local item3 = CCMenuItemImage:create(s_pPathF1, s_pPathF2) + pMenu:addChild(item3,kItemTagBasic) + item3:registerScriptTapHandler(nextCallback) + + local size = CCDirector:sharedDirector():getWinSize() + item1:setPosition(CCPointMake(size.width / 2 - item2:getContentSize().width * 2, item2:getContentSize().height / 2)) + item2:setPosition(CCPointMake(size.width / 2, item2:getContentSize().height / 2)) + item3:setPosition(CCPointMake(size.width / 2 + item2:getContentSize().width * 2, item2:getContentSize().height / 2)) + end + end + end + + local function TestNCallback(tag,pMenuItem) + local nIndex = pMenuItem:getZOrder() - ParticleTestParam.kSubMenuBasicZOrder + nSubtestNumber = nIndex + ShowCurrentTest() + end + + local function UpdateQuantityLabel() + if nQuantityParticles ~= nLastRenderedCount then + local pInfoLabel = tolua.cast(pNewScene:getChildByTag(ParticleTestParam.kTagInfoLayer), "CCLabelTTF") + local strInfo = string.format("%u particles", nQuantityParticles) + pInfoLabel:setString(strInfo) + + nLastRenderedCount = nQuantityParticles + end + end + + local function doTest() + local s = CCDirector:sharedDirector():getWinSize() + local pParticleSystem = tolua.cast(pNewScene:getChildByTag(ParticleTestParam.kTagParticleSystem),"CCParticleSystem") + if nil == pParticleSystem then + return + end + if 0 == nCurCase then + --duration + pParticleSystem:setDuration(-1) + + --gravity + pParticleSystem:setGravity(ccp(0,-90)) + + --angle + pParticleSystem:setAngle(90) + pParticleSystem:setAngleVar(0) + + --radial + pParticleSystem:setRadialAccel(0) + pParticleSystem:setRadialAccelVar(0) + + -- speed of particles + pParticleSystem:setSpeed(180) + pParticleSystem:setSpeedVar(50) + + -- emitter position + pParticleSystem:setPosition(ccp(s.width/2, 100)) + pParticleSystem:setPosVar(ccp(s.width/2,0)) + + -- life of particles + pParticleSystem:setLife(2.0) + pParticleSystem:setLifeVar(1) + + --emits per frame + pParticleSystem:setEmissionRate(pParticleSystem:getTotalParticles() / pParticleSystem:getLife()) + + --color of particles + pParticleSystem:setStartColor(ccc4f(0.5, 0.5, 0.5, 1.0)) + + pParticleSystem:setStartColorVar( ccc4f(0.5, 0.5, 0.5, 1.0)) + + pParticleSystem:setEndColor(ccc4f(0.1, 0.1, 0.1, 0.2)) + + pParticleSystem:setEndColorVar(ccc4f(0.1, 0.1, 0.1, 0.2)) + + -- size, in pixels + pParticleSystem:setEndSize(4.0) + pParticleSystem:setStartSize(4.0) + pParticleSystem:setEndSizeVar(0) + pParticleSystem:setStartSizeVar(0) + + -- additive + pParticleSystem:setBlendAdditive(false) + + elseif 1 == nCurCase then + --duration + pParticleSystem:setDuration(-1) + + --gravity + pParticleSystem:setGravity(ccp(0,-90)) + + --angle + pParticleSystem:setAngle(90) + pParticleSystem:setAngleVar(0) + + --radial + pParticleSystem:setRadialAccel(0) + pParticleSystem:setRadialAccelVar(0) + + -- speed of particles + pParticleSystem:setSpeed(180) + pParticleSystem:setSpeedVar(50) + + -- emitter position + pParticleSystem:setPosition(ccp(s.width/2, 100)) + pParticleSystem:setPosVar(ccp(s.width/2,0)) + + -- life of particles + pParticleSystem:setLife(2.0) + pParticleSystem:setLifeVar(1) + + --emits per frame + pParticleSystem:setEmissionRate(pParticleSystem:getTotalParticles() / pParticleSystem:getLife()) + + --color of particles + pParticleSystem:setStartColor(ccc4f(0.5, 0.5, 0.5, 1.0)) + + pParticleSystem:setStartColorVar( ccc4f(0.5, 0.5, 0.5, 1.0)) + + pParticleSystem:setEndColor(ccc4f(0.1, 0.1, 0.1, 0.2)) + + pParticleSystem:setEndColorVar(ccc4f(0.1, 0.1, 0.1, 0.2)) + + -- size, in pixels + pParticleSystem:setEndSize(8.0) + pParticleSystem:setStartSize(8.0) + pParticleSystem:setEndSizeVar(0) + pParticleSystem:setStartSizeVar(0) + + -- additive + pParticleSystem:setBlendAdditive(false) + elseif 2 == nCurCase then + --duration + pParticleSystem:setDuration(-1) + + --gravity + pParticleSystem:setGravity(ccp(0,-90)) + + --angle + pParticleSystem:setAngle(90) + pParticleSystem:setAngleVar(0) + + --radial + pParticleSystem:setRadialAccel(0) + pParticleSystem:setRadialAccelVar(0) + + -- speed of particles + pParticleSystem:setSpeed(180) + pParticleSystem:setSpeedVar(50) + + -- emitter position + pParticleSystem:setPosition(ccp(s.width/2, 100)) + pParticleSystem:setPosVar(ccp(s.width/2,0)) + + -- life of particles + pParticleSystem:setLife(2.0) + pParticleSystem:setLifeVar(1) + + --emits per frame + pParticleSystem:setEmissionRate(pParticleSystem:getTotalParticles() / pParticleSystem:getLife()) + + --color of particles + pParticleSystem:setStartColor(ccc4f(0.5, 0.5, 0.5, 1.0)) + + pParticleSystem:setStartColorVar( ccc4f(0.5, 0.5, 0.5, 1.0)) + + pParticleSystem:setEndColor(ccc4f(0.1, 0.1, 0.1, 0.2)) + + pParticleSystem:setEndColorVar(ccc4f(0.1, 0.1, 0.1, 0.2)) + + -- size, in pixels + pParticleSystem:setEndSize(32.0) + pParticleSystem:setStartSize(32.0) + pParticleSystem:setEndSizeVar(0) + pParticleSystem:setStartSizeVar(0) + + -- additive + pParticleSystem:setBlendAdditive(false) + elseif 3 == nCurCase then + --duration + pParticleSystem:setDuration(-1) + + --gravity + pParticleSystem:setGravity(ccp(0,-90)) + + --angle + pParticleSystem:setAngle(90) + pParticleSystem:setAngleVar(0) + + --radial + pParticleSystem:setRadialAccel(0) + pParticleSystem:setRadialAccelVar(0) + + -- speed of particles + pParticleSystem:setSpeed(180) + pParticleSystem:setSpeedVar(50) + + -- emitter position + pParticleSystem:setPosition(ccp(s.width/2, 100)) + pParticleSystem:setPosVar(ccp(s.width/2,0)) + + -- life of particles + pParticleSystem:setLife(2.0) + pParticleSystem:setLifeVar(1) + + --emits per frame + pParticleSystem:setEmissionRate(pParticleSystem:getTotalParticles() / pParticleSystem:getLife()) + + --color of particles + pParticleSystem:setStartColor(ccc4f(0.5, 0.5, 0.5, 1.0)) + + pParticleSystem:setStartColorVar( ccc4f(0.5, 0.5, 0.5, 1.0)) + + pParticleSystem:setEndColor(ccc4f(0.1, 0.1, 0.1, 0.2)) + + pParticleSystem:setEndColorVar(ccc4f(0.1, 0.1, 0.1, 0.2)) + + -- size, in pixels + pParticleSystem:setEndSize(64.0) + pParticleSystem:setStartSize(64.0) + pParticleSystem:setEndSizeVar(0) + pParticleSystem:setStartSizeVar(0) + + -- additive + pParticleSystem:setBlendAdditive(false) + end + end + + local function CreateParticleSystem() + local pParticleSystem = nil + --[[ + * Tests: + * 1: Point Particle System using 32-bit textures (PNG) + * 2: Point Particle System using 16-bit textures (PNG) + * 3: Point Particle System using 8-bit textures (PNG) + * 4: Point Particle System using 4-bit textures (PVRTC) + + * 5: Quad Particle System using 32-bit textures (PNG) + * 6: Quad Particle System using 16-bit textures (PNG) + * 7: Quad Particle System using 8-bit textures (PNG) + * 8: Quad Particle System using 4-bit textures (PVRTC) + ]]-- + pNewScene:removeChildByTag(ParticleTestParam.kTagParticleSystem, true) + + --remove the "fire.png" from the TextureCache cache. + local pTexture = CCTextureCache:sharedTextureCache():addImage("Images/fire.png") + CCTextureCache:sharedTextureCache():removeTexture(pTexture) + local pParticleSystem = CCParticleSystemQuad:new() + if 1 == nSubtestNumber then + CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA8888) + elseif 2 == nSubtestNumber then + CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA4444) + elseif 3 == nSubtestNumber then + CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_A8) + elseif 4 == nSubtestNumber then + CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA8888) + elseif 5 == nSubtestNumber then + CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA4444) + elseif 6 == nSubtestNumber then + CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_A8) + else + pParticleSystem = nil + print("Shall not happen!") + end + + if nil ~= pParticleSystem then + pParticleSystem:initWithTotalParticles(nQuantityParticles) + pParticleSystem:setTexture(CCTextureCache:sharedTextureCache():addImage("Images/fire.png")) + end + + pNewScene:addChild(pParticleSystem, 0, ParticleTestParam.kTagParticleSystem) + + doTest() + --restore the default pixel format + CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA8888) + end + + local function step(t) + local pAtlas = tolua.cast(pNewScene:getChildByTag(ParticleTestParam.kTagLabelAtlas),"CCLabelAtlas") + local pEmitter = tolua.cast(pNewScene:getChildByTag(ParticleTestParam.kTagParticleSystem),"CCParticleSystem") + local strInfo = string.format("%4d",pEmitter:getParticleCount()) + pAtlas:setString(strInfo) + end + + local function ScheduleFuncion() + local function OnEnterOrExit(tag) + local scheduler = CCDirector:sharedDirector():getScheduler() + if tag == "enter" then + ScheduleSelector = scheduler:scheduleScriptFunc(step,0,false) + elseif tag == "exit" then + scheduler:unscheduleScriptEntry(ScheduleSelector) + end + end + pNewScene:registerScriptHandler(OnEnterOrExit) + end + + local function onDecrease() + nQuantityParticles = nQuantityParticles - ParticleTestParam.kNodesIncrease + if nQuantityParticles < 0 then + nQuantityParticles = 0 + end + + UpdateQuantityLabel() + CreateParticleSystem() + end + + local function onIncrease() + nQuantityParticles = nQuantityParticles + ParticleTestParam.kNodesIncrease + if nQuantityParticles > ParticleTestParam.kMaxParticles then + nQuantityParticles = ParticleTestParam.kMaxParticles + end + + UpdateQuantityLabel() + CreateParticleSystem() + end + + local function InitWithSubTest(nSubtest,nParticles) + nSubtestNumber = nSubtest + local s = CCDirector:sharedDirector():getWinSize() + + nLastRenderedCount = 0 + nQuantityParticles = nParticles + + --"+","-" Menu + CCMenuItemFont:setFontSize(65) + local pDecrease = CCMenuItemFont:create(" - ") + pDecrease:registerScriptTapHandler(onDecrease) + pDecrease:setColor(ccc3(0,200,20)) + local pIncrease = CCMenuItemFont:create(" + ") + pIncrease:registerScriptTapHandler(onIncrease) + pIncrease:setColor(ccc3(0,200,20)) + + local pMenuAddOrSub = CCMenu:create() + pMenuAddOrSub:addChild(pDecrease) + pMenuAddOrSub:addChild(pIncrease) + pMenuAddOrSub:alignItemsHorizontally() + pMenuAddOrSub:setPosition(ccp(s.width/2, s.height/2+15)) + pNewScene:addChild(pMenuAddOrSub,1) + + local pInfoLabel = CCLabelTTF:create("0 nodes", "Marker Felt", 30) + pInfoLabel:setColor(ccc3(0,200,20)) + pInfoLabel:setPosition(ccp(s.width/2, s.height - 90)) + pNewScene:addChild(pInfoLabel, 1, ParticleTestParam.kTagInfoLayer) + + --particles on stage + local pLabelAtlas = CCLabelAtlas:create("0000", "fps_images.png", 12, 32, string.byte('.')) + pNewScene:addChild(pLabelAtlas, 0, ParticleTestParam.kTagLabelAtlas) + pLabelAtlas:setPosition(ccp(s.width-66,50)) + + --ParticleTestMenuLayer + local pParticleMenuLayer = CCLayer:create() + local pParticleMenu = CCMenu:create() + CreatePerfomBasicLayerMenu(pParticleMenu) + CreateBasicLayerMenuItem(pParticleMenu,true,ParticleTestParam.TEST_COUNT,nCurCase) + pParticleMenu:setPosition(ccp(0, 0)) + pParticleMenuLayer:addChild(pParticleMenu) + pNewScene:addChild(pParticleMenuLayer) + + --Sub Tests + CCMenuItemFont:setFontSize(40) + local pSubMenu = CCMenu:create() + local i = 1 + for i = 1, 6 do + local strNum = string.format("%d ",i) + local pItemFont = CCMenuItemFont:create(strNum) + pItemFont:registerScriptTapHandler(TestNCallback) + pSubMenu:addChild(pItemFont, i + ParticleTestParam.kSubMenuBasicZOrder) + if i <= 3 then + pItemFont:setColor(ccc3(200,20,20)) + else + pItemFont:setColor(ccc3(0,200,20)) + end + end + pSubMenu:alignItemsHorizontally() + pSubMenu:setPosition(ccp(s.width/2, 80)) + pNewScene:addChild(pSubMenu, 2) + + local pLabel = CCLabelTTF:create(GetTitle(), "Arial", 40) + pNewScene:addChild(pLabel, 1) + pLabel:setPosition(ccp(s.width/2, s.height-32)) + pLabel:setColor(ccc3(255,255,40)) + + UpdateQuantityLabel() + CreateParticleSystem() + ScheduleFuncion() + end + + function ShowCurrentTest() + if nil ~= pNewScene then + CCDirector:sharedDirector():getScheduler():unscheduleScriptEntry(ScheduleSelector) + end + pNewScene = CCScene:create() + InitWithSubTest(nSubtestNumber,nQuantityParticles) + CCDirector:sharedDirector():replaceScene(pNewScene) + end + + + InitWithSubTest(1,ParticleTestParam.kNodesIncrease) + return pNewScene +end + +---------------------------------- +--PerformanceSpriteTest +---------------------------------- +local SpriteTestParam = +{ + kMaxNodes = 50000, + kNodesIncrease = 250, + TEST_COUNT = 7, + + kTagInfoLayer = 1, + kTagMainLayer = 2, + -- 50000 -- kMaxNodes + kTagMenuLayer = 50000 + 1000, + kInitNodes = 50, + kSubMenuBasicZOrder = 20, + + kRandMax = 32767 +} + +local function runSpriteTest() + --PerformanceParticle param + local nLastRenderedCount = 0 + local nQuantityNodes = 0 + local nSubtestNumber = 0 + --BasiceLayer param + local bControlMenuVisible = false + local nMaxCases = 0 + local nCurCase = 0 + + local ScheduleSelector = nil + + --SubTest + local pBatchNode = nil + + local function GetTitle() + local strTitle = nil + if 0 == nCurCase then + strTitle = string.format("A (%d) position",nSubtestNumber) + elseif 1 == nCurCase then + strTitle = string.format("B (%d) scale",nSubtestNumber) + elseif 2 == nCurCase then + strTitle = string.format("C (%d) scale + rot",nSubtestNumber) + elseif 3 == nCurCase then + strTitle = string.format("D (%d) 100%% out",nSubtestNumber) + elseif 4 == nCurCase then + strTitle = string.format("E (%d) 80%% out",nSubtestNumber) + elseif 5 == nCurCase then + strTitle = string.format("F (%d) actions",nSubtestNumber) + elseif 6 == nCurCase then + strTitle = string.format("G (%d) actions 80%% out",nSubtestNumber) + end + + return strTitle + end + + local pNewScene = CCScene:create() + + local function CreateBasicLayerMenuItem(pMenu,bMenuVisible,nMaxCasesNum,nCurCaseIndex) + if nil ~= pMenu then + bControlMenuVisible = bMenuVisible + nMaxCases = nMaxCasesNum + nCurCase = nCurCaseIndex + if true == bControlMenuVisible then + local function backCallback() + nCurCase = nCurCase - 1 + if nCurCase < 0 then + nCurCase = nCurCase + nMaxCases + end + ShowCurrentTest() + end + + local function restartCallback() + ShowCurrentTest() + end + + local function nextCallback() + nCurCase = nCurCase + 1 + --No check nMaxCases + nCurCase = nCurCase % nMaxCases + ShowCurrentTest() + end + + local size = CCDirector:sharedDirector():getWinSize() + local item1 = CCMenuItemImage:create(s_pPathB1, s_pPathB2) + item1:registerScriptTapHandler(backCallback) + pMenu:addChild(item1,kItemTagBasic) + local item2 = CCMenuItemImage:create(s_pPathR1, s_pPathR2) + item2:registerScriptTapHandler(restartCallback) + pMenu:addChild(item2,kItemTagBasic) + local item3 = CCMenuItemImage:create(s_pPathF1, s_pPathF2) + pMenu:addChild(item3,kItemTagBasic) + item3:registerScriptTapHandler(nextCallback) + + local size = CCDirector:sharedDirector():getWinSize() + item1:setPosition(CCPointMake(size.width / 2 - item2:getContentSize().width * 2, item2:getContentSize().height / 2)) + item2:setPosition(CCPointMake(size.width / 2, item2:getContentSize().height / 2)) + item3:setPosition(CCPointMake(size.width / 2 + item2:getContentSize().width * 2, item2:getContentSize().height / 2)) + end + end + end + + local function UpdateNodes() + if nQuantityNodes ~= nLastRenderedCount then + local pInfoLabel = tolua.cast(pNewScene:getChildByTag(SpriteTestParam.kTagInfoLayer), "CCLabelTTF") + local strInfo = string.format("%u nodes", nQuantityNodes) + pInfoLabel:setString(strInfo) + nLastRenderedCount = nQuantityNodes + end + end + + local function PerformancePosition(pSprite) + local size = CCDirector:sharedDirector():getWinSize() + pSprite:setPosition(ccp((math.random(0,SpriteTestParam.kRandMax) % (size.width) ), (math.random(0,SpriteTestParam.kRandMax) % (size.height)))) + end + + local function PerformanceScale(pSprite) + local size = CCDirector:sharedDirector():getWinSize() + pSprite:setPosition(ccp((math.random(0,SpriteTestParam.kRandMax) % (size.width) ), (math.random(0,SpriteTestParam.kRandMax) % (size.height)))) + pSprite:setScale(math.random() * 100 / 50) + end + + local function PerformanceRotationScale(pSprite) + local size = CCDirector:sharedDirector():getWinSize() + pSprite:setPosition(ccp((math.random(0,SpriteTestParam.kRandMax) % (size.width) ), (math.random(0,SpriteTestParam.kRandMax) % (size.height)))) + pSprite:setRotation(math.random() * 360) + pSprite:setScale(math.random() * 2) + end + + local function PerformanceOut100(pSprite) + pSprite:setPosition(ccp( -1000, -1000)) + end + + local function Performanceout20(pSprite) + local size = CCDirector:sharedDirector():getWinSize() + + if math.random() < 0.2 then + pSprite:setPosition(ccp((math.random(0,SpriteTestParam.kRandMax) % (size.width) ), (math.random(0,SpriteTestParam.kRandMax) % (size.height)))) + else + pSprite:setPosition(ccp( -1000, -1000)) + end + end + + local function PerformanceActions(pSprite) + local size = CCDirector:sharedDirector():getWinSize() + pSprite:setPosition(ccp((math.random(0,SpriteTestParam.kRandMax) % (size.width) ), (math.random(0,SpriteTestParam.kRandMax) % (size.height)))) + + local fPeriod = 0.5 + (math.random(0,SpriteTestParam.kRandMax) % 1000) / 500.0 + local pRot = CCRotateBy:create(fPeriod, 360.0 * math.random() ) + local pRot_back = pRot:reverse() + local arrRot = CCArray:create() + arrRot:addObject(pRot) + arrRot:addObject(pRot_back) + local pPermanentRotation = CCRepeatForever:create(CCSequence:create(arrRot)) + pSprite:runAction(pPermanentRotation) + + local fGrowDuration = 0.5 + (math.random(0,SpriteTestParam.kRandMax) % 1000) / 500.0 + local pGrow = CCScaleBy:create(fGrowDuration, 0.5, 0.5) + local arrGrow = CCArray:create() + arrGrow:addObject(pGrow) + arrGrow:addObject(pGrow:reverse()) + local pPermanentScaleLoop = CCRepeatForever:create(CCSequence:create(arrGrow)) + pSprite:runAction(pPermanentScaleLoop) + end + + local function PerformanceActions20(pSprite) + local size = CCDirector:sharedDirector():getWinSize() + + if math.random() < 0.2 then + pSprite:setPosition(ccp((math.random(0,SpriteTestParam.kRandMax) % (size.width) ), (math.random(0,SpriteTestParam.kRandMax) % (size.height)))) + else + pSprite:setPosition(ccp( -1000, -1000)) + end + + local pPeriod = 0.5 + (math.random(0,SpriteTestParam.kRandMax) % 1000) / 500.0 + local pRot = CCRotateBy:create(pPeriod, 360.0 * math.random()) + local pRot_back = pRot:reverse() + local arrRot = CCArray:create() + arrRot:addObject(pRot) + arrRot:addObject(pRot_back) + local pPermanentRotation = CCRepeatForever:create(CCSequence:create(arrRot)) + pSprite:runAction(pPermanentRotation) + + + local fGrowDuration = 0.5 + (math.random(0,SpriteTestParam.kRandMax) % 1000) / 500.0 + local pGrow = CCScaleBy:create(fGrowDuration, 0.5, 0.5) + local pPermanentScaleLoop = CCRepeatForever:create(CCSequence:createWithTwoActions(pGrow, pGrow:reverse())) + pSprite:runAction(pPermanentScaleLoop) + + end + + local function CreateSpriteWithTag(nTag) + --create + CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA8888) + local pSprite = nil + if 1 == nSubtestNumber then + pSprite = CCSprite:create("Images/grossinis_sister1.png") + pNewScene:addChild(pSprite, 0, nTag+100) + elseif 2 == nSubtestNumber or 3 == nSubtestNumber then + pSprite = CCSprite:createWithTexture(pBatchNode:getTexture(), CCRectMake(0, 0, 52, 139)) + pBatchNode:addChild(pSprite, 0, nTag+100) + elseif 4 == nSubtestNumber then + local nIndex = math.floor((math.random() * 1400 / 100)) + 1 + local strPath = string.format("Images/grossini_dance_%02d.png", nIndex) + pSprite = CCSprite:create(strPath) + pNewScene:addChild(pSprite, 0, nTag+100) + elseif 5 == nSubtestNumber or 6 == nSubtestNumber then + local nY = 0 + local nX = 0 + local nR = math.floor(math.random() * 1400 / 100) + + nX = nR % 5 + nY = math.floor(nR / 5) + + nX = nX * 85 + nY = nY * 121 + pSprite = CCSprite:createWithTexture(pBatchNode:getTexture(), CCRectMake(nX,nY,85,121)) + pBatchNode:addChild(pSprite, 0, nTag+100) + elseif 7 == nSubtestNumber then + local nX = 0 + local nY = 0 + local nR = math.floor(math.random() * 6400 / 100) + + nX = nR % 8 + nY = math.floor(nR / 8) + + local strPath = string.format("Images/sprites_test/sprite-%d-%d.png", nX, nY) + pSprite = CCSprite:create(strPath) + pNewScene:addChild(pSprite, 0, nTag+100) + elseif 8 == nSubtestNumber or 9 == nSubtestNumber then + local nX = 0 + local nY = 0 + local nR = math.floor(math.random() * 6400 / 100) + + nX = nR % 8 + nY = math.floor(nR / 8) + + nX = nX * 32 + nY = nY * 32 + pSprite = CCSprite:createWithTexture(pBatchNode:getTexture(), CCRectMake(nX,nY,32,32)) + pBatchNode:addChild(pSprite, 0, nTag+100) + end + CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_Default) + + return pSprite + end + + local function RemoveByTag(nTag) + if 1 == nSubtestNumber or 4 == nSubtestNumber or 7 == nSubtestNumber then + pNewScene:removeChildByTag(nTag + 100, true) + elseif 2 == nSubtestNumber or 3 == nSubtestNumber or 5 == nSubtestNumber or 6 == nSubtestNumber or 8 == nSubtestNumber or 9 == nSubtestNumber then + pBatchNode:removeChildAtIndex(nTag,true) + end + + end + + local function DoTest(pSprite) + if 0 == nCurCase then + PerformancePosition(pSprite) + elseif 1 == nCurCase then + PerformanceScale(pSprite) + elseif 2 == nCurCase then + PerformanceRotationScale(pSprite) + elseif 3 == nCurCase then + PerformanceOut100(pSprite) + elseif 4 == nCurCase then + Performanceout20(pSprite) + elseif 5 == nCurCase then + PerformanceActions(pSprite) + elseif 6 == nCurCase then + PerformanceActions20(pSprite) + end + end + + local function onDecrease() + if nQuantityNodes <= 0 then + return + end + + local i = 0 + for i = 0 , SpriteTestParam.kNodesIncrease - 1 do + nQuantityNodes = nQuantityNodes - 1 + RemoveByTag(nQuantityNodes) + end + UpdateNodes() + end + + local function onIncrease() + if nQuantityNodes >= SpriteTestParam.kMaxNodes then + return + end + + local i = 0 + for i = 0,SpriteTestParam.kNodesIncrease - 1 do + local pSprite = CreateSpriteWithTag(nQuantityNodes) + DoTest(pSprite) + nQuantityNodes = nQuantityNodes + 1 + end + UpdateNodes() + end + + local function TestNCallback(tag,pMenuItem) + local nIndex = pMenuItem:getZOrder() - SpriteTestParam.kSubMenuBasicZOrder + nSubtestNumber = nIndex + ShowCurrentTest() + end + + local function InitWithSubTest(nSubTest) + pBatchNode = nil + --[[ + * Tests: + * 1: 1 (32-bit) PNG sprite of 52 x 139 + * 2: 1 (32-bit) PNG Batch Node using 1 sprite of 52 x 139 + * 3: 1 (16-bit) PNG Batch Node using 1 sprite of 52 x 139 + * 4: 1 (4-bit) PVRTC Batch Node using 1 sprite of 52 x 139 + + * 5: 14 (32-bit) PNG sprites of 85 x 121 each + * 6: 14 (32-bit) PNG Batch Node of 85 x 121 each + * 7: 14 (16-bit) PNG Batch Node of 85 x 121 each + * 8: 14 (4-bit) PVRTC Batch Node of 85 x 121 each + + * 9: 64 (32-bit) sprites of 32 x 32 each + *10: 64 (32-bit) PNG Batch Node of 32 x 32 each + *11: 64 (16-bit) PNG Batch Node of 32 x 32 each + *12: 64 (4-bit) PVRTC Batch Node of 32 x 32 each + ]]-- + --purge textures + local pMgr = CCTextureCache:sharedTextureCache() + --[mgr removeAllTextures] + pMgr:removeTexture(pMgr:addImage("Images/grossinis_sister1.png")) + pMgr:removeTexture(pMgr:addImage("Images/grossini_dance_atlas.png")) + pMgr:removeTexture(pMgr:addImage("Images/spritesheet1.png")) + + if 1 == nSubTest or 4 == nSubTest or 7 == nSubTest then + elseif 2 == nSubTest then + CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA8888) + pBatchNode = CCSpriteBatchNode:create("Images/grossinis_sister1.png", 100) + pNewScene:addChild(pBatchNode, 0) + elseif 3 == nSubTest then + CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA4444) + pBatchNode = CCSpriteBatchNode:create("Images/grossinis_sister1.png", 100) + pNewScene:addChild(pBatchNode, 0) + elseif 5 == nSubTest then + CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA8888) + pBatchNode = CCSpriteBatchNode:create("Images/grossini_dance_atlas.png", 100) + pNewScene:addChild(pBatchNode, 0) + elseif 6 == nSubTest then + CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA4444) + pBatchNode = CCSpriteBatchNode:create("Images/grossini_dance_atlas.png", 100) + pNewScene:addChild(pBatchNode, 0) + elseif 8 == nSubTest then + CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA8888) + pBatchNode = CCSpriteBatchNode:create("Images/spritesheet1.png", 100) + pNewScene:addChild(pBatchNode, 0) + elseif 9 == nSubTest then + CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA4444) + pBatchNode = CCSpriteBatchNode:create("Images/spritesheet1.png", 100) + pNewScene:addChild(pBatchNode, 0) + end + + if nil ~= pBatchNode then + pBatchNode:retain() + end + + CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_Default) + end + + local function InitWithSpriteTest(nSubtest,nNodes) + nSubtestNumber = nSubtest + --about create subset + InitWithSubTest(nSubtest) + local s = CCDirector:sharedDirector():getWinSize() + + nLastRenderedCount = 0 + nQuantityNodes = 0 + + --"+","-" Menu + CCMenuItemFont:setFontSize(65) + local pDecrease = CCMenuItemFont:create(" - ") + pDecrease:registerScriptTapHandler(onDecrease) + pDecrease:setColor(ccc3(0,200,20)) + local pIncrease = CCMenuItemFont:create(" + ") + pIncrease:registerScriptTapHandler(onIncrease) + pIncrease:setColor(ccc3(0,200,20)) + + local pMenuAddOrSub = CCMenu:create() + pMenuAddOrSub:addChild(pDecrease) + pMenuAddOrSub:addChild(pIncrease) + pMenuAddOrSub:alignItemsHorizontally() + pMenuAddOrSub:setPosition(ccp(s.width/2, s.height/2+15)) + pNewScene:addChild(pMenuAddOrSub,1) + + local pInfoLabel = CCLabelTTF:create("0 nodes", "Marker Felt", 30) + pInfoLabel:setColor(ccc3(0,200,20)) + pInfoLabel:setPosition(ccp(s.width/2, s.height - 90)) + pNewScene:addChild(pInfoLabel, 1, SpriteTestParam.kTagInfoLayer) + + --SpriteTestMenuLayer + local pSpriteMenuLayer = CCLayer:create() + local pSpriteMenu = CCMenu:create() + CreatePerfomBasicLayerMenu(pSpriteMenu) + CreateBasicLayerMenuItem(pSpriteMenu,true,SpriteTestParam.TEST_COUNT,nCurCase) + pSpriteMenu:setPosition(ccp(0, 0)) + pSpriteMenuLayer:addChild(pSpriteMenu) + pNewScene:addChild(pSpriteMenuLayer,1,SpriteTestParam.kTagMenuLayer) + + + --Sub Tests + CCMenuItemFont:setFontSize(40) + local pSubMenu = CCMenu:create() + local i = 1 + for i = 1, 9 do + local strNum = string.format("%d ",i) + local pItemFont = CCMenuItemFont:create(strNum) + pItemFont:registerScriptTapHandler(TestNCallback) + pSubMenu:addChild(pItemFont, i + SpriteTestParam.kSubMenuBasicZOrder) + if i <= 3 then + pItemFont:setColor(ccc3(200,20,20)) + elseif i <= 6 then + pItemFont:setColor(ccc3(0,200,20)) + else + pItemFont:setColor(ccc3(0,20,200)) + end + end + + + pSubMenu:alignItemsHorizontally() + pSubMenu:setPosition(ccp(s.width/2, 80)) + pNewScene:addChild(pSubMenu, 2) + + local pLabel = CCLabelTTF:create(GetTitle(), "Arial", 40) + pNewScene:addChild(pLabel, 1) + pLabel:setPosition(ccp(s.width/2, s.height-32)) + pLabel:setColor(ccc3(255,255,40)) + while nQuantityNodes < nNodes do + onIncrease() + end + end + + function ShowCurrentTest() + pNewScene = CCScene:create() + InitWithSpriteTest(nSubtestNumber,nQuantityNodes) + CCDirector:sharedDirector():replaceScene(pNewScene) + end + + InitWithSpriteTest(1,SpriteTestParam.kInitNodes) + + return pNewScene +end + +---------------------------------- +--PerformanceTextureTest +---------------------------------- +local TextureTestParam = +{ + TEST_COUNT = 1, +} + +local function runTextureTest() + + local function GetTitle() + return "Texture Performance Test" + end + + local function GetSubtitle() + return "See console for results" + end + + local nTexCurCase = 0 + local pNewscene = CCScene:create() + local pLayer = CCLayer:create() + local s = CCDirector:sharedDirector():getWinSize() + + local function PerformTestsPNG(strFileName) + local time + local pTexture = nil + local pCache = CCTextureCache:sharedTextureCache() + print("RGBA 8888") + CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA8888) + pTexture = pCache:addImage(strFileName) + if nil ~= pTexture then + --os.time()--get secs,not micr sec + print("add sucess") + else + print(" ERROR") + end + pCache:removeTexture(pTexture) + + print("RGBA 4444") + CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA4444) + --gettimeofday(&now, NULL) + pTexture = pCache:addImage(strFileName) + if nil ~= pTexture then + print("add sucess") + else + print(" ERROR") + end + pCache:removeTexture(pTexture) + + print("RGBA 5551") + CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGB5A1) + --gettimeofday(&now, NULL) + pTexture = pCache:addImage(strFileName) + if nil ~= pTexture then + print("add sucess") + else + print(" ERROR") + end + pCache:removeTexture(pTexture) + + print("RGB 565") + CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGB565) + -- gettimeofday(&now, NULL) + pTexture = pCache:addImage(strFileName) + if nil ~= pTexture then + --CCLog(" ms:%f", calculateDeltaTime(&now) ) + print("add sucess") + else + print(" ERROR") + end + pCache:removeTexture(pTexture) + end + local function PerformTests() + print("--------") + print("--- PNG 128x128 ---") + PerformTestsPNG("Images/test_image.png") + + print("--- PNG 512x512 ---") + PerformTestsPNG("Images/texture512x512.png") + + print("EMPTY IMAGE") + print("--- PNG 1024x1024 ---") + PerformTestsPNG("Images/texture1024x1024.png") + + print("SPRITESHEET IMAGE") + print("--- PNG 1024x1024 ---") + PerformTestsPNG("Images/PlanetCute-1024x1024.png") + + print("LANDSCAPE IMAGE") + print("--- PNG 1024x1024 ---") + PerformTestsPNG("Images/landscape-1024x1024.png") + end + + local function InitTextureMenuLayer() + if nil == pLayer then + return + end + + --Title + local pLabel = CCLabelTTF:create(GetTitle(), "Arial", 40) + pLayer:addChild(pLabel, 1) + pLabel:setPosition(ccp(s.width/2, s.height-32)) + pLabel:setColor(ccc3(255,255,40)) + + --Subtitle + local pSubLabel = CCLabelTTF:create(GetSubtitle(), "Thonburi", 16) + pLayer:addChild(pSubLabel, 1) + pSubLabel:setPosition(ccp(s.width/2, s.height-80)) + + --menu + local pMenu = CCMenu:create() + CreatePerfomBasicLayerMenu(pMenu) + pMenu:setPosition(ccp(0, 0)) + pLayer:addChild(pMenu) + + PerformTests() + end + + InitTextureMenuLayer() + pNewscene:addChild(pLayer) + return pNewscene +end +---------------------------------- +--PerformanceTouchesTest +---------------------------------- +local TouchesTestParam = +{ + TEST_COUNT = 2, +} +local function runTouchesTest() + local nTouchCurCase = 0 + --PerformBasicLayer param + local bControlMenuVisible = false + local nMaxCases = 0 + local nCurCase = 0 + --TouchesMainScene param + local pClassLabel = nil + local nNumberOfTouchesB = 0 + local nNumberOfTouchesM = 0 + local nNumberOfTouchesE = 0 + local nNumberOfTouchesC = 0 + local fElapsedTime = 0.0 + + local s = CCDirector:sharedDirector():getWinSize() + local pNewscene = CCScene:create() + local pLayer = CCLayer:create() + + local function GetTitle() + if 0 == nCurCase then + return "Targeted touches" + elseif 1 == nCurCase then + return "Standard touches" + end + end + + local function CreateBasicLayerMenuItem(pMenu,bMenuVisible,nMaxCasesNum,nCurCaseIndex) + if nil ~= pMenu then + bControlMenuVisible = bMenuVisible + nMaxCases = nMaxCasesNum + nCurCase = nCurCaseIndex + if true == bControlMenuVisible then + local function backCallback() + nCurCase = nCurCase - 1 + if nCurCase < 0 then + nCurCase = nCurCase + nMaxCases + end + ShowCurrentTest() + end + + local function restartCallback() + ShowCurrentTest() + end + + local function nextCallback() + nCurCase = nCurCase + 1 + --No check nMaxCases + nCurCase = nCurCase % nMaxCases + ShowCurrentTest() + end + + local size = CCDirector:sharedDirector():getWinSize() + local item1 = CCMenuItemImage:create(s_pPathB1, s_pPathB2) + item1:registerScriptTapHandler(backCallback) + pMenu:addChild(item1,kItemTagBasic) + local item2 = CCMenuItemImage:create(s_pPathR1, s_pPathR2) + item2:registerScriptTapHandler(restartCallback) + pMenu:addChild(item2,kItemTagBasic) + local item3 = CCMenuItemImage:create(s_pPathF1, s_pPathF2) + pMenu:addChild(item3,kItemTagBasic) + item3:registerScriptTapHandler(nextCallback) + + local size = CCDirector:sharedDirector():getWinSize() + item1:setPosition(CCPointMake(size.width / 2 - item2:getContentSize().width * 2, item2:getContentSize().height / 2)) + item2:setPosition(CCPointMake(size.width / 2, item2:getContentSize().height / 2)) + item3:setPosition(CCPointMake(size.width / 2 + item2:getContentSize().width * 2, item2:getContentSize().height / 2)) + end + end + end + + local function update(fTime) + fElapsedTime = fElapsedTime + fTime + + if fElapsedTime > 1.0 then + local fFrameRateB = nNumberOfTouchesB / fElapsedTime + local fFrameRateM = nNumberOfTouchesM / fElapsedTime + local fFrameRateE = nNumberOfTouchesE / fElapsedTime + local fFrameRateC = nNumberOfTouchesC / fElapsedTime + fElapsedTime = 0 + nNumberOfTouchesB = 0 + nNumberOfTouchesM = 0 + nNumberOfTouchesE = 0 + nNumberOfTouchesC = 0 + + local strInfo = string.format("%.1f %.1f %.1f %.1f",fFrameRateB, fFrameRateM, fFrameRateE, fFrameRateC) + if nil ~= pClassLabel then + pClassLabel:setString(strInfo) + end + end + + end + + -- handling touch events + local function onTouchBegan(tableArray) + if 0 == nCurCase then + nNumberOfTouchesB = nNumberOfTouchesB + 1 + elseif 1 == nCurCase then + nNumberOfTouchesB = nNumberOfTouchesB + table.getn(tableArray) + end + end + + local function onTouchMoved(tableArray) + if 0 == nCurCase then + nNumberOfTouchesM = nNumberOfTouchesM + 1 + elseif 1 == nCurCase then + nNumberOfTouchesM = nNumberOfTouchesM + table.getn(tableArray) + end + end + + local function onTouchEnded(tableArray) + if 0 == nCurCase then + nNumberOfTouchesE = nNumberOfTouchesE + 1 + elseif 1 == nCurCase then + nNumberOfTouchesE = nNumberOfTouchesE + table.getn(tableArray) + end + end + + local function onTouchCancelled(tableArray) + if 0 == nCurCase then + nNumberOfTouchesC = nNumberOfTouchesC + 1 + elseif 1 == nCurCase then + nNumberOfTouchesC = nNumberOfTouchesC + table.getn(tableArray) + end + end + + local function onTouch(eventType,tableArray) + if eventType == "began" then + return onTouchBegan(tableArray) + elseif eventType == "moved" then + return onTouchMoved(tableArray) + elseif eventType == "ended" then + return onTouchEnded(tableArray) + elseif eventType == "cancelled" then + return onTouchCancelled(tableArray) + end + end + + local function InitLayer() + --menu + local pTouchesTestMenu = CCMenu:create() + CreatePerfomBasicLayerMenu(pTouchesTestMenu) + CreateBasicLayerMenuItem(pTouchesTestMenu,true,TouchesTestParam.TEST_COUNT,nCurCase) + pTouchesTestMenu:setPosition(ccp(0, 0)) + pLayer:addChild(pTouchesTestMenu) + + --Title + local pLabel = CCLabelTTF:create(GetTitle(), "Arial", 40) + pLayer:addChild(pLabel, 1) + pLabel:setPosition(ccp(s.width/2, s.height-32)) + pLabel:setColor(ccc3(255,255,40)) + + pLayer:scheduleUpdateWithPriorityLua(update,0) + + pClassLabel = CCLabelBMFont:create("00.0", "fonts/arial16.fnt") + pClassLabel:setPosition(ccp(s.width/2, s.height/2)) + pLayer:addChild(pClassLabel) + + fElapsedTime = 0.0 + nNumberOfTouchesB = 0 + nNumberOfTouchesM = 0 + nNumberOfTouchesE = 0 + nNumberOfTouchesC = 0 + pLayer:setTouchEnabled(true) + + pLayer:registerScriptTouchHandler(onTouch,true) + end + + function ShowCurrentTest() + if nil ~= pLayer then + pLayer:unscheduleUpdate() + end + + pNewscene = CCScene:create() + + if nil ~= pNewscene then + pLayer = CCLayer:create() + InitLayer() + pNewscene:addChild(pLayer) + CCDirector:sharedDirector():replaceScene(pNewscene) + end + end + + InitLayer() + pNewscene:addChild(pLayer) + return pNewscene +end + + +------------------------ +-- +------------------------ +local CreatePerformancesTestTable = +{ + runNodeChildrenTest, + runParticleTest, + runSpriteTest, + runTextureTest, + runTouchesTest +} + +local function CreatePerformancesTestScene(nPerformanceNo) + local pNewscene = CreatePerformancesTestTable[nPerformanceNo]() + return pNewscene +end +local function menuCallback(tag, pMenuItem) local scene = nil --- tag = tag - kItemTagBasic - - if tag == "enter" then - scene = PerformanceSpriteTest() - elseif tag == 1 then - - elseif tag == 2 then - - elseif tag == 3 then - - elseif tag == 4 then - - end - if scene ~= nil then - CCDirector:sharedDirector():replaceScene(scene) - end + local nIdx = pMenuItem:getZOrder() - kItemTagBasic + local PerformanceTestScene = CreatePerformancesTestScene(nIdx) + if nil ~= PerformanceTestScene then + CCDirector:sharedDirector():replaceScene(PerformanceTestScene) + end end local function PerformanceMainLayer() @@ -45,11 +1687,11 @@ local function PerformanceMainLayer() menu:setPosition(CCPointMake(0, 0)) CCMenuItemFont:setFontName("Arial") CCMenuItemFont:setFontSize(24) - for i = 0, MAX_COUNT - 1 do + for i = 1, MAX_COUNT do local item = CCMenuItemFont:create(testsName[i]) item:registerScriptTapHandler(menuCallback) item:setPosition(s.width / 2, s.height - (i + 1) * LINE_SPACE) - menu:addChild(item, kItemTagBasic + i, kItemTagBasic + i) + menu:addChild(item, kItemTagBasic + i) end layer:addChild(menu) @@ -60,7 +1702,7 @@ end ------------------------------------- -- Performance Test ------------------------------------- -function PerformanceTest() +function PerformanceTestMain() local scene = CCScene:create() scene:addChild(PerformanceMainLayer()) diff --git a/samples/Lua/TestLua/Resources/luaScript/mainMenu.lua b/samples/Lua/TestLua/Resources/luaScript/mainMenu.lua index 304bde69a9..5b44363919 100644 --- a/samples/Lua/TestLua/Resources/luaScript/mainMenu.lua +++ b/samples/Lua/TestLua/Resources/luaScript/mainMenu.lua @@ -75,7 +75,7 @@ local _allTests = { { isSupported = false, name = "Accelerometer" , create_func= AccelerometerMain }, { isSupported = false, name = "KeypadTest" , create_func= KeypadTestMain }, { isSupported = true, name = "CocosDenshionTest" , create_func = CocosDenshionTestMain }, - { isSupported = false, name = "PerformanceTest" , create_func= PerformanceTestMain }, + { isSupported = true, name = "PerformanceTest" , create_func= PerformanceTestMain }, { isSupported = true, name = "ZwoptexTest" , create_func = ZwoptexTestMain }, { isSupported = false, name = "CurlTest" , create_func= CurlTestMain }, { isSupported = true, name = "UserDefaultTest" , create_func= UserDefaultTestMain }, diff --git a/tools/jsbcc/README b/tools/jsbcc/README index 8145ebde8b..00983c8209 100644 --- a/tools/jsbcc/README +++ b/tools/jsbcc/README @@ -1,7 +1,11 @@ jsbcc stands for JavasSript Byte Code Compiler. -it compiles javascript files to SpiderMonkey byte code files +It compiles javascript files to SpiderMonkey byte code files. It supports Mac and win32 now. Usage: jsbcc input_js_file [byte_code_file] - -Note: it also supports pipeline, so you can use it like this: +Note: it also supports pipeline on Mac, so you can use it like this: ls *.js | jsbcc + +Furthermore, 2 scripts supplied to help: "jsbcc.sh" on Mac and "jsbcc.bat" on win32 + jsbcc.sh/jsbcc.bat js_root_dir +js_root_dir is the root directory of js source files. The scripts search and compile js source files recrusively. + \ No newline at end of file diff --git a/tools/jsbcc/jsbcc-vc2010.vcxproj b/tools/jsbcc/jsbcc-vc2010.vcxproj new file mode 100644 index 0000000000..c1447336ec --- /dev/null +++ b/tools/jsbcc/jsbcc-vc2010.vcxproj @@ -0,0 +1,97 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + {BD6738AE-6468-4881-B32B-5749DCF95511} + Win32Proj + jsbcc + jsbcc + + + + Application + true + Unicode + + + Application + false + true + Unicode + + + + + + + + + + + + + true + + + false + + + + + + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;XP_WIN;%(PreprocessorDefinitions) + ..\..\scripting\javascript\spidermonkey-win32\include;%(AdditionalIncludeDirectories) + + + Console + true + ..\..\scripting\javascript\spidermonkey-win32\lib;%(AdditionalLibraryDirectories) + Ws2_32.lib;mozjs.lib + + + copy "$(ProjectDir)..\..\scripting\javascript\spidermonkey-win32\lib\mozjs.dll" "$(TargetDir)" +copy "$(ProjectDir)src\jsbcc.bat" "$(TargetDir)" + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;XP_WIN;%(PreprocessorDefinitions) + ..\..\scripting\javascript\spidermonkey-win32\include;%(AdditionalIncludeDirectories) + + + Console + true + true + true + ..\..\scripting\javascript\spidermonkey-win32\lib;%(AdditionalLibraryDirectories) + Ws2_32.lib;mozjs.lib + + + copy "$(ProjectDir)..\..\scripting\javascript\spidermonkey-win32\lib\mozjs.dll" "$(TargetDir)" +copy "$(ProjectDir)src\jsbcc.bat" "$(TargetDir)" + + + + + + + + + \ No newline at end of file diff --git a/tools/jsbcc/jsbcc-vc2010.vcxproj.filters b/tools/jsbcc/jsbcc-vc2010.vcxproj.filters new file mode 100644 index 0000000000..9f88da1bc4 --- /dev/null +++ b/tools/jsbcc/jsbcc-vc2010.vcxproj.filters @@ -0,0 +1,22 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + \ No newline at end of file diff --git a/tools/jsbcc/src/jsbcc.bat b/tools/jsbcc/src/jsbcc.bat new file mode 100644 index 0000000000..b9c09ac3d4 --- /dev/null +++ b/tools/jsbcc/src/jsbcc.bat @@ -0,0 +1 @@ +for /f %%f in ('dir %1\*.js /s/b') do jsbcc.exe %%f \ No newline at end of file diff --git a/tools/jsbcc/src/main.cpp b/tools/jsbcc/src/main.cpp index f052f8b2d4..8dafb95b91 100644 --- a/tools/jsbcc/src/main.cpp +++ b/tools/jsbcc/src/main.cpp @@ -9,15 +9,25 @@ #include #include -#include #include + +#ifdef WIN32 +#include +#define STDIN_FILENO 0 +#else #include +#include +#endif #include "jsapi.h" +#ifdef WIN32 +const char *USAGE = "Usage: jsbcc input_js_file [byte_code_file]"; +#else const char *USAGE = "Usage: jsbcc input_js_file [byte_code_file]\n"\ " Or\n"\ " ls *.js | jsbcc -p"; +#endif const char *BYTE_CODE_FILE_EXT = ".jsc"; enum ErrorCode { @@ -84,7 +94,6 @@ bool CompileFile(const std::string &inputFilePath, const std::string &outputFile JS::CompileOptions options(context); options.setUTF8(true); options.setSourcePolicy(JS::CompileOptions::NO_SOURCE); - js::RootedObject rootedObject(context, global); std::cout << "Compiling ..." << std::endl; JSScript *script = JS::Compile(context, rootedObject, options, inputFilePath.c_str()); @@ -102,7 +111,6 @@ bool CompileFile(const std::string &inputFilePath, const std::string &outputFile } } -Exit: if (context) { JS_DestroyContext(context); context = NULL; diff --git a/tools/travis-scripts/before-install.sh b/tools/travis-scripts/before-install.sh new file mode 100755 index 0000000000..cdec1fcf84 --- /dev/null +++ b/tools/travis-scripts/before-install.sh @@ -0,0 +1,58 @@ +#!/bin/bash + +# exit this script if any commmand fails +set -e + +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +COCOS2DX_ROOT="$DIR"/../.. + +mkdir -p $HOME/bin +pushd $HOME/bin + + +install_android_ndk() +{ + # Download android ndk + echo "Download android ndk ..." + curl -O http://dl.google.com/android/ndk/android-ndk-r8e-linux-x86_64.tar.bz2 + echo "Decompress android-ndk-r8e-linux-x86_64.tar.bz2 ..." + tar xjf android-ndk-r8e-linux-x86_64.tar.bz2 + # Rename ndk + mv android-ndk-r8e android-ndk +} + +if [ "$GEN_JSB"x = "YES"x ]; then + if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then + exit 0 + fi + install_android_ndk + # Download llvm3.1 + echo "Download llvm3.1 ..." + curl -O http://llvm.org/releases/3.1/clang+llvm-3.1-x86_64-linux-ubuntu_12.04.tar.gz + echo "Decompress android-ndk-r8e-linux-x86_64.tar.bz2 ..." + tar xzf clang+llvm-3.1-x86_64-linux-ubuntu_12.04.tar.gz + # Rename llvm + mv clang+llvm-3.1-x86_64-linux-ubuntu_12.04 clang+llvm-3.1 +fi + +if [ "$PLATFORM"x = "linux"x ]; then + bash $COCOS2DX_ROOT/install-deps-linux.sh +fi + +if [ "$PLATFORM"x = "nacl"x ]; then + sudo apt-get update + sudo apt-get install libc6:i386 + echo "Download nacl_sdk ..." + wget http://storage.googleapis.com/nativeclient-mirror/nacl/nacl_sdk/nacl_sdk.zip + echo "Decompress nacl_sdk.zip" + unzip nacl_sdk.zip + nacl_sdk/naclsdk update --force pepper_canary +fi + +if [ "$PLATFORM"x = "android"x ]; then + install_android_ndk +fi + + + +popd diff --git a/tools/travis-scripts/generate-jsbindings.sh b/tools/travis-scripts/generate-jsbindings.sh new file mode 100755 index 0000000000..88afac162d --- /dev/null +++ b/tools/travis-scripts/generate-jsbindings.sh @@ -0,0 +1,198 @@ +#!/bin/bash + +# Generate JS bindings for Cocos2D-X +# ... using Android NDK system headers +# ... and automatically update submodule references +# ... and push these changes to remote repos + +# Dependencies +# +# For bindings generator: +# (see ../../../tojs/genbindings.sh +# ... for the defaults used if the environment is not customized) +# +# * $PYTHON_BIN +# * $CLANG_ROOT +# * $NDK_ROOT +# +# For automatically pushing changes: +# +# * REMOTE_AUTOGEN_BINDINGS_REPOSITORY +# * REMOTE_COCOS2DX_REPOSITORY +# * Note : Ensure you have commit access to above repositories +# * COCOS2DX_PULL_BASE +# * hub +# * see http://defunkt.io/hub/ +# * Ensure that hub has an OAuth token to REMOTE_COCOS2DX_REPOSITORY +# * see http://defunkt.io/hub/hub.1.html#CONFIGURATION + +#Set git user +git config --global user.email "CocosRobot@gmail.com" +git config --global user.name "CocosRobot" + +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +COCOS2DX_ROOT="$DIR"/../.. +TOJS_ROOT=$COCOS2DX_ROOT/tools/tojs +GENERATED_WORKTREE="$COCOS2DX_ROOT"/scripting/javascript/bindings/generated +REMOTE_AUTOGEN_BINDINGS_REPOSITORY="https://github.com/angeltown/cocos2dx-autogen-bindings.git" +REMOTE_COCOS2DX_REPOSITORY="https://github.com/angeltown/cocos2d-x.git" +COCOS2DX_PULL_BASE="dumganhar/cocos2d-x:travis" + +sudo apt-get --force-yes --yes install python-yaml python-cheetah + +# Update cocos2d-x repo +# It needs to be updated in Jenkins command before executing this script. +#pushd "$COCOS2DX_ROOT" + +#git checkout -f +#git checkout gles20 +#git pull upstream gles20 +#rm -rf "$GENERATED_WORKTREE" +#git submodule update --init + +#popd + +# Update submodule of auto-gen JSBinding repo. +pushd "$GENERATED_WORKTREE" + +git checkout -B master +#Set remotes +git remote add upstream https://${GH_TOKEN}@github.com/angeltown/cocos2dx-autogen-bindings.git 2> /dev/null > /dev/null + +echo "Delete all directories and files except '.git' and 'README'." +ls -a | grep -E -v ^\[.\]\{1,2\}$ | grep -E -v ^\.git$ | grep -E -v ^README$ | xargs -I{} rm -rf {} +echo "Show files in scripting/javascript/bindings/generated folder." +ls -a +popd + +# Exit on error +set -e + +# 1. Generate JS bindings +pushd "$TOJS_ROOT" +./genbindings.sh +popd + +echo +echo Bindings generated successfully +echo + +if [ -z "${REMOTE_AUTOGEN_BINDINGS_REPOSITORY+aaa}" ]; then + echo + echo Environment variable must be set REMOTE_AUTOGEN_BINDINGS_REPOSITORY + echo This script expects to automatically push changes + echo to this repo + echo example + echo REMOTE_AUTOGEN_BINDINGS_REPOSITORY=\"git@github.com:folecr/cocos2dx-autogen-bindings.git\" + echo REMOTE_AUTOGEN_BINDINGS_REPOSITORY=\"\$HOME/test/cocos2dx-autogen-bindings\" + echo + echo Exiting with failure. + echo + exit 1 +fi + +if [ -z "${COMMITTAG+aaa}" ]; then +# ... if COMMITTAG is not set, use this machine's hostname + COMMITTAG=`hostname -s` +fi + +echo +echo Using "'$COMMITTAG'" in the commit messages +echo + +ELAPSEDSECS=`date +%s` +echo Using "$ELAPSEDSECS" in the branch names for pseudo-uniqueness + +GENERATED_BRANCH=autogeneratedbindings_"$ELAPSEDSECS" + + +# 2. In JSBindings repo, Check if there are any files that are different from the index + +pushd "$GENERATED_WORKTREE" + +# Run status to record the output in the log +git status + +echo +echo Comparing with HEAD ... +echo + +# Don't exit on non-zero return value +set +e +git diff --stat --exit-code + +DIFF_RETVAL=$? +if [ $DIFF_RETVAL -eq 0 ] +then + echo + echo "No differences in generated files" + echo "Exiting with success." + echo + exit 0 +else + echo + echo "Generated files differ from HEAD. Continuing." + echo +fi + +# Exit on error +set -e + +# 3. In JSBindings repo, Check out a branch named "autogeneratedbindings" and commit the auto generated bindings to it +git checkout -b "$GENERATED_BRANCH" +git add --verbose . +git add --verbose -u . +git commit --verbose -m "$COMMITTAG : autogenerated bindings" + +# 4. In JSBindings repo, Push the commit with generated bindings to "master" of the auto generated bindings repository +git push -fq upstream "$GENERATED_BRANCH":master 2> /dev/null + +popd + +if [ -z "${REMOTE_COCOS2DX_REPOSITORY+aaa}" ]; then + echo + echo Environment variable is not set REMOTE_COCOS2DX_REPOSITORY + echo This script will NOT automatically push changes + echo unless this variable is set. + echo example + echo REMOTE_COCOS2DX_REPOSITORY=\"git@github.com:cocos2d/cocos2d-x.git\" + echo REMOTE_COCOS2DX_REPOSITORY=\"\$HOME/test/cocos2d-x\" + echo + echo Exiting with success. + echo + exit 0 +fi + +COCOS_BRANCH=updategeneratedsubmodule_"$ELAPSEDSECS" + +pushd "${DIR}" + +# 5. In Cocos2D-X repo, Checkout a branch named "updategeneratedsubmodule" Update the submodule reference to point to the commit with generated bindings +cd "${COCOS2DX_ROOT}" +git add scripting/javascript/bindings/generated +git checkout -b "$COCOS_BRANCH" +git commit -m "$COMMITTAG : updating submodule reference to latest autogenerated bindings" +#Set remotes +git remote add upstream https://${GH_TOKEN}@github.com/angeltown/cocos2d-x.git 2> /dev/null > /dev/null +# 6. In Cocos2D-X repo, Push the commit with updated submodule to "master" of the cocos2d-x repository +git push -fq upstream "$COCOS_BRANCH" 2> /dev/null + +if [ -z "${COCOS2DX_PULL_BASE+aaa}" ]; then + echo + echo Environment variable is not set COCOS2DX_PULL_BASE + echo This script will NOT automatically generate pull requests + echo unless this variable is set. + echo example + echo COCOS2DX_PULL_BASE=\"cocos2d/cocos2d-x:master\" + echo COCOS2DX_PULL_BASE=\"username/repository:branch\" + echo + echo Exiting with success. + echo + exit 0 +fi + +# 7. +curl --user "angeltown:$GH_PASSWORD" --request POST --data "{ \"title\": \"$COMMITTAG : updating submodule reference to latest autogenerated bindings\", \"body\": \"\", \"head\": \"angeltown:${COCOS_BRANCH}\", \"base\": \"travis\"}" https://api.github.com/repos/dumganhar/cocos2d-x/pulls 2> /dev/null > /dev/null +# ${HUB} pull-request "$COMMITTAG : updating submodule reference to latest autogenerated bindings" -b "$COCOS2DX_PULL_BASE" -h "$COCOS_BRANCH" + +popd diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh new file mode 100755 index 0000000000..51148702d1 --- /dev/null +++ b/tools/travis-scripts/run-script.sh @@ -0,0 +1,37 @@ +#!/bin/bash +# exit this script if any commmand fails +set -e + +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +COCOS2DX_ROOT="$DIR"/../.. + +if [ "$GEN_JSB"x = "YES"x ]; then + if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then + exit 0 + fi + cd $COCOS2DX_ROOT/tools/travis-scripts + ./generate-jsbindings.sh +fi + +build_android() +{ + cd $COCOS2DX_ROOT/samples/$1/$2/proj.android + ./build_native.sh +} + +if [ "$PLATFORM"x = "android"x ]; then + build_android Cpp HelloCpp + build_android Javascript TestJavascript + build_android Lua TestLua +fi + +if [ "$PLATFORM"x = "nacl"x ]; then + cd $COCOS2DX_ROOT + make -j4 +fi + +if [ "$PLATFORM"x = "linux"x ]; then + cd $COCOS2DX_ROOT + make -j4 +fi +