gFont.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "gfx/gFont.h"
  24. #include "core/resourceManager.h"
  25. #include "core/stream/fileStream.h"
  26. #include "core/strings/unicode.h"
  27. #include "core/strings/findMatch.h"
  28. #include "core/strings/stringFunctions.h"
  29. #include "core/util/endian.h"
  30. #include "core/util/safeDelete.h"
  31. #include "console/console.h"
  32. #include "console/engineAPI.h"
  33. #include "platform/threads/mutex.h"
  34. #include "zlib/zlib.h"
  35. GFX_ImplementTextureProfile(GFXFontTextureProfile,
  36. GFXTextureProfile::DiffuseMap,
  37. GFXTextureProfile::PreserveSize |
  38. GFXTextureProfile::Static |
  39. GFXTextureProfile::KeepBitmap |
  40. GFXTextureProfile::NoMipmap,
  41. GFXTextureProfile::NONE);
  42. template<> void *Resource<GFont>::create(const Torque::Path &path)
  43. {
  44. #ifdef TORQUE_DEBUG_RES_MANAGER
  45. Con::printf( "Resource<GFont>::create - [%s]", path.getFullPath().c_str() );
  46. #endif
  47. return GFont::load( path );
  48. }
  49. template<> ResourceBase::Signature Resource<GFont>::signature()
  50. {
  51. return MakeFourCC('f','o','n','t');
  52. }
  53. /// Used for repacking in GFont::importStrip.
  54. struct GlyphMap
  55. {
  56. U32 charId;
  57. GBitmap *bitmap;
  58. };
  59. static S32 QSORT_CALLBACK GlyphMapCompare(const void *a, const void *b)
  60. {
  61. S32 ha = ((GlyphMap *) a)->bitmap->getHeight();
  62. S32 hb = ((GlyphMap *) b)->bitmap->getHeight();
  63. return hb - ha;
  64. }
  65. const U32 GFont::csm_fileVersion = 3;
  66. String GFont::getFontCacheFilename(const String &faceName, U32 size)
  67. {
  68. return String::ToString("%s/%s %d (%s).uft",
  69. Con::getVariable("$GUI::fontCacheDirectory"), faceName.c_str(), size, getCharSetName(0));
  70. }
  71. GFont* GFont::load( const Torque::Path& path )
  72. {
  73. FileStream stream;
  74. stream.open( path.getFullPath(), Torque::FS::File::Read );
  75. if ( stream.getStatus() != Stream::Ok )
  76. return NULL;
  77. GFont *ret = new GFont;
  78. ret->mGFTFile = path;
  79. if(!ret->read(stream))
  80. {
  81. Con::errorf( "GFont::load - error reading '%s'", path.getFullPath().c_str() );
  82. SAFE_DELETE(ret);
  83. }
  84. else
  85. {
  86. #ifndef TORQUE_OS_XENON
  87. PlatformFont *platFont = createPlatformFont(ret->getFontFaceName(), ret->getFontSize(), ret->getFontCharSet());
  88. if ( platFont == NULL )
  89. {
  90. Con::errorf( "GFont::load - error creating platform font for '%s'", path.getFullPath().c_str() );
  91. SAFE_DELETE(ret);
  92. }
  93. else
  94. ret->setPlatformFont(platFont);
  95. #endif
  96. }
  97. return ret;
  98. }
  99. Resource<GFont> GFont::create(const String &faceName, U32 size, const char *cacheDirectory, U32 charset /* = TGE_ANSI_CHARSET */)
  100. {
  101. if( !cacheDirectory )
  102. cacheDirectory = Con::getVariable( "$GUI::fontCacheDirectory" );
  103. const Torque::Path path( String::ToString("%s/%s %d (%s).uft",
  104. cacheDirectory, faceName.c_str(), size, getCharSetName(charset)) );
  105. Resource<GFont> ret;
  106. // If the file already exists attempt to load it
  107. if (Platform::isFile(path.getFullPath().c_str()))
  108. {
  109. ret = ResourceManager::get().load(path);
  110. if (ret != NULL)
  111. {
  112. ret->mGFTFile = path;
  113. return ret;
  114. }
  115. }
  116. // Otherwise attempt to have the platform generate a new font
  117. PlatformFont *platFont = createPlatformFont(faceName, size, charset);
  118. if (platFont == NULL)
  119. {
  120. String fontName;
  121. #ifdef _XBOX
  122. //AssertFatal( false, "Font creation is not supported on the Xbox platform. Create the font files (*.uft) using the Windows/MacOS build of the project." );
  123. if(!faceName.equal("arial", String::NoCase) || size != 14)
  124. {
  125. return create("Arial", 14, cacheDirectory, charset);
  126. }
  127. return ret;
  128. #endif
  129. // Couldn't load the requested font. This probably will be common
  130. // since many unix boxes don't have arial or lucida console installed.
  131. // Attempt to map the font name into a font we're pretty sure exist
  132. // Lucida Console is a common code & console font on windows, and
  133. // Monaco is the recommended code & console font on mac.
  134. if (faceName.equal("arial", String::NoCase))
  135. fontName = "Helvetica";
  136. else if (faceName.equal("lucida console", String::NoCase))
  137. fontName = "Monaco";
  138. else if (faceName.equal("monaco", String::NoCase))
  139. fontName = "Courier";
  140. else
  141. return ret;
  142. return create(fontName, size, cacheDirectory, charset);
  143. }
  144. // Create the actual GFont and set some initial properties
  145. GFont *font = new GFont;
  146. font->mPlatformFont = platFont;
  147. font->mGFTFile = path;
  148. font->mFaceName = faceName;
  149. font->mSize = size;
  150. font->mCharSet = charset;
  151. font->mHeight = platFont->getFontHeight();
  152. font->mBaseline = platFont->getFontBaseLine();
  153. font->mAscent = platFont->getFontBaseLine();
  154. font->mDescent = platFont->getFontHeight() - platFont->getFontBaseLine();
  155. // Flag it to save when we exit
  156. font->mNeedSave = true;
  157. // Load the newly created font into the ResourceManager
  158. ret.setResource(ResourceManager::get().load(path), font);
  159. return ret;
  160. }
  161. //-------------------------------------------------------------------------
  162. GFont::GFont()
  163. {
  164. VECTOR_SET_ASSOCIATION(mCharInfoList);
  165. VECTOR_SET_ASSOCIATION(mTextureSheets);
  166. for (U32 i = 0; i < (sizeof(mRemapTable) / sizeof(S32)); i++)
  167. mRemapTable[i] = -1;
  168. mCurX = mCurY = mCurSheet = -1;
  169. mPlatformFont = NULL;
  170. mSize = 0;
  171. mCharSet = 0;
  172. mNeedSave = false;
  173. mMutex = Mutex::createMutex();
  174. }
  175. GFont::~GFont()
  176. {
  177. if(mNeedSave)
  178. {
  179. AssertFatal( mGFTFile.getFullPath().isNotEmpty(), "GFont::~GFont - path not set" );
  180. FileStream stream;
  181. stream.open(mGFTFile, Torque::FS::File::Write);
  182. if(stream.getStatus() == Stream::Ok)
  183. write(stream);
  184. stream.close();
  185. }
  186. S32 i;
  187. for(i = 0;i < mCharInfoList.size();i++)
  188. {
  189. SAFE_DELETE_ARRAY(mCharInfoList[i].bitmapData);
  190. }
  191. for(i=0; i<mTextureSheets.size(); i++)
  192. mTextureSheets[i] = NULL;
  193. SAFE_DELETE(mPlatformFont);
  194. Mutex::destroyMutex(mMutex);
  195. }
  196. void GFont::dumpInfo() const
  197. {
  198. // Number and extent of mapped characters?
  199. U32 mapCount = 0, mapBegin=0xFFFF, mapEnd=0;
  200. for(U32 i=0; i<0x10000; i++)
  201. {
  202. if(mRemapTable[i] != -1)
  203. {
  204. mapCount++;
  205. if(i<mapBegin) mapBegin = i;
  206. if(i>mapEnd) mapEnd = i;
  207. }
  208. }
  209. // Let's write out all the info we can on this font.
  210. Con::printf(" '%s' %dpt", mFaceName.c_str(), mSize);
  211. Con::printf(" - %d texture sheets, %d mapped characters.", mTextureSheets.size(), mapCount);
  212. if(mapCount)
  213. Con::printf(" - Codepoints range from 0x%x to 0x%x.", mapBegin, mapEnd);
  214. else
  215. Con::printf(" - No mapped codepoints.");
  216. Con::printf(" - Platform font is %s.", (mPlatformFont ? "present" : "not present") );
  217. }
  218. //-----------------------------------------------------------------------------
  219. bool GFont::loadCharInfo(const UTF16 ch)
  220. {
  221. PROFILE_SCOPE(GFont_loadCharInfo);
  222. if(mRemapTable[ch] != -1)
  223. return true; // Not really an error
  224. if(mPlatformFont && mPlatformFont->isValidChar(ch))
  225. {
  226. Mutex::lockMutex(mMutex); // the CharInfo returned by mPlatformFont is static data, must protect from changes.
  227. PlatformFont::CharInfo &ci = mPlatformFont->getCharInfo(ch);
  228. if(ci.bitmapData)
  229. addBitmap(ci);
  230. mCharInfoList.push_back(ci);
  231. mRemapTable[ch] = mCharInfoList.size() - 1;
  232. mNeedSave = true;
  233. Mutex::unlockMutex(mMutex);
  234. return true;
  235. }
  236. return false;
  237. }
  238. void GFont::addBitmap(PlatformFont::CharInfo &charInfo)
  239. {
  240. U32 nextCurX = U32(mCurX + charInfo.width ); /*7) & ~0x3;*/
  241. U32 nextCurY = U32(mCurY + mPlatformFont->getFontHeight()); // + 7) & ~0x3;
  242. // These are here for postmortem debugging.
  243. bool routeA = false, routeB = false;
  244. if(mCurSheet == -1 || nextCurY >= TextureSheetSize)
  245. {
  246. routeA = true;
  247. addSheet();
  248. // Recalc our nexts.
  249. nextCurX = U32(mCurX + charInfo.width); // + 7) & ~0x3;
  250. nextCurY = U32(mCurY + mPlatformFont->getFontHeight()); // + 7) & ~0x3;
  251. }
  252. if( nextCurX >= TextureSheetSize)
  253. {
  254. routeB = true;
  255. mCurX = 0;
  256. mCurY = nextCurY;
  257. // Recalc our nexts.
  258. nextCurX = U32(mCurX + charInfo.width); // + 7) & ~0x3;
  259. nextCurY = U32(mCurY + mPlatformFont->getFontHeight()); // + 7) & ~0x3;
  260. }
  261. // Check the Y once more - sometimes we advance to a new row and run off
  262. // the end.
  263. if(nextCurY >= TextureSheetSize)
  264. {
  265. routeA = true;
  266. addSheet();
  267. // Recalc our nexts.
  268. nextCurX = U32(mCurX + charInfo.width); // + 7) & ~0x3;
  269. nextCurY = U32(mCurY + mPlatformFont->getFontHeight()); // + 7) & ~0x3;
  270. }
  271. charInfo.bitmapIndex = mCurSheet;
  272. charInfo.xOffset = mCurX;
  273. charInfo.yOffset = mCurY;
  274. mCurX = nextCurX;
  275. S32 x, y;
  276. GBitmap *bmp = mTextureSheets[mCurSheet].getBitmap();
  277. AssertFatal(bmp->getFormat() == GFXFormatA8, "GFont::addBitmap - cannot added characters to non-greyscale textures!");
  278. for(y = 0;y < charInfo.height;y++)
  279. for(x = 0;x < charInfo.width;x++)
  280. *bmp->getAddress(x + charInfo.xOffset, y + charInfo.yOffset) = charInfo.bitmapData[y * charInfo.width + x];
  281. mTextureSheets[mCurSheet].refresh();
  282. }
  283. void GFont::addSheet()
  284. {
  285. GBitmap *bitmap = new GBitmap(TextureSheetSize, TextureSheetSize, false, GFXFormatA8 );
  286. // Set everything to transparent.
  287. U8 *bits = bitmap->getWritableBits();
  288. dMemset(bits, 0, sizeof(U8) *TextureSheetSize*TextureSheetSize);
  289. GFXTexHandle handle = GFXTexHandle( bitmap, &GFXFontTextureProfile, true, avar("%s() - (line %d)", __FUNCTION__, __LINE__) );
  290. mTextureSheets.increment();
  291. mTextureSheets.last() = handle;
  292. mCurX = 0;
  293. mCurY = 0;
  294. mCurSheet = mTextureSheets.size() - 1;
  295. }
  296. //-----------------------------------------------------------------------------
  297. const PlatformFont::CharInfo &GFont::getCharInfo(const UTF16 in_charIndex)
  298. {
  299. PROFILE_SCOPE(GFont_getCharInfo);
  300. AssertFatal(in_charIndex, "GFont::getCharInfo - can't get info for char 0!");
  301. if(mRemapTable[in_charIndex] == -1)
  302. loadCharInfo(in_charIndex);
  303. AssertFatal(mRemapTable[in_charIndex] != -1, "No remap info for this character");
  304. return mCharInfoList[mRemapTable[in_charIndex]];
  305. }
  306. const PlatformFont::CharInfo &GFont::getDefaultCharInfo()
  307. {
  308. static PlatformFont::CharInfo c;
  309. // c is initialized by the CharInfo default constructor.
  310. return c;
  311. }
  312. //-----------------------------------------------------------------------------
  313. U32 GFont::getStrWidth(const UTF8* in_pString)
  314. {
  315. AssertFatal(in_pString != NULL, "GFont::getStrWidth: String is NULL, height is undefined");
  316. // If we ain't running debug...
  317. if (in_pString == NULL || *in_pString == '\0')
  318. return 0;
  319. return getStrNWidth(in_pString, dStrlen(in_pString));
  320. }
  321. U32 GFont::getStrWidthPrecise(const UTF8* in_pString)
  322. {
  323. AssertFatal(in_pString != NULL, "GFont::getStrWidth: String is NULL, height is undefined");
  324. // If we ain't running debug...
  325. if (in_pString == NULL)
  326. return 0;
  327. return getStrNWidthPrecise(in_pString, dStrlen(in_pString));
  328. }
  329. //-----------------------------------------------------------------------------
  330. U32 GFont::getStrNWidth(const UTF8 *str, U32 n)
  331. {
  332. // UTF8 conversion is expensive. Avoid converting in a tight loop.
  333. FrameTemp<UTF16> str16(n + 1);
  334. convertUTF8toUTF16N(str, str16, n + 1);
  335. return getStrNWidth(str16, dStrlen(str16));
  336. }
  337. U32 GFont::getStrNWidth(const UTF16 *str, U32 n)
  338. {
  339. AssertFatal(str != NULL, "GFont::getStrNWidth: String is NULL");
  340. if (str == NULL || str[0] == '\0' || n == 0)
  341. return 0;
  342. U32 totWidth = 0;
  343. UTF16 curChar;
  344. U32 charCount;
  345. for(charCount = 0; charCount < n; charCount++)
  346. {
  347. curChar = str[charCount];
  348. if(curChar == '\0')
  349. break;
  350. if(isValidChar(curChar))
  351. {
  352. const PlatformFont::CharInfo& rChar = getCharInfo(curChar);
  353. totWidth += rChar.xIncrement;
  354. }
  355. else if (curChar == dT('\t'))
  356. {
  357. const PlatformFont::CharInfo& rChar = getCharInfo(dT(' '));
  358. totWidth += rChar.xIncrement * TabWidthInSpaces;
  359. }
  360. }
  361. return(totWidth);
  362. }
  363. U32 GFont::getStrNWidthPrecise(const UTF8 *str, U32 n)
  364. {
  365. FrameTemp<UTF16> str16(n + 1);
  366. convertUTF8toUTF16N(str, str16, n + 1);
  367. return getStrNWidthPrecise(str16, dStrlen(str16));
  368. }
  369. U32 GFont::getStrNWidthPrecise(const UTF16 *str, U32 n)
  370. {
  371. AssertFatal(str != NULL, "GFont::getStrNWidth: String is NULL");
  372. if (str == NULL || str[0] == '\0' || n == 0)
  373. return(0);
  374. U32 totWidth = 0;
  375. UTF16 curChar;
  376. U32 charCount = 0;
  377. for(charCount = 0; charCount < n; charCount++)
  378. {
  379. curChar = str[charCount];
  380. if(curChar == '\0')
  381. break;
  382. if(isValidChar(curChar))
  383. {
  384. const PlatformFont::CharInfo& rChar = getCharInfo(curChar);
  385. totWidth += rChar.xIncrement;
  386. }
  387. else if (curChar == dT('\t'))
  388. {
  389. const PlatformFont::CharInfo& rChar = getCharInfo(dT(' '));
  390. totWidth += rChar.xIncrement * TabWidthInSpaces;
  391. }
  392. }
  393. UTF16 endChar = str[getMin(charCount,n-1)];
  394. if (isValidChar(endChar))
  395. {
  396. const PlatformFont::CharInfo& rChar = getCharInfo(endChar);
  397. if (rChar.width != rChar.xIncrement)
  398. totWidth += (rChar.width - rChar.xIncrement);
  399. }
  400. return(totWidth);
  401. }
  402. U32 GFont::getBreakPos(const UTF16 *str16, U32 slen, U32 width, bool breakOnWhitespace)
  403. {
  404. // Some early out cases.
  405. if(slen==0)
  406. return 0;
  407. U32 ret = 0;
  408. U32 lastws = 0;
  409. UTF16 c;
  410. U32 charCount = 0;
  411. for( charCount=0; charCount < slen; charCount++)
  412. {
  413. c = str16[charCount];
  414. if(c == '\0')
  415. break;
  416. if(c == dT('\t'))
  417. c = dT(' ');
  418. if(!isValidChar(c))
  419. {
  420. ret++;
  421. continue;
  422. }
  423. if(c == dT(' '))
  424. lastws = ret+1;
  425. const PlatformFont::CharInfo& rChar = getCharInfo(c);
  426. if(rChar.width > width || rChar.xIncrement > width)
  427. {
  428. if(lastws && breakOnWhitespace)
  429. return lastws;
  430. return ret;
  431. }
  432. width -= rChar.xIncrement;
  433. ret++;
  434. }
  435. return ret;
  436. }
  437. void GFont::wrapString(const UTF8 *txt, U32 lineWidth, Vector<U32> &startLineOffset, Vector<U32> &lineLen)
  438. {
  439. // TODO: Is this error still true?
  440. //Con::errorf("GFont::wrapString(): Not yet converted to be UTF-8 safe");
  441. startLineOffset.clear();
  442. lineLen.clear();
  443. if (!txt || !txt[0] || lineWidth < getCharWidth('W')) //make sure the line width is greater then a single character
  444. return;
  445. U32 len = dStrlen(txt);
  446. U32 startLine;
  447. for (U32 i = 0; i < len;)
  448. {
  449. startLine = i;
  450. startLineOffset.push_back(startLine);
  451. // loop until the string is too large
  452. bool needsNewLine = false;
  453. U32 lineStrWidth = 0;
  454. for (; i < len; i++)
  455. {
  456. if( txt[ i ] == '\n' )
  457. {
  458. needsNewLine = true;
  459. break;
  460. }
  461. else if(isValidChar(txt[i]))
  462. {
  463. lineStrWidth += getCharInfo(txt[i]).xIncrement;
  464. if( lineStrWidth > lineWidth )
  465. {
  466. needsNewLine = true;
  467. break;
  468. }
  469. }
  470. }
  471. if (!needsNewLine)
  472. {
  473. // we are done!
  474. lineLen.push_back(i - startLine);
  475. return;
  476. }
  477. S32 j;
  478. // Did we hit a hardwrap (newline character) in the string.
  479. bool hardwrap = ( txt[i] == '\n' );
  480. if ( hardwrap )
  481. {
  482. j = i;
  483. }
  484. // determine where to put the newline
  485. // we need to backtrack until we find a space character
  486. // we don't do this for hardwrap(s)
  487. else
  488. {
  489. for (j = i - 1; j >= startLine; j--)
  490. {
  491. if ( dIsspace(txt[j]) || txt[i] == '\n' )
  492. break;
  493. }
  494. if (j < startLine)
  495. {
  496. // the line consists of a single word!
  497. // So, just break up the word
  498. j = i - 1;
  499. }
  500. }
  501. lineLen.push_back(j - startLine);
  502. i = j;
  503. // Now we need to increment through any space characters at the
  504. // beginning of the next line.
  505. // We don't skip spaces after a hardwrap because they were obviously intended.
  506. for (i++; i < len; i++)
  507. {
  508. if ( txt[i] == '\n' )
  509. continue;
  510. if ( dIsspace( txt[i] ) && !hardwrap )
  511. continue;
  512. break;
  513. }
  514. }
  515. }
  516. //-----------------------------------------------------------------------------
  517. bool GFont::read(Stream& io_rStream)
  518. {
  519. // Handle versioning
  520. U32 version;
  521. io_rStream.read(&version);
  522. if(version != csm_fileVersion)
  523. return false;
  524. char buf[256];
  525. io_rStream.readString(buf);
  526. mFaceName = buf;
  527. io_rStream.read(&mSize);
  528. io_rStream.read(&mCharSet);
  529. io_rStream.read(&mHeight);
  530. io_rStream.read(&mBaseline);
  531. io_rStream.read(&mAscent);
  532. io_rStream.read(&mDescent);
  533. U32 size = 0;
  534. io_rStream.read(&size);
  535. mCharInfoList.setSize(size);
  536. U32 i;
  537. for(i = 0; i < size; i++)
  538. {
  539. PlatformFont::CharInfo *ci = &mCharInfoList[i];
  540. io_rStream.read(&ci->bitmapIndex);
  541. io_rStream.read(&ci->xOffset);
  542. io_rStream.read(&ci->yOffset);
  543. io_rStream.read(&ci->width);
  544. io_rStream.read(&ci->height);
  545. io_rStream.read(&ci->xOrigin);
  546. io_rStream.read(&ci->yOrigin);
  547. io_rStream.read(&ci->xIncrement);
  548. ci->bitmapData = NULL;
  549. }
  550. U32 numSheets = 0;
  551. io_rStream.read(&numSheets);
  552. for(i = 0; i < numSheets; i++)
  553. {
  554. GBitmap *bmp = new GBitmap;
  555. if(!bmp->readBitmap("png", io_rStream))
  556. {
  557. delete bmp;
  558. return false;
  559. }
  560. GFXTexHandle handle = GFXTexHandle(bmp, &GFXFontTextureProfile, true, avar("%s() - Read Font Sheet for %s %d (line %d)", __FUNCTION__, mFaceName.c_str(), mSize, __LINE__));
  561. //handle.setFilterNearest();
  562. mTextureSheets.push_back(handle);
  563. }
  564. // Read last position info
  565. io_rStream.read(&mCurX);
  566. io_rStream.read(&mCurY);
  567. io_rStream.read(&mCurSheet);
  568. // Read the remap table.
  569. U32 minGlyph, maxGlyph;
  570. io_rStream.read(&minGlyph);
  571. io_rStream.read(&maxGlyph);
  572. if(maxGlyph >= minGlyph)
  573. {
  574. // Length of buffer..
  575. U32 buffLen;
  576. io_rStream.read(&buffLen);
  577. // Read the buffer.
  578. FrameTemp<S32> inBuff(buffLen);
  579. io_rStream.read(buffLen, inBuff);
  580. // Decompress.
  581. uLongf destLen = (maxGlyph-minGlyph+1)*sizeof(S32);
  582. uncompress((Bytef*)&mRemapTable[minGlyph], &destLen, (Bytef*)(S32*)inBuff, buffLen);
  583. AssertISV(destLen == (maxGlyph-minGlyph+1)*sizeof(S32), "GFont::read - invalid remap table data!");
  584. // Make sure we've got the right endianness.
  585. for(i = minGlyph; i <= maxGlyph; i++)
  586. mRemapTable[i] = convertBEndianToHost(mRemapTable[i]);
  587. }
  588. return (io_rStream.getStatus() == Stream::Ok);
  589. }
  590. bool GFont::write(Stream& stream)
  591. {
  592. // Handle versioning
  593. stream.write(csm_fileVersion);
  594. // Write font info
  595. stream.write(mFaceName);
  596. stream.write(mSize);
  597. stream.write(mCharSet);
  598. stream.write(mHeight);
  599. stream.write(mBaseline);
  600. stream.write(mAscent);
  601. stream.write(mDescent);
  602. // Write char info list
  603. stream.write(U32(mCharInfoList.size()));
  604. U32 i;
  605. for(i = 0; i < mCharInfoList.size(); i++)
  606. {
  607. const PlatformFont::CharInfo *ci = &mCharInfoList[i];
  608. stream.write(ci->bitmapIndex);
  609. stream.write(ci->xOffset);
  610. stream.write(ci->yOffset);
  611. stream.write(ci->width);
  612. stream.write(ci->height);
  613. stream.write(ci->xOrigin);
  614. stream.write(ci->yOrigin);
  615. stream.write(ci->xIncrement);
  616. }
  617. stream.write(mTextureSheets.size());
  618. for(i = 0; i < mTextureSheets.size(); i++)
  619. mTextureSheets[i].getBitmap()->writeBitmap("png", stream);
  620. stream.write(mCurX);
  621. stream.write(mCurY);
  622. stream.write(mCurSheet);
  623. // Get the min/max we have values for, and only write that range out.
  624. S32 minGlyph = S32_MAX, maxGlyph = 0;
  625. for(i = 0; i < 65536; i++)
  626. {
  627. if(mRemapTable[i] != -1)
  628. {
  629. if(i>maxGlyph) maxGlyph = i;
  630. if(i<minGlyph) minGlyph = i;
  631. }
  632. }
  633. stream.write(minGlyph);
  634. stream.write(maxGlyph);
  635. // Skip it if we don't have any glyphs to do...
  636. if(maxGlyph >= minGlyph)
  637. {
  638. // Put everything big endian, to be consistent. Do this inplace.
  639. for(i = minGlyph; i <= maxGlyph; i++)
  640. mRemapTable[i] = convertHostToBEndian(mRemapTable[i]);
  641. {
  642. // Compress.
  643. const U32 buffSize = 128 * 1024;
  644. FrameTemp<S32> outBuff(buffSize);
  645. uLongf destLen = buffSize * sizeof(S32);
  646. compress2((Bytef*)(S32*)outBuff, &destLen, (Bytef*)(S32*)&mRemapTable[minGlyph], (maxGlyph-minGlyph+1)*sizeof(S32), 9);
  647. // Write out.
  648. stream.write((U32)destLen);
  649. stream.write(destLen, outBuff);
  650. }
  651. // Put us back to normal.
  652. for(i = minGlyph; i <= maxGlyph; i++)
  653. mRemapTable[i] = convertBEndianToHost(mRemapTable[i]);
  654. }
  655. return (stream.getStatus() == Stream::Ok);
  656. }
  657. void GFont::exportStrip(const char *fileName, U32 padding, U32 kerning)
  658. {
  659. // Figure dimensions of our strip by iterating over all the char infos.
  660. U32 totalHeight = 0;
  661. U32 totalWidth = 0;
  662. S32 heightMin=0, heightMax=0;
  663. for(S32 i=0; i<mCharInfoList.size(); i++)
  664. {
  665. totalWidth += mCharInfoList[i].width + kerning + 2*padding;
  666. heightMin = getMin((S32)heightMin, (S32)getBaseline() - (S32)mCharInfoList[i].yOrigin);
  667. heightMax = getMax((S32)heightMax, (S32)getBaseline() - (S32)mCharInfoList[i].yOrigin + (S32)mCharInfoList[i].height);
  668. }
  669. totalHeight = heightMax - heightMin + 2*padding;
  670. // Make the bitmap.
  671. GBitmap gb(totalWidth, totalHeight, false, mTextureSheets[0].getBitmap()->getFormat());
  672. dMemset(gb.getWritableBits(), 0, sizeof(U8) * totalHeight * totalWidth );
  673. // Ok, copy some rects, taking into account padding, kerning, offset.
  674. U32 curWidth = kerning + padding;
  675. for(S32 i=0; i<mCharInfoList.size(); i++)
  676. {
  677. // Skip invalid stuff.
  678. if(mCharInfoList[i].bitmapIndex == -1 || mCharInfoList[i].height == 0 || mCharInfoList[i].width == 0)
  679. continue;
  680. // Copy the rect.
  681. U32 bitmap = mCharInfoList[i].bitmapIndex;
  682. RectI ri(mCharInfoList[i].xOffset, mCharInfoList[i].yOffset, mCharInfoList[i].width, mCharInfoList[i].height );
  683. Point2I outRi(curWidth, padding + getBaseline() - mCharInfoList[i].yOrigin);
  684. gb.copyRect(mTextureSheets[bitmap].getBitmap(), ri, outRi);
  685. // Advance.
  686. curWidth += mCharInfoList[i].width + kerning + 2*padding;
  687. }
  688. // Write the image!
  689. FileStream fs;
  690. fs.open( fileName, Torque::FS::File::Write );
  691. if(fs.getStatus() != Stream::Ok)
  692. {
  693. Con::errorf("GFont::exportStrip - failed to open '%s' for writing.", fileName);
  694. return;
  695. }
  696. // Done!
  697. gb.writeBitmap("png", fs);
  698. }
  699. void GFont::setPlatformFont(PlatformFont *inPlatformFont)
  700. {
  701. AssertFatal( mPlatformFont == NULL, "Trying to set platform font which already exists");
  702. mPlatformFont = inPlatformFont;
  703. }
  704. void GFont::importStrip(const char *fileName, U32 padding, U32 kerning)
  705. {
  706. // Wipe our texture sheets, and reload bitmap data from the specified file.
  707. // Also deal with kerning.
  708. // Also, we may have to load RGBA instead of RGB.
  709. // Wipe our texture sheets.
  710. mCurSheet = mCurX = mCurY = 0;
  711. mTextureSheets.clear();
  712. // Now, load the font strip.
  713. Resource<GBitmap> strip = GBitmap::load(fileName);
  714. if(!strip)
  715. {
  716. Con::errorf("GFont::importStrip - could not load file '%s'!", fileName);
  717. return;
  718. }
  719. // And get parsing and copying - load up all the characters as separate
  720. // GBitmaps, sort, then pack. Not terribly efficient but this is basically
  721. // on offline task anyway.
  722. // Ok, snag some glyphs.
  723. Vector<GlyphMap> glyphList;
  724. glyphList.reserve(mCharInfoList.size());
  725. U32 curWidth = 0;
  726. for(S32 i=0; i<mCharInfoList.size(); i++)
  727. {
  728. // Skip invalid stuff.
  729. if(mCharInfoList[i].bitmapIndex == -1 || mCharInfoList[i].height == 0 || mCharInfoList[i].width == 0)
  730. continue;
  731. // Allocate a new bitmap for this glyph, taking into account kerning and padding.
  732. glyphList.increment();
  733. GlyphMap& lastGlyphMap = glyphList.last();
  734. lastGlyphMap.bitmap = new GBitmap(mCharInfoList[i].width + kerning + 2 * padding, mCharInfoList[i].height + 2 * padding, false, strip->getFormat());
  735. lastGlyphMap.charId = i;
  736. // Copy the rect.
  737. RectI ri(curWidth, getBaseline() - mCharInfoList[i].yOrigin, lastGlyphMap.bitmap->getWidth(), lastGlyphMap.bitmap->getHeight());
  738. Point2I outRi(0,0);
  739. lastGlyphMap.bitmap->copyRect(strip, ri, outRi);
  740. // Update glyph attributes.
  741. mCharInfoList[i].width = lastGlyphMap.bitmap->getWidth();
  742. mCharInfoList[i].height = lastGlyphMap.bitmap->getHeight();
  743. mCharInfoList[i].xOffset -= kerning + padding;
  744. mCharInfoList[i].xIncrement += kerning;
  745. mCharInfoList[i].yOffset -= padding;
  746. // Advance.
  747. curWidth += ri.extent.x;
  748. }
  749. // Ok, we have a big list of glyphmaps now. So let's sort them, then pack them.
  750. dQsort(glyphList.address(), glyphList.size(), sizeof(GlyphMap), GlyphMapCompare);
  751. // They're sorted by height, so now we can do some sort of awesome packing.
  752. Point2I curSheetSize(256, 256);
  753. Vector<U32> sheetSizes;
  754. S32 curY = 0;
  755. S32 curX = 0;
  756. S32 curLnHeight = 0;
  757. S32 maxHeight = 0;
  758. for(U32 i = 0; i < glyphList.size(); i++)
  759. {
  760. PlatformFont::CharInfo *ci = &mCharInfoList[glyphList[i].charId];
  761. if(ci->height > maxHeight)
  762. maxHeight = ci->height;
  763. if(curX + ci->width > curSheetSize.x)
  764. {
  765. curY += curLnHeight;
  766. curX = 0;
  767. curLnHeight = 0;
  768. }
  769. if(curY + ci->height > curSheetSize.y)
  770. {
  771. sheetSizes.push_back(curSheetSize.y);
  772. curX = 0;
  773. curY = 0;
  774. curLnHeight = 0;
  775. }
  776. if(ci->height > curLnHeight)
  777. curLnHeight = ci->height;
  778. ci->bitmapIndex = sheetSizes.size();
  779. ci->xOffset = curX;
  780. ci->yOffset = curY;
  781. curX += ci->width;
  782. }
  783. // Terminate the packing loop calculations.
  784. curY += curLnHeight;
  785. if(curY < 64)
  786. curSheetSize.y = 64;
  787. else if(curY < 128)
  788. curSheetSize.y = 128;
  789. sheetSizes.push_back(curSheetSize.y);
  790. if(getHeight() + padding * 2 > maxHeight)
  791. maxHeight = getHeight() + padding * 2;
  792. // Allocate texture pages.
  793. for(S32 i=0; i<sheetSizes.size(); i++)
  794. {
  795. GBitmap *bitmap = new GBitmap(TextureSheetSize, TextureSheetSize, false, strip->getFormat());
  796. // Set everything to transparent.
  797. U8 *bits = bitmap->getWritableBits();
  798. dMemset(bits, 0, sizeof(U8) *TextureSheetSize*TextureSheetSize * strip->getBytesPerPixel());
  799. GFXTexHandle handle = GFXTexHandle( bitmap, &GFXFontTextureProfile, true, avar("%s() - Font Sheet for %s (line %d)", __FUNCTION__, fileName, __LINE__) );
  800. mTextureSheets.increment();
  801. mTextureSheets.last() = handle;
  802. }
  803. // Alright, we're ready to copy bits!
  804. for(S32 i=0; i<glyphList.size(); i++)
  805. {
  806. // Copy each glyph into the appropriate place.
  807. PlatformFont::CharInfo *ci = &mCharInfoList[glyphList[i].charId];
  808. U32 bi = ci->bitmapIndex;
  809. mTextureSheets[bi]->getBitmap()->copyRect(glyphList[i].bitmap, RectI(0,0, glyphList[i].bitmap->getWidth(),glyphList[i].bitmap->getHeight()), Point2I(ci->xOffset, ci->yOffset));
  810. }
  811. // Ok, all done! Just refresh some textures and we're set.
  812. for(S32 i=0; i<sheetSizes.size(); i++)
  813. mTextureSheets[i].refresh();
  814. }
  815. DefineEngineFunction( populateFontCacheString, void, ( const char *faceName, S32 fontSize, const char *string ),,
  816. "Populate the font cache for the specified font with characters from the specified string.\n"
  817. "@param faceName The name of the font face.\n"
  818. "@param fontSize The size of the font in pixels.\n"
  819. "@param string The string to populate.\n"
  820. "@ingroup Font\n" )
  821. {
  822. Resource<GFont> f = GFont::create(faceName, fontSize, Con::getVariable("$GUI::fontCacheDirectory"));
  823. if(f == NULL)
  824. {
  825. Con::errorf("populateFontCacheString - could not load font '%s %d'", faceName, fontSize);
  826. return;
  827. }
  828. if(!f->hasPlatformFont())
  829. {
  830. Con::errorf("populateFontCacheString - font '%s %d' has no platform font. Cannot generate more characters.", faceName, fontSize);
  831. return;
  832. }
  833. // This has the side effect of generating character info, including the bitmaps.
  834. f->getStrWidthPrecise( string );
  835. }
  836. DefineEngineFunction( populateFontCacheRange, void, ( const char *faceName, S32 fontSize, U32 rangeStart, U32 rangeEnd ),,
  837. "Populate the font cache for the specified font with Unicode code points in the specified range.\n"
  838. "@param faceName The name of the font face.\n"
  839. "@param fontSize The size of the font in pixels.\n"
  840. "@param rangeStart The start Unicode point.\n"
  841. "@param rangeEnd The end Unicode point.\n"
  842. "@note We only support BMP-0, so code points range from 0 to 65535.\n"
  843. "@ingroup Font\n" )
  844. {
  845. Resource<GFont> f = GFont::create(faceName, fontSize, Con::getVariable("$GUI::fontCacheDirectory"));
  846. if(f == NULL)
  847. {
  848. Con::errorf("populateFontCacheRange - could not load font '%s %d'", faceName, fontSize);
  849. return;
  850. }
  851. if(rangeStart > rangeEnd)
  852. {
  853. Con::errorf("populateFontCacheRange - range start is after end");
  854. return;
  855. }
  856. if(!f->hasPlatformFont())
  857. {
  858. Con::errorf("populateFontCacheRange - font '%s %d' has no platform font Cannot generate more characters.", faceName, fontSize);
  859. return;
  860. }
  861. // This has the side effect of generating character info, including the bitmaps.
  862. for(U32 i=rangeStart; i<rangeEnd; i++)
  863. {
  864. if(f->isValidChar(i))
  865. f->getCharWidth(i);
  866. else
  867. Con::warnf("populateFontCacheRange - skipping invalid char 0x%x", i);
  868. }
  869. // All done!
  870. }
  871. DefineEngineFunction( dumpFontCacheStatus, void, (),,
  872. "Dumps to the console a full description of all cached fonts, along with "
  873. "info on the codepoints each contains.\n"
  874. "@ingroup Font\n" )
  875. {
  876. Resource<GFont> theFont = ResourceManager::get().startResourceList( Resource<GFont>::signature() );
  877. Con::printf("--------------------------------------------------------------------------");
  878. Con::printf(" Font Cache Usage Report");
  879. while( theFont != NULL )
  880. {
  881. theFont->dumpInfo();
  882. theFont = ResourceManager::get().nextResource();
  883. }
  884. }
  885. DefineEngineFunction( writeFontCache, void, (),,
  886. "Force all cached fonts to serialize themselves to the cache.\n"
  887. "@ingroup Font\n" )
  888. {
  889. Resource<GFont> theFont = ResourceManager::get().startResourceList( Resource<GFont>::signature() );
  890. Con::printf("--------------------------------------------------------------------------");
  891. Con::printf(" Writing font cache to disk");
  892. while( theFont != NULL )
  893. {
  894. const String fileName( theFont.getPath() );
  895. FileStream stream;
  896. stream.open(fileName, Torque::FS::File::Write);
  897. if(stream.getStatus() == Stream::Ok)
  898. {
  899. Con::printf(" o Writing '%s' to disk...", fileName.c_str());
  900. theFont->write(stream);
  901. }
  902. else
  903. {
  904. Con::errorf(" o Could not open '%s' for write", fileName.c_str());
  905. }
  906. theFont = ResourceManager::get().nextResource();
  907. }
  908. }
  909. DefineEngineFunction( populateAllFontCacheString, void, ( const char *string ),,
  910. "Populate the font cache for all fonts with characters from the specified string.\n"
  911. "@ingroup Font\n" )
  912. {
  913. Resource<GFont> theFont = ResourceManager::get().startResourceList( Resource<GFont>::signature() );
  914. Con::printf("Populating font cache with string '%s'", string);
  915. while( theFont != NULL )
  916. {
  917. if(theFont->hasPlatformFont())
  918. {
  919. // This has the side effect of generating character info, including the bitmaps.
  920. theFont->getStrWidthPrecise( string );
  921. }
  922. else
  923. {
  924. const String fileName( theFont.getPath() );
  925. Con::errorf("populateAllFontCacheString - font '%s' has no platform font. Cannot generate more characters.", fileName.c_str());
  926. }
  927. theFont = ResourceManager::get().nextResource();
  928. }
  929. }
  930. DefineEngineFunction( populateAllFontCacheRange, void, ( U32 rangeStart, U32 rangeEnd ),,
  931. "Populate the font cache for all fonts with Unicode code points in the specified range.\n"
  932. "@param rangeStart The start Unicode point.\n"
  933. "@param rangeEnd The end Unicode point.\n"
  934. "@note We only support BMP-0, so code points range from 0 to 65535.\n"
  935. "@ingroup Font\n" )
  936. {
  937. if(rangeStart > rangeEnd)
  938. {
  939. Con::errorf("populateAllFontCacheRange - range start is after end!");
  940. return;
  941. }
  942. Resource<GFont> theFont = ResourceManager::get().startResourceList( Resource<GFont>::signature() );
  943. Con::printf("Populating font cache with range 0x%x to 0x%x", rangeStart, rangeEnd);
  944. while( theFont != NULL )
  945. {
  946. const String fileName( theFont.getPath() );
  947. if(theFont->hasPlatformFont())
  948. {
  949. // This has the side effect of generating character info, including the bitmaps.
  950. Con::printf(" o Populating font '%s'", fileName.c_str());
  951. for(U32 i=rangeStart; i<rangeEnd; i++)
  952. {
  953. if(theFont->isValidChar(i))
  954. theFont->getCharWidth(i);
  955. else
  956. Con::warnf("populateAllFontCacheRange - skipping invalid char 0x%x", i);
  957. }
  958. }
  959. else
  960. {
  961. Con::errorf("populateAllFontCacheRange - font '%s' has no platform font. Cannot generate more characters.", fileName.c_str());
  962. }
  963. theFont = ResourceManager::get().nextResource();
  964. }
  965. }
  966. DefineEngineFunction( exportCachedFont, void,
  967. ( const char *faceName, S32 fontSize, const char *fileName, S32 padding, S32 kerning ),,
  968. "Export specified font to the specified filename as a PNG. The "
  969. "image can then be processed in Photoshop or another tool and "
  970. "reimported using importCachedFont. Characters in the font are "
  971. "exported as one long strip.\n"
  972. "@param faceName The name of the font face.\n"
  973. "@param fontSize The size of the font in pixels.\n"
  974. "@param fileName The file name and path for the output PNG.\n"
  975. "@param padding The padding between characters.\n"
  976. "@param kerning The kerning between characters.\n"
  977. "@ingroup Font\n" )
  978. {
  979. // Tell the font to export itself.
  980. Resource<GFont> f = GFont::create(faceName, fontSize, Con::getVariable("$GUI::fontCacheDirectory"));
  981. if(f == NULL)
  982. {
  983. Con::errorf("exportCachedFont - could not load font '%s %d'", faceName, fontSize);
  984. return;
  985. }
  986. f->exportStrip(fileName, padding, kerning);
  987. }
  988. DefineEngineFunction( importCachedFont, void,
  989. ( const char *faceName, S32 fontSize, const char *fileName, S32 padding, S32 kerning ),,
  990. "Import an image strip from exportCachedFont. Call with the "
  991. "same parameters you called exportCachedFont.\n"
  992. "@param faceName The name of the font face.\n"
  993. "@param fontSize The size of the font in pixels.\n"
  994. "@param fileName The file name and path for the input PNG.\n"
  995. "@param padding The padding between characters.\n"
  996. "@param kerning The kerning between characters.\n"
  997. "@ingroup Font\n" )
  998. {
  999. // Tell the font to import itself.
  1000. Resource<GFont> f = GFont::create(faceName, fontSize, Con::getVariable("$GUI::fontCacheDirectory"));
  1001. if(f == NULL)
  1002. {
  1003. Con::errorf("importCachedFont - could not load font '%s %d'", faceName, fontSize);
  1004. return;
  1005. }
  1006. f->importStrip(fileName, padding, kerning);
  1007. }
  1008. DefineEngineFunction( duplicateCachedFont, void,
  1009. ( const char *oldFontName, S32 oldFontSize, const char *newFontName ),,
  1010. "Copy the specified old font to a new name. The new copy will not have a "
  1011. "platform font backing it, and so will never have characters added to it. "
  1012. "But this is useful for making copies of fonts to add postprocessing effects "
  1013. "to via exportCachedFont.\n"
  1014. "@param oldFontName The name of the font face to copy.\n"
  1015. "@param oldFontSize The size of the font to copy.\n"
  1016. "@param newFontName The name of the new font face.\n"
  1017. "@ingroup Font\n" )
  1018. {
  1019. String newFontFile = GFont::getFontCacheFilename(newFontName, oldFontSize);
  1020. // Load the original font.
  1021. Resource<GFont> font = GFont::create(oldFontName, oldFontSize, Con::getVariable("$GUI::fontCacheDirectory"));
  1022. // Deal with inexplicably missing or failed to load fonts.
  1023. if (font == NULL)
  1024. {
  1025. Con::errorf(" o Couldn't find font : %s", oldFontName);
  1026. return;
  1027. }
  1028. // Ok, dump info!
  1029. FileStream stream;
  1030. stream.open( newFontFile, Torque::FS::File::Write );
  1031. if(stream.getStatus() == Stream::Ok)
  1032. {
  1033. Con::printf( " o Writing duplicate font '%s' to disk...", newFontFile.c_str() );
  1034. font->write(stream);
  1035. stream.close();
  1036. }
  1037. else
  1038. {
  1039. Con::errorf( " o Could not open '%s' for write", newFontFile.c_str() );
  1040. }
  1041. }