Font.cpp 26 KB

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