Merge pull request #3425 from dumganhar/iss2488-new-label-sample

Iss2488: Merge PR https://github.com/cocos2d/cocos2d-x/pull/3422
This commit is contained in:
James Chen 2013-08-15 07:16:48 -07:00
commit 9ab671fb03
47 changed files with 2750 additions and 3312 deletions

View File

@ -1 +1 @@
1feddf59d7fbc2b063a496bbf4a4770d0ac4435e
b347c177e552f5a7b345253c78b21dad031a9d8a

View File

@ -65,18 +65,14 @@ label_nodes/CCFont.cpp \
label_nodes/CCFontAtlas.cpp \
label_nodes/CCFontAtlasCache.cpp \
label_nodes/CCFontAtlasFactory.cpp \
label_nodes/CCFontCache.cpp \
label_nodes/CCFontDefinition.cpp \
label_nodes/CCFontFNT.cpp \
label_nodes/CCFontFreeType.cpp \
label_nodes/CCFontRenderFreeType.cpp \
label_nodes/CCLabel.cpp \
label_nodes/CCLabelAtlas.cpp \
label_nodes/CCLabelBMFont.cpp \
label_nodes/CCLabelTTF.cpp \
label_nodes/CCLabelTextFormatter.cpp \
label_nodes/CCStringBMFont.cpp \
label_nodes/CCStringTTF.cpp \
label_nodes/CCTextImage.cpp \
layers_scenes_transitions_nodes/CCLayer.cpp \
layers_scenes_transitions_nodes/CCScene.cpp \

View File

@ -99,8 +99,7 @@ THE SOFTWARE.
#include "label_nodes/CCLabelAtlas.h"
#include "label_nodes/CCLabelTTF.h"
#include "label_nodes/CCLabelBMFont.h"
#include "label_nodes/CCStringBMFont.h"
#include "label_nodes/CCStringTTF.h"
#include "label_nodes/CCLabel.h"
// layers_scenes_transitions_nodes
#include "layers_scenes_transitions_nodes/CCLayer.h"

View File

@ -25,8 +25,88 @@
#include "CCFont.h"
#include "support/ccUTF8.h"
#include "CCFontFNT.h"
#include "CCFontFreeType.h"
NS_CC_BEGIN
const char * Font::_glyphASCII = "\"!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþ ";
const char * Font::_glyphNEHE = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ";
Font::Font() : _usedGlyphs(GlyphCollection::ASCII), _customGlyphs(nullptr)
{
}
const char * Font::getGlyphCollection(GlyphCollection glyphs)
{
switch (glyphs)
{
case GlyphCollection::NEHE:
return _glyphNEHE;
break;
case GlyphCollection::ASCII:
return _glyphASCII;
break;
default:
return 0;
break;
}
}
void Font::setCurrentGlyphCollection(GlyphCollection glyphs, const char *customGlyphs)
{
if (_customGlyphs)
delete [] _customGlyphs;
switch (glyphs)
{
case GlyphCollection::NEHE:
_customGlyphs = 0;
break;
case GlyphCollection::ASCII:
_customGlyphs = 0;
break;
default:
int lenght = strlen(customGlyphs);
_customGlyphs = new char [lenght + 2];
memcpy(_customGlyphs, customGlyphs, lenght);
_customGlyphs[lenght] = 0;
_customGlyphs[lenght+1] = 0;
break;
}
}
const char * Font::getCurrentGlyphCollection()
{
if (_customGlyphs)
{
return _customGlyphs;
}
else
{
return getGlyphCollection(_usedGlyphs);
}
}
Font* Font::createWithTTF(const char* fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs)
{
return FontFreeType::create(fntName, fontSize, glyphs, customGlyphs);
}
Font* Font::createWithFNT(const char* fntFilePath)
{
return FontFNT::create(fntFilePath);
}
unsigned short int * Font::getUTF16Text(const char *pText, int &outNumLetters)
{
unsigned short* utf16String = cc_utf8_to_utf16(pText);

View File

@ -26,31 +26,54 @@
#define _CCFont_h_
#include <string>
#include "cocos2d.h"
#include "CCLabel.h"
NS_CC_BEGIN
// fwd
class GlyphDef;
class FontAtlas;
class CC_DLL Font : public Object
{
public:
// create the font
static Font* createWithTTF(const char* fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs);
static Font* createWithFNT(const char* fntFilePath);
virtual ~Font() {}
virtual FontAtlas *createFontAtlas() = 0;
virtual Size * getAdvancesForTextUTF16(unsigned short *pText, int &outNumLetters) = 0;
virtual const char * getCurrentGlyphCollection();
virtual bool createFontObject(const std::string &fontName, int fontSize) { return false; }
virtual int getLetterPadding() { return 0; }
virtual unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) { return 0; }
virtual int getFontMaxHeight() { return 0; }
virtual GlyphDef * getGlyphDefintionsForText(const char *pText, int &outNumGlyphs, bool UTF16text = false) { return 0; }
virtual int getFontMaxHeight() { return 0; }
virtual Rect getRectForChar(unsigned short theChar);
virtual unsigned short int * getUTF16Text(const char *pText, int &outNumLetters);
virtual int getUTF16TextLenght(unsigned short int *pText);
virtual unsigned short int * getUTF16Text(const char *pText, int &outNumLetters);
virtual unsigned short int * trimUTF16Text(unsigned short int *pText, int newBegin, int newEnd);
protected:
Font();
virtual ~Font() {}
void setCurrentGlyphCollection(GlyphCollection glyphs, const char *customGlyphs = 0);
const char * getGlyphCollection(GlyphCollection glyphs);
private:
GlyphCollection _usedGlyphs;
char * _customGlyphs;
static const char * _glyphASCII;
static const char * _glyphNEHE;
};
NS_CC_END

View File

@ -27,11 +27,8 @@ void FontAtlas::relaseTextures()
{
for( auto &item: _atlasTextures)
{
if ( item.second )
item.second->release();
item.second->release();
}
_atlasTextures.clear();
}
void FontAtlas::addLetterDefinition(const FontLetterDefinition &letterDefinition)
@ -39,7 +36,7 @@ void FontAtlas::addLetterDefinition(const FontLetterDefinition &letterDefinition
_fontLetterDefinitions[letterDefinition.letteCharUTF16] = letterDefinition;
}
bool FontAtlas::getLetterDefinitionForChar(unsigned short letteCharUTF16, FontLetterDefinition &outDefinition) const
bool FontAtlas::getLetterDefinitionForChar(unsigned short letteCharUTF16, FontLetterDefinition &outDefinition)
{
auto outIterator = _fontLetterDefinitions.find(letteCharUTF16);
@ -60,12 +57,12 @@ void FontAtlas::addTexture(Texture2D &texture, int slot)
_atlasTextures[slot] = &texture;
}
Texture2D & FontAtlas::getTexture(int slot)
Texture2D & FontAtlas::getTexture(int slot)
{
return *(_atlasTextures[slot]);
}
float FontAtlas::getCommonLineHeight() const
float FontAtlas::getCommonLineHeight()
{
return _commonLineHeight;
}
@ -75,21 +72,9 @@ void FontAtlas::setCommonLineHeight(float newHeight)
_commonLineHeight = newHeight;
}
unsigned short int * FontAtlas::getUTF16Text(const char *pText, int &outNumLetters) const
{
unsigned short* utf16String = cc_utf8_to_utf16(pText);
if(!utf16String)
return 0;
outNumLetters = cc_wcslen(utf16String);
return utf16String;
}
Font & FontAtlas::getFont() const
Font & FontAtlas::getFont()
{
return _font;
}
NS_CC_END

View File

@ -24,11 +24,13 @@
#ifndef _CCFontAtlas_h_
#define _CCFontAtlas_h_
#include <map>
NS_CC_BEGIN
//fwd
class Font;
struct FontLetterDefinition
{
unsigned short letteCharUTF16;
@ -47,20 +49,20 @@ struct FontLetterDefinition
class CC_DLL FontAtlas : public Object
{
public:
FontAtlas(Font &theFont);
virtual ~FontAtlas();
void addLetterDefinition(const FontLetterDefinition &letterDefinition);
bool getLetterDefinitionForChar(unsigned short letteCharUTF16, FontLetterDefinition &outDefinition) const;
void addTexture(Texture2D &texture, int slot);
Texture2D & getTexture(int slot);
bool getLetterDefinitionForChar(unsigned short letteCharUTF16, FontLetterDefinition &outDefinition);
void addTexture(Texture2D &texture, int slot);
float getCommonLineHeight();
void setCommonLineHeight(float newHeight);
float getCommonLineHeight() const;
unsigned short int * getUTF16Text(const char *pText, int &outNumLetters) const;
Font & getFont() const;
Texture2D & getTexture(int slot);
Font & getFont();
private:

View File

@ -30,24 +30,16 @@ NS_CC_BEGIN
std::map<std::string, FontAtlas *> FontAtlasCache::_atlasMap;
FontAtlas * FontAtlasCache::getFontAtlasTTF(const char *fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs)
{
std::string atlasName = generateFontName(fontFileName, size, glyphs);
FontAtlas *tempAtlas = _atlasMap[atlasName];
FontAtlas *tempAtlas = _atlasMap[atlasName];
if ( !tempAtlas )
{
tempAtlas = FontAtlasFactory::createAtlasFromTTF(fontFileName, size, glyphs, customGlyphs);
if (tempAtlas)
{
_atlasMap[atlasName] = tempAtlas;
}
else
{
return nullptr;
}
}
else
{
@ -65,15 +57,8 @@ FontAtlas * FontAtlasCache::getFontAtlasFNT(const char *fontFileName)
if ( !tempAtlas )
{
tempAtlas = FontAtlasFactory::createAtlasFromFNT(fontFileName);
if (tempAtlas)
{
_atlasMap[atlasName] = tempAtlas;
}
else
{
return nullptr;
}
}
else
{
@ -89,7 +74,6 @@ std::string FontAtlasCache::generateFontName(const char *fontFileName, int size,
switch (theGlyphs)
{
case GlyphCollection::DYNAMIC:
tempName.append("_DYNAMIC_");
break;
@ -110,9 +94,9 @@ std::string FontAtlasCache::generateFontName(const char *fontFileName, int size,
break;
}
// std::to_string is not supported on android, using std::stringstream instead.
std::stringstream ss;
ss << size;
// std::to_string is not supported on android, using std::stringstream instead.
return tempName.append(ss.str());
}
@ -120,7 +104,7 @@ bool FontAtlasCache::releaseFontAtlas(FontAtlas *atlas)
{
if (atlas)
{
for( auto &item: _atlasMap)
for( auto &item: _atlasMap )
{
if ( item.second == atlas )
{

View File

@ -40,7 +40,8 @@ public:
static FontAtlas * getFontAtlasTTF(const char *fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs = 0);
static FontAtlas * getFontAtlasFNT(const char *fontFileName);
static bool releaseFontAtlas(FontAtlas *atlas);
static bool releaseFontAtlas(FontAtlas *atlas);
private:

View File

@ -14,154 +14,29 @@
NS_CC_BEGIN
const char *FontAtlasFactory::glyphASCII = "\"!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþ ";
const char *FontAtlasFactory::glyphNEHE = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ";
FontAtlas * FontAtlasFactory::createAtlasFromTTF(const char* fntFilePath, int fontSize, GlyphCollection glyphs, const char *customGlyphs)
{
FontDefinitionTTF *def = 0;
if ( (glyphs == GlyphCollection::NEHE) || (glyphs == GlyphCollection::ASCII) )
if( glyphs == GlyphCollection::DYNAMIC )
{
def = FontDefinitionTTF::create(fntFilePath, fontSize, getGlyphCollection(glyphs));
}
else
{
if( glyphs == GlyphCollection::DYNAMIC )
{
log("ERROR: GlyphCollection::DYNAMIC is not supported yet!");
return nullptr;
}
else
{
if ( !customGlyphs )
{
log("ERROR: GlyphCollection::CUSTOM used but no input glyphs provided!");
return nullptr;
}
def = FontDefinitionTTF::create(fntFilePath, fontSize, customGlyphs);
}
}
if(!def)
log("ERROR: GlyphCollection::DYNAMIC is not supported yet!");
return nullptr;
}
// create the font atlas from the font definition
FontAtlas *tempAtlas = def->createFontAtlas();
// release the font definition, we don't need it anymore
def->release();
// return the atlas
return tempAtlas;
Font *font = Font::createWithTTF(fntFilePath, fontSize, glyphs, customGlyphs);
if (font)
return font->createFontAtlas();
else
return nullptr;
}
FontAtlas * FontAtlasFactory::createAtlasFromFNT(const char* fntFilePath)
{
CCBMFontConfiguration *newConf = FNTConfigLoadFile(fntFilePath);
Font *pFont = Font::createWithFNT(fntFilePath);
if (newConf)
return createFontAtlasFromFNTConfig(newConf);
if(pFont)
return pFont->createFontAtlas();
else
return 0;
}
const char * FontAtlasFactory::getGlyphCollection(GlyphCollection glyphs)
{
switch (glyphs)
{
case GlyphCollection::NEHE:
return glyphNEHE;
break;
case GlyphCollection::ASCII:
return glyphASCII;
break;
default:
return 0;
break;
}
}
FontAtlas * FontAtlasFactory::createFontAtlasFromFNTConfig(CCBMFontConfiguration *theConfig)
{
if (!theConfig)
return 0;
FontFNT *tempFont = new FontFNT(theConfig);
if (!tempFont)
return 0;
FontAtlas *tempAtlas = new FontAtlas(*tempFont);
if (!tempAtlas)
return 0;
// check that everything is fine with the BMFontCofniguration
if (!theConfig->_fontDefDictionary)
return 0;
int numGlyphs = theConfig->_characterSet->size();
if (!numGlyphs)
return 0;
if (theConfig->_commonHeight == 0)
return 0;
// commone height
tempAtlas->setCommonLineHeight(theConfig->_commonHeight);
ccBMFontDef fontDef;
tFontDefHashElement *current_element, *tmp;
// Purge uniform hash
HASH_ITER(hh, theConfig->_fontDefDictionary, current_element, tmp)
{
FontLetterDefinition tempDefinition;
fontDef = current_element->fontDef;
Rect tempRect;
tempRect = fontDef.rect;
tempRect = CC_RECT_PIXELS_TO_POINTS(tempRect);
tempDefinition.letteCharUTF16 = fontDef.charID;
tempDefinition.offsetX = fontDef.xOffset;
tempDefinition.offsetY = fontDef.yOffset;
tempDefinition.U = tempRect.origin.x;
tempDefinition.V = tempRect.origin.y;
tempDefinition.width = tempRect.size.width;
tempDefinition.height = tempRect.size.height;
//carloX: only one texture supported FOR NOW
tempDefinition.textureID = 0;
tempDefinition.anchorX = 0.5f;
tempDefinition.anchorY = 0.5f;
// add the new definition
tempAtlas->addLetterDefinition(tempDefinition);
}
// add the texture (only one texture for now)
Texture2D *tempTexture = TextureCache::getInstance()->addImage(theConfig->getAtlasName());
if (!tempTexture)
return 0;
// add the texture
tempAtlas->addTexture(*tempTexture, 0);
return tempAtlas;
return nullptr;
}
NS_CC_END

View File

@ -28,6 +28,7 @@
#include "cocos2d.h"
#include "CCFontAtlas.h"
NS_CC_BEGIN
class CC_DLL FontAtlasFactory
@ -39,15 +40,6 @@ public:
static FontAtlas * createAtlasFromFNT(const char* fntFilePath);
private:
static const char * getGlyphCollection(GlyphCollection glyphs);
// carloX: this needs to be moved somewhere else, but it's good enough for now
static FontAtlas * createFontAtlasFromFNTConfig(CCBMFontConfiguration *theConfig);
static const char *glyphASCII;
static const char *glyphNEHE;
};
NS_CC_END

View File

@ -27,19 +27,27 @@
NS_CC_BEGIN
const int FontDefinitionTTF::_DEFAUL_ATALS_TEXTURE_SIZE = 1024;
FontDefinitionTTF::FontDefinitionTTF():_textImages(0), _commonLineHeight(0)
{
}
FontDefinitionTTF* FontDefinitionTTF::create(const char *fontName, int fontSize, const char *letters, int textureSize )
FontDefinitionTTF* FontDefinitionTTF::create(Font *font, int textureSize)
{
if (textureSize == 0)
textureSize = _DEFAUL_ATALS_TEXTURE_SIZE;
FontDefinitionTTF *ret = new FontDefinitionTTF;
if(!ret)
return 0;
if ( ret->initDefinition( fontName, fontSize, letters, textureSize ) )
const char *pGlyph = font->getCurrentGlyphCollection();
if (!pGlyph)
return nullptr;
if ( ret->initDefinition(font, pGlyph, textureSize ) )
{
return ret;
}
@ -102,17 +110,15 @@ bool FontDefinitionTTF::prepareLetterDefinitions(TextFontPagesDef *pageDefs)
if (tempDef.validDefinition)
{
tempDef.letteCharUTF16 = currentGlyph.getUTF8Letter();
tempDef.width = letterWidth + currentGlyph.getPadding();
tempDef.height = (letterHeight - 1);
tempDef.U = (posXUV - 1);
tempDef.V = posYUV;
tempDef.offsetX = currentGlyph.getRect().origin.x;
tempDef.offsetY = currentGlyph.getRect().origin.y;
tempDef.textureID = cPages;
tempDef.commonLineHeight = currentGlyph.getCommonHeight();
tempDef.letteCharUTF16 = currentGlyph.getUTF8Letter();
tempDef.width = letterWidth + currentGlyph.getPadding();
tempDef.height = (letterHeight - 1);
tempDef.U = (posXUV - 1);
tempDef.V = posYUV;
tempDef.offsetX = currentGlyph.getRect().origin.x;
tempDef.offsetY = currentGlyph.getRect().origin.y;
tempDef.textureID = cPages;
tempDef.commonLineHeight = currentGlyph.getCommonHeight();
// take from pixels to points
tempDef.width = tempDef.width / CC_CONTENT_SCALE_FACTOR();
@ -125,15 +131,15 @@ bool FontDefinitionTTF::prepareLetterDefinitions(TextFontPagesDef *pageDefs)
}
else
{
tempDef.letteCharUTF16 = currentGlyph.getUTF8Letter();
tempDef.commonLineHeight = 0;
tempDef.width = 0;
tempDef.height = 0;
tempDef.U = 0;
tempDef.V = 0;
tempDef.offsetX = 0;
tempDef.offsetY = 0;
tempDef.textureID = 0;
tempDef.letteCharUTF16 = currentGlyph.getUTF8Letter();
tempDef.commonLineHeight = 0;
tempDef.width = 0;
tempDef.height = 0;
tempDef.U = 0;
tempDef.V = 0;
tempDef.offsetX = 0;
tempDef.offsetY = 0;
tempDef.textureID = 0;
}
@ -156,14 +162,14 @@ bool FontDefinitionTTF::prepareLetterDefinitions(TextFontPagesDef *pageDefs)
return true;
}
bool FontDefinitionTTF::initDefinition(const char *fontName, int fontSize, const char *letters, int textureSize)
bool FontDefinitionTTF::initDefinition(cocos2d::Font *font, const char *letters, int textureSize)
{
// preare texture/image stuff
_textImages = new TextImage();
if (!_textImages)
return false;
if (!_textImages->initWithString(letters, textureSize, textureSize, fontName, fontSize, true))
if (!_textImages->initWithString(letters, textureSize, textureSize, font, true))
{
delete _textImages;
_textImages = 0;
@ -182,50 +188,32 @@ void FontDefinitionTTF::addLetterDefinition(FontLetterDefinition &defToAdd)
}
}
FontLetterDefinition & FontDefinitionTTF::getLetterDefinition(unsigned short int theLetter)
{
return _fontLettersDefinitionUTF16[theLetter];
}
Texture2D * FontDefinitionTTF::getTexture(int index)
{
TextFontPagesDef *pPages = _textImages->getPages();
if (!pPages)
return nullptr;
return pPages->getPageAt(index)->getPageTexture();
}
int FontDefinitionTTF::getNumTextures()
{
TextFontPagesDef *pPages = _textImages->getPages();
if (pPages)
{
return pPages->getNumPages();
}
return 0;
}
FontAtlas * FontDefinitionTTF::createFontAtlas()
{
FontAtlas *retAtlas = new FontAtlas( *_textImages->getFont() );
int numTextures = 0;
TextFontPagesDef *pPages = _textImages->getPages();
if (pPages)
numTextures = pPages->getNumPages();
else
return nullptr;
if (!numTextures)
return nullptr;
FontAtlas *retAtlas = new FontAtlas(*_textImages->getFont());
if (!retAtlas)
return 0;
// add all the textures
int numTextures = getNumTextures();
if (!numTextures)
return 0;
for (int c = 0; c<numTextures; ++c)
retAtlas->addTexture(*getTexture(c), c);
for (int c = 0; c < numTextures; ++c)
{
TextFontPagesDef *pPages = _textImages->getPages();
retAtlas->addTexture(*(pPages->getPageAt(c)->getPageTexture()), c);
}
// set the common line height
retAtlas->setCommonLineHeight(getCommonLineHeight() * 0.8);
retAtlas->setCommonLineHeight(_commonLineHeight * 0.8);
for( auto &item: _fontLettersDefinitionUTF16 )
{

View File

@ -31,20 +31,13 @@
NS_CC_BEGIN
#define DEFAULT_ATLAS_TEXTURE_SIZE 1024
/**
*/
class CC_DLL FontDefinitionTTF : public Object
{
public:
static FontDefinitionTTF* create(const char *fontName, int fontSize, const char *letters, int textureSize = DEFAULT_ATLAS_TEXTURE_SIZE);
FontLetterDefinition & getLetterDefinition(unsigned short int theLetter);
Texture2D * getTexture(int index);
int getNumTextures();
Font * getFont() { return _textImages->getFont(); }
float getCommonLineHeight() { return _commonLineHeight; }
static FontDefinitionTTF* create(Font *font, int textureSize = 0);
FontAtlas * createFontAtlas();
private:
@ -52,13 +45,14 @@ private:
FontDefinitionTTF();
~FontDefinitionTTF();
bool initDefinition(const char *fontName, int fontSize, const char *letters, int textureSize);
bool initDefinition(Font *font, const char *letters, int textureSize);
bool prepareLetterDefinitions(TextFontPagesDef *pageDefs);
void addLetterDefinition(FontLetterDefinition &defToAdd);
TextImage * _textImages;
std::map<unsigned short, FontLetterDefinition> _fontLettersDefinitionUTF16;
float _commonLineHeight;
static const int _DEFAUL_ATALS_TEXTURE_SIZE;
};

View File

@ -7,10 +7,34 @@
//
#include "CCFontFNT.h"
#include "CCFontAtlas.h"
NS_CC_BEGIN
FontFNT * FontFNT::create(const char* fntFilePath)
{
CCBMFontConfiguration *newConf = FNTConfigLoadFile(fntFilePath);
if (!newConf)
return nullptr;
// add the texture
Texture2D *tempTexture = TextureCache::getInstance()->addImage(newConf->getAtlasName());
if ( !tempTexture )
{
delete newConf;
return nullptr;
}
FontFNT *tempFont = new FontFNT(newConf);
if (!tempFont)
{
delete newConf;
return nullptr;
}
return tempFont;
}
FontFNT::~FontFNT()
{
@ -100,4 +124,75 @@ Rect FontFNT::getRectForChar(unsigned short theChar)
return getRectForCharInternal(theChar);
}
FontAtlas * FontFNT::createFontAtlas()
{
FontAtlas *tempAtlas = new FontAtlas(*this);
if (!tempAtlas)
return nullptr;
// check that everything is fine with the BMFontCofniguration
if (!_configuration->_fontDefDictionary)
return nullptr;
int numGlyphs = _configuration->_characterSet->size();
if (!numGlyphs)
return nullptr;
if (_configuration->_commonHeight == 0)
return nullptr;
// commone height
tempAtlas->setCommonLineHeight(_configuration->_commonHeight);
ccBMFontDef fontDef;
tFontDefHashElement *current_element, *tmp;
// Purge uniform hash
HASH_ITER(hh, _configuration->_fontDefDictionary, current_element, tmp)
{
FontLetterDefinition tempDefinition;
fontDef = current_element->fontDef;
Rect tempRect;
tempRect = fontDef.rect;
tempRect = CC_RECT_PIXELS_TO_POINTS(tempRect);
tempDefinition.letteCharUTF16 = fontDef.charID;
tempDefinition.offsetX = fontDef.xOffset;
tempDefinition.offsetY = fontDef.yOffset;
tempDefinition.U = tempRect.origin.x;
tempDefinition.V = tempRect.origin.y;
tempDefinition.width = tempRect.size.width;
tempDefinition.height = tempRect.size.height;
//carloX: only one texture supported FOR NOW
tempDefinition.textureID = 0;
tempDefinition.anchorX = 0.5f;
tempDefinition.anchorY = 0.5f;
// add the new definition
tempAtlas->addLetterDefinition(tempDefinition);
}
// add the texture (only one texture for now)
Texture2D *tempTexture = TextureCache::getInstance()->addImage(_configuration->getAtlasName());
if (!tempTexture)
return 0;
// add the texture
tempAtlas->addTexture(*tempTexture, 0);
// done
return tempAtlas;
}
NS_CC_END

View File

@ -35,10 +35,16 @@ class FontFNT : public Font
public:
static FontFNT * create(const char* fntFilePath);
virtual Size* getAdvancesForTextUTF16(unsigned short *pText, int &outNumLetters) override;
virtual Rect getRectForChar(unsigned short theChar) override;
virtual FontAtlas *createFontAtlas() override;
protected:
FontFNT(CCBMFontConfiguration *theContfig) : _configuration(theContfig) {}
virtual ~FontFNT();
virtual Size* getAdvancesForTextUTF16(unsigned short *pText, int &outNumLetters);
virtual Rect getRectForChar(unsigned short theChar);
private:

View File

@ -23,10 +23,12 @@
****************************************************************************/
#include <stdio.h>
#include "cocos2d.h"
#include "support/ccUTF8.h"
#include "CCFontFreeType.h"
#include "CCTextImage.h"
#include "CCFont.h"
#include "CCFontDefinition.h"
NS_CC_BEGIN
@ -34,7 +36,29 @@ NS_CC_BEGIN
FT_Library FontFreeType::_FTlibrary;
bool FontFreeType::_FTInitialized = false;
FontFreeType * FontFreeType::create(const std::string &fontName, int fontSize, GlyphCollection glyphs, const char *customGlyphs)
{
if( glyphs == GlyphCollection::DYNAMIC )
{
log("ERROR: GlyphCollection::DYNAMIC is not supported yet!");
return nullptr;
}
FontFreeType *tempFont = new FontFreeType();
if (!tempFont)
return nullptr;
tempFont->setCurrentGlyphCollection(glyphs, customGlyphs);
if( !tempFont->createFontObject(fontName, fontSize))
{
delete tempFont;
return nullptr;
}
return tempFont;
}
bool FontFreeType::initFreeType()
{
@ -111,6 +135,21 @@ FontFreeType::~FontFreeType()
// TO DO
}
FontAtlas * FontFreeType::createFontAtlas()
{
FontDefinitionTTF *def = 0;
def = FontDefinitionTTF::create(this);
if(!def)
return nullptr;
FontAtlas *atlas = def->createFontAtlas();
// release the font definition, we don't need it anymore
def->release();
return atlas;
}
bool FontFreeType::getBBOXFotChar(unsigned short theChar, Rect &outRect)
{
if (!_fontRef)
@ -276,7 +315,7 @@ int FontFreeType::getHorizontalKerningForChars(unsigned short firstChar, unsign
if (!_fontRef)
return 0;
bool hasKerning = FT_HAS_KERNING( _fontRef );
bool hasKerning = FT_HAS_KERNING( _fontRef ) != 0;
if (!hasKerning)
return 0;

View File

@ -25,9 +25,11 @@
#ifndef _FontFreetype_h_
#define _FontFreetype_h_
#include "CCFont.h"
#include <string>
#include <ft2build.h>
#include "CCFont.h"
#include FT_FREETYPE_H
NS_CC_BEGIN
@ -36,19 +38,24 @@ class CC_DLL FontFreeType : public Font
{
public:
static FontFreeType * create(const std::string &fontName, int fontSize, GlyphCollection glyphs, const char *customGlyphs);
virtual FontAtlas * createFontAtlas() override;
virtual Size * getAdvancesForTextUTF16(unsigned short *pText, int &outNumLetters) override;
virtual GlyphDef * getGlyphDefintionsForText(const char *pText, int &outNumGlyphs, bool UTF16text = false) override;
unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) override;
virtual int getFontMaxHeight() override;
virtual int getLetterPadding() override;
protected:
FontFreeType();
virtual ~FontFreeType();
virtual Size * getAdvancesForTextUTF16(unsigned short *pText, int &outNumLetters);
virtual bool createFontObject(const std::string &fontName, int fontSize);
virtual GlyphDef * getGlyphDefintionsForText(const char *pText, int &outNumGlyphs, bool UTF16text = false);
unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight);
virtual int getFontMaxHeight();
virtual int getLetterPadding();
bool createFontObject(const std::string &fontName, int fontSize);
private:
bool initFreeType();
void shutdownFreeType();
FT_Library getFTLibrary();
@ -60,10 +67,8 @@ private:
static FT_Library _FTlibrary;
static bool _FTInitialized;
FT_Face _fontRef;
const int _letterPadding;
std::string _fontName;
};

View File

@ -1,51 +0,0 @@
/****************************************************************************
Copyright (c) 2013 Zynga 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 _FontRender_h_
#define _FontRender_h_
NS_CC_BEGIN
// FWD
class Font;
class TextPageDef;
class CC_DLL FontRender
{
public:
FontRender(Font *pFont) { _font = pFont; }
virtual ~FontRender() {}
virtual unsigned char * preparePageGlyphData(TextPageDef *thePage) = 0;
protected:
Font * _font;
};
NS_CC_END
#endif

View File

@ -1,138 +0,0 @@
/****************************************************************************
Copyright (c) 2013 Zynga 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 "cocos2d.h"
#include "CCTextImage.h"
#include "CCFontRenderFreeType.h"
#include <ft2build.h>
#include FT_FREETYPE_H
//#define _DEBUG_FONTS_
#ifdef _DEBUG_FONTS_
#include "CCImage.h"
#endif
NS_CC_BEGIN
bool FontRenderFreeType::renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize)
{
if (!_font)
return false;
unsigned char *sourceBitmap = 0;
int sourceWidth = 0;
int sourceHeight = 0;
// get the glyph's bitmap
sourceBitmap = _font->getGlyphBitmap(charToRender, sourceWidth, sourceHeight);
if(!sourceBitmap)
return false;
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
int iTemp = cTemp << 24 | cTemp << 16 | cTemp << 8 | cTemp;
*(int*) &destMemory[(iX + ( iY * destSize ) ) * 4] = iTemp;
iX += 1;
}
iX = posX;
iY += 1;
}
//everything good
return true;
}
unsigned char * FontRenderFreeType::preparePageGlyphData(TextPageDef *thePage)
{
if (!thePage)
return 0;
if (!_font)
return 0;
if (thePage->getNumLines() == 0)
return NULL;
int pageWidth = thePage->getWidth();
int pageHeight = thePage->getHeight();
// prepare memory and clean to 0
int sizeInBytes = (pageWidth * pageHeight * 4);
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 *pCurrentLine = thePage->getLineAt(c);
float origX = _font->getLetterPadding();
float origY = pCurrentLine->getY();
int numGlyphToRender = pCurrentLine->getNumGlyph();
for (int cglyph = 0; cglyph < numGlyphToRender; ++cglyph)
{
GlyphDef currGlyph = pCurrentLine->getGlyphAt(cglyph);
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,"carlottone%d", counter);
++counter;
Image *pImage = new Image;
pImage->initWithRawData(data, (pageWidth * pageWidth * 4), 1024, 1024, 8, false);
pImage->saveToFile(outFilename);
#endif
// we are done here
return data;
}
NS_CC_END

View File

@ -1,48 +0,0 @@
/****************************************************************************
Copyright (c) 2013 Zynga 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 _FontRenderFreeType_h_
#define _FontRenderFreeType_h_
#include "CCFontRender.h"
NS_CC_BEGIN
class CC_DLL FontRenderFreeType : public FontRender
{
public:
FontRenderFreeType(Font *pFont): FontRender(pFont) {}
virtual ~FontRenderFreeType() {}
virtual unsigned char * preparePageGlyphData(TextPageDef *thePage);
private:
bool renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize);
};
NS_CC_END
#endif

View File

@ -23,66 +23,747 @@
****************************************************************************/
#include "CCLabel.h"
#include "CCStringBMFont.h"
#include "CCStringTTF.h"
#include "CCFontDefinition.h"
#include "CCFontCache.h"
#include "CCFontAtlasCache.h"
#include "CCLabelTextFormatter.h"
NS_CC_BEGIN
Label* Label::createWithTTF( const char* label, const char* fntFilePath, int fontSize, GlyphCollection glyphs, int lineSize, const char *customGlyphs )
Label* Label::createWithTTF( const char* label, const char* fontFilePath, int fontSize, int lineSize, TextHAlignment alignment, GlyphCollection glyphs, const char *customGlyphs )
{
FontAtlas *tempAtlas = FontAtlasCache::getFontAtlasTTF(fntFilePath, fontSize, glyphs, customGlyphs);
FontAtlas *tempAtlas = FontAtlasCache::getFontAtlasTTF(fontFilePath, fontSize, glyphs, customGlyphs);
if (!tempAtlas)
return nullptr;
// create the actual label
StringTTF* templabel = StringTTF::create(tempAtlas, TextHAlignment::CENTER, lineSize);
Label* templabel = Label::createWithAtlas(tempAtlas, alignment, lineSize);
if (templabel)
{
templabel->setText(label, lineSize, TextHAlignment::CENTER, false);
templabel->setText(label, lineSize, alignment, false);
return templabel;
}
return nullptr;
return 0;
}
Label* Label::createWithBMFont( const char* label, const char* bmfontFilePath, int lineSize)
Label* Label::createWithBMFont( const char* label, const char* bmfontFilePath, TextHAlignment alignment, int lineSize)
{
FontAtlas *tempAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath);
if (!tempAtlas)
return 0;
StringTTF* templabel = StringTTF::create(tempAtlas, TextHAlignment::CENTER, lineSize);
Label* templabel = Label::createWithAtlas(tempAtlas, alignment, lineSize);
if (templabel)
{
templabel->setText(label, lineSize, TextHAlignment::CENTER, false);
templabel->setText(label, lineSize, alignment, false);
return templabel;
}
else
{
return 0;
}
return 0;
}
Label* Label::createWithAtlas(FontAtlas *pAtlas, TextHAlignment alignment, int lineSize)
{
Label *ret = new Label(pAtlas, alignment);
if (!ret)
return 0;
if( ret->init() )
{
ret->autorelease();
return ret;
}
else
{
delete ret;
return 0;
}
return ret;
}
Label::Label(FontAtlas *pAtlas, TextHAlignment alignment): _currentUTF8String(0),
_originalUTF8String(0),
_fontAtlas(pAtlas),
_alignment(alignment),
_lineBreakWithoutSpaces(false),
_advances(0),
_displayedColor(Color3B::WHITE),
_realColor(Color3B::WHITE),
_cascadeColorEnabled(true),
_cascadeOpacityEnabled(true),
_displayedOpacity(255),
_realOpacity(255),
_isOpacityModifyRGB(false)
{
}
Label::~Label()
{
if (_currentUTF8String)
delete [] _currentUTF8String;
if (_advances)
delete [] _advances;
if (_fontAtlas)
FontAtlasCache::releaseFontAtlas(_fontAtlas);
}
bool Label::init()
{
return true;
}
void Label::setString(const char *stringToRender)
{
setText(stringToRender, _width, TextHAlignment::CENTER, false);
}
bool Label::setText(const char *stringToRender, float lineWidth, TextHAlignment alignment, bool lineBreakWithoutSpaces)
{
if (!_fontAtlas)
return false;
// carloX
// reset the string
resetCurrentString();
_width = lineWidth;
_alignment = alignment;
_lineBreakWithoutSpaces = lineBreakWithoutSpaces;
// release all the sprites
moveAllSpritesToCache();
// store locally common line height
_commonLineHeight = _fontAtlas->getCommonLineHeight();
if (_commonLineHeight <= 0)
return false;
int numLetter = 0;
unsigned short* utf16String = cc_utf8_to_utf16(stringToRender);
if(!utf16String)
return false;
numLetter = cc_wcslen(utf16String);
SpriteBatchNode::initWithTexture(&_fontAtlas->getTexture(0), numLetter);
_cascadeColorEnabled = true;
//
setCurrentString(utf16String);
setOriginalString(utf16String);
// align text
alignText();
// done here
return true;
}
void Label::setAlignment(TextHAlignment alignment)
{
// store the new alignment
if (alignment != _alignment)
{
// store
_alignment = alignment;
// reset the string
resetCurrentString();
// need to align text again
alignText();
}
}
void Label::setWidth(float width)
{
if (width != _width)
{
// store
_width = width;
// reset the string
resetCurrentString();
// need to align text again
alignText();
}
}
void Label::setLineBreakWithoutSpace(bool breakWithoutSpace)
{
if (breakWithoutSpace != _lineBreakWithoutSpaces)
{
// store
_lineBreakWithoutSpaces = breakWithoutSpace;
// need to align text again
alignText();
}
}
void Label::setScale(float scale)
{
Node::setScale(scale);
alignText();
}
void Label::setScaleX(float scaleX)
{
Node::setScaleX(scaleX);
alignText();
}
void Label::setScaleY(float scaleY)
{
Node::setScaleY(scaleY);
alignText();
}
void Label::alignText()
{
hideAllLetters();
LabelTextFormatter::createStringSprites(this);
if( LabelTextFormatter::multilineText(this) )
{
hideAllLetters();
LabelTextFormatter::createStringSprites(this);
}
LabelTextFormatter::alignText(this);
}
void Label::hideAllLetters()
{
Object* Obj = NULL;
CCARRAY_FOREACH(&_spriteArray, Obj)
{
((Sprite *)Obj)->setVisible(false);
}
CCARRAY_FOREACH(&_spriteArrayCache, Obj)
{
((Sprite *)Obj)->setVisible(false);
}
}
bool Label::computeAdvancesForString(unsigned short int *stringToRender)
{
if (_advances)
{
delete [] _advances;
_advances = 0;
}
Font &theFont = _fontAtlas->getFont();
int letterCount = 0;
_advances = theFont.getAdvancesForTextUTF16(stringToRender, letterCount);
if(!_advances)
return false;
else
return true;
}
bool Label::setOriginalString(unsigned short *stringToSet)
{
if (_originalUTF8String)
{
delete [] _originalUTF8String;
_originalUTF8String = 0;
}
int newStringLenght = cc_wcslen(stringToSet);
_originalUTF8String = new unsigned short int [newStringLenght + 1];
memset(_originalUTF8String, 0, (newStringLenght + 1) * 2);
memcpy(_originalUTF8String, stringToSet, (newStringLenght * 2));
_originalUTF8String[newStringLenght] = 0;
return true;
}
bool Label::setCurrentString(unsigned short *stringToSet)
{
// set the new string
if (_currentUTF8String)
{
delete [] _currentUTF8String;
_currentUTF8String = 0;
}
//
_currentUTF8String = stringToSet;
// compute the advances
return computeAdvancesForString(stringToSet);
}
void Label::resetCurrentString()
{
if ((!_currentUTF8String) && (!_originalUTF8String))
return;
// set the new string
if (_currentUTF8String)
{
delete [] _currentUTF8String;
_currentUTF8String = 0;
}
int stringLenght = cc_wcslen(_originalUTF8String);
_currentUTF8String = new unsigned short int [stringLenght + 1];
memcpy(_currentUTF8String, _originalUTF8String, stringLenght * 2);
_currentUTF8String[stringLenght] = 0;
}
Sprite * Label::createNewSpriteFromLetterDefinition(FontLetterDefinition &theDefinition, Texture2D *theTexture)
{
Rect uvRect;
uvRect.size.height = theDefinition.height;
uvRect.size.width = theDefinition.width;
uvRect.origin.x = theDefinition.U;
uvRect.origin.y = theDefinition.V;
SpriteFrame *pFrame = SpriteFrame::createWithTexture(theTexture, uvRect);
Sprite *tempSprite = getSprite();
if (!tempSprite)
return 0;
tempSprite->initWithSpriteFrame(pFrame);
tempSprite->setAnchorPoint(Point(theDefinition.anchorX, theDefinition.anchorY));
tempSprite->setBatchNode(this);
// Apply label properties
tempSprite->setOpacityModifyRGB(_isOpacityModifyRGB);
// Color MUST be set before opacity, since opacity might change color if OpacityModifyRGB is on
tempSprite->updateDisplayedColor(_displayedColor);
tempSprite->updateDisplayedOpacity(_displayedOpacity);
return tempSprite;
}
Sprite * Label::updateSpriteWithLetterDefinition(Sprite *spriteToUpdate, FontLetterDefinition &theDefinition, Texture2D *theTexture)
{
if (!spriteToUpdate)
{
return 0;
}
else
{
Rect uvRect;
uvRect.size.height = theDefinition.height;
uvRect.size.width = theDefinition.width;
uvRect.origin.x = theDefinition.U;
uvRect.origin.y = theDefinition.V;
SpriteFrame *frame = SpriteFrame::createWithTexture(theTexture, uvRect);
if (frame)
{
spriteToUpdate->setTexture(theTexture);
spriteToUpdate->setDisplayFrame(frame);
spriteToUpdate->setAnchorPoint(Point(theDefinition.anchorX, theDefinition.anchorY));
spriteToUpdate->setBatchNode(this);
}
return spriteToUpdate;
}
}
Sprite * Label::getSpriteForLetter(unsigned short int newLetter)
{
if (!_fontAtlas)
return 0;
FontLetterDefinition tempDefinition;
bool validDefinition = _fontAtlas->getLetterDefinitionForChar(newLetter, tempDefinition);
if (validDefinition)
{
Sprite *newSprite = createNewSpriteFromLetterDefinition(tempDefinition, &_fontAtlas->getTexture(tempDefinition.textureID) );
this->addChild(newSprite);
return newSprite;
}
else
{
return 0;
}
}
Label::Label()
Sprite * Label::updateSpriteForLetter(Sprite *spriteToUpdate, unsigned short int newLetter)
{
if (!spriteToUpdate || !_fontAtlas)
return 0;
else
{
FontLetterDefinition tempDefinition;
bool validDefinition = _fontAtlas->getLetterDefinitionForChar(newLetter, tempDefinition);
if (validDefinition)
{
Sprite *pNewSprite = updateSpriteWithLetterDefinition(spriteToUpdate, tempDefinition, &_fontAtlas->getTexture(tempDefinition.textureID) );
return pNewSprite;
}
else
{
return 0;
}
}
}
Label::~Label()
void Label::moveAllSpritesToCache()
{
Object* pObj = NULL;
CCARRAY_FOREACH(&_spriteArray, pObj)
{
((Sprite *)pObj)->removeFromParent();
_spriteArrayCache.addObject(pObj);
}
_spriteArray.removeAllObjects();
}
Sprite * Label::getSprite()
{
if (_spriteArrayCache.count())
{
Sprite *retSprite = (Sprite *) _spriteArrayCache.lastObject();
_spriteArrayCache.removeLastObject();
return retSprite;
}
else
{
Sprite *retSprite = new Sprite;
return retSprite;
}
}
///// PROTOCOL STUFF
Sprite * Label::getSpriteChild(int ID)
{
Object* pObj = NULL;
CCARRAY_FOREACH(&_spriteArray, pObj)
{
Sprite *pSprite = (Sprite *)pObj;
if ( pSprite->getTag() == ID)
{
return pSprite;
}
}
return 0;
}
Array * Label::getChildrenLetters()
{
return &_spriteArray;
}
Sprite * Label::getSpriteForChar(unsigned short int theChar, int spriteIndexHint)
{
// ret sprite
Sprite *retSprite = 0;
// look for already existing sprites
retSprite = getSpriteChild(spriteIndexHint);
if (!retSprite)
{
retSprite = getSpriteForLetter(theChar);
if (!retSprite)
return 0;
if (retSprite)
retSprite->setTag(spriteIndexHint);
_spriteArray.addObject(retSprite);
}
// the sprite is now visible
retSprite->setVisible(true);
// set the right texture letter to the sprite
updateSpriteForLetter(retSprite, theChar);
// we are done here
return retSprite;
}
float Label::getLetterPosXLeft( Sprite* sp )
{
float scaleX = _scaleX;
return sp->getPosition().x * scaleX - (sp->getContentSize().width * scaleX * sp->getAnchorPoint().x);
}
float Label::getLetterPosXRight( Sprite* sp )
{
float scaleX = _scaleX;
return sp->getPosition().x * scaleX + (sp->getContentSize().width * scaleX * sp->getAnchorPoint().x);
}
int Label::getCommonLineHeight()
{
return _commonLineHeight;
}
int Label::getKerningForCharsPair(unsigned short first, unsigned short second)
{
return 0;
}
int Label::getXOffsetForChar(unsigned short c)
{
FontLetterDefinition tempDefinition;
bool validDefinition = _fontAtlas->getLetterDefinitionForChar(c, tempDefinition);
if (!validDefinition)
return -1;
return (tempDefinition.offsetX);
}
int Label::getYOffsetForChar(unsigned short c)
{
FontLetterDefinition tempDefinition;
bool validDefinition = _fontAtlas->getLetterDefinitionForChar(c, tempDefinition);
if (!validDefinition)
return -1;
return (tempDefinition.offsetY);
}
int Label::getAdvanceForChar(unsigned short c, int hintPositionInString)
{
if (_advances)
{
// not that advance contains the X offset already
FontLetterDefinition tempDefinition;
bool validDefinition = _fontAtlas->getLetterDefinitionForChar(c, tempDefinition);
if (!validDefinition)
return -1;
return (_advances[hintPositionInString].width);
}
else
{
return -1;
}
}
Rect Label::getRectForChar(unsigned short c)
{
return _fontAtlas->getFont().getRectForChar(c);
}
// string related stuff
int Label::getStringNumLines()
{
int quantityOfLines = 1;
unsigned int stringLen = _currentUTF8String ? cc_wcslen(_currentUTF8String) : 0;
if (stringLen == 0)
return (-1);
// count number of lines
for (unsigned int i = 0; i < stringLen - 1; ++i)
{
unsigned short c = _currentUTF8String[i];
if (c == '\n')
{
quantityOfLines++;
}
}
return quantityOfLines;
}
int Label::getStringLenght()
{
return _currentUTF8String ? cc_wcslen(_currentUTF8String) : 0;
}
unsigned short Label::getCharAtStringPosition(int position)
{
return _currentUTF8String[position];
}
unsigned short * Label::getUTF8String()
{
return _currentUTF8String;
}
void Label::assignNewUTF8String(unsigned short *newString)
{
setCurrentString(newString);
}
TextHAlignment Label::getTextAlignment()
{
return _alignment;
}
// label related stuff
float Label::getMaxLineWidth()
{
return _width;
}
bool Label::breakLineWithoutSpace()
{
return _lineBreakWithoutSpaces;
}
Size Label::getLabelContentSize()
{
return getContentSize();
}
void Label::setLabelContentSize(const Size &newSize)
{
setContentSize(newSize);
}
// TESTING STUFF THAT NEEDS TO GO ////////////////////////////////////////////////////////////////
Label* Label::createWithBMFontOLD( const char* label, const char* bmfontFilePath, int lineSize)
// RGBA protocol
bool Label::isOpacityModifyRGB() const
{
return StringBMFont::create(label, bmfontFilePath, lineSize);
return _isOpacityModifyRGB;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
void Label::setOpacityModifyRGB(bool isOpacityModifyRGB)
{
_isOpacityModifyRGB = isOpacityModifyRGB;
if (_children && _children->count() != 0)
{
Object* child;
CCARRAY_FOREACH(_children, child)
{
Node* pNode = static_cast<Node*>( child );
if (pNode)
{
RGBAProtocol *pRGBAProtocol = dynamic_cast<RGBAProtocol*>(pNode);
if (pRGBAProtocol)
{
pRGBAProtocol->setOpacityModifyRGB(_isOpacityModifyRGB);
}
}
}
}
}
unsigned char Label::getOpacity() const
{
return _realOpacity;
}
unsigned char Label::getDisplayedOpacity() const
{
return _displayedOpacity;
}
void Label::setOpacity(GLubyte opacity)
{
_displayedOpacity = _realOpacity = opacity;
if( _cascadeOpacityEnabled ) {
GLubyte parentOpacity = 255;
RGBAProtocol* pParent = dynamic_cast<RGBAProtocol*>(_parent);
if (pParent && pParent->isCascadeOpacityEnabled())
{
parentOpacity = pParent->getDisplayedOpacity();
}
this->updateDisplayedOpacity(parentOpacity);
}
}
void Label::updateDisplayedOpacity(GLubyte parentOpacity)
{
_displayedOpacity = _realOpacity * parentOpacity/255.0;
Object* pObj;
CCARRAY_FOREACH(_children, pObj)
{
Sprite *item = static_cast<Sprite*>( pObj );
item->updateDisplayedOpacity(_displayedOpacity);
}
}
bool Label::isCascadeOpacityEnabled() const
{
return false;
}
void Label::setCascadeOpacityEnabled(bool cascadeOpacityEnabled)
{
_cascadeOpacityEnabled = cascadeOpacityEnabled;
}
const Color3B& Label::getColor(void) const
{
return _realColor;
}
const Color3B& Label::getDisplayedColor() const
{
return _displayedColor;
}
void Label::setColor(const Color3B& color)
{
_displayedColor = _realColor = color;
if( _cascadeColorEnabled )
{
Color3B parentColor = Color3B::WHITE;
RGBAProtocol* pParent = dynamic_cast<RGBAProtocol*>(_parent);
if (pParent && pParent->isCascadeColorEnabled())
parentColor = pParent->getDisplayedColor();
updateDisplayedColor(parentColor);
}
}
void Label::updateDisplayedColor(const Color3B& parentColor)
{
_displayedColor.r = _realColor.r * parentColor.r/255.0;
_displayedColor.g = _realColor.g * parentColor.g/255.0;
_displayedColor.b = _realColor.b * parentColor.b/255.0;
Object* pObj;
CCARRAY_FOREACH(_children, pObj)
{
Sprite *item = static_cast<Sprite*>( pObj );
item->updateDisplayedColor(_displayedColor);
}
}
bool Label::isCascadeColorEnabled() const
{
return false;
}
void Label::setCascadeColorEnabled(bool cascadeColorEnabled)
{
_cascadeColorEnabled = cascadeColorEnabled;
}
NS_CC_END

View File

@ -27,6 +27,8 @@
#define _COCOS2D_CCLABEL_H_
#include "sprite_nodes/CCSpriteBatchNode.h"
#include "CCLabelTextFormatProtocol.h"
#include "ccTypes.h"
NS_CC_BEGIN
@ -39,33 +41,126 @@ enum class GlyphCollection {
};
class CC_DLL Label : public SpriteBatchNode, public LabelProtocol, public RGBAProtocol
//fwd
struct FontLetterDefinition;
class FontAtlas;
class CC_DLL Label : public SpriteBatchNode, public LabelProtocol, public RGBAProtocol, public LabelTextFormatProtocol
{
public:
static Label* createWithTTF( const char* label, const char* fntFilePath, int fontSize, GlyphCollection glyphs = GlyphCollection::NEHE, int lineSize = 0, const char *customGlyphs = 0 );
static Label* createWithBMFont( const char* label, const char* bmfontFilePath, int lineSize = 0 );
// static create
static Label* createWithTTF( const char* label, const char* fontFilePath, int fontSize, int lineSize = 0, TextHAlignment alignment = TextHAlignment::CENTER, GlyphCollection glyphs = GlyphCollection::NEHE, const char *customGlyphs = 0 );
virtual ~Label();
Label();
static Label* createWithBMFont( const char* label, const char* bmfontFilePath, TextHAlignment alignment = TextHAlignment::CENTER, int lineSize = 0 );
virtual void setAlignment(TextHAlignment alignment) = 0;
virtual void setWidth(float width) = 0;
virtual void setLineBreakWithoutSpace(bool breakWithoutSpace) = 0;
virtual void setScale(float scale) = 0;
virtual void setScaleX(float scaleX) = 0;
virtual void setScaleY(float scaleY) = 0;
bool setText(const char *stringToRender, float lineWidth, TextHAlignment alignment = TextHAlignment::LEFT, bool lineBreakWithoutSpaces = false);
virtual void setString(const char *stringToRender);
virtual void setAlignment(TextHAlignment alignment);
virtual void setWidth(float width);
virtual void setLineBreakWithoutSpace(bool breakWithoutSpace);
virtual void setScale(float scale);
virtual void setScaleX(float scaleX);
virtual void setScaleY(float scaleY);
// RGBAProtocol
virtual bool isOpacityModifyRGB() const;
virtual void setOpacityModifyRGB(bool isOpacityModifyRGB);
virtual void setOpacity(GLubyte opacity);
virtual void updateDisplayedOpacity(GLubyte parentOpacity);
virtual bool isCascadeOpacityEnabled() const;
virtual void setCascadeOpacityEnabled(bool cascadeOpacityEnabled);
virtual void setColor(const Color3B& color);
virtual void updateDisplayedColor(const Color3B& parentColor);
virtual bool isCascadeColorEnabled() const;
virtual void setCascadeColorEnabled(bool cascadeColorEnabled);
virtual const Color3B& getColor(void) const;
virtual const Color3B& getDisplayedColor() const;
virtual unsigned char getOpacity() const;
virtual unsigned char getDisplayedOpacity() const;
// needs to go - TEST STUFF /////////////////////////////////////////////////////////////////////////
static Label* createWithBMFontOLD( const char* label, const char* bmfontFilePath, int lineSize = 0);
/////////////////////////////////////////////////////////////////////////////////////////////////////
// CCLabelTextFormat protocol implementation
virtual Sprite * getSpriteChild(int ID);
virtual Array * getChildrenLetters();
virtual Sprite * getSpriteForChar(unsigned short int theChar, int spriteIndexHint);
virtual float getLetterPosXLeft( Sprite* sp );
virtual float getLetterPosXRight( Sprite* sp );
// font related stuff
virtual int getCommonLineHeight();
virtual int getKerningForCharsPair(unsigned short first, unsigned short second);
virtual int getXOffsetForChar(unsigned short c);
virtual int getYOffsetForChar(unsigned short c);
virtual int getAdvanceForChar(unsigned short c, int hintPositionInString);
virtual Rect getRectForChar(unsigned short c) ;
// string related stuff
virtual int getStringNumLines();
virtual int getStringLenght();
virtual unsigned short getCharAtStringPosition(int position);
virtual unsigned short * getUTF8String();
virtual void assignNewUTF8String(unsigned short *newString);
virtual TextHAlignment getTextAlignment();
// label related stuff
virtual float getMaxLineWidth() ;
virtual bool breakLineWithoutSpace();
virtual Size getLabelContentSize();
virtual void setLabelContentSize(const Size &newSize);
// carloX
const char * getString() const { return "not implemented"; }
private:
Label(FontAtlas *pAtlas, TextHAlignment alignment);
~Label();
static Label* createWithAtlas(FontAtlas *pAtlas, TextHAlignment alignment = TextHAlignment::LEFT, int lineSize = 0);
bool init();
void alignText();
void hideAllLetters();
void moveAllSpritesToCache();
bool computeAdvancesForString(unsigned short int *stringToRender);
bool setCurrentString(unsigned short *stringToSet);
bool setOriginalString(unsigned short *stringToSet);
void resetCurrentString();
Sprite * getSprite();
Sprite * createNewSpriteFromLetterDefinition(FontLetterDefinition &theDefinition, Texture2D *theTexture);
Sprite * updateSpriteWithLetterDefinition(Sprite *spriteToUpdate, FontLetterDefinition &theDefinition, Texture2D *theTexture);
Sprite * getSpriteForLetter(unsigned short int newLetter);
Sprite * updateSpriteForLetter(Sprite *spriteToUpdate, unsigned short int newLetter);
Array _spriteArray;
Array _spriteArrayCache;
float _commonLineHeight;
bool _lineBreakWithoutSpaces;
float _width;
TextHAlignment _alignment;
unsigned short int * _currentUTF8String;
unsigned short int * _originalUTF8String;
Size * _advances;
FontAtlas * _fontAtlas;
Color3B _displayedColor;
Color3B _realColor;
bool _cascadeColorEnabled;
bool _cascadeOpacityEnabled;
unsigned char _displayedOpacity;
unsigned char _realOpacity;
bool _isOpacityModifyRGB;
};
NS_CC_END
#endif /*__COCOS2D_CCLABEL_H */

View File

@ -32,33 +32,33 @@ class CC_DLL LabelTextFormatProtocol
public:
// sprite related stuff
virtual cocos2d::Sprite * getSpriteChild(int ID) = 0;
virtual cocos2d::Array * getChildrenLetters() = 0;
virtual cocos2d::Sprite * getSpriteForChar(unsigned short int theChar, int spriteIndexHint) = 0;
virtual float getLetterPosXLeft( cocos2d::Sprite* sp ) = 0;
virtual float getLetterPosXRight( cocos2d::Sprite* sp ) = 0;
virtual cocos2d::Sprite *getSpriteChild(int ID) = 0;
virtual cocos2d::Array *getChildrenLetters() = 0;
virtual cocos2d::Sprite *getSpriteForChar(unsigned short int theChar, int spriteIndexHint) = 0;
virtual float getLetterPosXLeft( cocos2d::Sprite* sp ) = 0;
virtual float getLetterPosXRight( cocos2d::Sprite* sp ) = 0;
// font related stuff
virtual int getCommonLineHeight() = 0;
virtual int getKerningForCharsPair(unsigned short first, unsigned short second) = 0;
virtual int getXOffsetForChar(unsigned short c) = 0;
virtual int getYOffsetForChar(unsigned short c) = 0;
virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) = 0;
virtual cocos2d::Rect getRectForChar(unsigned short c) = 0;
virtual int getCommonLineHeight() = 0;
virtual int getKerningForCharsPair(unsigned short first, unsigned short second) = 0;
virtual int getXOffsetForChar(unsigned short c) = 0;
virtual int getYOffsetForChar(unsigned short c) = 0;
virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) = 0;
virtual cocos2d::Rect getRectForChar(unsigned short c) = 0;
// string related stuff
virtual int getStringNumLines() = 0;
virtual int getStringLenght() = 0;
virtual unsigned short getCharAtStringPosition(int position) = 0;
virtual unsigned short * getUTF8String() = 0;
virtual void assignNewUTF8String(unsigned short *newString) = 0;
virtual TextHAlignment getTextAlignment() = 0;
virtual int getStringNumLines() = 0;
virtual int getStringLenght() = 0;
virtual unsigned short getCharAtStringPosition(int position) = 0;
virtual unsigned short * getUTF8String() = 0;
virtual void assignNewUTF8String(unsigned short *newString) = 0;
virtual TextHAlignment getTextAlignment() = 0;
// label related stuff
virtual float getMaxLineWidth() = 0;
virtual bool breakLineWithoutSpace() = 0;
virtual cocos2d::Size getLabelContentSize() = 0;
virtual void setLabelContentSize(const Size &newSize) = 0;
virtual float getMaxLineWidth() = 0;
virtual bool breakLineWithoutSpace() = 0;
virtual cocos2d::Size getLabelContentSize() = 0;
virtual void setLabelContentSize(const Size &newSize) = 0;
};

View File

@ -224,7 +224,7 @@ bool LabelTextFormatter::alignText(LabelTextFormatProtocol *theLabel)
vector<unsigned short> last_line;
for (int ctr = 0; ctr <= str_len; ++ctr)
{
unsigned char currentChar = theLabel->getCharAtStringPosition(ctr);
unsigned short int currentChar = theLabel->getCharAtStringPosition(ctr);
if (currentChar == '\n' || currentChar == 0)
{
@ -301,7 +301,7 @@ bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel)
unsigned short prev = -1;
Size tmpSize = Size::ZERO;
Size tmpSize = Size::ZERO;
int longestLine = 0;
unsigned int totalHeight = 0;

View File

@ -1,733 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga 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.
Use any of these editors to generate BMFonts:
http://glyphdesigner.71squared.com/ (Commercial, Mac OS X)
http://www.n4te.com/hiero/hiero.jnlp (Free, Java)
http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java)
http://www.angelcode.com/products/bmfont/ (Free, Windows only)
****************************************************************************/
#include "CCStringBMFont.h"
#include "cocoa/CCString.h"
#include "cocoa/CCDictionary.h"
#include "CCConfiguration.h"
#include "CCLabelTextFormatter.h"
#include "draw_nodes/CCDrawingPrimitives.h"
#include "sprite_nodes/CCSprite.h"
//#include "support/CCPointExtension.h"
#include "platform/CCFileUtils.h"
#include "CCDirector.h"
#include "textures/CCTextureCache.h"
#include "support/ccUTF8.h"
using namespace std;
NS_CC_BEGIN
// The return value needs to be deleted by CC_SAFE_DELETE_ARRAY.
static unsigned short* copyUTF16StringNN(unsigned short* str)
{
int length = str ? cc_wcslen(str) : 0;
unsigned short* ret = new unsigned short[length+1];
for (int i = 0; i < length; ++i) {
ret[i] = str[i];
}
ret[length] = 0;
return ret;
}
//
//CCLabelBMFont
//
//LabelBMFont - Purge Cache
void StringBMFont::purgeCachedData()
{
FNTConfigRemoveCache();
}
StringBMFont * StringBMFont::create()
{
StringBMFont * pRet = new StringBMFont();
if (pRet && pRet->init())
{
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
StringBMFont * StringBMFont::create(const char *str, const char *fntFile, float width, TextHAlignment alignment)
{
return StringBMFont::create(str, fntFile, width, alignment, Point::ZERO);
}
StringBMFont * StringBMFont::create(const char *str, const char *fntFile, float width)
{
return StringBMFont::create(str, fntFile, width, TextHAlignment::LEFT, Point::ZERO);
}
StringBMFont * StringBMFont::create(const char *str, const char *fntFile)
{
return StringBMFont::create(str, fntFile, kLabelAutomaticWidth, TextHAlignment::LEFT, Point::ZERO);
}
//LabelBMFont - Creation & Init
StringBMFont *StringBMFont::create(const char *str, const char *fntFile, float width/* = kLabelAutomaticWidth*/, TextHAlignment alignment/* = kTextAlignmentLeft*/, Point imageOffset/* = Point::ZERO*/)
{
StringBMFont *pRet = new StringBMFont();
if(pRet && pRet->initWithString(str, fntFile, width, alignment, imageOffset))
{
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
bool StringBMFont::init()
{
return initWithString(NULL, NULL, kLabelAutomaticWidth, TextHAlignment::LEFT, Point::ZERO);
}
bool StringBMFont::initWithString(const char *theString, const char *fntFile, float width/* = kLabelAutomaticWidth*/, TextHAlignment alignment/* = kTextAlignmentLeft*/, Point imageOffset/* = Point::ZERO*/)
{
CCAssert(!_configuration, "re-init is no longer supported");
CCAssert( (theString && fntFile) || (theString==NULL && fntFile==NULL), "Invalid params for StringBMFont");
Texture2D *texture = NULL;
if (fntFile)
{
CCBMFontConfiguration *newConf = FNTConfigLoadFile(fntFile);
if (!newConf)
{
CCLOG("cocos2d: WARNING. StringBMFont: Impossible to create font. Please check file: '%s'", fntFile);
release();
return false;
}
newConf->retain();
CC_SAFE_RELEASE(_configuration);
_configuration = newConf;
_fntFile = fntFile;
texture = TextureCache::getInstance()->addImage(_configuration->getAtlasName());
}
else
{
texture = new Texture2D();
texture->autorelease();
}
if (theString == NULL)
{
theString = "";
}
if (SpriteBatchNode::initWithTexture(texture, strlen(theString)))
{
_width = width;
_alignment = alignment;
_displayedOpacity = _realOpacity = 255;
_displayedColor = _realColor = Color3B::WHITE;
_cascadeOpacityEnabled = true;
_cascadeColorEnabled = true;
_contentSize = Size::ZERO;
_isOpacityModifyRGB = _textureAtlas->getTexture()->hasPremultipliedAlpha();
_anchorPoint = Point(0.5f, 0.5f);
_imageOffset = imageOffset;
_reusedChar = new Sprite();
_reusedChar->initWithTexture(_textureAtlas->getTexture(), Rect(0, 0, 0, 0), false);
_reusedChar->setBatchNode(this);
this->setString(theString);
return true;
}
return false;
}
StringBMFont::StringBMFont()
: _string(NULL)
, _initialString(NULL)
, _alignment(TextHAlignment::CENTER)
, _width(-1.0f)
, _configuration(NULL)
, _lineBreakWithoutSpaces(false)
, _imageOffset(Point::ZERO)
, _reusedChar(NULL)
, _displayedOpacity(255)
, _realOpacity(255)
, _displayedColor(Color3B::WHITE)
, _realColor(Color3B::WHITE)
, _cascadeColorEnabled(true)
, _cascadeOpacityEnabled(true)
, _isOpacityModifyRGB(false)
{
}
StringBMFont::~StringBMFont()
{
CC_SAFE_RELEASE(_reusedChar);
CC_SAFE_DELETE_ARRAY(_string);
CC_SAFE_DELETE_ARRAY(_initialString);
CC_SAFE_RELEASE(_configuration);
}
// StringBMFont - Atlas generation
int StringBMFont::kerningAmountForFirst(unsigned short first, unsigned short second)
{
int ret = 0;
unsigned int key = (first<<16) | (second & 0xffff);
if( _configuration->_kerningDictionary ) {
tKerningHashElement *element = NULL;
HASH_FIND_INT(_configuration->_kerningDictionary, &key, element);
if(element)
ret = element->amount;
}
return ret;
}
const char* StringBMFont::getString(void) const
{
return _initialStringUTF8.c_str();
}
//StringBMFont - RGBAProtocol protocol
const Color3B& StringBMFont::getColor() const
{
return _realColor;
}
const Color3B& StringBMFont::getDisplayedColor() const
{
return _displayedColor;
}
void StringBMFont::setColor(const Color3B& color)
{
_displayedColor = _realColor = color;
if( _cascadeColorEnabled ) {
Color3B parentColor = Color3B::WHITE;
RGBAProtocol* pParent = dynamic_cast<RGBAProtocol*>(_parent);
if (pParent && pParent->isCascadeColorEnabled())
{
parentColor = pParent->getDisplayedColor();
}
this->updateDisplayedColor(parentColor);
}
}
GLubyte StringBMFont::getOpacity(void) const
{
return _realOpacity;
}
GLubyte StringBMFont::getDisplayedOpacity(void) const
{
return _displayedOpacity;
}
/** Override synthesized setOpacity to recurse items */
void StringBMFont::setOpacity(GLubyte opacity)
{
_displayedOpacity = _realOpacity = opacity;
if( _cascadeOpacityEnabled ) {
GLubyte parentOpacity = 255;
RGBAProtocol* pParent = dynamic_cast<RGBAProtocol*>(_parent);
if (pParent && pParent->isCascadeOpacityEnabled())
{
parentOpacity = pParent->getDisplayedOpacity();
}
this->updateDisplayedOpacity(parentOpacity);
}
}
void StringBMFont::setOpacityModifyRGB(bool var)
{
_isOpacityModifyRGB = var;
if (_children && _children->count() != 0)
{
Object* child;
CCARRAY_FOREACH(_children, child)
{
Node* pNode = static_cast<Node*>( child );
if (pNode)
{
RGBAProtocol *pRGBAProtocol = dynamic_cast<RGBAProtocol*>(pNode);
if (pRGBAProtocol)
{
pRGBAProtocol->setOpacityModifyRGB(_isOpacityModifyRGB);
}
}
}
}
}
bool StringBMFont::isOpacityModifyRGB() const
{
return _isOpacityModifyRGB;
}
void StringBMFont::updateDisplayedOpacity(GLubyte parentOpacity)
{
_displayedOpacity = _realOpacity * parentOpacity/255.0;
Object* pObj;
CCARRAY_FOREACH(_children, pObj)
{
Sprite *item = static_cast<Sprite*>( pObj );
item->updateDisplayedOpacity(_displayedOpacity);
}
}
void StringBMFont::updateDisplayedColor(const Color3B& parentColor)
{
_displayedColor.r = _realColor.r * parentColor.r/255.0;
_displayedColor.g = _realColor.g * parentColor.g/255.0;
_displayedColor.b = _realColor.b * parentColor.b/255.0;
Object* pObj;
CCARRAY_FOREACH(_children, pObj)
{
Sprite *item = static_cast<Sprite*>( pObj );
item->updateDisplayedColor(_displayedColor);
}
}
bool StringBMFont::isCascadeColorEnabled() const
{
return false;
}
void StringBMFont::setCascadeColorEnabled(bool cascadeColorEnabled)
{
_cascadeColorEnabled = cascadeColorEnabled;
}
bool StringBMFont::isCascadeOpacityEnabled() const
{
return false;
}
void StringBMFont::setCascadeOpacityEnabled(bool cascadeOpacityEnabled)
{
_cascadeOpacityEnabled = cascadeOpacityEnabled;
}
// StringBMFont - AnchorPoint
void StringBMFont::setAnchorPoint(const Point& point)
{
if( ! point.equals(_anchorPoint))
{
SpriteBatchNode::setAnchorPoint(point);
updateLabel();
}
}
// StringBMFont - Alignment
void StringBMFont::setAlignment(TextHAlignment alignment)
{
this->_alignment = alignment;
updateLabel();
}
void StringBMFont::setWidth(float width)
{
this->_width = width;
updateLabel();
}
void StringBMFont::setLineBreakWithoutSpace( bool breakWithoutSpace )
{
_lineBreakWithoutSpaces = breakWithoutSpace;
updateLabel();
}
void StringBMFont::setScale(float scale)
{
SpriteBatchNode::setScale(scale);
updateLabel();
}
void StringBMFont::setScaleX(float scaleX)
{
SpriteBatchNode::setScaleX(scaleX);
updateLabel();
}
void StringBMFont::setScaleY(float scaleY)
{
SpriteBatchNode::setScaleY(scaleY);
updateLabel();
}
float StringBMFont::getLetterPosXLeft( Sprite* sp )
{
return sp->getPosition().x * _scaleX - (sp->getContentSize().width * _scaleX * sp->getAnchorPoint().x);
}
float StringBMFont::getLetterPosXRight( Sprite* sp )
{
return sp->getPosition().x * _scaleX + (sp->getContentSize().width * _scaleX * sp->getAnchorPoint().x);
}
// StringBMFont - FntFile
void StringBMFont::setFntFile(const char* fntFile)
{
if (fntFile != NULL && strcmp(fntFile, _fntFile.c_str()) != 0 )
{
CCBMFontConfiguration *newConf = FNTConfigLoadFile(fntFile);
CCAssert( newConf, "CCStringBMFont: Impossible to create font. Please check file");
_fntFile = fntFile;
CC_SAFE_RETAIN(newConf);
CC_SAFE_RELEASE(_configuration);
_configuration = newConf;
this->setTexture(TextureCache::getInstance()->addImage(_configuration->getAtlasName()));
LabelTextFormatter::createStringSprites(this);
}
}
const char* StringBMFont::getFntFile()
{
return _fntFile.c_str();
}
//StringBMFont - Debug draw
#if CC_LabelBMFontNew_DEBUG_DRAW
void StringBMFont::draw()
{
SpriteBatchNode::draw();
const Size& s = this->getContentSize();
Point vertices[4]={
ccp(0,0),ccp(s.width,0),
ccp(s.width,s.height),ccp(0,s.height),
};
ccDrawPoly(vertices, 4, true);
}
#endif // CC_LABELBMFONT_DEBUG_DRAW
int StringBMFont::getCommonLineHeight()
{
if (_configuration)
{
return _configuration->_commonHeight;
}
else
{
return -1;
}
}
int StringBMFont::getKerningForCharsPair(unsigned short first, unsigned short second)
{
return this->kerningAmountForFirst(first, second);
}
ccBMFontDef StringBMFont::getFontDefForChar(unsigned short int theChar)
{
ccBMFontDef fontDef;
tFontDefHashElement *element = NULL;
unsigned int key = theChar;
HASH_FIND_INT(_configuration->_fontDefDictionary, &key, element);
if (element)
{
fontDef = element->fontDef;
}
return fontDef;
}
// return a sprite for rendering one letter
Sprite * StringBMFont::getSpriteForChar(unsigned short int theChar, int spriteIndexHint)
{
Rect rect;
ccBMFontDef fontDef;
Sprite *pRetSprite = 0;
// unichar is a short, and an int is needed on HASH_FIND_INT
tFontDefHashElement *element = NULL;
unsigned int key = theChar;
HASH_FIND_INT(_configuration->_fontDefDictionary, &key, element);
if (! element)
{
return 0;
}
fontDef = element->fontDef;
rect = fontDef.rect;
rect = CC_RECT_PIXELS_TO_POINTS(rect);
rect.origin.x += _imageOffset.x;
rect.origin.y += _imageOffset.y;
//bool hasSprite = true;
pRetSprite = (Sprite*)(this->getChildByTag(spriteIndexHint));
if(pRetSprite )
{
// Reusing previous Sprite
pRetSprite->setVisible(true);
}
else
{
pRetSprite = new Sprite();
pRetSprite->initWithTexture(_textureAtlas->getTexture(), rect);
addChild(pRetSprite, spriteIndexHint, spriteIndexHint);
pRetSprite->release();
// Apply label properties
pRetSprite->setOpacityModifyRGB(_isOpacityModifyRGB);
// Color MUST be set before opacity, since opacity might change color if OpacityModifyRGB is on
pRetSprite->updateDisplayedColor(_displayedColor);
pRetSprite->updateDisplayedOpacity(_displayedOpacity);
}
// updating previous sprite
pRetSprite->setTextureRect(rect, false, rect.size);
return pRetSprite;
}
int StringBMFont::getStringNumLines()
{
int quantityOfLines = 1;
unsigned int stringLen = _string ? cc_wcslen(_string) : 0;
if (stringLen == 0)
return (-1);
// count number of lines
for (unsigned int i = 0; i < stringLen - 1; ++i)
{
unsigned short c = _string[i];
if (c == '\n')
{
quantityOfLines++;
}
}
return quantityOfLines;
}
// need cross implementation
int StringBMFont::getStringLenght()
{
return _string ? cc_wcslen(_string) : 0;
}
unsigned short StringBMFont::getCharAtStringPosition(int position)
{
return _string[position];
}
int StringBMFont::getXOffsetForChar(unsigned short c)
{
ccBMFontDef fontDef = getFontDefForChar(c);
return fontDef.xOffset;
}
int StringBMFont::getYOffsetForChar(unsigned short c)
{
ccBMFontDef fontDef = getFontDefForChar(c);
return fontDef.yOffset;
}
Rect StringBMFont::getRectForChar(unsigned short c)
{
ccBMFontDef fontDef = getFontDefForChar(c);
return fontDef.rect;
}
int StringBMFont::getAdvanceForChar(unsigned short c, int hintPositionInString)
{
ccBMFontDef fontDef = getFontDefForChar(c);
return fontDef.xAdvance;
}
void StringBMFont::setLabelContentSize(const Size &newSize)
{
setContentSize(newSize);
}
void StringBMFont::createStringSprites()
{
LabelTextFormatter::createStringSprites(this);
}
void StringBMFont::setString(const char *newString)
{
// store initial string in char8 format
_initialStringUTF8 = newString;
// update the initial string if needed
unsigned short* utf16String = cc_utf8_to_utf16(newString);
unsigned short* tmp = _initialString;
_initialString = copyUTF16StringNN(utf16String);
CC_SAFE_DELETE_ARRAY(tmp);
CC_SAFE_DELETE_ARRAY(utf16String);
// do the rest of the josb
updateLabel();
}
void StringBMFont::setCString(const char *label)
{
setString(label);
}
void StringBMFont::updateLabel()
{
if ( _initialString!=0 )
{
// set the new string
CC_SAFE_DELETE_ARRAY(_string);
_string = copyUTF16StringNN(_initialString);
// hide all the letters and create or recicle sprites for the new letters
updateLetterSprites();
// format the text on more than line
multilineText();
// align the text (left - center - right)
alignText();
}
}
void StringBMFont::updateLetterSprites()
{
// hide all the letters
hideStringSprites();
// create new letters sprites
createStringSprites();
}
void StringBMFont::hideStringSprites()
{
if (_children && _children->count() != 0)
{
Object* child;
CCARRAY_FOREACH(_children, child)
{
Node* pNode = (Node*) child;
if (pNode)
{
pNode->setVisible(false);
}
}
}
}
void StringBMFont::multilineText()
{
if (_width > 0)
{
// format on more than one line
LabelTextFormatter::multilineText(this);
// hide all the letter sprites and create/reclaim letters sprite with new position
updateLetterSprites();
}
}
void StringBMFont::alignText()
{
if (_alignment != TextHAlignment::LEFT)
{
LabelTextFormatter::alignText(this);
}
}
unsigned short * StringBMFont::getUTF8String()
{
return _string;
}
Sprite * StringBMFont::getSpriteChild(int ID)
{
return (Sprite*)this->getChildByTag(ID);
}
float StringBMFont::getMaxLineWidth()
{
return _width;
}
TextHAlignment StringBMFont::getTextAlignment()
{
return _alignment;
}
Array* StringBMFont::getChildrenLetters()
{
return _children;
}
void StringBMFont::assignNewUTF8String(unsigned short *newString)
{
CC_SAFE_DELETE_ARRAY(_string);
_string = newString;
}
Size StringBMFont::getLabelContentSize()
{
return getContentSize();
}
bool StringBMFont::breakLineWithoutSpace()
{
return _lineBreakWithoutSpaces;
}
NS_CC_END

View File

@ -1,204 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga 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.
Use any of these editors to generate BMFonts:
http://glyphdesigner.71squared.com/ (Commercial, Mac OS X)
http://www.n4te.com/hiero/hiero.jnlp (Free, Java)
http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java)
http://www.angelcode.com/products/bmfont/ (Free, Windows only)
****************************************************************************/
#ifndef __CCBITMAP_FONT_ATLAS_H__NEW_
#define __CCBITMAP_FONT_ATLAS_H__NEW_
#include "sprite_nodes/CCSpriteBatchNode.h"
#include "support/data_support/uthash.h"
#include "CCLabelBMFont.h"
#include "CCLabelTextFormatProtocol.h"
#include <map>
#include <sstream>
#include <iostream>
#include <vector>
#include "CCLabel.h"
NS_CC_BEGIN
class CC_DLL StringBMFont: public Label, public LabelTextFormatProtocol
{
public:
StringBMFont();
virtual ~StringBMFont();
/** Purges the cached data.
Removes from memory the cached configurations and the atlas name dictionary.
@since v0.99.3
*/
static void purgeCachedData();
/** creates a bitmap font atlas with an initial string and the FNT file */
static StringBMFont * create(const char *str, const char *fntFile, float width, TextHAlignment alignment, Point imageOffset);
static StringBMFont * create(const char *str, const char *fntFile, float width, TextHAlignment alignment);
static StringBMFont * create(const char *str, const char *fntFile, float width);
static StringBMFont * create(const char *str, const char *fntFile);
/** Creates an label.
*/
static StringBMFont * create();
bool init();
/** init a bitmap font atlas with an initial string and the FNT file */
bool initWithString(const char *str, const char *fntFile, float width = kLabelAutomaticWidth, TextHAlignment alignment = TextHAlignment::LEFT, Point imageOffset = Point::ZERO);
/** updates the font chars based on the string to render */
// super method
virtual void setString(const char *newString);
virtual const char* getString(void) const;
virtual void setCString(const char *label);
virtual void setAnchorPoint(const Point& var);
virtual void updateLabel();
virtual void setAlignment(TextHAlignment alignment);
virtual void setWidth(float width);
virtual void setLineBreakWithoutSpace(bool breakWithoutSpace);
virtual void setScale(float scale);
virtual void setScaleX(float scaleX);
virtual void setScaleY(float scaleY);
// RGBAProtocol
virtual bool isOpacityModifyRGB() const;
virtual void setOpacityModifyRGB(bool isOpacityModifyRGB);
virtual GLubyte getOpacity() const;
virtual GLubyte getDisplayedOpacity() const;
virtual void setOpacity(GLubyte opacity);
virtual void updateDisplayedOpacity(GLubyte parentOpacity);
virtual bool isCascadeOpacityEnabled() const;
virtual void setCascadeOpacityEnabled(bool cascadeOpacityEnabled);
virtual const Color3B& getColor(void) const;
virtual const Color3B& getDisplayedColor() const;
virtual void setColor(const Color3B& color);
virtual void updateDisplayedColor(const Color3B& parentColor);
virtual bool isCascadeColorEnabled() const;
virtual void setCascadeColorEnabled(bool cascadeColorEnabled);
// StringBMFont protocol stuff
virtual Sprite * getSpriteChild(int ID);
virtual Array * getChildrenLetters();
virtual Sprite * getSpriteForChar(unsigned short int theChar, int spriteIndexHint);
virtual int getCommonLineHeight();
virtual int getKerningForCharsPair(unsigned short first, unsigned short second);
virtual int getXOffsetForChar(unsigned short c);
virtual int getYOffsetForChar(unsigned short c);
virtual int getAdvanceForChar(unsigned short c, int hintPositionInString);
virtual Rect getRectForChar(unsigned short c);
float getLetterPosXLeft( Sprite* sp );
float getLetterPosXRight( Sprite* sp );
virtual int getStringNumLines();
virtual int getStringLenght();
virtual unsigned short getCharAtStringPosition(int position);
virtual unsigned short * getUTF8String();
virtual void assignNewUTF8String(unsigned short *newString);
virtual float getMaxLineWidth();
virtual bool breakLineWithoutSpace();
virtual TextHAlignment getTextAlignment();
virtual Size getLabelContentSize();
virtual void setLabelContentSize(const Size &newSize);
void setFntFile(const char* fntFile);
const char* getFntFile();
#if CC_LABELBMFONT_DEBUG_DRAW
virtual void draw();
#endif // CC_LABELBMFONT_DEBUG_DRAW
private:
char * atlasNameFromFntFile(const char *fntFile);
int kerningAmountForFirst(unsigned short first, unsigned short second);
// some more new stuff
void alignText();
void multilineText();
ccBMFontDef getFontDefForChar(unsigned short int theChar);
void createStringSprites();
void hideStringSprites();
void updateLetterSprites();
protected:
// string to render
unsigned short* _string;
// name of fntFile
std::string _fntFile;
// initial string without line breaks
unsigned short* _initialString;
std::string _initialStringUTF8;
// alignment of all lines
TextHAlignment _alignment;
// max width until a line break is added
float _width;
CCBMFontConfiguration *_configuration;
bool _lineBreakWithoutSpaces;
// offset of the texture atlas
Point _imageOffset;
// reused char
Sprite *_reusedChar;
// texture RGBA
GLubyte _displayedOpacity;
GLubyte _realOpacity;
Color3B _displayedColor;
Color3B _realColor;
bool _cascadeColorEnabled;
bool _cascadeOpacityEnabled;
/** conforms to RGBAProtocol protocol */
bool _isOpacityModifyRGB;
};
/** Free function that parses a FNT file a place it on the cache
*/
CC_DLL CCBMFontConfiguration * FNTConfigLoadFile( const char *file );
/** Purges the FNT config cache
*/
CC_DLL void FNTConfigRemoveCache( void );
// end of GUI group
/// @}
/// @}
NS_CC_END
#endif //__CCBITMAP_FONT_ATLAS_H__

View File

@ -1,671 +0,0 @@
/****************************************************************************
Copyright (c) 2013 Zynga 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 "cocos2d.h"
#include "CCStringTTF.h"
#include "CCFont.h"
#include "CCLabelTextFormatter.h"
#include "CCFontAtlasCache.h"
NS_CC_BEGIN
StringTTF::StringTTF(FontAtlas *pAtlas, TextHAlignment alignment): _currentUTF8String(0),
_originalUTF8String(0),
_fontAtlas(pAtlas),
_alignment(alignment),
_lineBreakWithoutSpaces(false),
_advances(0),
_displayedColor(Color3B::WHITE),
_realColor(Color3B::WHITE),
_cascadeColorEnabled(true)
{
}
StringTTF* StringTTF::create(FontAtlas *pAtlas, TextHAlignment alignment, int lineSize)
{
StringTTF *ret = new StringTTF(pAtlas, alignment);
if (!ret)
return nullptr;
if( ret->init() )
{
ret->autorelease();
return ret;
}
else
{
delete ret;
return nullptr;
}
return ret;
}
StringTTF::~StringTTF()
{
if (_currentUTF8String)
{
delete [] _currentUTF8String;
_currentUTF8String = 0;
}
if (_advances)
{
delete [] _advances;
_advances = 0;
}
if (_fontAtlas)
{
FontAtlasCache::releaseFontAtlas(_fontAtlas);
}
}
bool StringTTF::init()
{
return true;
}
void StringTTF::setString(const char *stringToRender)
{
setText(stringToRender, 0, TextHAlignment::CENTER, false);
}
bool StringTTF::setText(const char *stringToRender, float lineWidth, TextHAlignment alignment, bool lineBreakWithoutSpaces)
{
if (!_fontAtlas)
return false;
_width = lineWidth;
_alignment = alignment;
_lineBreakWithoutSpaces = lineBreakWithoutSpaces;
// release all the sprites
moveAllSpritesToCache();
// store locally common line height
_commonLineHeight = _fontAtlas->getCommonLineHeight();
if (_commonLineHeight <= 0)
return false;
int numLetter = 0;
unsigned short* utf16String = cc_utf8_to_utf16(stringToRender);
if(!utf16String)
return false;
numLetter = cc_wcslen(utf16String);
SpriteBatchNode::initWithTexture(&_fontAtlas->getTexture(0), numLetter);
_cascadeColorEnabled = true;
//
setCurrentString(utf16String);
setOriginalString(utf16String);
// align text
alignText();
// done here
return true;
}
void StringTTF::setAlignment(TextHAlignment alignment)
{
// store the new alignment
if (alignment != _alignment)
{
// store
_alignment = alignment;
// reset the string
resetCurrentString();
// need to align text again
alignText();
}
}
void StringTTF::setWidth(float width)
{
if (width != _width)
{
// store
_width = width;
// need to align text again
alignText();
}
}
void StringTTF::setLineBreakWithoutSpace(bool breakWithoutSpace)
{
if (breakWithoutSpace != _lineBreakWithoutSpaces)
{
// store
_lineBreakWithoutSpaces = breakWithoutSpace;
// need to align text again
alignText();
}
}
void StringTTF::setScale(float scale)
{
Node::setScale(scale);
alignText();
}
void StringTTF::setScaleX(float scaleX)
{
Node::setScaleX(scaleX);
alignText();
}
void StringTTF::setScaleY(float scaleY)
{
Node::setScaleY(scaleY);
alignText();
}
void StringTTF::alignText()
{
hideAllLetters();
LabelTextFormatter::createStringSprites(this);
if( LabelTextFormatter::multilineText(this) )
{
hideAllLetters();
LabelTextFormatter::createStringSprites(this);
}
LabelTextFormatter::alignText(this);
}
void StringTTF::hideAllLetters()
{
Object* Obj = NULL;
CCARRAY_FOREACH(&_spriteArray, Obj)
{
((Sprite *)Obj)->setVisible(false);
}
CCARRAY_FOREACH(&_spriteArrayCache, Obj)
{
((Sprite *)Obj)->setVisible(false);
}
}
bool StringTTF::computeAdvancesForString(unsigned short int *stringToRender)
{
if (_advances)
{
delete [] _advances;
_advances = 0;
}
Font &theFont = _fontAtlas->getFont();
int letterCount = 0;
_advances = theFont.getAdvancesForTextUTF16(stringToRender, letterCount);
if(!_advances)
return false;
else
return true;
}
bool StringTTF::setOriginalString(unsigned short *stringToSet)
{
if (_originalUTF8String)
{
delete [] _originalUTF8String;
_originalUTF8String = 0;
}
int newStringLenght = cc_wcslen(stringToSet);
_originalUTF8String = new unsigned short int [newStringLenght + 1];
memset(_originalUTF8String, 0, (newStringLenght + 1) * 2);
memcpy(_originalUTF8String, stringToSet, (newStringLenght * 2));
_originalUTF8String[newStringLenght] = 0;
return true;
}
bool StringTTF::setCurrentString(unsigned short *stringToSet)
{
// set the new string
if (_currentUTF8String)
{
delete [] _currentUTF8String;
_currentUTF8String = 0;
}
//
_currentUTF8String = stringToSet;
// compute the advances
return computeAdvancesForString(stringToSet);
}
void StringTTF::resetCurrentString()
{
// set the new string
if (_currentUTF8String)
{
delete [] _currentUTF8String;
_currentUTF8String = 0;
}
int stringLenght = cc_wcslen(_originalUTF8String);
_currentUTF8String = new unsigned short int [stringLenght + 1];
memcpy(_currentUTF8String, _originalUTF8String, stringLenght * 2);
_currentUTF8String[stringLenght] = 0;
}
Sprite * StringTTF::createNewSpriteFromLetterDefinition(FontLetterDefinition &theDefinition, Texture2D *theTexture)
{
Rect uvRect;
uvRect.size.height = theDefinition.height;
uvRect.size.width = theDefinition.width;
uvRect.origin.x = theDefinition.U;
uvRect.origin.y = theDefinition.V;
SpriteFrame *pFrame = SpriteFrame::createWithTexture(theTexture, uvRect);
Sprite *tempSprite = getSprite();
if (!tempSprite)
return nullptr;
tempSprite->initWithSpriteFrame(pFrame);
tempSprite->setAnchorPoint(Point(theDefinition.anchorX, theDefinition.anchorY));
tempSprite->setBatchNode(this);
return tempSprite;
}
Sprite * StringTTF::updateSpriteWithLetterDefinition(Sprite *spriteToUpdate, FontLetterDefinition &theDefinition, Texture2D *theTexture)
{
if (!spriteToUpdate)
{
return nullptr;
}
else
{
Rect uvRect;
uvRect.size.height = theDefinition.height;
uvRect.size.width = theDefinition.width;
uvRect.origin.x = theDefinition.U;
uvRect.origin.y = theDefinition.V;
SpriteFrame *frame = SpriteFrame::createWithTexture(theTexture, uvRect);
if (frame)
{
spriteToUpdate->setTexture(theTexture);
spriteToUpdate->setDisplayFrame(frame);
spriteToUpdate->setAnchorPoint(Point(theDefinition.anchorX, theDefinition.anchorY));
spriteToUpdate->setBatchNode(this);
}
return spriteToUpdate;
}
}
Sprite * StringTTF::getSpriteForLetter(unsigned short int newLetter)
{
if (!_fontAtlas)
return nullptr;
FontLetterDefinition tempDefinition;
bool validDefinition = _fontAtlas->getLetterDefinitionForChar(newLetter, tempDefinition);
if (validDefinition)
{
Sprite *newSprite = createNewSpriteFromLetterDefinition(tempDefinition, &_fontAtlas->getTexture(tempDefinition.textureID) );
this->addChild(newSprite);
return newSprite;
}
else
{
return nullptr;
}
}
Sprite * StringTTF::updateSpriteForLetter(Sprite *spriteToUpdate, unsigned short int newLetter)
{
if (!spriteToUpdate || !_fontAtlas)
return nullptr;
FontLetterDefinition tempDefinition;
bool validDefinition = _fontAtlas->getLetterDefinitionForChar(newLetter, tempDefinition);
if (validDefinition)
{
Sprite *pNewSprite = updateSpriteWithLetterDefinition(spriteToUpdate, tempDefinition, &_fontAtlas->getTexture(tempDefinition.textureID) );
return pNewSprite;
}
else
{
return nullptr;
}
}
void StringTTF::moveAllSpritesToCache()
{
Object* pObj = NULL;
CCARRAY_FOREACH(&_spriteArray, pObj)
{
((Sprite *)pObj)->removeFromParent();
_spriteArrayCache.addObject(pObj);
}
_spriteArray.removeAllObjects();
}
Sprite * StringTTF::getSprite()
{
if (_spriteArrayCache.count())
{
Sprite *retSprite = (Sprite *) _spriteArrayCache.lastObject();
_spriteArrayCache.removeLastObject();
return retSprite;
}
else
{
Sprite *retSprite = new Sprite;
return retSprite;
}
}
///// PROTOCOL STUFF
Sprite * StringTTF::getSpriteChild(int ID)
{
Object* pObj = NULL;
CCARRAY_FOREACH(&_spriteArray, pObj)
{
Sprite *pSprite = (Sprite *)pObj;
if ( pSprite->getTag() == ID)
{
return pSprite;
}
}
return nullptr;
}
Array * StringTTF::getChildrenLetters()
{
return &_spriteArray;
}
Sprite * StringTTF::getSpriteForChar(unsigned short int theChar, int spriteIndexHint)
{
// ret sprite
Sprite *retSprite = 0;
// look for already existing sprites
retSprite = getSpriteChild(spriteIndexHint);
if (!retSprite)
{
retSprite = getSpriteForLetter(theChar);
if (!retSprite)
return nullptr;
if (retSprite)
retSprite->setTag(spriteIndexHint);
_spriteArray.addObject(retSprite);
}
// the sprite is now visible
retSprite->setVisible(true);
// set the right texture letter to the sprite
updateSpriteForLetter(retSprite, theChar);
// we are done here
return retSprite;
}
float StringTTF::getLetterPosXLeft( Sprite* sp )
{
float scaleX = _scaleX;
return sp->getPosition().x * scaleX - (sp->getContentSize().width * scaleX * sp->getAnchorPoint().x);
}
float StringTTF::getLetterPosXRight( Sprite* sp )
{
float scaleX = _scaleX;
return sp->getPosition().x * scaleX + (sp->getContentSize().width * scaleX * sp->getAnchorPoint().x);
}
int StringTTF::getCommonLineHeight()
{
return _commonLineHeight;
}
int StringTTF::getKerningForCharsPair(unsigned short first, unsigned short second)
{
return 0;
}
int StringTTF::getXOffsetForChar(unsigned short c)
{
FontLetterDefinition tempDefinition;
bool validDefinition = _fontAtlas->getLetterDefinitionForChar(c, tempDefinition);
if (!validDefinition)
return -1;
return (tempDefinition.offsetX);
}
int StringTTF::getYOffsetForChar(unsigned short c)
{
FontLetterDefinition tempDefinition;
bool validDefinition = _fontAtlas->getLetterDefinitionForChar(c, tempDefinition);
if (!validDefinition)
return -1;
return (tempDefinition.offsetY);
}
int StringTTF::getAdvanceForChar(unsigned short c, int hintPositionInString)
{
if (_advances)
{
// not that advance contains the X offset already
FontLetterDefinition tempDefinition;
bool validDefinition = _fontAtlas->getLetterDefinitionForChar(c, tempDefinition);
if (!validDefinition)
return -1;
return (_advances[hintPositionInString].width - tempDefinition.offsetX);
}
else
{
return -1;
}
}
Rect StringTTF::getRectForChar(unsigned short c)
{
return _fontAtlas->getFont().getRectForChar(c);
}
// string related stuff
int StringTTF::getStringNumLines()
{
int quantityOfLines = 1;
unsigned int stringLen = _currentUTF8String ? cc_wcslen(_currentUTF8String) : 0;
if (stringLen == 0)
return (-1);
// count number of lines
for (unsigned int i = 0; i < stringLen - 1; ++i)
{
unsigned short c = _currentUTF8String[i];
if (c == '\n')
{
quantityOfLines++;
}
}
return quantityOfLines;
}
int StringTTF::getStringLenght()
{
return _currentUTF8String ? cc_wcslen(_currentUTF8String) : 0;
}
unsigned short StringTTF::getCharAtStringPosition(int position)
{
return _currentUTF8String[position];
}
unsigned short * StringTTF::getUTF8String()
{
return _currentUTF8String;
}
void StringTTF::assignNewUTF8String(unsigned short *newString)
{
setCurrentString(newString);
}
TextHAlignment StringTTF::getTextAlignment()
{
return _alignment;
}
// label related stuff
float StringTTF::getMaxLineWidth()
{
return _width;
}
bool StringTTF::breakLineWithoutSpace()
{
return _lineBreakWithoutSpaces;
}
Size StringTTF::getLabelContentSize()
{
return getContentSize();
}
void StringTTF::setLabelContentSize(const Size &newSize)
{
setContentSize(newSize);
}
// RGBA protocol
bool StringTTF::isOpacityModifyRGB() const
{
return false;
}
void StringTTF::setOpacityModifyRGB(bool isOpacityModifyRGB)
{
}
unsigned char StringTTF::getOpacity() const
{
return 0;
}
unsigned char StringTTF::getDisplayedOpacity() const
{
return 0;
}
void StringTTF::setOpacity(GLubyte opacity)
{
}
void StringTTF::updateDisplayedOpacity(GLubyte parentOpacity)
{
}
bool StringTTF::isCascadeOpacityEnabled() const
{
return false;
}
void StringTTF::setCascadeOpacityEnabled(bool cascadeOpacityEnabled)
{
}
const Color3B& StringTTF::getColor(void) const
{
return _realColor;
}
const Color3B& StringTTF::getDisplayedColor() const
{
return _displayedColor;
}
void StringTTF::setColor(const Color3B& color)
{
_displayedColor = _realColor = color;
if( _cascadeColorEnabled )
{
Color3B parentColor = Color3B::WHITE;
RGBAProtocol* pParent = dynamic_cast<RGBAProtocol*>(_parent);
if (pParent && pParent->isCascadeColorEnabled())
parentColor = pParent->getDisplayedColor();
updateDisplayedColor(parentColor);
}
}
void StringTTF::updateDisplayedColor(const Color3B& parentColor)
{
_displayedColor.r = _realColor.r * parentColor.r/255.0;
_displayedColor.g = _realColor.g * parentColor.g/255.0;
_displayedColor.b = _realColor.b * parentColor.b/255.0;
Object* pObj;
CCARRAY_FOREACH(_children, pObj)
{
Sprite *item = static_cast<Sprite*>( pObj );
item->updateDisplayedColor(_displayedColor);
}
}
bool StringTTF::isCascadeColorEnabled() const
{
return false;
}
void StringTTF::setCascadeColorEnabled(bool cascadeColorEnabled)
{
_cascadeColorEnabled = cascadeColorEnabled;
}
NS_CC_END

View File

@ -1,146 +0,0 @@
/****************************************************************************
Copyright (c) 2013 Zynga 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 _StringTTF_h
#define _StringTTF_h
#include "CCFontDefinition.h"
#include "CCLabelTextFormatProtocol.h"
#include "CCLabel.h"
#include "CCFontAtlas.h"
NS_CC_BEGIN
class CC_DLL StringTTF : public Label, public LabelTextFormatProtocol
{
public:
static StringTTF* create(FontAtlas *pAtlas, TextHAlignment alignment = TextHAlignment::LEFT, int lineSize = 0);
// main interface
bool setText(const char *stringToRender, float lineWidth, TextHAlignment alignment = TextHAlignment::LEFT, bool lineBreakWithoutSpaces = false);
void setString(const char *stringToRender);
const char* getString() const { return "not implemented"; }
virtual void setAlignment(TextHAlignment alignment);
virtual void setWidth(float width);
virtual void setLineBreakWithoutSpace(bool breakWithoutSpace);
virtual void setScale(float scale);
virtual void setScaleX(float scaleX);
virtual void setScaleY(float scaleY);
// RGBAProtocol
virtual bool isOpacityModifyRGB() const;
virtual void setOpacityModifyRGB(bool isOpacityModifyRGB);
virtual unsigned char getOpacity() const;
virtual unsigned char getDisplayedOpacity() const;
virtual void setOpacity(GLubyte opacity);
virtual void updateDisplayedOpacity(GLubyte parentOpacity);
virtual bool isCascadeOpacityEnabled() const;
virtual void setCascadeOpacityEnabled(bool cascadeOpacityEnabled);
virtual const Color3B& getColor(void) const;
virtual const Color3B& getDisplayedColor() const;
virtual void setColor(const Color3B& color);
virtual void updateDisplayedColor(const Color3B& parentColor);
virtual bool isCascadeColorEnabled() const;
virtual void setCascadeColorEnabled(bool cascadeColorEnabled);
// CCLabelTextFormat protocol implementation
// sprite related stuff
virtual Sprite * getSpriteChild(int ID);
virtual Array * getChildrenLetters();
virtual Sprite * getSpriteForChar(unsigned short int theChar, int spriteIndexHint);
virtual float getLetterPosXLeft( Sprite* sp );
virtual float getLetterPosXRight( Sprite* sp );
// font related stuff
virtual int getCommonLineHeight();
virtual int getKerningForCharsPair(unsigned short first, unsigned short second);
virtual int getXOffsetForChar(unsigned short c);
virtual int getYOffsetForChar(unsigned short c);
virtual int getAdvanceForChar(unsigned short c, int hintPositionInString);
virtual Rect getRectForChar(unsigned short c) ;
// string related stuff
virtual int getStringNumLines();
virtual int getStringLenght();
virtual unsigned short getCharAtStringPosition(int position);
virtual unsigned short * getUTF8String();
virtual void assignNewUTF8String(unsigned short *newString);
virtual TextHAlignment getTextAlignment();
// label related stuff
virtual float getMaxLineWidth() ;
virtual bool breakLineWithoutSpace();
virtual Size getLabelContentSize();
virtual void setLabelContentSize(const Size &newSize);
private:
//
StringTTF(FontAtlas *pAtlas, TextHAlignment alignment = TextHAlignment::LEFT);
~StringTTF();
bool init();
void alignText();
void hideAllLetters();
void moveAllSpritesToCache();
bool computeAdvancesForString(unsigned short int *stringToRender);
bool setCurrentString(unsigned short *stringToSet);
bool setOriginalString(unsigned short *stringToSet);
void resetCurrentString();
Sprite * getSprite();
Sprite * createNewSpriteFromLetterDefinition(FontLetterDefinition &theDefinition, Texture2D *theTexture);
Sprite * updateSpriteWithLetterDefinition(Sprite *spriteToUpdate, FontLetterDefinition &theDefinition, Texture2D *theTexture);
Sprite * getSpriteForLetter(unsigned short int newLetter);
Sprite * updateSpriteForLetter(Sprite *spriteToUpdate, unsigned short int newLetter);
Array _spriteArray;
Array _spriteArrayCache;
float _commonLineHeight;
bool _lineBreakWithoutSpaces;
float _width;
TextHAlignment _alignment;
unsigned short int * _currentUTF8String;
unsigned short int * _originalUTF8String;
Size * _advances;
FontAtlas * _fontAtlas;
Color3B _displayedColor;
Color3B _realColor;
bool _cascadeColorEnabled;
};
NS_CC_END
#endif

View File

@ -30,7 +30,7 @@
#include "cocos2d.h"
#include "CCTextImage.h"
#include "CCFontFreeType.h"
#include "CCFontRenderFreeType.h"
#include "CCFont.h"
NS_CC_BEGIN
@ -91,8 +91,6 @@ bool TextPageDef::generatePageTexture(bool releasePageData)
int dataLenght = (_width * _height * 4);
bool textureCreated = _pageTexture->initWithData(_pageData, dataLenght, Texture2D::PixelFormat::RGBA8888, _width, _height, imageSize);
// _pageTexture->setPremultipliedAlpha(true);
// release the page data if requested
if ( releasePageData && textureCreated )
{
@ -132,7 +130,7 @@ TextFontPagesDef::~TextFontPagesDef()
}
}
TextImage::TextImage(): _font(0), _fontRender(0), _fontPages(0)
TextImage::TextImage(): _font(0), _fontPages(0)
{
}
@ -143,37 +141,38 @@ TextImage::~TextImage()
if (_font)
_font->release();
if (_fontRender)
delete _fontRender;
}
bool TextImage::initWithString(const char * pText, int nWidth, int nHeight, const char * pFontName, int nSize, bool releaseRAWData)
bool TextImage::initWithString(const char *text, int nWidth, int nHeight, cocos2d::Font* font, bool releaseRAWData)
{
// carloX
bool textIsUTF16 = false;
// create the reference to the font we want to use
if ( !createFontRef(pFontName, nSize) )
return 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(pText) )
if ( !generateTextGlyphs(text) )
return false;
Size constrainSize;
unsigned short int *strUTF16 = 0;
int stringNumChars;
int stringNumChars;
if ( textIsUTF16 )
{
strUTF16 = (unsigned short int *)pText;
strUTF16 = (unsigned short int *)text;
stringNumChars = cc_wcslen(strUTF16);
}
else
{
// string needs to go to unicode
strUTF16 = _font->getUTF16Text(pText, stringNumChars);
strUTF16 = _font->getUTF16Text(text, stringNumChars);
}
if (!strUTF16 || !stringNumChars)
@ -189,6 +188,8 @@ bool TextImage::initWithString(const char * pText, int nWidth, int nHeight, cons
// actually create the needed images
return createImageDataFromPages(_fontPages, releaseRAWData);
return true;
}
bool TextImage::createPageDefinitions(unsigned short int *inText, int imageWidth, int imageHeight, int lineHeight)
@ -321,48 +322,6 @@ int TextImage::getNumGlyphsFittingInSize(std::map<unsigned short int, GlyphDef>
return numChar;
}
bool TextImage::createFontRef(const char *fontName, int fontSize)
{
if (_font)
{
_font->release();
_font = 0;
}
// carloX
_font = new FontFreeType();
if (!_font)
return false;
_font->retain();
if( !_font->createFontObject(fontName, fontSize))
return false;
return true;
}
bool TextImage::createFontRender()
{
if (!_font)
return false;
if (_fontRender)
{
delete _fontRender;
_fontRender = 0;
}
// carloX
_fontRender = new FontRenderFreeType(_font);
if (!_fontRender)
return false;
return true;
}
bool TextImage::addGlyphsToLine(TextLineDef *line, const char *lineText, bool textIsUTF16)
{
if (!_font)
@ -445,19 +404,104 @@ bool TextImage::createImageDataFromPages(TextFontPagesDef *thePages, bool releas
unsigned char * TextImage::preparePageGlyphData(TextPageDef *thePage)
{
if ( !_fontRender )
return renderGlyphData(thePage);
}
unsigned char * TextImage::renderGlyphData(TextPageDef *thePage)
{
if (!thePage)
return 0;
if (!_font)
return 0;
if (thePage->getNumLines() == 0)
return NULL;
int pageWidth = thePage->getWidth();
int pageHeight = thePage->getHeight();
// prepare memory and clean to 0
int sizeInBytes = (pageWidth * pageHeight * 4);
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)
{
createFontRender();
TextLineDef *pCurrentLine = thePage->getLineAt(c);
float origX = _font->getLetterPadding();
float origY = pCurrentLine->getY();
int numGlyphToRender = pCurrentLine->getNumGlyph();
for (int cglyph = 0; cglyph < numGlyphToRender; ++cglyph)
{
GlyphDef currGlyph = pCurrentLine->getGlyphAt(cglyph);
renderCharAt(currGlyph.getUTF8Letter(), origX, origY, data, pageWidth);
origX += (currGlyph.getRect().size.width + _font->getLetterPadding());
}
}
if (_fontRender)
#ifdef _DEBUG_FONTS_
static int counter = 0;
char outFilename[512];
sprintf(outFilename,"testIMG%d", counter);
++counter;
Image *pImage = new Image;
pImage->initWithRawData(data, (pageWidth * pageWidth * 4), 1024, 1024, 8, false);
pImage->saveToFile(outFilename);
#endif
// we are done here
return data;
}
bool TextImage::renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize)
{
if (!_font)
return false;
unsigned char *sourceBitmap = 0;
int sourceWidth = 0;
int sourceHeight = 0;
// get the glyph's bitmap
sourceBitmap = _font->getGlyphBitmap(charToRender, sourceWidth, sourceHeight);
if(!sourceBitmap)
return false;
int iX = posX;
int iY = posY;
for (int y = 0; y < sourceHeight; ++y)
{
return _fontRender->preparePageGlyphData(thePage);
}
else
{
return 0;
int bitmap_y = y * sourceWidth;
for (int x = 0; x < sourceWidth; ++x)
{
unsigned char cTemp = sourceBitmap[bitmap_y + x];
// the final pixel
int iTemp = cTemp << 24 | cTemp << 16 | cTemp << 8 | cTemp;
*(int*) &destMemory[(iX + ( iY * destSize ) ) * 4] = iTemp;
iX += 1;
}
iX = posX;
iY += 1;
}
//everything good
return true;
}
NS_CC_END

View File

@ -25,11 +25,13 @@
#ifndef _TextImage_h_
#define _TextImage_h_
#include "CCFontRender.h"
#include "CCFont.h"
//#include "CCFont.h"
#include <vector>
NS_CC_BEGIN
class Font;
/** @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
@ -161,27 +163,27 @@ public:
TextImage();
~TextImage();
bool initWithString(const char *pText, int nWidth, int nHeight, const char * pFontName, int nSize, bool releaseRAWData = true);
bool initWithString(const char *text, int nWidth, int nHeight, Font* font, bool releaseRAWData = true);
TextFontPagesDef * getPages() { return _fontPages; }
Font * getFont() { return _font; }
private:
unsigned char * preparePageGlyphData(TextPageDef *thePage);
bool createImageDataFromPages(TextFontPagesDef *thePages, bool releaseRAWData = true);
bool createFontRender();
bool addGlyphsToLine(TextLineDef *line, const char *lineText, bool textIsUTF16 = false);
bool createFontRef(const char *fontName, int size);
bool generateTextGlyphs(const char * pText);
int getNumGlyphsFittingInSize(std::map<unsigned short int, GlyphDef> &glyphDefs, unsigned short int *strUTF8, Font *pFont, 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);
bool renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize);
std::map<unsigned short int, GlyphDef> _textGlyphs;
TextFontPagesDef * _fontPages;
Font * _font;
FontRender * _fontRender;
Font * _font;
};

View File

@ -1,442 +0,0 @@
/****************************************************************************
Copyright (c) 2010 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#define __CC_PLATFORM_IMAGE_CPP__
#include "platform/CCImageCommon_cpp.h"
#include <string.h>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include "platform/CCImage.h"
#include "platform/CCFileUtils.h"
#include "platform/CCCommon.h"
#include "CCStdC.h"
#include "ft2build.h"
#include FT_FREETYPE_H
#define szFont_kenning 2
#define SHIFT6(num) (num>>6)
using namespace std;
struct TextLine {
int iLineWidth;
wchar_t* text;
};
NS_CC_BEGIN
class BitmapDC
{
public:
BitmapDC()
{
libError = FT_Init_FreeType( &library );
iInterval = szFont_kenning;
_data = NULL;
reset();
}
~BitmapDC(void)
{
FT_Done_FreeType(library);
}
void reset() {
iMaxLineWidth = 0;
iMaxLineHeight = 0;
size_t size = vLines.size();
for (int i=0; i<size; ++i) {
TextLine line = vLines[i];
free(line.text);
}
vLines.clear();
}
int utf8(char **p)
{
if ((**p & 0x80) == 0x00)
{
int a = *((*p)++);
return a;
}
if ((**p & 0xE0) == 0xC0)
{
int a = *((*p)++) & 0x1F;
int b = *((*p)++) & 0x3F;
return (a << 6) | b;
}
if ((**p & 0xF0) == 0xE0)
{
int a = *((*p)++) & 0x0F;
int b = *((*p)++) & 0x3F;
int c = *((*p)++) & 0x3F;
return (a << 12) | (b << 6) | c;
}
if ((**p & 0xF8) == 0xF0)
{
int a = *((*p)++) & 0x07;
int b = *((*p)++) & 0x3F;
int c = *((*p)++) & 0x3F;
int d = *((*p)++) & 0x3F;
return (a << 18) | (b << 12) | (c << 8) | d;
}
return 0;
}
void buildLine(wchar_t* buf, size_t buf_len, FT_Face face, int iCurXCursor, FT_UInt cLastChar) {
TextLine oTempLine;
wchar_t* text = (wchar_t*)malloc(sizeof(wchar_t) * (buf_len+1));
memcpy(text, buf, sizeof(wchar_t) * buf_len);
text[buf_len] = '\0';
oTempLine.text = text;
//get last glyph
int iError = FT_Load_Char(face, cLastChar, FT_LOAD_DEFAULT);
oTempLine.iLineWidth = iCurXCursor - SHIFT6((face->glyph->metrics.horiAdvance - face->glyph->metrics.horiBearingX - face->glyph->metrics.width))/*-iInterval*/;//TODO interval
iMaxLineWidth = MAX(iMaxLineWidth, oTempLine.iLineWidth);
vLines.push_back(oTempLine);
}
bool divideString(FT_Face face, const char* sText, int iMaxWidth, int iMaxHeight) {
int iError = 0;
int iCurXCursor, iCurYCursor;
const char* pText = sText;
FT_UInt unicode = utf8((char**)&pText);
iError = FT_Load_Char(face, unicode, FT_LOAD_DEFAULT);
if (iError) {
return false;
}
iCurXCursor = -SHIFT6(face->glyph->metrics.horiBearingX);
FT_UInt cLastCh = 0;
pText = sText;
size_t text_len = 0;
wchar_t* text_buf = (wchar_t*) malloc(sizeof(wchar_t) * strlen(sText));
while (unicode=utf8((char**)&pText)) {
if (unicode == '\n') {
buildLine(text_buf, text_len, face, iCurXCursor, cLastCh);
text_len = 0;
iError = FT_Load_Char(face, unicode, FT_LOAD_DEFAULT);
if (iError) {
free(text_buf);
return false;
}
iCurXCursor = -SHIFT6(face->glyph->metrics.horiBearingX);
continue;
}
iError = FT_Load_Char(face, unicode, FT_LOAD_DEFAULT);
if (iError) {
free(text_buf);
return false;
}
//check its width
//divide it when exceeding
if ((iMaxWidth > 0
&& iCurXCursor + SHIFT6(face->glyph->metrics.width)
> iMaxWidth)) {
buildLine(text_buf, text_len, face , iCurXCursor, cLastCh);
text_len = 0;
iCurXCursor = -SHIFT6(face->glyph->metrics.horiBearingX);
}
cLastCh = unicode;
text_buf[text_len] = unicode;
++text_len;
iCurXCursor += SHIFT6(face->glyph->metrics.horiAdvance) + iInterval;
}
if (iError) {
free(text_buf);
return false;
}
buildLine(text_buf, text_len, face, iCurXCursor, cLastCh);
free(text_buf);
return true;
}
/**
* compute the start pos of every line
*
* return >0 represent the start x pos of the line
* while -1 means fail
*
*/
int computeLineStart(FT_Face face, Image::TextAlign eAlignMask, char cText,
int iLineIndex) {
int iRet;
int iError = FT_Load_Glyph(face, FT_Get_Char_Index(face, cText),
FT_LOAD_DEFAULT);
if (iError) {
return -1;
}
if (eAlignMask == Image::kAlignCenter) {
iRet = (iMaxLineWidth - vLines[iLineIndex].iLineWidth) / 2
- SHIFT6(face->glyph->metrics.horiBearingX );
} else if (eAlignMask == Image::kAlignRight) {
iRet = (iMaxLineWidth - vLines[iLineIndex].iLineWidth)
- SHIFT6(face->glyph->metrics.horiBearingX );
} else {
// left or other situation
iRet = -SHIFT6(face->glyph->metrics.horiBearingX );
}
return iRet;
}
int computeLineStartY( FT_Face face, Image::TextAlign eAlignMask, int txtHeight, int borderHeight ){
int iRet;
if (eAlignMask == Image::kAlignCenter || eAlignMask == Image::kAlignLeft ||
eAlignMask == Image::kAlignRight ) {
//vertical center
iRet = (borderHeight - txtHeight)/2 + SHIFT6(face->size->metrics.ascender);
} else if (eAlignMask == Image::kAlignBottomRight ||
eAlignMask == Image::kAlignBottom ||
eAlignMask == Image::kAlignBottomLeft ) {
//vertical bottom
iRet = borderHeight - txtHeight + SHIFT6(face->size->metrics.ascender);
} else {
// left or other situation
iRet = SHIFT6(face->size->metrics.ascender);
}
return iRet;
}
bool getBitmap(const char *text, int nWidth, int nHeight, Image::TextAlign eAlignMask, const char * pFontName, float fontSize) {
FT_Face face;
FT_Error iError;
const char* pText = text;
//data will be deleted by Image
// if (_data) {
// delete _data;
// }
int iCurXCursor, iCurYCursor;
bool bRet = false;
if (libError) {
return false;
}
do {
//CCLog(" ---- FT_New_Face with pFontName = %s", pFontName);
iError = FT_New_Face( library, pFontName, 0, &face );
if (iError) {
//no valid font found use default
//CCLog(" ---- no valid font, use default %s", pFontName);
iError = FT_New_Face( library, "/usr/fonts/font_repository/monotype/arial.ttf", 0, &face );
}
CC_BREAK_IF(iError);
//select utf8 charmap
iError = FT_Select_Charmap(face,FT_ENCODING_UNICODE);
CC_BREAK_IF(iError);
iError = FT_Set_Pixel_Sizes(face, fontSize,fontSize);
CC_BREAK_IF(iError);
iError = divideString(face, text, nWidth, nHeight)?0:1;
//compute the final line width
iMaxLineWidth = MAX(iMaxLineWidth, nWidth);
iMaxLineHeight = (face->size->metrics.ascender >> 6)
- (face->size->metrics.descender >> 6);
iMaxLineHeight *= vLines.size();
int txtHeight = iMaxLineHeight;
//compute the final line height
iMaxLineHeight = MAX(iMaxLineHeight, nHeight);
_data = new unsigned char[iMaxLineWidth * iMaxLineHeight*4];
// iCurYCursor = SHIFT6(face->size->metrics.ascender);
iCurYCursor = computeLineStartY( face, eAlignMask, txtHeight, iMaxLineHeight );
memset(_data,0, iMaxLineWidth * iMaxLineHeight*4);
size_t lines = vLines.size();
for (size_t i = 0; i < lines; i++) {
const wchar_t* text_ptr = vLines[i].text;
//initialize the origin cursor
iCurXCursor = computeLineStart(face, eAlignMask, text_ptr[0], i);
size_t text_len = wcslen(text_ptr);
for (size_t i=0; i<text_len; ++i) {
int iError = FT_Load_Char(face, text_ptr[i], FT_LOAD_RENDER);
if (iError) {
break;
}
// convert glyph to bitmap with 256 gray
// and get the bitmap
FT_Bitmap& bitmap = face->glyph->bitmap;
int yoffset = iCurYCursor - (face->glyph->metrics.horiBearingY >> 6);
int xoffset = iCurXCursor + (face->glyph->metrics.horiBearingX >> 6);
for (int i = 0; i < bitmap.rows; ++i) {
for (int j = 0; j < bitmap.width; ++j) {
unsigned char cTemp = bitmap.buffer[i * bitmap.width + j];
if (cTemp == 0) continue;
// if it has gray>0 we set show it as 1, o otherwise
int iY = yoffset + i;
int iX = xoffset + j;
if (iY>=iMaxLineHeight) {
//exceed the height truncate
continue;
}
// _data[(iY * iMaxLineWidth + iX) * 4 + 3] =
// bitmap.buffer[i * bitmap.width + j] ?
// 0xff : 0;//alpha
// _data[(iY * iMaxLineWidth + iX) * 4 + 1] =
// bitmap.buffer[i * bitmap.width + j];//R
// _data[(iY * iMaxLineWidth + iX) * 4 + 2] =
// bitmap.buffer[i * bitmap.width + j];//G
// _data[(iY * iMaxLineWidth + iX) * 4 + 0] =
// bitmap.buffer[i * bitmap.width + j];//B
int iTemp = cTemp << 24 | cTemp << 16 | cTemp << 8 | cTemp;
*(int*) &_data[(iY * iMaxLineWidth + iX) * 4 + 0] = iTemp;
}
}
//step to next glyph
iCurXCursor += (face->glyph->metrics.horiAdvance >> 6)
+ iInterval;
pText++;
}
iCurYCursor += (face->size->metrics.ascender >> 6)
- (face->size->metrics.descender >> 6);
}
//print all image bitmap
// for (int i = 0; i < iMaxLineHeight; i++) {
// for (int j = 0; j < iMaxLineWidth; j++) {
// printf("%d",
// _data[(i * iMaxLineWidth + j) * 4] ? 1 : 0);
// }
// printf("\n");
// }
// free face
FT_Done_Face(face);
face = NULL;
//clear all lines
vLines.clear();
//success;
if (iError) {
bRet = false;
} else
bRet = true;
}while(0);
return bRet;
}
public:
FT_Library library;
unsigned char *_data;
int libError;
vector<TextLine> vLines;
int iInterval;
int iMaxLineWidth;
int iMaxLineHeight;
};
static BitmapDC& sharedBitmapDC()
{
static BitmapDC s_BmpDC;
return s_BmpDC;
}
bool Image::initWithString(
const char * pText,
int nWidth/* = 0*/,
int nHeight/* = 0*/,
TextAlign eAlignMask/* = kAlignCenter*/,
const char * pFontName/* = nil*/,
int nSize/* = 0*/)
{
bool bRet = false;
do
{
CC_BREAK_IF(! pText);
BitmapDC &dc = sharedBitmapDC();
std::string fullFontName = pFontName;
std::string lowerCasePath = fullFontName;
std::transform(lowerCasePath.begin(), lowerCasePath.end(), lowerCasePath.begin(), ::tolower);
if ( lowerCasePath.find(".ttf") != std::string::npos ) {
fullFontName = FileUtils::getInstance()->fullPathForFilename(pFontName);
}
//CCLog("-----pText=%s and Font File is %s nWidth= %d,nHeight=%d",pText,fullFontName.c_str(),nWidth,nHeight);
CC_BREAK_IF(! dc.getBitmap(pText, nWidth, nHeight, eAlignMask, fullFontName.c_str(), nSize));
//CCLog("---- dc.getBitmap is Succesfull...");
// assign the dc._data to _data in order to save time
_data = dc._data;
CC_BREAK_IF(! _data);
_width = (short)dc.iMaxLineWidth;
_height = (short)dc.iMaxLineHeight;
_preMulti = true;
_renderFormat = Texture2D::PixelFormat::RGBA8888;
bRet = true;
dc.reset();
} while (0);
return bRet;
}
NS_CC_END

View File

@ -52,18 +52,14 @@ SOURCES = ../actions/CCAction.cpp \
../label_nodes/CCFontAtlas.cpp \
../label_nodes/CCFontAtlasCache.cpp \
../label_nodes/CCFontAtlasFactory.cpp \
../label_nodes/CCFontCache.cpp \
../label_nodes/CCFontDefinition.cpp \
../label_nodes/CCFontFNT.cpp \
../label_nodes/CCFontFreeType.cpp \
../label_nodes/CCFontRenderFreeType.cpp \
../label_nodes/CCLabel.cpp \
../label_nodes/CCLabelAtlas.cpp \
../label_nodes/CCLabelBMFont.cpp \
../label_nodes/CCLabelTTF.cpp \
../label_nodes/CCLabelTextFormatter.cpp \
../label_nodes/CCStringBMFont.cpp \
../label_nodes/CCStringTTF.cpp \
../label_nodes/CCTextImage.cpp \
../layers_scenes_transitions_nodes/CCLayer.cpp \
../layers_scenes_transitions_nodes/CCScene.cpp \

View File

@ -49,18 +49,14 @@ SOURCES = ../actions/CCAction.cpp \
../label_nodes/CCFontAtlas.cpp \
../label_nodes/CCFontAtlasCache.cpp \
../label_nodes/CCFontAtlasFactory.cpp \
../label_nodes/CCFontCache.cpp \
../label_nodes/CCFontDefinition.cpp \
../label_nodes/CCFontFNT.cpp \
../label_nodes/CCFontFreeType.cpp \
../label_nodes/CCFontRenderFreeType.cpp \
../label_nodes/CCLabel.cpp \
../label_nodes/CCLabelAtlas.cpp \
../label_nodes/CCLabelBMFont.cpp \
../label_nodes/CCLabelTTF.cpp \
../label_nodes/CCLabelTextFormatter.cpp \
../label_nodes/CCStringBMFont.cpp \
../label_nodes/CCStringTTF.cpp \
../label_nodes/CCTextImage.cpp \
../layers_scenes_transitions_nodes/CCLayer.cpp \
../layers_scenes_transitions_nodes/CCScene.cpp \

View File

@ -178,18 +178,14 @@ xcopy /Y /Q "$(ProjectDir)..\platform\third_party\win32\libraries\*.*" "$(OutDir
<ClCompile Include="..\label_nodes\CCFontAtlas.cpp" />
<ClCompile Include="..\label_nodes\CCFontAtlasCache.cpp" />
<ClCompile Include="..\label_nodes\CCFontAtlasFactory.cpp" />
<ClCompile Include="..\label_nodes\CCFontCache.cpp" />
<ClCompile Include="..\label_nodes\CCFontDefinition.cpp" />
<ClCompile Include="..\label_nodes\CCFontFNT.cpp" />
<ClCompile Include="..\label_nodes\CCFontFreeType.cpp" />
<ClCompile Include="..\label_nodes\CCFontRenderFreeType.cpp" />
<ClCompile Include="..\label_nodes\CCLabel.cpp" />
<ClCompile Include="..\label_nodes\CCLabelAtlas.cpp" />
<ClCompile Include="..\label_nodes\CCLabelBMFont.cpp" />
<ClCompile Include="..\label_nodes\CCLabelTextFormatter.cpp" />
<ClCompile Include="..\label_nodes\CCLabelTTF.cpp" />
<ClCompile Include="..\label_nodes\CCStringBMFont.cpp" />
<ClCompile Include="..\label_nodes\CCStringTTF.cpp" />
<ClCompile Include="..\label_nodes\CCTextImage.cpp" />
<ClCompile Include="..\layers_scenes_transitions_nodes\CCLayer.cpp" />
<ClCompile Include="..\layers_scenes_transitions_nodes\CCScene.cpp" />
@ -334,16 +330,12 @@ xcopy /Y /Q "$(ProjectDir)..\platform\third_party\win32\libraries\*.*" "$(OutDir
<ClInclude Include="..\label_nodes\CCFontDefinition.h" />
<ClInclude Include="..\label_nodes\CCFontFNT.h" />
<ClInclude Include="..\label_nodes\CCFontFreeType.h" />
<ClInclude Include="..\label_nodes\CCFontRender.h" />
<ClInclude Include="..\label_nodes\CCFontRenderFreeType.h" />
<ClInclude Include="..\label_nodes\CCLabel.h" />
<ClInclude Include="..\label_nodes\CCLabelAtlas.h" />
<ClInclude Include="..\label_nodes\CCLabelBMFont.h" />
<ClInclude Include="..\label_nodes\CCLabelTextFormatProtocol.h" />
<ClInclude Include="..\label_nodes\CCLabelTextFormatter.h" />
<ClInclude Include="..\label_nodes\CCLabelTTF.h" />
<ClInclude Include="..\label_nodes\CCStringBMFont.h" />
<ClInclude Include="..\label_nodes\CCStringTTF.h" />
<ClInclude Include="..\label_nodes\CCTextImage.h" />
<ClInclude Include="..\layers_scenes_transitions_nodes\CCLayer.h" />
<ClInclude Include="..\layers_scenes_transitions_nodes\CCScene.h" />

View File

@ -485,9 +485,6 @@
<ClCompile Include="..\label_nodes\CCFontAtlasFactory.cpp">
<Filter>label_nodes</Filter>
</ClCompile>
<ClCompile Include="..\label_nodes\CCFontCache.cpp">
<Filter>label_nodes</Filter>
</ClCompile>
<ClCompile Include="..\label_nodes\CCFontDefinition.cpp">
<Filter>label_nodes</Filter>
</ClCompile>
@ -497,21 +494,12 @@
<ClCompile Include="..\label_nodes\CCFontFreeType.cpp">
<Filter>label_nodes</Filter>
</ClCompile>
<ClCompile Include="..\label_nodes\CCFontRenderFreeType.cpp">
<Filter>label_nodes</Filter>
</ClCompile>
<ClCompile Include="..\label_nodes\CCLabel.cpp">
<Filter>label_nodes</Filter>
</ClCompile>
<ClCompile Include="..\label_nodes\CCLabelTextFormatter.cpp">
<Filter>label_nodes</Filter>
</ClCompile>
<ClCompile Include="..\label_nodes\CCStringBMFont.cpp">
<Filter>label_nodes</Filter>
</ClCompile>
<ClCompile Include="..\label_nodes\CCStringTTF.cpp">
<Filter>label_nodes</Filter>
</ClCompile>
<ClCompile Include="..\label_nodes\CCTextImage.cpp">
<Filter>label_nodes</Filter>
</ClCompile>
@ -1018,12 +1006,6 @@
<ClInclude Include="..\label_nodes\CCFontFreeType.h">
<Filter>label_nodes</Filter>
</ClInclude>
<ClInclude Include="..\label_nodes\CCFontRender.h">
<Filter>label_nodes</Filter>
</ClInclude>
<ClInclude Include="..\label_nodes\CCFontRenderFreeType.h">
<Filter>label_nodes</Filter>
</ClInclude>
<ClInclude Include="..\label_nodes\CCLabel.h">
<Filter>label_nodes</Filter>
</ClInclude>
@ -1033,12 +1015,6 @@
<ClInclude Include="..\label_nodes\CCLabelTextFormatter.h">
<Filter>label_nodes</Filter>
</ClInclude>
<ClInclude Include="..\label_nodes\CCStringBMFont.h">
<Filter>label_nodes</Filter>
</ClInclude>
<ClInclude Include="..\label_nodes\CCStringTTF.h">
<Filter>label_nodes</Filter>
</ClInclude>
<ClInclude Include="..\label_nodes\CCTextImage.h">
<Filter>label_nodes</Filter>
</ClInclude>

View File

@ -142,7 +142,7 @@ void TextureCache::addImageAsync(const char *path, Object *target, SEL_CallFuncO
if (_asyncStructQueue == NULL)
{
_asyncStructQueue = new queue<AsyncStruct*>();
_imageInfoQueue = new queue<ImageInfo*>();
_imageInfoQueue = new queue<ImageInfo*>();
// create a new thread to load images
_loadingThread = new std::thread(&TextureCache::loadImage, this);

View File

@ -69,15 +69,6 @@ static std::function<Layer*()> createFunctions[] =
CL(LabelTTFAlignment),
CL(LabelBMFontBounds),
CL(TTFFontShadowAndStroke),
CL(NewLabelTTFTestLongLine),
// CL(NewLabelTTFTestUnicode),
CL(NewLabelTTFColorTest),
CL(NewLabelTTFFontsTest),
CL(NewLabelTTFAlignment),
CL(NewLabelTTFUnicode),
CL(NewLabelBMFontTest),
// CL(NewLabelFontDefTest),
// should be moved to another test
CL(Atlas1),
};
@ -357,12 +348,13 @@ LabelTTFAlignment::LabelTTFAlignment()
LabelTTF* ttf0 = LabelTTF::create("Alignment 0\nnew line", "Helvetica", 12,
Size(256, 32), TextHAlignment::LEFT);
ttf0->setPosition(Point(s.width/2,(s.height/6)*2));
ttf0->setAnchorPoint(Point(0.5f,0.5f));
this->addChild(ttf0);
LabelTTF* ttf1 = LabelTTF::create("Alignment 1\nnew line", "Helvetica", 12,
Size(245, 32), TextHAlignment::CENTER);
Size(245, 32), TextHAlignment::CENTER);
ttf1->setPosition(Point(s.width/2,(s.height/6)*3));
ttf1->setAnchorPoint(Point(0.5f,0.5f));
this->addChild(ttf1);
@ -452,7 +444,6 @@ void Atlas3::step(float dt)
LabelBMFont *label3 = (LabelBMFont*) getChildByTag(kTagBitmapAtlas3);
label3->setString(string);
}
std::string Atlas3::title()
@ -1620,321 +1611,3 @@ void LabelBMFontBounds::draw()
};
DrawPrimitives::drawPoly(vertices, 4, true);
}
LabelBMFontNewTest::LabelBMFontNewTest()
{
Size s = Director::getInstance()->getWinSize();
LayerColor *layer = LayerColor::create(Color4B(128,128,128,255));
addChild(layer, -10);
// LabelBMFont
label1 = StringBMFont::create("Testing Glyph Designer", "fonts/boundsTestFont.fnt");
addChild(label1);
label1->setPosition(Point(s.width/2, s.height/2));
}
void LabelBMFontNewTest::draw()
{
}
std::string LabelBMFontNewTest::title()
{
return "New LabelBMFont";
}
std::string LabelBMFontNewTest::subtitle()
{
return "Testing the new LabelBMFont";
}
///
//
// NewLabelTTFTestLongLine
//
NewLabelTTFTestLongLine::NewLabelTTFTestLongLine()
{
Size size = Director::getInstance()->getWinSize();
// Long sentence
auto label1 = Label::createWithTTF(LongSentencesExample, "fonts/arial.ttf", 28, GlyphCollection::NEHE, size.width);
label1->setPosition( Point(size.width/2, size.height/2) );
label1->setAnchorPoint(Point(0.5, 1.0));
addChild(label1);
}
std::string NewLabelTTFTestLongLine::title()
{
return "Label() using TTF";
}
std::string NewLabelTTFTestLongLine::subtitle()
{
return "Uses the new Label() with TTF. Testing auto-wrapping";
}
//
// NewLabelTTFColorTest
//
NewLabelTTFColorTest::NewLabelTTFColorTest()
{
Size size = Director::getInstance()->getWinSize();
// Green
auto label1 = Label::createWithTTF("Green", "fonts/arial.ttf", 35, GlyphCollection::NEHE, size.width);
label1->setPosition( Point(size.width/2, size.height/5 * 1.5) );
label1->setColor( Color3B::GREEN );
label1->setAnchorPoint(Point(0.5, 0.5));
addChild(label1);
// Red
auto label2 = Label::createWithTTF("Red", "fonts/arial.ttf", 35, GlyphCollection::NEHE, size.width);
label2->setPosition( Point(size.width/2, size.height/5 * 2.0) );
label2->setColor( Color3B::RED );
label2->setAnchorPoint(Point(0.5, 0.5));
addChild(label2);
// Blue
auto label3 = Label::createWithTTF("Blue", "fonts/arial.ttf", 35, GlyphCollection::NEHE, size.width);
label3->setPosition( Point(size.width/2, size.height/5 * 2.5) );
label3->setColor( Color3B::BLUE );
label3->setAnchorPoint(Point(0.5, 0.5));
addChild(label3);
}
std::string NewLabelTTFColorTest::title()
{
return "Label() using TTF with color";
}
std::string NewLabelTTFColorTest::subtitle()
{
return "Uses the new Label() with TTF. Testing Color";
}
//
// NewLabelTTFColorTest
//
NewLabelTTFAlignment::NewLabelTTFAlignment()
{
Size size = Director::getInstance()->getWinSize();
_label = Label::createWithTTF(LongSentencesExample, "fonts/arial.ttf", 45, GlyphCollection::NEHE, size.width);
_label->setPosition( Point(size.width/2, size.height/2) );
_label->setAnchorPoint(Point(0.5, 0.5));
Menu *menu = Menu::create(
MenuItemFont::create("Left", CC_CALLBACK_1(NewLabelTTFAlignment::setAlignmentLeft, this)),
MenuItemFont::create("Center", CC_CALLBACK_1(NewLabelTTFAlignment::setAlignmentCenter, this)),
MenuItemFont::create("Right", CC_CALLBACK_1(NewLabelTTFAlignment::setAlignmentRight, this)),
NULL);
menu->alignItemsVerticallyWithPadding(4);
menu->setPosition(Point(50, size.height / 4 ));
addChild(_label);
this->addChild(menu);
}
void NewLabelTTFAlignment::updateAlignment()
{
if (_label)
{
_label->setAlignment(_horizAlign);
}
}
void NewLabelTTFAlignment::setAlignmentLeft(Object* sender)
{
_horizAlign = TextHAlignment::LEFT;
this->updateAlignment();
}
void NewLabelTTFAlignment::setAlignmentCenter(Object* sender)
{
_horizAlign = TextHAlignment::CENTER;
this->updateAlignment();
}
void NewLabelTTFAlignment::setAlignmentRight(Object* sender)
{
_horizAlign = TextHAlignment::RIGHT;
this->updateAlignment();
}
std::string NewLabelTTFAlignment::title()
{
return "Label() using TTF alignment";
}
std::string NewLabelTTFAlignment::subtitle()
{
return "Uses the new Label() with TTF. Testing alignment";
}
//
// NewLabelTTF unicode test
//
NewLabelTTFUnicode::NewLabelTTFUnicode()
{
Dictionary *strings = Dictionary::createWithContentsOfFile("fonts/strings.xml");
const char *chinese = static_cast<String*>(strings->objectForKey("chinese1"))->_string.c_str();
//const char *russian = static_cast<String*>(strings->objectForKey("russian"))->_string.c_str();
//const char *spanish = static_cast<String*>(strings->objectForKey("spanish"))->_string.c_str();
//const char *japanese = static_cast<String*>(strings->objectForKey("japanese"))->_string.c_str();
Size size = Director::getInstance()->getWinSize();
float vStep = size.height/9;
float vSize = size.height;
// Spanish
auto label1 = Label::createWithTTF("Buen día, ¿cómo te llamas?", "fonts/arial.ttf", 45, GlyphCollection::ASCII, size.width);
label1->setPosition( Point(size.width/2, vSize - (vStep * 4.5)) );
label1->setAnchorPoint(Point(0.5, 0.5));
addChild(label1);
// German
auto label2 = Label::createWithTTF("In welcher Straße haben Sie gelebt?", "fonts/arial.ttf", 45, GlyphCollection::ASCII, size.width);
label2->setPosition( Point(size.width/2, vSize - (vStep * 5.5)) );
label2->setAnchorPoint(Point(0.5, 0.5));
addChild(label2);
// chinese
auto label3 = Label::createWithTTF(chinese, "fonts/wt021.ttf", 45, GlyphCollection::CUSTOM, size.width, chinese);
label3->setPosition( Point(size.width/2, vSize - (vStep * 6.5)) );
label3->setAnchorPoint(Point(0.5, 0.5));
addChild(label3);
}
std::string NewLabelTTFUnicode::title()
{
return "Label() using TTF with unicode";
}
std::string NewLabelTTFUnicode::subtitle()
{
return "Uses the new Label() with TTF. Testing unicode";
}
//
// NewLabelTTFFontsTest
//
NewLabelTTFFontsTest::NewLabelTTFFontsTest()
{
const char *ttfpaths[] = {
"fonts/A Damn Mess.ttf",
"fonts/Abberancy.ttf",
"fonts/Abduction.ttf",
"fonts/American Typewriter.ttf",
"fonts/Paint Boy.ttf",
"fonts/Schwarzwald Regular.ttf",
"fonts/Scissor Cuts.ttf",
};
#define arraysize(ar) (sizeof(ar) / sizeof(ar[0]))
Size size = Director::getInstance()->getWinSize();
for(int i=0;i < arraysize(ttfpaths); ++i) {
auto label = Label::createWithTTF( ttfpaths[i], ttfpaths[i], 40, GlyphCollection::NEHE);
if( label ) {
label->setPosition( Point(size.width/2, ((size.height * 0.6)/arraysize(ttfpaths) * i) + (size.height/5)));
addChild(label);
label->setAnchorPoint(Point(0.5, 0.5));
} else {
log("ERROR: Cannot load: %s", ttfpaths[i]);
}
}
}
std::string NewLabelTTFFontsTest::title()
{
return "Label() using different TTF files";
}
std::string NewLabelTTFFontsTest::subtitle()
{
//return "Uses the new Label() with non standard TTF files";
return "";
}
//
// NEW LABEL with BMFont
//
NewLabelBMFontTest::NewLabelBMFontTest()
{
Size size = Director::getInstance()->getWinSize();
auto label1 = Label::createWithBMFont("Hello World, this is testing the new Label using fnt file", "fonts/bitmapFontTest2.fnt", size.width);
label1->setPosition( Point(size.width/2, size.height/2) );
label1->setAnchorPoint(Point(0.5, 0.5));
addChild(label1);
}
std::string NewLabelBMFontTest::title()
{
return "Label() using BMFont";
}
std::string NewLabelBMFontTest::subtitle()
{
return "Uses the new Label() with BMFont";
}
//
/// NEW LABEL with BMFont
//
NewLabelBMFontTestOld::NewLabelBMFontTestOld()
{
Size size = Director::getInstance()->getWinSize();
label = Label::createWithBMFontOLD("Hello world, this uses new label with FTN file", "fonts/bitmapFontTest2.fnt", size.width);
label->setPosition( Point(size.width/2, size.height/2) );
label->setAnchorPoint(Point(0.5, 0.5));
label->retain();
addChild(label);
}
NewLabelBMFontTestOld::~NewLabelBMFontTestOld()
{
CC_SAFE_RELEASE(label);
}
std::string NewLabelBMFontTestOld::title()
{
return "Label() using BMFont OLD";
}
std::string NewLabelBMFontTestOld::subtitle()
{
return "Uses the new Label() with BMFont OLD";
}
//
// NEW LABEL with FontDefinition
//
NewLabelFontDefTest::NewLabelFontDefTest()
{
}
std::string NewLabelFontDefTest::title()
{
return "NOT IMPLEMENTED YET";
}
std::string NewLabelFontDefTest::subtitle()
{
return "NOT IMPLEMENTED YET";
}

View File

@ -316,38 +316,6 @@ private:
LabelBMFont *label1;
};
class LabelBMFontNewTest : public AtlasDemo
{
public:
LabelBMFontNewTest();
virtual void draw();
virtual std::string title();
virtual std::string subtitle();
private:
StringBMFont *label1;
};
class NewLabelTTFTestLongLine : public AtlasDemo
{
public:
NewLabelTTFTestLongLine();
virtual std::string title();
virtual std::string subtitle();
};
class NewLabelTTFColorTest : public AtlasDemo
{
public:
NewLabelTTFColorTest();
virtual std::string title();
virtual std::string subtitle();
};
class NewLabelTTFUnicode : public AtlasDemo
{
public:
@ -358,38 +326,6 @@ public:
virtual std::string subtitle();
};
class NewLabelTTFAlignment : public AtlasDemo
{
public:
NewLabelTTFAlignment();
virtual std::string title();
virtual std::string subtitle();
private:
void setAlignmentLeft(Object* sender);
void setAlignmentCenter(Object* sender);
void setAlignmentRight(Object* sender);
void updateAlignment();
Label * _label;
TextHAlignment _horizAlign;
};
class NewLabelTTFFontsTest : public AtlasDemo
{
public:
NewLabelTTFFontsTest();
virtual std::string title();
virtual std::string subtitle();
};
class NewLabelBMFontTest : public AtlasDemo
{
public:
@ -402,22 +338,6 @@ public:
private:
};
class NewLabelBMFontTestOld : public AtlasDemo
{
public:
NewLabelBMFontTestOld();
~NewLabelBMFontTestOld();
virtual std::string title();
virtual std::string subtitle();
private:
Label *label;
};
class NewLabelFontDefTest : public AtlasDemo
{
public:

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,282 @@
#ifndef _ATLAS_TEST_NEW_H_
#define _ATLAS_TEST_NEW_H_
#include "../testBasic.h"
#include "../BaseTest.h"
class AtlasDemoNew : public BaseTest
{
protected:
public:
AtlasDemoNew(void);
~AtlasDemoNew(void);
virtual std::string title();
virtual std::string subtitle();
virtual void onEnter();
void restartCallback(Object* sender);
void nextCallback(Object* sender);
void backCallback(Object* sender);
};
class LabelTTFAlignmentNew : public AtlasDemoNew
{
public:
LabelTTFAlignmentNew();
virtual std::string title();
virtual std::string subtitle();
};
class LabelFNTColorAndOpacity : public AtlasDemoNew
{
float _time;
public:
LabelFNTColorAndOpacity();
virtual void step(float dt);
virtual std::string title();
virtual std::string subtitle();
};
class LabelFNTSpriteActions : public AtlasDemoNew
{
float _time;
public:
LabelFNTSpriteActions();
virtual void step(float dt);
virtual void draw();
virtual std::string title();
virtual std::string subtitle();
};
class LabelFNTPadding : public AtlasDemoNew
{
public:
LabelFNTPadding();
virtual std::string title();
virtual std::string subtitle();
};
class LabelFNTOffset : public AtlasDemoNew
{
public:
LabelFNTOffset();
virtual std::string title();
virtual std::string subtitle();
};
class LabelFNTColor : public AtlasDemoNew
{
public:
LabelFNTColor();
virtual std::string title();
virtual std::string subtitle();
};
class LabelFNTHundredLabels : public AtlasDemoNew
{
public:
LabelFNTHundredLabels();
virtual std::string title();
virtual std::string subtitle();
};
class LabelFNTMultiLine : public AtlasDemoNew
{
public:
LabelFNTMultiLine();
virtual std::string title();
virtual std::string subtitle();
};
class LabelFNTandTTFEmpty : public AtlasDemoNew
{
public:
LabelFNTandTTFEmpty();
void updateStrings(float dt);
virtual std::string title();
virtual std::string subtitle();
private:
bool setEmpty;
};
class LabelFNTRetina : public AtlasDemoNew
{
public:
LabelFNTRetina();
virtual std::string title();
virtual std::string subtitle();
};
class LabelFNTGlyphDesigner : public AtlasDemoNew
{
public:
LabelFNTGlyphDesigner();
virtual std::string title();
virtual std::string subtitle();
};
class AtlasTestSceneNew : public TestScene
{
public:
virtual void runThisTest();
};
class LabelTTFUnicodeChinese : public AtlasDemoNew
{
public:
LabelTTFUnicodeChinese();
virtual std::string title();
virtual std::string subtitle();
};
class LabelFNTUnicodeChinese : public AtlasDemoNew
{
public:
LabelFNTUnicodeChinese();
virtual std::string title();
virtual std::string subtitle();
};
class LabelFNTMultiLineAlignment : public AtlasDemoNew
{
public:
LabelFNTMultiLineAlignment();
~LabelFNTMultiLineAlignment();
void snapArrowsToEdge();
virtual std::string title();
virtual std::string subtitle();
void stringChanged(Object *sender);
void alignmentChanged(Object *sender);
virtual void ccTouchesBegan(Set *touches, Event *event);
virtual void ccTouchesEnded(Set *touches, Event *event);
virtual void ccTouchesMoved(Set *touches, Event *event);
public:
Label *_labelShouldRetain;
Sprite *_arrowsBarShouldRetain;
Sprite *_arrowsShouldRetain;
MenuItemFont *_lastSentenceItem, *_lastAlignmentItem;
bool _drag;
};
class LabelFNTUNICODELanguages : public AtlasDemoNew
{
public:
LabelFNTUNICODELanguages();
virtual std::string title();
virtual std::string subtitle();
};
class LabelFNTBounds : public AtlasDemoNew
{
public:
LabelFNTBounds();
virtual void draw();
virtual std::string title();
virtual std::string subtitle();
private:
Label *label1;
};
class LabelTTFLongLineWrapping : public AtlasDemoNew
{
public:
LabelTTFLongLineWrapping();
virtual std::string title();
virtual std::string subtitle();
};
class LabelTTFColor : public AtlasDemoNew
{
public:
LabelTTFColor();
virtual std::string title();
virtual std::string subtitle();
};
class LabelTTFUnicodeNew : public AtlasDemoNew
{
public:
LabelTTFUnicodeNew();
virtual std::string title();
virtual std::string subtitle();
};
class LabelTTFDynamicAlignment : public AtlasDemoNew
{
public:
LabelTTFDynamicAlignment();
virtual std::string title();
virtual std::string subtitle();
private:
void setAlignmentLeft(Object* sender);
void setAlignmentCenter(Object* sender);
void setAlignmentRight(Object* sender);
void updateAlignment();
Label * _label;
TextHAlignment _horizAlign;
};
class LabelTTFFontsTestNew : public AtlasDemoNew
{
public:
LabelTTFFontsTestNew();
virtual std::string title();
virtual std::string subtitle();
};
class LabelBMFontTestNew : public AtlasDemoNew
{
public:
LabelBMFontTestNew();
virtual std::string title();
virtual std::string subtitle();
private:
};
class LabelFontDefTestNew : public AtlasDemoNew
{
public:
LabelFontDefTestNew();
virtual std::string title();
virtual std::string subtitle();
private:
};
// we don't support linebreak mode
#endif

View File

@ -56,6 +56,7 @@ struct {
{ "KeypadTest", []() { return new KeypadTestScene(); } },
#endif
{ "LabelTest", [](){return new AtlasTestScene(); } },
{ "LabelTestNew", [](){return new AtlasTestSceneNew(); } },
{ "LayerTest", [](){return new LayerTestScene();} },
{ "MenuTest", [](){return new MenuTestScene();} },
{ "MotionStreakTest", [](){return new MotionStreakTestScene();} },

View File

@ -20,6 +20,7 @@
#include "TileMapTest/TileMapTest.h"
#include "IntervalTest/IntervalTest.h"
#include "LabelTest/LabelTest.h"
#include "LabelTest/LabelTestNew.h"
#include "TextInputTest/TextInputTest.h"
#include "SpriteTest/SpriteTest.h"
#include "SchedulerTest/SchedulerTest.h"

View File

@ -65,6 +65,7 @@ SOURCES = ../Classes/AccelerometerTest/AccelerometerTest.cpp \
../Classes/KeyboardTest/KeyboardTest.cpp \
../Classes/KeypadTest/KeypadTest.cpp \
../Classes/LabelTest/LabelTest.cpp \
../Classes/LabelTest/LabelTestNew.cpp \
../Classes/LayerTest/LayerTest.cpp \
../Classes/MenuTest/MenuTest.cpp \
../Classes/MotionStreakTest/MotionStreakTest.cpp \

View File

@ -68,6 +68,7 @@ SOURCES = ../Classes/AccelerometerTest/AccelerometerTest.cpp \
../Classes/IntervalTest/IntervalTest.cpp \
../Classes/KeypadTest/KeypadTest.cpp \
../Classes/LabelTest/LabelTest.cpp \
../Classes/LabelTest/LabelTestNew.cpp \
../Classes/LayerTest/LayerTest.cpp \
../Classes/MenuTest/MenuTest.cpp \
../Classes/MotionStreakTest/MotionStreakTest.cpp \

View File

@ -156,6 +156,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\libwebsockets\win32\lib\*.*" "$(O
<ClCompile Include="..\Classes\ExtensionsTest\TableViewTest\CustomTableViewCell.cpp" />
<ClCompile Include="..\Classes\ExtensionsTest\TableViewTest\TableViewTestScene.cpp" />
<ClCompile Include="..\Classes\FileUtilsTest\FileUtilsTest.cpp" />
<ClCompile Include="..\Classes\LabelTest\LabelTestNew.cpp" />
<ClCompile Include="..\Classes\SpineTest\SpineTest.cpp" />
<ClCompile Include="..\Classes\TexturePackerEncryptionTest\TextureAtlasEncryptionTest.cpp" />
<ClCompile Include="..\Classes\VisibleRect.cpp" />
@ -265,6 +266,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\libwebsockets\win32\lib\*.*" "$(O
<ClInclude Include="..\Classes\ExtensionsTest\TableViewTest\CustomTableViewCell.h" />
<ClInclude Include="..\Classes\ExtensionsTest\TableViewTest\TableViewTestScene.h" />
<ClInclude Include="..\Classes\FileUtilsTest\FileUtilsTest.h" />
<ClInclude Include="..\Classes\LabelTest\LabelTestNew.h" />
<ClInclude Include="..\Classes\SpineTest\SpineTest.h" />
<ClInclude Include="..\Classes\TexturePackerEncryptionTest\TextureAtlasEncryptionTest.h" />
<ClInclude Include="..\Classes\VisibleRect.h" />

View File

@ -552,6 +552,9 @@
<ClCompile Include="..\Classes\ExtensionsTest\NetworkTest\SocketIOTest.cpp">
<Filter>Classes\ExtensionsTest\NetworkTest</Filter>
</ClCompile>
<ClCompile Include="..\Classes\LabelTest\LabelTestNew.cpp">
<Filter>Classes\LabelTest</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="main.h">
@ -1049,5 +1052,8 @@
<ClInclude Include="..\Classes\ExtensionsTest\NetworkTest\SocketIOTest.h">
<Filter>Classes\ExtensionsTest\NetworkTest</Filter>
</ClInclude>
<ClInclude Include="..\Classes\LabelTest\LabelTestNew.h">
<Filter>Classes\LabelTest</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@ -1 +1 @@
daaf13ab82feffbd1c8e201d76cb83ed8f2dabca
ca78185e84f3f44b992ff541f2b86e16ea08e830