Merge remote-tracking branch 'remotes/upstream/develop' into develop

Conflicts:
	cocos/2d/CCFontDefinition.cpp
This commit is contained in:
Hanju Kim 2014-01-22 14:15:21 +09:00
commit 64ab0c0e35
91 changed files with 1394 additions and 3793 deletions

View File

@ -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.

View File

@ -1 +1 @@
63e6598ea5798bf42bbd22c2295e65f7c739695a
db31f01b55bf1ae19e57e71bae6f58a037bfe5b9

View File

@ -1 +1 @@
447e7ba37294e6da0df2e02f5a62f30fb15e3272
986d41d9721f8079f005999caa9fb0053ea11321

View File

@ -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 \

View File

@ -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();
}
}

View File

@ -234,7 +234,7 @@ void EventDispatcher::visitTarget(Node* node, bool isRootNode)
if (isRootNode)
{
std::vector<int> globalZOrders;
std::vector<float> 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);

View File

@ -231,7 +231,7 @@ protected:
std::unordered_map<Node*, int> _nodePriorityMap;
/** key: Global Z Order, value: Sorted Nodes */
std::unordered_map<int, std::vector<Node*>> _globalZOrderNodeMap;
std::unordered_map<float, std::vector<Node*>> _globalZOrderNodeMap;
/** The listeners to be added after dispatching event */
std::vector<EventListener*> _toAddedListeners;

View File

@ -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);

View File

@ -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;
};

View File

@ -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<FontFreeType*>(_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;
}

View File

@ -49,6 +49,7 @@ struct FontLetterDefinition
float anchorX;
float anchorY;
bool validDefinition;
int xAdvance;
};
class CC_DLL FontAtlas : public Object

View File

@ -26,8 +26,10 @@
#include <sstream>
#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
{

View File

@ -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

View File

@ -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_) */

View File

@ -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)

View File

@ -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;

View File

@ -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 <unordered_map>
#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<unsigned short, FontLetterDefinition> _fontLettersDefinitionUTF16;
float _commonLineHeight;
static const int DEFAUL_ATLAS_TEXTURE_SIZE;
};
NS_CC_END
#endif

View File

@ -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);
}

View File

@ -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;

View File

@ -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<int>(_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<int>(_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<int>(_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

View File

@ -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

View File

@ -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);
}
@ -476,18 +477,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;
@ -521,7 +522,7 @@ bool Label::setCurrentString(unsigned short *stringToSet)
//
_currentUTF16String = stringToSet;
// compute the advances
return computeAdvancesForString(stringToSet);
return computeHorizontalKernings(stringToSet);
}
void Label::resetCurrentString()
@ -560,10 +561,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;
@ -698,8 +697,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);
@ -712,12 +711,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
@ -725,9 +724,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
@ -752,7 +758,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;
@ -760,7 +766,7 @@ int Label::getAdvanceForChar(unsigned short c, int hintPositionInString) const
if (!validDefinition)
return -1;
return (_advances[hintPositionInString].width);
return tempDefinition.xAdvance;
}
else
{

View File

@ -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;

View File

@ -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;

View File

@ -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<unsigned short> strWhole = cc_utf16_vec_from_utf16_str(theLabel->getUTF8String());
size_t stringLength = strWhole.size();
vector<unsigned short> multiline_string;
multiline_string.reserve( stringLength );
vector<unsigned short> 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<LetterInfo> *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<unsigned short> 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<unsigned short> 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<LetterInfo> *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)
{

View File

@ -64,29 +64,12 @@ THE SOFTWARE.
NS_CC_BEGIN
#if CC_USE_ARRAY_VECTOR
bool nodeComparisonLess(const RCPtr<Object>& pp1, const RCPtr<Object>& pp2)
bool nodeComparisonLess(Node* n1, Node* n2)
{
Object *p1 = static_cast<Object*>(pp1);
Object *p2 = static_cast<Object*>(pp2);
Node *n1 = static_cast<Node*>(p1);
Node *n2 = static_cast<Node*>(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<Node*>(p1);
Node *n2 = static_cast<Node*>(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);
}
}

View File

@ -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<Object>& pp1, const RCPtr<Object>& 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

View File

@ -101,8 +101,8 @@ void ParallaxNode::addChild(Node *child, int z, const Point& ratio, const Point&
ccArrayAppendObjectWithResize(_parallaxArray, (Object*)obj);
Point pos = _position;
pos.x = pos.x * ratio.x + offset.x;
pos.y = pos.y * ratio.y + offset.y;
pos.x = -pos.x + pos.x * ratio.x + offset.x;
pos.y = -pos.y + pos.y * ratio.y + offset.y;
child->setPosition(pos);
Node::addChild(child, z, child->getTag());

View File

@ -384,7 +384,6 @@ void ParticleBatchNode::draw(void)
_batchCommand.init(
_globalZOrder,
_textureAtlas->getTexture()->getName(),
_shaderProgram,
_blendFunc,
_textureAtlas,

View File

@ -358,7 +358,6 @@ void SpriteBatchNode::draw()
_batchCommand.init(
_globalZOrder,
_textureAtlas->getTexture()->getName(),
_shaderProgram,
_blendFunc,
_textureAtlas,

View File

@ -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 <stdio.h>
#include <string.h>
#include <vector>
#include <string>
#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; c<numLines; ++c )
{
delete _lines[c];
}
_lines.clear();
if (_pageData)
{
delete [] _pageData;
}
if (_pageTexture)
{
_pageTexture->release();
}
}
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<unsigned short int, GlyphDef> &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

View File

@ -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 <vector>
#include <unordered_map>
#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<int>(_glyphs.size()); }
const GlyphDef & getGlyphAt(int index) const { return _glyphs[index]; }
protected:
float _x;
float _y;
float _width;
float _height;
std::vector<GlyphDef> _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<int>(_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<TextLineDef*> _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<int>(_pages.size()); }
TextPageDef* getPageAt(int index) const { return _pages[index]; }
protected:
std::vector<TextPageDef*> _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<unsigned short int, GlyphDef> &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<unsigned short int, GlyphDef> _textGlyphs;
TextFontPagesDef* _fontPages;
Font* _font;
};
NS_CC_END
#endif // _CCTextImage_h_

View File

@ -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

View File

@ -247,9 +247,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClCompile Include="CCFont.cpp" />
<ClCompile Include="CCFontAtlas.cpp" />
<ClCompile Include="CCFontAtlasCache.cpp" />
<ClCompile Include="CCFontAtlasFactory.cpp" />
<ClCompile Include="CCFontCharMap.cpp" />
<ClCompile Include="CCFontDefinition.cpp" />
<ClCompile Include="CCFontFNT.cpp" />
<ClCompile Include="CCFontFreeType.cpp" />
<ClCompile Include="ccFPSImages.c" />
@ -288,7 +286,6 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClCompile Include="CCSpriteFrame.cpp" />
<ClCompile Include="CCSpriteFrameCache.cpp" />
<ClCompile Include="CCTextFieldTTF.cpp" />
<ClCompile Include="CCTextImage.cpp" />
<ClCompile Include="CCTexture2D.cpp" />
<ClCompile Include="CCTextureAtlas.cpp" />
<ClCompile Include="CCTextureCache.cpp" />
@ -429,9 +426,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClInclude Include="CCFont.h" />
<ClInclude Include="CCFontAtlas.h" />
<ClInclude Include="CCFontAtlasCache.h" />
<ClInclude Include="CCFontAtlasFactory.h" />
<ClInclude Include="CCFontCharMap.h" />
<ClInclude Include="CCFontDefinition.h" />
<ClInclude Include="CCFontFNT.h" />
<ClInclude Include="CCFontFreeType.h" />
<ClInclude Include="ccFPSImages.h" />
@ -490,7 +485,6 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClInclude Include="CCSpriteFrame.h" />
<ClInclude Include="CCSpriteFrameCache.h" />
<ClInclude Include="CCTextFieldTTF.h" />
<ClInclude Include="CCTextImage.h" />
<ClInclude Include="CCTexture2D.h" />
<ClInclude Include="CCTextureAtlas.h" />
<ClInclude Include="CCTextureCache.h" />

View File

@ -318,12 +318,6 @@
<ClCompile Include="CCFontAtlasCache.cpp">
<Filter>label_nodes</Filter>
</ClCompile>
<ClCompile Include="CCFontAtlasFactory.cpp">
<Filter>label_nodes</Filter>
</ClCompile>
<ClCompile Include="CCFontDefinition.cpp">
<Filter>label_nodes</Filter>
</ClCompile>
<ClCompile Include="CCFontFNT.cpp">
<Filter>label_nodes</Filter>
</ClCompile>
@ -345,9 +339,6 @@
<ClCompile Include="CCLabelTTF.cpp">
<Filter>label_nodes</Filter>
</ClCompile>
<ClCompile Include="CCTextImage.cpp">
<Filter>label_nodes</Filter>
</ClCompile>
<ClCompile Include="..\base\etc1.cpp">
<Filter>platform\etc</Filter>
</ClCompile>
@ -834,12 +825,6 @@
<ClInclude Include="CCFontAtlasCache.h">
<Filter>label_nodes</Filter>
</ClInclude>
<ClInclude Include="CCFontAtlasFactory.h">
<Filter>label_nodes</Filter>
</ClInclude>
<ClInclude Include="CCFontDefinition.h">
<Filter>label_nodes</Filter>
</ClInclude>
<ClInclude Include="CCFontFNT.h">
<Filter>label_nodes</Filter>
</ClInclude>
@ -864,9 +849,6 @@
<ClInclude Include="CCLabelTTF.h">
<Filter>label_nodes</Filter>
</ClInclude>
<ClInclude Include="CCTextImage.h">
<Filter>label_nodes</Filter>
</ClInclude>
<ClInclude Include="..\base\etc1.h">
<Filter>platform\etc</Filter>
</ClInclude>

View File

@ -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 <Cocoa/Cocoa.h>
#include "platform/CCCommon.h"
#include "CCEGLView.h"
#define GLFW_EXPOSE_NATIVE_NSGL
#define GLFW_EXPOSE_NATIVE_COCOA
#include "glfw3native.h"
#include <stdarg.h>
#include <stdio.h>
#import "EAGLView.h"
#include <Cocoa/Cocoa.h>
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

View File

@ -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 <Foundation/Foundation.h>
#import "CCDirectorCaller.h"
#import "CCDirector.h"
#import "EAGLView.h"
#import "CCEventDispatcherMac.h"
#include "CCDirector.h"
#include "CCAutoreleasePool.h"
#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
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];
}

View File

@ -27,7 +27,6 @@ THE SOFTWARE.
#include <unordered_map>
#include "EAGLView.h"
#include "CCDirector.h"
#include "CCSet.h"
#include "CCTouch.h"

View File

@ -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 <Availability.h>
#ifndef __CC_EVENT_DISPATCHER_MAC_H__
#define __CC_EVENT_DISPATCHER_MAC_H__
#import <Cocoa/Cocoa.h>
#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 <NSObject>
@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 <NSObject>
@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 <NSObject>
@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 <CCMacEventDelegate> {
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<CCMouseEventDelegate>) 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<CCKeyboardEventDelegate>) 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<CCTouchEventDelegate>)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__

View File

@ -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 <Availability.h>
#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<CCMouseEventDelegate>) 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<CCKeyboardEventDelegate>) 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<CCTouchEventDelegate>) 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

View File

@ -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 <Cocoa/Cocoa.h>
@interface CCWindow : NSWindow
{
}
- (id) initWithFrame:(NSRect)frame fullscreen:(BOOL)fullscreen;
@end
#endif // __CC_WINDOW_H__

View File

@ -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

View File

@ -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 <Cocoa/Cocoa.h>
#import "ccConfig.h"
//PROTOCOLS:
@protocol CCMacEventDelegate <NSObject>
// 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<CCMacEventDelegate> eventDelegate_;
BOOL isFullScreen_;
NSWindow *fullScreenWindow_;
// cache
NSWindow *windowGLView_;
NSView *superViewGLView_;
NSRect originalWinRect_; // Original size and position
float frameZoomFactor_;
}
@property (nonatomic, readwrite, assign) id<CCMacEventDelegate> 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__

View File

@ -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 <Availability.h>
#import "EAGLView.h"
#import "CCEGLView.h"
#import <OpenGL/gl.h>
#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

View File

@ -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;

View File

@ -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;

View File

@ -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<int>(_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

View File

@ -25,8 +25,10 @@ THE SOFTWARE.
#ifndef __AUTORELEASEPOOL_H__
#define __AUTORELEASEPOOL_H__
#include <stack>
#include <vector>
#include <string>
#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<Object*> _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<Object*> _managedObjectArray;
std::string _name;
};
class CC_DLL PoolManager
{
Vector<AutoreleasePool*> _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<AutoreleasePool*> _releasePoolStack;
AutoreleasePool *_curReleasePool;
};
// end of base_nodes group

View File

@ -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;
}

View File

@ -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

@ -1 +1 @@
Subproject commit de699f63aef423c3d90725171b0f020a719ef572
Subproject commit 68ff365557a8bdb119c2a4e2502214b4d1025c7e

View File

@ -1 +1 @@
9d9d07e19dba691a22e4d184f0ec0e6ae6207a9b
85c7400aec0f87b3851772fbdbc01bf59f5402d8

View File

@ -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,
}

View File

@ -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

View File

@ -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

View File

@ -124,6 +124,7 @@ Classes/PerformanceTest/PerformanceLabelTest.cpp \
Classes/PerformanceTest/PerformanceRendererTest.cpp \
Classes/PerformanceTest/PerformanceContainerTest.cpp \
Classes/PhysicsTest/PhysicsTest.cpp \
Classes/ReleasePoolTest/ReleasePoolTest.cpp \
Classes/RenderTextureTest/RenderTextureTest.cpp \
Classes/RotateWorldTest/RotateWorldTest.cpp \
Classes/SceneTest/SceneTest.cpp \

View File

@ -119,6 +119,7 @@ set(SAMPLE_SRC
Classes/PerformanceTest/PerformanceRendererTest.cpp
Classes/PerformanceTest/PerformanceContainerTest.cpp
Classes/PhysicsTest/PhysicsTest.cpp
Classes/ReleasePoolTest/ReleasePoolTest.cpp
Classes/RenderTextureTest/RenderTextureTest.cpp
Classes/RotateWorldTest/RotateWorldTest.cpp
Classes/SceneTest/SceneTest.cpp

View File

@ -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_

View File

@ -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<Object>& obj) {
static_cast<Node*>( static_cast<Object*>(obj) )->getPosition();
});
#else
std::for_each(std::begin(children), std::end(children), [](Node* obj) {
obj->getPosition();
});
#endif
CC_PROFILER_STOP(this->profilerName());
}

View File

@ -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);
}

View File

@ -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__

View File

@ -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();} },

View File

@ -68,5 +68,6 @@
#include "DataVisitorTest/DataVisitorTest.h"
#include "ConfigurationTest/ConfigurationTest.h"
#include "PhysicsTest/PhysicsTest.h"
#include "ReleasePoolTest/ReleasePoolTest.h"
#endif

View File

@ -190,6 +190,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$
<ClCompile Include="..\Classes\PerformanceTest\PerformanceLabelTest.cpp" />
<ClCompile Include="..\Classes\PerformanceTest\PerformanceRendererTest.cpp" />
<ClCompile Include="..\Classes\PhysicsTest\PhysicsTest.cpp" />
<ClCompile Include="..\Classes\ReleasePoolTest\ReleasePoolTest.cpp" />
<ClCompile Include="..\Classes\ShaderTest\ShaderTest2.cpp" />
<ClCompile Include="..\Classes\SpineTest\SpineTest.cpp" />
<ClCompile Include="..\Classes\TexturePackerEncryptionTest\TextureAtlasEncryptionTest.cpp" />
@ -338,6 +339,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$
<ClInclude Include="..\Classes\PerformanceTest\PerformanceLabelTest.h" />
<ClInclude Include="..\Classes\PerformanceTest\PerformanceRendererTest.h" />
<ClInclude Include="..\Classes\PhysicsTest\PhysicsTest.h" />
<ClInclude Include="..\Classes\ReleasePoolTest\ReleasePoolTest.h" />
<ClInclude Include="..\Classes\ShaderTest\ShaderTest2.h" />
<ClInclude Include="..\Classes\SpineTest\SpineTest.h" />
<ClInclude Include="..\Classes\TexturePackerEncryptionTest\TextureAtlasEncryptionTest.h" />

View File

@ -307,6 +307,9 @@
<Filter Include="Classes\ExtensionsTest\CocoStudioSceneTest\TriggerCode">
<UniqueIdentifier>{5ff3af4e-0610-480b-b297-8f407e12f369}</UniqueIdentifier>
</Filter>
<Filter Include="Classes\ReleasePoolTest">
<UniqueIdentifier>{f71fab28-32be-45c9-a941-9a22b5a59e51}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="main.cpp">
@ -721,6 +724,9 @@
<ClCompile Include="..\Classes\PerformanceTest\PerformanceContainerTest.cpp">
<Filter>Classes\PerformanceTest</Filter>
</ClCompile>
<ClCompile Include="..\Classes\ReleasePoolTest\ReleasePoolTest.cpp">
<Filter>Classes\ReleasePoolTest</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="main.h">
@ -1333,5 +1339,8 @@
<ClInclude Include="..\Classes\PerformanceTest\PerformanceContainerTest.h">
<Filter>Classes\PerformanceTest</Filter>
</ClInclude>
<ClInclude Include="..\Classes\ReleasePoolTest\ReleasePoolTest.h">
<Filter>Classes\ReleasePoolTest</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@ -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()
{

View File

@ -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()
{

View File

@ -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()
{

View File

@ -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()
{

View File

@ -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()
{

View File

@ -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)

View File

@ -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)

View File

@ -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")

View File

@ -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)

View File

@ -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

View File

@ -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)

View File

@ -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)

View File

@ -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())

View File

@ -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)

View File

@ -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

View File

@ -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())

View File

@ -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

View File

@ -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)

@ -1 +1 @@
Subproject commit 6fc3372cdfdbf39dd20bdcf1f60eb779773d32d7
Subproject commit ad6f6c781687b0dd471c4df53c0ba5925e43894d

View File

@ -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

View File

@ -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

View File

@ -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
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

View File

@ -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

View File

@ -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

View File

@ -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