Font.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047
  1. /**
  2. * Copyright (c) 2006-2020 LOVE Development Team
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. * 2. Altered source versions must be plainly marked as such, and must not be
  17. * misrepresented as being the original software.
  18. * 3. This notice may not be removed or altered from any source distribution.
  19. **/
  20. #include "common/config.h"
  21. #include "Font.h"
  22. #include "font/GlyphData.h"
  23. #include "libraries/utf8/utf8.h"
  24. #include "common/math.h"
  25. #include "common/Matrix.h"
  26. #include "Graphics.h"
  27. #include <math.h>
  28. #include <sstream>
  29. #include <algorithm> // for max
  30. #include <limits>
  31. namespace love
  32. {
  33. namespace graphics
  34. {
  35. static inline uint16 normToUint16(double n)
  36. {
  37. return (uint16) (n * LOVE_UINT16_MAX);
  38. }
  39. love::Type Font::type("Font", &Object::type);
  40. int Font::fontCount = 0;
  41. const vertex::CommonFormat Font::vertexFormat = vertex::CommonFormat::XYf_STus_RGBAub;
  42. Font::Font(love::font::Rasterizer *r, const SamplerState &s)
  43. : rasterizers({r})
  44. , height(r->getHeight())
  45. , lineHeight(1)
  46. , textureWidth(128)
  47. , textureHeight(128)
  48. , samplerState()
  49. , dpiScale(r->getDPIScale())
  50. , useSpacesAsTab(false)
  51. , textureCacheID(0)
  52. {
  53. samplerState.minFilter = s.minFilter;
  54. samplerState.magFilter = s.magFilter;
  55. samplerState.maxAnisotropy = s.maxAnisotropy;
  56. // Try to find the best texture size match for the font size. default to the
  57. // largest texture size if no rough match is found.
  58. while (true)
  59. {
  60. if ((height * 0.8) * height * 30 <= textureWidth * textureHeight)
  61. break;
  62. TextureSize nextsize = getNextTextureSize();
  63. if (nextsize.width <= textureWidth && nextsize.height <= textureHeight)
  64. break;
  65. textureWidth = nextsize.width;
  66. textureHeight = nextsize.height;
  67. }
  68. love::font::GlyphData *gd = r->getGlyphData(32); // Space character.
  69. pixelFormat = gd->getFormat();
  70. gd->release();
  71. if (!r->hasGlyph(9)) // No tab character in the Rasterizer.
  72. useSpacesAsTab = true;
  73. loadVolatile();
  74. ++fontCount;
  75. }
  76. Font::~Font()
  77. {
  78. --fontCount;
  79. }
  80. Font::TextureSize Font::getNextTextureSize() const
  81. {
  82. TextureSize size = {textureWidth, textureHeight};
  83. int maxsize = 2048;
  84. auto gfx = Module::getInstance<Graphics>(Module::M_GRAPHICS);
  85. if (gfx != nullptr)
  86. {
  87. const auto &caps = gfx->getCapabilities();
  88. maxsize = (int) caps.limits[Graphics::LIMIT_TEXTURE_SIZE];
  89. }
  90. int maxwidth = std::min(8192, maxsize);
  91. int maxheight = std::min(4096, maxsize);
  92. if (size.width * 2 <= maxwidth || size.height * 2 <= maxheight)
  93. {
  94. // {128, 128} -> {256, 128} -> {256, 256} -> {512, 256} -> etc.
  95. if (size.width == size.height)
  96. size.width *= 2;
  97. else
  98. size.height *= 2;
  99. }
  100. return size;
  101. }
  102. bool Font::loadVolatile()
  103. {
  104. textureCacheID++;
  105. glyphs.clear();
  106. textures.clear();
  107. createTexture();
  108. return true;
  109. }
  110. void Font::createTexture()
  111. {
  112. auto gfx = Module::getInstance<graphics::Graphics>(Module::M_GRAPHICS);
  113. gfx->flushStreamDraws();
  114. Texture *texture = nullptr;
  115. TextureSize size = {textureWidth, textureHeight};
  116. TextureSize nextsize = getNextTextureSize();
  117. bool recreatetexture = false;
  118. // If we have an existing texture already, we'll try replacing it with a
  119. // larger-sized one rather than creating a second one. Having a single
  120. // texture reduces texture switches and draw calls when rendering.
  121. if ((nextsize.width > size.width || nextsize.height > size.height) && !textures.empty())
  122. {
  123. recreatetexture = true;
  124. size = nextsize;
  125. textures.pop_back();
  126. }
  127. Image::Settings settings;
  128. texture = gfx->newImage(TEXTURE_2D, pixelFormat, size.width, size.height, 1, settings);
  129. texture->setSamplerState(samplerState);
  130. {
  131. size_t bpp = getPixelFormatSize(pixelFormat);
  132. size_t pixelcount = size.width * size.height;
  133. // Initialize the texture with transparent white for Luminance-Alpha
  134. // formats (since we keep luminance constant and vary alpha in those
  135. // glyphs), and transparent black otherwise.
  136. std::vector<uint8> emptydata(pixelcount * bpp, 0);
  137. if (pixelFormat == PIXELFORMAT_LA8_UNORM)
  138. {
  139. for (size_t i = 0; i < pixelcount; i++)
  140. emptydata[i * 2 + 0] = 255;
  141. }
  142. Rect rect = {0, 0, size.width, size.height};
  143. texture->replacePixels(emptydata.data(), emptydata.size(), 0, 0, rect, false);
  144. }
  145. textures.emplace_back(texture, Acquire::NORETAIN);
  146. textureWidth = size.width;
  147. textureHeight = size.height;
  148. rowHeight = textureX = textureY = TEXTURE_PADDING;
  149. // Re-add the old glyphs if we re-created the existing texture object.
  150. if (recreatetexture)
  151. {
  152. textureCacheID++;
  153. std::vector<uint32> glyphstoadd;
  154. for (const auto &glyphpair : glyphs)
  155. glyphstoadd.push_back(glyphpair.first);
  156. glyphs.clear();
  157. for (uint32 g : glyphstoadd)
  158. addGlyph(g);
  159. }
  160. }
  161. void Font::unloadVolatile()
  162. {
  163. glyphs.clear();
  164. textures.clear();
  165. }
  166. love::font::GlyphData *Font::getRasterizerGlyphData(uint32 glyph)
  167. {
  168. // Use spaces for the tab 'glyph'.
  169. if (glyph == 9 && useSpacesAsTab)
  170. {
  171. love::font::GlyphData *spacegd = rasterizers[0]->getGlyphData(32);
  172. PixelFormat fmt = spacegd->getFormat();
  173. love::font::GlyphMetrics gm = {};
  174. gm.advance = spacegd->getAdvance() * SPACES_PER_TAB;
  175. gm.bearingX = spacegd->getBearingX();
  176. gm.bearingY = spacegd->getBearingY();
  177. spacegd->release();
  178. return new love::font::GlyphData(glyph, gm, fmt);
  179. }
  180. for (const StrongRef<love::font::Rasterizer> &r : rasterizers)
  181. {
  182. if (r->hasGlyph(glyph))
  183. return r->getGlyphData(glyph);
  184. }
  185. return rasterizers[0]->getGlyphData(glyph);
  186. }
  187. const Font::Glyph &Font::addGlyph(uint32 glyph)
  188. {
  189. StrongRef<love::font::GlyphData> gd(getRasterizerGlyphData(glyph), Acquire::NORETAIN);
  190. int w = gd->getWidth();
  191. int h = gd->getHeight();
  192. if (w + TEXTURE_PADDING * 2 < textureWidth && h + TEXTURE_PADDING * 2 < textureHeight)
  193. {
  194. if (textureX + w + TEXTURE_PADDING > textureWidth)
  195. {
  196. // Out of space - new row!
  197. textureX = TEXTURE_PADDING;
  198. textureY += rowHeight;
  199. rowHeight = TEXTURE_PADDING;
  200. }
  201. if (textureY + h + TEXTURE_PADDING > textureHeight)
  202. {
  203. // Totally out of space - new texture!
  204. createTexture();
  205. // Makes sure the above code for checking if the glyph can fit at
  206. // the current position in the texture is run again for this glyph.
  207. return addGlyph(glyph);
  208. }
  209. }
  210. Glyph g;
  211. g.texture = 0;
  212. g.spacing = floorf(gd->getAdvance() / dpiScale + 0.5f);
  213. memset(g.vertices, 0, sizeof(GlyphVertex) * 4);
  214. // Don't waste space for empty glyphs.
  215. if (w > 0 && h > 0)
  216. {
  217. Texture *texture = textures.back();
  218. g.texture = texture;
  219. Rect rect = {textureX, textureY, gd->getWidth(), gd->getHeight()};
  220. texture->replacePixels(gd->getData(), gd->getSize(), 0, 0, rect, false);
  221. double tX = (double) textureX, tY = (double) textureY;
  222. double tWidth = (double) textureWidth, tHeight = (double) textureHeight;
  223. Color32 c(255, 255, 255, 255);
  224. // Extrude the quad borders by 1 pixel. We have an extra pixel of
  225. // transparent padding in the texture atlas, so the quad extrusion will
  226. // add some antialiasing at the edges of the quad.
  227. int o = 1;
  228. // 0---2
  229. // | / |
  230. // 1---3
  231. const GlyphVertex verts[4] =
  232. {
  233. {float(-o), float(-o), normToUint16((tX-o)/tWidth), normToUint16((tY-o)/tHeight), c},
  234. {float(-o), (h+o)/dpiScale, normToUint16((tX-o)/tWidth), normToUint16((tY+h+o)/tHeight), c},
  235. {(w+o)/dpiScale, float(-o), normToUint16((tX+w+o)/tWidth), normToUint16((tY-o)/tHeight), c},
  236. {(w+o)/dpiScale, (h+o)/dpiScale, normToUint16((tX+w+o)/tWidth), normToUint16((tY+h+o)/tHeight), c}
  237. };
  238. // Copy vertex data to the glyph and set proper bearing.
  239. for (int i = 0; i < 4; i++)
  240. {
  241. g.vertices[i] = verts[i];
  242. g.vertices[i].x += gd->getBearingX() / dpiScale;
  243. g.vertices[i].y -= gd->getBearingY() / dpiScale;
  244. }
  245. textureX += w + TEXTURE_PADDING;
  246. rowHeight = std::max(rowHeight, h + TEXTURE_PADDING);
  247. }
  248. glyphs[glyph] = g;
  249. return glyphs[glyph];
  250. }
  251. const Font::Glyph &Font::findGlyph(uint32 glyph)
  252. {
  253. const auto it = glyphs.find(glyph);
  254. if (it != glyphs.end())
  255. return it->second;
  256. return addGlyph(glyph);
  257. }
  258. float Font::getKerning(uint32 leftglyph, uint32 rightglyph)
  259. {
  260. uint64 packedglyphs = ((uint64) leftglyph << 32) | (uint64) rightglyph;
  261. const auto it = kerning.find(packedglyphs);
  262. if (it != kerning.end())
  263. return it->second;
  264. float k = rasterizers[0]->getKerning(leftglyph, rightglyph);
  265. for (const auto &r : rasterizers)
  266. {
  267. if (r->hasGlyph(leftglyph) && r->hasGlyph(rightglyph))
  268. {
  269. k = floorf(r->getKerning(leftglyph, rightglyph) / dpiScale + 0.5f);
  270. break;
  271. }
  272. }
  273. kerning[packedglyphs] = k;
  274. return k;
  275. }
  276. void Font::getCodepointsFromString(const std::string &text, Codepoints &codepoints)
  277. {
  278. codepoints.reserve(text.size());
  279. try
  280. {
  281. utf8::iterator<std::string::const_iterator> i(text.begin(), text.begin(), text.end());
  282. utf8::iterator<std::string::const_iterator> end(text.end(), text.begin(), text.end());
  283. while (i != end)
  284. {
  285. uint32 g = *i++;
  286. codepoints.push_back(g);
  287. }
  288. }
  289. catch (utf8::exception &e)
  290. {
  291. throw love::Exception("UTF-8 decoding error: %s", e.what());
  292. }
  293. }
  294. void Font::getCodepointsFromString(const std::vector<ColoredString> &strs, ColoredCodepoints &codepoints)
  295. {
  296. if (strs.empty())
  297. return;
  298. codepoints.cps.reserve(strs[0].str.size());
  299. for (const ColoredString &cstr : strs)
  300. {
  301. // No need to add the color if the string is empty anyway, and the code
  302. // further on assumes no two colors share the same starting position.
  303. if (cstr.str.size() == 0)
  304. continue;
  305. IndexedColor c = {cstr.color, (int) codepoints.cps.size()};
  306. codepoints.colors.push_back(c);
  307. getCodepointsFromString(cstr.str, codepoints.cps);
  308. }
  309. if (codepoints.colors.size() == 1)
  310. {
  311. IndexedColor c = codepoints.colors[0];
  312. if (c.index == 0 && c.color == Colorf(1.0f, 1.0f, 1.0f, 1.0f))
  313. codepoints.colors.pop_back();
  314. }
  315. }
  316. float Font::getHeight() const
  317. {
  318. return (float) floorf(height / dpiScale + 0.5f);
  319. }
  320. std::vector<Font::DrawCommand> Font::generateVertices(const ColoredCodepoints &codepoints, const Colorf &constantcolor, std::vector<GlyphVertex> &vertices, float extra_spacing, Vector2 offset, TextInfo *info)
  321. {
  322. // Spacing counter and newline handling.
  323. float dx = offset.x;
  324. float dy = offset.y;
  325. float heightoffset = 0.0f;
  326. if (rasterizers[0]->getDataType() == font::Rasterizer::DATA_TRUETYPE)
  327. heightoffset = getBaseline();
  328. int maxwidth = 0;
  329. // Keeps track of when we need to switch textures in our vertex array.
  330. std::vector<DrawCommand> commands;
  331. // Pre-allocate space for the maximum possible number of vertices.
  332. size_t vertstartsize = vertices.size();
  333. vertices.reserve(vertstartsize + codepoints.cps.size() * 4);
  334. uint32 prevglyph = 0;
  335. Colorf linearconstantcolor = gammaCorrectColor(constantcolor);
  336. Color32 curcolor = toColor32(constantcolor);
  337. int curcolori = -1;
  338. int ncolors = (int) codepoints.colors.size();
  339. for (int i = 0; i < (int) codepoints.cps.size(); i++)
  340. {
  341. uint32 g = codepoints.cps[i];
  342. if (curcolori + 1 < ncolors && codepoints.colors[curcolori + 1].index == i)
  343. {
  344. Colorf c = codepoints.colors[++curcolori].color;
  345. c.r = std::min(std::max(c.r, 0.0f), 1.0f);
  346. c.g = std::min(std::max(c.g, 0.0f), 1.0f);
  347. c.b = std::min(std::max(c.b, 0.0f), 1.0f);
  348. c.a = std::min(std::max(c.a, 0.0f), 1.0f);
  349. gammaCorrectColor(c);
  350. c *= linearconstantcolor;
  351. unGammaCorrectColor(c);
  352. curcolor = toColor32(c);
  353. }
  354. if (g == '\n')
  355. {
  356. if (dx > maxwidth)
  357. maxwidth = (int) dx;
  358. // Wrap newline, but do not print it.
  359. dy += floorf(getHeight() * getLineHeight() + 0.5f);
  360. dx = offset.x;
  361. prevglyph = 0;
  362. continue;
  363. }
  364. // Ignore carriage returns
  365. if (g == '\r')
  366. continue;
  367. uint32 cacheid = textureCacheID;
  368. const Glyph &glyph = findGlyph(g);
  369. // If findGlyph invalidates the texture cache, re-start the loop.
  370. if (cacheid != textureCacheID)
  371. {
  372. i = -1; // The next iteration will increment this to 0.
  373. maxwidth = 0;
  374. dx = offset.x;
  375. dy = offset.y;
  376. commands.clear();
  377. vertices.resize(vertstartsize);
  378. prevglyph = 0;
  379. curcolori = -1;
  380. curcolor = toColor32(constantcolor);
  381. continue;
  382. }
  383. // Add kerning to the current horizontal offset.
  384. dx += getKerning(prevglyph, g);
  385. if (glyph.texture != nullptr)
  386. {
  387. // Copy the vertices and set their colors and relative positions.
  388. for (int j = 0; j < 4; j++)
  389. {
  390. vertices.push_back(glyph.vertices[j]);
  391. vertices.back().x += dx;
  392. vertices.back().y += dy + heightoffset;
  393. vertices.back().color = curcolor;
  394. }
  395. // Check if glyph texture has changed since the last iteration.
  396. if (commands.empty() || commands.back().texture != glyph.texture)
  397. {
  398. // Add a new draw command if the texture has changed.
  399. DrawCommand cmd;
  400. cmd.startvertex = (int) vertices.size() - 4;
  401. cmd.vertexcount = 0;
  402. cmd.texture = glyph.texture;
  403. commands.push_back(cmd);
  404. }
  405. commands.back().vertexcount += 4;
  406. }
  407. // Advance the x position for the next glyph.
  408. dx += glyph.spacing;
  409. // Account for extra spacing given to space characters.
  410. if (g == ' ' && extra_spacing != 0.0f)
  411. dx = floorf(dx + extra_spacing);
  412. prevglyph = g;
  413. }
  414. const auto drawsort = [](const DrawCommand &a, const DrawCommand &b) -> bool
  415. {
  416. // Texture binds are expensive, so we should sort by that first.
  417. if (a.texture != b.texture)
  418. return a.texture < b.texture;
  419. else
  420. return a.startvertex < b.startvertex;
  421. };
  422. std::sort(commands.begin(), commands.end(), drawsort);
  423. if (dx > maxwidth)
  424. maxwidth = (int) dx;
  425. if (info != nullptr)
  426. {
  427. info->width = maxwidth - offset.x;
  428. info->height = (int) dy + (dx > 0.0f ? floorf(getHeight() * getLineHeight() + 0.5f) : 0) - offset.y;
  429. }
  430. return commands;
  431. }
  432. std::vector<Font::DrawCommand> Font::generateVerticesFormatted(const ColoredCodepoints &text, const Colorf &constantcolor, float wrap, AlignMode align, std::vector<GlyphVertex> &vertices, TextInfo *info)
  433. {
  434. wrap = std::max(wrap, 0.0f);
  435. uint32 cacheid = textureCacheID;
  436. std::vector<DrawCommand> drawcommands;
  437. vertices.reserve(text.cps.size() * 4);
  438. std::vector<int> widths;
  439. std::vector<ColoredCodepoints> lines;
  440. getWrap(text, wrap, lines, &widths);
  441. float y = 0.0f;
  442. float maxwidth = 0.0f;
  443. for (int i = 0; i < (int) lines.size(); i++)
  444. {
  445. const auto &line = lines[i];
  446. float width = (float) widths[i];
  447. love::Vector2 offset(0.0f, floorf(y));
  448. float extraspacing = 0.0f;
  449. maxwidth = std::max(width, maxwidth);
  450. switch (align)
  451. {
  452. case ALIGN_RIGHT:
  453. offset.x = floorf(wrap - width);
  454. break;
  455. case ALIGN_CENTER:
  456. offset.x = floorf((wrap - width) / 2.0f);
  457. break;
  458. case ALIGN_JUSTIFY:
  459. {
  460. float numspaces = (float) std::count(line.cps.begin(), line.cps.end(), ' ');
  461. if (width < wrap && numspaces >= 1)
  462. extraspacing = (wrap - width) / numspaces;
  463. else
  464. extraspacing = 0.0f;
  465. break;
  466. }
  467. case ALIGN_LEFT:
  468. default:
  469. break;
  470. }
  471. std::vector<DrawCommand> newcommands = generateVertices(line, constantcolor, vertices, extraspacing, offset);
  472. if (!newcommands.empty())
  473. {
  474. auto firstcmd = newcommands.begin();
  475. // If the first draw command in the new list has the same texture
  476. // as the last one in the existing list we're building and its
  477. // vertices are in-order, we can combine them (saving a draw call.)
  478. if (!drawcommands.empty())
  479. {
  480. auto prevcmd = drawcommands.back();
  481. if (prevcmd.texture == firstcmd->texture && (prevcmd.startvertex + prevcmd.vertexcount) == firstcmd->startvertex)
  482. {
  483. drawcommands.back().vertexcount += firstcmd->vertexcount;
  484. ++firstcmd;
  485. }
  486. }
  487. // Append the new draw commands to the list we're building.
  488. drawcommands.insert(drawcommands.end(), firstcmd, newcommands.end());
  489. }
  490. y += getHeight() * getLineHeight();
  491. }
  492. if (info != nullptr)
  493. {
  494. info->width = (int) maxwidth;
  495. info->height = (int) y;
  496. }
  497. if (cacheid != textureCacheID)
  498. {
  499. vertices.clear();
  500. drawcommands = generateVerticesFormatted(text, constantcolor, wrap, align, vertices);
  501. }
  502. return drawcommands;
  503. }
  504. void Font::printv(graphics::Graphics *gfx, const Matrix4 &t, const std::vector<DrawCommand> &drawcommands, const std::vector<GlyphVertex> &vertices)
  505. {
  506. if (vertices.empty() || drawcommands.empty())
  507. return;
  508. Matrix4 m(gfx->getTransform(), t);
  509. for (const DrawCommand &cmd : drawcommands)
  510. {
  511. Graphics::StreamDrawCommand streamcmd;
  512. streamcmd.formats[0] = vertexFormat;
  513. streamcmd.indexMode = vertex::TriangleIndexMode::QUADS;
  514. streamcmd.vertexCount = cmd.vertexcount;
  515. streamcmd.texture = cmd.texture;
  516. Graphics::StreamVertexData data = gfx->requestStreamDraw(streamcmd);
  517. GlyphVertex *vertexdata = (GlyphVertex *) data.stream[0];
  518. memcpy(vertexdata, &vertices[cmd.startvertex], sizeof(GlyphVertex) * cmd.vertexcount);
  519. m.transformXY(vertexdata, &vertices[cmd.startvertex], cmd.vertexcount);
  520. }
  521. }
  522. void Font::print(graphics::Graphics *gfx, const std::vector<ColoredString> &text, const Matrix4 &m, const Colorf &constantcolor)
  523. {
  524. ColoredCodepoints codepoints;
  525. getCodepointsFromString(text, codepoints);
  526. std::vector<GlyphVertex> vertices;
  527. std::vector<DrawCommand> drawcommands = generateVertices(codepoints, constantcolor, vertices);
  528. printv(gfx, m, drawcommands, vertices);
  529. }
  530. void Font::printf(graphics::Graphics *gfx, const std::vector<ColoredString> &text, float wrap, AlignMode align, const Matrix4 &m, const Colorf &constantcolor)
  531. {
  532. ColoredCodepoints codepoints;
  533. getCodepointsFromString(text, codepoints);
  534. std::vector<GlyphVertex> vertices;
  535. std::vector<DrawCommand> drawcommands = generateVerticesFormatted(codepoints, constantcolor, wrap, align, vertices);
  536. printv(gfx, m, drawcommands, vertices);
  537. }
  538. int Font::getWidth(const std::string &str)
  539. {
  540. if (str.size() == 0) return 0;
  541. std::istringstream iss(str);
  542. std::string line;
  543. int max_width = 0;
  544. while (getline(iss, line, '\n'))
  545. {
  546. int width = 0;
  547. uint32 prevglyph = 0;
  548. try
  549. {
  550. utf8::iterator<std::string::const_iterator> i(line.begin(), line.begin(), line.end());
  551. utf8::iterator<std::string::const_iterator> end(line.end(), line.begin(), line.end());
  552. while (i != end)
  553. {
  554. uint32 c = *i++;
  555. // Ignore carriage returns
  556. if (c == '\r')
  557. continue;
  558. const Glyph &g = findGlyph(c);
  559. width += g.spacing + getKerning(prevglyph, c);
  560. prevglyph = c;
  561. }
  562. }
  563. catch (utf8::exception &e)
  564. {
  565. throw love::Exception("UTF-8 decoding error: %s", e.what());
  566. }
  567. max_width = std::max(max_width, width);
  568. }
  569. return max_width;
  570. }
  571. int Font::getWidth(char character)
  572. {
  573. const Glyph &g = findGlyph(character);
  574. return g.spacing;
  575. }
  576. void Font::getWrap(const ColoredCodepoints &codepoints, float wraplimit, std::vector<ColoredCodepoints> &lines, std::vector<int> *linewidths)
  577. {
  578. // Per-line info.
  579. float width = 0.0f;
  580. float widthbeforelastspace = 0.0f;
  581. float widthoftrailingspace = 0.0f;
  582. uint32 prevglyph = 0;
  583. int lastspaceindex = -1;
  584. // Keeping the indexed colors "in sync" is a bit tricky, since we split
  585. // things up and we might skip some glyphs but we don't want to skip any
  586. // color which starts at those indices.
  587. Colorf curcolor(1.0f, 1.0f, 1.0f, 1.0f);
  588. bool addcurcolor = false;
  589. int curcolori = -1;
  590. int endcolori = (int) codepoints.colors.size() - 1;
  591. // A wrapped line of text.
  592. ColoredCodepoints wline;
  593. int i = 0;
  594. while (i < (int) codepoints.cps.size())
  595. {
  596. uint32 c = codepoints.cps[i];
  597. // Determine the current color before doing anything else, to make sure
  598. // it's still applied to future glyphs even if this one is skipped.
  599. if (curcolori < endcolori && codepoints.colors[curcolori + 1].index == i)
  600. {
  601. curcolor = codepoints.colors[curcolori + 1].color;
  602. curcolori++;
  603. addcurcolor = true;
  604. }
  605. // Split text at newlines.
  606. if (c == '\n')
  607. {
  608. lines.push_back(wline);
  609. // Ignore the width of any trailing spaces, for individual lines.
  610. if (linewidths)
  611. linewidths->push_back(width - widthoftrailingspace);
  612. // Make sure the new line keeps any color that was set previously.
  613. addcurcolor = true;
  614. width = widthbeforelastspace = widthoftrailingspace = 0.0f;
  615. prevglyph = 0; // Reset kerning information.
  616. lastspaceindex = -1;
  617. wline.cps.clear();
  618. wline.colors.clear();
  619. i++;
  620. continue;
  621. }
  622. // Ignore carriage returns
  623. if (c == '\r')
  624. {
  625. i++;
  626. continue;
  627. }
  628. const Glyph &g = findGlyph(c);
  629. float charwidth = g.spacing + getKerning(prevglyph, c);
  630. float newwidth = width + charwidth;
  631. // Wrap the line if it exceeds the wrap limit. Don't wrap yet if we're
  632. // processing a newline character, though.
  633. if (c != ' ' && newwidth > wraplimit)
  634. {
  635. // If this is the first character in the line and it exceeds the
  636. // limit, skip it completely.
  637. if (wline.cps.empty())
  638. i++;
  639. else if (lastspaceindex != -1)
  640. {
  641. // 'Rewind' to the last seen space, if the line has one.
  642. // FIXME: This could be more efficient...
  643. while (!wline.cps.empty() && wline.cps.back() != ' ')
  644. wline.cps.pop_back();
  645. while (!wline.colors.empty() && wline.colors.back().index >= (int) wline.cps.size())
  646. wline.colors.pop_back();
  647. // Also 'rewind' to the color that the last character is using.
  648. for (int colori = curcolori; colori >= 0; colori--)
  649. {
  650. if (codepoints.colors[colori].index <= lastspaceindex)
  651. {
  652. curcolor = codepoints.colors[colori].color;
  653. curcolori = colori;
  654. break;
  655. }
  656. }
  657. // Ignore the width of trailing spaces in wrapped lines.
  658. width = widthbeforelastspace;
  659. i = lastspaceindex;
  660. i++; // Start the next line after the space.
  661. }
  662. lines.push_back(wline);
  663. if (linewidths)
  664. linewidths->push_back(width);
  665. addcurcolor = true;
  666. prevglyph = 0;
  667. width = widthbeforelastspace = widthoftrailingspace = 0.0f;
  668. wline.cps.clear();
  669. wline.colors.clear();
  670. lastspaceindex = -1;
  671. continue;
  672. }
  673. if (prevglyph != ' ' && c == ' ')
  674. widthbeforelastspace = width;
  675. width = newwidth;
  676. prevglyph = c;
  677. if (addcurcolor)
  678. {
  679. wline.colors.push_back({curcolor, (int) wline.cps.size()});
  680. addcurcolor = false;
  681. }
  682. wline.cps.push_back(c);
  683. // Keep track of the last seen space, so we can "rewind" to it when
  684. // wrapping.
  685. if (c == ' ')
  686. {
  687. lastspaceindex = i;
  688. widthoftrailingspace += charwidth;
  689. }
  690. else if (c != '\n')
  691. widthoftrailingspace = 0.0f;
  692. i++;
  693. }
  694. // Push the last line.
  695. if (!wline.cps.empty())
  696. {
  697. lines.push_back(wline);
  698. // Ignore the width of any trailing spaces, for individual lines.
  699. if (linewidths)
  700. linewidths->push_back(width - widthoftrailingspace);
  701. }
  702. }
  703. void Font::getWrap(const std::vector<ColoredString> &text, float wraplimit, std::vector<std::string> &lines, std::vector<int> *linewidths)
  704. {
  705. ColoredCodepoints cps;
  706. getCodepointsFromString(text, cps);
  707. std::vector<ColoredCodepoints> codepointlines;
  708. getWrap(cps, wraplimit, codepointlines, linewidths);
  709. std::string line;
  710. for (const ColoredCodepoints &codepoints : codepointlines)
  711. {
  712. line.clear();
  713. line.reserve(codepoints.cps.size());
  714. for (uint32 codepoint : codepoints.cps)
  715. {
  716. char character[5] = {'\0'};
  717. char *end = utf8::unchecked::append(codepoint, character);
  718. line.append(character, end - character);
  719. }
  720. lines.push_back(line);
  721. }
  722. }
  723. void Font::setLineHeight(float height)
  724. {
  725. lineHeight = height;
  726. }
  727. float Font::getLineHeight() const
  728. {
  729. return lineHeight;
  730. }
  731. void Font::setSamplerState(const SamplerState &s)
  732. {
  733. samplerState.minFilter = s.minFilter;
  734. samplerState.magFilter = s.magFilter;
  735. samplerState.maxAnisotropy = s.maxAnisotropy;
  736. for (const auto &texture : textures)
  737. texture->setSamplerState(samplerState);
  738. }
  739. const SamplerState &Font::getSamplerState() const
  740. {
  741. return samplerState;
  742. }
  743. int Font::getAscent() const
  744. {
  745. return floorf(rasterizers[0]->getAscent() / dpiScale + 0.5f);
  746. }
  747. int Font::getDescent() const
  748. {
  749. return floorf(rasterizers[0]->getDescent() / dpiScale + 0.5f);
  750. }
  751. float Font::getBaseline() const
  752. {
  753. float ascent = getAscent();
  754. if (ascent != 0.0f)
  755. return ascent;
  756. else if (rasterizers[0]->getDataType() == font::Rasterizer::DATA_TRUETYPE)
  757. return floorf(getHeight() / 1.25f + 0.5f); // 1.25 is magic line height for true type fonts
  758. else
  759. return 0.0f;
  760. }
  761. bool Font::hasGlyph(uint32 glyph) const
  762. {
  763. for (const StrongRef<love::font::Rasterizer> &r : rasterizers)
  764. {
  765. if (r->hasGlyph(glyph))
  766. return true;
  767. }
  768. return false;
  769. }
  770. bool Font::hasGlyphs(const std::string &text) const
  771. {
  772. if (text.size() == 0)
  773. return false;
  774. try
  775. {
  776. utf8::iterator<std::string::const_iterator> i(text.begin(), text.begin(), text.end());
  777. utf8::iterator<std::string::const_iterator> end(text.end(), text.begin(), text.end());
  778. while (i != end)
  779. {
  780. uint32 codepoint = *i++;
  781. if (!hasGlyph(codepoint))
  782. return false;
  783. }
  784. }
  785. catch (utf8::exception &e)
  786. {
  787. throw love::Exception("UTF-8 decoding error: %s", e.what());
  788. }
  789. return true;
  790. }
  791. void Font::setFallbacks(const std::vector<Font *> &fallbacks)
  792. {
  793. for (const Font *f : fallbacks)
  794. {
  795. if (f->rasterizers[0]->getDataType() != this->rasterizers[0]->getDataType())
  796. throw love::Exception("Font fallbacks must be of the same font type.");
  797. }
  798. rasterizers.resize(1);
  799. // NOTE: this won't invalidate already-rasterized glyphs.
  800. for (const Font *f : fallbacks)
  801. rasterizers.push_back(f->rasterizers[0]);
  802. }
  803. float Font::getDPIScale() const
  804. {
  805. return dpiScale;
  806. }
  807. uint32 Font::getTextureCacheID() const
  808. {
  809. return textureCacheID;
  810. }
  811. bool Font::getConstant(const char *in, AlignMode &out)
  812. {
  813. return alignModes.find(in, out);
  814. }
  815. bool Font::getConstant(AlignMode in, const char *&out)
  816. {
  817. return alignModes.find(in, out);
  818. }
  819. std::vector<std::string> Font::getConstants(AlignMode)
  820. {
  821. return alignModes.getNames();
  822. }
  823. StringMap<Font::AlignMode, Font::ALIGN_MAX_ENUM>::Entry Font::alignModeEntries[] =
  824. {
  825. { "left", ALIGN_LEFT },
  826. { "right", ALIGN_RIGHT },
  827. { "center", ALIGN_CENTER },
  828. { "justify", ALIGN_JUSTIFY },
  829. };
  830. StringMap<Font::AlignMode, Font::ALIGN_MAX_ENUM> Font::alignModes(Font::alignModeEntries, sizeof(Font::alignModeEntries));
  831. } // graphics
  832. } // love