gFont.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  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. convertUTF8toUTF16(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. convertUTF8toUTF16(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. U32 wide = 0;
  450. startLine = i;
  451. startLineOffset.push_back(startLine);
  452. // loop until the string is too large
  453. bool needsNewLine = false;
  454. U32 lineStrWidth = 0;
  455. for (; i < len; i++)
  456. {
  457. if( txt[ i ] == '\n' )
  458. {
  459. needsNewLine = true;
  460. break;
  461. }
  462. else if(isValidChar(txt[i]))
  463. {
  464. lineStrWidth += getCharInfo(txt[i]).xIncrement;
  465. if(txt[i] < 0) // symbols which code > 127
  466. {
  467. wide++; i++;
  468. }
  469. if( lineStrWidth > lineWidth )
  470. {
  471. needsNewLine = true;
  472. break;
  473. }
  474. }
  475. }
  476. if (!needsNewLine)
  477. {
  478. // we are done!
  479. lineLen.push_back(i - startLine - wide);
  480. return;
  481. }
  482. S32 j;
  483. // Did we hit a hardwrap (newline character) in the string.
  484. bool hardwrap = ( txt[i] == '\n' );
  485. if ( hardwrap )
  486. {
  487. j = i;
  488. }
  489. // determine where to put the newline
  490. // we need to backtrack until we find a space character
  491. // we don't do this for hardwrap(s)
  492. else
  493. {
  494. for (j = i - 1; j >= startLine; j--)
  495. {
  496. if ( dIsspace(txt[j]) || txt[i] == '\n' )
  497. break;
  498. }
  499. if (j < startLine)
  500. {
  501. // the line consists of a single word!
  502. // So, just break up the word
  503. j = i - 1;
  504. }
  505. }
  506. lineLen.push_back(j - startLine - wide);
  507. i = j;
  508. // Now we need to increment through any space characters at the
  509. // beginning of the next line.
  510. // We don't skip spaces after a hardwrap because they were obviously intended.
  511. for (i++; i < len; i++)
  512. {
  513. if ( txt[i] == '\n' )
  514. continue;
  515. if ( dIsspace( txt[i] ) && !hardwrap )
  516. continue;
  517. break;
  518. }
  519. }
  520. }
  521. //-----------------------------------------------------------------------------
  522. bool GFont::read(Stream& io_rStream)
  523. {
  524. // Handle versioning
  525. U32 version;
  526. io_rStream.read(&version);
  527. if(version != csm_fileVersion)
  528. return false;
  529. char buf[256];
  530. io_rStream.readString(buf);
  531. mFaceName = buf;
  532. io_rStream.read(&mSize);
  533. io_rStream.read(&mCharSet);
  534. io_rStream.read(&mHeight);
  535. io_rStream.read(&mBaseline);
  536. io_rStream.read(&mAscent);
  537. io_rStream.read(&mDescent);
  538. U32 size = 0;
  539. io_rStream.read(&size);
  540. mCharInfoList.setSize(size);
  541. U32 i;
  542. for(i = 0; i < size; i++)
  543. {
  544. PlatformFont::CharInfo *ci = &mCharInfoList[i];
  545. io_rStream.read(&ci->bitmapIndex);
  546. io_rStream.read(&ci->xOffset);
  547. io_rStream.read(&ci->yOffset);
  548. io_rStream.read(&ci->width);
  549. io_rStream.read(&ci->height);
  550. io_rStream.read(&ci->xOrigin);
  551. io_rStream.read(&ci->yOrigin);
  552. io_rStream.read(&ci->xIncrement);
  553. ci->bitmapData = NULL;
  554. }
  555. U32 numSheets = 0;
  556. io_rStream.read(&numSheets);
  557. for(i = 0; i < numSheets; i++)
  558. {
  559. GBitmap *bmp = new GBitmap;
  560. if(!bmp->readBitmap("png", io_rStream))
  561. {
  562. delete bmp;
  563. return false;
  564. }
  565. GFXTexHandle handle = GFXTexHandle(bmp, &GFXFontTextureProfile, true, avar("%s() - Read Font Sheet for %s %d (line %d)", __FUNCTION__, mFaceName.c_str(), mSize, __LINE__));
  566. //handle.setFilterNearest();
  567. mTextureSheets.push_back(handle);
  568. }
  569. // Read last position info
  570. io_rStream.read(&mCurX);
  571. io_rStream.read(&mCurY);
  572. io_rStream.read(&mCurSheet);
  573. // Read the remap table.
  574. U32 minGlyph, maxGlyph;
  575. io_rStream.read(&minGlyph);
  576. io_rStream.read(&maxGlyph);
  577. if(maxGlyph >= minGlyph)
  578. {
  579. // Length of buffer..
  580. U32 buffLen;
  581. io_rStream.read(&buffLen);
  582. // Read the buffer.
  583. FrameTemp<S32> inBuff(buffLen);
  584. io_rStream.read(buffLen, inBuff);
  585. // Decompress.
  586. uLongf destLen = (maxGlyph-minGlyph+1)*sizeof(S32);
  587. uncompress((Bytef*)&mRemapTable[minGlyph], &destLen, (Bytef*)(S32*)inBuff, buffLen);
  588. AssertISV(destLen == (maxGlyph-minGlyph+1)*sizeof(S32), "GFont::read - invalid remap table data!");
  589. // Make sure we've got the right endianness.
  590. for(i = minGlyph; i <= maxGlyph; i++)
  591. mRemapTable[i] = convertBEndianToHost(mRemapTable[i]);
  592. }
  593. return (io_rStream.getStatus() == Stream::Ok);
  594. }
  595. bool GFont::write(Stream& stream)
  596. {
  597. // Handle versioning
  598. stream.write(csm_fileVersion);
  599. // Write font info
  600. stream.write(mFaceName);
  601. stream.write(mSize);
  602. stream.write(mCharSet);
  603. stream.write(mHeight);
  604. stream.write(mBaseline);
  605. stream.write(mAscent);
  606. stream.write(mDescent);
  607. // Write char info list
  608. stream.write(U32(mCharInfoList.size()));
  609. U32 i;
  610. for(i = 0; i < mCharInfoList.size(); i++)
  611. {
  612. const PlatformFont::CharInfo *ci = &mCharInfoList[i];
  613. stream.write(ci->bitmapIndex);
  614. stream.write(ci->xOffset);
  615. stream.write(ci->yOffset);
  616. stream.write(ci->width);
  617. stream.write(ci->height);
  618. stream.write(ci->xOrigin);
  619. stream.write(ci->yOrigin);
  620. stream.write(ci->xIncrement);
  621. }
  622. stream.write(mTextureSheets.size());
  623. for(i = 0; i < mTextureSheets.size(); i++)
  624. mTextureSheets[i].getBitmap()->writeBitmap("png", stream);
  625. stream.write(mCurX);
  626. stream.write(mCurY);
  627. stream.write(mCurSheet);
  628. // Get the min/max we have values for, and only write that range out.
  629. S32 minGlyph = S32_MAX, maxGlyph = 0;
  630. for(i = 0; i < 65536; i++)
  631. {
  632. if(mRemapTable[i] != -1)
  633. {
  634. if(i>maxGlyph) maxGlyph = i;
  635. if(i<minGlyph) minGlyph = i;
  636. }
  637. }
  638. stream.write(minGlyph);
  639. stream.write(maxGlyph);
  640. // Skip it if we don't have any glyphs to do...
  641. if(maxGlyph >= minGlyph)
  642. {
  643. // Put everything big endian, to be consistent. Do this inplace.
  644. for(i = minGlyph; i <= maxGlyph; i++)
  645. mRemapTable[i] = convertHostToBEndian(mRemapTable[i]);
  646. {
  647. // Compress.
  648. const U32 buffSize = 128 * 1024;
  649. FrameTemp<S32> outBuff(buffSize);
  650. uLongf destLen = buffSize * sizeof(S32);
  651. compress2((Bytef*)(S32*)outBuff, &destLen, (Bytef*)(S32*)&mRemapTable[minGlyph], (maxGlyph-minGlyph+1)*sizeof(S32), 9);
  652. // Write out.
  653. stream.write((U32)destLen);
  654. stream.write(destLen, outBuff);
  655. }
  656. // Put us back to normal.
  657. for(i = minGlyph; i <= maxGlyph; i++)
  658. mRemapTable[i] = convertBEndianToHost(mRemapTable[i]);
  659. }
  660. return (stream.getStatus() == Stream::Ok);
  661. }
  662. void GFont::exportStrip(const char *fileName, U32 padding, U32 kerning)
  663. {
  664. // Figure dimensions of our strip by iterating over all the char infos.
  665. U32 totalHeight = 0;
  666. U32 totalWidth = 0;
  667. S32 heightMin=0, heightMax=0;
  668. for(S32 i=0; i<mCharInfoList.size(); i++)
  669. {
  670. totalWidth += mCharInfoList[i].width + kerning + 2*padding;
  671. heightMin = getMin((S32)heightMin, (S32)getBaseline() - (S32)mCharInfoList[i].yOrigin);
  672. heightMax = getMax((S32)heightMax, (S32)getBaseline() - (S32)mCharInfoList[i].yOrigin + (S32)mCharInfoList[i].height);
  673. }
  674. totalHeight = heightMax - heightMin + 2*padding;
  675. // Make the bitmap.
  676. GBitmap gb(totalWidth, totalHeight, false, mTextureSheets[0].getBitmap()->getFormat());
  677. dMemset(gb.getWritableBits(), 0, sizeof(U8) * totalHeight * totalWidth );
  678. // Ok, copy some rects, taking into account padding, kerning, offset.
  679. U32 curWidth = kerning + padding;
  680. for(S32 i=0; i<mCharInfoList.size(); i++)
  681. {
  682. // Skip invalid stuff.
  683. if(mCharInfoList[i].bitmapIndex == -1 || mCharInfoList[i].height == 0 || mCharInfoList[i].width == 0)
  684. continue;
  685. // Copy the rect.
  686. U32 bitmap = mCharInfoList[i].bitmapIndex;
  687. RectI ri(mCharInfoList[i].xOffset, mCharInfoList[i].yOffset, mCharInfoList[i].width, mCharInfoList[i].height );
  688. Point2I outRi(curWidth, padding + getBaseline() - mCharInfoList[i].yOrigin);
  689. gb.copyRect(mTextureSheets[bitmap].getBitmap(), ri, outRi);
  690. // Advance.
  691. curWidth += mCharInfoList[i].width + kerning + 2*padding;
  692. }
  693. // Write the image!
  694. FileStream fs;
  695. fs.open( fileName, Torque::FS::File::Write );
  696. if(fs.getStatus() != Stream::Ok)
  697. {
  698. Con::errorf("GFont::exportStrip - failed to open '%s' for writing.", fileName);
  699. return;
  700. }
  701. // Done!
  702. gb.writeBitmap("png", fs);
  703. }
  704. void GFont::setPlatformFont(PlatformFont *inPlatformFont)
  705. {
  706. AssertFatal( mPlatformFont == NULL, "Trying to set platform font which already exists");
  707. mPlatformFont = inPlatformFont;
  708. }
  709. void GFont::importStrip(const char *fileName, U32 padding, U32 kerning)
  710. {
  711. // Wipe our texture sheets, and reload bitmap data from the specified file.
  712. // Also deal with kerning.
  713. // Also, we may have to load RGBA instead of RGB.
  714. // Wipe our texture sheets.
  715. mCurSheet = mCurX = mCurY = 0;
  716. mTextureSheets.clear();
  717. // Now, load the font strip.
  718. Resource<GBitmap> strip = GBitmap::load(fileName);
  719. if(!strip)
  720. {
  721. Con::errorf("GFont::importStrip - could not load file '%s'!", fileName);
  722. return;
  723. }
  724. // And get parsing and copying - load up all the characters as separate
  725. // GBitmaps, sort, then pack. Not terribly efficient but this is basically
  726. // on offline task anyway.
  727. // Ok, snag some glyphs.
  728. Vector<GlyphMap> glyphList;
  729. glyphList.reserve(mCharInfoList.size());
  730. U32 curWidth = 0;
  731. for(S32 i=0; i<mCharInfoList.size(); i++)
  732. {
  733. // Skip invalid stuff.
  734. if(mCharInfoList[i].bitmapIndex == -1 || mCharInfoList[i].height == 0 || mCharInfoList[i].width == 0)
  735. continue;
  736. // Allocate a new bitmap for this glyph, taking into account kerning and padding.
  737. glyphList.increment();
  738. glyphList.last().bitmap = new GBitmap(mCharInfoList[i].width + kerning + 2*padding, mCharInfoList[i].height + 2*padding, false, strip->getFormat());
  739. glyphList.last().charId = i;
  740. // Copy the rect.
  741. RectI ri(curWidth, getBaseline() - mCharInfoList[i].yOrigin, glyphList.last().bitmap->getWidth(), glyphList.last().bitmap->getHeight());
  742. Point2I outRi(0,0);
  743. glyphList.last().bitmap->copyRect(strip, ri, outRi);
  744. // Update glyph attributes.
  745. mCharInfoList[i].width = glyphList.last().bitmap->getWidth();
  746. mCharInfoList[i].height = glyphList.last().bitmap->getHeight();
  747. mCharInfoList[i].xOffset -= kerning + padding;
  748. mCharInfoList[i].xIncrement += kerning;
  749. mCharInfoList[i].yOffset -= padding;
  750. // Advance.
  751. curWidth += ri.extent.x;
  752. }
  753. // Ok, we have a big list of glyphmaps now. So let's sort them, then pack them.
  754. dQsort(glyphList.address(), glyphList.size(), sizeof(GlyphMap), GlyphMapCompare);
  755. // They're sorted by height, so now we can do some sort of awesome packing.
  756. Point2I curSheetSize(256, 256);
  757. Vector<U32> sheetSizes;
  758. S32 curY = 0;
  759. S32 curX = 0;
  760. S32 curLnHeight = 0;
  761. S32 maxHeight = 0;
  762. for(U32 i = 0; i < glyphList.size(); i++)
  763. {
  764. PlatformFont::CharInfo *ci = &mCharInfoList[glyphList[i].charId];
  765. if(ci->height > maxHeight)
  766. maxHeight = ci->height;
  767. if(curX + ci->width > curSheetSize.x)
  768. {
  769. curY += curLnHeight;
  770. curX = 0;
  771. curLnHeight = 0;
  772. }
  773. if(curY + ci->height > curSheetSize.y)
  774. {
  775. sheetSizes.push_back(curSheetSize.y);
  776. curX = 0;
  777. curY = 0;
  778. curLnHeight = 0;
  779. }
  780. if(ci->height > curLnHeight)
  781. curLnHeight = ci->height;
  782. ci->bitmapIndex = sheetSizes.size();
  783. ci->xOffset = curX;
  784. ci->yOffset = curY;
  785. curX += ci->width;
  786. }
  787. // Terminate the packing loop calculations.
  788. curY += curLnHeight;
  789. if(curY < 64)
  790. curSheetSize.y = 64;
  791. else if(curY < 128)
  792. curSheetSize.y = 128;
  793. sheetSizes.push_back(curSheetSize.y);
  794. if(getHeight() + padding * 2 > maxHeight)
  795. maxHeight = getHeight() + padding * 2;
  796. // Allocate texture pages.
  797. for(S32 i=0; i<sheetSizes.size(); i++)
  798. {
  799. GBitmap *bitmap = new GBitmap(TextureSheetSize, TextureSheetSize, false, strip->getFormat());
  800. // Set everything to transparent.
  801. U8 *bits = bitmap->getWritableBits();
  802. dMemset(bits, 0, sizeof(U8) *TextureSheetSize*TextureSheetSize * strip->getBytesPerPixel());
  803. GFXTexHandle handle = GFXTexHandle( bitmap, &GFXFontTextureProfile, true, avar("%s() - Font Sheet for %s (line %d)", __FUNCTION__, fileName, __LINE__) );
  804. mTextureSheets.increment();
  805. mTextureSheets.last() = handle;
  806. }
  807. // Alright, we're ready to copy bits!
  808. for(S32 i=0; i<glyphList.size(); i++)
  809. {
  810. // Copy each glyph into the appropriate place.
  811. PlatformFont::CharInfo *ci = &mCharInfoList[glyphList[i].charId];
  812. U32 bi = ci->bitmapIndex;
  813. mTextureSheets[bi]->getBitmap()->copyRect(glyphList[i].bitmap, RectI(0,0, glyphList[i].bitmap->getWidth(),glyphList[i].bitmap->getHeight()), Point2I(ci->xOffset, ci->yOffset));
  814. }
  815. // Ok, all done! Just refresh some textures and we're set.
  816. for(S32 i=0; i<sheetSizes.size(); i++)
  817. mTextureSheets[i].refresh();
  818. }
  819. DefineEngineFunction( populateFontCacheString, void, ( const char *faceName, S32 fontSize, const char *string ),,
  820. "Populate the font cache for the specified font with characters from the specified string.\n"
  821. "@param faceName The name of the font face.\n"
  822. "@param fontSize The size of the font in pixels.\n"
  823. "@param string The string to populate.\n"
  824. "@ingroup Font\n" )
  825. {
  826. Resource<GFont> f = GFont::create(faceName, fontSize, Con::getVariable("$GUI::fontCacheDirectory"));
  827. if(f == NULL)
  828. {
  829. Con::errorf("populateFontCacheString - could not load font '%s %d'", faceName, fontSize);
  830. return;
  831. }
  832. if(!f->hasPlatformFont())
  833. {
  834. Con::errorf("populateFontCacheString - font '%s %d' has no platform font. Cannot generate more characters.", faceName, fontSize);
  835. return;
  836. }
  837. // This has the side effect of generating character info, including the bitmaps.
  838. f->getStrWidthPrecise( string );
  839. }
  840. DefineEngineFunction( populateFontCacheRange, void, ( const char *faceName, S32 fontSize, U32 rangeStart, U32 rangeEnd ),,
  841. "Populate the font cache for the specified font with Unicode code points in the specified range.\n"
  842. "@param faceName The name of the font face.\n"
  843. "@param fontSize The size of the font in pixels.\n"
  844. "@param rangeStart The start Unicode point.\n"
  845. "@param rangeEnd The end Unicode point.\n"
  846. "@note We only support BMP-0, so code points range from 0 to 65535.\n"
  847. "@ingroup Font\n" )
  848. {
  849. Resource<GFont> f = GFont::create(faceName, fontSize, Con::getVariable("$GUI::fontCacheDirectory"));
  850. if(f == NULL)
  851. {
  852. Con::errorf("populateFontCacheRange - could not load font '%s %d'", faceName, fontSize);
  853. return;
  854. }
  855. if(rangeStart > rangeEnd)
  856. {
  857. Con::errorf("populateFontCacheRange - range start is after end");
  858. return;
  859. }
  860. if(!f->hasPlatformFont())
  861. {
  862. Con::errorf("populateFontCacheRange - font '%s %d' has no platform font Cannot generate more characters.", faceName, fontSize);
  863. return;
  864. }
  865. // This has the side effect of generating character info, including the bitmaps.
  866. for(U32 i=rangeStart; i<rangeEnd; i++)
  867. {
  868. if(f->isValidChar(i))
  869. f->getCharWidth(i);
  870. else
  871. Con::warnf("populateFontCacheRange - skipping invalid char 0x%x", i);
  872. }
  873. // All done!
  874. }
  875. DefineEngineFunction( dumpFontCacheStatus, void, (),,
  876. "Dumps to the console a full description of all cached fonts, along with "
  877. "info on the codepoints each contains.\n"
  878. "@ingroup Font\n" )
  879. {
  880. Resource<GFont> theFont = ResourceManager::get().startResourceList( Resource<GFont>::signature() );
  881. Con::printf("--------------------------------------------------------------------------");
  882. Con::printf(" Font Cache Usage Report");
  883. while( theFont != NULL )
  884. {
  885. theFont->dumpInfo();
  886. theFont = ResourceManager::get().nextResource();
  887. }
  888. }
  889. DefineEngineFunction( writeFontCache, void, (),,
  890. "Force all cached fonts to serialize themselves to the cache.\n"
  891. "@ingroup Font\n" )
  892. {
  893. Resource<GFont> theFont = ResourceManager::get().startResourceList( Resource<GFont>::signature() );
  894. Con::printf("--------------------------------------------------------------------------");
  895. Con::printf(" Writing font cache to disk");
  896. while( theFont != NULL )
  897. {
  898. const String fileName( theFont.getPath() );
  899. FileStream stream;
  900. stream.open(fileName, Torque::FS::File::Write);
  901. if(stream.getStatus() == Stream::Ok)
  902. {
  903. Con::printf(" o Writing '%s' to disk...", fileName.c_str());
  904. theFont->write(stream);
  905. }
  906. else
  907. {
  908. Con::errorf(" o Could not open '%s' for write", fileName.c_str());
  909. }
  910. theFont = ResourceManager::get().nextResource();
  911. }
  912. }
  913. DefineEngineFunction( populateAllFontCacheString, void, ( const char *string ),,
  914. "Populate the font cache for all fonts with characters from the specified string.\n"
  915. "@ingroup Font\n" )
  916. {
  917. Resource<GFont> theFont = ResourceManager::get().startResourceList( Resource<GFont>::signature() );
  918. Con::printf("Populating font cache with string '%s'", string);
  919. while( theFont != NULL )
  920. {
  921. if(theFont->hasPlatformFont())
  922. {
  923. // This has the side effect of generating character info, including the bitmaps.
  924. theFont->getStrWidthPrecise( string );
  925. }
  926. else
  927. {
  928. const String fileName( theFont.getPath() );
  929. Con::errorf("populateAllFontCacheString - font '%s' has no platform font. Cannot generate more characters.", fileName.c_str());
  930. }
  931. theFont = ResourceManager::get().nextResource();
  932. }
  933. }
  934. DefineEngineFunction( populateAllFontCacheRange, void, ( U32 rangeStart, U32 rangeEnd ),,
  935. "Populate the font cache for all fonts with Unicode code points in the specified range.\n"
  936. "@param rangeStart The start Unicode point.\n"
  937. "@param rangeEnd The end Unicode point.\n"
  938. "@note We only support BMP-0, so code points range from 0 to 65535.\n"
  939. "@ingroup Font\n" )
  940. {
  941. if(rangeStart > rangeEnd)
  942. {
  943. Con::errorf("populateAllFontCacheRange - range start is after end!");
  944. return;
  945. }
  946. Resource<GFont> theFont = ResourceManager::get().startResourceList( Resource<GFont>::signature() );
  947. Con::printf("Populating font cache with range 0x%x to 0x%x", rangeStart, rangeEnd);
  948. while( theFont != NULL )
  949. {
  950. const String fileName( theFont.getPath() );
  951. if(theFont->hasPlatformFont())
  952. {
  953. // This has the side effect of generating character info, including the bitmaps.
  954. Con::printf(" o Populating font '%s'", fileName.c_str());
  955. for(U32 i=rangeStart; i<rangeEnd; i++)
  956. {
  957. if(theFont->isValidChar(i))
  958. theFont->getCharWidth(i);
  959. else
  960. Con::warnf("populateAllFontCacheRange - skipping invalid char 0x%x", i);
  961. }
  962. }
  963. else
  964. {
  965. Con::errorf("populateAllFontCacheRange - font '%s' has no platform font. Cannot generate more characters.", fileName.c_str());
  966. }
  967. theFont = ResourceManager::get().nextResource();
  968. }
  969. }
  970. DefineEngineFunction( exportCachedFont, void,
  971. ( const char *faceName, S32 fontSize, const char *fileName, S32 padding, S32 kerning ),,
  972. "Export specified font to the specified filename as a PNG. The "
  973. "image can then be processed in Photoshop or another tool and "
  974. "reimported using importCachedFont. Characters in the font are "
  975. "exported as one long strip.\n"
  976. "@param faceName The name of the font face.\n"
  977. "@param fontSize The size of the font in pixels.\n"
  978. "@param fileName The file name and path for the output PNG.\n"
  979. "@param padding The padding between characters.\n"
  980. "@param kerning The kerning between characters.\n"
  981. "@ingroup Font\n" )
  982. {
  983. // Tell the font to export itself.
  984. Resource<GFont> f = GFont::create(faceName, fontSize, Con::getVariable("$GUI::fontCacheDirectory"));
  985. if(f == NULL)
  986. {
  987. Con::errorf("exportCachedFont - could not load font '%s %d'", faceName, fontSize);
  988. return;
  989. }
  990. f->exportStrip(fileName, padding, kerning);
  991. }
  992. DefineEngineFunction( importCachedFont, void,
  993. ( const char *faceName, S32 fontSize, const char *fileName, S32 padding, S32 kerning ),,
  994. "Import an image strip from exportCachedFont. Call with the "
  995. "same parameters you called exportCachedFont.\n"
  996. "@param faceName The name of the font face.\n"
  997. "@param fontSize The size of the font in pixels.\n"
  998. "@param fileName The file name and path for the input PNG.\n"
  999. "@param padding The padding between characters.\n"
  1000. "@param kerning The kerning between characters.\n"
  1001. "@ingroup Font\n" )
  1002. {
  1003. // Tell the font to import itself.
  1004. Resource<GFont> f = GFont::create(faceName, fontSize, Con::getVariable("$GUI::fontCacheDirectory"));
  1005. if(f == NULL)
  1006. {
  1007. Con::errorf("importCachedFont - could not load font '%s %d'", faceName, fontSize);
  1008. return;
  1009. }
  1010. f->importStrip(fileName, padding, kerning);
  1011. }
  1012. DefineEngineFunction( duplicateCachedFont, void,
  1013. ( const char *oldFontName, S32 oldFontSize, const char *newFontName ),,
  1014. "Copy the specified old font to a new name. The new copy will not have a "
  1015. "platform font backing it, and so will never have characters added to it. "
  1016. "But this is useful for making copies of fonts to add postprocessing effects "
  1017. "to via exportCachedFont.\n"
  1018. "@param oldFontName The name of the font face to copy.\n"
  1019. "@param oldFontSize The size of the font to copy.\n"
  1020. "@param newFontName The name of the new font face.\n"
  1021. "@ingroup Font\n" )
  1022. {
  1023. String newFontFile = GFont::getFontCacheFilename(newFontName, oldFontSize);
  1024. // Load the original font.
  1025. Resource<GFont> font = GFont::create(oldFontName, oldFontSize, Con::getVariable("$GUI::fontCacheDirectory"));
  1026. // Deal with inexplicably missing or failed to load fonts.
  1027. if (font == NULL)
  1028. {
  1029. Con::errorf(" o Couldn't find font : %s", oldFontName);
  1030. return;
  1031. }
  1032. // Ok, dump info!
  1033. FileStream stream;
  1034. stream.open( newFontFile, Torque::FS::File::Write );
  1035. if(stream.getStatus() == Stream::Ok)
  1036. {
  1037. Con::printf( " o Writing duplicate font '%s' to disk...", newFontFile.c_str() );
  1038. font->write(stream);
  1039. stream.close();
  1040. }
  1041. else
  1042. {
  1043. Con::errorf( " o Could not open '%s' for write", newFontFile.c_str() );
  1044. }
  1045. }