CCFontFNT.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  1. /****************************************************************************
  2. Copyright (c) 2013 Zynga Inc.
  3. Copyright (c) 2013-2017 Chukong Technologies Inc.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. ****************************************************************************/
  21. #include "2d/CCFontFNT.h"
  22. #include "2d/CCFontAtlas.h"
  23. #include "platform/CCFileUtils.h"
  24. #include "base/CCConfiguration.h"
  25. #include "base/CCDirector.h"
  26. #include "base/CCMap.h"
  27. #include "base/ccUTF8.h"
  28. #include "renderer/CCTextureCache.h"
  29. #include <cmath>
  30. #include <set>
  31. #include <unordered_map>
  32. NS_CC_BEGIN
  33. /**
  34. * @addtogroup GUI
  35. * @{
  36. * @addtogroup label
  37. * @{
  38. */
  39. enum {
  40. kLabelAutomaticWidth = -1,
  41. };
  42. struct _FontDefHashElement;
  43. /**
  44. @struct BMFontDef
  45. BMFont definition
  46. */
  47. typedef struct _BMFontDef {
  48. //! ID of the character
  49. unsigned int charID;
  50. //! origin and size of the font
  51. Rect rect;
  52. //! The X amount the image should be offset when drawing the image (in pixels)
  53. short xOffset;
  54. //! The Y amount the image should be offset when drawing the image (in pixels)
  55. short yOffset;
  56. //! The amount to move the current position after drawing the character (in pixels)
  57. short xAdvance;
  58. } BMFontDef;
  59. /** @struct BMFontPadding
  60. BMFont padding
  61. @since v0.8.2
  62. */
  63. typedef struct _BMFontPadding {
  64. /// padding left
  65. int left;
  66. /// padding top
  67. int top;
  68. /// padding right
  69. int right;
  70. /// padding bottom
  71. int bottom;
  72. } BMFontPadding;
  73. /** @brief BMFontConfiguration has parsed configuration of the .fnt file
  74. @since v0.8
  75. */
  76. class CC_DLL BMFontConfiguration : public Ref
  77. {
  78. // FIXME: Creating a public interface so that the bitmapFontArray[] is accessible
  79. public://@public
  80. // BMFont definitions
  81. std::unordered_map<int /* key */, BMFontDef /* fontDef */> _fontDefDictionary;
  82. //! FNTConfig: Common Height Should be signed (issue #1343)
  83. int _commonHeight;
  84. //! Padding
  85. BMFontPadding _padding;
  86. //! atlas name
  87. std::string _atlasName;
  88. //! values for kerning
  89. std::unordered_map<uint64_t /* key */, int /* amount */> _kerningDictionary;
  90. // Character Set defines the letters that actually exist in the font
  91. std::set<unsigned int> *_characterSet;
  92. //! Font Size
  93. int _fontSize;
  94. public:
  95. /**
  96. * @js ctor
  97. */
  98. BMFontConfiguration();
  99. /**
  100. * @js NA
  101. * @lua NA
  102. */
  103. virtual ~BMFontConfiguration();
  104. /**
  105. * @js NA
  106. * @lua NA
  107. */
  108. std::string description() const;
  109. /** allocates a BMFontConfiguration with a FNT file */
  110. static BMFontConfiguration * create(const std::string& FNTfile);
  111. /** initializes a BitmapFontConfiguration with a FNT file */
  112. bool initWithFNTfile(const std::string& FNTfile);
  113. const std::string& getAtlasName() { return _atlasName; }
  114. void setAtlasName(const std::string& atlasName) { _atlasName = atlasName; }
  115. std::set<unsigned int>* getCharacterSet() const;
  116. private:
  117. std::set<unsigned int>* parseConfigFile(const std::string& controlFile);
  118. std::set<unsigned int>* parseBinaryConfigFile(unsigned char* pData, unsigned long size, const std::string& controlFile);
  119. unsigned int parseCharacterDefinition(const char* line);
  120. void parseInfoArguments(const char* line);
  121. void parseCommonArguments(const char* line);
  122. void parseImageFileName(const char* line, const std::string& fntFile);
  123. void parseKerningEntry(const char* line);
  124. void purgeKerningDictionary();
  125. void purgeFontDefDictionary();
  126. };
  127. //
  128. //FNTConfig Cache - free functions
  129. //
  130. static Map<std::string, BMFontConfiguration*>* s_configurations = nullptr;
  131. BMFontConfiguration* FNTConfigLoadFile(const std::string& fntFile)
  132. {
  133. BMFontConfiguration* ret = nullptr;
  134. if (s_configurations == nullptr)
  135. {
  136. s_configurations = new (std::nothrow) Map<std::string, BMFontConfiguration*>();
  137. }
  138. ret = s_configurations->at(fntFile);
  139. if( ret == nullptr )
  140. {
  141. ret = BMFontConfiguration::create(fntFile);
  142. if (ret)
  143. {
  144. s_configurations->insert(fntFile, ret);
  145. }
  146. }
  147. return ret;
  148. }
  149. //
  150. //BitmapFontConfiguration
  151. //
  152. BMFontConfiguration * BMFontConfiguration::create(const std::string& FNTfile)
  153. {
  154. BMFontConfiguration * ret = new (std::nothrow) BMFontConfiguration();
  155. if (ret->initWithFNTfile(FNTfile))
  156. {
  157. ret->autorelease();
  158. return ret;
  159. }
  160. CC_SAFE_DELETE(ret);
  161. return nullptr;
  162. }
  163. bool BMFontConfiguration::initWithFNTfile(const std::string& FNTfile)
  164. {
  165. _characterSet = this->parseConfigFile(FNTfile);
  166. if (! _characterSet)
  167. {
  168. return false;
  169. }
  170. return true;
  171. }
  172. std::set<unsigned int>* BMFontConfiguration::getCharacterSet() const
  173. {
  174. return _characterSet;
  175. }
  176. BMFontConfiguration::BMFontConfiguration()
  177. : _commonHeight(0)
  178. , _characterSet(nullptr)
  179. , _fontSize(0)
  180. {
  181. }
  182. BMFontConfiguration::~BMFontConfiguration()
  183. {
  184. CCLOGINFO( "deallocing BMFontConfiguration: %p", this );
  185. this->purgeFontDefDictionary();
  186. this->purgeKerningDictionary();
  187. _atlasName.clear();
  188. CC_SAFE_DELETE(_characterSet);
  189. }
  190. std::string BMFontConfiguration::description(void) const
  191. {
  192. return StringUtils::format(
  193. "<BMFontConfiguration = " CC_FORMAT_PRINTF_SIZE_T " | Glphys:%d Kernings:%d | Image = %s>",
  194. (size_t)this,
  195. static_cast<int>(_fontDefDictionary.size()),
  196. static_cast<int>(_kerningDictionary.size()),
  197. _atlasName.c_str()
  198. );
  199. }
  200. void BMFontConfiguration::purgeKerningDictionary()
  201. {
  202. _kerningDictionary.clear();
  203. }
  204. void BMFontConfiguration::purgeFontDefDictionary()
  205. {
  206. _fontDefDictionary.clear();
  207. }
  208. std::set<unsigned int>* BMFontConfiguration::parseConfigFile(const std::string& controlFile)
  209. {
  210. std::string data = FileUtils::getInstance()->getStringFromFile(controlFile);
  211. if (data.empty())
  212. {
  213. return nullptr;
  214. }
  215. if (data.size() >= (sizeof("BMP") - 1) && memcmp("BMF", data.c_str(), sizeof("BMP") - 1) == 0) {
  216. // Handle fnt file of binary format
  217. std::set<unsigned int>* ret = parseBinaryConfigFile((unsigned char*)&data.front(), data.size(), controlFile);
  218. return ret;
  219. }
  220. if (data[0] == 0)
  221. {
  222. CCLOG("cocos2d: Error parsing FNTfile %s", controlFile.c_str());
  223. return nullptr;
  224. }
  225. auto contents = data.c_str();
  226. std::set<unsigned int> *validCharsString = new (std::nothrow) std::set<unsigned int>();
  227. auto contentsLen = strlen(contents);
  228. char line[512] = {0};
  229. auto next = strchr(contents, '\n');
  230. auto base = contents;
  231. size_t lineLength = 0;
  232. size_t parseCount = 0;
  233. while (next)
  234. {
  235. lineLength = ((int)(next - base));
  236. memcpy(line, contents + parseCount, lineLength);
  237. line[lineLength] = 0;
  238. parseCount += lineLength + 1;
  239. if (parseCount < contentsLen)
  240. {
  241. base = next + 1;
  242. next = strchr(base, '\n');
  243. }
  244. else
  245. {
  246. next = nullptr;
  247. }
  248. if (memcmp(line, "info face", 9) == 0)
  249. {
  250. // FIXME: info parsing is incomplete
  251. // Not needed for the Hiero editors, but needed for the AngelCode editor
  252. // [self parseInfoArguments:line];
  253. this->parseInfoArguments(line);
  254. }
  255. // Check to see if the start of the line is something we are interested in
  256. else if (memcmp(line, "common lineHeight", 17) == 0)
  257. {
  258. this->parseCommonArguments(line);
  259. }
  260. else if (memcmp(line, "page id", 7) == 0)
  261. {
  262. this->parseImageFileName(line, controlFile);
  263. }
  264. else if (memcmp(line, "chars c", 7) == 0)
  265. {
  266. // Ignore this line
  267. }
  268. else if (memcmp(line, "char", 4) == 0)
  269. {
  270. // Parse the current line and create a new CharDef
  271. unsigned int charID = this->parseCharacterDefinition(line);
  272. validCharsString->insert(charID);
  273. }
  274. else if (memcmp(line, "kerning first", 13) == 0)
  275. {
  276. this->parseKerningEntry(line);
  277. }
  278. }
  279. return validCharsString;
  280. }
  281. std::set<unsigned int>* BMFontConfiguration::parseBinaryConfigFile(unsigned char* pData, unsigned long size, const std::string& controlFile)
  282. {
  283. /* based on http://www.angelcode.com/products/bmfont/doc/file_format.html file format */
  284. std::set<unsigned int> *validCharsString = new (std::nothrow) std::set<unsigned int>();
  285. unsigned long remains = size;
  286. CCASSERT(pData[3] == 3, "Only version 3 is supported");
  287. pData += 4; remains -= 4;
  288. while (remains > 0)
  289. {
  290. unsigned char blockId = pData[0]; pData += 1; remains -= 1;
  291. uint32_t blockSize = 0; memcpy(&blockSize, pData, 4);
  292. pData += 4; remains -= 4;
  293. if (blockId == 1)
  294. {
  295. /*
  296. fontSize 2 int 0
  297. bitField 1 bits 2 bit 0: smooth, bit 1: unicode, bit 2: italic, bit 3: bold, bit 4: fixedHeight, bits 5-7: reserved
  298. charSet 1 uint 3
  299. stretchH 2 uint 4
  300. aa 1 uint 6
  301. paddingUp 1 uint 7
  302. paddingRight 1 uint 8
  303. paddingDown 1 uint 9
  304. paddingLeft 1 uint 10
  305. spacingHoriz 1 uint 11
  306. spacingVert 1 uint 12
  307. outline 1 uint 13 added with version 2
  308. fontName n+1 string 14 null terminated string with length n
  309. */
  310. memcpy(&_fontSize, pData, 2);
  311. _padding.top = (unsigned char)pData[7];
  312. _padding.right = (unsigned char)pData[8];
  313. _padding.bottom = (unsigned char)pData[9];
  314. _padding.left = (unsigned char)pData[10];
  315. }
  316. else if (blockId == 2)
  317. {
  318. /*
  319. lineHeight 2 uint 0
  320. base 2 uint 2
  321. scaleW 2 uint 4
  322. scaleH 2 uint 6
  323. pages 2 uint 8
  324. bitField 1 bits 10 bits 0-6: reserved, bit 7: packed
  325. alphaChnl 1 uint 11
  326. redChnl 1 uint 12
  327. greenChnl 1 uint 13
  328. blueChnl 1 uint 14
  329. */
  330. uint16_t lineHeight = 0; memcpy(&lineHeight, pData, 2);
  331. _commonHeight = lineHeight;
  332. uint16_t scaleW = 0; memcpy(&scaleW, pData + 4, 2);
  333. uint16_t scaleH = 0; memcpy(&scaleH, pData + 6, 2);
  334. CCASSERT(scaleW <= Configuration::getInstance()->getMaxTextureSize() && scaleH <= Configuration::getInstance()->getMaxTextureSize(), "CCLabelBMFont: page can't be larger than supported");
  335. uint16_t pages = 0; memcpy(&pages, pData + 8, 2);
  336. CCASSERT(pages == 1, "CCBitfontAtlas: only supports 1 page");
  337. }
  338. else if (blockId == 3)
  339. {
  340. /*
  341. pageNames p*(n+1) strings 0 p null terminated strings, each with length n
  342. */
  343. const char *value = (const char *)pData;
  344. CCASSERT(strlen(value) < blockSize, "Block size should be less then string");
  345. _atlasName = FileUtils::getInstance()->fullPathFromRelativeFile(value, controlFile);
  346. }
  347. else if (blockId == 4)
  348. {
  349. /*
  350. id 4 uint 0+c*20 These fields are repeated until all characters have been described
  351. x 2 uint 4+c*20
  352. y 2 uint 6+c*20
  353. width 2 uint 8+c*20
  354. height 2 uint 10+c*20
  355. xoffset 2 int 12+c*20
  356. yoffset 2 int 14+c*20
  357. xadvance 2 int 16+c*20
  358. page 1 uint 18+c*20
  359. chnl 1 uint 19+c*20
  360. */
  361. unsigned long count = blockSize / 20;
  362. for (unsigned long i = 0; i < count; i++)
  363. {
  364. uint32_t charId = 0; memcpy(&charId, pData + (i * 20), 4);
  365. BMFontDef& fontDef = _fontDefDictionary[charId];
  366. fontDef.charID = charId;
  367. uint16_t charX = 0; memcpy(&charX, pData + (i * 20) + 4, 2);
  368. fontDef.rect.origin.x = charX;
  369. uint16_t charY = 0; memcpy(&charY, pData + (i * 20) + 6, 2);
  370. fontDef.rect.origin.y = charY;
  371. uint16_t charWidth = 0; memcpy(&charWidth, pData + (i * 20) + 8, 2);
  372. fontDef.rect.size.width = charWidth;
  373. uint16_t charHeight = 0; memcpy(&charHeight, pData + (i * 20) + 10, 2);
  374. fontDef.rect.size.height = charHeight;
  375. int16_t xoffset = 0; memcpy(&xoffset, pData + (i * 20) + 12, 2);
  376. fontDef.xOffset = xoffset;
  377. int16_t yoffset = 0; memcpy(&yoffset, pData + (i * 20) + 14, 2);
  378. fontDef.yOffset = yoffset;
  379. int16_t xadvance = 0; memcpy(&xadvance, pData + (i * 20) + 16, 2);
  380. fontDef.xAdvance = xadvance;
  381. validCharsString->insert(fontDef.charID);
  382. }
  383. }
  384. else if (blockId == 5) {
  385. /*
  386. first 4 uint 0+c*10 These fields are repeated until all kerning pairs have been described
  387. second 4 uint 4+c*10
  388. amount 2 int 8+c*10
  389. */
  390. unsigned long count = blockSize / 20;
  391. for (unsigned long i = 0; i < count; i++)
  392. {
  393. uint32_t first = 0; memcpy(&first, pData + (i * 10), 4);
  394. uint32_t second = 0; memcpy(&second, pData + (i * 10) + 4, 4);
  395. int16_t amount = 0; memcpy(&amount, pData + (i * 10) + 8, 2);
  396. uint64_t key = ((uint64_t)first<<32) | ((uint64_t)second&0xffffffffll);
  397. _kerningDictionary[key] = amount;
  398. }
  399. }
  400. pData += blockSize; remains -= blockSize;
  401. }
  402. return validCharsString;
  403. }
  404. void BMFontConfiguration::parseImageFileName(const char* line, const std::string& fntFile)
  405. {
  406. //////////////////////////////////////////////////////////////////////////
  407. // line to parse:
  408. // page id=0 file="bitmapFontTest.png"
  409. //////////////////////////////////////////////////////////////////////////
  410. // page ID. Sanity check
  411. int pageId;
  412. sscanf(line, "page id=%d", &pageId);
  413. CCASSERT(pageId == 0, "LabelBMFont file could not be found");
  414. // file
  415. char fileName[255];
  416. sscanf(strchr(line,'"') + 1, "%[^\"]", fileName);
  417. _atlasName = FileUtils::getInstance()->fullPathFromRelativeFile(fileName, fntFile);
  418. }
  419. void BMFontConfiguration::parseInfoArguments(const char* line)
  420. {
  421. //////////////////////////////////////////////////////////////////////////
  422. // possible lines to parse:
  423. // info face="Script" size=32 bold=0 italic=0 charset="" unicode=1 stretchH=100 smooth=1 aa=1 padding=1,4,3,2 spacing=0,0 outline=0
  424. // info face="Cracked" size=36 bold=0 italic=0 charset="" unicode=0 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1
  425. //////////////////////////////////////////////////////////////////////////
  426. sscanf(strstr(line, "size=") + 5, "%d", &_fontSize);
  427. // padding
  428. sscanf(strstr(line,"padding=") + 8, "%d,%d,%d,%d", &_padding.top, &_padding.right, &_padding.bottom, &_padding.left);
  429. //CCLOG("cocos2d: padding: %d,%d,%d,%d", _padding.left, _padding.top, _padding.right, _padding.bottom);
  430. }
  431. void BMFontConfiguration::parseCommonArguments(const char* line)
  432. {
  433. //////////////////////////////////////////////////////////////////////////
  434. // line to parse:
  435. // common lineHeight=104 base=26 scaleW=1024 scaleH=512 pages=1 packed=0
  436. //////////////////////////////////////////////////////////////////////////
  437. // Height
  438. auto tmp = strstr(line, "lineHeight=") + 11;
  439. sscanf(tmp, "%d", &_commonHeight);
  440. #if COCOS2D_DEBUG > 0
  441. // scaleW. sanity check
  442. int value;
  443. tmp = strstr(tmp, "scaleW=") + 7;
  444. sscanf(tmp, "%d", &value);
  445. int maxTextureSize = Configuration::getInstance()->getMaxTextureSize();
  446. CCASSERT(value <= maxTextureSize, "CCLabelBMFont: page can't be larger than supported");
  447. // scaleH. sanity check
  448. tmp = strstr(tmp, "scaleH=") + 7;
  449. sscanf(tmp, "%d", &value);
  450. CCASSERT(value <= maxTextureSize, "CCLabelBMFont: page can't be larger than supported");
  451. // pages. sanity check
  452. tmp = strstr(tmp, "pages=") + 6;
  453. sscanf(tmp, "%d", &value);
  454. CCASSERT(value == 1, "CCBitfontAtlas: only supports 1 page");
  455. #endif
  456. // packed (ignore) What does this mean ??
  457. }
  458. unsigned int BMFontConfiguration::parseCharacterDefinition(const char* line)
  459. {
  460. unsigned int charID = 0;
  461. //////////////////////////////////////////////////////////////////////////
  462. // line to parse:
  463. // char id=32 x=0 y=0 width=0 height=0 xoffset=0 yoffset=44 xadvance=14 page=0 chnl=0
  464. //////////////////////////////////////////////////////////////////////////
  465. // Character ID
  466. auto tmp = strstr(line, "id=") + 3;
  467. sscanf(tmp, "%u", &charID);
  468. BMFontDef& characterDefinition = _fontDefDictionary[charID];
  469. characterDefinition.charID = charID;
  470. // Character x
  471. tmp = strstr(tmp, "x=") + 2;
  472. sscanf(tmp, "%f", &characterDefinition.rect.origin.x);
  473. // Character y
  474. tmp = strstr(tmp, "y=") + 2;
  475. sscanf(tmp, "%f", &characterDefinition.rect.origin.y);
  476. // Character width
  477. tmp = strstr(tmp, "width=") + 6;
  478. sscanf(tmp, "%f", &characterDefinition.rect.size.width);
  479. // Character height
  480. tmp = strstr(tmp, "height=") + 7;
  481. sscanf(tmp, "%f", &characterDefinition.rect.size.height);
  482. // Character xoffset
  483. tmp = strstr(tmp, "xoffset=") + 8;
  484. sscanf(tmp, "%hd", &characterDefinition.xOffset);
  485. // Character yoffset
  486. tmp = strstr(tmp, "yoffset=") + 8;
  487. sscanf(tmp, "%hd", &characterDefinition.yOffset);
  488. // Character xadvance
  489. tmp = strstr(tmp, "xadvance=") + 9;
  490. sscanf(tmp, "%hd", &characterDefinition.xAdvance);
  491. return charID;
  492. }
  493. void BMFontConfiguration::parseKerningEntry(const char* line)
  494. {
  495. //////////////////////////////////////////////////////////////////////////
  496. // line to parse:
  497. // kerning first=121 second=44 amount=-7
  498. //////////////////////////////////////////////////////////////////////////
  499. int first, second, amount;
  500. auto tmp = strstr(line, "first=") + 6;
  501. sscanf(tmp, "%d", &first);
  502. tmp = strstr(tmp, "second=") + 7;
  503. sscanf(tmp, "%d", &second);
  504. tmp = strstr(tmp, "amount=") + 7;
  505. sscanf(tmp, "%d", &amount);
  506. uint64_t key = ((uint64_t)first<<32) | ((uint64_t)second&0xffffffffll);
  507. _kerningDictionary[key] = amount;
  508. }
  509. FontFNT * FontFNT::create(const std::string& fntFilePath, const Vec2& imageOffset /* = Vec2::ZERO */)
  510. {
  511. BMFontConfiguration *newConf = FNTConfigLoadFile(fntFilePath);
  512. if (!newConf)
  513. return nullptr;
  514. // add the texture
  515. Texture2D *tempTexture = Director::getInstance()->getTextureCache()->addImage(newConf->getAtlasName());
  516. if (!tempTexture)
  517. {
  518. return nullptr;
  519. }
  520. FontFNT *tempFont = new FontFNT(newConf,imageOffset);
  521. tempFont->setFontSize(newConf->_fontSize);
  522. if (!tempFont)
  523. {
  524. return nullptr;
  525. }
  526. tempFont->autorelease();
  527. return tempFont;
  528. }
  529. FontFNT::FontFNT(BMFontConfiguration *theContfig, const Vec2& imageOffset /* = Vec2::ZERO */)
  530. :_configuration(theContfig)
  531. ,_imageOffset(CC_POINT_PIXELS_TO_POINTS(imageOffset))
  532. {
  533. _configuration->retain();
  534. }
  535. FontFNT::~FontFNT()
  536. {
  537. _configuration->release();
  538. }
  539. void FontFNT::purgeCachedData()
  540. {
  541. if (s_configurations)
  542. {
  543. s_configurations->clear();
  544. CC_SAFE_DELETE(s_configurations);
  545. }
  546. }
  547. int * FontFNT::getHorizontalKerningForTextUTF32(const std::u32string& text, int &outNumLetters) const
  548. {
  549. outNumLetters = static_cast<int>(text.length());
  550. if (!outNumLetters)
  551. return nullptr;
  552. int *sizes = new (std::nothrow) int[outNumLetters];
  553. if (!sizes)
  554. return nullptr;
  555. for (int c = 0; c < outNumLetters; ++c)
  556. {
  557. if (c < (outNumLetters-1))
  558. sizes[c] = getHorizontalKerningForChars(text[c], text[c+1]);
  559. else
  560. sizes[c] = 0;
  561. }
  562. return sizes;
  563. }
  564. int FontFNT::getHorizontalKerningForChars(char32_t firstChar, char32_t secondChar) const
  565. {
  566. int ret = 0;
  567. uint64_t key = ((uint64_t)firstChar << 32) | ((uint64_t)secondChar & 0xffffffffll);
  568. auto iter = _configuration->_kerningDictionary.find(key);
  569. if (iter != _configuration->_kerningDictionary.end())
  570. {
  571. ret = iter->second;
  572. }
  573. return ret;
  574. }
  575. void FontFNT::setFontSize(float fontSize)
  576. {
  577. _fontSize = fontSize;
  578. }
  579. int FontFNT::getOriginalFontSize()const
  580. {
  581. return _configuration->_fontSize;
  582. }
  583. FontAtlas * FontFNT::createFontAtlas()
  584. {
  585. // check that everything is fine with the BMFontCofniguration
  586. if (_configuration->_fontDefDictionary.empty())
  587. return nullptr;
  588. size_t numGlyphs = _configuration->_characterSet->size();
  589. if (numGlyphs == 0)
  590. return nullptr;
  591. if (_configuration->_commonHeight == 0)
  592. return nullptr;
  593. FontAtlas *tempAtlas = new (std::nothrow) FontAtlas(*this);
  594. if (tempAtlas == nullptr)
  595. return nullptr;
  596. // common height
  597. int originalFontSize = _configuration->_fontSize;
  598. float originalLineHeight = _configuration->_commonHeight;
  599. float factor = 0.0f;
  600. if (std::abs(_fontSize - originalFontSize) < FLT_EPSILON) {
  601. factor = 1.0f;
  602. }else {
  603. factor = _fontSize / originalFontSize;
  604. }
  605. tempAtlas->setLineHeight(originalLineHeight * factor);
  606. for (auto&& e : _configuration->_fontDefDictionary)
  607. {
  608. BMFontDef& fontDef = e.second;
  609. FontLetterDefinition tempDefinition;
  610. Rect tempRect;
  611. tempRect = fontDef.rect;
  612. tempRect = CC_RECT_PIXELS_TO_POINTS(tempRect);
  613. tempDefinition.offsetX = fontDef.xOffset;
  614. tempDefinition.offsetY = fontDef.yOffset;
  615. tempDefinition.U = tempRect.origin.x + _imageOffset.x;
  616. tempDefinition.V = tempRect.origin.y + _imageOffset.y;
  617. tempDefinition.width = tempRect.size.width;
  618. tempDefinition.height = tempRect.size.height;
  619. //carloX: only one texture supported FOR NOW
  620. tempDefinition.textureID = 0;
  621. tempDefinition.validDefinition = true;
  622. tempDefinition.xAdvance = fontDef.xAdvance;
  623. // add the new definition
  624. if (65535 < fontDef.charID) {
  625. CCLOGWARN("Warning: 65535 < fontDef.charID (%u), ignored", fontDef.charID);
  626. } else {
  627. tempAtlas->addLetterDefinition(fontDef.charID,tempDefinition);
  628. }
  629. }
  630. // add the texture (only one texture for now)
  631. Texture2D *tempTexture = Director::getInstance()->getTextureCache()->addImage(_configuration->getAtlasName());
  632. if (!tempTexture) {
  633. CC_SAFE_RELEASE(tempAtlas);
  634. return nullptr;
  635. }
  636. // add the texture
  637. tempAtlas->addTexture(tempTexture, 0);
  638. // done
  639. return tempAtlas;
  640. }
  641. void FontFNT::reloadBMFontResource(const std::string& fntFilePath)
  642. {
  643. if (s_configurations == nullptr)
  644. {
  645. s_configurations = new (std::nothrow) Map<std::string, BMFontConfiguration*>();
  646. }
  647. BMFontConfiguration *ret = s_configurations->at(fntFilePath);
  648. if (ret != nullptr)
  649. {
  650. s_configurations->erase(fntFilePath);
  651. }
  652. ret = BMFontConfiguration::create(fntFilePath);
  653. if (ret)
  654. {
  655. s_configurations->insert(fntFilePath, ret);
  656. Director::getInstance()->getTextureCache()->reloadTexture(ret->getAtlasName());
  657. }
  658. }
  659. NS_CC_END