diff --git a/CHANGELOG b/CHANGELOG index e77a4728ac..a4000b16fd 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -10,10 +10,14 @@ cocos2d-x-3.0beta2 ?.? ? [NEW] Renderer: Added BatchCommand. This command is not "batchable" with other commands, but improves performance in about 10% [NEW] LuaBindings: Bindings-generator supports to bind namespace for lua. + [FIX] Bindings-generator supports Windows again and remove dependency of LLVM since we only need binary(libclang.so/dll). + [FIX] Removes unused files for MAC platform after using glfw3 to create opengl context. + [FIX] Wrong arithmetic of child's position in ParallaxNode::addChild() [FIX] CocoStudio: TestColliderDetector in ArmatureTest can't work. [FIX] Crash if file doesn't exist when using FileUtils::getStringFromFile. [FIX] If setting a shorter string than before while using LabelAtlas, the effect will be wrong. [FIX] Label: Crash when using unknown characters. + [FIX] Label: Missing line breaks and wrong alignment. [FIX] Console: log(format, va_args) is private to prevent possible resolution errors [FIX] Configuration: dumpInfo() -> getInfo() [FIX] ControlSlider doesn't support to set selected thumb sprite. diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index a520602c3d..3ce4eaa042 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -63e6598ea5798bf42bbd22c2295e65f7c739695a \ No newline at end of file +db31f01b55bf1ae19e57e71bae6f58a037bfe5b9 \ No newline at end of file diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index eac7e38de9..dc3bae7a56 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -447e7ba37294e6da0df2e02f5a62f30fb15e3272 \ No newline at end of file +ff284ac388641341140f8b6817f2cd26e4f07cf2 \ No newline at end of file diff --git a/cocos/2d/Android.mk b/cocos/2d/Android.mk index 2253bcd7d9..432ace90c5 100644 --- a/cocos/2d/Android.mk +++ b/cocos/2d/Android.mk @@ -50,8 +50,6 @@ CCFont.cpp \ CCFontCharMap.cpp \ CCFontAtlas.cpp \ CCFontAtlasCache.cpp \ -CCFontAtlasFactory.cpp \ -CCFontDefinition.cpp \ CCFontFNT.cpp \ CCFontFreeType.cpp \ ccFPSImages.c \ @@ -91,7 +89,6 @@ CCSpriteBatchNode.cpp \ CCSpriteFrame.cpp \ CCSpriteFrameCache.cpp \ CCTextFieldTTF.cpp \ -CCTextImage.cpp \ CCTexture2D.cpp \ CCTextureAtlas.cpp \ CCTextureCache.cpp \ diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index d66385e295..c45e10851e 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -165,9 +165,6 @@ bool Director::init(void) _renderer = new Renderer; _console = new Console; - // create autorelease pool - PoolManager::sharedPoolManager()->push(); - return true; } @@ -193,9 +190,8 @@ Director::~Director(void) delete _renderer; delete _console; - // pop the autorelease pool - PoolManager::sharedPoolManager()->pop(); - PoolManager::purgePoolManager(); + // clean auto release pool + PoolManager::destroyInstance(); // delete _lastUpdate CC_SAFE_DELETE(_lastUpdate); @@ -1049,7 +1045,7 @@ void DisplayLinkDirector::mainLoop() drawScene(); // release the objects - PoolManager::sharedPoolManager()->pop(); + PoolManager::getInstance()->getCurrentPool()->clear(); } } diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index 538a26fd13..ac155142be 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -234,7 +234,7 @@ void EventDispatcher::visitTarget(Node* node, bool isRootNode) if (isRootNode) { - std::vector globalZOrders; + std::vector globalZOrders; globalZOrders.reserve(_globalZOrderNodeMap.size()); for (const auto& e : _globalZOrderNodeMap) @@ -242,7 +242,7 @@ void EventDispatcher::visitTarget(Node* node, bool isRootNode) globalZOrders.push_back(e.first); } - std::sort(globalZOrders.begin(), globalZOrders.end(), [](const int a, const int b){ + std::sort(globalZOrders.begin(), globalZOrders.end(), [](const float a, const float b){ return a < b; }); @@ -1166,7 +1166,7 @@ bool EventDispatcher::isEnabled() const void EventDispatcher::setDirtyForNode(Node* node) { - // Mark the node dirty only when there was an eventlistener associates with it. + // Mark the node dirty only when there is an eventlistener associated with it. if (_nodeListenersMap.find(node) != _nodeListenersMap.end()) { _dirtyNodes.insert(node); diff --git a/cocos/2d/CCEventDispatcher.h b/cocos/2d/CCEventDispatcher.h index 13cfe77232..f7c886508b 100644 --- a/cocos/2d/CCEventDispatcher.h +++ b/cocos/2d/CCEventDispatcher.h @@ -231,7 +231,7 @@ protected: std::unordered_map _nodePriorityMap; /** key: Global Z Order, value: Sorted Nodes */ - std::unordered_map> _globalZOrderNodeMap; + std::unordered_map> _globalZOrderNodeMap; /** The listeners to be added after dispatching event */ std::vector _toAddedListeners; diff --git a/cocos/2d/CCFont.cpp b/cocos/2d/CCFont.cpp index 1c2d3bab86..3c44e8d5d3 100644 --- a/cocos/2d/CCFont.cpp +++ b/cocos/2d/CCFont.cpp @@ -26,15 +26,8 @@ #include "CCFont.h" #include "ccUTF8.h" -#include "CCFontFNT.h" -#include "CCFontFreeType.h" -#include "CCFontCharMap.h" -#include "edtaa3func.h" - NS_CC_BEGIN -const int Font::DistanceMapSpread = 3; - const char * Font::_glyphASCII = "\"!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþ "; const char * Font::_glyphNEHE = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ "; @@ -43,7 +36,6 @@ const char * Font::_glyphNEHE = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLM Font::Font() : _usedGlyphs(GlyphCollection::ASCII) , _customGlyphs(nullptr) -,_distanceFieldEnabled(false) { } @@ -107,189 +99,6 @@ const char * Font::getCurrentGlyphCollection() const } } -Font* Font::createWithTTF(const std::string& fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs) -{ - return FontFreeType::create(fntName, fontSize, glyphs, customGlyphs); -} - -Font* Font::createWithFNT(const std::string& fntFilePath) -{ - return FontFNT::create(fntFilePath); -} - -Font* Font::createWithCharMap(const std::string& plistFile) -{ - return FontCharMap::create(plistFile); -} - -Font* Font::createWithCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap) -{ - return FontCharMap::create(texture,itemWidth,itemHeight,startCharMap); -} - -Font* Font::createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) -{ - return FontCharMap::create(charMapFile,itemWidth,itemHeight,startCharMap); -} - -unsigned char * Font::makeDistanceMap( unsigned char *img, unsigned int width, unsigned int height) -{ - unsigned int pixelAmount = (width + 2 * DistanceMapSpread) * (height + 2 * DistanceMapSpread); - - short * xdist = (short *) malloc( pixelAmount * sizeof(short) ); - short * ydist = (short *) malloc( pixelAmount * sizeof(short) ); - double * gx = (double *) calloc( pixelAmount, sizeof(double) ); - double * gy = (double *) calloc( pixelAmount, sizeof(double) ); - double * data = (double *) calloc( pixelAmount, sizeof(double) ); - double * outside = (double *) calloc( pixelAmount, sizeof(double) ); - double * inside = (double *) calloc( pixelAmount, sizeof(double) ); - unsigned int i,j; - - // Convert img into double (data) rescale image levels between 0 and 1 - unsigned int outWidth = width + 2 * DistanceMapSpread; - for (i = 0; i < width; ++i) - { - for (j = 0; j < height; ++j) - { - data[j * outWidth + DistanceMapSpread + i] = img[j * width + i] / 255.0; - } - } - - width += 2 * DistanceMapSpread; - height += 2 * DistanceMapSpread; - - // Transform background (outside contour, in areas of 0's) - computegradient( data, width, height, gx, gy); - edtaa3(data, gx, gy, width, height, xdist, ydist, outside); - for( i=0; i< pixelAmount; i++) - if( outside[i] < 0.0 ) - outside[i] = 0.0; - - // Transform foreground (inside contour, in areas of 1's) - for( i=0; i< pixelAmount; i++) - data[i] = 1 - data[i]; - computegradient( data, width, height, gx, gy); - edtaa3(data, gx, gy, width, height, xdist, ydist, inside); - for( i=0; i< pixelAmount; i++) - if( inside[i] < 0.0 ) - inside[i] = 0.0; - - // The bipolar distance field is now outside-inside - double dist; - /* Single channel 8-bit output (bad precision and range, but simple) */ - unsigned char *out = (unsigned char *) malloc( pixelAmount * sizeof(unsigned char) ); - for( i=0; i < pixelAmount; i++) - { - dist = outside[i] - inside[i]; - dist = 128.0 - dist*16; - if( dist < 0 ) dist = 0; - if( dist > 255 ) dist = 255; - out[i] = (unsigned char) dist; - } - /* Dual channel 16-bit output (more complicated, but good precision and range) */ - /*unsigned char *out = (unsigned char *) malloc( pixelAmount * 3 * sizeof(unsigned char) ); - for( i=0; i< pixelAmount; i++) - { - dist = outside[i] - inside[i]; - dist = 128.0 - dist*16; - if( dist < 0.0 ) dist = 0.0; - if( dist >= 256.0 ) dist = 255.999; - // R channel is a copy of the original grayscale image - out[3*i] = img[i]; - // G channel is fraction - out[3*i + 1] = (unsigned char) ( 256 - (dist - floor(dist)* 256.0 )); - // B channel is truncated integer part - out[3*i + 2] = (unsigned char)dist; - }*/ - - free( xdist ); - free( ydist ); - free( gx ); - free( gy ); - free( data ); - free( outside ); - free( inside ); - - return out; -} - -void Font::setDistanceFieldEnabled(bool distanceFieldEnabled) -{ - _distanceFieldEnabled = distanceFieldEnabled; -} - -bool Font::renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize) -{ - unsigned char *sourceBitmap = 0; - int sourceWidth = 0; - int sourceHeight = 0; - - sourceBitmap = getGlyphBitmap(charToRender, sourceWidth, sourceHeight); - - if (!sourceBitmap) - return false; - - if (_distanceFieldEnabled) - { - unsigned char * out = makeDistanceMap(sourceBitmap,sourceWidth,sourceHeight); - - int iX = posX; - int iY = posY; - - sourceWidth += 2 * DistanceMapSpread; - sourceHeight += 2 * DistanceMapSpread; - - for (int y = 0; y < sourceHeight; ++y) - { - int bitmap_y = y * sourceWidth; - - for (int x = 0; x < sourceWidth; ++x) - { - /* Dual channel 16-bit output (more complicated, but good precision and range) */ - /*int index = (iX + ( iY * destSize )) * 3; - int index2 = (bitmap_y + x)*3; - destMemory[index] = out[index2]; - destMemory[index + 1] = out[index2 + 1]; - destMemory[index + 2] = out[index2 + 2];*/ - - //Single channel 8-bit output - destMemory[iX + ( iY * destSize )] = out[bitmap_y + x]; - - iX += 1; - } - - iX = posX; - iY += 1; - } - free(out); - return true; - } - - int iX = posX; - int iY = posY; - - for (int y = 0; y < sourceHeight; ++y) - { - int bitmap_y = y * sourceWidth; - - for (int x = 0; x < sourceWidth; ++x) - { - unsigned char cTemp = sourceBitmap[bitmap_y + x]; - - // the final pixel - destMemory[(iX + ( iY * destSize ) )] = cTemp; - - iX += 1; - } - - iX = posX; - iY += 1; - } - - //everything good - return true; -} - unsigned short int * Font::getUTF16Text(const char *text, int &outNumLetters) const { unsigned short* utf16String = cc_utf8_to_utf16(text); diff --git a/cocos/2d/CCFont.h b/cocos/2d/CCFont.h index f8bb2b5201..359fb834a4 100644 --- a/cocos/2d/CCFont.h +++ b/cocos/2d/CCFont.h @@ -33,35 +33,20 @@ NS_CC_BEGIN // fwd -class GlyphDef; class FontAtlas; class CC_DLL Font : public Object { public: - static const int DistanceMapSpread; - // create the font - static Font* createWithTTF(const std::string& fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs); - static Font* createWithFNT(const std::string& fntFilePath); - - static Font * createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); - static Font * createWithCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); - static Font * createWithCharMap(const std::string& plistFile); - - static unsigned char * makeDistanceMap(unsigned char *img, unsigned int width, unsigned int height); - void setDistanceFieldEnabled(bool distanceFieldEnabled); - bool isDistanceFieldEnabled() const { return _distanceFieldEnabled;} - bool renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize); - virtual FontAtlas *createFontAtlas() = 0; - virtual Size* getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const = 0; + virtual int* getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const = 0; virtual const char* getCurrentGlyphCollection() const; virtual int getLetterPadding() const { return 0; } virtual unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) const { return 0; } - virtual GlyphDef* getGlyphDefintionsForText(const char *text, int &outNumGlyphs, bool UTF16text = false) const { return 0; } + virtual int getFontMaxHeight() const { return 0; } virtual Rect getRectForChar(unsigned short theChar) const; @@ -85,7 +70,6 @@ protected: char * _customGlyphs; static const char * _glyphASCII; static const char * _glyphNEHE; - bool _distanceFieldEnabled; }; diff --git a/cocos/2d/CCFontAtlas.cpp b/cocos/2d/CCFontAtlas.cpp index 6327d1cc31..3e056e5f6f 100644 --- a/cocos/2d/CCFontAtlas.cpp +++ b/cocos/2d/CCFontAtlas.cpp @@ -24,7 +24,6 @@ ****************************************************************************/ #include "CCFontAtlas.h" -#include "CCFont.h" #include "CCFontFreeType.h" #include "ccUTF8.h" #include "CCDirector.h" @@ -39,10 +38,9 @@ _font(&theFont), _currentPageData(nullptr) { _font->retain(); - _makeDistanceMap = _font->isDistanceFieldEnabled(); FontFreeType* fontTTf = dynamic_cast(_font); - if (fontTTf && fontTTf->isDynamicGlyphCollection()) + if (fontTTf) { _currentPageLineHeight = _font->getFontMaxHeight(); _commonLineHeight = _currentPageLineHeight * 0.8f; @@ -51,23 +49,24 @@ _currentPageData(nullptr) _currentPageOrigX = 0; _currentPageOrigY = 0; _letterPadding = 5; - + + _makeDistanceMap = fontTTf->isDistanceFieldEnabled(); if(_makeDistanceMap) { - _commonLineHeight += 2 * Font::DistanceMapSpread; - _letterPadding += 2 * Font::DistanceMapSpread; - _currentPageDataSize = (PAGE_WIDTH * PAGE_HEIGHT * 1); - } - else - { - _currentPageDataSize = (PAGE_WIDTH * PAGE_HEIGHT * 1); + _commonLineHeight += 2 * FontFreeType::DistanceMapSpread; + _letterPadding += 2 * FontFreeType::DistanceMapSpread; } + _currentPageDataSize = (PAGE_WIDTH * PAGE_HEIGHT * 1); _currentPageData = new unsigned char[_currentPageDataSize]; memset(_currentPageData, 0, _currentPageDataSize); addTexture(*tex,0); tex->release(); } + else + { + _makeDistanceMap = false; + } } FontAtlas::~FontAtlas() @@ -134,7 +133,7 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) tempDef.anchorX = 0.0f; tempDef.anchorY = 1.0f; - if (!fontTTf->getBBOXFotChar(utf16String[i], tempRect)) + if (!fontTTf->getBBOXFotChar(utf16String[i], tempRect,tempDef.xAdvance)) { tempDef.validDefinition = false; tempDef.letteCharUTF16 = utf16String[i]; @@ -146,6 +145,7 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) tempDef.offsetX = 0; tempDef.offsetY = 0; tempDef.textureID = 0; + tempDef.xAdvance = 0; } else { @@ -156,7 +156,6 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) tempDef.offsetX = tempRect.origin.x; tempDef.offsetY = tempRect.origin.y; tempDef.commonLineHeight = _currentPageLineHeight; - } fontDefs[utf16String[i]] = tempDef; } @@ -165,7 +164,8 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) Size _pageContentSize = Size(PAGE_WIDTH,PAGE_HEIGHT); float scaleFactor = CC_CONTENT_SCALE_FACTOR(); float glyphWidth; - Texture2D::PixelFormat pixelFormat = _makeDistanceMap ? Texture2D::PixelFormat::A8 : Texture2D::PixelFormat::A8; + Texture2D::PixelFormat pixelFormat = Texture2D::PixelFormat::A8; + for(auto it = fontDefs.begin(); it != fontDefs.end(); it++) { @@ -194,7 +194,7 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) tex->release(); } } - _font->renderCharAt(it->second.letteCharUTF16,_currentPageOrigX,_currentPageOrigY,_currentPageData,PAGE_WIDTH); + fontTTf->renderCharAt(it->second.letteCharUTF16,_currentPageOrigX,_currentPageOrigY,_currentPageData,PAGE_WIDTH); it->second.U = _currentPageOrigX - 1; it->second.V = _currentPageOrigY; @@ -235,7 +235,7 @@ float FontAtlas::getCommonLineHeight() const void FontAtlas::setCommonLineHeight(float newHeight) { if(_makeDistanceMap) - newHeight += 2 * Font::DistanceMapSpread; + newHeight += 2 * FontFreeType::DistanceMapSpread; _commonLineHeight = newHeight; } diff --git a/cocos/2d/CCFontAtlas.h b/cocos/2d/CCFontAtlas.h index b4122e1294..d938e417a6 100644 --- a/cocos/2d/CCFontAtlas.h +++ b/cocos/2d/CCFontAtlas.h @@ -49,6 +49,7 @@ struct FontLetterDefinition float anchorX; float anchorY; bool validDefinition; + int xAdvance; }; class CC_DLL FontAtlas : public Object diff --git a/cocos/2d/CCFontAtlasCache.cpp b/cocos/2d/CCFontAtlasCache.cpp index ce0f18a54e..1701ac3701 100644 --- a/cocos/2d/CCFontAtlasCache.cpp +++ b/cocos/2d/CCFontAtlasCache.cpp @@ -26,8 +26,10 @@ #include #include "CCFontAtlasCache.h" -#include "CCFontAtlasFactory.h" +#include "CCFontFNT.h" +#include "CCFontFreeType.h" +#include "CCFontCharMap.h" NS_CC_BEGIN @@ -40,15 +42,24 @@ FontAtlas * FontAtlasCache::getFontAtlasTTF(const std::string& fontFileName, int if ( !tempAtlas ) { - tempAtlas = FontAtlasFactory::createAtlasFromTTF(fontFileName, size, glyphs, customGlyphs, useDistanceField); - if (tempAtlas) - _atlasMap[atlasName] = tempAtlas; + FontFreeType *font = FontFreeType::create(fontFileName, size, glyphs, customGlyphs); + if (font) + { + font->setDistanceFieldEnabled(useDistanceField); + tempAtlas = font->createFontAtlas(); + if (tempAtlas) + _atlasMap[atlasName] = tempAtlas; + } + else + { + return nullptr; + } } else { tempAtlas->retain(); } - + return tempAtlas; } @@ -59,9 +70,18 @@ FontAtlas * FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName) if ( !tempAtlas ) { - tempAtlas = FontAtlasFactory::createAtlasFromFNT(fontFileName); - if (tempAtlas) - _atlasMap[atlasName] = tempAtlas; + Font *font = FontFNT::create(fontFileName); + + if(font) + { + tempAtlas = font->createFontAtlas(); + if (tempAtlas) + _atlasMap[atlasName] = tempAtlas; + } + else + { + return nullptr; + } } else { @@ -78,9 +98,18 @@ FontAtlas * FontAtlasCache::getFontAtlasCharMap(const std::string& plistFile) if ( !tempAtlas ) { - tempAtlas = FontAtlasFactory::createAtlasFromCharMap(plistFile); - if (tempAtlas) - _atlasMap[atlasName] = tempAtlas; + Font *font = FontCharMap::create(plistFile); + + if(font) + { + tempAtlas = font->createFontAtlas(); + if (tempAtlas) + _atlasMap[atlasName] = tempAtlas; + } + else + { + return nullptr; + } } else { @@ -99,9 +128,18 @@ FontAtlas * FontAtlasCache::getFontAtlasCharMap(Texture2D* texture, int itemWidt if ( !tempAtlas ) { - tempAtlas = FontAtlasFactory::createAtlasFromCharMap(texture,itemWidth,itemHeight,startCharMap); - if (tempAtlas) - _atlasMap[atlasName] = tempAtlas; + Font *font = FontCharMap::create(texture,itemWidth,itemHeight,startCharMap); + + if(font) + { + tempAtlas = font->createFontAtlas(); + if (tempAtlas) + _atlasMap[atlasName] = tempAtlas; + } + else + { + return nullptr; + } } else { @@ -118,9 +156,18 @@ FontAtlas * FontAtlasCache::getFontAtlasCharMap(const std::string& charMapFile, if ( !tempAtlas ) { - tempAtlas = FontAtlasFactory::createAtlasFromCharMap(charMapFile,itemWidth,itemHeight,startCharMap); - if (tempAtlas) - _atlasMap[atlasName] = tempAtlas; + Font *font = FontCharMap::create(charMapFile,itemWidth,itemHeight,startCharMap); + + if(font) + { + tempAtlas = font->createFontAtlas(); + if (tempAtlas) + _atlasMap[atlasName] = tempAtlas; + } + else + { + return nullptr; + } } else { diff --git a/cocos/2d/CCFontAtlasFactory.cpp b/cocos/2d/CCFontAtlasFactory.cpp deleted file mode 100644 index 3b6d536223..0000000000 --- a/cocos/2d/CCFontAtlasFactory.cpp +++ /dev/null @@ -1,105 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 Zynga Inc. - Copyright (c) 2013-2014 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "CCFontAtlasFactory.h" -#include "CCFontFNT.h" - -// carloX this NEEDS to be changed -#include "CCLabelBMFont.h" - -NS_CC_BEGIN - -FontAtlas * FontAtlasFactory::createAtlasFromTTF(const std::string& fntFilePath, int fontSize, GlyphCollection glyphs, const char *customGlyphs, bool useDistanceField) -{ - - Font *font = Font::createWithTTF(fntFilePath, fontSize, glyphs, customGlyphs); - if (font) - { - font->setDistanceFieldEnabled(useDistanceField); - return font->createFontAtlas(); - } - else - { - return nullptr; - } -} - -FontAtlas * FontAtlasFactory::createAtlasFromFNT(const std::string& fntFilePath) -{ - Font *font = Font::createWithFNT(fntFilePath); - - if(font) - { - return font->createFontAtlas(); - } - else - { - return nullptr; - } -} - -FontAtlas * FontAtlasFactory::createAtlasFromCharMap(const std::string& plistFile) -{ - Font *font = Font::createWithCharMap(plistFile); - - if(font) - { - return font->createFontAtlas(); - } - else - { - return nullptr; - } -} - -FontAtlas * FontAtlasFactory::createAtlasFromCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap) -{ - Font *font = Font::createWithCharMap(texture,itemWidth,itemHeight,startCharMap); - - if(font) - { - return font->createFontAtlas(); - } - else - { - return nullptr; - } -} - -FontAtlas * FontAtlasFactory::createAtlasFromCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) -{ - Font *font = Font::createWithCharMap(charMapFile,itemWidth,itemHeight,startCharMap); - - if(font) - { - return font->createFontAtlas(); - } - else - { - return nullptr; - } -} - -NS_CC_END diff --git a/cocos/2d/CCFontAtlasFactory.h b/cocos/2d/CCFontAtlasFactory.h deleted file mode 100644 index 7c97430fa4..0000000000 --- a/cocos/2d/CCFontAtlasFactory.h +++ /dev/null @@ -1,52 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 Zynga Inc. - Copyright (c) 2013-2014 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#ifndef _CCFontAtlasFactory_h_ -#define _CCFontAtlasFactory_h_ - -#include "CCFontAtlas.h" -#include "CCLabel.h" - - -NS_CC_BEGIN - -class CC_DLL FontAtlasFactory -{ - -public: - - static FontAtlas * createAtlasFromTTF(const std::string& fntFilePath, int fontSize, GlyphCollection glyphs, const char *customGlyphs = 0, bool useDistanceField = false); - static FontAtlas * createAtlasFromFNT(const std::string& fntFilePath); - - static FontAtlas * createAtlasFromCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); - static FontAtlas * createAtlasFromCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); - static FontAtlas * createAtlasFromCharMap(const std::string& plistFile); - -private: -}; - -NS_CC_END - -#endif /* defined(_CCFontAtlasFactory_h_) */ diff --git a/cocos/2d/CCFontCharMap.cpp b/cocos/2d/CCFontCharMap.cpp index 3036295315..2c60978639 100644 --- a/cocos/2d/CCFontCharMap.cpp +++ b/cocos/2d/CCFontCharMap.cpp @@ -99,7 +99,7 @@ FontCharMap::~FontCharMap() } -Size * FontCharMap::getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const +int * FontCharMap::getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const { if (!text) return 0; @@ -109,14 +109,13 @@ Size * FontCharMap::getAdvancesForTextUTF16(unsigned short *text, int &outNumLet if (!outNumLetters) return 0; - Size *sizes = new Size[outNumLetters]; + int *sizes = new int[outNumLetters]; if (!sizes) return 0; - int advance = _itemWidth * CC_CONTENT_SCALE_FACTOR(); for (int c = 0; c < outNumLetters; ++c) { - sizes[c].width = advance; + sizes[c] = 0; } return sizes; @@ -149,10 +148,9 @@ FontAtlas * FontCharMap::createFontAtlas() tempDefinition.validDefinition = true; tempDefinition.width = _itemWidth; tempDefinition.height = _itemHeight; + tempDefinition.xAdvance = _itemWidth * CC_CONTENT_SCALE_FACTOR(); int charId = _mapStartChar; - float itemWidthInPixels = _itemWidth * CC_CONTENT_SCALE_FACTOR(); - float itemHeightInPixels = _itemHeight * CC_CONTENT_SCALE_FACTOR(); for (int row = 0; row < itemsPerColumn; ++row) { for (int col = 0; col < itemsPerRow; ++col) diff --git a/cocos/2d/CCFontCharMap.h b/cocos/2d/CCFontCharMap.h index a39b5f7032..92fbfd519b 100644 --- a/cocos/2d/CCFontCharMap.h +++ b/cocos/2d/CCFontCharMap.h @@ -37,7 +37,7 @@ public: static FontCharMap * create(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); static FontCharMap * create(const std::string& plistFile); - virtual Size* getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const override; + virtual int* getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const override; virtual Rect getRectForChar(unsigned short theChar) const override; virtual FontAtlas *createFontAtlas() override; diff --git a/cocos/2d/CCFontDefinition.cpp b/cocos/2d/CCFontDefinition.cpp deleted file mode 100644 index ebb79f3172..0000000000 --- a/cocos/2d/CCFontDefinition.cpp +++ /dev/null @@ -1,235 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 Zynga Inc. - Copyright (c) 2013-2014 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - - -#include "CCFontDefinition.h" -#include "CCDirector.h" - -NS_CC_BEGIN - -const int FontDefinitionTTF::DEFAUL_ATLAS_TEXTURE_SIZE = 1024; - -FontDefinitionTTF::FontDefinitionTTF():_textImages(0), _commonLineHeight(0) -{ -} - -FontDefinitionTTF* FontDefinitionTTF::create(Font *font, int textureSize) -{ - if (textureSize == 0) - textureSize = DEFAUL_ATLAS_TEXTURE_SIZE; - - FontDefinitionTTF *ret = new FontDefinitionTTF; - - if (!ret) - return 0; - - const char *glyph = font->getCurrentGlyphCollection(); - if (!glyph) - return nullptr; - - if (ret->initDefinition(font, glyph, textureSize)) - { - ret->autorelease(); - return ret; - } - else - { - delete ret; - return 0; - } -} - -FontDefinitionTTF::~FontDefinitionTTF() -{ - if (_textImages) - { - delete _textImages; - } -} - -bool FontDefinitionTTF::prepareLetterDefinitions(TextFontPagesDef *pageDefs) -{ - // get all the pages - TextFontPagesDef *pages = pageDefs; - if (!pages) - return (false); - - float maxLineHeight = -1; - - // loops all the pages - for (int cPages = 0; cPages < pages->getNumPages(); ++cPages) - { - // loops all the lines in this page - for (int cLines = 0; cLinesgetPageAt(cPages)->getNumLines(); ++cLines) - { - float posXUV = 0.0; - float posYUV = pages->getPageAt(cPages)->getLineAt(cLines)->getY(); - - int charsCounter = 0; - - for (int c = 0; c < pages->getPageAt(cPages)->getLineAt(cLines)->getNumGlyph(); ++c) - { - // the current glyph - GlyphDef currentGlyph = pages->getPageAt(cPages)->getLineAt(cLines)->getGlyphAt(c); - - // letter width - float letterWidth = currentGlyph.getRect().size.width; - - // letter height - float letterHeight = pages->getPageAt(cPages)->getLineAt(cLines)->getHeight(); - - // add this letter definition - FontLetterDefinition tempDef; - - - // carloX little hack (this should be done outside the loop) - if (posXUV == 0.0) - posXUV = currentGlyph.getPadding(); - - tempDef.validDefinition = currentGlyph.isValid(); - - if (tempDef.validDefinition) - { - tempDef.letteCharUTF16 = currentGlyph.getUTF8Letter(); - tempDef.width = letterWidth + currentGlyph.getPadding(); - tempDef.height = (letterHeight - 1); - tempDef.U = (posXUV - 1); - tempDef.V = posYUV; - tempDef.offsetX = currentGlyph.getRect().origin.x; - tempDef.offsetY = currentGlyph.getRect().origin.y; - tempDef.textureID = cPages; - tempDef.commonLineHeight = currentGlyph.getCommonHeight(); - - // take from pixels to points - tempDef.width = tempDef.width / CC_CONTENT_SCALE_FACTOR(); - tempDef.height = tempDef.height / CC_CONTENT_SCALE_FACTOR(); - tempDef.U = tempDef.U / CC_CONTENT_SCALE_FACTOR(); - tempDef.V = tempDef.V / CC_CONTENT_SCALE_FACTOR(); - - if (tempDef.commonLineHeight>maxLineHeight) - maxLineHeight = tempDef.commonLineHeight; - } - else - { - tempDef.letteCharUTF16 = currentGlyph.getUTF8Letter(); - tempDef.commonLineHeight = 0; - tempDef.width = 0; - tempDef.height = 0; - tempDef.U = 0; - tempDef.V = 0; - tempDef.offsetX = 0; - tempDef.offsetY = 0; - tempDef.textureID = 0; - } - - - // add this definition - addLetterDefinition(tempDef); - - // move bounding box to the next letter - posXUV += letterWidth + currentGlyph.getPadding(); - - // next char in the string - ++charsCounter; - } - } - } - - // store the common line height - _commonLineHeight = maxLineHeight; - - // - return true; -} - -bool FontDefinitionTTF::initDefinition(cocos2d::Font *font, const char *letters, int textureSize) -{ - // preare texture/image stuff - _textImages = new TextImage(); - if (!_textImages) - return false; - - if (!_textImages->initWithString(letters, textureSize, textureSize, font, true)) - { - delete _textImages; - _textImages = 0; - return false; - } - - // prepare the new letter definition - return prepareLetterDefinitions(_textImages->getPages()); -} - -void FontDefinitionTTF::addLetterDefinition(const FontLetterDefinition &defToAdd) -{ - if (_fontLettersDefinitionUTF16.find(defToAdd.letteCharUTF16) == _fontLettersDefinitionUTF16.end()) - { - _fontLettersDefinitionUTF16[defToAdd.letteCharUTF16] = defToAdd; - } -} - -FontAtlas * FontDefinitionTTF::createFontAtlas() -{ - int numTextures = 0; - TextFontPagesDef *pages = _textImages->getPages(); - - if (pages) - numTextures = pages->getNumPages(); - else - return nullptr; - - if (!numTextures) - return nullptr; - - FontAtlas *retAtlas = new FontAtlas(*_textImages->getFont()); - - if (!retAtlas) - return 0; - - for (int c = 0; c < numTextures; ++c) - { - TextFontPagesDef *pPages = _textImages->getPages(); - retAtlas->addTexture(*(pPages->getPageAt(c)->getPageTexture()), c); - } - - // set the common line height - retAtlas->setCommonLineHeight(_commonLineHeight * 0.8); - - for( auto &item: _fontLettersDefinitionUTF16 ) - { - if ( item.second.validDefinition ) - { - FontLetterDefinition tempDefinition = item.second; - tempDefinition.anchorX = 0.0f; - tempDefinition.anchorY = 1.0f; - retAtlas->addLetterDefinition(tempDefinition); - } - } - - // done here - return retAtlas; -} - -NS_CC_END diff --git a/cocos/2d/CCFontDefinition.h b/cocos/2d/CCFontDefinition.h deleted file mode 100644 index 5bec2bb098..0000000000 --- a/cocos/2d/CCFontDefinition.h +++ /dev/null @@ -1,70 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 Zynga Inc. - Copyright (c) 2013-2014 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#ifndef _FontDefinition_h_ -#define _FontDefinition_h_ - -#include - -#include "CCTextImage.h" -#include "CCFont.h" -#include "CCFontAtlas.h" - -NS_CC_BEGIN - -/** - */ -class CC_DLL FontDefinitionTTF : public Object -{ -public: - - static FontDefinitionTTF* create(Font *font, int textureSize = 0); - FontAtlas * createFontAtlas(); - -private: - /** - * @js ctor - */ - FontDefinitionTTF(); - /** - * @js NA - * @lua NA - */ - ~FontDefinitionTTF(); - - bool initDefinition(Font *font, const char *letters, int textureSize); - bool prepareLetterDefinitions(TextFontPagesDef *pageDefs); - void addLetterDefinition(const FontLetterDefinition &defToAdd); - - TextImage * _textImages; - std::unordered_map _fontLettersDefinitionUTF16; - float _commonLineHeight; - - static const int DEFAUL_ATLAS_TEXTURE_SIZE; -}; - -NS_CC_END - -#endif diff --git a/cocos/2d/CCFontFNT.cpp b/cocos/2d/CCFontFNT.cpp index 53eade4046..a2ffa45fa3 100644 --- a/cocos/2d/CCFontFNT.cpp +++ b/cocos/2d/CCFontFNT.cpp @@ -62,7 +62,7 @@ FontFNT::~FontFNT() } -Size * FontFNT::getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const +int * FontFNT::getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const { if (!text) return 0; @@ -72,39 +72,21 @@ Size * FontFNT::getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters if (!outNumLetters) return 0; - Size *sizes = new Size[outNumLetters]; + int *sizes = new int[outNumLetters]; if (!sizes) return 0; for (int c = 0; c < outNumLetters; ++c) { - int advance = 0; - int kerning = 0; - - advance = getAdvanceForChar(text[c]); - if (c < (outNumLetters-1)) - kerning = getHorizontalKerningForChars(text[c], text[c+1]); - - sizes[c].width = (advance + kerning); + sizes[c] = getHorizontalKerningForChars(text[c], text[c+1]); + else + sizes[c] = 0; } return sizes; } -int FontFNT::getAdvanceForChar(unsigned short theChar) const -{ - tFontDefHashElement *element = nullptr; - - // unichar is a short, and an int is needed on HASH_FIND_INT - unsigned int key = theChar; - HASH_FIND_INT(_configuration->_fontDefDictionary, &key, element); - if (! element) - return -1; - - return element->fontDef.xAdvance; -} - int FontFNT::getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const { int ret = 0; @@ -194,9 +176,8 @@ FontAtlas * FontFNT::createFontAtlas() //carloX: only one texture supported FOR NOW tempDefinition.textureID = 0; - tempDefinition.anchorX = 0.5f; - tempDefinition.anchorY = 0.5f; tempDefinition.validDefinition = true; + tempDefinition.xAdvance = fontDef.xAdvance; // add the new definition tempAtlas->addLetterDefinition(tempDefinition); } diff --git a/cocos/2d/CCFontFNT.h b/cocos/2d/CCFontFNT.h index 85588a662a..563c8bff93 100644 --- a/cocos/2d/CCFontFNT.h +++ b/cocos/2d/CCFontFNT.h @@ -39,7 +39,7 @@ public: static FontFNT * create(const std::string& fntFilePath); - virtual Size* getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const override; + virtual int* getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const override; virtual Rect getRectForChar(unsigned short theChar) const override; virtual FontAtlas *createFontAtlas() override; @@ -55,7 +55,6 @@ protected: private: - int getAdvanceForChar(unsigned short theChar) const; int getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const; Rect getRectForCharInternal(unsigned short theChar) const; diff --git a/cocos/2d/CCFontFreeType.cpp b/cocos/2d/CCFontFreeType.cpp index c503611b71..d867157065 100644 --- a/cocos/2d/CCFontFreeType.cpp +++ b/cocos/2d/CCFontFreeType.cpp @@ -28,24 +28,19 @@ THE SOFTWARE. #include "ccUTF8.h" #include "CCFontFreeType.h" -#include "CCTextImage.h" -#include "CCFont.h" -#include "CCFontDefinition.h" #include "platform/CCFileUtils.h" +#include "edtaa3func.h" NS_CC_BEGIN FT_Library FontFreeType::_FTlibrary; bool FontFreeType::_FTInitialized = false; +const int FontFreeType::DistanceMapSpread = 3; FontFreeType * FontFreeType::create(const std::string &fontName, int fontSize, GlyphCollection glyphs, const char *customGlyphs) { - bool dynamicGlyphCollection = false; - if(glyphs == GlyphCollection::DYNAMIC) - dynamicGlyphCollection = true; - - FontFreeType *tempFont = new FontFreeType(dynamicGlyphCollection); + FontFreeType *tempFont = new FontFreeType(); if (!tempFont) return nullptr; @@ -89,13 +84,11 @@ FT_Library FontFreeType::getFTLibrary() return _FTlibrary; } -FontFreeType::FontFreeType(bool dynamicGlyphCollection) +FontFreeType::FontFreeType() : _fontRef(nullptr), -_letterPadding(5), -_dynamicGlyphCollection(dynamicGlyphCollection) +_letterPadding(5) +,_distanceFieldEnabled(false) { - if(_distanceFieldEnabled) - _letterPadding += 2 * DistanceMapSpread; } bool FontFreeType::createFontObject(const std::string &fontName, int fontSize) @@ -141,26 +134,16 @@ FontFreeType::~FontFreeType() FontAtlas * FontFreeType::createFontAtlas() { - if (_dynamicGlyphCollection) + FontAtlas *atlas = new FontAtlas(*this); + if (_usedGlyphs != GlyphCollection::DYNAMIC) { - FontAtlas *atlas = new FontAtlas(*this); - this->release(); - return atlas; - } - else - { - FontDefinitionTTF *def = FontDefinitionTTF::create(this); - - if (!def) - return nullptr; - - FontAtlas *atlas = def->createFontAtlas(); - - return atlas; - } + atlas->prepareLetterDefinitions(cc_utf8_to_utf16(getCurrentGlyphCollection())); + } + this->release(); + return atlas; } -bool FontFreeType::getBBOXFotChar(unsigned short theChar, Rect &outRect) const +bool FontFreeType::getBBOXFotChar(unsigned short theChar, Rect &outRect, int &xAdvance) const { if (!_fontRef) return false; @@ -181,75 +164,12 @@ bool FontFreeType::getBBOXFotChar(unsigned short theChar, Rect &outRect) const outRect.size.width = (_fontRef->glyph->metrics.width >> 6); outRect.size.height = (_fontRef->glyph->metrics.height >> 6); + xAdvance = (static_cast(_fontRef->glyph->metrics.horiAdvance >> 6)); + return true; } -GlyphDef * FontFreeType::getGlyphDefintionsForText(const char *text, int &outNumGlyphs, bool UTF16text) const -{ - unsigned short* utf16String = 0; - - if (UTF16text) - { - utf16String = (unsigned short*) text; - } - else - { - utf16String = cc_utf8_to_utf16(text); - } - - // - if (!utf16String) - return 0; - - int numChar = cc_wcslen(utf16String); - if (!numChar) - return 0; - - // allocate the needed Glyphs - GlyphDef *glyphs = new GlyphDef[numChar]; - assert(glyphs != nullptr); - if (!glyphs) - return 0; - - // sore result as CCRect - for (int c = 0; c < numChar; ++c) - { - Rect tempRect; - - if (!getBBOXFotChar(utf16String[c], tempRect)) - { - log("Warning: Cannot find definition for glyph: %c in font:%s", utf16String[c], _fontName.c_str()); - - tempRect.origin.x = 0; - tempRect.origin.y = 0; - tempRect.size.width = 0; - tempRect.size.height = 0; - - glyphs[c].setRect(tempRect); - glyphs[c].setUTF16Letter(utf16String[c]); - glyphs[c].setValid(false); - glyphs[c].setPadding(_letterPadding); - } - else - { - glyphs[c].setRect(tempRect); - glyphs[c].setUTF16Letter(utf16String[c]); - glyphs[c].setPadding(_letterPadding); - glyphs[c].setValid(true); - } - } - - outNumGlyphs = numChar; - - // free memory - if (!UTF16text) - delete [] utf16String; - - // done - return glyphs; -} - -Size * FontFreeType::getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const +int * FontFreeType::getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const { if (!text) return 0; @@ -259,64 +179,21 @@ Size * FontFreeType::getAdvancesForTextUTF16(unsigned short *text, int &outNumLe if (!outNumLetters) return 0; - Size *sizes = new Size[outNumLetters]; + int *sizes = new int[outNumLetters]; if (!sizes) return 0; for (int c = 0; c < outNumLetters; ++c) { - int advance = 0; - int kerning = 0; - - advance = getAdvanceForChar(text[c]); - if (c < (outNumLetters-1)) - kerning = getHorizontalKerningForChars(text[c], text[c+1]); - - sizes[c].width = (advance + kerning); + sizes[c] = getHorizontalKerningForChars(text[c], text[c+1]); + else + sizes[c] = 0; } return sizes; } -int FontFreeType::getAdvanceForChar(unsigned short theChar) const -{ - if (!_fontRef) - return 0; - - // get the ID to the char we need - int glyph_index = FT_Get_Char_Index(_fontRef, theChar); - - if (!glyph_index) - return 0; - - // load glyph infos - if (FT_Load_Glyph(_fontRef, glyph_index, FT_LOAD_DEFAULT)) - return 0; - - // get to the advance for this glyph - return (static_cast(_fontRef->glyph->metrics.horiAdvance >> 6)); -} - -int FontFreeType::getBearingXForChar(unsigned short theChar) const -{ - - if (!_fontRef) - return 0; - - // get the ID to the char we need - int glyphIndex = FT_Get_Char_Index(_fontRef, theChar); - - if (!glyphIndex) - return 0; - - // load glyph infos - if (FT_Load_Glyph(_fontRef, glyphIndex, FT_LOAD_DEFAULT)) - return 0; - - return (static_cast(_fontRef->glyph->metrics.horiBearingX >>6)); -} - int FontFreeType::getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const { if (!_fontRef) @@ -380,4 +257,164 @@ int FontFreeType::getLetterPadding() const return _letterPadding; } +unsigned char * makeDistanceMap( unsigned char *img, unsigned int width, unsigned int height) +{ + unsigned int pixelAmount = (width + 2 * FontFreeType::DistanceMapSpread) * (height + 2 * FontFreeType::DistanceMapSpread); + + short * xdist = (short *) malloc( pixelAmount * sizeof(short) ); + short * ydist = (short *) malloc( pixelAmount * sizeof(short) ); + double * gx = (double *) calloc( pixelAmount, sizeof(double) ); + double * gy = (double *) calloc( pixelAmount, sizeof(double) ); + double * data = (double *) calloc( pixelAmount, sizeof(double) ); + double * outside = (double *) calloc( pixelAmount, sizeof(double) ); + double * inside = (double *) calloc( pixelAmount, sizeof(double) ); + unsigned int i,j; + + // Convert img into double (data) rescale image levels between 0 and 1 + unsigned int outWidth = width + 2 * FontFreeType::DistanceMapSpread; + for (i = 0; i < width; ++i) + { + for (j = 0; j < height; ++j) + { + data[j * outWidth + FontFreeType::DistanceMapSpread + i] = img[j * width + i] / 255.0; + } + } + + width += 2 * FontFreeType::DistanceMapSpread; + height += 2 * FontFreeType::DistanceMapSpread; + + // Transform background (outside contour, in areas of 0's) + computegradient( data, width, height, gx, gy); + edtaa3(data, gx, gy, width, height, xdist, ydist, outside); + for( i=0; i< pixelAmount; i++) + if( outside[i] < 0.0 ) + outside[i] = 0.0; + + // Transform foreground (inside contour, in areas of 1's) + for( i=0; i< pixelAmount; i++) + data[i] = 1 - data[i]; + computegradient( data, width, height, gx, gy); + edtaa3(data, gx, gy, width, height, xdist, ydist, inside); + for( i=0; i< pixelAmount; i++) + if( inside[i] < 0.0 ) + inside[i] = 0.0; + + // The bipolar distance field is now outside-inside + double dist; + /* Single channel 8-bit output (bad precision and range, but simple) */ + unsigned char *out = (unsigned char *) malloc( pixelAmount * sizeof(unsigned char) ); + for( i=0; i < pixelAmount; i++) + { + dist = outside[i] - inside[i]; + dist = 128.0 - dist*16; + if( dist < 0 ) dist = 0; + if( dist > 255 ) dist = 255; + out[i] = (unsigned char) dist; + } + /* Dual channel 16-bit output (more complicated, but good precision and range) */ + /*unsigned char *out = (unsigned char *) malloc( pixelAmount * 3 * sizeof(unsigned char) ); + for( i=0; i< pixelAmount; i++) + { + dist = outside[i] - inside[i]; + dist = 128.0 - dist*16; + if( dist < 0.0 ) dist = 0.0; + if( dist >= 256.0 ) dist = 255.999; + // R channel is a copy of the original grayscale image + out[3*i] = img[i]; + // G channel is fraction + out[3*i + 1] = (unsigned char) ( 256 - (dist - floor(dist)* 256.0 )); + // B channel is truncated integer part + out[3*i + 2] = (unsigned char)dist; + }*/ + + free( xdist ); + free( ydist ); + free( gx ); + free( gy ); + free( data ); + free( outside ); + free( inside ); + + return out; +} + +void FontFreeType::setDistanceFieldEnabled(bool distanceFieldEnabled) +{ + if(distanceFieldEnabled) + _letterPadding += 2 * DistanceMapSpread; + _distanceFieldEnabled = distanceFieldEnabled; +} + +bool FontFreeType::renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize) +{ + unsigned char *sourceBitmap = 0; + int sourceWidth = 0; + int sourceHeight = 0; + + sourceBitmap = getGlyphBitmap(charToRender, sourceWidth, sourceHeight); + + if (!sourceBitmap) + return false; + + if (_distanceFieldEnabled) + { + unsigned char * out = makeDistanceMap(sourceBitmap,sourceWidth,sourceHeight); + + int iX = posX; + int iY = posY; + + sourceWidth += 2 * DistanceMapSpread; + sourceHeight += 2 * DistanceMapSpread; + + for (int y = 0; y < sourceHeight; ++y) + { + int bitmap_y = y * sourceWidth; + + for (int x = 0; x < sourceWidth; ++x) + { + /* Dual channel 16-bit output (more complicated, but good precision and range) */ + /*int index = (iX + ( iY * destSize )) * 3; + int index2 = (bitmap_y + x)*3; + destMemory[index] = out[index2]; + destMemory[index + 1] = out[index2 + 1]; + destMemory[index + 2] = out[index2 + 2];*/ + + //Single channel 8-bit output + destMemory[iX + ( iY * destSize )] = out[bitmap_y + x]; + + iX += 1; + } + + iX = posX; + iY += 1; + } + free(out); + return true; + } + + int iX = posX; + int iY = posY; + + for (int y = 0; y < sourceHeight; ++y) + { + int bitmap_y = y * sourceWidth; + + for (int x = 0; x < sourceWidth; ++x) + { + unsigned char cTemp = sourceBitmap[bitmap_y + x]; + + // the final pixel + destMemory[(iX + ( iY * destSize ) )] = cTemp; + + iX += 1; + } + + iX = posX; + iY += 1; + } + + //everything good + return true; +} + NS_CC_END \ No newline at end of file diff --git a/cocos/2d/CCFontFreeType.h b/cocos/2d/CCFontFreeType.h index bd86c5effc..45e3c2a17d 100644 --- a/cocos/2d/CCFontFreeType.h +++ b/cocos/2d/CCFontFreeType.h @@ -39,25 +39,28 @@ NS_CC_BEGIN class CC_DLL FontFreeType : public Font { public: - + static const int DistanceMapSpread; + static FontFreeType * create(const std::string &fontName, int fontSize, GlyphCollection glyphs, const char *customGlyphs); static void shutdownFreeType(); + void setDistanceFieldEnabled(bool distanceFieldEnabled); + bool isDistanceFieldEnabled() const { return _distanceFieldEnabled;} + bool renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize); + virtual FontAtlas * createFontAtlas() override; - virtual Size * getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const override; - virtual GlyphDef * getGlyphDefintionsForText(const char *text, int &outNumGlyphs, bool UTF16text = false) const override; + virtual int * getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const override; + unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) const override; virtual int getFontMaxHeight() const override; virtual int getLetterPadding() const override; - bool getBBOXFotChar(unsigned short theChar, Rect &outRect) const; - - inline bool isDynamicGlyphCollection() { return _dynamicGlyphCollection;} + bool getBBOXFotChar(unsigned short theChar, Rect &outRect,int &xAdvance) const; protected: - FontFreeType(bool dynamicGlyphCollection = false); + FontFreeType(); virtual ~FontFreeType(); bool createFontObject(const std::string &fontName, int fontSize); @@ -66,8 +69,6 @@ private: bool initFreeType(); FT_Library getFTLibrary(); - int getAdvanceForChar(unsigned short theChar) const; - int getBearingXForChar(unsigned short theChar) const; int getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const; static FT_Library _FTlibrary; @@ -76,7 +77,7 @@ private: int _letterPadding; std::string _fontName; Data _ttfData; - bool _dynamicGlyphCollection; + bool _distanceFieldEnabled; }; NS_CC_END diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index 0cac300283..95410695f4 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -24,7 +24,6 @@ ****************************************************************************/ #include "CCLabel.h" -#include "CCFontDefinition.h" #include "CCFontAtlasCache.h" #include "CCLabelTextFormatter.h" #include "CCSprite.h" @@ -33,6 +32,7 @@ #include "CCSpriteFrame.h" #include "CCDirector.h" #include "renderer/CCRenderer.h" +#include "CCFont.h" #define DISTANCEFIELD_ATLAS_FONTSIZE 50 @@ -193,7 +193,7 @@ Label::Label(FontAtlas *atlas, TextHAlignment alignment, bool useDistanceField,b , _alignment(alignment) , _currentUTF16String(nullptr) , _originalUTF16String(nullptr) -, _advances(nullptr) +, _horizontalKernings(nullptr) , _fontAtlas(atlas) , _isOpacityModifyRGB(true) , _useDistanceField(useDistanceField) @@ -208,7 +208,7 @@ Label::~Label() { delete [] _currentUTF16String; delete [] _originalUTF16String; - delete [] _advances; + delete [] _horizontalKernings; if (_fontAtlas) FontAtlasCache::releaseFontAtlas(_fontAtlas); @@ -226,6 +226,7 @@ bool Label::init() _reusedLetter = Sprite::createWithTexture(&_fontAtlas->getTexture(0)); _reusedLetter->setOpacityModifyRGB(_isOpacityModifyRGB); _reusedLetter->retain(); + _reusedLetter->setAnchorPoint(Point::ANCHOR_TOP_LEFT); } ret = SpriteBatchNode::initWithTexture(&_fontAtlas->getTexture(0), 30); } @@ -474,18 +475,18 @@ void Label::alignText() } } -bool Label::computeAdvancesForString(unsigned short int *stringToRender) +bool Label::computeHorizontalKernings(unsigned short int *stringToRender) { - if (_advances) + if (_horizontalKernings) { - delete [] _advances; - _advances = 0; + delete [] _horizontalKernings; + _horizontalKernings = 0; } int letterCount = 0; - _advances = _fontAtlas->getFont()->getAdvancesForTextUTF16(stringToRender, letterCount); + _horizontalKernings = _fontAtlas->getFont()->getHorizontalKerningForTextUTF16(stringToRender, letterCount); - if(!_advances) + if(!_horizontalKernings) return false; else return true; @@ -519,7 +520,7 @@ bool Label::setCurrentString(unsigned short *stringToSet) // _currentUTF16String = stringToSet; // compute the advances - return computeAdvancesForString(stringToSet); + return computeHorizontalKernings(stringToSet); } void Label::resetCurrentString() @@ -558,10 +559,8 @@ Sprite * Label::updateSpriteWithLetterDefinition(Sprite *spriteToUpdate, const F SpriteFrame *frame = SpriteFrame::createWithTexture(theTexture, uvRect); if (frame) { - spriteToUpdate->setBatchNode(this); - spriteToUpdate->setTexture(theTexture); - spriteToUpdate->setSpriteFrame(frame); - spriteToUpdate->setAnchorPoint(Point(theDefinition.anchorX, theDefinition.anchorY)); + spriteToUpdate->setBatchNode(this); + spriteToUpdate->setSpriteFrame(frame); } return spriteToUpdate; @@ -692,8 +691,8 @@ Sprite * Label::getLetter(int ID) sp = Sprite::createWithTexture(&_fontAtlas->getTexture(_lettersInfo[ID].def.textureID),uvRect); sp->setBatchNode(this); - sp->setAnchorPoint(Point(_lettersInfo[ID].def.anchorX, _lettersInfo[ID].def.anchorY)); - sp->setPosition(_lettersInfo[ID].position); + sp->setAnchorPoint(Point::ANCHOR_MIDDLE); + sp->setPosition(Point(_lettersInfo[ID].position.x+uvRect.size.width/2,_lettersInfo[ID].position.y-uvRect.size.height/2)); sp->setOpacity(_realOpacity); this->addSpriteWithoutQuad(sp, ID, ID); @@ -706,12 +705,12 @@ Sprite * Label::getLetter(int ID) float Label::getLetterPosXLeft( int index ) const { - return _lettersInfo[index].position.x * _scaleX - (_lettersInfo[index].contentSize.width * _scaleX * _lettersInfo[index].def.anchorX); + return _lettersInfo[index].position.x * _scaleX; } float Label::getLetterPosXRight( int index ) const { - return _lettersInfo[index].position.x * _scaleX + (_lettersInfo[index].contentSize.width * _scaleX * _lettersInfo[index].def.anchorX); + return (_lettersInfo[index].position.x + _lettersInfo[index].contentSize.width) * _scaleX; } int Label::getCommonLineHeight() const @@ -719,9 +718,16 @@ int Label::getCommonLineHeight() const return _commonLineHeight; } -int Label::getKerningForCharsPair(unsigned short first, unsigned short second) const +int Label::getKerningInString(int hintPositionInString) const { - return 0; + if (_horizontalKernings) + { + return (_horizontalKernings[hintPositionInString]); + } + else + { + return -1; + } } int Label::getXOffsetForChar(unsigned short c) const @@ -746,7 +752,7 @@ int Label::getYOffsetForChar(unsigned short c) const int Label::getAdvanceForChar(unsigned short c, int hintPositionInString) const { - if (_advances) + if (_horizontalKernings) { // not that advance contains the X offset already FontLetterDefinition tempDefinition; @@ -754,7 +760,7 @@ int Label::getAdvanceForChar(unsigned short c, int hintPositionInString) const if (!validDefinition) return -1; - return (_advances[hintPositionInString].width); + return tempDefinition.xAdvance; } else { diff --git a/cocos/2d/CCLabel.h b/cocos/2d/CCLabel.h index b34507312e..fc8328ed82 100644 --- a/cocos/2d/CCLabel.h +++ b/cocos/2d/CCLabel.h @@ -123,7 +123,7 @@ public: // font related stuff virtual int getCommonLineHeight() const override; - virtual int getKerningForCharsPair(unsigned short first, unsigned short second) const override; + virtual int getKerningInString(int hintPositionInString) const override; virtual int getXOffsetForChar(unsigned short c) const override; virtual int getYOffsetForChar(unsigned short c) const override; virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) const override; @@ -170,7 +170,7 @@ private: void alignText(); - bool computeAdvancesForString(unsigned short int *stringToRender); + bool computeHorizontalKernings(unsigned short int *stringToRender); bool setCurrentString(unsigned short *stringToSet); bool setOriginalString(unsigned short *stringToSet); void resetCurrentString(); @@ -189,7 +189,7 @@ private: TextHAlignment _alignment; unsigned short int * _currentUTF16String; unsigned short int * _originalUTF16String; - Size * _advances; + int * _horizontalKernings; FontAtlas * _fontAtlas; bool _isOpacityModifyRGB; diff --git a/cocos/2d/CCLabelTextFormatProtocol.h b/cocos/2d/CCLabelTextFormatProtocol.h index e91d7b875a..997d9ee753 100644 --- a/cocos/2d/CCLabelTextFormatProtocol.h +++ b/cocos/2d/CCLabelTextFormatProtocol.h @@ -61,7 +61,7 @@ public: // font related stuff virtual int getCommonLineHeight() const = 0; - virtual int getKerningForCharsPair(unsigned short first, unsigned short second) const = 0; + virtual int getKerningInString(int hintPositionInString) const = 0; virtual int getXOffsetForChar(unsigned short c) const = 0; virtual int getYOffsetForChar(unsigned short c) const = 0; virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) const = 0; diff --git a/cocos/2d/CCLabelTextFormatter.cpp b/cocos/2d/CCLabelTextFormatter.cpp index 968d196f18..a5d8be7cda 100644 --- a/cocos/2d/CCLabelTextFormatter.cpp +++ b/cocos/2d/CCLabelTextFormatter.cpp @@ -35,70 +35,39 @@ NS_CC_BEGIN bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel) { - // to do if (m_fWidth > 0) - if (theLabel->getMaxLineWidth()) - { - // Step 1: Make multiline - vector strWhole = cc_utf16_vec_from_utf16_str(theLabel->getUTF8String()); - size_t stringLength = strWhole.size(); - - vector multiline_string; - multiline_string.reserve( stringLength ); - - vector last_word; - last_word.reserve( stringLength ); - - unsigned int line = 1, i = 0; - - bool isStartOfLine = false, isStartOfWord = false; - float startOfLine = -1, startOfWord = -1; - - int skip = 0; - - int strLen = theLabel->getStringLenght(); - std::vector *leterInfo = theLabel->getLettersInfo(); - int tIndex = 0; + int strLen = theLabel->getStringLenght(); + auto strWhole = theLabel->getUTF8String(); - for (int j = 0; j+skip < strLen; j++) - { - LetterInfo* info = &leterInfo->at(j+skip); + vector multiline_string; + multiline_string.reserve( strLen ); - unsigned int justSkipped = 0; - - while (info->def.validDefinition == false) - { - justSkipped++; - tIndex = j+skip+justSkipped; - if(tIndex < strLen) - info = &leterInfo->at( tIndex ); - else - break; - } - skip += justSkipped; - tIndex = j + skip; - - if (tIndex >= stringLength) - break; - - unsigned short character = strWhole[tIndex]; - - if (!isStartOfWord) - { - startOfWord = theLabel->getLetterPosXLeft( tIndex ); - isStartOfWord = true; - } - - if (!isStartOfLine) - { - startOfLine = startOfWord; - isStartOfLine = true; - } - - // Newline. - if (character == '\n') + vector last_word; + last_word.reserve( strLen ); + + unsigned int line = 1; + + bool isStartOfLine = false, isStartOfWord = false; + float startOfLine = -1, startOfWord = -1; + + int skip = 0; + + std::vector *leterInfo = theLabel->getLettersInfo(); + int tIndex = 0; + + for (int j = 0; j+skip < strLen; j++) + { + LetterInfo* info = &leterInfo->at(j+skip); + + unsigned int justSkipped = 0; + + while (info->def.validDefinition == false) + { + justSkipped++; + tIndex = j+skip+justSkipped; + if (strWhole[tIndex-1] == '\n') { cc_utf8_trim_ws(&last_word); - + last_word.push_back('\n'); multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end()); last_word.clear(); @@ -106,119 +75,102 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel) isStartOfLine = false; startOfWord = -1; startOfLine = -1; - i += justSkipped; ++line; - - if (i >= stringLength) - break; - - character = strWhole[i]; - - if (!startOfWord) - { - startOfWord = theLabel->getLetterPosXLeft( tIndex ); - isStartOfWord = true; - } - if (!startOfLine) - { - startOfLine = startOfWord; - isStartOfLine = true; - } } - - // Whitespace. - if (isspace_unicode(character)) + if(tIndex < strLen) + { + info = &leterInfo->at( tIndex ); + } + else + break; + } + skip += justSkipped; + tIndex = j + skip; + + if (tIndex >= strLen) + break; + + unsigned short character = strWhole[tIndex]; + + if (!isStartOfWord) + { + startOfWord = theLabel->getLetterPosXLeft( tIndex ); + isStartOfWord = true; + } + + if (!isStartOfLine) + { + startOfLine = startOfWord; + isStartOfLine = true; + } + + // Whitespace. + if (isspace_unicode(character)) + { + last_word.push_back(character); + multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end()); + last_word.clear(); + isStartOfWord = false; + startOfWord = -1; + continue; + } + + // Out of bounds. + if (theLabel->getLetterPosXRight( tIndex ) - startOfLine > theLabel->getMaxLineWidth()) + { + if (!theLabel->breakLineWithoutSpace()) { last_word.push_back(character); - multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end()); - last_word.clear(); - isStartOfWord = false; - startOfWord = -1; - ++i; - continue; - } - - // Out of bounds. - if (theLabel->getLetterPosXRight( tIndex ) - startOfLine > theLabel->getMaxLineWidth()) - { - if (!theLabel->breakLineWithoutSpace()) - { - last_word.push_back(character); - - int found = cc_utf8_find_last_not_char(multiline_string, ' '); - if (found != -1) - cc_utf8_trim_ws(&multiline_string); - else - multiline_string.clear(); - - if (multiline_string.size() > 0) - multiline_string.push_back('\n'); - - ++line; - isStartOfLine = false; - startOfLine = -1; - ++i; - } + + int found = cc_utf8_find_last_not_char(multiline_string, ' '); + if (found != -1) + cc_utf8_trim_ws(&multiline_string); else - { - cc_utf8_trim_ws(&last_word); - - last_word.push_back('\n'); - multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end()); - last_word.clear(); - isStartOfWord = false; - isStartOfLine = false; - startOfWord = -1; - startOfLine = -1; - ++line; - - if (i >= stringLength) - break; - - if (!startOfWord) - { - startOfWord = theLabel->getLetterPosXLeft( tIndex ); - isStartOfWord = true; - } - if (!startOfLine) - { - startOfLine = startOfWord; - isStartOfLine = true; - } - - --j; - } - - continue; + multiline_string.clear(); + + if (multiline_string.size() > 0) + multiline_string.push_back('\n'); + + ++line; + isStartOfLine = false; + startOfLine = -1; } else { - // Character is normal. - last_word.push_back(character); - ++i; - continue; + cc_utf8_trim_ws(&last_word); + + last_word.push_back('\n'); + multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end()); + last_word.clear(); + isStartOfWord = false; + isStartOfLine = false; + startOfWord = -1; + startOfLine = -1; + ++line; + --j; } } - - multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end()); - - size_t size = multiline_string.size(); - unsigned short* strNew = new unsigned short[size + 1]; - - for (size_t j = 0; j < size; ++j) + else { - strNew[j] = multiline_string[j]; + // Character is normal. + last_word.push_back(character); } - - strNew[size] = 0; - theLabel->assignNewUTF8String(strNew); - - return true; } - else + + multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end()); + + size_t size = multiline_string.size(); + unsigned short* strNew = new unsigned short[size + 1]; + + for (size_t j = 0; j < size; ++j) { - return false; + strNew[j] = multiline_string[j]; } + + strNew[size] = 0; + theLabel->assignNewUTF8String(strNew); + + return true; } bool LabelTextFormatter::alignText(LabelTextFormatProtocol *theLabel) @@ -337,7 +289,7 @@ bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel) charAdvance = theLabel->getAdvanceForChar(c, i); charRect = theLabel->getRectForChar(c); - int kerningAmount = theLabel->getKerningForCharsPair(prev, c); + int kerningAmount = theLabel->getKerningInString(i); if (c == '\n') { @@ -351,9 +303,8 @@ bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel) // See issue 1343. cast( signed short + unsigned integer ) == unsigned integer (sign is lost!) int yOffset = commonLineHeight - charYOffset; - - Point fontPos = Point((float)nextFontPositionX + charXOffset + charRect.size.width * 0.5f + kerningAmount, - (float)nextFontPositionY + yOffset - charRect.size.height * 0.5f); + Point fontPos = Point((float)nextFontPositionX + charXOffset + kerningAmount, + (float)nextFontPositionY + yOffset); if( theLabel->recordLetterInfo(CC_POINT_PIXELS_TO_POINTS(fontPos),c,i) == false) { diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 56cc9b8c10..d331ca1405 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -64,29 +64,12 @@ THE SOFTWARE. NS_CC_BEGIN -#if CC_USE_ARRAY_VECTOR -bool nodeComparisonLess(const RCPtr& pp1, const RCPtr& pp2) +bool nodeComparisonLess(Node* n1, Node* n2) { - Object *p1 = static_cast(pp1); - Object *p2 = static_cast(pp2); - Node *n1 = static_cast(p1); - Node *n2 = static_cast(p2); - return( n1->getLocalZOrder() < n2->getLocalZOrder() || ( n1->getLocalZOrder() == n2->getLocalZOrder() && n1->getOrderOfArrival() < n2->getOrderOfArrival() ) ); } -#else -bool nodeComparisonLess(Object* p1, Object* p2) -{ - Node *n1 = static_cast(p1); - Node *n2 = static_cast(p2); - - return( n1->getLocalZOrder() < n2->getLocalZOrder() || - ( n1->getLocalZOrder() == n2->getLocalZOrder() && n1->getOrderOfArrival() < n2->getOrderOfArrival() ) - ); -} -#endif // XXX: Yes, nodes might have a sort problem once every 15 days if the game runs at 60 FPS and each frame sprites are reordered. static int s_globalOrderOfArrival = 1; @@ -232,11 +215,11 @@ void Node::setLocalZOrder(int z) _eventDispatcher->setDirtyForNode(this); } -void Node::setGlobalZOrder(float zOrder) +void Node::setGlobalZOrder(float globalZOrder) { - if (_globalZOrder != zOrder) + if (_globalZOrder != globalZOrder) { - _globalZOrder = zOrder; + _globalZOrder = globalZOrder; _eventDispatcher->setDirtyForNode(this); } } diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index df2f29d86d..92f63c6edc 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -1,9 +1,9 @@ /**************************************************************************** Copyright (c) 2008-2010 Ricardo Quesada -Copyright (c) 2009 Valentin Milea -Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2011 Zynga Inc. -Copyright (c) 2013-2014 Chukong Technologies Inc. + Copyright (c) 2009 Valentin Milea + Copyright (c) 2010-2012 cocos2d-x.org + Copyright (c) 2011 Zynga Inc. + Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -72,11 +72,7 @@ enum { kNodeOnCleanup }; -#if CC_USE_ARRAY_VECTOR -bool nodeComparisonLess(const RCPtr& pp1, const RCPtr& pp2); -#else -bool nodeComparisonLess(Object* p1, Object* p2); -#endif +bool nodeComparisonLess(Node* n1, Node* n2); class EventListener; @@ -173,9 +169,9 @@ public: @see `setGlobalZOrder` @see `setVertexZ` */ - virtual void setLocalZOrder(int zOrder); + virtual void setLocalZOrder(int localZOrder); - CC_DEPRECATED_ATTRIBUTE virtual void setZOrder(int zOrder) { setLocalZOrder(zOrder); } + CC_DEPRECATED_ATTRIBUTE virtual void setZOrder(int localZOrder) { setLocalZOrder(localZOrder); } /* Helper function used by `setLocalZOrder`. Don't use it unless you know what you are doing. */ virtual void _setLocalZOrder(int z); @@ -208,7 +204,7 @@ public: @since v3.0 */ - virtual void setGlobalZOrder(float zOrder); + virtual void setGlobalZOrder(float globalZOrder); /** * Returns the Node's Global Z Order. * @@ -535,11 +531,11 @@ public: * A node which called addChild subsequently will take a larger arrival order, * If two children have the same Z order, the child with larger arrival order will be drawn later. * - * @warning This method is used internally for zOrder sorting, don't change this manually + * @warning This method is used internally for localZOrder sorting, don't change this manually * * @param orderOfArrival The arrival order. */ - virtual void setOrderOfArrival(int orderOfArrival); + void setOrderOfArrival(int orderOfArrival); /** * Returns the arrival order, indecates which children is added previously. * @@ -547,7 +543,7 @@ public: * * @return The arrival order. */ - virtual int getOrderOfArrival() const; + int getOrderOfArrival() const; /** @deprecated No longer needed @@ -595,24 +591,24 @@ public: */ virtual void addChild(Node * child); /** - * Adds a child to the container with a z-order + * Adds a child to the container with a local z-order * * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. * * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param zOrder Z order for drawing priority. Please refer to `setLocalZOrder(int)` */ - virtual void addChild(Node * child, int zOrder); + virtual void addChild(Node * child, int localZOrder); /** * Adds a child to the container with z order and tag * * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. * * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param zOrder Z order for drawing priority. Please refer to setLocalZOrder(int) * @param tag A interger to identify the node easily. Please refer to setTag(int) */ - virtual void addChild(Node* child, int zOrder, int tag); + virtual void addChild(Node* child, int localZOrder, int tag); /** * Gets a child from the container with its tag * @@ -715,9 +711,9 @@ public: * Reorders a child according to a new z value. * * @param child An already added child node. It MUST be already added. - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param localZOrder Z order for drawing priority. Please refer to setLocalZOrder(int) */ - virtual void reorderChild(Node * child, int zOrder); + virtual void reorderChild(Node * child, int localZOrder); /** * Sorts the children array once before drawing, instead of every time when a child is added or reordered. @@ -1477,7 +1473,7 @@ protected: GLProgram *_shaderProgram; ///< OpenGL shader - int _orderOfArrival; ///< used to preserve sequence while sorting children with the same zOrder + int _orderOfArrival; ///< used to preserve sequence while sorting children with the same localZOrder Scheduler *_scheduler; ///< scheduler used to schedule timers and updates diff --git a/cocos/2d/CCParticleBatchNode.cpp b/cocos/2d/CCParticleBatchNode.cpp index f54d823b1b..40a7bc471b 100644 --- a/cocos/2d/CCParticleBatchNode.cpp +++ b/cocos/2d/CCParticleBatchNode.cpp @@ -384,7 +384,6 @@ void ParticleBatchNode::draw(void) _batchCommand.init( _globalZOrder, - _textureAtlas->getTexture()->getName(), _shaderProgram, _blendFunc, _textureAtlas, diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index e8dc9cf8cb..e93b462d68 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -358,7 +358,6 @@ void SpriteBatchNode::draw() _batchCommand.init( _globalZOrder, - _textureAtlas->getTexture()->getName(), _shaderProgram, _blendFunc, _textureAtlas, diff --git a/cocos/2d/CCTextImage.cpp b/cocos/2d/CCTextImage.cpp deleted file mode 100644 index cd972a172e..0000000000 --- a/cocos/2d/CCTextImage.cpp +++ /dev/null @@ -1,478 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 Zynga Inc. - Copyright (c) 2013-2014 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include -#include -#include -#include - -#include "CCTextImage.h" -#include "CCFontFreeType.h" -#include "CCFont.h" -#include "ccUTF8.h" - -NS_CC_BEGIN - - -TextLineDef::TextLineDef(float x, float y, float width, float height) :_x(x), _y(y), _width(width), _height(height) -{ -} - -TextPageDef::TextPageDef(int pageNum, int width, int height): _pageNum(pageNum), - _width(width), - _height(height), - _pageData(0), - _pageTexture(0) -{ -} - -TextPageDef::~TextPageDef() -{ - size_t numLines = _lines.size(); - - for( size_t c = 0; crelease(); - } -} - -bool TextPageDef::generatePageTexture(bool releasePageData) -{ - if (!_pageData) - return false; - - if (_pageTexture) - { - _pageTexture->release(); - _pageTexture = 0; - } - - Size imageSize = Size((float)(_width), (float)(_height)); - if((imageSize.width <= 0) || (imageSize.height <= 0)) - return false; - - _pageTexture = new Texture2D(); - if (!_pageTexture) - return false; - - int dataLenght = (_width * _height * 1); - bool textureCreated = _pageTexture->initWithData(_pageData, dataLenght, Texture2D::PixelFormat::A8, _width, _height, imageSize); - - // release the page data if requested - if (releasePageData && textureCreated) - { - delete [] _pageData; - _pageData = 0; - } - - return textureCreated; -} - -void TextPageDef::preparePageTexture(bool releaseRAWData) -{ - generatePageTexture(releaseRAWData); -} - -Texture2D *TextPageDef::getPageTexture() -{ - if (!_pageTexture) - { - generatePageTexture(); - } - - return _pageTexture; -} - -TextFontPagesDef::TextFontPagesDef() -{ -} - -TextFontPagesDef::~TextFontPagesDef() -{ - size_t numPages = _pages.size(); - for( size_t c = 0; c < numPages; ++c ) - { - if (_pages[c]) - delete _pages[c]; - } -} - -TextImage::TextImage(): _fontPages(0), _font(0) -{ -} - -TextImage::~TextImage() -{ - if (_fontPages) - delete _fontPages; - - if (_font) - _font->release(); -} - -bool TextImage::initWithString(const char *text, int width, int height, cocos2d::Font* font, bool releaseRAWData) -{ - bool textIsUTF16 = false; - - if (_font) - { - _font->release(); - _font = 0; - } - - // carloX - _font = font; - - // generate the glyphs for the requested text (glyphs are latter's bounding boxes) - if (!generateTextGlyphs(text)) - return false; - - Size constrainSize; - unsigned short int *strUTF16 = 0; - - int stringNumChars; - if (textIsUTF16) - { - strUTF16 = (unsigned short int *)text; - stringNumChars = cc_wcslen(strUTF16); - } - else - { - // string needs to go to unicode - strUTF16 = _font->getUTF16Text(text, stringNumChars); - } - - if (!strUTF16 || !stringNumChars) - return false; - - // create all the needed pages - if (!createPageDefinitions(strUTF16, width, height, _font->getFontMaxHeight())) - return false; - - // release the original string if needed - if (!textIsUTF16) - delete [] strUTF16; - - // actually create the needed images - return createImageDataFromPages(_fontPages, releaseRAWData); - - return true; -} - -bool TextImage::createPageDefinitions(unsigned short int *inText, int imageWidth, int imageHeight, int lineHeight) -{ - bool needToReleaseText = false; - int delta = 0; - int currentPage = 0; - float currentY = 0.0; - - // - unsigned short int *strUTF16 = inText; - - if (_fontPages) - delete _fontPages; - - // create pages for the font - _fontPages = new TextFontPagesDef(); - if (!_fontPages) - return false; - - // create the first page (ther is going to be at least one page) - TextPageDef *currentPageDef = new TextPageDef(currentPage, imageWidth, imageHeight); - if (!currentPageDef) - return false; - - // add the current page - _fontPages->addPage(currentPageDef); - - // work out creating pages - - do { - - // choose texture page - if ((currentY + lineHeight) > imageHeight) - { - currentY = 0; - currentPage += 1; - - // create a new page and add - currentPageDef = new TextPageDef(currentPage, imageWidth, imageHeight); - if (!currentPageDef) - return false; - - _fontPages->addPage(currentPageDef); - } - - // get the new fitting string - Size tempSize; - tempSize.width = imageWidth; - tempSize.height = imageHeight; - - // figure out how many glyphs fit in this line - int newLineSize = 0; - int numFittingChar = getNumGlyphsFittingInSize(_textGlyphs, strUTF16, _font, &tempSize, newLineSize); - - // crete the temporary new string - unsigned short int *pTempString = 0; - pTempString = _font->trimUTF16Text(strUTF16, 0, (numFittingChar - 1)); - - // create the new line and add to the current page - TextLineDef *newLine = new TextLineDef(0.0, currentY, newLineSize, lineHeight); - if (!newLine) - return false; - - // add all the glyphs to this line - addGlyphsToLine(newLine, (const char *)pTempString, true); - - // add the line the to current page - currentPageDef->addLine(newLine); - - // can now release the string - delete [] pTempString; - - // create the new string - int stringLenght = _font->getUTF16TextLenght(strUTF16); - delta = (stringLenght - numFittingChar); - - // there is still some leftover, need to work on it - if (delta) - { - // create the new string - unsigned short int *tempS = _font->trimUTF16Text(strUTF16, numFittingChar, (stringLenght - 1)); - - if (needToReleaseText) - delete [] strUTF16; - - // a copy of the string has been created, so next time I'll need to release it - needToReleaseText = true; - - // assign pointer - strUTF16 = tempS; - } - - // go to next line - currentY += lineHeight; - - } while(delta); - - if (needToReleaseText) - delete [] strUTF16; - - return true; -} - -int TextImage::getNumGlyphsFittingInSize(std::unordered_map &glyphDefs, unsigned short int *strUTF8, Font *font, Size *constrainSize, int &outNewSize) -{ - if (!strUTF8) - return 0; - - float widthWithBBX = 0.0f; - float lastWidth = 0.0f; - - // get the string to UTF8 - int numChar = cc_wcslen(strUTF8); - - for (int c = 0; c < numChar; ++c) - { - widthWithBBX += (glyphDefs[strUTF8[c]].getRect().size.width + glyphDefs[strUTF8[c]].getPadding()); - - if (widthWithBBX >= constrainSize->width) - { - outNewSize = lastWidth; - return c; - } - - lastWidth = widthWithBBX; - } - - outNewSize = constrainSize->width; - return numChar; -} - -bool TextImage::addGlyphsToLine(TextLineDef *line, const char *lineText, bool textIsUTF16) -{ - if (!_font) - return false; - - int numLetters = 0; - unsigned short int *UTF16string = 0; - - if (textIsUTF16) - { - UTF16string = (unsigned short int *)lineText; - numLetters = cc_wcslen(UTF16string); - } - else - { - UTF16string = _font->getUTF16Text(lineText, numLetters); - } - - for (int c = 0; c < numLetters; ++c) - { - _textGlyphs[UTF16string[c]].setCommonHeight(line->getHeight()); - line->addGlyph(_textGlyphs[UTF16string[c]] ); - } - - if(!textIsUTF16) - delete [] UTF16string; - - return true; -} - -bool TextImage::generateTextGlyphs(const char * text) -{ - if (!_font) - return false; - - int numGlyphs = 0; - GlyphDef *newGlyphs = _font->getGlyphDefintionsForText(text, numGlyphs); - - if (!newGlyphs) - return false; - - if (!_textGlyphs.empty()) - _textGlyphs.clear(); - - for (int c = 0; c < numGlyphs; ++c) - _textGlyphs[newGlyphs[c].getUTF8Letter()] = newGlyphs[c]; - - delete [] newGlyphs; - return true; -} - -bool TextImage::createImageDataFromPages(TextFontPagesDef *thePages, bool releaseRAWData) -{ - int numPages = thePages->getNumPages(); - if (!numPages) - return false; - - for (int c = 0; c < numPages; ++c) - { - unsigned char *pageData = 0; - pageData = preparePageGlyphData(thePages->getPageAt(c)); - - if (pageData) - { - // set the page data - thePages->getPageAt(c)->setPageData(pageData); - - // crete page texture and relase RAW data - thePages->getPageAt(c)->preparePageTexture(releaseRAWData); - } - else - { - return false; - } - } - - return true; -} - -unsigned char * TextImage::preparePageGlyphData(TextPageDef *thePage) -{ - return renderGlyphData(thePage); -} - -unsigned char * TextImage::renderGlyphData(TextPageDef *thePage) -{ - if (!thePage) - return 0; - - if (!_font) - return 0; - - if (thePage->getNumLines() == 0) - return nullptr; - - int pageWidth = thePage->getWidth(); - int pageHeight = thePage->getHeight(); - - // prepare memory and clean to 0 - int sizeInBytes = (pageWidth * pageHeight * 1); - unsigned char* data = new unsigned char[sizeInBytes]; - - if (!data) - return 0; - - memset(data, 0, sizeInBytes); - - int numLines = thePage->getNumLines(); - - for (int c = 0; c < numLines; ++c) - { - TextLineDef *currentLine = thePage->getLineAt(c); - - float origX = _font->getLetterPadding(); - float origY = currentLine->getY(); - - int numGlyphToRender = currentLine->getNumGlyph(); - - for (int cglyph = 0; cglyph < numGlyphToRender; ++cglyph) - { - GlyphDef currGlyph = currentLine->getGlyphAt(cglyph); - _font->renderCharAt(currGlyph.getUTF8Letter(), origX, origY, data, pageWidth); - origX += (currGlyph.getRect().size.width + _font->getLetterPadding()); - } - } - -#ifdef _DEBUG_FONTS_ - static int counter = 0; - char outFilename[512]; - sprintf(outFilename,"testIMG%d", counter); - ++counter; - Image *image = new Image; - image->initWithRawData(data, (pageWidth * pageWidth * 4), 1024, 1024, 8, false); - image->saveToFile(outFilename); -#endif - - // we are done here - return data; -} - -NS_CC_END - - - - - - - - - - - - diff --git a/cocos/2d/CCTextImage.h b/cocos/2d/CCTextImage.h deleted file mode 100644 index b7baddb561..0000000000 --- a/cocos/2d/CCTextImage.h +++ /dev/null @@ -1,215 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 Zynga Inc. - Copyright (c) 2013-2014 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#ifndef _CCTextImage_h_ -#define _CCTextImage_h_ - -#include -#include - -#include "CCPlatformMacros.h" -#include "CCGeometry.h" - -NS_CC_BEGIN - -class Font; -class Texture2D; - -/** @brief GlyphDef defines one single glyph (character) in a text image - * - * it defines the bounding box for the glyph in the texture page, the character the padding (spacing) between characters - * - */ - -class CC_DLL GlyphDef -{ -public: - - GlyphDef() : _validGlyph(false) {} - GlyphDef(unsigned short int letterUTF8, const Rect &rect) { - _gliphRect = rect; - _uTF16Letter = letterUTF8; - } - - void setUTF16Letter(unsigned short int letterUTF8) { _uTF16Letter = letterUTF8; } - void setRect(const Rect & theRect) { _gliphRect = theRect; } - - unsigned short int getUTF8Letter() const { return _uTF16Letter; } - const Rect& getRect() const { return _gliphRect; } - - void setPadding(float padding) { _padding = padding; } - float getPadding() const { return _padding; } - - void setCommonHeight(float commonHeight) { _commonHeight = commonHeight; } - float getCommonHeight() const { return _commonHeight; } - - void setValid(bool isValid) { _validGlyph = isValid; } - bool isValid() const { return _validGlyph; } - -protected: - Rect _gliphRect; - unsigned short int _uTF16Letter; - float _padding; - float _commonHeight; - bool _validGlyph; - -}; - -/** @brief TextLineDef define a line of text in a text image texture page - * - * conllects all the GlyphDef for a text line plus line size and line position in text image space - * - */ -class CC_DLL TextLineDef -{ -public: - - TextLineDef(float x, float y, float width, float height); - - float getX() const { return _x; } - float getY() const { return _y; } - float getWidth() const { return _width; } - float getHeight() const { return _height; } - - void addGlyph(GlyphDef theGlyph) { _glyphs.push_back(theGlyph); } - int getNumGlyph() const { return static_cast(_glyphs.size()); } - const GlyphDef & getGlyphAt(int index) const { return _glyphs[index]; } - -protected: - float _x; - float _y; - float _width; - float _height; - std::vector _glyphs; -}; - -/** @brief TextPageDef defines one text image page (a TextImage can have/use more than one page) - * - * collects all the TextLineDef for one page, the witdh and height of the page and the graphics (texture) for the page - * - */ -class CC_DLL TextPageDef -{ -public: - /** - * @js NA - */ - TextPageDef(int pageNum, int width, int height); - /** - * @js NA - * @lua NA - */ - ~TextPageDef(); - - void addLine(TextLineDef *theLine) { _lines.push_back(theLine); } - int getNumLines() const { return static_cast(_lines.size()); } - TextLineDef * getLineAt(int index) const { return _lines[index]; } - int getWidth() const { return _width; } - int getHeight() const { return _height; } - int getPageNumber() const { return _pageNum; } - void setPageData(unsigned char *data) { _pageData = data; } - const unsigned char * getPageData() const { return _pageData; } - Texture2D *getPageTexture(); - void preparePageTexture(bool releaseRAWData = true); - -protected: - bool generatePageTexture(bool releasePageData = false); - - int _pageNum; - int _width; - int _height; - unsigned char * _pageData; - Texture2D* _pageTexture; - std::vector _lines; -}; - -/** @brief CCTextFontPages collection of pages (TextPageDef) - * - * A TextImage is composed by one or more text pages. This calss collects all of those pages - */ -class CC_DLL TextFontPagesDef -{ -public: - /** - * @js ctor - */ - TextFontPagesDef(); - /** - * @js NA - * @lua NA - */ - ~TextFontPagesDef(); - - void addPage(TextPageDef *newPage) { _pages.push_back(newPage); } - int getNumPages() const { return static_cast(_pages.size()); } - TextPageDef* getPageAt(int index) const { return _pages[index]; } - -protected: - std::vector _pages; - -}; - -/** @brief TextImage - * - */ -class CC_DLL TextImage -{ -public: - /** - * @js ctor - */ - TextImage(); - /** - * @js NA - * @lua NA - */ - ~TextImage(); - - bool initWithString(const char *text, int width, int height, Font* font, bool releaseRAWData = true); - - TextFontPagesDef* getPages() const { return _fontPages; } - Font* getFont() const { return _font; } - -protected: - bool createImageDataFromPages(TextFontPagesDef *thePages, bool releaseRAWData = true); - bool addGlyphsToLine(TextLineDef *line, const char *lineText, bool textIsUTF16 = false); - bool generateTextGlyphs(const char * text); - int getNumGlyphsFittingInSize(std::unordered_map &glyphDefs, unsigned short int *strUTF8, Font *font, Size *constrainSize, int &outNewSize); - bool createPageDefinitions(unsigned short int *inText, int imageWidth, int imageHeight, int lineHeight); - unsigned char * preparePageGlyphData(TextPageDef *thePage); - - // glyph rendering - unsigned char * renderGlyphData(TextPageDef *thePage); - - std::unordered_map _textGlyphs; - TextFontPagesDef* _fontPages; - Font* _font; -}; - - -NS_CC_END - - -#endif // _CCTextImage_h_ diff --git a/cocos/2d/CMakeLists.txt b/cocos/2d/CMakeLists.txt index 886c2ebc21..d32040f867 100644 --- a/cocos/2d/CMakeLists.txt +++ b/cocos/2d/CMakeLists.txt @@ -67,8 +67,6 @@ set(COCOS2D_SRC CCFont.cpp CCFontAtlas.cpp CCFontAtlasCache.cpp - CCFontAtlasFactory.cpp - CCFontDefinition.cpp CCFontFNT.cpp CCFontFreeType.cpp CCFontCharMap.cpp @@ -77,7 +75,6 @@ set(COCOS2D_SRC CCLabelBMFont.cpp CCLabelTTF.cpp CCLabelTextFormatter.cpp - CCTextImage.cpp CCLayer.cpp CCScene.cpp CCTransition.cpp diff --git a/cocos/2d/cocos2d.vcxproj b/cocos/2d/cocos2d.vcxproj index 9c7bd8f40f..123231cb40 100644 --- a/cocos/2d/cocos2d.vcxproj +++ b/cocos/2d/cocos2d.vcxproj @@ -247,9 +247,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - - @@ -288,7 +286,6 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - @@ -429,9 +426,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - - @@ -490,7 +485,6 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - diff --git a/cocos/2d/cocos2d.vcxproj.filters b/cocos/2d/cocos2d.vcxproj.filters index 6a28597e2d..6b63c0cf67 100644 --- a/cocos/2d/cocos2d.vcxproj.filters +++ b/cocos/2d/cocos2d.vcxproj.filters @@ -318,12 +318,6 @@ label_nodes - - label_nodes - - - label_nodes - label_nodes @@ -345,9 +339,6 @@ label_nodes - - label_nodes - platform\etc @@ -834,12 +825,6 @@ label_nodes - - label_nodes - - - label_nodes - label_nodes @@ -864,9 +849,6 @@ label_nodes - - label_nodes - platform\etc diff --git a/cocos/2d/platform/mac/CCCommon.mm b/cocos/2d/platform/mac/CCCommon.mm index 52e4fb7beb..d36241ee7b 100644 --- a/cocos/2d/platform/mac/CCCommon.mm +++ b/cocos/2d/platform/mac/CCCommon.mm @@ -22,14 +22,15 @@ 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 "platform/CCCommon.h" +#include "CCEGLView.h" +#define GLFW_EXPOSE_NATIVE_NSGL +#define GLFW_EXPOSE_NATIVE_COCOA +#include "glfw3native.h" #include #include -#import "EAGLView.h" - +#include NS_CC_BEGIN @@ -50,7 +51,7 @@ void MessageBox(const char * msg, const char * title) [alert setInformativeText:tmpTitle]; [alert setAlertStyle:NSWarningAlertStyle]; - NSWindow *window = [[CCEAGLView sharedEGLView] window]; + id window = glfwGetCocoaWindow(EGLView::getInstance()->getWindow()); [alert beginSheetModalForWindow:window modalDelegate:[window delegate] didEndSelector:nil diff --git a/cocos/2d/platform/mac/CCDevice.mm b/cocos/2d/platform/mac/CCDevice.cpp similarity index 100% rename from cocos/2d/platform/mac/CCDevice.mm rename to cocos/2d/platform/mac/CCDevice.cpp diff --git a/cocos/2d/platform/mac/CCDirectorCaller.mm b/cocos/2d/platform/mac/CCDirectorCaller.mm index f371dae133..cb6536141c 100644 --- a/cocos/2d/platform/mac/CCDirectorCaller.mm +++ b/cocos/2d/platform/mac/CCDirectorCaller.mm @@ -22,13 +22,14 @@ 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. ****************************************************************************/ -#import + #import "CCDirectorCaller.h" -#import "CCDirector.h" -#import "EAGLView.h" -#import "CCEventDispatcherMac.h" +#include "CCDirector.h" #include "CCAutoreleasePool.h" +#import +#import + static id s_sharedDirectorCaller; @interface NSObject(CADisplayLink) @@ -81,8 +82,7 @@ static id s_sharedDirectorCaller; NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; cocos2d::Director::getInstance()->drawScene(); - cocos2d::PoolManager::sharedPoolManager()->pop(); - [[CCEventDispatcher sharedDispatcher] dispatchQueuedEvents]; + cocos2d::PoolManager::getInstance()->getCurrentPool()->clear(); [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:nil]; @@ -115,21 +115,9 @@ static CVReturn MyDisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTime // All we do here is tell the display it needs a refresh NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - // get the opengl view - CCEAGLView *openGLView = [CCEAGLView sharedEGLView]; - [openGLView lockOpenGLContext]; - // run the main cocos2d loop cocos2d::Director::getInstance()->mainLoop(); - // flush buffer (this line is very important!) - [[openGLView openGLContext] flushBuffer]; - - [openGLView unlockOpenGLContext]; - - // send any queued events - [[CCEventDispatcher sharedDispatcher] dispatchQueuedEvents]; - [pool release]; } diff --git a/cocos/2d/platform/mac/CCEGLView.mm b/cocos/2d/platform/mac/CCEGLView.cpp similarity index 99% rename from cocos/2d/platform/mac/CCEGLView.mm rename to cocos/2d/platform/mac/CCEGLView.cpp index a3635be8ed..31fe864776 100644 --- a/cocos/2d/platform/mac/CCEGLView.mm +++ b/cocos/2d/platform/mac/CCEGLView.cpp @@ -27,7 +27,6 @@ THE SOFTWARE. #include -#include "EAGLView.h" #include "CCDirector.h" #include "CCSet.h" #include "CCTouch.h" diff --git a/cocos/2d/platform/mac/CCEventDispatcherMac.h b/cocos/2d/platform/mac/CCEventDispatcherMac.h deleted file mode 100644 index df47784455..0000000000 --- a/cocos/2d/platform/mac/CCEventDispatcherMac.h +++ /dev/null @@ -1,277 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010 Ricardo Quesada -Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2011 Zynga Inc. -Copyright (c) 2013-2014 Chukong Technologies Inc. - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -// Only compile this code on Mac. These files should not be included on your iOS project. -// But in case they are included, it won't be compiled. -#import -#ifndef __CC_EVENT_DISPATCHER_MAC_H__ -#define __CC_EVENT_DISPATCHER_MAC_H__ - -#import - -#import "EAGLView.h" -//#import "../../Support/uthash.h" // hack: uthash needs to be imported before utlist to prevent warning -//#import "../../Support/utlist.h" -#import "ccConfig.h" - -//NS_CC_BEGIN; -#pragma mark - MouseEventDelegate - -/** MouseEventDelegate protocol. - Implement it in your node to receive any of mouse events - */ -@protocol CCMouseEventDelegate -@optional - -// -// left -// -/** called when the "mouseDown" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccMouseDown:(NSEvent*)event; - -/** called when the "mouseDragged" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccMouseDragged:(NSEvent*)event; - -/** called when the "mouseMoved" event is received. - Return YES to avoid propagating the event to other delegates. - By default, "mouseMoved" is disabled. To enable it, send the "setAcceptsMouseMovedEvents:YES" message to the main window. - */ --(BOOL) ccMouseMoved:(NSEvent*)event; - -/** called when the "mouseUp" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccMouseUp:(NSEvent*)event; - - -// -// right -// - -/** called when the "rightMouseDown" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccRightMouseDown:(NSEvent*)event; - -/** called when the "rightMouseDragged" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccRightMouseDragged:(NSEvent*)event; - -/** called when the "rightMouseUp" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccRightMouseUp:(NSEvent*)event; - -// -// other -// - -/** called when the "otherMouseDown" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccOtherMouseDown:(NSEvent*)event; - -/** called when the "otherMouseDragged" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccOtherMouseDragged:(NSEvent*)event; - -/** called when the "otherMouseUp" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccOtherMouseUp:(NSEvent*)event; - -// -// scroll wheel -// - -/** called when the "scrollWheel" event is received. - Return YES to avoid propagating the event to other delegates. - */ -- (BOOL)ccScrollWheel:(NSEvent *)theEvent; - - -// -// enter / exit -// - -/** called when the "mouseEntered" event is received. - Return YES to avoid propagating the event to other delegates. - */ -- (void)ccMouseEntered:(NSEvent *)theEvent; - -/** called when the "mouseExited" event is received. - Return YES to avoid propagating the event to other delegates. - */ -- (void)ccMouseExited:(NSEvent *)theEvent; - -@end - -#pragma mark - KeyboardEventDelegate - -/** KeyboardEventDelegate protocol. - Implement it in your node to receive any of keyboard events - */ -@protocol CCKeyboardEventDelegate -@optional -/** called when the "keyUp" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccKeyUp:(NSEvent*)event; - -/** called when the "keyDown" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccKeyDown:(NSEvent*)event; -/** called when the "flagsChanged" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccFlagsChanged:(NSEvent*)event; -@end - -#pragma mark - -#pragma mark TouchEventDelegate - -/** TouchEventDelegate protocol. - Implement it in your node to receive any of touch events - */ -@protocol CCTouchEventDelegate -@optional -/** called when the "touchesBegan" event is received. - Return YES to avoid propagating the event to other delegates. - */ -- (BOOL)ccTouchesBeganWithEvent:(NSEvent *)event; - -/** called when the "touchesMoved" event is received. - Return YES to avoid propagating the event to other delegates. - */ -- (BOOL)ccTouchesMovedWithEvent:(NSEvent *)event; - -/** called when the "touchesEnded" event is received. - Return YES to avoid propagating the event to other delegates. - */ -- (BOOL)ccTouchesEndedWithEvent:(NSEvent *)event; - -/** called when the "touchesCancelled" event is received. - Return YES to avoid propagating the event to other delegates. - */ -- (BOOL)ccTouchesCancelledWithEvent:(NSEvent *)event; - -@end - - -#pragma mark - EventDispatcher - -struct _listEntry; - -/** EventDispatcher - - This is object is responsible for dispatching the events: - - Mouse events - - Keyboard events - - Touch events - - Only available on Mac - */ -@interface CCEventDispatcher : NSObject { - - BOOL dispatchEvents_; - - struct _listEntry *keyboardDelegates_; - struct _listEntry *mouseDelegates_; - struct _listEntry *touchDelegates_; -} - -@property (nonatomic, readwrite) BOOL dispatchEvents; - - -/** EventDispatcher singleton */ -+(CCEventDispatcher*) sharedDispatcher; - -#pragma mark EventDispatcher - Mouse - -/** Adds a mouse delegate to the dispatcher's list. - Delegates with a lower priority value will be called before higher priority values. - All the events will be propgated to all the delegates, unless the one delegate returns YES. - - IMPORTANT: The delegate will be retained. - */ --(void) addMouseDelegate:(id) delegate priority:(NSInteger)priority; - -/** removes a mouse delegate */ --(void) removeMouseDelegate:(id) delegate; - -/** Removes all mouse delegates, releasing all the delegates */ --(void) removeAllMouseDelegates; - -#pragma mark EventDispatcher - Keyboard - -/** Adds a Keyboard delegate to the dispatcher's list. - Delegates with a lower priority value will be called before higher priority values. - All the events will be propgated to all the delegates, unless the one delegate returns YES. - - IMPORTANT: The delegate will be retained. - */ --(void) addKeyboardDelegate:(id) delegate priority:(NSInteger)priority; - -/** removes a mouse delegate */ --(void) removeKeyboardDelegate:(id) delegate; - -/** Removes all mouse delegates, releasing all the delegates */ --(void) removeAllKeyboardDelegates; - -#pragma mark EventDispatcher - Touches - -/** Adds a Touch delegate to the dispatcher's list. - Delegates with a lower priority value will be called before higher priority values. - All the events will be propgated to all the delegates, unless the one delegate returns YES. - - IMPORTANT: The delegate will be retained. - */ -- (void)addTouchDelegate:(id)delegate priority:(NSInteger)priority; - -/** Removes a touch delegate */ -- (void)removeTouchDelegate:(id) delegate; - -/** Removes all touch delegates, releasing all the delegates */ -- (void)removeAllTouchDelegates; - -#pragma mark EventDispatcher - Dispatch Events - -#if CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD --(void) dispatchQueuedEvents; -#endif - -@end - -//NS_CC_END; -#endif // __CC_EVENT_DISPATCHER_MAC_H__ diff --git a/cocos/2d/platform/mac/CCEventDispatcherMac.mm b/cocos/2d/platform/mac/CCEventDispatcherMac.mm deleted file mode 100644 index 691383d36a..0000000000 --- a/cocos/2d/platform/mac/CCEventDispatcherMac.mm +++ /dev/null @@ -1,649 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010 Ricardo Quesada -Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2011 Zynga Inc. -Copyright (c) 2013-2014 Chukong Technologies Inc. - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -// Only compile this code on Mac. These files should not be included on your iOS project. -// But in case they are included, it won't be compiled. -#import - -#import "CCEventDispatcherMac.h" -#import "ccConfig.h" -#include "utlist.h" - -#include "CCDirector.h" - -//NS_CC_BEGIN; -static CCEventDispatcher *sharedDispatcher = nil; - -enum { - // mouse - kImplementsMouseDown = 1 << 0, - kImplementsMouseMoved = 1 << 1, - kImplementsMouseDragged = 1 << 2, - kImplementsMouseUp = 1 << 3, - kImplementsRightMouseDown = 1 << 4, - kImplementsRightMouseDragged = 1 << 5, - kImplementsRightMouseUp = 1 << 6, - kImplementsOtherMouseDown = 1 << 7, - kImplementsOtherMouseDragged = 1 << 8, - kImplementsOtherMouseUp = 1 << 9, - kImplementsScrollWheel = 1 << 10, - kImplementsMouseEntered = 1 << 11, - kImplementsMouseExited = 1 << 12, - - kImplementsTouchesBegan = 1 << 13, - kImplementsTouchesMoved = 1 << 14, - kImplementsTouchesEnded = 1 << 15, - kImplementsTouchesCancelled = 1 << 16, - - // keyboard - kImplementsKeyUp = 1 << 0, - kImplementsKeyDown = 1 << 1, - kImplementsFlagsChanged = 1 << 2, -}; - - -typedef struct _listEntry -{ - struct _listEntry *prev, *next; - id delegate; - NSInteger priority; - NSUInteger flags; -} tListEntry; - - -#if CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD - -#define QUEUE_EVENT_MAX 128 -struct _eventQueue { - SEL selector; - NSEvent *event; -}; - -static struct _eventQueue eventQueue[QUEUE_EVENT_MAX]; -static int eventQueueCount; - -#endif // CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD - - -@implementation CCEventDispatcher - -@synthesize dispatchEvents=dispatchEvents_; - - -+(CCEventDispatcher*) sharedDispatcher -{ - @synchronized(self) { - if (sharedDispatcher == nil) - sharedDispatcher = [[self alloc] init]; // assignment not done here - } - return sharedDispatcher; -} - -+(id) allocWithZone:(NSZone *)zone -{ - @synchronized(self) { - NSAssert(sharedDispatcher == nil, @"Attempted to allocate a second instance of a singleton."); - return [super allocWithZone:zone]; - } - return nil; // on subsequent allocation attempts return nil -} - --(id) init -{ - if( (self = [super init]) ) - { - // events enabled by default - dispatchEvents_ = YES; - - // delegates - keyboardDelegates_ = nullptr; - mouseDelegates_ = nullptr; - touchDelegates_ = nullptr; - -#if CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD - eventQueueCount = 0; -#endif - } - - return self; -} - -- (void) dealloc -{ - [super dealloc]; -} - -#pragma mark EventDispatcher - add / remove delegates - --(void) addDelegate:(id)delegate priority:(NSInteger)priority flags:(NSUInteger)flags list:(tListEntry**)list -{ - tListEntry *listElement = (tListEntry *)malloc( sizeof(*listElement) ); - - listElement->delegate = [delegate retain]; - listElement->priority = priority; - listElement->flags = flags; - listElement->next = listElement->prev = nullptr; - - // empty list ? - if( ! *list ) { - DL_APPEND( *list, listElement ); - - } else { - BOOL added = NO; - - for( tListEntry *elem = *list; elem ; elem = elem->next ) { - if( priority < elem->priority ) { - - if( elem == *list ) - DL_PREPEND(*list, listElement); - else { - listElement->next = elem; - listElement->prev = elem->prev; - - elem->prev->next = listElement; - elem->prev = listElement; - } - - added = YES; - break; - } - } - - // Not added? priority has the higher value. Append it. - if( !added ) - DL_APPEND(*list, listElement); - } -} - --(void) removeDelegate:(id)delegate fromList:(tListEntry**)list -{ - tListEntry *entry, *tmp; - - // updates with priority < 0 - DL_FOREACH_SAFE( *list, entry, tmp ) { - if( entry->delegate == delegate ) { - DL_DELETE( *list, entry ); - [delegate release]; - free(entry); - break; - } - } -} - --(void) removeAllDelegatesFromList:(tListEntry**)list -{ - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( *list, entry, tmp ) { - DL_DELETE( *list, entry ); - free(entry); - } -} - - --(void) addMouseDelegate:(id) delegate priority:(NSInteger)priority -{ - NSUInteger flags = 0; - - flags |= ( [delegate respondsToSelector:@selector(ccMouseDown:)] ? kImplementsMouseDown : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccMouseDragged:)] ? kImplementsMouseDragged : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccMouseMoved:)] ? kImplementsMouseMoved : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccMouseUp:)] ? kImplementsMouseUp : 0 ); - - flags |= ( [delegate respondsToSelector:@selector(ccRightMouseDown:)] ? kImplementsRightMouseDown : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccRightMouseDragged:)] ? kImplementsRightMouseDragged : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccRightMouseUp:)] ? kImplementsRightMouseUp : 0 ); - - flags |= ( [delegate respondsToSelector:@selector(ccOtherMouseDown:)] ? kImplementsOtherMouseDown : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccOtherMouseDragged:)] ? kImplementsOtherMouseDragged : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccOtherMouseUp:)] ? kImplementsOtherMouseUp : 0 ); - - flags |= ( [delegate respondsToSelector:@selector(ccMouseEntered:)] ? kImplementsMouseEntered : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccMouseExited:)] ? kImplementsMouseExited : 0 ); - - flags |= ( [delegate respondsToSelector:@selector(ccScrollWheel:)] ? kImplementsScrollWheel : 0 ); - - [self addDelegate:delegate priority:priority flags:flags list:&mouseDelegates_]; -} - --(void) removeMouseDelegate:(id) delegate -{ - [self removeDelegate:delegate fromList:&mouseDelegates_]; -} - --(void) removeAllMouseDelegates -{ - [self removeAllDelegatesFromList:&mouseDelegates_]; -} - --(void) addKeyboardDelegate:(id) delegate priority:(NSInteger)priority -{ - NSUInteger flags = 0; - - flags |= ( [delegate respondsToSelector:@selector(ccKeyUp:)] ? kImplementsKeyUp : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccKeyDown:)] ? kImplementsKeyDown : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccFlagsChanged:)] ? kImplementsFlagsChanged : 0 ); - - [self addDelegate:delegate priority:priority flags:flags list:&keyboardDelegates_]; -} - --(void) removeKeyboardDelegate:(id) delegate -{ - [self removeDelegate:delegate fromList:&keyboardDelegates_]; -} - --(void) removeAllKeyboardDelegates -{ - [self removeAllDelegatesFromList:&keyboardDelegates_]; -} - --(void) addTouchDelegate:(id) delegate priority:(NSInteger)priority -{ - NSUInteger flags = 0; - - flags |= ( [delegate respondsToSelector:@selector(ccTouchesBeganWithEvent:)] ? kImplementsTouchesBegan : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccTouchesMovedWithEvent:)] ? kImplementsTouchesMoved : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccTouchesEndedWithEvent:)] ? kImplementsTouchesEnded : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccTouchesCancelledWithEvent:)] ? kImplementsTouchesCancelled : 0 ); - - [self addDelegate:delegate priority:priority flags:flags list:&touchDelegates_]; -} - --(void) removeTouchDelegate:(id) delegate -{ - [self removeDelegate:delegate fromList:&touchDelegates_]; -} - --(void) removeAllTouchDelegates -{ - [self removeAllDelegatesFromList:&touchDelegates_]; -} - - -#pragma mark EventDispatcher - Mouse events -// -// Mouse events -// - -// -// Left -// -- (void)mouseDown:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsMouseDown ) { - void *swallows = [entry->delegate performSelector:@selector(ccMouseDown:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)mouseMoved:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsMouseMoved ) { - void *swallows = [entry->delegate performSelector:@selector(ccMouseMoved:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)mouseDragged:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsMouseDragged ) { - void *swallows = [entry->delegate performSelector:@selector(ccMouseDragged:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)mouseUp:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsMouseUp ) { - void *swallows = [entry->delegate performSelector:@selector(ccMouseUp:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -// -// Mouse Right -// -- (void)rightMouseDown:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsRightMouseDown ) { - void *swallows = [entry->delegate performSelector:@selector(ccRightMouseDown:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)rightMouseDragged:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsRightMouseDragged ) { - void *swallows = [entry->delegate performSelector:@selector(ccRightMouseDragged:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)rightMouseUp:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsRightMouseUp ) { - void *swallows = [entry->delegate performSelector:@selector(ccRightMouseUp:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -// -// Mouse Other -// -- (void)otherMouseDown:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsOtherMouseDown ) { - void *swallows = [entry->delegate performSelector:@selector(ccOtherMouseDown:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)otherMouseDragged:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsOtherMouseDragged ) { - void *swallows = [entry->delegate performSelector:@selector(ccOtherMouseDragged:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)otherMouseUp:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsOtherMouseUp ) { - void *swallows = [entry->delegate performSelector:@selector(ccOtherMouseUp:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -// -// Scroll Wheel -// -- (void)scrollWheel:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsScrollWheel ) { - void *swallows = [entry->delegate performSelector:@selector(ccScrollWheel:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -// -// Mouse enter / exit -- (void)mouseExited:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsMouseEntered ) { - void *swallows = [entry->delegate performSelector:@selector(ccMouseEntered:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)mouseEntered:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsMouseExited) { - void *swallows = [entry->delegate performSelector:@selector(ccMouseExited:) withObject:event]; - if( swallows ) - break; - } - } - } -} - - -#pragma mark EventDispatcher - Keyboard events - -// Keyboard events -- (void)keyDown:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; -// cocos2d::Director::getInstance()->getKeyboardDispatcher()->dispatchKeyboardEvent(event.keyCode, true); - - DL_FOREACH_SAFE( keyboardDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsKeyDown ) { - void *swallows = [entry->delegate performSelector:@selector(ccKeyDown:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)keyUp:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; -// cocos2d::Director::getInstance()->getKeyboardDispatcher()->dispatchKeyboardEvent(event.keyCode, false); - - DL_FOREACH_SAFE( keyboardDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsKeyUp ) { - void *swallows = [entry->delegate performSelector:@selector(ccKeyUp:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)flagsChanged:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( keyboardDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsFlagsChanged ) { - void *swallows = [entry->delegate performSelector:@selector(ccFlagsChanged:) withObject:event]; - if( swallows ) - break; - } - } - } -} - - -#pragma mark EventDispatcher - Touch events - -- (void)touchesBeganWithEvent:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( touchDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsTouchesBegan) { - void *swallows = [entry->delegate performSelector:@selector(ccTouchesBeganWithEvent:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)touchesMovedWithEvent:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( touchDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsTouchesMoved) { - void *swallows = [entry->delegate performSelector:@selector(ccTouchesMovedWithEvent:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)touchesEndedWithEvent:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( touchDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsTouchesEnded) { - void *swallows = [entry->delegate performSelector:@selector(ccTouchesEndedWithEvent:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)touchesCancelledWithEvent:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( touchDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsTouchesCancelled) { - void *swallows = [entry->delegate performSelector:@selector(ccTouchesCancelledWithEvent:) withObject:event]; - if( swallows ) - break; - } - } - } -} - - -#pragma mark EventDispatcher - queue events - -#if CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD --(void) queueEvent:(NSEvent*)event selector:(SEL)selector -{ - NSAssert( eventQueueCount < QUEUE_EVENT_MAX, @"CCEventDispatcher: recompile. Increment QUEUE_EVENT_MAX value"); - - @synchronized (self) { - eventQueue[eventQueueCount].selector = selector; - eventQueue[eventQueueCount].event = [event copy]; - - eventQueueCount++; - } -} - --(void) dispatchQueuedEvents -{ - @synchronized (self) { - for( int i=0; i < eventQueueCount; i++ ) { - SEL sel = eventQueue[i].selector; - NSEvent *event = eventQueue[i].event; - - [self performSelector:sel withObject:event]; - - [event release]; - } - - eventQueueCount = 0; - } -} -#endif // CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD - -//NS_CC_END; -@end diff --git a/cocos/2d/platform/mac/CCWindow.h b/cocos/2d/platform/mac/CCWindow.h deleted file mode 100644 index 78ac008922..0000000000 --- a/cocos/2d/platform/mac/CCWindow.h +++ /dev/null @@ -1,39 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2013-2014 Chukong Technologies Inc. - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -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 __CC_WINDOW_H__ -#define __CC_WINDOW_H__ - -#import - - -@interface CCWindow : NSWindow -{ -} -- (id) initWithFrame:(NSRect)frame fullscreen:(BOOL)fullscreen; - -@end - -#endif // __CC_WINDOW_H__ \ No newline at end of file diff --git a/cocos/2d/platform/mac/CCWindow.m b/cocos/2d/platform/mac/CCWindow.m deleted file mode 100644 index 97d442d29a..0000000000 --- a/cocos/2d/platform/mac/CCWindow.m +++ /dev/null @@ -1,82 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2013-2014 Chukong Technologies Inc. - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -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. -****************************************************************************/ - -#import "CCWindow.h" -#import "EAGLView.h" - -@implementation CCWindow - -- (id) initWithFrame:(NSRect)frame fullscreen:(BOOL)fullscreen -{ - int styleMask = fullscreen ? NSBackingStoreBuffered : ( NSTitledWindowMask | NSClosableWindowMask ); - self = [self initWithContentRect:frame - styleMask:styleMask - backing:NSBackingStoreBuffered - defer:YES]; - - if (self != nil) - { - if(fullscreen) - { - [self setLevel:NSMainMenuWindowLevel+1]; - [self setHidesOnDeactivate:YES]; - [self setHasShadow:NO]; - } - - [self setAcceptsMouseMovedEvents:NO]; - [self setOpaque:YES]; - } - return self; -} - -- (BOOL) canBecomeKeyWindow -{ - return YES; -} - -- (BOOL) canBecomeMainWindow -{ - return YES; -} - -- (void) keyDown:(NSEvent *)event -{ - // exit fullscreen if user pressed esc - if([event keyCode] == 53) - { - CCEAGLView* eaglView = [CCEAGLView sharedEGLView]; - - // cancel full screen - if( [eaglView isFullScreen] ) - [eaglView setFullScreen:NO]; - - // let another responder take it - else - [super keyDown:event]; - } -} - -@end - diff --git a/cocos/2d/platform/mac/EAGLView.h b/cocos/2d/platform/mac/EAGLView.h deleted file mode 100644 index 8c8ecd477f..0000000000 --- a/cocos/2d/platform/mac/EAGLView.h +++ /dev/null @@ -1,120 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2013-2014 Chukong Technologies Inc. - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -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 __EAGLVIEW_MAC_H__ -#define __EAGLVIEW_MAC_H__ - -#import -#import "ccConfig.h" - -//PROTOCOLS: - -@protocol CCMacEventDelegate -// Mouse -- (void)mouseDown:(NSEvent *)theEvent; -- (void)mouseUp:(NSEvent *)theEvent; -- (void)mouseMoved:(NSEvent *)theEvent; -- (void)mouseDragged:(NSEvent *)theEvent; -- (void)rightMouseDown:(NSEvent*)event; -- (void)rightMouseDragged:(NSEvent*)event; -- (void)rightMouseUp:(NSEvent*)event; -- (void)otherMouseDown:(NSEvent*)event; -- (void)otherMouseDragged:(NSEvent*)event; -- (void)otherMouseUp:(NSEvent*)event; -- (void)scrollWheel:(NSEvent *)theEvent; -- (void)mouseEntered:(NSEvent *)theEvent; -- (void)mouseExited:(NSEvent *)theEvent; - - -// Keyboard -- (void)keyDown:(NSEvent *)theEvent; -- (void)keyUp:(NSEvent *)theEvent; -- (void)flagsChanged:(NSEvent *)theEvent; - -// Touches -- (void)touchesBeganWithEvent:(NSEvent *)event; -- (void)touchesMovedWithEvent:(NSEvent *)event; -- (void)touchesEndedWithEvent:(NSEvent *)event; -- (void)touchesCancelledWithEvent:(NSEvent *)event; - -#if CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD -- (void)queueEvent:(NSEvent*)event selector:(SEL)selector; -#endif - -@end - -/** MacGLView - - Only available for Mac OS X - */ -@interface CCEAGLView : NSOpenGLView { - id eventDelegate_; - - BOOL isFullScreen_; - NSWindow *fullScreenWindow_; - - // cache - NSWindow *windowGLView_; - NSView *superViewGLView_; - NSRect originalWinRect_; // Original size and position - - float frameZoomFactor_; -} - -@property (nonatomic, readwrite, assign) id eventDelegate; - -// whether or not the view is in fullscreen mode -@property (nonatomic, readonly) BOOL isFullScreen; - -@property (nonatomic, readwrite) float frameZoomFactor; - -// initializes the MacGLView with a frame rect and an OpenGL context -- (id) initWithFrame:(NSRect)frameRect shareContext:(NSOpenGLContext*)context; - -- (id) initWithFrame:(NSRect)frameRect pixelFormat:(NSOpenGLPixelFormat *)format; - -/** uses and locks the OpenGL context */ --(void) lockOpenGLContext; - -/** unlocks the openGL context */ --(void) unlockOpenGLContext; - -/** returns the depth format of the view in BPP */ -- (NSUInteger) depthFormat; - -- (void) setFrameZoomFactor:(float)frameZoomFactor; - -// get the view object -+(id) sharedEGLView; - --(int) getWidth; --(int) getHeight; --(void) swapBuffers; - --(void) setFullScreen:(BOOL)fullscreen; - -@end -#endif // __EAGLVIEW_MAC_H__ - diff --git a/cocos/2d/platform/mac/EAGLView.mm b/cocos/2d/platform/mac/EAGLView.mm deleted file mode 100644 index 68573ba99f..0000000000 --- a/cocos/2d/platform/mac/EAGLView.mm +++ /dev/null @@ -1,490 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2013-2014 Chukong Technologies Inc. - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -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. -****************************************************************************/ - -/* - * Idea of subclassing NSOpenGLView was taken from "TextureUpload" Apple's sample - */ - -#import - -#import "EAGLView.h" -#import "CCEGLView.h" -#import -#import "CCDirector.h" -#import "ccConfig.h" -#import "CCSet.h" -#import "CCTouch.h" -#import "CCIMEDispatcher.h" -#import "CCWindow.h" -#import "CCEventDispatcherMac.h" -#import "CCEGLView.h" - - -//USING_NS_CC; -static CCEAGLView *view; - -@implementation CCEAGLView - -@synthesize eventDelegate = eventDelegate_, isFullScreen = isFullScreen_, frameZoomFactor=frameZoomFactor_; - -+(id) sharedEGLView -{ - return view; -} - -- (id) initWithFrame:(NSRect)frameRect -{ - self = [self initWithFrame:frameRect shareContext:nil]; - return self; -} - -- (id) initWithFrame:(NSRect)frameRect shareContext:(NSOpenGLContext*)context -{ - NSOpenGLPixelFormatAttribute attribs[] = - { -// NSOpenGLPFAAccelerated, -// NSOpenGLPFANoRecovery, - NSOpenGLPFADoubleBuffer, - NSOpenGLPFADepthSize, 24, - - 0 - }; - - NSOpenGLPixelFormat *pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs]; - - if (!pixelFormat) - NSLog(@"No OpenGL pixel format"); - - if( (self = [super initWithFrame:frameRect pixelFormat:[pixelFormat autorelease]]) ) { - - if( context ) - [self setOpenGLContext:context]; - - // event delegate - eventDelegate_ = [CCEventDispatcher sharedDispatcher]; - } - - cocos2d::EGLView::getInstance()->setFrameSize(frameRect.size.width, frameRect.size.height); - - frameZoomFactor_ = 1.0f; - - view = self; - return self; -} - -- (id) initWithFrame:(NSRect)frameRect pixelFormat:(NSOpenGLPixelFormat *)format{ - // event delegate - eventDelegate_ = [CCEventDispatcher sharedDispatcher]; - - cocos2d::EGLView::getInstance()->setFrameSize(frameRect.size.width, frameRect.size.height); - - frameZoomFactor_ = 1.0f; - - view = self; - - [super initWithFrame:frameRect pixelFormat:format]; - - return self; -} - -- (void) update -{ - // XXX: Should I do something here ? - [super update]; -} - -- (void) prepareOpenGL -{ - // XXX: Initialize OpenGL context - - [super prepareOpenGL]; - - // Make this openGL context current to the thread - // (i.e. all openGL on this thread calls will go to this context) - [[self openGLContext] makeCurrentContext]; - - // Synchronize buffer swaps with vertical refresh rate - GLint swapInt = 1; - [[self openGLContext] setValues:&swapInt forParameter:NSOpenGLCPSwapInterval]; - -// GLint order = -1; -// [[self openGLContext] setValues:&order forParameter:NSOpenGLCPSurfaceOrder]; -} - -- (NSUInteger) depthFormat -{ - return 24; -} - -- (void) setFrameZoomFactor:(float)frameZoomFactor -{ - frameZoomFactor_ = frameZoomFactor; - - NSRect winRect = [[self window] frame]; - NSRect viewRect = [self frame]; - - // compute the margin width and margin height - float diffX = winRect.size.width - viewRect.size.width; - float diffY = winRect.size.height - viewRect.size.height; - - // new window width and height - float newWindowWidth = (int)(viewRect.size.width * frameZoomFactor + diffX); - float newWindowHeight = (int)(viewRect.size.height * frameZoomFactor + diffY); - - // display window in the center of the screen - NSRect screenRect = [[NSScreen mainScreen] frame]; - float originX = (screenRect.size.width - newWindowWidth) / 2; - float originY = (screenRect.size.height - newWindowHeight) / 2; - - [[self window] setFrame:NSMakeRect(originX, originY, newWindowWidth, newWindowHeight) display:true]; -} - -- (void) reshape -{ - // We draw on a secondary thread through the display link - // When resizing the view, -reshape is called automatically on the main thread - // Add a mutex around to avoid the threads accessing the context simultaneously when resizing - - [self lockOpenGLContext]; - -// NSRect rect = [self bounds]; - - cocos2d::Director *director = cocos2d::Director::getInstance(); -// CGSize size = NSSizeToCGSize(rect.size); -// cocos2d::Size ccsize = cocos2d::Size(size.width, size.height); - //director->reshapeProjection(ccsize); - - // avoid flicker - director->drawScene(); -// [self setNeedsDisplay:YES]; - - [self unlockOpenGLContext]; -} - --(void) lockOpenGLContext -{ - NSOpenGLContext *glContext = [self openGLContext]; - NSAssert( glContext, @"FATAL: could not get openGL context"); - - [glContext makeCurrentContext]; - CGLLockContext((CGLContextObj)[glContext CGLContextObj]); -} - --(void) unlockOpenGLContext -{ - NSOpenGLContext *glContext = [self openGLContext]; - NSAssert( glContext, @"FATAL: could not get openGL context"); - - CGLUnlockContext((CGLContextObj)[glContext CGLContextObj]); -} - -- (void) dealloc -{ - CCLOGINFO("deallocing CCEAGLView: %p", self); - [super dealloc]; -} - --(int) getWidth -{ - NSSize bound = [self bounds].size; - return bound.width; -} - --(int) getHeight -{ - NSSize bound = [self bounds].size; - return bound.height; -} - --(void) swapBuffers -{ -} - -// -// setFullScreen code taken from GLFullScreen example by Apple -// -- (void) setFullScreen:(BOOL)fullscreen -{ - // Mac OS X 10.6 and later offer a simplified mechanism to create full-screen contexts -#if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5 - - if (isFullScreen_ == fullscreen) - return; - - CCEAGLView *openGLview = [[self class] sharedEGLView]; - - if( fullscreen ) { - originalWinRect_ = [openGLview frame]; - - // Cache normal window and superview of openGLView - if(!windowGLView_) - windowGLView_ = [[openGLview window] retain]; - - [superViewGLView_ release]; - superViewGLView_ = [[openGLview superview] retain]; - - - // Get screen size - NSRect displayRect = [[NSScreen mainScreen] frame]; - - // Create a screen-sized window on the display you want to take over - fullScreenWindow_ = [[CCWindow alloc] initWithFrame:displayRect fullscreen:YES]; - - // Remove glView from window - [openGLview removeFromSuperview]; - - // Set new frame - [openGLview setFrame:displayRect]; - - // Attach glView to fullscreen window - [fullScreenWindow_ setContentView:openGLview]; - - // Show the fullscreen window - [fullScreenWindow_ makeKeyAndOrderFront:self]; - [fullScreenWindow_ makeMainWindow]; - //[fullScreenWindow_ setNextResponder:superViewGLView_]; - - } else { - - // Remove glView from fullscreen window - [openGLview removeFromSuperview]; - - // Release fullscreen window - [fullScreenWindow_ release]; - fullScreenWindow_ = nil; - - // Attach glView to superview - [superViewGLView_ addSubview:openGLview]; - - // Set new frame - [openGLview setFrame:originalWinRect_]; - - // Show the window - [windowGLView_ makeKeyAndOrderFront:self]; - [windowGLView_ makeMainWindow]; - } - - // issue #1189 - [windowGLView_ makeFirstResponder:openGLview]; - - isFullScreen_ = fullscreen; - - //[openGLview retain]; // Retain +1 - - // is this necessary? - // re-configure glView - //cocos2d::Director *director = cocos2d::Director::getInstance(); - //director->setOpenGLView(openGLview); //[self setView:openGLview]; - - //[openGLview release]; // Retain -1 - - [openGLview setNeedsDisplay:YES]; -#else -#error Full screen is not supported for Mac OS 10.5 or older yet -#error If you don't want FullScreen support, you can safely remove these 2 lines -#endif -} - -#if CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD -#define DISPATCH_EVENT(__event__, __selector__) [eventDelegate_ queueEvent:__event__ selector:__selector__]; -#else -#define DISPATCH_EVENT(__event__, __selector__) \ - id obj = eventDelegate_; \ - [obj performSelector:__selector__ \ - onThread:[(cocos2d::Director*)[Director sharedDirector] runningThread] \ - withObject:__event__ \ - waitUntilDone:NO]; -#endif - -#pragma mark CCEAGLView - Mouse events - -- (void)mouseDown:(NSEvent *)theEvent -{ - NSPoint event_location = [theEvent locationInWindow]; - NSPoint local_point = [self convertPoint:event_location fromView:nil]; - - float x = local_point.x; - float y = [self getHeight] - local_point.y; - - NSInteger ids[1] = {0}; - float xs[1] = {0.0f}; - float ys[1] = {0.0f}; - - ids[0] = [theEvent eventNumber]; - xs[0] = x / frameZoomFactor_; - ys[0] = y / frameZoomFactor_; - - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, (int*)ids, xs, ys); -} - -- (void)mouseMoved:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)mouseDragged:(NSEvent *)theEvent -{ - NSPoint event_location = [theEvent locationInWindow]; - NSPoint local_point = [self convertPoint:event_location fromView:nil]; - - float x = local_point.x; - float y = [self getHeight] - local_point.y; - - NSInteger ids[1] = {0}; - float xs[1] = {0.0f}; - float ys[1] = {0.0f}; - - ids[0] = [theEvent eventNumber]; - xs[0] = x / frameZoomFactor_; - ys[0] = y / frameZoomFactor_; - - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(1, (int*)ids, xs, ys); -} - -- (void)mouseUp:(NSEvent *)theEvent -{ - NSPoint event_location = [theEvent locationInWindow]; - NSPoint local_point = [self convertPoint:event_location fromView:nil]; - - float x = local_point.x; - float y = [self getHeight] - local_point.y; - - NSInteger ids[1] = {0}; - float xs[1] = {0.0f}; - float ys[1] = {0.0f}; - - ids[0] = [theEvent eventNumber]; - xs[0] = x / frameZoomFactor_; - ys[0] = y / frameZoomFactor_; - - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, (int*)ids, xs, ys); -} - -- (void)rightMouseDown:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); - - // pass the event along to the next responder (like your NSWindow subclass) - [super rightMouseDown:theEvent]; -} - -- (void)rightMouseDragged:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); - [super rightMouseDragged:theEvent]; -} - -- (void)rightMouseUp:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); - [super rightMouseUp:theEvent]; -} - -- (void)otherMouseDown:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); - [super otherMouseDown:theEvent]; -} - -- (void)otherMouseDragged:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); - [super otherMouseDragged:theEvent]; -} - -- (void)otherMouseUp:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); - [super otherMouseUp:theEvent]; -} - -- (void)mouseEntered:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); - [super mouseEntered:theEvent]; -} - -- (void)mouseExited:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); - [super mouseExited:theEvent]; -} - --(void) scrollWheel:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); - [super scrollWheel:theEvent]; -} - -#pragma mark CCEAGLView - Key events - --(BOOL) becomeFirstResponder -{ - return YES; -} - --(BOOL) acceptsFirstResponder -{ - return YES; -} - --(BOOL) resignFirstResponder -{ - return YES; -} - -- (void)keyDown:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); - - // pass the event along to the next responder (like your NSWindow subclass) - [super keyDown:theEvent]; -} - -- (void)keyUp:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); - - // pass the event along to the next responder (like your NSWindow subclass) - [super keyUp:theEvent]; -} - -- (void)flagsChanged:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -#pragma mark CCEAGLView - Touch events -- (void)touchesBeganWithEvent:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)touchesMovedWithEvent:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)touchesEndedWithEvent:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)touchesCancelledWithEvent:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} -@end diff --git a/cocos/2d/renderer/CCBatchCommand.cpp b/cocos/2d/renderer/CCBatchCommand.cpp index b9b0c7fab9..6b8d77c518 100644 --- a/cocos/2d/renderer/CCBatchCommand.cpp +++ b/cocos/2d/renderer/CCBatchCommand.cpp @@ -26,6 +26,7 @@ #include "renderer/CCBatchCommand.h" #include "ccGLStateCache.h" #include "CCTextureAtlas.h" +#include "CCTexture2D.h" NS_CC_BEGIN @@ -38,10 +39,13 @@ BatchCommand::BatchCommand() _shader = nullptr; } -void BatchCommand::init(float globalOrder, GLuint textureID, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform) +void BatchCommand::init(float globalOrder, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform) { + CCASSERT(shader, "shader cannot be nill"); + CCASSERT(textureAtlas, "textureAtlas cannot be nill"); + _globalOrder = globalOrder; - _textureID = textureID; + _textureID = textureAtlas->getTexture()->getName(); _blendType = blendType; _shader = shader; diff --git a/cocos/2d/renderer/CCBatchCommand.h b/cocos/2d/renderer/CCBatchCommand.h index 9ac5b346ee..a33f4ad891 100644 --- a/cocos/2d/renderer/CCBatchCommand.h +++ b/cocos/2d/renderer/CCBatchCommand.h @@ -43,19 +43,15 @@ public: BatchCommand(); ~BatchCommand(); - void init(float depth, GLuint texutreID, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform); + void init(float depth, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform); void execute(); protected: + //Material int32_t _materialID; - - //Maternal GLuint _textureID; - GLProgram* _shader; -// GLuint _shaderID; - BlendFunc _blendType; TextureAtlas *_textureAtlas; diff --git a/cocos/base/CCAutoreleasePool.cpp b/cocos/base/CCAutoreleasePool.cpp index 5e551ec3aa..76a273dfcb 100644 --- a/cocos/base/CCAutoreleasePool.cpp +++ b/cocos/base/CCAutoreleasePool.cpp @@ -27,54 +27,49 @@ THE SOFTWARE. NS_CC_BEGIN -static PoolManager* s_pPoolManager = NULL; - AutoreleasePool::AutoreleasePool() +:_name("") { _managedObjectArray.reserve(150); + PoolManager::getInstance()->push(this); +} + +AutoreleasePool::AutoreleasePool(const std::string &name) +:_name(name) +{ + _managedObjectArray.reserve(150); + PoolManager::getInstance()->push(this); } AutoreleasePool::~AutoreleasePool() { CCLOGINFO("deallocing AutoreleasePool: %p", this); + clear(); + + PoolManager::getInstance()->pop(); } void AutoreleasePool::addObject(Object* object) { - _managedObjectArray.pushBack(object); - - CCASSERT(object->_reference > 1, "reference count should be greater than 1"); - ++(object->_autoReleaseCount); - object->release(); // no ref count, in this case autorelease pool added. -} - -void AutoreleasePool::removeObject(Object* object) -{ - for (unsigned int i = 0; i < object->_autoReleaseCount; ++i) - { - _managedObjectArray.eraseObject(object, false); - } + _managedObjectArray.push_back(object); } void AutoreleasePool::clear() { - if (!_managedObjectArray.empty()) + for (const auto &obj : _managedObjectArray) { - //CCAutoreleasePool* pReleasePool; -#ifdef _DEBUG - int nIndex = _managedObjectArray.size() - 1; -#endif + obj->release(); + } + _managedObjectArray.clear(); +} - for(const auto &obj : _managedObjectArray) { - --(obj->_autoReleaseCount); - //(*it)->release(); - //delete (*it); -#ifdef _DEBUG - nIndex--; -#endif - } - - _managedObjectArray.clear(); +void AutoreleasePool::dump() +{ + CCLOG("autorelease pool: %s, number of managed object %d\n", _name.c_str(), static_cast(_managedObjectArray.size())); + CCLOG("%20s%20s%20s", "Object pointer", "Object id", "reference count"); + for (const auto &obj : _managedObjectArray) + { + CCLOG("%20p%20u%20u\n", obj, obj->_ID, obj->retainCount()); } } @@ -85,105 +80,67 @@ void AutoreleasePool::clear() // //-------------------------------------------------------------------- -PoolManager* PoolManager::sharedPoolManager() +PoolManager* PoolManager::s_singleInstance = nullptr; + +PoolManager* PoolManager::getInstance() { - if (s_pPoolManager == NULL) + if (s_singleInstance == nullptr) { - s_pPoolManager = new PoolManager(); + s_singleInstance = new PoolManager(); + // Add the first auto release pool + s_singleInstance->_curReleasePool = new AutoreleasePool("cocos2d autorelease pool"); + s_singleInstance->_releasePoolStack.push(s_singleInstance->_curReleasePool); } - return s_pPoolManager; + return s_singleInstance; } -void PoolManager::purgePoolManager() +void PoolManager::destroyInstance() { - CC_SAFE_DELETE(s_pPoolManager); + delete s_singleInstance; + s_singleInstance = nullptr; } PoolManager::PoolManager() { - _releasePoolStack.reserve(150); - _curReleasePool = 0; } PoolManager::~PoolManager() { CCLOGINFO("deallocing PoolManager: %p", this); - finalize(); - - // we only release the last autorelease pool here - _curReleasePool = 0; - _releasePoolStack.erase(0); -} - -void PoolManager::finalize() -{ - if (!_releasePoolStack.empty()) + + while (!_releasePoolStack.empty()) { - for(const auto &pool : _releasePoolStack) { - pool->clear(); - } + AutoreleasePool* pool = _releasePoolStack.top(); + _releasePoolStack.pop(); + + delete pool; } } -void PoolManager::push() + +AutoreleasePool* PoolManager::getCurrentPool() const { - AutoreleasePool* pool = new AutoreleasePool(); //ref = 1 + return _curReleasePool; +} + +void PoolManager::push(AutoreleasePool *pool) +{ + _releasePoolStack.push(pool); _curReleasePool = pool; - - _releasePoolStack.pushBack(pool); //ref = 2 - - pool->release(); //ref = 1 } void PoolManager::pop() { - if (! _curReleasePool) + // Can not pop the pool that created by engine + CC_ASSERT(_releasePoolStack.size() >= 1); + + _releasePoolStack.pop(); + + // Should update _curReleasePool if a temple pool is released + if (_releasePoolStack.size() > 1) { - return; + _curReleasePool = _releasePoolStack.top(); } - - ssize_t count = _releasePoolStack.size(); - - _curReleasePool->clear(); - - if (count > 1) - { - _releasePoolStack.erase(count-1); - -// if(nCount > 1) -// { -// _curReleasePool = _releasePoolStack.at(count - 2); -// return; -// } - _curReleasePool = _releasePoolStack.at(count - 2); - } - - /*_curReleasePool = NULL;*/ -} - -void PoolManager::removeObject(Object* object) -{ - CCASSERT(_curReleasePool, "current auto release pool should not be null"); - - _curReleasePool->removeObject(object); -} - -void PoolManager::addObject(Object* object) -{ - getCurReleasePool()->addObject(object); -} - - -AutoreleasePool* PoolManager::getCurReleasePool() -{ - if(!_curReleasePool) - { - push(); - } - - CCASSERT(_curReleasePool, "current auto release pool should not be null"); - - return _curReleasePool; } NS_CC_END diff --git a/cocos/base/CCAutoreleasePool.h b/cocos/base/CCAutoreleasePool.h index d6ee35349b..0415eb713e 100644 --- a/cocos/base/CCAutoreleasePool.h +++ b/cocos/base/CCAutoreleasePool.h @@ -25,8 +25,10 @@ THE SOFTWARE. #ifndef __AUTORELEASEPOOL_H__ #define __AUTORELEASEPOOL_H__ +#include +#include +#include #include "CCObject.h" -#include "CCVector.h" NS_CC_BEGIN @@ -35,24 +37,21 @@ NS_CC_BEGIN * @{ */ -class CC_DLL AutoreleasePool : public Object +class CC_DLL AutoreleasePool { - /** - * The underlying array of object managed by the pool. - * - * Although Array retains the object once when an object is added, proper - * Object::release() is called outside the array to make sure that the pool - * does not affect the managed object's reference count. So an object can - * be destructed properly by calling Object::release() even if the object - * is in the pool. - */ - Vector _managedObjectArray; public: /** + * @warn Don't create an auto release pool in heap, create it in stack. * @js NA * @lua NA */ AutoreleasePool(); + + /** + * Create an autorelease pool with specific name. This name is useful for debugging. + */ + AutoreleasePool(const std::string &name); + /** * @js NA * @lua NA @@ -72,15 +71,6 @@ public: */ void addObject(Object *object); - /** - * Remove a given object from this pool. - * - * @param object The object to be removed from the pool. - * @js NA - * @lua NA - */ - void removeObject(Object *object); - /** * Clear the autorelease pool. * @@ -90,88 +80,70 @@ public: * @lua NA */ void clear(); + + /** + * Dump the objects that are put into autorelease pool. It is used for debugging. + * + * The result will look like: + * Object pointer address object id reference count + * + */ + void dump(); + +private: + /** + * The underlying array of object managed by the pool. + * + * Although Array retains the object once when an object is added, proper + * Object::release() is called outside the array to make sure that the pool + * does not affect the managed object's reference count. So an object can + * be destructed properly by calling Object::release() even if the object + * is in the pool. + */ + std::vector _managedObjectArray; + std::string _name; }; class CC_DLL PoolManager { - Vector _releasePoolStack; - AutoreleasePool *_curReleasePool; - - AutoreleasePool *getCurReleasePool(); public: /** * @js NA * @lua NA */ - static PoolManager* sharedPoolManager(); + CC_DEPRECATED_ATTRIBUTE static PoolManager* sharedPoolManager() { return getInstance(); } + static PoolManager* getInstance(); + /** * @js NA * @lua NA */ - static void purgePoolManager(); + CC_DEPRECATED_ATTRIBUTE static void purgePoolManager() { destroyInstance(); } + static void destroyInstance(); + /** - * @js NA - * @lua NA + * Get current auto release pool, there is at least one auto release pool that created by engine. + * You can create your own auto release pool at demand, which will be put into auto releae pool stack. */ - PoolManager(); - /** - * @js NA - * @lua NA - */ - ~PoolManager(); + AutoreleasePool *getCurrentPool() const; - /** - * Clear all the AutoreleasePool on the pool stack. - * @js NA - * @lua NA - */ - void finalize(); - - /** - * Push a new AutoreleasePool to the pool stack. - * @js NA - * @lua NA - */ - void push(); - - /** - * Pop one AutoreleasePool from the pool stack. - * - * This method will ensure that there is at least one AutoreleasePool on - * the stack. - * - * The AutoreleasePool being poped is destructed. - * @js NA - * @lua NA - */ - void pop(); - - /** - * Remove a given object from the current autorelease pool. - * - * @param object The object to be removed. - * - * @see AutoreleasePool::removeObject - * @js NA - * @lua NA - */ - void removeObject(Object *object); - - /** - * Add a given object to the current autorelease pool. - * - * @param object The object to add. - * - * @see AutoreleasePool::addObject - * @js NA - * @lua NA - */ - void addObject(Object *object); /** * @js NA * @lua NA */ friend class AutoreleasePool; + +private: + PoolManager(); + ~PoolManager(); + + void push(AutoreleasePool *pool); + void pop(); + + static PoolManager* s_singleInstance; + + std::stack _releasePoolStack; + AutoreleasePool *_curReleasePool; }; // end of base_nodes group diff --git a/cocos/base/CCObject.cpp b/cocos/base/CCObject.cpp index 09dc4399f6..b1cc8f49d0 100644 --- a/cocos/base/CCObject.cpp +++ b/cocos/base/CCObject.cpp @@ -34,7 +34,6 @@ NS_CC_BEGIN Object::Object() : _luaID(0) , _reference(1) // when the object is created, the reference count of it is 1 -, _autoReleaseCount(0) { static unsigned int uObjectCount = 0; @@ -43,13 +42,6 @@ Object::Object() Object::~Object() { - // if the object is managed, we should remove it - // from pool manager - if (_autoReleaseCount > 0) - { - PoolManager::sharedPoolManager()->removeObject(this); - } - // if the object is referenced by Lua engine, remove it if (_luaID) { @@ -67,7 +59,7 @@ Object::~Object() Object* Object::autorelease() { - PoolManager::sharedPoolManager()->addObject(this); + PoolManager::getInstance()->getCurrentPool()->addObject(this); return this; } diff --git a/cocos/base/CCObject.h b/cocos/base/CCObject.h index 2280508856..49b201b871 100644 --- a/cocos/base/CCObject.h +++ b/cocos/base/CCObject.h @@ -71,14 +71,12 @@ class CC_DLL Object { public: /// object id, ScriptSupport need public _ID - unsigned int _ID; + unsigned int _ID; /// Lua reference id - int _luaID; + int _luaID; protected: /// count of references - unsigned int _reference; - /// count of autorelease - unsigned int _autoReleaseCount; + unsigned int _reference; public: /** * Constructor diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index de699f63ae..68ff365557 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit de699f63aef423c3d90725171b0f020a719ef572 +Subproject commit 68ff365557a8bdb119c2a4e2502214b4d1025c7e diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id b/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id index e296678e5b..4089e57f63 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id @@ -1 +1 @@ -9d9d07e19dba691a22e4d184f0ec0e6ae6207a9b \ No newline at end of file +85c7400aec0f87b3851772fbdbc01bf59f5402d8 \ No newline at end of file diff --git a/cocos/scripting/lua/script/Cocos2dConstants.lua b/cocos/scripting/lua/script/Cocos2dConstants.lua index 9e12b80b6a..2bcb461d27 100644 --- a/cocos/scripting/lua/script/Cocos2dConstants.lua +++ b/cocos/scripting/lua/script/Cocos2dConstants.lua @@ -359,3 +359,11 @@ cc.GLYPHCOLLECTION_NEHE = 1 cc.GLYPHCOLLECTION_ASCII = 2 cc.GLYPHCOLLECTION_CUSTOM = 3 +cc.LabelEffect = +{ + NORMAL = 0, + OUTLINE = 1, + SHADOW = 2, + GLOW = 3, +} + diff --git a/cocos/scripting/lua/script/Deprecated.lua b/cocos/scripting/lua/script/Deprecated.lua index 38ae6ff614..84cb38409f 100644 --- a/cocos/scripting/lua/script/Deprecated.lua +++ b/cocos/scripting/lua/script/Deprecated.lua @@ -1112,3 +1112,19 @@ end rawset(CCEGLView,"sharedOpenGLView",CCEGLViewDeprecated.sharedOpenGLView) --functions of CCEGLView will be deprecated end +--functions of cc.Node will be deprecated begin +local NodeDeprecated = { } +function NodeDeprecated.setZOrder(self,zOrder) + deprecatedTip("cc.Node:setZOrder","cc.Node:setLocalZOrder") + return self:setLocalZOrder(zOrder) +end +rawset(cc.Node,"setZOrder",NodeDeprecated.setZOrder) + +function NodeDeprecated.getZOrder(self) + deprecatedTip("cc.Node:getZOrder","cc.Node:getLocalZOrder") + return self:getLocalZOrder() +end +rawset(cc.Node,"getZOrder",NodeDeprecated.getZOrder) +--functions of cc.Node will be deprecated end + + diff --git a/extensions/GUI/CCEditBox/CCEditBoxImplMac.mm b/extensions/GUI/CCEditBox/CCEditBoxImplMac.mm index a3f7654bd5..cdfab6a402 100644 --- a/extensions/GUI/CCEditBox/CCEditBoxImplMac.mm +++ b/extensions/GUI/CCEditBox/CCEditBoxImplMac.mm @@ -28,10 +28,15 @@ #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) #include "CCEditBox.h" -#import "EAGLView.h" +#define GLFW_EXPOSE_NATIVE_NSGL +#define GLFW_EXPOSE_NATIVE_COCOA +#include "glfw3native.h" + #define getEditBoxImplMac() ((cocos2d::extension::EditBoxImplMac*)editBox_) + + @implementation CCCustomNSTextField - (CGRect)textRectForBounds:(CGRect)bounds { @@ -58,6 +63,10 @@ @synthesize editState = editState_; @synthesize editBox = editBox_; +- (id) getNSWindow { + return glfwGetCocoaWindow(cocos2d::EGLView::getInstance()->getWindow()); +} + - (void)dealloc { [textField_ resignFirstResponder]; @@ -84,7 +93,7 @@ [textField_ setDelegate:self]; self.editBox = editBox; - [[CCEAGLView sharedEGLView] addSubview:textField_]; + [[[self getNSWindow] contentView] addSubview:textField_]; return self; }while(0); @@ -94,8 +103,7 @@ -(void) doAnimationWhenKeyboardMoveWithDuration:(float)duration distance:(float)distance { - id eglView = [CCEAGLView sharedEGLView]; - [eglView doAnimationWhenKeyboardMoveWithDuration:duration distance:distance]; + [[[self getNSWindow] contentView] doAnimationWhenKeyboardMoveWithDuration:duration distance:distance]; } -(void) setPosition:(NSPoint) pos diff --git a/samples/Cpp/TestCpp/Android.mk b/samples/Cpp/TestCpp/Android.mk index 1d661d5aa1..fa93be3210 100644 --- a/samples/Cpp/TestCpp/Android.mk +++ b/samples/Cpp/TestCpp/Android.mk @@ -123,7 +123,9 @@ Classes/PerformanceTest/PerformanceTouchesTest.cpp \ Classes/PerformanceTest/PerformanceLabelTest.cpp \ Classes/PerformanceTest/PerformanceRendererTest.cpp \ Classes/PerformanceTest/PerformanceContainerTest.cpp \ +Classes/PerformanceTest/PerformanceEventDispatcherTest.cpp \ Classes/PhysicsTest/PhysicsTest.cpp \ +Classes/ReleasePoolTest/ReleasePoolTest.cpp \ Classes/RenderTextureTest/RenderTextureTest.cpp \ Classes/RotateWorldTest/RotateWorldTest.cpp \ Classes/SceneTest/SceneTest.cpp \ diff --git a/samples/Cpp/TestCpp/CMakeLists.txt b/samples/Cpp/TestCpp/CMakeLists.txt index df0a738a87..bdc404e01f 100644 --- a/samples/Cpp/TestCpp/CMakeLists.txt +++ b/samples/Cpp/TestCpp/CMakeLists.txt @@ -118,7 +118,9 @@ set(SAMPLE_SRC Classes/PerformanceTest/PerformanceLabelTest.cpp Classes/PerformanceTest/PerformanceRendererTest.cpp Classes/PerformanceTest/PerformanceContainerTest.cpp + Classes/PerformanceTest/PerformanceEventDispatcherTest.cpp Classes/PhysicsTest/PhysicsTest.cpp + Classes/ReleasePoolTest/ReleasePoolTest.cpp Classes/RenderTextureTest/RenderTextureTest.cpp Classes/RotateWorldTest/RotateWorldTest.cpp Classes/SceneTest/SceneTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ActionsProgressTest/ActionsProgressTest.h b/samples/Cpp/TestCpp/Classes/ActionsProgressTest/ActionsProgressTest.h index 9e16818164..f453ac0c2f 100644 --- a/samples/Cpp/TestCpp/Classes/ActionsProgressTest/ActionsProgressTest.h +++ b/samples/Cpp/TestCpp/Classes/ActionsProgressTest/ActionsProgressTest.h @@ -24,7 +24,7 @@ ****************************************************************************/ #ifndef _ACTIONS__PROGRESS_TEST_H_ -#define _ACTIONS_PROGRESS_TEST_H_ +#define _ACTIONS__PROGRESS_TEST_H_ #include "../testBasic.h" #include "../BaseTest.h" @@ -99,4 +99,4 @@ public: virtual void runThisTest(); }; -#endif +#endif // _ACTIONS__PROGRESS_TEST_H_ diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceEventDispatcherTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceEventDispatcherTest.cpp new file mode 100644 index 0000000000..28953d22ff --- /dev/null +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceEventDispatcherTest.cpp @@ -0,0 +1,795 @@ +// +// PerformanceEventDispatcherTest.cpp +// + +#include "PerformanceEventDispatcherTest.h" + +#include + +// Enable profiles for this file +#undef CC_PROFILER_DISPLAY_TIMERS +#define CC_PROFILER_DISPLAY_TIMERS() Profiler::getInstance()->displayTimers() +#undef CC_PROFILER_PURGE_ALL +#define CC_PROFILER_PURGE_ALL() Profiler::getInstance()->releaseAllTimers() + +#undef CC_PROFILER_START +#define CC_PROFILER_START(__name__) ProfilingBeginTimingBlock(__name__) +#undef CC_PROFILER_STOP +#define CC_PROFILER_STOP(__name__) ProfilingEndTimingBlock(__name__) +#undef CC_PROFILER_RESET +#define CC_PROFILER_RESET(__name__) ProfilingResetTimingBlock(__name__) + +#undef CC_PROFILER_START_CATEGORY +#define CC_PROFILER_START_CATEGORY(__cat__, __name__) do{ if(__cat__) ProfilingBeginTimingBlock(__name__); } while(0) +#undef CC_PROFILER_STOP_CATEGORY +#define CC_PROFILER_STOP_CATEGORY(__cat__, __name__) do{ if(__cat__) ProfilingEndTimingBlock(__name__); } while(0) +#undef CC_PROFILER_RESET_CATEGORY +#define CC_PROFILER_RESET_CATEGORY(__cat__, __name__) do{ if(__cat__) ProfilingResetTimingBlock(__name__); } while(0) + +#undef CC_PROFILER_START_INSTANCE +#define CC_PROFILER_START_INSTANCE(__id__, __name__) do{ ProfilingBeginTimingBlock( String::createWithFormat("%08X - %s", __id__, __name__)->getCString() ); } while(0) +#undef CC_PROFILER_STOP_INSTANCE +#define CC_PROFILER_STOP_INSTANCE(__id__, __name__) do{ ProfilingEndTimingBlock( String::createWithFormat("%08X - %s", __id__, __name__)->getCString() ); } while(0) +#undef CC_PROFILER_RESET_INSTANCE +#define CC_PROFILER_RESET_INSTANCE(__id__, __name__) do{ ProfilingResetTimingBlock( String::createWithFormat("%08X - %s", __id__, __name__)->getCString() ); } while(0) + +static std::function createFunctions[] = +{ + CL(TouchEventDispatchingPerfTest), + CL(KeyboardEventDispatchingPerfTest), + CL(CustomEventDispatchingPerfTest), +}; + +#define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0])) + +enum { + kTagInfoLayer = 1, + + kTagBase = 20000, +}; + +enum { + kMaxNodes = 15000, + kNodesIncrease = 500, +}; + +static int g_curCase = 0; + +//////////////////////////////////////////////////////// +// +// EventDispatcherBasicLayer +// +//////////////////////////////////////////////////////// + +EventDispatcherBasicLayer::EventDispatcherBasicLayer(bool bControlMenuVisible, int nMaxCases, int nCurCase) +: PerformBasicLayer(bControlMenuVisible, nMaxCases, nCurCase) +{ +} + +void EventDispatcherBasicLayer::showCurrentTest() +{ + int nodes = ((PerformanceEventDispatcherScene*)getParent())->getQuantityOfNodes(); + + auto scene = createFunctions[_curCase](); + + g_curCase = _curCase; + + if (scene) + { + scene->initWithQuantityOfNodes(nodes); + + Director::getInstance()->replaceScene(scene); + } +} + +//////////////////////////////////////////////////////// +// +// PerformanceEventDispatcherScene +// +//////////////////////////////////////////////////////// +void PerformanceEventDispatcherScene::initWithQuantityOfNodes(unsigned int nNodes) +{ + _type = 0; + srand(time(nullptr)); + auto s = Director::getInstance()->getWinSize(); + + // Title + auto label = LabelTTF::create(title().c_str(), "Arial", 40); + addChild(label, 1, TAG_TITLE); + label->setPosition(Point(s.width/2, s.height-32)); + label->setColor(Color3B(255,255,40)); + + // Subtitle + std::string strSubTitle = subtitle(); + if(strSubTitle.length()) + { + auto l = LabelTTF::create(strSubTitle.c_str(), "Thonburi", 16); + addChild(l, 1, TAG_SUBTITLE); + l->setPosition(Point(s.width/2, s.height-80)); + } + + _lastRenderedCount = 0; + _currentQuantityOfNodes = 0; + _quantityOfNodes = nNodes; + + MenuItemFont::setFontSize(65); + auto decrease = MenuItemFont::create(" - ", [&](Object *sender) { + _quantityOfNodes -= kNodesIncrease; + if( _quantityOfNodes < 0 ) + _quantityOfNodes = 0; + + updateQuantityLabel(); + updateQuantityOfNodes(); + updateProfilerName(); + CC_PROFILER_PURGE_ALL(); + srand(0); + }); + decrease->setColor(Color3B(0,200,20)); + _decrease = decrease; + + auto increase = MenuItemFont::create(" + ", [&](Object *sender) { + _quantityOfNodes += kNodesIncrease; + if( _quantityOfNodes > kMaxNodes ) + _quantityOfNodes = kMaxNodes; + + updateQuantityLabel(); + updateQuantityOfNodes(); + updateProfilerName(); + CC_PROFILER_PURGE_ALL(); + srand(0); + }); + increase->setColor(Color3B(0,200,20)); + _increase = increase; + + auto menu = Menu::create(decrease, increase, NULL); + menu->alignItemsHorizontally(); + menu->setPosition(Point(s.width/2, s.height/2+15)); + addChild(menu, 1); + + auto infoLabel = LabelTTF::create("0 listeners", "Marker Felt", 30); + infoLabel->setColor(Color3B(0,200,20)); + infoLabel->setPosition(Point(s.width/2, s.height/2-15)); + addChild(infoLabel, 1, kTagInfoLayer); + + auto menuLayer = new EventDispatcherBasicLayer(true, MAX_LAYER, g_curCase); + addChild(menuLayer); + menuLayer->release(); + + printf("Size of Node: %lu\n", sizeof(Node)); + + int oldFontSize = MenuItemFont::getFontSize(); + MenuItemFont::setFontSize(24); + + Vector toggleItems; + + generateTestFunctions(); + + CCASSERT(!_testFunctions.empty(), "Should not be empty after generate test functions"); + + + for (const auto& f : _testFunctions) + { + toggleItems.pushBack(MenuItemFont::create(f.name)); + } + + auto reset = [this](){ + // Removes all nodes + for (auto& node : _nodes) + { + node->removeFromParent(); + } + + _nodes.clear(); + + // Removes all fixed listeners + for (auto& listener : _fixedPriorityListeners) + { + Director::getInstance()->getEventDispatcher()->removeEventListener(listener); + } + + this->_lastRenderedCount = 0; + }; + + auto toggle = MenuItemToggle::createWithCallback([=](Object* sender){ + auto toggle = static_cast(sender); + this->_type = toggle->getSelectedIndex(); + auto label = static_cast(this->getChildByTag(TAG_SUBTITLE)); + label->setString(StringUtils::format("Test '%s', See console", this->_testFunctions[this->_type].name)); + this->updateProfilerName(); + reset(); + }, toggleItems); + + toggle->setAnchorPoint(Point::ANCHOR_MIDDLE_LEFT); + toggle->setPosition(VisibleRect::left()); + _toggle = toggle; + + auto start = MenuItemFont::create("start", [this](Object* sender){ + auto director = Director::getInstance(); + auto sched = director->getScheduler(); + + CC_PROFILER_PURGE_ALL(); + sched->scheduleSelector(schedule_selector(PerformanceEventDispatcherScene::dumpProfilerInfo), this, 2, false); + + this->unscheduleUpdate(); + this->scheduleUpdate(); + this->_startItem->setEnabled(false); + this->_stopItem->setEnabled(true); + this->_toggle->setEnabled(false); + this->_increase->setEnabled(false); + this->_decrease->setEnabled(false); + }); + start->setAnchorPoint(Point::ANCHOR_MIDDLE_RIGHT); + start->setPosition(VisibleRect::right() + Point(0, 40)); + _startItem = start; + + auto stop = MenuItemFont::create("stop", [=](Object* sender){ + auto director = Director::getInstance(); + auto sched = director->getScheduler(); + + sched->unscheduleSelector(schedule_selector(PerformanceEventDispatcherScene::dumpProfilerInfo), this); + + this->unscheduleUpdate(); + this->_startItem->setEnabled(true); + this->_stopItem->setEnabled(false); + this->_toggle->setEnabled(true); + this->_increase->setEnabled(true); + this->_decrease->setEnabled(true); + + reset(); + }); + + stop->setEnabled(false); + stop->setAnchorPoint(Point::ANCHOR_MIDDLE_RIGHT); + stop->setPosition(VisibleRect::right() + Point(0, -40)); + _stopItem = stop; + + auto menu2 = Menu::create(toggle, start, stop, NULL); + menu2->setPosition(Point::ZERO); + addChild(menu2); + + MenuItemFont::setFontSize(oldFontSize); + + updateQuantityLabel(); + updateQuantityOfNodes(); + updateProfilerName(); +} + +std::string PerformanceEventDispatcherScene::title() const +{ + return "No title"; +} + +std::string PerformanceEventDispatcherScene::subtitle() const +{ + return ""; +} + +void PerformanceEventDispatcherScene::updateQuantityLabel() +{ + if( _quantityOfNodes != _lastRenderedCount ) + { + auto infoLabel = static_cast( getChildByTag(kTagInfoLayer) ); + char str[20] = {0}; + sprintf(str, "%u listeners", _quantityOfNodes); + infoLabel->setString(str); + } +} + +const char * PerformanceEventDispatcherScene::profilerName() +{ + return _profilerName; +} + +void PerformanceEventDispatcherScene::updateProfilerName() +{ + snprintf(_profilerName, sizeof(_profilerName)-1, "%s(%d)", testName(), _quantityOfNodes); +} + +void PerformanceEventDispatcherScene::dumpProfilerInfo(float dt) +{ + CC_PROFILER_DISPLAY_TIMERS(); +} + +void PerformanceEventDispatcherScene::update(float dt) +{ + _testFunctions[_type].func(); +} + +void PerformanceEventDispatcherScene::updateQuantityOfNodes() +{ + _currentQuantityOfNodes = _quantityOfNodes; +} + +const char* PerformanceEventDispatcherScene::testName() +{ + return _testFunctions[_type].name; +} + + +//////////////////////////////////////////////////////// +// +// TouchEventDispatchingPerfTest +// +//////////////////////////////////////////////////////// + +void TouchEventDispatchingPerfTest::generateTestFunctions() +{ + TestFunction testFunctions[] = { + { "OneByOne-scenegraph", [=](){ + auto dispatcher = Director::getInstance()->getEventDispatcher(); + if (_quantityOfNodes != _lastRenderedCount) + { + auto listener = EventListenerTouchOneByOne::create(); + listener->onTouchBegan = [](Touch* touch, Event* event){ + return false; + }; + + listener->onTouchMoved = [](Touch* touch, Event* event){}; + listener->onTouchEnded = [](Touch* touch, Event* event){}; + + // Create new touchable nodes + for (int i = 0; i < this->_quantityOfNodes; ++i) + { + auto node = Node::create(); + node->setTag(1000 + i); + this->addChild(node); + this->_nodes.push_back(node); + dispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), node); + } + + _lastRenderedCount = _quantityOfNodes; + } + + Size size = Director::getInstance()->getWinSize(); + EventTouch touchEvent; + touchEvent.setEventCode(EventTouch::EventCode::BEGAN); + std::vector touches; + + for (int i = 0; i < 4; ++i) + { + Touch* touch = new Touch(); + touch->autorelease(); + touch->setTouchInfo(i, rand() % 200, rand() % 200); + touches.push_back(touch); + } + touchEvent.setTouches(touches); + + CC_PROFILER_START(this->profilerName()); + dispatcher->dispatchEvent(&touchEvent); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "OneByOne-fixed", [=](){ + auto dispatcher = Director::getInstance()->getEventDispatcher(); + if (_quantityOfNodes != _lastRenderedCount) + { + auto listener = EventListenerTouchOneByOne::create(); + listener->onTouchBegan = [](Touch* touch, Event* event){ + return false; + }; + + listener->onTouchMoved = [](Touch* touch, Event* event){}; + listener->onTouchEnded = [](Touch* touch, Event* event){}; + + for (int i = 0; i < this->_quantityOfNodes; ++i) + { + auto l = listener->clone(); + this->_fixedPriorityListeners.push_back(l); + dispatcher->addEventListenerWithFixedPriority(l, i+1); + } + + _lastRenderedCount = _quantityOfNodes; + } + + Size size = Director::getInstance()->getWinSize(); + EventTouch touchEvent; + touchEvent.setEventCode(EventTouch::EventCode::BEGAN); + std::vector touches; + + for (int i = 0; i < 4; ++i) + { + Touch* touch = new Touch(); + touch->autorelease(); + touch->setTouchInfo(i, rand() % 200, rand() % 200); + touches.push_back(touch); + } + touchEvent.setTouches(touches); + + CC_PROFILER_START(this->profilerName()); + dispatcher->dispatchEvent(&touchEvent); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "AllAtOnce-scenegraph", [=](){ + auto dispatcher = Director::getInstance()->getEventDispatcher(); + if (_quantityOfNodes != _lastRenderedCount) + { + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesBegan = [](const std::vector touches, Event* event){}; + listener->onTouchesMoved = [](const std::vector touches, Event* event){}; + listener->onTouchesEnded = [](const std::vector touches, Event* event){}; + + // Create new touchable nodes + for (int i = 0; i < this->_quantityOfNodes; ++i) + { + auto node = Node::create(); + node->setTag(1000 + i); + this->addChild(node); + this->_nodes.push_back(node); + dispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), node); + } + + _lastRenderedCount = _quantityOfNodes; + } + + Size size = Director::getInstance()->getWinSize(); + EventTouch touchEvent; + touchEvent.setEventCode(EventTouch::EventCode::BEGAN); + std::vector touches; + + for (int i = 0; i < 4; ++i) + { + Touch* touch = new Touch(); + touch->autorelease(); + touch->setTouchInfo(i, rand() % 200, rand() % 200); + touches.push_back(touch); + } + touchEvent.setTouches(touches); + + CC_PROFILER_START(this->profilerName()); + dispatcher->dispatchEvent(&touchEvent); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "AllAtOnce-fixed", [=](){ + auto dispatcher = Director::getInstance()->getEventDispatcher(); + if (_quantityOfNodes != _lastRenderedCount) + { + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesBegan = [](const std::vector touches, Event* event){}; + listener->onTouchesMoved = [](const std::vector touches, Event* event){}; + listener->onTouchesEnded = [](const std::vector touches, Event* event){}; + + for (int i = 0; i < this->_quantityOfNodes; ++i) + { + auto l = listener->clone(); + this->_fixedPriorityListeners.push_back(l); + dispatcher->addEventListenerWithFixedPriority(l, i+1); + } + + _lastRenderedCount = _quantityOfNodes; + } + + Size size = Director::getInstance()->getWinSize(); + EventTouch touchEvent; + touchEvent.setEventCode(EventTouch::EventCode::BEGAN); + std::vector touches; + + for (int i = 0; i < 4; ++i) + { + Touch* touch = new Touch(); + touch->autorelease(); + touch->setTouchInfo(i, rand() % 200, rand() % 200); + touches.push_back(touch); + } + touchEvent.setTouches(touches); + + CC_PROFILER_START(this->profilerName()); + dispatcher->dispatchEvent(&touchEvent); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "TouchModeMix-scenegraph", [=](){ + auto dispatcher = Director::getInstance()->getEventDispatcher(); + if (_quantityOfNodes != _lastRenderedCount) + { + auto listenerOneByOne = EventListenerTouchOneByOne::create(); + listenerOneByOne->onTouchBegan = [](Touch* touch, Event* event){ + return false; + }; + + listenerOneByOne->onTouchMoved = [](Touch* touch, Event* event){}; + listenerOneByOne->onTouchEnded = [](Touch* touch, Event* event){}; + + auto listenerAllAtOnce = EventListenerTouchAllAtOnce::create(); + listenerAllAtOnce->onTouchesBegan = [](const std::vector touches, Event* event){}; + listenerAllAtOnce->onTouchesMoved = [](const std::vector touches, Event* event){}; + listenerAllAtOnce->onTouchesEnded = [](const std::vector touches, Event* event){}; + + int i = 0; + // Create new touchable nodes + for (; i < this->_quantityOfNodes/2; ++i) + { + auto node = Node::create(); + node->setTag(1000 + i); + this->addChild(node); + this->_nodes.push_back(node); + dispatcher->addEventListenerWithSceneGraphPriority(listenerOneByOne->clone(), node); + } + + for (; i < this->_quantityOfNodes; ++i) + { + auto node = Node::create(); + node->setTag(1000 + i); + this->addChild(node); + this->_nodes.push_back(node); + dispatcher->addEventListenerWithSceneGraphPriority(listenerAllAtOnce->clone(), node); + } + + _lastRenderedCount = _quantityOfNodes; + } + + Size size = Director::getInstance()->getWinSize(); + EventTouch touchEvent; + touchEvent.setEventCode(EventTouch::EventCode::BEGAN); + std::vector touches; + + for (int i = 0; i < 4; ++i) + { + Touch* touch = new Touch(); + touch->autorelease(); + touch->setTouchInfo(i, rand() % 200, rand() % 200); + touches.push_back(touch); + } + touchEvent.setTouches(touches); + + CC_PROFILER_START(this->profilerName()); + dispatcher->dispatchEvent(&touchEvent); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "TouchModeMix-fixed", [=](){ + auto dispatcher = Director::getInstance()->getEventDispatcher(); + if (_quantityOfNodes != _lastRenderedCount) + { + auto listenerOneByOne = EventListenerTouchOneByOne::create(); + listenerOneByOne->onTouchBegan = [](Touch* touch, Event* event){ + return false; + }; + + listenerOneByOne->onTouchMoved = [](Touch* touch, Event* event){}; + listenerOneByOne->onTouchEnded = [](Touch* touch, Event* event){}; + + auto listenerAllAtOnce = EventListenerTouchAllAtOnce::create(); + listenerAllAtOnce->onTouchesBegan = [](const std::vector touches, Event* event){}; + listenerAllAtOnce->onTouchesMoved = [](const std::vector touches, Event* event){}; + listenerAllAtOnce->onTouchesEnded = [](const std::vector touches, Event* event){}; + + int i = 0; + + for (; i < this->_quantityOfNodes/2; ++i) + { + auto l = listenerOneByOne->clone(); + this->_fixedPriorityListeners.push_back(l); + dispatcher->addEventListenerWithFixedPriority(l, i+1); + } + + for (; i < this->_quantityOfNodes; ++i) + { + auto l = listenerAllAtOnce->clone(); + this->_fixedPriorityListeners.push_back(l); + dispatcher->addEventListenerWithFixedPriority(l, i+1); + } + + _lastRenderedCount = _quantityOfNodes; + } + + Size size = Director::getInstance()->getWinSize(); + EventTouch touchEvent; + touchEvent.setEventCode(EventTouch::EventCode::BEGAN); + std::vector touches; + + for (int i = 0; i < 4; ++i) + { + Touch* touch = new Touch(); + touch->autorelease(); + touch->setTouchInfo(i, rand() % 200, rand() % 200); + touches.push_back(touch); + } + touchEvent.setTouches(touches); + + CC_PROFILER_START(this->profilerName()); + dispatcher->dispatchEvent(&touchEvent); + CC_PROFILER_STOP(this->profilerName()); + } } , + }; + + for (const auto& func : testFunctions) + { + _testFunctions.push_back(func); + } +} + +std::string TouchEventDispatchingPerfTest::title() const +{ + return "Touch Event Dispatching Perf test"; +} + +std::string TouchEventDispatchingPerfTest::subtitle() const +{ + return "Test 'OneByOne-scenegraph', See console"; +} + +//////////////////////////////////////////////////////// +// +// KeyboardEventDispatchingPerfTest +// +//////////////////////////////////////////////////////// + +void KeyboardEventDispatchingPerfTest::generateTestFunctions() +{ + TestFunction testFunctions[] = { + { "keyboard-scenegraph", [=](){ + auto dispatcher = Director::getInstance()->getEventDispatcher(); + if (_quantityOfNodes != _lastRenderedCount) + { + auto listener = EventListenerKeyboard::create(); + listener->onKeyPressed = [](EventKeyboard::KeyCode keyCode, Event* event){}; + listener->onKeyReleased = [](EventKeyboard::KeyCode keyCode, Event* event){}; + + // Create new nodes listen to keyboard event + for (int i = 0; i < this->_quantityOfNodes; ++i) + { + auto node = Node::create(); + node->setTag(1000 + i); + this->addChild(node); + this->_nodes.push_back(node); + dispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), node); + } + + _lastRenderedCount = _quantityOfNodes; + } + + EventKeyboard event(EventKeyboard::KeyCode::KEY_RETURN, true); + + CC_PROFILER_START(this->profilerName()); + dispatcher->dispatchEvent(&event); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "keyboard-fixed", [=](){ + auto dispatcher = Director::getInstance()->getEventDispatcher(); + if (_quantityOfNodes != _lastRenderedCount) + { + auto listener = EventListenerKeyboard::create(); + listener->onKeyPressed = [](EventKeyboard::KeyCode keyCode, Event* event){}; + listener->onKeyReleased = [](EventKeyboard::KeyCode keyCode, Event* event){}; + + for (int i = 0; i < this->_quantityOfNodes; ++i) + { + auto l = listener->clone(); + this->_fixedPriorityListeners.push_back(l); + dispatcher->addEventListenerWithFixedPriority(l, i+1); + } + + _lastRenderedCount = _quantityOfNodes; + } + + EventKeyboard event(EventKeyboard::KeyCode::KEY_RETURN, true); + + CC_PROFILER_START(this->profilerName()); + dispatcher->dispatchEvent(&event); + CC_PROFILER_STOP(this->profilerName()); + } } , + }; + + for (const auto& func : testFunctions) + { + _testFunctions.push_back(func); + } +} + +std::string KeyboardEventDispatchingPerfTest::title() const +{ + return "Keyboard Event Dispatching Perf test"; +} + +std::string KeyboardEventDispatchingPerfTest::subtitle() const +{ + return "Test 'keyboard-scenegraph', See console"; +} + +//////////////////////////////////////////////////////// +// +// CustomEventDispatchingPerfTest +// +//////////////////////////////////////////////////////// + +void CustomEventDispatchingPerfTest::onEnter() +{ + PerformanceEventDispatcherScene::onEnter(); + + for (int i = 0; i < 2000; i++) + { + auto listener = EventListenerCustom::create(StringUtils::format("custom_event_%d", i), [](EventCustom* event){}); + _eventDispatcher->addEventListenerWithFixedPriority(listener, i + 1); + _customListeners.push_back(listener); + } +} + +void CustomEventDispatchingPerfTest::onExit() +{ + for (auto& l : _customListeners) + { + _eventDispatcher->removeEventListener(l); + } + PerformanceEventDispatcherScene::onExit(); +} + +void CustomEventDispatchingPerfTest::generateTestFunctions() +{ + TestFunction testFunctions[] = { + { "custom-scenegraph", [=](){ + auto dispatcher = Director::getInstance()->getEventDispatcher(); + if (_quantityOfNodes != _lastRenderedCount) + { + auto listener = EventListenerCustom::create("custom_event_test_scenegraph", [](EventCustom* event){}); + + // Create new nodes listen to custom event + for (int i = 0; i < this->_quantityOfNodes; ++i) + { + auto node = Node::create(); + node->setTag(1000 + i); + this->addChild(node); + this->_nodes.push_back(node); + dispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), node); + } + + _lastRenderedCount = _quantityOfNodes; + } + + EventCustom event("custom_event_test_scenegraph"); + + CC_PROFILER_START(this->profilerName()); + dispatcher->dispatchEvent(&event); + CC_PROFILER_STOP(this->profilerName()); + } } , + { "custom-fixed", [=](){ + auto dispatcher = Director::getInstance()->getEventDispatcher(); + if (_quantityOfNodes != _lastRenderedCount) + { + auto listener = EventListenerCustom::create("custom_event_test_fixed", [](EventCustom* event){}); + + for (int i = 0; i < this->_quantityOfNodes; ++i) + { + auto l = listener->clone(); + this->_fixedPriorityListeners.push_back(l); + dispatcher->addEventListenerWithFixedPriority(l, i+1); + } + + _lastRenderedCount = _quantityOfNodes; + } + + EventCustom event("custom_event_test_fixed"); + + CC_PROFILER_START(this->profilerName()); + dispatcher->dispatchEvent(&event); + CC_PROFILER_STOP(this->profilerName()); + } } , + }; + + for (const auto& func : testFunctions) + { + _testFunctions.push_back(func); + } +} + +std::string CustomEventDispatchingPerfTest::title() const +{ + return "Custom Event Dispatching Perf test"; +} + +std::string CustomEventDispatchingPerfTest::subtitle() const +{ + return "Test 'custom-scenegraph', See console"; +} + +///---------------------------------------- +void runEventDispatcherPerformanceTest() +{ + auto scene = createFunctions[g_curCase](); + scene->initWithQuantityOfNodes(kNodesIncrease); + + Director::getInstance()->replaceScene(scene); +} + diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceEventDispatcherTest.h b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceEventDispatcherTest.h new file mode 100644 index 0000000000..b8b6022b62 --- /dev/null +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceEventDispatcherTest.h @@ -0,0 +1,106 @@ +// +// PerformanceEventDispatcherTest.h + +#ifndef __PERFORMANCE_EVENTDISPATCHER_TEST_H__ +#define __PERFORMANCE_EVENTDISPATCHER_TEST_H__ + +#include "PerformanceTest.h" +#include "CCProfiling.h" + +class EventDispatcherBasicLayer : public PerformBasicLayer +{ +public: + EventDispatcherBasicLayer(bool bControlMenuVisible, int nMaxCases = 0, int nCurCase = 0); + + virtual void showCurrentTest(); +}; + +class PerformanceEventDispatcherScene : public Scene +{ +public: + static const int TAG_TITLE = 100; + static const int TAG_SUBTITLE = 101; + + struct TestFunction + { + const char* name; + std::function func; + }; + + virtual void initWithQuantityOfNodes(unsigned int nNodes); + virtual void generateTestFunctions() = 0; + + virtual std::string title() const; + virtual std::string subtitle() const; + virtual void updateQuantityOfNodes(); + + const char* profilerName(); + void updateProfilerName(); + + // for the profiler + virtual const char* testName(); + void updateQuantityLabel(); + int getQuantityOfNodes() { return _quantityOfNodes; } + void dumpProfilerInfo(float dt); + + // overrides + virtual void update(float dt) override; + +protected: + char _profilerName[256]; + int _lastRenderedCount; + int _quantityOfNodes; + int _currentQuantityOfNodes; + unsigned int _type; + std::vector _testFunctions; + std::vector _nodes; + std::vector _fixedPriorityListeners; + MenuItemFont* _increase; + MenuItemFont* _decrease; + MenuItemFont* _startItem; + MenuItemFont* _stopItem; + MenuItemToggle* _toggle; +}; + +class TouchEventDispatchingPerfTest : public PerformanceEventDispatcherScene +{ +public: + CREATE_FUNC(TouchEventDispatchingPerfTest); + + virtual void generateTestFunctions() override; + + virtual std::string title() const override; + virtual std::string subtitle() const override; +}; + +class KeyboardEventDispatchingPerfTest : public PerformanceEventDispatcherScene +{ +public: + CREATE_FUNC(KeyboardEventDispatchingPerfTest); + + virtual void generateTestFunctions() override; + + virtual std::string title() const override; + virtual std::string subtitle() const override; +}; + +class CustomEventDispatchingPerfTest : public PerformanceEventDispatcherScene +{ +public: + CREATE_FUNC(CustomEventDispatchingPerfTest); + + virtual void onEnter() override; + virtual void onExit() override; + + virtual void generateTestFunctions() override; + + virtual std::string title() const override; + virtual std::string subtitle() const override; + +private: + std::vector _customListeners; +}; + +void runEventDispatcherPerformanceTest(); + +#endif /* defined(__PERFORMANCE_EVENTDISPATCHER_TEST_H__) */ diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp index 96a3aeb67a..ecd42ef59a 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp @@ -397,15 +397,9 @@ void CallFuncsSpriteSheetForEach::update(float dt) CC_PROFILER_START(this->profilerName()); -#if CC_USE_ARRAY_VECTOR - std::for_each(std::begin(children), std::end(children), [](const RCPtr& obj) { - static_cast( static_cast(obj) )->getPosition(); - }); -#else std::for_each(std::begin(children), std::end(children), [](Node* obj) { obj->getPosition(); }); -#endif CC_PROFILER_STOP(this->profilerName()); } diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTest.cpp index 7884aec8d3..63ce78dfe3 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTest.cpp @@ -9,6 +9,7 @@ #include "PerformanceLabelTest.h" #include "PerformanceRendererTest.h" #include "PerformanceContainerTest.h" +#include "PerformanceEventDispatcherTest.h" enum { @@ -29,7 +30,8 @@ struct { { "Touches Perf Test",[](Object*sender){runTouchesTest();} }, { "Label Perf Test",[](Object*sender){runLabelTest();} }, { "Renderer Perf Test",[](Object*sender){runRendererTest();} }, - { "Container Perf Test", [](Object* sender ) { runContainerPerformanceTest(); } } + { "Container Perf Test", [](Object* sender ) { runContainerPerformanceTest(); } }, + { "EventDispatcher Perf Test", [](Object* sender ) { runEventDispatcherPerformanceTest(); } }, }; static const int g_testMax = sizeof(g_testsName)/sizeof(g_testsName[0]); diff --git a/samples/Cpp/TestCpp/Classes/ReleasePoolTest/ReleasePoolTest.cpp b/samples/Cpp/TestCpp/Classes/ReleasePoolTest/ReleasePoolTest.cpp new file mode 100644 index 0000000000..8cadafa0d4 --- /dev/null +++ b/samples/Cpp/TestCpp/Classes/ReleasePoolTest/ReleasePoolTest.cpp @@ -0,0 +1,80 @@ +#include "ReleasePoolTest.h" + +using namespace cocos2d; + +class TestObject : public Object +{ +public: + TestObject() : _name(""){} + + TestObject(std::string name) : _name(name) + { + CCLOG("TestObject:%s is created", _name.c_str()); + } + + ~TestObject() + { + if (_name.size() > 0) + CCLOG("TestObject:%s is destroyed", _name.c_str()); + } + +private: + std::string _name; +}; + +void ReleasePoolTestScene::runThisTest() +{ + // title + auto label = LabelTTF::create("AutoreasePool Test", "Arial", 32); + addChild(label, 9999); + label->setPosition(Point(VisibleRect::center().x, VisibleRect::top().y - 30)); + + // reference count should be added when added into auto release pool + + TestObject *obj = new TestObject("testobj"); + obj->autorelease(); + assert(obj->retainCount() == 1); + + // should retain first before invoking autorelease + obj->retain(); + obj->autorelease(); + assert(obj->retainCount() == 2); + + // create an autorelease pool in stack + + { + AutoreleasePool pool1; + + // can invoke autorelease more than once + obj->retain(); + obj->autorelease(); + assert(obj->retainCount() == 3); + obj->retain(); + obj->autorelease(); + assert(obj->retainCount() == 4); + + // retain, release can work together with autorelease pool + obj->retain(); + assert(obj->retainCount() == 5); + obj->release(); + assert(obj->retainCount() == 4); + } + + assert(obj->retainCount() == 2); + + // example of using temple autorelease pool + { + AutoreleasePool pool2; + char name[20]; + for (int i = 0; i < 100; ++i) + { + snprintf(name, 20, "object%d", i); + TestObject *tmpObj = new TestObject(name); + tmpObj->autorelease(); + } + } + + // object in pool2 should be released + + Director::getInstance()->replaceScene(this); +} diff --git a/samples/Cpp/TestCpp/Classes/ReleasePoolTest/ReleasePoolTest.h b/samples/Cpp/TestCpp/Classes/ReleasePoolTest/ReleasePoolTest.h new file mode 100644 index 0000000000..abd518b571 --- /dev/null +++ b/samples/Cpp/TestCpp/Classes/ReleasePoolTest/ReleasePoolTest.h @@ -0,0 +1,18 @@ +/* + * + */ +#ifndef __RELEASE_POOL_TEST_H__ +#define __RELEASE_POOL_TEST_H__ + +#include "../testBasic.h" + +class ReleasePoolTestScene : public TestScene +{ +public: + virtual void runThisTest(); + +private: + +}; + +#endif // __RELEASE_POOL_TEST_H__ diff --git a/samples/Cpp/TestCpp/Classes/controller.cpp b/samples/Cpp/TestCpp/Classes/controller.cpp index 471a399298..f1f04ae2a2 100644 --- a/samples/Cpp/TestCpp/Classes/controller.cpp +++ b/samples/Cpp/TestCpp/Classes/controller.cpp @@ -73,6 +73,7 @@ struct { { "ParticleTest", [](){return new ParticleTestScene(); } }, { "PerformanceTest", []() { return new PerformanceTestScene(); } }, { "PhysicsTest", []() { return new PhysicsTestScene(); } }, + { "ReleasePoolTest", [](){ return new ReleasePoolTestScene(); } }, { "RenderTextureTest", [](){return new RenderTextureScene(); } }, { "RotateWorldTest", [](){return new RotateWorldTestScene(); } }, { "SceneTest", [](){return new SceneTestScene();} }, diff --git a/samples/Cpp/TestCpp/Classes/tests.h b/samples/Cpp/TestCpp/Classes/tests.h index d030ae34f3..9e20f96590 100644 --- a/samples/Cpp/TestCpp/Classes/tests.h +++ b/samples/Cpp/TestCpp/Classes/tests.h @@ -68,5 +68,6 @@ #include "DataVisitorTest/DataVisitorTest.h" #include "ConfigurationTest/ConfigurationTest.h" #include "PhysicsTest/PhysicsTest.h" +#include "ReleasePoolTest/ReleasePoolTest.h" #endif diff --git a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj index 056b3f6cff..620b12b3f1 100644 --- a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj +++ b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj @@ -187,9 +187,11 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$ + + @@ -335,9 +337,11 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$ + + diff --git a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters index 5cfe11e6c9..2600ec0428 100644 --- a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters +++ b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters @@ -307,6 +307,9 @@ {5ff3af4e-0610-480b-b297-8f407e12f369} + + {f71fab28-32be-45c9-a941-9a22b5a59e51} + @@ -721,6 +724,12 @@ Classes\PerformanceTest + + Classes\ReleasePoolTest + + + Classes\PerformanceTest + @@ -1333,5 +1342,11 @@ Classes\PerformanceTest + + Classes\ReleasePoolTest + + + Classes\PerformanceTest + \ No newline at end of file diff --git a/samples/Javascript/CocosDragonJS/Classes/AppDelegate.cpp b/samples/Javascript/CocosDragonJS/Classes/AppDelegate.cpp index f14e6df017..d8ec78b296 100644 --- a/samples/Javascript/CocosDragonJS/Classes/AppDelegate.cpp +++ b/samples/Javascript/CocosDragonJS/Classes/AppDelegate.cpp @@ -145,26 +145,6 @@ bool AppDelegate::applicationDidFinishLaunching() return true; } -void handle_signal(int signal) { - static int internal_state = 0; - ScriptingCore* sc = ScriptingCore::getInstance(); - // should start everything back - auto director = Director::getInstance(); - if (director->getRunningScene()) { - director->popToRootScene(); - } else { - PoolManager::sharedPoolManager()->finalize(); - if (internal_state == 0) { - //sc->dumpRoot(NULL, 0, NULL); - sc->start(); - internal_state = 1; - } else { - sc->runScript("hello.js"); - internal_state = 0; - } - } -} - // This function will be called when the app is inactive. When comes a phone call,it's be invoked too void AppDelegate::applicationDidEnterBackground() { diff --git a/samples/Javascript/CrystalCraze/Classes/AppDelegate.cpp b/samples/Javascript/CrystalCraze/Classes/AppDelegate.cpp index 63f1c31aed..f8cd0ab32d 100644 --- a/samples/Javascript/CrystalCraze/Classes/AppDelegate.cpp +++ b/samples/Javascript/CrystalCraze/Classes/AppDelegate.cpp @@ -126,26 +126,6 @@ bool AppDelegate::applicationDidFinishLaunching() return true; } -void handle_signal(int signal) { - static int internal_state = 0; - ScriptingCore* sc = ScriptingCore::getInstance(); - // should start everything back - auto director = Director::getInstance(); - if (director->getRunningScene()) { - director->popToRootScene(); - } else { - PoolManager::sharedPoolManager()->finalize(); - if (internal_state == 0) { - //sc->dumpRoot(NULL, 0, NULL); - sc->start(); - internal_state = 1; - } else { - sc->runScript("hello.js"); - internal_state = 0; - } - } -} - // This function will be called when the app is inactive. When comes a phone call,it's be invoked too void AppDelegate::applicationDidEnterBackground() { diff --git a/samples/Javascript/MoonWarriors/Classes/AppDelegate.cpp b/samples/Javascript/MoonWarriors/Classes/AppDelegate.cpp index c1406c1586..ee9406b274 100644 --- a/samples/Javascript/MoonWarriors/Classes/AppDelegate.cpp +++ b/samples/Javascript/MoonWarriors/Classes/AppDelegate.cpp @@ -68,26 +68,6 @@ bool AppDelegate::applicationDidFinishLaunching() return true; } -void handle_signal(int signal) { - static int internal_state = 0; - ScriptingCore* sc = ScriptingCore::getInstance(); - // should start everything back - auto director = Director::getInstance(); - if (director->getRunningScene()) { - director->popToRootScene(); - } else { - PoolManager::sharedPoolManager()->finalize(); - if (internal_state == 0) { - //sc->dumpRoot(NULL, 0, NULL); - sc->start(); - internal_state = 1; - } else { - sc->runScript("hello.js"); - internal_state = 0; - } - } -} - // This function will be called when the app is inactive. When comes a phone call,it's be invoked too void AppDelegate::applicationDidEnterBackground() { diff --git a/samples/Javascript/TestJavascript/Classes/AppDelegate.cpp b/samples/Javascript/TestJavascript/Classes/AppDelegate.cpp index d5d37f513a..ec3a33e02b 100644 --- a/samples/Javascript/TestJavascript/Classes/AppDelegate.cpp +++ b/samples/Javascript/TestJavascript/Classes/AppDelegate.cpp @@ -121,26 +121,6 @@ bool AppDelegate::applicationDidFinishLaunching() return true; } -void handle_signal(int signal) { - static int internal_state = 0; - ScriptingCore* sc = ScriptingCore::getInstance(); - // should start everything back - auto director = Director::getInstance(); - if (director->getRunningScene()) { - director->popToRootScene(); - } else { - PoolManager::sharedPoolManager()->finalize(); - if (internal_state == 0) { - //sc->dumpRoot(NULL, 0, NULL); - sc->start(); - internal_state = 1; - } else { - sc->runScript("hello.js"); - internal_state = 0; - } - } -} - // This function will be called when the app is inactive. When comes a phone call,it's be invoked too void AppDelegate::applicationDidEnterBackground() { diff --git a/samples/Javascript/WatermelonWithMe/Classes/AppDelegate.cpp b/samples/Javascript/WatermelonWithMe/Classes/AppDelegate.cpp index 663cd87769..a6798abad9 100644 --- a/samples/Javascript/WatermelonWithMe/Classes/AppDelegate.cpp +++ b/samples/Javascript/WatermelonWithMe/Classes/AppDelegate.cpp @@ -65,26 +65,6 @@ bool AppDelegate::applicationDidFinishLaunching() return true; } -void handle_signal(int signal) { - static int internal_state = 0; - ScriptingCore* sc = ScriptingCore::getInstance(); - // should start everything back - auto director = Director::getInstance(); - if (director->getRunningScene()) { - director->popToRootScene(); - } else { - PoolManager::sharedPoolManager()->finalize(); - if (internal_state == 0) { - //sc->dumpRoot(NULL, 0, NULL); - sc->start(); - internal_state = 1; - } else { - sc->runScript("hello.js"); - internal_state = 0; - } - } -} - // This function will be called when the app is inactive. When comes a phone call,it's be invoked too void AppDelegate::applicationDidEnterBackground() { diff --git a/samples/Lua/TestLua/Resources/luaScript/AssetsManagerTest/AssetsManagerTest.lua b/samples/Lua/TestLua/Resources/luaScript/AssetsManagerTest/AssetsManagerTest.lua index bd09f69e8a..39d4a63e89 100644 --- a/samples/Lua/TestLua/Resources/luaScript/AssetsManagerTest/AssetsManagerTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/AssetsManagerTest/AssetsManagerTest.lua @@ -116,7 +116,7 @@ local function updateLayer() local function menuCallback(tag, menuItem) local scene = nil - local nIdx = menuItem:getZOrder() - itemTagBasic + local nIdx = menuItem:getLocalZOrder() - itemTagBasic local ExtensionsTestScene = CreateExtensionsTestScene(nIdx) if nil ~= ExtensionsTestScene then cc.Director:getInstance():replaceScene(ExtensionsTestScene) diff --git a/samples/Lua/TestLua/Resources/luaScript/BugsTest/BugsTest.lua b/samples/Lua/TestLua/Resources/luaScript/BugsTest/BugsTest.lua index e935a44a44..487b2fec70 100644 --- a/samples/Lua/TestLua/Resources/luaScript/BugsTest/BugsTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/BugsTest/BugsTest.lua @@ -583,7 +583,7 @@ local function BugsTestMainLayer() --menu callback local function menuCallback(tag, pMenuItem) - local nIdx = pMenuItem:getZOrder() - kItemTagBasic + local nIdx = pMenuItem:getLocalZOrder() - kItemTagBasic local BugTestScene = CreateBugsTestScene(nIdx) if nil ~= testScene then cc.Director:getInstance():replaceScene(testScene) diff --git a/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioArmatureTest/CocoStudioArmatureTest.lua b/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioArmatureTest/CocoStudioArmatureTest.lua index 7c15e2900b..0163ccf583 100644 --- a/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioArmatureTest/CocoStudioArmatureTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioArmatureTest/CocoStudioArmatureTest.lua @@ -633,7 +633,7 @@ function TestChangeZorder:onEnter() local function changeZorder(dt) local node = self:getChildByTag(self.currentTag) - node:setZOrder(math.random(0,1) * 3) + node:setLocalZOrder(math.random(0,1) * 3) self.currentTag = (self.currentTag + 1) % 3 end @@ -828,7 +828,7 @@ function TestParticleDisplay:onEnter() bone:addDisplay(p1, 0) bone:changeDisplayWithIndex(0, true) bone:setIgnoreMovementBoneData(true) - bone:setZOrder(100) + bone:setLocalZOrder(100) bone:setScale(1.2) self.armature:addBone(bone, "bady-a3") @@ -836,7 +836,7 @@ function TestParticleDisplay:onEnter() bone:addDisplay(p2, 0) bone:changeDisplayWithIndex(0, true) bone:setIgnoreMovementBoneData(true) - bone:setZOrder(100) + bone:setLocalZOrder(100) bone:setScale(1.2) self.armature:addBone(bone, "bady-a30") diff --git a/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioSceneTest/CocoStudioSceneTest.lua b/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioSceneTest/CocoStudioSceneTest.lua index 3c453756a4..fb8f52a742 100644 --- a/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioSceneTest/CocoStudioSceneTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioSceneTest/CocoStudioSceneTest.lua @@ -40,7 +40,7 @@ function SceneEditorTestLayer:createGameScene() itemBack:registerScriptTapHandler(menuCloseCallback) local menuBack = cc.Menu:create() menuBack:setPosition(cc.p(0.0, 0.0)) - menuBack:setZOrder(4) + menuBack:setLocalZOrder(4) menuBack:addChild(itemBack) node:addChild(menuBack) diff --git a/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioTest.lua b/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioTest.lua index f830bc194e..8a9bf8fa5a 100644 --- a/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioTest.lua @@ -67,7 +67,7 @@ function CocoStudioTestLayer.extend(target) end function CocoStudioTestLayer.onMenuCallback(tag,sender) - local index = sender:getZOrder() - ITEM_TAG_BASIC + local index = sender:getLocalZOrder() - ITEM_TAG_BASIC cocoStudioTestItemNames[index].testScene() end diff --git a/samples/Lua/TestLua/Resources/luaScript/CocosDenshionTest/CocosDenshionTest.lua b/samples/Lua/TestLua/Resources/luaScript/CocosDenshionTest/CocosDenshionTest.lua index 62aef54479..2d818a618e 100644 --- a/samples/Lua/TestLua/Resources/luaScript/CocosDenshionTest/CocosDenshionTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/CocosDenshionTest/CocosDenshionTest.lua @@ -33,7 +33,7 @@ local function CocosDenshionTest() } local function menuCallback(tag, pMenuItem) - local nIdx = pMenuItem:getZOrder() - 10000 + local nIdx = pMenuItem:getLocalZOrder() - 10000 -- play background music if nIdx == 0 then AudioEngine.playMusic(MUSIC_FILE, true) diff --git a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ExtensionTest.lua b/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ExtensionTest.lua index 361dd03615..80deae2f4d 100644 --- a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ExtensionTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ExtensionTest.lua @@ -1201,7 +1201,7 @@ local function ExtensionsMainLayer() local function menuCallback(tag, pMenuItem) local scene = nil - local nIdx = pMenuItem:getZOrder() - kItemTagBasic + local nIdx = pMenuItem:getLocalZOrder() - kItemTagBasic local ExtensionsTestScene = CreateExtensionsTestScene(nIdx) if nil ~= ExtensionsTestScene then cc.Director:getInstance():replaceScene(ExtensionsTestScene) diff --git a/samples/Lua/TestLua/Resources/luaScript/LabelTestNew/LabelTestNew.lua b/samples/Lua/TestLua/Resources/luaScript/LabelTestNew/LabelTestNew.lua index 375f710ddd..68108fc1d9 100644 --- a/samples/Lua/TestLua/Resources/luaScript/LabelTestNew/LabelTestNew.lua +++ b/samples/Lua/TestLua/Resources/luaScript/LabelTestNew/LabelTestNew.lua @@ -42,7 +42,7 @@ function LabelFNTColorAndOpacity.create() local col = cc.LayerColor:create( cc.c4b(128,128,128,255) ) layer:addChild(col, -10) - local label1 = cc.Label:createWithBMFont("Test", "fonts/bitmapFontTest2.fnt") + local label1 = cc.Label:createWithBMFont("fonts/bitmapFontTest2.fnt", "Test") -- testing anchors label1:setAnchorPoint( cc.p(0,0) ) @@ -55,15 +55,15 @@ function LabelFNTColorAndOpacity.create() local repeatAction = cc.RepeatForever:create(seq) label1:runAction(repeatAction) - local label2 = cc.Label:createWithBMFont("Test", "fonts/bitmapFontTest2.fnt") + local label2 = cc.Label:createWithBMFont("fonts/bitmapFontTest2.fnt", "Test") -- testing anchors label2:setAnchorPoint( cc.p(0.5, 0.5) ) label2:setColor(cc.c3b(255, 0, 0 )) layer:addChild(label2, 0, kTagBitmapAtlas2) - label2:runAction( tolua.cast(repeatAction:clone(), "Action") ) + label2:runAction( tolua.cast(repeatAction:clone(), "cc.Action") ) - local label3 = cc.Label:createWithBMFont("Test", "fonts/bitmapFontTest2.fnt") + local label3 = cc.Label:createWithBMFont("fonts/bitmapFontTest2.fnt", "Test") -- testing anchors label3:setAnchorPoint( cc.p(1,1) ) layer:addChild(label3, 0, kTagBitmapAtlas3) @@ -85,13 +85,13 @@ function LabelFNTColorAndOpacity.step(dt) m_time = m_time + dt local string = string.format("%2.2f Test j", m_time) - local label1 = tolua.cast(LabelFNTColorAndOpacity.layer:getChildByTag(kTagBitmapAtlas1), "Label") + local label1 = tolua.cast(LabelFNTColorAndOpacity.layer:getChildByTag(kTagBitmapAtlas1), "cc.Label") label1:setString(string) - local label2 = tolua.cast(LabelFNTColorAndOpacity.layer:getChildByTag(kTagBitmapAtlas2), "Label") + local label2 = tolua.cast(LabelFNTColorAndOpacity.layer:getChildByTag(kTagBitmapAtlas2), "cc.Label") label2:setString(string) - local label3 = tolua.cast(LabelFNTColorAndOpacity.layer:getChildByTag(kTagBitmapAtlas3), "Label") + local label3 = tolua.cast(LabelFNTColorAndOpacity.layer:getChildByTag(kTagBitmapAtlas3), "cc.Label") label3:setString(string) end @@ -121,7 +121,7 @@ function LabelFNTSpriteActions.create() LabelFNTSpriteActions.layer = layer -- Upper Label - local label = cc.Label:createWithBMFont("Bitmap Font Atlas", "fonts/bitmapFontTest.fnt") + local label = cc.Label:createWithBMFont("fonts/bitmapFontTest.fnt", "Bitmap Font Atlas") layer:addChild(label) local s = cc.Director:getInstance():getWinSize() @@ -160,12 +160,12 @@ function LabelFNTSpriteActions.create() -- Bottom Label - local label2 = cc.Label:createWithBMFont("00.0", "fonts/bitmapFontTest.fnt") + local label2 = cc.Label:createWithBMFont("fonts/bitmapFontTest.fnt", "00.0") layer:addChild(label2, 0, kTagBitmapAtlas2) label2:setPosition( cc.p(s.width/2.0, 80) ) local lastChar = label2:getLetter(3) - lastChar:runAction(tolua.cast( rot_4ever:clone(), "Action" )) + lastChar:runAction(tolua.cast( rot_4ever:clone(), "cc.Action" )) layer:registerScriptHandler(LabelFNTSpriteActions.onNodeEvent) @@ -203,7 +203,7 @@ function LabelFNTPadding:create() Helper.initWithLayer(layer) LabelFNTPadding.layer = layer - local label = cc.Label:createWithBMFont("abcdefg", "fonts/bitmapFontTest4.fnt") + local label = cc.Label:createWithBMFont("fonts/bitmapFontTest4.fnt", "abcdefg") layer:addChild(label) local s = cc.Director:getInstance():getWinSize() @@ -231,17 +231,17 @@ function LabelFNTOffset:create() LabelFNTOffset.layer = layer local s = cc.Director:getInstance():getWinSize() - local label = cc.Label:createWithBMFont("FaFeFiFoFu", "fonts/bitmapFontTest5.fnt") + local label = cc.Label:createWithBMFont("fonts/bitmapFontTest5.fnt", "FaFeFiFoFu") layer:addChild(label) label:setPosition( cc.p(s.width/2, s.height/2+50) ) label:setAnchorPoint( cc.p(0.5, 0.5) ) - label = cc.Label:createWithBMFont("fafefifofu", "fonts/bitmapFontTest5.fnt") + label = cc.Label:createWithBMFont("fonts/bitmapFontTest5.fnt", "fafefifofu") layer:addChild(label) label:setPosition( cc.p(s.width/2, s.height/2) ) label:setAnchorPoint( cc.p(0.5, 0.5) ) - label = cc.Label:createWithBMFont("aeiou", "fonts/bitmapFontTest5.fnt") + label = cc.Label:createWithBMFont("fonts/bitmapFontTest5.fnt", "aeiou") layer:addChild(label) label:setPosition( cc.p(s.width/2, s.height/2-50) ) label:setAnchorPoint( cc.p(0.5, 0.5) ) @@ -264,19 +264,19 @@ function LabelFNTColor:create() local s = cc.Director:getInstance():getWinSize() - local label = cc.Label:createWithBMFont("Blue", "fonts/bitmapFontTest5.fnt") + local label = cc.Label:createWithBMFont("fonts/bitmapFontTest5.fnt", "Blue") label:setColor( cc.c3b(0, 0, 255 )) layer:addChild(label) label:setPosition( cc.p(s.width/2, s.height/4) ) label:setAnchorPoint( cc.p(0.5, 0.5) ) - label = cc.Label:createWithBMFont("Red", "fonts/bitmapFontTest5.fnt") + label = cc.Label:createWithBMFont("fonts/bitmapFontTest5.fnt", "Red") layer:addChild(label) label:setPosition( cc.p(s.width/2, 2*s.height/4) ) label:setAnchorPoint( cc.p(0.5, 0.5) ) label:setColor( cc.c3b(255, 0, 0) ) - label = cc.Label:createWithBMFont("G", "fonts/bitmapFontTest5.fnt") + label = cc.Label:createWithBMFont("fonts/bitmapFontTest5.fnt", "Green") layer:addChild(label) label:setPosition( cc.p(s.width/2, 3*s.height/4) ) label:setAnchorPoint( cc.p(0.5, 0.5) ) @@ -301,20 +301,23 @@ function LabelTTFColor:create() Helper.initWithLayer(layer) local s = cc.Director:getInstance():getWinSize() + local ttfConfig = {} + ttfConfig.fontFilePath="fonts/arial.ttf" + ttfConfig.fontSize=35 - local label1 = cc.Label:createWithTTF("Green", "fonts/arial.ttf", 35, s.width, cc.VERTICAL_TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_NEHE) + local label1 = cc.Label:createWithTTF(ttfConfig,"Green", cc.VERTICAL_TEXT_ALIGNMENT_CENTER, s.width) label1:setColor( cc.c3b(0, 255, 0 )) layer:addChild(label1) label1:setPosition( cc.p(s.width/2, s.height/5 * 1.5) ) label1:setAnchorPoint( cc.p(0.5, 0.5) ) - local label2 = cc.Label:createWithTTF("Red", "fonts/arial.ttf", 35, s.width, cc.VERTICAL_TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_NEHE) + local label2 = cc.Label:createWithTTF(ttfConfig, "Red", cc.VERTICAL_TEXT_ALIGNMENT_CENTER, s.width) layer:addChild(label2) label2:setPosition( cc.p(s.width/2, s.height/5 * 2.0) ) label2:setAnchorPoint( cc.p(0.5, 0.5) ) label2:setColor( cc.c3b(255, 0, 0) ) - local label3 = cc.Label:createWithTTF("Blue", "fonts/arial.ttf", 35, s.width, cc.VERTICAL_TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_NEHE) + local label3 = cc.Label:createWithTTF(ttfConfig, "Blue", cc.VERTICAL_TEXT_ALIGNMENT_CENTER, s.width) layer:addChild(label3) label3:setPosition( cc.p(s.width/2, s.height/5 * 2.5) ) label3:setAnchorPoint( cc.p(0.5, 0.5) ) @@ -342,7 +345,7 @@ function LabelFNTHundredLabels:create() local i = 0 for i = 0, 100, 1 do local str = string.format("-%d-", i) - local label = cc.Label:createWithBMFont(str, "fonts/bitmapFontTest.fnt") + local label = cc.Label:createWithBMFont("fonts/bitmapFontTest.fnt", str) layer:addChild(label) local s = cc.Director:getInstance():getWinSize() @@ -353,7 +356,7 @@ function LabelFNTHundredLabels:create() end Helper.titleLabel:setString("New Label + .FNT file") - Helper.subtitleLabel:setString("Creating several Labels using the same FNT file; should be fast") + Helper.subtitleLabel:setString("Creating several Labels using the same FNT file should be fast") return layer end @@ -371,7 +374,7 @@ function LabelFNTMultiLine:create() local s = nil -- Left - local label1 = cc.Label:createWithBMFont(" Multi line\nLeft", "fonts/bitmapFontTest3.fnt") + local label1 = cc.Label:createWithBMFont("fonts/bitmapFontTest3.fnt", " Multi line\nLeft") label1:setAnchorPoint(cc.p(0,0)) layer:addChild(label1, 0, kTagBitmapAtlas1) @@ -380,7 +383,7 @@ function LabelFNTMultiLine:create() -- Center - local label2 = cc.Label:createWithBMFont("Multi line\nCenter", "fonts/bitmapFontTest3.fnt") + local label2 = cc.Label:createWithBMFont("fonts/bitmapFontTest3.fnt", "Multi line\nCenter") label2:setAnchorPoint(cc.p(0.5, 0.5)) layer:addChild(label2, 0, kTagBitmapAtlas2) @@ -388,7 +391,7 @@ function LabelFNTMultiLine:create() cclog("content size: %.2fx%.2f", s.width, s.height) -- right - local label3 = cc.Label:createWithBMFont("Multi line\nRight\nThree lines Three", "fonts/bitmapFontTest3.fnt") + local label3 = cc.Label:createWithBMFont("fonts/bitmapFontTest3.fnt", "Multi line\nRight\nThree lines Three") label3:setAnchorPoint(cc.p(1, 1)) layer:addChild(label3, 0, kTagBitmapAtlas3) @@ -433,13 +436,17 @@ function LabelFNTandTTFEmpty.create() local s = cc.Director:getInstance():getWinSize() -- cc.LabelBMFont - local label1 = cc.Label:createWithBMFont("", "fonts/bitmapFontTest3.fnt",cc.TEXT_ALIGNMENT_CENTER,s.width) + local label1 = cc.Label:createWithBMFont("fonts/bitmapFontTest3.fnt", "", cc.TEXT_ALIGNMENT_CENTER,s.width) layer:addChild(label1, 0, kTagBitmapAtlas1) label1:setPosition(cc.p(s.width/2, s.height-100)) -- cc.LabelTTF - local label2 = cc.Label:createWithTTF("", "fonts/arial.ttf", 48, s.width, cc.TEXT_ALIGNMENT_CENTER,cc.GLYPHCOLLECTION_NEHE) + local ttfConfig = {} + ttfConfig.fontFilePath = "fonts/arial.ttf" + ttfConfig.fontSize = 48 + local label2 = cc.Label:createWithTTF(ttfConfig, "", cc.TEXT_ALIGNMENT_CENTER, s.width) layer:addChild(label2, 0, kTagBitmapAtlas2) + label2:setAnchorPoint(cc.p(0.5, 0.5)) label2:setPosition(cc.p(s.width/2, s.height/2)) layer:registerScriptHandler(LabelFNTandTTFEmpty.onNodeEvent) @@ -481,7 +488,7 @@ function LabelFNTRetina.create() local s = cc.Director:getInstance():getWinSize() -- cc.LabelBMFont - local label1 = cc.Label:createWithBMFont("TESTING RETINA DISPLAY", "fonts/konqa32.fnt") + local label1 = cc.Label:createWithBMFont("fonts/konqa32.fnt", "TESTING RETINA DISPLAY") label1:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(label1) label1:setPosition(cc.p(s.width/2, s.height/2)) @@ -503,7 +510,7 @@ function LabelFNTGlyphDesigner.create() local s = cc.Director:getInstance():getWinSize() - local label1 = cc.Label:createWithBMFont("TESTING RETINA DISPLAY", "fonts/futura-48.fnt") + local label1 = cc.Label:createWithBMFont("fonts/futura-48.fnt", "TESTING RETINA DISPLAY") label1:setAnchorPoint(cc.p(0.5, 0.5)) layer:addChild(label1) @@ -523,8 +530,13 @@ function LabelTTFUnicodeChinese.create() Helper.subtitleLabel:setString("Testing new Label + TTF with Chinese character") local s = cc.Director:getInstance():getWinSize() - - local label1 = cc.Label:createWithTTF("美好的一天啊", "fonts/wt021.ttf", 55, s.width, cc.TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_CUSTOM, "美好的一天啊") + local ttfConfig = {} + ttfConfig.fontFilePath="fonts/wt021.ttf" + ttfConfig.fontSize=55 + ttfConfig.glyphs=cc.GLYPHCOLLECTION_CUSTOM + ttfConfig.customGlyphs="美好的一天啊" + + local label1 = cc.Label:createWithTTF(ttfConfig,"美好的一天啊", cc.TEXT_ALIGNMENT_CENTER, s.width) label1:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(label1) label1:setPosition(cc.p(s.width/2, s.height/2)) @@ -542,7 +554,7 @@ function LabelFNTUnicodeChinese.create() Helper.initWithLayer(layer) local size = cc.Director:getInstance():getWinSize() - local lable = cc.Label:createWithBMFont("中国", "fonts/bitmapFontChinese.fnt") + local lable = cc.Label:createWithBMFont("fonts/bitmapFontChinese.fnt", "中国") lable:setAnchorPoint(cc.p(0.5,0.5)) lable:setPosition(cc.p(size.width / 2, size.height /2)) layer:addChild(lable) @@ -591,7 +603,7 @@ function LabelFNTMultiLineAlignment.create() local size = cc.Director:getInstance():getWinSize() -- create and initialize a Label - LabelFNTMultiLineAlignment._pLabelShouldRetain = cc.Label:createWithBMFont(LongSentencesExample, "fonts/markerFelt.fnt", cc.TEXT_ALIGNMENT_CENTER, size.width/1.5) + LabelFNTMultiLineAlignment._pLabelShouldRetain = cc.Label:createWithBMFont("fonts/markerFelt.fnt", LongSentencesExample, cc.TEXT_ALIGNMENT_CENTER, size.width/1.5) LabelFNTMultiLineAlignment._pLabelShouldRetain:setAnchorPoint(cc.p(0.5, 0.5)) LabelFNTMultiLineAlignment._pLabelShouldRetain:retain() @@ -677,7 +689,7 @@ end function LabelFNTMultiLineAlignment.stringChanged(tag, sender) - local item = tolua.cast(sender, "MenuItemFont") + local item = tolua.cast(sender, "cc.MenuItemFont") item:setColor(cc.c3b(255, 0, 0)) LabelFNTMultiLineAlignment._pLastAlignmentItem:setColor(cc.c3b(255, 255, 255)) LabelFNTMultiLineAlignment._pLastAlignmentItem = item @@ -695,7 +707,7 @@ end function LabelFNTMultiLineAlignment.alignmentChanged(tag, sender) -- cclog("LabelFNTMultiLineAlignment.alignmentChanged, tag:"..tag) - local item = tolua.cast(sender, "MenuItemFont") + local item = tolua.cast(sender, "cc.MenuItemFont") item:setColor(cc.c3b(255, 0, 0)) LabelFNTMultiLineAlignment._pLastAlignmentItem:setColor(cc.c3b(255, 255, 255)) LabelFNTMultiLineAlignment._pLastAlignmentItem = item @@ -759,17 +771,17 @@ function LabelFNTUNICODELanguages.create() local s = cc.Director:getInstance():getWinSize() - local label1 = cc.Label:createWithBMFont("Buen día", "fonts/arial-unicode-26.fnt", 200, cc.TEXT_ALIGNMENT_LEFT) + local label1 = cc.Label:createWithBMFont("fonts/arial-unicode-26.fnt", "Buen día", cc.TEXT_ALIGNMENT_CENTER, 200) label1:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(label1) label1:setPosition(cc.p(s.width/2, s.height/4*3)) - local label2 = cc.Label:createWithBMFont("美好的一天", "fonts/arial-unicode-26.fnt") + local label2 = cc.Label:createWithBMFont("fonts/arial-unicode-26.fnt", "美好的一天") label2:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(label2) label2:setPosition(cc.p(s.width/2, s.height/4*2)) - local label3 = cc.Label:createWithBMFont("良い一日を", "fonts/arial-unicode-26.fnt") + local label3 = cc.Label:createWithBMFont("fonts/arial-unicode-26.fnt", "良い一日を") label3:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(label3) label3:setPosition(cc.p(s.width/2, s.height/4*1)) @@ -788,21 +800,20 @@ function LabelTTFAlignmentNew.create() Helper.subtitleLabel:setString("Tests alignment values") local s = cc.Director:getInstance():getWinSize() - - local ttf0 = cc.Label:createWithTTF("Alignment 0\nnew line", "fonts/tahoma.ttf", 32) - ttf0:setAlignment(cc.TEXT_ALIGNMENT_LEFT) + local ttfConfig = {} + ttfConfig.fontFilePath="fonts/tahoma.ttf" + ttfConfig.fontSize=32 + local ttf0 = cc.Label:createWithTTF(ttfConfig, "Alignment 0\nnew line", cc.TEXT_ALIGNMENT_LEFT) ttf0:setPosition(cc.p(s.width/2,(s.height/6)*2 - 30)) ttf0:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(ttf0) - local ttf1 = cc.Label:createWithTTF("Alignment 1\nnew line", "fonts/tahoma.ttf", 32) - ttf1:setAlignment(cc.TEXT_ALIGNMENT_CENTER) + local ttf1 = cc.Label:createWithTTF(ttfConfig, "Alignment 1\nnew line", cc.TEXT_ALIGNMENT_CENTER) ttf1:setPosition(cc.p(s.width/2,(s.height/6)*3 - 30)) ttf1:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(ttf1) - local ttf2 = cc.Label:createWithTTF("Alignment 2\nnew line", "fonts/tahoma.ttf", 32) - ttf2:setAlignment(cc.TEXT_ALIGNMENT_RIGHT) + local ttf2 = cc.Label:createWithTTF(ttfConfig, "Alignment 2\nnew line", cc.TEXT_ALIGNMENT_RIGHT) ttf2:setPosition(cc.p(s.width/2,(s.height/6)*4 - 30)) ttf2:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(ttf2) @@ -824,18 +835,26 @@ function LabelTTFUnicodeNew.create() local s = cc.Director:getInstance():getWinSize() local vStep = s.height/9 local vSize = s.height + + local ttfConfig = {} + ttfConfig.fontFilePath="fonts/arial.ttf" + ttfConfig.fontSize=45 + ttfConfig.glyphs=cc.GLYPHCOLLECTION_ASCII - local label1 = cc.Label:createWithTTF("Buen día, ¿cómo te llamas?", "fonts/arial.ttf", 45, s.width, cc.TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_ASCII) + local label1 = cc.Label:createWithTTF(ttfConfig,"Buen día, ¿cómo te llamas?", cc.TEXT_ALIGNMENT_CENTER, s.width) label1:setAnchorPoint(cc.p(0.5,0.5)) label1:setPosition(cc.p(s.width/2, vSize - vStep * 4.5)) layer:addChild(label1) - local label2 = cc.Label:createWithTTF("In welcher Straße haben Sie gelebt?", "fonts/arial.ttf", 45, s.width, cc.TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_ASCII) + local label2 = cc.Label:createWithTTF(ttfConfig, "In welcher Straße haben Sie gelebt?", cc.TEXT_ALIGNMENT_CENTER, s.width) label2:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(label2) label2:setPosition(cc.p(s.width/2, vSize - vStep * 5.5)) - local label3 = cc.Label:createWithTTF("美好的一天", "fonts/wt021.ttf", 45, s.width, cc.TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_CUSTOM, "美好的一天") + ttfConfig.fontFilePath = "fonts/wt021.ttf" + ttfConfig.glyphs = cc.GLYPHCOLLECTION_CUSTOM + ttfConfig.customGlyphs = "美好的一天" + local label3 = cc.Label:createWithTTF(ttfConfig, "美好的一天", cc.TEXT_ALIGNMENT_CENTER, s.width) label3:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(label3) label3:setPosition(cc.p(s.width/2, vSize - vStep * 6.5)) @@ -862,7 +881,7 @@ function LabelFNTBounds.create() layer:addChild(colorlayer, -10) -- cc.LabelBMFont - local label1 = cc.Label:createWithBMFont("Testing Glyph Designer", "fonts/boundsTestFont.fnt", cc.TEXT_ALIGNMENT_CENTER, s.width) + local label1 = cc.Label:createWithBMFont("fonts/boundsTestFont.fnt", "Testing Glyph Designer", cc.TEXT_ALIGNMENT_CENTER, s.width) label1:setAnchorPoint(cc.p(0.5, 0.5)) layer:addChild(label1) @@ -899,8 +918,10 @@ function LabelTTFLongLineWrapping.create() Helper.subtitleLabel:setString("Uses the new Label with TTF. Testing auto-wrapping") local s = cc.Director:getInstance():getWinSize() - - local label1 = cc.Label:createWithTTF(LongSentencesExample, "fonts/arial.ttf", 28, s.width,cc.TEXT_ALIGNMENT_LEFT, cc.GLYPHCOLLECTION_NEHE) + local ttfConfig = {} + ttfConfig.fontFilePath = "fonts/arial.ttf" + ttfConfig.fontSize = 28 + local label1 = cc.Label:createWithTTF(ttfConfig, LongSentencesExample, cc.TEXT_ALIGNMENT_LEFT, s.width) label1:setAnchorPoint(cc.p(0.5,1.0)) label1:setPosition(cc.p(s.width/2, s.height/2)) layer:addChild(label1) @@ -927,8 +948,10 @@ function LabelTTFDynamicAlignment.create() LabelTTFDynamicAlignment._eHorizAlign = cc.TEXT_ALIGNMENT_LEFT local s = cc.Director:getInstance():getWinSize() - - LabelTTFDynamicAlignment._label = cc.Label:createWithTTF(LongSentencesExample, "fonts/arial.ttf", 45, s.width, cc.TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_NEHE) + local ttfConfig = {} + ttfConfig.fontFilePath = "fonts/arial.ttf" + ttfConfig.fontSize = 45 + LabelTTFDynamicAlignment._label = cc.Label:createWithTTF(ttfConfig, LongSentencesExample, cc.TEXT_ALIGNMENT_CENTER, s.width) LabelTTFDynamicAlignment._label:setPosition( cc.p(s.width/2, s.height/2) ) LabelTTFDynamicAlignment._label:setAnchorPoint(cc.p(0.5, 0.5)) layer:addChild(LabelTTFDynamicAlignment._label) @@ -1000,9 +1023,12 @@ function LabelTTFFontsTestNew.create() "fonts/Schwarzwald Regular.ttf", "fonts/Scissor Cuts.ttf", } - + local ttfConfig = {} + ttfConfig.fontFilePath = ttfPaths[0] + ttfConfig.fontSize = 40 for i=1, table.getn(ttfPaths) do - local label = cc.Label:createWithTTF( ttfPaths[i], ttfPaths[i], 40, 0, cc.TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_NEHE) + ttfConfig.fontFilePath = ttfPaths[i] + local label = cc.Label:createWithTTF( ttfConfig, ttfPaths[i], cc.TEXT_ALIGNMENT_CENTER, 0) if nil ~= label then label:setPosition( cc.p(s.width/2, ((s.height * 0.6)/table.getn(ttfPaths) * (i -1)) + (s.height/5))) layer:addChild(label) @@ -1029,13 +1055,180 @@ function LabelBMFontTestNew.create() local s = cc.Director:getInstance():getWinSize() - local label1 = cc.Label:createWithBMFont("Hello World, this is testing the new Label using fnt file", "fonts/bitmapFontTest2.fnt", cc.TEXT_ALIGNMENT_CENTER, s.width) + local label1 = cc.Label:createWithBMFont("fonts/bitmapFontTest2.fnt", "Hello World, this is testing the new Label using fnt file", cc.TEXT_ALIGNMENT_CENTER, s.width) label1:setAnchorPoint(cc.p(0.5,0.5)) label1:setPosition(cc.p(s.width/2, s.height/2)) layer:addChild(label1) return layer end + +-------------------------------------------------------- +----- LabelTTFDistanceField +-------------------------------------------------------- +local LabelTTFDistanceField = {} +function LabelTTFDistanceField.create() + local layer = cc.Layer:create() + Helper.initWithLayer(layer) + Helper.titleLabel:setString("New Label + .TTF") + Helper.subtitleLabel:setString("Testing rendering base on DistanceField") + + local s = cc.Director:getInstance():getWinSize() + local ttfConfig = {} + ttfConfig.fontFilePath = "fonts/arial.ttf" + ttfConfig.fontSize = 80 + ttfConfig.glyphs = cc.GLYPHCOLLECTION_DYNAMIC + ttfConfig.customGlyphs = nil + ttfConfig.distanceFieldEnabled = true + + local label1 = cc.Label:createWithTTF(ttfConfig,"Distance Field",cc.TEXT_ALIGNMENT_CENTER,s.width) + label1:setAnchorPoint(cc.p(0.5,0.5)) + label1:setPosition(cc.p(s.width/2, s.height/2)) + label1:setColor( cc.c3b(0, 255, 0) ) + local action = cc.Sequence:create(cc.DelayTime:create(1.0), + cc.ScaleTo:create(6.0,5.0,5.0), + cc.ScaleTo:create(6.0,1.0,1.0)) + label1:runAction(cc.RepeatForever:create(action)) + layer:addChild(label1) + + local label2 = cc.Label:createWithTTF(ttfConfig,"Distance Field",cc.TEXT_ALIGNMENT_CENTER,s.width) + label2:setPosition( cc.p(s.width/2, s.height/5) ) + label2:setColor( cc.c3b(255, 0, 0)) + label2:setAnchorPoint(cc.p(0.5, 0.5)) + layer:addChild(label2) + + return layer +end + +-------------------------------------------------------- +----- LabelTTFDistanceFieldEffect +-------------------------------------------------------- +local LabelTTFDistanceFieldEffect = {} +function LabelTTFDistanceFieldEffect.create() + local layer = cc.Layer:create() + Helper.initWithLayer(layer) + Helper.titleLabel:setString("New Label + .TTF") + Helper.subtitleLabel:setString("Testing effect base on DistanceField") + + local s = cc.Director:getInstance():getWinSize() + + local col = cc.LayerColor:create( cc.c4b(200, 191, 231, 255)) + layer:addChild(col) + + local ttfConfig = {} + ttfConfig.fontFilePath = "fonts/arial.ttf" + ttfConfig.fontSize = 80 + ttfConfig.glyphs = cc.GLYPHCOLLECTION_DYNAMIC + ttfConfig.customGlyphs = nil + ttfConfig.distanceFieldEnabled = true + + local label1 = cc.Label:createWithTTF(ttfConfig,"Glow",cc.TEXT_ALIGNMENT_CENTER,s.width) + label1:setAnchorPoint(cc.p(0.5,0.5)) + label1:setPosition(cc.p(s.width/2, s.height/2)) + label1:setColor( cc.c3b(0, 255, 0) ) + label1:setLabelEffect(cc.LabelEffect.GLOW, cc.c3b(255, 255, 0)) + layer:addChild(label1) + + local label2 = cc.Label:createWithTTF(ttfConfig,"Outline",cc.TEXT_ALIGNMENT_CENTER,s.width) + label2:setPosition( cc.p(s.width/2, s.height * 0.375)) + label2:setColor( cc.c3b(255, 0, 0)) + label2:setAnchorPoint(cc.p(0.5, 0.5)) + label2:setLabelEffect(cc.LabelEffect.OUTLINE, cc.c3b(0, 0, 255)) + layer:addChild(label2) + + local label3 = cc.Label:createWithTTF(ttfConfig,"Shadow",cc.TEXT_ALIGNMENT_CENTER,s.width) + label3:setPosition( cc.p(s.width/2, s.height * 0.25)) + label3:setColor( cc.c3b(255, 0, 0)) + label3:setAnchorPoint(cc.p(0.5, 0.5)) + label3:setLabelEffect(cc.LabelEffect.SHADOW, cc.c3b(0, 0, 0)) + layer:addChild(label3) + + return layer +end + + +-------------------------------------------------------------------- +-- +-- LabelCharMapTest +-- +-------------------------------------------------------------------- +local LabelCharMapTest = {} + +function LabelCharMapTest.create() + local layer = cc.Layer:create() + Helper.initWithLayer(layer) + Helper.titleLabel:setString("New Label + char map file") + Helper.subtitleLabel:setString("Updating label should be fast.") + + time = 0 + + local label1 = cc.Label:createWithCharMap("fonts/tuffy_bold_italic-charmap.plist") + layer:addChild(label1, 0, kTagSprite1) + label1:setPosition( cc.p(10,100) ) + label1:setOpacity( 200 ) + + local label2 = cc.Label:createWithCharMap("fonts/tuffy_bold_italic-charmap.plist") + layer:addChild(label2, 0, kTagSprite2) + label2:setPosition( cc.p(10,160) ) + label2:setOpacity( 32 ) + + local label3 = cc.Label:createWithCharMap("fonts/tuffy_bold_italic-charmap.png", 48, 64, 32)--32 means Space key + label3:setString("123 Test") + layer:addChild(label3, 0, kTagSprite3) + label3:setPosition(cc.p(10,220)) + + local function step(dt) + time = time + dt + local info = string.format("%2.2f Test", time) + + local label1 = layer:getChildByTag(kTagSprite1) + label1:setString(info) + + local label2 = layer:getChildByTag(kTagSprite2) + info = string.format("%d",time) + label2:setString(info) + end + + layer:scheduleUpdateWithPriorityLua(step, 0) + + function onNodeEvent(tag) + if tag == "exit" then + layer:unscheduleUpdate() + end + end + + layer:registerScriptHandler(onNodeEvent) + + return layer +end + + +-------------------------------------------------------- +----- LabelCrashTest +-------------------------------------------------------- +local LabelCrashTest = {} +function LabelCrashTest.create() + local layer = cc.Layer:create() + Helper.initWithLayer(layer) + Helper.titleLabel:setString("New Label + .TTF") + Helper.subtitleLabel:setString("Testing rendering base on DistanceField") + + local ttfConfig = {} + ttfConfig.fontFilePath = "fonts/arial.ttf" + ttfConfig.fontSize = 80 + ttfConfig.glyphs = cc.GLYPHCOLLECTION_DYNAMIC + ttfConfig.customGlyphs = nil + ttfConfig.distanceFieldEnabled = true + local s = cc.Director:getInstance():getWinSize() + local label1 = cc.Label:createWithTTF(ttfConfig,"Test崩溃123", cc.TEXT_ALIGNMENT_CENTER, s.width) + label1:setPosition( cc.p(s.width/2, s.height/2) ) + label1:setAnchorPoint(cc.p(0.5, 0.5)) + layer:addChild(label1) + + return layer +end + +------------ function LabelTestNew() cclog("LabelTestNew") m_time = 0 @@ -1064,6 +1257,10 @@ function LabelTestNew() LabelTTFDynamicAlignment.create, LabelTTFFontsTestNew.create, LabelBMFontTestNew.create, + LabelTTFDistanceField.create, + LabelTTFDistanceFieldEffect.create, + LabelCharMapTest.create, + LabelCrashTest.create, } scene:addChild(LabelFNTColorAndOpacity.create()) scene:addChild(CreateBackMenuItem()) diff --git a/samples/Lua/TestLua/Resources/luaScript/LuaBridgeTest/LuaBridgeTest.lua b/samples/Lua/TestLua/Resources/luaScript/LuaBridgeTest/LuaBridgeTest.lua index dd149a00d5..6fea800fee 100644 --- a/samples/Lua/TestLua/Resources/luaScript/LuaBridgeTest/LuaBridgeTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/LuaBridgeTest/LuaBridgeTest.lua @@ -127,7 +127,7 @@ local function LuaBridgeLayer() local function menuCallback(tag, pMenuItem) local scene = nil - local nIdx = pMenuItem:getZOrder() - itemTagBasic + local nIdx = pMenuItem:getLocalZOrder() - itemTagBasic local newScene = newLuaBridgeScene(nIdx) if nil ~= newScene then newScene:addChild(createMenuToBridgeScene(),10) diff --git a/samples/Lua/TestLua/Resources/luaScript/NewEventDispatcherTest/NewEventDispatcherTest.lua b/samples/Lua/TestLua/Resources/luaScript/NewEventDispatcherTest/NewEventDispatcherTest.lua index 10be2d574c..959950d73e 100644 --- a/samples/Lua/TestLua/Resources/luaScript/NewEventDispatcherTest/NewEventDispatcherTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/NewEventDispatcherTest/NewEventDispatcherTest.lua @@ -210,9 +210,9 @@ function TouchableSpriteTest:onEnter() print("sprite onTouchesEnded..") target:setOpacity(255) if target == sprite2 then - sprite1:setZOrder(100) + sprite1:setLocalZOrder(100) elseif target == sprite1 then - sprite1:setZOrder(0) + sprite1:setLocalZOrder(0) end end diff --git a/samples/Lua/TestLua/Resources/luaScript/NodeTest/NodeTest.lua b/samples/Lua/TestLua/Resources/luaScript/NodeTest/NodeTest.lua index 9ffcac5706..09a7fdd5db 100644 --- a/samples/Lua/TestLua/Resources/luaScript/NodeTest/NodeTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/NodeTest/NodeTest.lua @@ -631,6 +631,58 @@ local function NodeNonOpaqueTest() return layer end +----------------------------------- +-- NodeGlobalZValueTest +----------------------------------- +local function NodeGlobalZValueTest() + local layer = getBaseLayer() + Helper.titleLabel:setString("Global Z Value") + Helper.subtitleLabel:setString("Center Sprite should change go from foreground to background") + + + local s = cc.Director:getInstance():getWinSize() + local zOrderSprite = nil + for i = 1,9 do + local parent = cc.Node:create() + local sprite = nil + if i == 5 then + sprite = cc.Sprite:create("Images/grossinis_sister2.png") + sprite:setGlobalZOrder(-1) + zOrderSprite = sprite + else + sprite = cc.Sprite:create("Images/grossinis_sister1.png") + end + parent:addChild(sprite) + layer:addChild(parent) + + local w = sprite:getContentSize().width + sprite:setPosition(s.width/2 - w*0.7*(i - 6),s.height / 2) + end + + local accum = 0 + + local function update(dt) + accum = accum + dt + if accum > 1 then + local z = zOrderSprite:getGlobalZOrder() + zOrderSprite:setGlobalZOrder(-z) + accum = 0 + end + end + + local function onNodeEvent(tag) + if tag == "exit" then + layer:unscheduleUpdate() + end + end + layer:scheduleUpdateWithPriorityLua(update,0) + layer:registerScriptHandler(onNodeEvent) + + return layer +end + + + function CocosNodeTest() local scene = cc.Scene:create() @@ -647,7 +699,8 @@ function CocosNodeTest() CameraZoomTest, ConvertToNode, NodeOpaqueTest, - NodeNonOpaqueTest + NodeNonOpaqueTest, + NodeGlobalZValueTest, } scene:addChild(CameraCenterTest()) diff --git a/samples/Lua/TestLua/Resources/luaScript/ParticleTest/ParticleTest.lua b/samples/Lua/TestLua/Resources/luaScript/ParticleTest/ParticleTest.lua index f0a9c1ae7c..1d1ff4f2bd 100644 --- a/samples/Lua/TestLua/Resources/luaScript/ParticleTest/ParticleTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/ParticleTest/ParticleTest.lua @@ -1278,8 +1278,8 @@ local function reorderSystem(dt) local childArray = ReorderParticleSystems_batchNode:getChildren() local random = math.random(1,table.getn(childArray)) local child = childArray[random] - -- problem: there's no getZOrder() for cc.Object - -- ReorderParticleSystems_batchNode:reorderChild(child, child:getZOrder() - 1) + -- problem: there's no getLocalZOrder() for cc.Object + -- ReorderParticleSystems_batchNode:reorderChild(child, child:getLocalZOrder() - 1) ReorderParticleSystems_batchNode:reorderChild(child, math.random(0, 99999)) end diff --git a/samples/Lua/TestLua/Resources/luaScript/PerformanceTest/PerformanceTest.lua b/samples/Lua/TestLua/Resources/luaScript/PerformanceTest/PerformanceTest.lua index 71f6c569f1..15c285d1a1 100644 --- a/samples/Lua/TestLua/Resources/luaScript/PerformanceTest/PerformanceTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/PerformanceTest/PerformanceTest.lua @@ -501,7 +501,7 @@ local function runParticleTest() end local function TestNCallback(tag,pMenuItem) - local nIndex = pMenuItem:getZOrder() - ParticleTestParam.kSubMenuBasicZOrder + local nIndex = pMenuItem:getLocalZOrder() - ParticleTestParam.kSubMenuBasicZOrder nSubtestNumber = nIndex ShowCurrentTest() end @@ -1178,7 +1178,7 @@ local function runSpriteTest() end local function TestNCallback(tag,pMenuItem) - local nIndex = pMenuItem:getZOrder() - SpriteTestParam.kSubMenuBasicZOrder + local nIndex = pMenuItem:getLocalZOrder() - SpriteTestParam.kSubMenuBasicZOrder nSubtestNumber = nIndex ShowCurrentTest() end @@ -1661,7 +1661,7 @@ local function CreatePerformancesTestScene(nPerformanceNo) end local function menuCallback(tag, pMenuItem) local scene = nil - local nIdx = pMenuItem:getZOrder() - kItemTagBasic + local nIdx = pMenuItem:getLocalZOrder() - kItemTagBasic local PerformanceTestScene = CreatePerformancesTestScene(nIdx) if nil ~= PerformanceTestScene then cc.Director:getInstance():replaceScene(PerformanceTestScene) diff --git a/tools/bindings-generator b/tools/bindings-generator index 6fc3372cdf..ad6f6c7816 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit 6fc3372cdfdbf39dd20bdcf1f60eb779773d32d7 +Subproject commit ad6f6c781687b0dd471c4df53c0ba5925e43894d diff --git a/tools/jenkins-scripts/job-trigger.py b/tools/jenkins-scripts/job-trigger.py index 5641f26862..ea83ac6712 100755 --- a/tools/jenkins-scripts/job-trigger.py +++ b/tools/jenkins-scripts/job-trigger.py @@ -59,7 +59,7 @@ def main(): except: traceback.print_exc() - job_trigger_url = os.environ['JOB_TRIGGER_URL']+access_token + job_trigger_url = os.environ['JOB_TRIGGER_URL'] #send trigger and payload post_data = {'payload':""} post_data['payload']= payload_str diff --git a/tools/tojs/genbindings-win32.bat b/tools/tojs/genbindings-win32.bat new file mode 100644 index 0000000000..b8c4c0e537 --- /dev/null +++ b/tools/tojs/genbindings-win32.bat @@ -0,0 +1,88 @@ +@echo off + +:: This script is used to generate jsbinding glue codes. +:: You should modify PYTHON_ROOT and NDK_ROOT to work under your environment. +:: Android ndk version must be at least ndk-r9b. + +set PYTHON_ROOT=C:/Python27 +set NDK_ROOT=G:/android/android-ndk-r9b +set NDK_LLVM_ROOT=%NDK_ROOT%/toolchains/llvm-3.3/prebuilt/windows-x86_64 + +set COCOS2DX_ROOT=%cd%/../.. +set "COCOS2DX_ROOT=%COCOS2DX_ROOT:\=/%" +set CXX_GENERATOR_ROOT=%COCOS2DX_ROOT%/tools/bindings-generator +set TO_JS_ROOT=%COCOS2DX_ROOT%/tools/tojs +set "CXX_GENERATOR_ROOT=%CXX_GENERATOR_ROOT:\=/%" +set OUTPUT_DIR=%COCOS2DX_ROOT%/scripting/auto-generated/js-bindings +set "OUTPUT_DIR=%OUTPUT_DIR:/=\%" + +set PATH=%PATH%;%CXX_GENERATOR_ROOT%/libclang;%CXX_GENERATOR_ROOT%/tools/win32;%PYTHON_ROOT% + +:: write userconf.ini + +set _CONF_INI_FILE=%cd%\userconf.ini +if exist %_CONF_INI_FILE% del /Q %_CONF_INI_FILE% + + +echo +echo generating userconf.ini... +echo --- +echo [DEFAULT] > %_CONF_INI_FILE% +echo androidndkdir=%NDK_ROOT% >> %_CONF_INI_FILE% +echo clangllvmdir=%NDK_LLVM_ROOT% >> %_CONF_INI_FILE% +echo cocosdir=%COCOS2DX_ROOT% >> %_CONF_INI_FILE% +echo cxxgeneratordir=%CXX_GENERATOR_ROOT% >> %_CONF_INI_FILE% +:: fixme: to fix parse error, we must difine __WCHAR_MAX__ and undefine __MINGW32__ . +echo extra_flags=-D__WCHAR_MAX__=0x7fffffff -U__MINGW32__ >> %_CONF_INI_FILE% +echo --- + + + +:: Generate bindings for cocos2dx +echo Generating bindings for cocos2dx... +python %CXX_GENERATOR_ROOT%/generator.py %TO_JS_ROOT%/cocos2dx.ini -s cocos2d-x -t spidermonkey -o %OUTPUT_DIR% -n js_cocos2dx_auto +if %errorlevel% neq 0 goto ERROR + +echo "Generating bindings for cocos2dx_extension..." +python %CXX_GENERATOR_ROOT%/generator.py %TO_JS_ROOT%/cocos2dx_extension.ini -s cocos2dx_extension -t spidermonkey -o %OUTPUT_DIR% -n js_cocos2dx_extension_auto +if %errorlevel% neq 0 goto ERROR + +echo "Generating bindings for cocos2dx_builder..." +python %CXX_GENERATOR_ROOT%/generator.py %TO_JS_ROOT%/cocos2dx_builder.ini -s cocos2dx_builder -t spidermonkey -o %OUTPUT_DIR% -n jsb_cocos2dx_builder_auto +if %errorlevel% neq 0 goto ERROR + +echo "Generating bindings for cocos2dx_gui..." +python %CXX_GENERATOR_ROOT%/generator.py %TO_JS_ROOT%/cocos2dx_gui.ini -s cocos2dx_gui -t spidermonkey -o %OUTPUT_DIR% -n js_cocos2dx_gui_auto +if %errorlevel% neq 0 goto ERROR + + +echo "Generating bindings for cocos2dx_studio..." +python %CXX_GENERATOR_ROOT%/generator.py %TO_JS_ROOT%/cocos2dx_studio.ini -s cocos2dx_studio -t spidermonkey -o %OUTPUT_DIR% -n js_cocos2dx_studio_auto +if %errorlevel% neq 0 goto ERROR + + +echo "Generating bindings for cocos2dx_spine..." +python %CXX_GENERATOR_ROOT%/generator.py %TO_JS_ROOT%/cocos2dx_spine.ini -s cocos2dx_spine -t spidermonkey -o %OUTPUT_DIR% -n js_cocos2dx_spine_auto +if %errorlevel% neq 0 goto ERROR + + +:: Change the generated file format from DOS to UNIX. +pushd "%OUTPUT_DIR%" +dos2unix * +popd + +echo --------------------------------- +echo Generating bindings succeeds. +echo --------------------------------- + +goto QUIT + +:ERROR +echo --------------------------------- +echo Generating bindings fails. +echo --------------------------------- + +:QUIT + +pause + diff --git a/tools/tojs/genbindings.sh b/tools/tojs/genbindings.sh index 00d2d7a8c5..aa95a4e28b 100755 --- a/tools/tojs/genbindings.sh +++ b/tools/tojs/genbindings.sh @@ -1,4 +1,9 @@ #!/bin/bash +# +# Usage: +# export NDK_ROOT=/path/to/ndk-r9b +# ./genbindings.sh +# # exit this script if any commmand fails set -e @@ -6,10 +11,12 @@ set -e # read user.cfg if it exists and is readable _CFG_FILE=$(dirname "$0")"/user.cfg" -if [ -f "$_CFG_FILE" ] +if [ -f "$_CFG_FILE" ]; then - [ -r "$_CFG_FILE" ] || die "Fatal Error: $_CFG_FILE exists but is unreadable" - . "$_CFG_FILE" + if [ ! -r "$_CFG_FILE" ]; then + echo "Fatal Error: $_CFG_FILE exists but is unreadable" + exit 1 + fi fi # paths @@ -19,11 +26,6 @@ if [ -z "${NDK_ROOT+aaa}" ]; then NDK_ROOT="$HOME/bin/android-ndk" fi -if [ -z "${CLANG_ROOT+aaa}" ]; then -# ... if CLANG_ROOT is not set, use "$HOME/bin/clang+llvm-3.3" - CLANG_ROOT="$HOME/bin/clang+llvm-3.3" -fi - if [ -z "${PYTHON_BIN+aaa}" ]; then # ... if PYTHON_BIN is not set, use "/usr/bin/python2.7" PYTHON_BIN="/usr/bin/python2.7" @@ -35,7 +37,7 @@ DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" # paths with defaults hardcoded to relative paths if [ -z "${COCOS2DX_ROOT+aaa}" ]; then - COCOS2DX_ROOT="$DIR/../../" + COCOS2DX_ROOT="$DIR/../.." fi if [ -z "${CXX_GENERATOR_ROOT+aaa}" ]; then @@ -43,16 +45,59 @@ if [ -z "${CXX_GENERATOR_ROOT+aaa}" ]; then fi if [ -z "${TOJS_ROOT+aaa}" ]; then - TO_JS_ROOT="$COCOS2DX_ROOT/tools/tojs" + TOJS_ROOT="$COCOS2DX_ROOT/tools/tojs" fi +# set output dir +OUTPUT_DIR=${COCOS2DX_ROOT}/cocos/scripting/auto-generated/js-bindings + echo "Paths" echo " NDK_ROOT: $NDK_ROOT" -echo " CLANG_ROOT: $CLANG_ROOT" echo " PYTHON_BIN: $PYTHON_BIN" echo " COCOS2DX_ROOT: $COCOS2DX_ROOT" echo " CXX_GENERATOR_ROOT: $CXX_GENERATOR_ROOT" -echo " TO_JS_ROOT: $TO_JS_ROOT" +echo " TOJS_ROOT: $TOJS_ROOT" + +# check NDK version, must be r9b +if ! grep -q r9b $NDK_ROOT/RELEASE.TXT +then + echo " Fatal Error: NDK r9b must be required!" + exit 1 +fi + +# check clang include path +OS_NAME=$('uname') +NDK_LLVM_ROOT=$NDK_ROOT/toolchains/llvm-3.3/prebuilt +case "$OS_NAME" in + Darwin | darwin) + echo "in darwin" + if [ -d "$NDK_LLVM_ROOT/darwin-x86_64" ]; then + NDK_LLVM_ROOT=$NDK_LLVM_ROOT/darwin-x86_64 + elif [ -d "$NDK_LLVM_ROOT/darwin-x86" ]; then + NDK_LLVM_ROOT=$NDK_LLVM_ROOT/darwin-x86 + else + echo $NDK_LLVM_ROOT + echo " Fatal Error: $NDK_LLVM_ROOT doesn't contains prebuilt llvm 3.3" + exit 1 + fi + ;; + Linux | linux) + echo "in linux" + if [ -d "$NDK_LLVM_ROOT/linux-x86_64" ]; then + NDK_LLVM_ROOT=$NDK_LLVM_ROOT/linux-x86_64 + elif [ -d "$NDK_LLVM_ROOT/linux-x86" ]; then + NDK_LLVM_ROOT=$NDK_LLVM_ROOT/linux-x86 + else + echo " Fatal Error: $NDK_LLVM_ROOT doesn't contains prebuilt llvm 3.3" + exit 1 + fi + ;; + *) + echo " Fatal Error: Please run this script in linux or mac osx." + exit 1 + ;; +esac + # write userconf.ini @@ -65,7 +110,7 @@ fi _CONTENTS="" _CONTENTS+="[DEFAULT]"'\n' _CONTENTS+="androidndkdir=$NDK_ROOT"'\n' -_CONTENTS+="clangllvmdir=$CLANG_ROOT"'\n' +_CONTENTS+="clangllvmdir=$NDK_LLVM_ROOT"'\n' _CONTENTS+="cocosdir=$COCOS2DX_ROOT"'\n' _CONTENTS+="cxxgeneratordir=$CXX_GENERATOR_ROOT"'\n' _CONTENTS+="extra_flags="'\n' @@ -80,19 +125,20 @@ echo --- # Generate bindings for cocos2dx echo "Generating bindings for cocos2dx..." set -x -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx.ini -s cocos2d-x -t spidermonkey -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/js-bindings -n jsb_cocos2dx_auto +LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOJS_ROOT}/cocos2dx.ini -s cocos2d-x -t spidermonkey -o ${OUTPUT_DIR} -n jsb_cocos2dx_auto echo "Generating bindings for cocos2dx_extension..." -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_extension.ini -s cocos2dx_extension -t spidermonkey -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/js-bindings -n jsb_cocos2dx_extension_auto +LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOJS_ROOT}/cocos2dx_extension.ini -s cocos2dx_extension -t spidermonkey -o ${OUTPUT_DIR} -n jsb_cocos2dx_extension_auto echo "Generating bindings for cocos2dx_builder..." -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_builder.ini -s cocos2dx_builder -t spidermonkey -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/js-bindings -n jsb_cocos2dx_builder_auto +LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOJS_ROOT}/cocos2dx_builder.ini -s cocos2dx_builder -t spidermonkey -o ${OUTPUT_DIR} -n jsb_cocos2dx_builder_auto echo "Generating bindings for cocos2dx_gui..." -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_gui.ini -s cocos2dx_gui -t spidermonkey -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/js-bindings -n jsb_cocos2dx_gui_auto +LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOJS_ROOT}/cocos2dx_gui.ini -s cocos2dx_gui -t spidermonkey -o ${OUTPUT_DIR} -n jsb_cocos2dx_gui_auto echo "Generating bindings for cocos2dx_studio..." -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_studio.ini -s cocos2dx_studio -t spidermonkey -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/js-bindings -n jsb_cocos2dx_studio_auto +LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOJS_ROOT}/cocos2dx_studio.ini -s cocos2dx_studio -t spidermonkey -o ${OUTPUT_DIR} -n jsb_cocos2dx_studio_auto echo "Generating bindings for cocos2dx_spine..." -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_spine.ini -s cocos2dx_spine -t spidermonkey -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/js-bindings -n jsb_cocos2dx_spine_auto \ No newline at end of file +LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOJS_ROOT}/cocos2dx_spine.ini -s cocos2dx_spine -t spidermonkey -o ${OUTPUT_DIR} -n jsb_cocos2dx_spine_auto + diff --git a/tools/tolua/genbindings-win32.bat b/tools/tolua/genbindings-win32.bat new file mode 100644 index 0000000000..1aeddcdcfa --- /dev/null +++ b/tools/tolua/genbindings-win32.bat @@ -0,0 +1,89 @@ +@echo off + +:: This script is used to generate luabinding glue codes. +:: You should modify PYTHON_ROOT and NDK_ROOT to work under your environment. +:: Android ndk version must be at least ndk-r9b. + +set PYTHON_ROOT=C:/Python27 +set NDK_ROOT=G:/android/android-ndk-r9b +set NDK_LLVM_ROOT=%NDK_ROOT%/toolchains/llvm-3.3/prebuilt/windows-x86_64 + +set COCOS2DX_ROOT=%cd%/../.. +set "COCOS2DX_ROOT=%COCOS2DX_ROOT:\=/%" +set CXX_GENERATOR_ROOT=%COCOS2DX_ROOT%/tools/bindings-generator +set TO_LUA_ROOT=%COCOS2DX_ROOT%/tools/tolua +set "CXX_GENERATOR_ROOT=%CXX_GENERATOR_ROOT:\=/%" +set OUTPUT_DIR=%COCOS2DX_ROOT%/scripting/auto-generated/lua-bindings +set "OUTPUT_DIR=%OUTPUT_DIR:/=\%" + +set PATH=%PATH%;%CXX_GENERATOR_ROOT%/libclang;%CXX_GENERATOR_ROOT%/tools/win32;%PYTHON_ROOT% + +:: write userconf.ini + +set _CONF_INI_FILE=%cd%\userconf.ini +if exist %_CONF_INI_FILE% del /Q %_CONF_INI_FILE% + + +echo +echo generating userconf.ini... +echo --- +echo [DEFAULT] > %_CONF_INI_FILE% +echo androidndkdir=%NDK_ROOT% >> %_CONF_INI_FILE% +echo clangllvmdir=%NDK_LLVM_ROOT% >> %_CONF_INI_FILE% +echo cocosdir=%COCOS2DX_ROOT% >> %_CONF_INI_FILE% +echo cxxgeneratordir=%CXX_GENERATOR_ROOT% >> %_CONF_INI_FILE% +:: fixme: to fix parse error, we must difine __WCHAR_MAX__ and undefine __MINGW32__ . +echo extra_flags=-D__WCHAR_MAX__=0x7fffffff -U__MINGW32__ >> %_CONF_INI_FILE% +echo --- + + + +:: Generate bindings for cocos2dx +echo Generating bindings for cocos2dx... +python %CXX_GENERATOR_ROOT%/generator.py %TO_LUA_ROOT%/cocos2dx.ini -s cocos2d-x -t lua -o %OUTPUT_DIR% -n lua_cocos2dx_auto +if %errorlevel% neq 0 goto ERROR + +echo "Generating bindings for cocos2dx_extension..." +python %CXX_GENERATOR_ROOT%/generator.py %TO_LUA_ROOT%/cocos2dx_extension.ini -s cocos2dx_extension -t lua -o %OUTPUT_DIR% -n lua_cocos2dx_extension_auto +if %errorlevel% neq 0 goto ERROR + +echo "Generating bindings for cocos2dx_gui..." +python %CXX_GENERATOR_ROOT%/generator.py %TO_LUA_ROOT%/cocos2dx_gui.ini -s cocos2dx_gui -t lua -o %OUTPUT_DIR% -n lua_cocos2dx_gui_auto +if %errorlevel% neq 0 goto ERROR + + +echo "Generating bindings for cocos2dx_studio..." +python %CXX_GENERATOR_ROOT%/generator.py %TO_LUA_ROOT%/cocos2dx_studio.ini -s cocos2dx_studio -t lua -o %OUTPUT_DIR% -n lua_cocos2dx_studio_auto +if %errorlevel% neq 0 goto ERROR + + +echo "Generating bindings for cocos2dx_spine..." +python %CXX_GENERATOR_ROOT%/generator.py %TO_LUA_ROOT%/cocos2dx_spine.ini -s cocos2dx_spine -t lua -o %OUTPUT_DIR% -n lua_cocos2dx_spine_auto +if %errorlevel% neq 0 goto ERROR + + +echo "Generating bindings for cocos2dx_physics..." +python %CXX_GENERATOR_ROOT%/generator.py %TO_LUA_ROOT%/cocos2dx_physics.ini -s cocos2dx_physics -t lua -o %OUTPUT_DIR% -n lua_cocos2dx_physics_auto +if %errorlevel% neq 0 goto ERROR + + +:: Change the generated file format from DOS to UNIX. +pushd "%OUTPUT_DIR%" +dos2unix * +popd + +echo --------------------------------- +echo Generating bindings succeeds. +echo --------------------------------- + +goto QUIT + +:ERROR +echo --------------------------------- +echo Generating bindings fails. +echo --------------------------------- + +:QUIT + +pause + diff --git a/tools/tolua/genbindings.sh b/tools/tolua/genbindings.sh index eb463fcfa5..e15de46b1a 100755 --- a/tools/tolua/genbindings.sh +++ b/tools/tolua/genbindings.sh @@ -1,4 +1,9 @@ #!/bin/bash +# +# Usage: +# export NDK_ROOT=/path/to/ndk-r9b +# ./genbindings.sh +# # exit this script if any commmand fails set -e @@ -6,10 +11,12 @@ set -e # read user.cfg if it exists and is readable _CFG_FILE=$(dirname "$0")"/user.cfg" -if [ -f "$_CFG_FILE" ] +if [ -f "$_CFG_FILE" ]; then - [ -r "$_CFG_FILE" ] || die "Fatal Error: $_CFG_FILE exists but is unreadable" - . "$_CFG_FILE" + if [ ! -r "$_CFG_FILE" ]; then + echo "Fatal Error: $_CFG_FILE exists but is unreadable" + exit 1 + fi fi # paths @@ -19,11 +26,6 @@ if [ -z "${NDK_ROOT+aaa}" ]; then NDK_ROOT="$HOME/bin/android-ndk" fi -if [ -z "${CLANG_ROOT+aaa}" ]; then -# ... if CLANG_ROOT is not set, use "$HOME/bin/clang+llvm-3.3" - CLANG_ROOT="$HOME/bin/clang+llvm-3.3" -fi - if [ -z "${PYTHON_BIN+aaa}" ]; then # ... if PYTHON_BIN is not set, use "/usr/bin/python2.7" PYTHON_BIN="/usr/bin/python2.7" @@ -35,24 +37,67 @@ DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" # paths with defaults hardcoded to relative paths if [ -z "${COCOS2DX_ROOT+aaa}" ]; then - COCOS2DX_ROOT="$DIR/../../" + COCOS2DX_ROOT="$DIR/../.." fi if [ -z "${CXX_GENERATOR_ROOT+aaa}" ]; then CXX_GENERATOR_ROOT="$COCOS2DX_ROOT/tools/bindings-generator" fi -if [ -z "${TOJS_ROOT+aaa}" ]; then - TO_JS_ROOT="$COCOS2DX_ROOT/tools/tolua" +if [ -z "${TOLUA_ROOT+aaa}" ]; then + TOLUA_ROOT="$COCOS2DX_ROOT/tools/tolua" fi +# set output dir +OUTPUT_DIR=${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings + echo "Paths" echo " NDK_ROOT: $NDK_ROOT" -echo " CLANG_ROOT: $CLANG_ROOT" echo " PYTHON_BIN: $PYTHON_BIN" echo " COCOS2DX_ROOT: $COCOS2DX_ROOT" echo " CXX_GENERATOR_ROOT: $CXX_GENERATOR_ROOT" -echo " TO_JS_ROOT: $TO_JS_ROOT" +echo " TOLUA_ROOT: $TOLUA_ROOT" + +# check NDK version, must be r9b +if ! grep -q r9b $NDK_ROOT/RELEASE.TXT +then + echo " Fatal Error: NDK r9b must be required!" + exit 1 +fi + +# check clang include path +OS_NAME=$('uname') +NDK_LLVM_ROOT=$NDK_ROOT/toolchains/llvm-3.3/prebuilt +case "$OS_NAME" in + Darwin | darwin) + echo "in darwin" + if [ -d "$NDK_LLVM_ROOT/darwin-x86_64" ]; then + NDK_LLVM_ROOT=$NDK_LLVM_ROOT/darwin-x86_64 + elif [ -d "$NDK_LLVM_ROOT/darwin-x86" ]; then + NDK_LLVM_ROOT=$NDK_LLVM_ROOT/darwin-x86 + else + echo $NDK_LLVM_ROOT + echo " Fatal Error: $NDK_LLVM_ROOT doesn't contains prebuilt llvm 3.3" + exit 1 + fi + ;; + Linux | linux) + echo "in linux" + if [ -d "$NDK_LLVM_ROOT/linux-x86_64" ]; then + NDK_LLVM_ROOT=$NDK_LLVM_ROOT/linux-x86_64 + elif [ -d "$NDK_LLVM_ROOT/linux-x86" ]; then + NDK_LLVM_ROOT=$NDK_LLVM_ROOT/linux-x86 + else + echo " Fatal Error: $NDK_LLVM_ROOT doesn't contains prebuilt llvm 3.3" + exit 1 + fi + ;; + *) + echo " Fatal Error: Please run this script in linux or mac osx." + exit 1 + ;; +esac + # write userconf.ini @@ -65,7 +110,7 @@ fi _CONTENTS="" _CONTENTS+="[DEFAULT]"'\n' _CONTENTS+="androidndkdir=$NDK_ROOT"'\n' -_CONTENTS+="clangllvmdir=$CLANG_ROOT"'\n' +_CONTENTS+="clangllvmdir=$NDK_LLVM_ROOT"'\n' _CONTENTS+="cocosdir=$COCOS2DX_ROOT"'\n' _CONTENTS+="cxxgeneratordir=$CXX_GENERATOR_ROOT"'\n' _CONTENTS+="extra_flags="'\n' @@ -80,19 +125,20 @@ echo --- # Generate bindings for cocos2dx echo "Generating bindings for cocos2dx..." set -x -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx.ini -s cocos2d-x -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_auto +LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOLUA_ROOT}/cocos2dx.ini -s cocos2d-x -t lua -o ${OUTPUT_DIR} -n lua_cocos2dx_auto echo "Generating bindings for cocos2dx_extension..." -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_extension.ini -s cocos2dx_extension -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_extension_auto +LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOLUA_ROOT}/cocos2dx_extension.ini -s cocos2dx_extension -t lua -o ${OUTPUT_DIR} -n lua_cocos2dx_extension_auto echo "Generating bindings for cocos2dx_gui..." -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_gui.ini -s cocos2dx_gui -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_gui_auto +LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOLUA_ROOT}/cocos2dx_gui.ini -s cocos2dx_gui -t lua -o ${OUTPUT_DIR} -n lua_cocos2dx_gui_auto echo "Generating bindings for cocos2dx_studio..." -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_studio.ini -s cocos2dx_studio -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_studio_auto +LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOLUA_ROOT}/cocos2dx_studio.ini -s cocos2dx_studio -t lua -o ${OUTPUT_DIR} -n lua_cocos2dx_studio_auto echo "Generating bindings for cocos2dx_spine..." -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_spine.ini -s cocos2dx_spine -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_spine_auto +LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOLUA_ROOT}/cocos2dx_spine.ini -s cocos2dx_spine -t lua -o ${OUTPUT_DIR} -n lua_cocos2dx_spine_auto echo "Generating bindings for cocos2dx_physics..." -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_physics.ini -s cocos2dx_physics -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_physics_auto +LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOLUA_ROOT}/cocos2dx_physics.ini -s cocos2dx_physics -t lua -o ${OUTPUT_DIR} -n lua_cocos2dx_physics_auto + diff --git a/tools/travis-scripts/before-install.sh b/tools/travis-scripts/before-install.sh index acfdd36e12..eb29f0fc5d 100755 --- a/tools/travis-scripts/before-install.sh +++ b/tools/travis-scripts/before-install.sh @@ -6,9 +6,6 @@ set -e DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" COCOS2DX_ROOT="$DIR"/../.. HOST_NAME="" -LLVM_VERSION="" -LLVM_PACKAGE="" -LLVM_PACKAGE_SUFFIX="" mkdir -p $HOME/bin cd $HOME/bin @@ -29,47 +26,6 @@ install_android_ndk() mv android-ndk-r9b android-ndk } -install_llvm() -{ - LLVM_VERSION="3.3" - if [ "$PLATFORM"x = "ios"x ]; then - LLVM_PACKAGE="clang+llvm-3.3-x86_64-apple-darwin12" - LLVM_PACKAGE_SUFFIX=".tar.gz" - else - LLVM_PACKAGE="clang+llvm-3.3-Ubuntu-13.04-x86_64-linux-gnu" - LLVM_PACKAGE_SUFFIX=".tar.bz2" - fi - - # Download llvm - echo "Download ${LLVM_PACKAGE} ..." - curl -O http://llvm.org/releases/${LLVM_VERSION}/${LLVM_PACKAGE}${LLVM_PACKAGE_SUFFIX} - echo "Decompress ${LLVM_PACKAGE} ..." - if [ "$PLATFORM"x = "ios"x ]; then - tar xzf ${LLVM_PACKAGE}${LLVM_PACKAGE_SUFFIX} - else - tar xjf ${LLVM_PACKAGE}${LLVM_PACKAGE_SUFFIX} - fi - - # Rename llvm - mv ${LLVM_PACKAGE} clang+llvm-${LLVM_VERSION} -} - -install_llvm_3_2() -{ - if [ "$PLATFORM"x = "ios"x ]; then - HOST_NAME="apple-darwin11" - else - HOST_NAME="linux-ubuntu-12.04" - fi - # Download llvm3.2 - echo "Download clang+llvm-3.2-x86_64-${HOST_NAME}.tar.gz" - curl -O http://llvm.org/releases/3.2/clang+llvm-3.2-x86_64-${HOST_NAME}.tar.gz - echo "Decompress clang+llvm-3.2-x86_64-${HOST_NAME}.tar.gz ..." - tar xzf clang+llvm-3.2-x86_64-${HOST_NAME}.tar.gz - # Rename llvm - mv clang+llvm-3.2-x86_64-${HOST_NAME} clang+llvm-3.2 -} - install_nacl_sdk() { # NaCl compilers are built for 32-bit linux so we need to install @@ -92,7 +48,6 @@ if [ "$GEN_JSB"x = "YES"x ]; then exit 0 fi install_android_ndk - install_llvm elif [ "$PLATFORM"x = "linux"x ]; then sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test # OpenMW team provides SDL2 package. @@ -104,19 +59,15 @@ elif [ "$PLATFORM"x = "linux"x ]; then g++ --version bash $COCOS2DX_ROOT/build/install-deps-linux.sh install_android_ndk - install_llvm elif [ "$PLATFORM"x = "nacl"x ]; then install_nacl_sdk elif [ "$PLATFORM"x = "android"x ]; then install_android_ndk - install_llvm elif [ "$PLATFORM"x = "emscripten"x ]; then sudo rm -rf /dev/shm && sudo ln -s /run/shm /dev/shm install_android_ndk - install_llvm_3_2 elif [ "$PLATFORM"x = "ios"x ]; then install_android_ndk - install_llvm pushd $COCOS2DX_ROOT git submodule add https://github.com/facebook/xctool.git ./xctool @@ -127,3 +78,4 @@ else echo "Unknown \$PLATFORM: '$PLATFORM'" exit 1 fi +