You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4883 lines
187KB

  1. // stb_truetype.h - v1.21 - public domain
  2. // authored from 2009-2016 by Sean Barrett / RAD Game Tools
  3. //
  4. // This library processes TrueType files:
  5. // parse files
  6. // extract glyph metrics
  7. // extract glyph shapes
  8. // render glyphs to one-channel bitmaps with antialiasing (box filter)
  9. // render glyphs to one-channel SDF bitmaps (signed-distance field/function)
  10. //
  11. // Todo:
  12. // non-MS cmaps
  13. // crashproof on bad data
  14. // hinting? (no longer patented)
  15. // cleartype-style AA?
  16. // optimize: use simple memory allocator for intermediates
  17. // optimize: build edge-list directly from curves
  18. // optimize: rasterize directly from curves?
  19. //
  20. // ADDITIONAL CONTRIBUTORS
  21. //
  22. // Mikko Mononen: compound shape support, more cmap formats
  23. // Tor Andersson: kerning, subpixel rendering
  24. // Dougall Johnson: OpenType / Type 2 font handling
  25. // Daniel Ribeiro Maciel: basic GPOS-based kerning
  26. //
  27. // Misc other:
  28. // Ryan Gordon
  29. // Simon Glass
  30. // github:IntellectualKitty
  31. // Imanol Celaya
  32. // Daniel Ribeiro Maciel
  33. //
  34. // Bug/warning reports/fixes:
  35. // "Zer" on mollyrocket Fabian "ryg" Giesen
  36. // Cass Everitt Martins Mozeiko
  37. // stoiko (Haemimont Games) Cap Petschulat
  38. // Brian Hook Omar Cornut
  39. // Walter van Niftrik github:aloucks
  40. // David Gow Peter LaValle
  41. // David Given Sergey Popov
  42. // Ivan-Assen Ivanov Giumo X. Clanjor
  43. // Anthony Pesch Higor Euripedes
  44. // Johan Duparc Thomas Fields
  45. // Hou Qiming Derek Vinyard
  46. // Rob Loach Cort Stratton
  47. // Kenney Phillis Jr. github:oyvindjam
  48. // Brian Costabile github:vassvik
  49. //
  50. // VERSION HISTORY
  51. //
  52. // 1.21 (2019-02-25) fix warning
  53. // 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics()
  54. // 1.19 (2018-02-11) GPOS kerning, STBTT_fmod
  55. // 1.18 (2018-01-29) add missing function
  56. // 1.17 (2017-07-23) make more arguments const; doc fix
  57. // 1.16 (2017-07-12) SDF support
  58. // 1.15 (2017-03-03) make more arguments const
  59. // 1.14 (2017-01-16) num-fonts-in-TTC function
  60. // 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts
  61. // 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual
  62. // 1.11 (2016-04-02) fix unused-variable warning
  63. // 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef
  64. // 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly
  65. // 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges
  66. // 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;
  67. // variant PackFontRanges to pack and render in separate phases;
  68. // fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);
  69. // fixed an assert() bug in the new rasterizer
  70. // replace assert() with STBTT_assert() in new rasterizer
  71. //
  72. // Full history can be found at the end of this file.
  73. //
  74. // LICENSE
  75. //
  76. // See end of file for license information.
  77. //
  78. // USAGE
  79. //
  80. // Include this file in whatever places need to refer to it. In ONE C/C++
  81. // file, write:
  82. // #define STB_TRUETYPE_IMPLEMENTATION
  83. // before the #include of this file. This expands out the actual
  84. // implementation into that C/C++ file.
  85. //
  86. // To make the implementation private to the file that generates the implementation,
  87. // #define STBTT_STATIC
  88. //
  89. // Simple 3D API (don't ship this, but it's fine for tools and quick start)
  90. // stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture
  91. // stbtt_GetBakedQuad() -- compute quad to draw for a given char
  92. //
  93. // Improved 3D API (more shippable):
  94. // #include "stb_rect_pack.h" -- optional, but you really want it
  95. // stbtt_PackBegin()
  96. // stbtt_PackSetOversampling() -- for improved quality on small fonts
  97. // stbtt_PackFontRanges() -- pack and renders
  98. // stbtt_PackEnd()
  99. // stbtt_GetPackedQuad()
  100. //
  101. // "Load" a font file from a memory buffer (you have to keep the buffer loaded)
  102. // stbtt_InitFont()
  103. // stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections
  104. // stbtt_GetNumberOfFonts() -- number of fonts for TTC font collections
  105. //
  106. // Render a unicode codepoint to a bitmap
  107. // stbtt_GetCodepointBitmap() -- allocates and returns a bitmap
  108. // stbtt_MakeCodepointBitmap() -- renders into bitmap you provide
  109. // stbtt_GetCodepointBitmapBox() -- how big the bitmap must be
  110. //
  111. // Character advance/positioning
  112. // stbtt_GetCodepointHMetrics()
  113. // stbtt_GetFontVMetrics()
  114. // stbtt_GetFontVMetricsOS2()
  115. // stbtt_GetCodepointKernAdvance()
  116. //
  117. // Starting with version 1.06, the rasterizer was replaced with a new,
  118. // faster and generally-more-precise rasterizer. The new rasterizer more
  119. // accurately measures pixel coverage for anti-aliasing, except in the case
  120. // where multiple shapes overlap, in which case it overestimates the AA pixel
  121. // coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If
  122. // this turns out to be a problem, you can re-enable the old rasterizer with
  123. // #define STBTT_RASTERIZER_VERSION 1
  124. // which will incur about a 15% speed hit.
  125. //
  126. // ADDITIONAL DOCUMENTATION
  127. //
  128. // Immediately after this block comment are a series of sample programs.
  129. //
  130. // After the sample programs is the "header file" section. This section
  131. // includes documentation for each API function.
  132. //
  133. // Some important concepts to understand to use this library:
  134. //
  135. // Codepoint
  136. // Characters are defined by unicode codepoints, e.g. 65 is
  137. // uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is
  138. // the hiragana for "ma".
  139. //
  140. // Glyph
  141. // A visual character shape (every codepoint is rendered as
  142. // some glyph)
  143. //
  144. // Glyph index
  145. // A font-specific integer ID representing a glyph
  146. //
  147. // Baseline
  148. // Glyph shapes are defined relative to a baseline, which is the
  149. // bottom of uppercase characters. Characters extend both above
  150. // and below the baseline.
  151. //
  152. // Current Point
  153. // As you draw text to the screen, you keep track of a "current point"
  154. // which is the origin of each character. The current point's vertical
  155. // position is the baseline. Even "baked fonts" use this model.
  156. //
  157. // Vertical Font Metrics
  158. // The vertical qualities of the font, used to vertically position
  159. // and space the characters. See docs for stbtt_GetFontVMetrics.
  160. //
  161. // Font Size in Pixels or Points
  162. // The preferred interface for specifying font sizes in stb_truetype
  163. // is to specify how tall the font's vertical extent should be in pixels.
  164. // If that sounds good enough, skip the next paragraph.
  165. //
  166. // Most font APIs instead use "points", which are a common typographic
  167. // measurement for describing font size, defined as 72 points per inch.
  168. // stb_truetype provides a point API for compatibility. However, true
  169. // "per inch" conventions don't make much sense on computer displays
  170. // since different monitors have different number of pixels per
  171. // inch. For example, Windows traditionally uses a convention that
  172. // there are 96 pixels per inch, thus making 'inch' measurements have
  173. // nothing to do with inches, and thus effectively defining a point to
  174. // be 1.333 pixels. Additionally, the TrueType font data provides
  175. // an explicit scale factor to scale a given font's glyphs to points,
  176. // but the author has observed that this scale factor is often wrong
  177. // for non-commercial fonts, thus making fonts scaled in points
  178. // according to the TrueType spec incoherently sized in practice.
  179. //
  180. // DETAILED USAGE:
  181. //
  182. // Scale:
  183. // Select how high you want the font to be, in points or pixels.
  184. // Call ScaleForPixelHeight or ScaleForMappingEmToPixels to compute
  185. // a scale factor SF that will be used by all other functions.
  186. //
  187. // Baseline:
  188. // You need to select a y-coordinate that is the baseline of where
  189. // your text will appear. Call GetFontBoundingBox to get the baseline-relative
  190. // bounding box for all characters. SF*-y0 will be the distance in pixels
  191. // that the worst-case character could extend above the baseline, so if
  192. // you want the top edge of characters to appear at the top of the
  193. // screen where y=0, then you would set the baseline to SF*-y0.
  194. //
  195. // Current point:
  196. // Set the current point where the first character will appear. The
  197. // first character could extend left of the current point; this is font
  198. // dependent. You can either choose a current point that is the leftmost
  199. // point and hope, or add some padding, or check the bounding box or
  200. // left-side-bearing of the first character to be displayed and set
  201. // the current point based on that.
  202. //
  203. // Displaying a character:
  204. // Compute the bounding box of the character. It will contain signed values
  205. // relative to <current_point, baseline>. I.e. if it returns x0,y0,x1,y1,
  206. // then the character should be displayed in the rectangle from
  207. // <current_point+SF*x0, baseline+SF*y0> to <current_point+SF*x1,baseline+SF*y1).
  208. //
  209. // Advancing for the next character:
  210. // Call GlyphHMetrics, and compute 'current_point += SF * advance'.
  211. //
  212. //
  213. // ADVANCED USAGE
  214. //
  215. // Quality:
  216. //
  217. // - Use the functions with Subpixel at the end to allow your characters
  218. // to have subpixel positioning. Since the font is anti-aliased, not
  219. // hinted, this is very import for quality. (This is not possible with
  220. // baked fonts.)
  221. //
  222. // - Kerning is now supported, and if you're supporting subpixel rendering
  223. // then kerning is worth using to give your text a polished look.
  224. //
  225. // Performance:
  226. //
  227. // - Convert Unicode codepoints to glyph indexes and operate on the glyphs;
  228. // if you don't do this, stb_truetype is forced to do the conversion on
  229. // every call.
  230. //
  231. // - There are a lot of memory allocations. We should modify it to take
  232. // a temp buffer and allocate from the temp buffer (without freeing),
  233. // should help performance a lot.
  234. //
  235. // NOTES
  236. //
  237. // The system uses the raw data found in the .ttf file without changing it
  238. // and without building auxiliary data structures. This is a bit inefficient
  239. // on little-endian systems (the data is big-endian), but assuming you're
  240. // caching the bitmaps or glyph shapes this shouldn't be a big deal.
  241. //
  242. // It appears to be very hard to programmatically determine what font a
  243. // given file is in a general way. I provide an API for this, but I don't
  244. // recommend it.
  245. //
  246. //
  247. // PERFORMANCE MEASUREMENTS FOR 1.06:
  248. //
  249. // 32-bit 64-bit
  250. // Previous release: 8.83 s 7.68 s
  251. // Pool allocations: 7.72 s 6.34 s
  252. // Inline sort : 6.54 s 5.65 s
  253. // New rasterizer : 5.63 s 5.00 s
  254. //////////////////////////////////////////////////////////////////////////////
  255. //////////////////////////////////////////////////////////////////////////////
  256. ////
  257. //// SAMPLE PROGRAMS
  258. ////
  259. //
  260. // Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless
  261. //
  262. #if 0
  263. #define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation
  264. #include "stb_truetype.h"
  265. unsigned char ttf_buffer[1<<20];
  266. unsigned char temp_bitmap[512*512];
  267. stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs
  268. GLuint ftex;
  269. void my_stbtt_initfont(void)
  270. {
  271. fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb"));
  272. stbtt_BakeFontBitmap(ttf_buffer,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits!
  273. // can free ttf_buffer at this point
  274. glGenTextures(1, &ftex);
  275. glBindTexture(GL_TEXTURE_2D, ftex);
  276. glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap);
  277. // can free temp_bitmap at this point
  278. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  279. }
  280. void my_stbtt_print(float x, float y, char *text)
  281. {
  282. // assume orthographic projection with units = screen pixels, origin at top left
  283. glEnable(GL_TEXTURE_2D);
  284. glBindTexture(GL_TEXTURE_2D, ftex);
  285. glBegin(GL_QUADS);
  286. while (*text) {
  287. if (*text >= 32 && *text < 128) {
  288. stbtt_aligned_quad q;
  289. stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9
  290. glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y0);
  291. glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y0);
  292. glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y1);
  293. glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y1);
  294. }
  295. ++text;
  296. }
  297. glEnd();
  298. }
  299. #endif
  300. //
  301. //
  302. //////////////////////////////////////////////////////////////////////////////
  303. //
  304. // Complete program (this compiles): get a single bitmap, print as ASCII art
  305. //
  306. #if 0
  307. #include <stdio.h>
  308. #define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation
  309. #include "stb_truetype.h"
  310. char ttf_buffer[1<<25];
  311. int main(int argc, char **argv)
  312. {
  313. stbtt_fontinfo font;
  314. unsigned char *bitmap;
  315. int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20);
  316. fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb"));
  317. stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0));
  318. bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0);
  319. for (j=0; j < h; ++j) {
  320. for (i=0; i < w; ++i)
  321. putchar(" .:ioVM@"[bitmap[j*w+i]>>5]);
  322. putchar('\n');
  323. }
  324. return 0;
  325. }
  326. #endif
  327. //
  328. // Output:
  329. //
  330. // .ii.
  331. // @@@@@@.
  332. // V@Mio@@o
  333. // :i. V@V
  334. // :oM@@M
  335. // :@@@MM@M
  336. // @@o o@M
  337. // :@@. M@M
  338. // @@@o@@@@
  339. // :M@@V:@@.
  340. //
  341. //////////////////////////////////////////////////////////////////////////////
  342. //
  343. // Complete program: print "Hello World!" banner, with bugs
  344. //
  345. #if 0
  346. char buffer[24<<20];
  347. unsigned char screen[20][79];
  348. int main(int arg, char **argv)
  349. {
  350. stbtt_fontinfo font;
  351. int i,j,ascent,baseline,ch=0;
  352. float scale, xpos=2; // leave a little padding in case the character extends left
  353. char *text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness
  354. fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb"));
  355. stbtt_InitFont(&font, buffer, 0);
  356. scale = stbtt_ScaleForPixelHeight(&font, 15);
  357. stbtt_GetFontVMetrics(&font, &ascent,0,0);
  358. baseline = (int) (ascent*scale);
  359. while (text[ch]) {
  360. int advance,lsb,x0,y0,x1,y1;
  361. float x_shift = xpos - (float) floor(xpos);
  362. stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb);
  363. stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1);
  364. stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]);
  365. // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong
  366. // because this API is really for baking character bitmaps into textures. if you want to render
  367. // a sequence of characters, you really need to render each bitmap to a temp buffer, then
  368. // "alpha blend" that into the working buffer
  369. xpos += (advance * scale);
  370. if (text[ch+1])
  371. xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]);
  372. ++ch;
  373. }
  374. for (j=0; j < 20; ++j) {
  375. for (i=0; i < 78; ++i)
  376. putchar(" .:ioVM@"[screen[j][i]>>5]);
  377. putchar('\n');
  378. }
  379. return 0;
  380. }
  381. #endif
  382. //////////////////////////////////////////////////////////////////////////////
  383. //////////////////////////////////////////////////////////////////////////////
  384. ////
  385. //// INTEGRATION WITH YOUR CODEBASE
  386. ////
  387. //// The following sections allow you to supply alternate definitions
  388. //// of C library functions used by stb_truetype, e.g. if you don't
  389. //// link with the C runtime library.
  390. #ifdef STB_TRUETYPE_IMPLEMENTATION
  391. // #define your own (u)stbtt_int8/16/32 before including to override this
  392. #ifndef stbtt_uint8
  393. typedef unsigned char stbtt_uint8;
  394. typedef signed char stbtt_int8;
  395. typedef unsigned short stbtt_uint16;
  396. typedef signed short stbtt_int16;
  397. typedef unsigned int stbtt_uint32;
  398. typedef signed int stbtt_int32;
  399. #endif
  400. typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1];
  401. typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1];
  402. // e.g. #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h
  403. #ifndef STBTT_ifloor
  404. #include <math.h>
  405. #define STBTT_ifloor(x) ((int) floor(x))
  406. #define STBTT_iceil(x) ((int) ceil(x))
  407. #endif
  408. #ifndef STBTT_sqrt
  409. #include <math.h>
  410. #define STBTT_sqrt(x) sqrt(x)
  411. #define STBTT_pow(x,y) pow(x,y)
  412. #endif
  413. #ifndef STBTT_fmod
  414. #include <math.h>
  415. #define STBTT_fmod(x,y) fmod(x,y)
  416. #endif
  417. #ifndef STBTT_cos
  418. #include <math.h>
  419. #define STBTT_cos(x) cos(x)
  420. #define STBTT_acos(x) acos(x)
  421. #endif
  422. #ifndef STBTT_fabs
  423. #include <math.h>
  424. #define STBTT_fabs(x) fabs(x)
  425. #endif
  426. // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h
  427. #ifndef STBTT_malloc
  428. #include <stdlib.h>
  429. #define STBTT_malloc(x,u) ((void)(u),malloc(x))
  430. #define STBTT_free(x,u) ((void)(u),free(x))
  431. #endif
  432. #ifndef STBTT_assert
  433. #include <assert.h>
  434. #define STBTT_assert(x) assert(x)
  435. #endif
  436. #ifndef STBTT_strlen
  437. #include <string.h>
  438. #define STBTT_strlen(x) strlen(x)
  439. #endif
  440. #ifndef STBTT_memcpy
  441. #include <string.h>
  442. #define STBTT_memcpy memcpy
  443. #define STBTT_memset memset
  444. #endif
  445. #endif
  446. ///////////////////////////////////////////////////////////////////////////////
  447. ///////////////////////////////////////////////////////////////////////////////
  448. ////
  449. //// INTERFACE
  450. ////
  451. ////
  452. #ifndef __STB_INCLUDE_STB_TRUETYPE_H__
  453. #define __STB_INCLUDE_STB_TRUETYPE_H__
  454. #ifdef STBTT_STATIC
  455. #define STBTT_DEF static
  456. #else
  457. #define STBTT_DEF extern
  458. #endif
  459. #ifdef __cplusplus
  460. extern "C" {
  461. #endif
  462. // private structure
  463. typedef struct
  464. {
  465. unsigned char *data;
  466. int cursor;
  467. int size;
  468. } stbtt__buf;
  469. //////////////////////////////////////////////////////////////////////////////
  470. //
  471. // TEXTURE BAKING API
  472. //
  473. // If you use this API, you only have to call two functions ever.
  474. //
  475. typedef struct
  476. {
  477. unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap
  478. float xoff,yoff,xadvance;
  479. } stbtt_bakedchar;
  480. STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf)
  481. float pixel_height, // height of font in pixels
  482. unsigned char *pixels, int pw, int ph, // bitmap to be filled in
  483. int first_char, int num_chars, // characters to bake
  484. stbtt_bakedchar *chardata); // you allocate this, it's num_chars long
  485. // if return is positive, the first unused row of the bitmap
  486. // if return is negative, returns the negative of the number of characters that fit
  487. // if return is 0, no characters fit and no rows were used
  488. // This uses a very crappy packing.
  489. typedef struct
  490. {
  491. float x0,y0,s0,t0; // top-left
  492. float x1,y1,s1,t1; // bottom-right
  493. } stbtt_aligned_quad;
  494. STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, // same data as above
  495. int char_index, // character to display
  496. float *xpos, float *ypos, // pointers to current position in screen pixel space
  497. stbtt_aligned_quad *q, // output: quad to draw
  498. int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier
  499. // Call GetBakedQuad with char_index = 'character - first_char', and it
  500. // creates the quad you need to draw and advances the current position.
  501. //
  502. // The coordinate system used assumes y increases downwards.
  503. //
  504. // Characters will extend both above and below the current position;
  505. // see discussion of "BASELINE" above.
  506. //
  507. // It's inefficient; you might want to c&p it and optimize it.
  508. STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap);
  509. // Query the font vertical metrics without having to create a font first.
  510. //////////////////////////////////////////////////////////////////////////////
  511. //
  512. // NEW TEXTURE BAKING API
  513. //
  514. // This provides options for packing multiple fonts into one atlas, not
  515. // perfectly but better than nothing.
  516. typedef struct
  517. {
  518. unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap
  519. float xoff,yoff,xadvance;
  520. float xoff2,yoff2;
  521. } stbtt_packedchar;
  522. typedef struct stbtt_pack_context stbtt_pack_context;
  523. typedef struct stbtt_fontinfo stbtt_fontinfo;
  524. #ifndef STB_RECT_PACK_VERSION
  525. typedef struct stbrp_rect stbrp_rect;
  526. #endif
  527. STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context);
  528. // Initializes a packing context stored in the passed-in stbtt_pack_context.
  529. // Future calls using this context will pack characters into the bitmap passed
  530. // in here: a 1-channel bitmap that is width * height. stride_in_bytes is
  531. // the distance from one row to the next (or 0 to mean they are packed tightly
  532. // together). "padding" is the amount of padding to leave between each
  533. // character (normally you want '1' for bitmaps you'll use as textures with
  534. // bilinear filtering).
  535. //
  536. // Returns 0 on failure, 1 on success.
  537. STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc);
  538. // Cleans up the packing context and frees all memory.
  539. #define STBTT_POINT_SIZE(x) (-(x))
  540. STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size,
  541. int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range);
  542. // Creates character bitmaps from the font_index'th font found in fontdata (use
  543. // font_index=0 if you don't know what that is). It creates num_chars_in_range
  544. // bitmaps for characters with unicode values starting at first_unicode_char_in_range
  545. // and increasing. Data for how to render them is stored in chardata_for_range;
  546. // pass these to stbtt_GetPackedQuad to get back renderable quads.
  547. //
  548. // font_size is the full height of the character from ascender to descender,
  549. // as computed by stbtt_ScaleForPixelHeight. To use a point size as computed
  550. // by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE()
  551. // and pass that result as 'font_size':
  552. // ..., 20 , ... // font max minus min y is 20 pixels tall
  553. // ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall
  554. typedef struct
  555. {
  556. float font_size;
  557. int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint
  558. int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints
  559. int num_chars;
  560. stbtt_packedchar *chardata_for_range; // output
  561. unsigned char h_oversample, v_oversample; // don't set these, they're used internally
  562. } stbtt_pack_range;
  563. STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges);
  564. // Creates character bitmaps from multiple ranges of characters stored in
  565. // ranges. This will usually create a better-packed bitmap than multiple
  566. // calls to stbtt_PackFontRange. Note that you can call this multiple
  567. // times within a single PackBegin/PackEnd.
  568. STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample);
  569. // Oversampling a font increases the quality by allowing higher-quality subpixel
  570. // positioning, and is especially valuable at smaller text sizes.
  571. //
  572. // This function sets the amount of oversampling for all following calls to
  573. // stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given
  574. // pack context. The default (no oversampling) is achieved by h_oversample=1
  575. // and v_oversample=1. The total number of pixels required is
  576. // h_oversample*v_oversample larger than the default; for example, 2x2
  577. // oversampling requires 4x the storage of 1x1. For best results, render
  578. // oversampled textures with bilinear filtering. Look at the readme in
  579. // stb/tests/oversample for information about oversampled fonts
  580. //
  581. // To use with PackFontRangesGather etc., you must set it before calls
  582. // call to PackFontRangesGatherRects.
  583. STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip);
  584. // If skip != 0, this tells stb_truetype to skip any codepoints for which
  585. // there is no corresponding glyph. If skip=0, which is the default, then
  586. // codepoints without a glyph recived the font's "missing character" glyph,
  587. // typically an empty box by convention.
  588. STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, // same data as above
  589. int char_index, // character to display
  590. float *xpos, float *ypos, // pointers to current position in screen pixel space
  591. stbtt_aligned_quad *q, // output: quad to draw
  592. int align_to_integer);
  593. STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects);
  594. STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects);
  595. STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects);
  596. // Calling these functions in sequence is roughly equivalent to calling
  597. // stbtt_PackFontRanges(). If you more control over the packing of multiple
  598. // fonts, or if you want to pack custom data into a font texture, take a look
  599. // at the source to of stbtt_PackFontRanges() and create a custom version
  600. // using these functions, e.g. call GatherRects multiple times,
  601. // building up a single array of rects, then call PackRects once,
  602. // then call RenderIntoRects repeatedly. This may result in a
  603. // better packing than calling PackFontRanges multiple times
  604. // (or it may not).
  605. // this is an opaque structure that you shouldn't mess with which holds
  606. // all the context needed from PackBegin to PackEnd.
  607. struct stbtt_pack_context {
  608. void *user_allocator_context;
  609. void *pack_info;
  610. int width;
  611. int height;
  612. int stride_in_bytes;
  613. int padding;
  614. int skip_missing;
  615. unsigned int h_oversample, v_oversample;
  616. unsigned char *pixels;
  617. void *nodes;
  618. };
  619. //////////////////////////////////////////////////////////////////////////////
  620. //
  621. // FONT LOADING
  622. //
  623. //
  624. STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data);
  625. // This function will determine the number of fonts in a font file. TrueType
  626. // collection (.ttc) files may contain multiple fonts, while TrueType font
  627. // (.ttf) files only contain one font. The number of fonts can be used for
  628. // indexing with the previous function where the index is between zero and one
  629. // less than the total fonts. If an error occurs, -1 is returned.
  630. STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index);
  631. // Each .ttf/.ttc file may have more than one font. Each font has a sequential
  632. // index number starting from 0. Call this function to get the font offset for
  633. // a given index; it returns -1 if the index is out of range. A regular .ttf
  634. // file will only define one font and it always be at offset 0, so it will
  635. // return '0' for index 0, and -1 for all other indices.
  636. // The following structure is defined publicly so you can declare one on
  637. // the stack or as a global or etc, but you should treat it as opaque.
  638. struct stbtt_fontinfo
  639. {
  640. void * userdata;
  641. unsigned char * data; // pointer to .ttf file
  642. int fontstart; // offset of start of font
  643. int numGlyphs; // number of glyphs, needed for range checking
  644. int loca,head,glyf,hhea,hmtx,kern,gpos; // table locations as offset from start of .ttf
  645. int index_map; // a cmap mapping for our chosen character encoding
  646. int indexToLocFormat; // format needed to map from glyph index to glyph
  647. stbtt__buf cff; // cff font data
  648. stbtt__buf charstrings; // the charstring index
  649. stbtt__buf gsubrs; // global charstring subroutines index
  650. stbtt__buf subrs; // private charstring subroutines index
  651. stbtt__buf fontdicts; // array of font dicts
  652. stbtt__buf fdselect; // map from glyph to fontdict
  653. };
  654. STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset);
  655. // Given an offset into the file that defines a font, this function builds
  656. // the necessary cached info for the rest of the system. You must allocate
  657. // the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't
  658. // need to do anything special to free it, because the contents are pure
  659. // value data with no additional data structures. Returns 0 on failure.
  660. //////////////////////////////////////////////////////////////////////////////
  661. //
  662. // CHARACTER TO GLYPH-INDEX CONVERSIOn
  663. STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint);
  664. // If you're going to perform multiple operations on the same character
  665. // and you want a speed-up, call this function with the character you're
  666. // going to process, then use glyph-based functions instead of the
  667. // codepoint-based functions.
  668. // Returns 0 if the character codepoint is not defined in the font.
  669. //////////////////////////////////////////////////////////////////////////////
  670. //
  671. // CHARACTER PROPERTIES
  672. //
  673. STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels);
  674. // computes a scale factor to produce a font whose "height" is 'pixels' tall.
  675. // Height is measured as the distance from the highest ascender to the lowest
  676. // descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics
  677. // and computing:
  678. // scale = pixels / (ascent - descent)
  679. // so if you prefer to measure height by the ascent only, use a similar calculation.
  680. STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels);
  681. // computes a scale factor to produce a font whose EM size is mapped to
  682. // 'pixels' tall. This is probably what traditional APIs compute, but
  683. // I'm not positive.
  684. STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap);
  685. // ascent is the coordinate above the baseline the font extends; descent
  686. // is the coordinate below the baseline the font extends (i.e. it is typically negative)
  687. // lineGap is the spacing between one row's descent and the next row's ascent...
  688. // so you should advance the vertical position by "*ascent - *descent + *lineGap"
  689. // these are expressed in unscaled coordinates, so you must multiply by
  690. // the scale factor for a given size
  691. STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap);
  692. // analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2
  693. // table (specific to MS/Windows TTF files).
  694. //
  695. // Returns 1 on success (table present), 0 on failure.
  696. STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1);
  697. // the bounding box around all possible characters
  698. STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing);
  699. // leftSideBearing is the offset from the current horizontal position to the left edge of the character
  700. // advanceWidth is the offset from the current horizontal position to the next horizontal position
  701. // these are expressed in unscaled coordinates
  702. STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2);
  703. // an additional amount to add to the 'advance' value between ch1 and ch2
  704. STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1);
  705. // Gets the bounding box of the visible part of the glyph, in unscaled coordinates
  706. STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing);
  707. STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2);
  708. STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);
  709. // as above, but takes one or more glyph indices for greater efficiency
  710. //////////////////////////////////////////////////////////////////////////////
  711. //
  712. // GLYPH SHAPES (you probably don't need these, but they have to go before
  713. // the bitmaps for C declaration-order reasons)
  714. //
  715. #ifndef STBTT_vmove // you can predefine these to use different values (but why?)
  716. enum {
  717. STBTT_vmove=1,
  718. STBTT_vline,
  719. STBTT_vcurve,
  720. STBTT_vcubic
  721. };
  722. #endif
  723. #ifndef stbtt_vertex // you can predefine this to use different values
  724. // (we share this with other code at RAD)
  725. #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file
  726. typedef struct
  727. {
  728. stbtt_vertex_type x,y,cx,cy,cx1,cy1;
  729. unsigned char type,padding;
  730. } stbtt_vertex;
  731. #endif
  732. STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index);
  733. // returns non-zero if nothing is drawn for this glyph
  734. STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices);
  735. STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices);
  736. // returns # of vertices and fills *vertices with the pointer to them
  737. // these are expressed in "unscaled" coordinates
  738. //
  739. // The shape is a series of contours. Each one starts with
  740. // a STBTT_moveto, then consists of a series of mixed
  741. // STBTT_lineto and STBTT_curveto segments. A lineto
  742. // draws a line from previous endpoint to its x,y; a curveto
  743. // draws a quadratic bezier from previous endpoint to
  744. // its x,y, using cx,cy as the bezier control point.
  745. STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices);
  746. // frees the data allocated above
  747. //////////////////////////////////////////////////////////////////////////////
  748. //
  749. // BITMAP RENDERING
  750. //
  751. STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata);
  752. // frees the bitmap allocated below
  753. STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff);
  754. // allocates a large-enough single-channel 8bpp bitmap and renders the
  755. // specified character/glyph at the specified scale into it, with
  756. // antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque).
  757. // *width & *height are filled out with the width & height of the bitmap,
  758. // which is stored left-to-right, top-to-bottom.
  759. //
  760. // xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap
  761. STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff);
  762. // the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel
  763. // shift for the character
  764. STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint);
  765. // the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap
  766. // in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap
  767. // is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the
  768. // width and height and positioning info for it first.
  769. STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint);
  770. // same as stbtt_MakeCodepointBitmap, but you can specify a subpixel
  771. // shift for the character
  772. STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint);
  773. // same as stbtt_MakeCodepointBitmapSubpixel, but prefiltering
  774. // is performed (see stbtt_PackSetOversampling)
  775. STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);
  776. // get the bbox of the bitmap centered around the glyph origin; so the
  777. // bitmap width is ix1-ix0, height is iy1-iy0, and location to place
  778. // the bitmap top left is (leftSideBearing*scale,iy0).
  779. // (Note that the bitmap uses y-increases-down, but the shape uses
  780. // y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.)
  781. STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1);
  782. // same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel
  783. // shift for the character
  784. // the following functions are equivalent to the above functions, but operate
  785. // on glyph indices instead of Unicode codepoints (for efficiency)
  786. STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff);
  787. STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff);
  788. STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph);
  789. STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph);
  790. STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int glyph);
  791. STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);
  792. STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1);
  793. // @TODO: don't expose this structure
  794. typedef struct
  795. {
  796. int w,h,stride;
  797. unsigned char *pixels;
  798. } stbtt__bitmap;
  799. // rasterize a shape with quadratic beziers into a bitmap
  800. STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, // 1-channel bitmap to draw into
  801. float flatness_in_pixels, // allowable error of curve in pixels
  802. stbtt_vertex *vertices, // array of vertices defining shape
  803. int num_verts, // number of vertices in above array
  804. float scale_x, float scale_y, // scale applied to input vertices
  805. float shift_x, float shift_y, // translation applied to input vertices
  806. int x_off, int y_off, // another translation applied to input
  807. int invert, // if non-zero, vertically flip shape
  808. void *userdata); // context for to STBTT_MALLOC
  809. //////////////////////////////////////////////////////////////////////////////
  810. //
  811. // Signed Distance Function (or Field) rendering
  812. STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata);
  813. // frees the SDF bitmap allocated below
  814. STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff);
  815. STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff);
  816. // These functions compute a discretized SDF field for a single character, suitable for storing
  817. // in a single-channel texture, sampling with bilinear filtering, and testing against
  818. // larger than some threshold to produce scalable fonts.
  819. // info -- the font
  820. // scale -- controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap
  821. // glyph/codepoint -- the character to generate the SDF for
  822. // padding -- extra "pixels" around the character which are filled with the distance to the character (not 0),
  823. // which allows effects like bit outlines
  824. // onedge_value -- value 0-255 to test the SDF against to reconstruct the character (i.e. the isocontour of the character)
  825. // pixel_dist_scale -- what value the SDF should increase by when moving one SDF "pixel" away from the edge (on the 0..255 scale)
  826. // if positive, > onedge_value is inside; if negative, < onedge_value is inside
  827. // width,height -- output height & width of the SDF bitmap (including padding)
  828. // xoff,yoff -- output origin of the character
  829. // return value -- a 2D array of bytes 0..255, width*height in size
  830. //
  831. // pixel_dist_scale & onedge_value are a scale & bias that allows you to make
  832. // optimal use of the limited 0..255 for your application, trading off precision
  833. // and special effects. SDF values outside the range 0..255 are clamped to 0..255.
  834. //
  835. // Example:
  836. // scale = stbtt_ScaleForPixelHeight(22)
  837. // padding = 5
  838. // onedge_value = 180
  839. // pixel_dist_scale = 180/5.0 = 36.0
  840. //
  841. // This will create an SDF bitmap in which the character is about 22 pixels
  842. // high but the whole bitmap is about 22+5+5=32 pixels high. To produce a filled
  843. // shape, sample the SDF at each pixel and fill the pixel if the SDF value
  844. // is greater than or equal to 180/255. (You'll actually want to antialias,
  845. // which is beyond the scope of this example.) Additionally, you can compute
  846. // offset outlines (e.g. to stroke the character border inside & outside,
  847. // or only outside). For example, to fill outside the character up to 3 SDF
  848. // pixels, you would compare against (180-36.0*3)/255 = 72/255. The above
  849. // choice of variables maps a range from 5 pixels outside the shape to
  850. // 2 pixels inside the shape to 0..255; this is intended primarily for apply
  851. // outside effects only (the interior range is needed to allow proper
  852. // antialiasing of the font at *smaller* sizes)
  853. //
  854. // The function computes the SDF analytically at each SDF pixel, not by e.g.
  855. // building a higher-res bitmap and approximating it. In theory the quality
  856. // should be as high as possible for an SDF of this size & representation, but
  857. // unclear if this is true in practice (perhaps building a higher-res bitmap
  858. // and computing from that can allow drop-out prevention).
  859. //
  860. // The algorithm has not been optimized at all, so expect it to be slow
  861. // if computing lots of characters or very large sizes.
  862. //////////////////////////////////////////////////////////////////////////////
  863. //
  864. // Finding the right font...
  865. //
  866. // You should really just solve this offline, keep your own tables
  867. // of what font is what, and don't try to get it out of the .ttf file.
  868. // That's because getting it out of the .ttf file is really hard, because
  869. // the names in the file can appear in many possible encodings, in many
  870. // possible languages, and e.g. if you need a case-insensitive comparison,
  871. // the details of that depend on the encoding & language in a complex way
  872. // (actually underspecified in truetype, but also gigantic).
  873. //
  874. // But you can use the provided functions in two possible ways:
  875. // stbtt_FindMatchingFont() will use *case-sensitive* comparisons on
  876. // unicode-encoded names to try to find the font you want;
  877. // you can run this before calling stbtt_InitFont()
  878. //
  879. // stbtt_GetFontNameString() lets you get any of the various strings
  880. // from the file yourself and do your own comparisons on them.
  881. // You have to have called stbtt_InitFont() first.
  882. STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags);
  883. // returns the offset (not index) of the font that matches, or -1 if none
  884. // if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold".
  885. // if you use any other flag, use a font name like "Arial"; this checks
  886. // the 'macStyle' header field; i don't know if fonts set this consistently
  887. #define STBTT_MACSTYLE_DONTCARE 0
  888. #define STBTT_MACSTYLE_BOLD 1
  889. #define STBTT_MACSTYLE_ITALIC 2
  890. #define STBTT_MACSTYLE_UNDERSCORE 4
  891. #define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0
  892. STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2);
  893. // returns 1/0 whether the first string interpreted as utf8 is identical to
  894. // the second string interpreted as big-endian utf16... useful for strings from next func
  895. STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID);
  896. // returns the string (which may be big-endian double byte, e.g. for unicode)
  897. // and puts the length in bytes in *length.
  898. //
  899. // some of the values for the IDs are below; for more see the truetype spec:
  900. // http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html
  901. // http://www.microsoft.com/typography/otspec/name.htm
  902. enum { // platformID
  903. STBTT_PLATFORM_ID_UNICODE =0,
  904. STBTT_PLATFORM_ID_MAC =1,
  905. STBTT_PLATFORM_ID_ISO =2,
  906. STBTT_PLATFORM_ID_MICROSOFT =3
  907. };
  908. enum { // encodingID for STBTT_PLATFORM_ID_UNICODE
  909. STBTT_UNICODE_EID_UNICODE_1_0 =0,
  910. STBTT_UNICODE_EID_UNICODE_1_1 =1,
  911. STBTT_UNICODE_EID_ISO_10646 =2,
  912. STBTT_UNICODE_EID_UNICODE_2_0_BMP=3,
  913. STBTT_UNICODE_EID_UNICODE_2_0_FULL=4
  914. };
  915. enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT
  916. STBTT_MS_EID_SYMBOL =0,
  917. STBTT_MS_EID_UNICODE_BMP =1,
  918. STBTT_MS_EID_SHIFTJIS =2,
  919. STBTT_MS_EID_UNICODE_FULL =10
  920. };
  921. enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes
  922. STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4,
  923. STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5,
  924. STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6,
  925. STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7
  926. };
  927. enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID...
  928. // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs
  929. STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410,
  930. STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411,
  931. STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412,
  932. STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419,
  933. STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409,
  934. STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D
  935. };
  936. enum { // languageID for STBTT_PLATFORM_ID_MAC
  937. STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11,
  938. STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23,
  939. STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32,
  940. STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 ,
  941. STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 ,
  942. STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33,
  943. STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19
  944. };
  945. #ifdef __cplusplus
  946. }
  947. #endif
  948. #endif // __STB_INCLUDE_STB_TRUETYPE_H__
  949. ///////////////////////////////////////////////////////////////////////////////
  950. ///////////////////////////////////////////////////////////////////////////////
  951. ////
  952. //// IMPLEMENTATION
  953. ////
  954. ////
  955. #ifdef STB_TRUETYPE_IMPLEMENTATION
  956. #ifndef STBTT_MAX_OVERSAMPLE
  957. #define STBTT_MAX_OVERSAMPLE 8
  958. #endif
  959. #if STBTT_MAX_OVERSAMPLE > 255
  960. #error "STBTT_MAX_OVERSAMPLE cannot be > 255"
  961. #endif
  962. typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1];
  963. #ifndef STBTT_RASTERIZER_VERSION
  964. #define STBTT_RASTERIZER_VERSION 2
  965. #endif
  966. #ifdef _MSC_VER
  967. #define STBTT__NOTUSED(v) (void)(v)
  968. #else
  969. #define STBTT__NOTUSED(v) (void)sizeof(v)
  970. #endif
  971. //////////////////////////////////////////////////////////////////////////
  972. //
  973. // stbtt__buf helpers to parse data from file
  974. //
  975. static stbtt_uint8 stbtt__buf_get8(stbtt__buf *b)
  976. {
  977. if (b->cursor >= b->size)
  978. return 0;
  979. return b->data[b->cursor++];
  980. }
  981. static stbtt_uint8 stbtt__buf_peek8(stbtt__buf *b)
  982. {
  983. if (b->cursor >= b->size)
  984. return 0;
  985. return b->data[b->cursor];
  986. }
  987. static void stbtt__buf_seek(stbtt__buf *b, int o)
  988. {
  989. STBTT_assert(!(o > b->size || o < 0));
  990. b->cursor = (o > b->size || o < 0) ? b->size : o;
  991. }
  992. static void stbtt__buf_skip(stbtt__buf *b, int o)
  993. {
  994. stbtt__buf_seek(b, b->cursor + o);
  995. }
  996. static stbtt_uint32 stbtt__buf_get(stbtt__buf *b, int n)
  997. {
  998. stbtt_uint32 v = 0;
  999. int i;
  1000. STBTT_assert(n >= 1 && n <= 4);
  1001. for (i = 0; i < n; i++)
  1002. v = (v << 8) | stbtt__buf_get8(b);
  1003. return v;
  1004. }
  1005. static stbtt__buf stbtt__new_buf(const void *p, size_t size)
  1006. {
  1007. stbtt__buf r;
  1008. STBTT_assert(size < 0x40000000);
  1009. r.data = (stbtt_uint8*) p;
  1010. r.size = (int) size;
  1011. r.cursor = 0;
  1012. return r;
  1013. }
  1014. #define stbtt__buf_get16(b) stbtt__buf_get((b), 2)
  1015. #define stbtt__buf_get32(b) stbtt__buf_get((b), 4)
  1016. static stbtt__buf stbtt__buf_range(const stbtt__buf *b, int o, int s)
  1017. {
  1018. stbtt__buf r = stbtt__new_buf(NULL, 0);
  1019. if (o < 0 || s < 0 || o > b->size || s > b->size - o) return r;
  1020. r.data = b->data + o;
  1021. r.size = s;
  1022. return r;
  1023. }
  1024. static stbtt__buf stbtt__cff_get_index(stbtt__buf *b)
  1025. {
  1026. int count, start, offsize;
  1027. start = b->cursor;
  1028. count = stbtt__buf_get16(b);
  1029. if (count) {
  1030. offsize = stbtt__buf_get8(b);
  1031. STBTT_assert(offsize >= 1 && offsize <= 4);
  1032. stbtt__buf_skip(b, offsize * count);
  1033. stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1);
  1034. }
  1035. return stbtt__buf_range(b, start, b->cursor - start);
  1036. }
  1037. static stbtt_uint32 stbtt__cff_int(stbtt__buf *b)
  1038. {
  1039. int b0 = stbtt__buf_get8(b);
  1040. if (b0 >= 32 && b0 <= 246) return b0 - 139;
  1041. else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108;
  1042. else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108;
  1043. else if (b0 == 28) return stbtt__buf_get16(b);
  1044. else if (b0 == 29) return stbtt__buf_get32(b);
  1045. STBTT_assert(0);
  1046. return 0;
  1047. }
  1048. static void stbtt__cff_skip_operand(stbtt__buf *b) {
  1049. int v, b0 = stbtt__buf_peek8(b);
  1050. STBTT_assert(b0 >= 28);
  1051. if (b0 == 30) {
  1052. stbtt__buf_skip(b, 1);
  1053. while (b->cursor < b->size) {
  1054. v = stbtt__buf_get8(b);
  1055. if ((v & 0xF) == 0xF || (v >> 4) == 0xF)
  1056. break;
  1057. }
  1058. } else {
  1059. stbtt__cff_int(b);
  1060. }
  1061. }
  1062. static stbtt__buf stbtt__dict_get(stbtt__buf *b, int key)
  1063. {
  1064. stbtt__buf_seek(b, 0);
  1065. while (b->cursor < b->size) {
  1066. int start = b->cursor, end, op;
  1067. while (stbtt__buf_peek8(b) >= 28)
  1068. stbtt__cff_skip_operand(b);
  1069. end = b->cursor;
  1070. op = stbtt__buf_get8(b);
  1071. if (op == 12) op = stbtt__buf_get8(b) | 0x100;
  1072. if (op == key) return stbtt__buf_range(b, start, end-start);
  1073. }
  1074. return stbtt__buf_range(b, 0, 0);
  1075. }
  1076. static void stbtt__dict_get_ints(stbtt__buf *b, int key, int outcount, stbtt_uint32 *out)
  1077. {
  1078. int i;
  1079. stbtt__buf operands = stbtt__dict_get(b, key);
  1080. for (i = 0; i < outcount && operands.cursor < operands.size; i++)
  1081. out[i] = stbtt__cff_int(&operands);
  1082. }
  1083. static int stbtt__cff_index_count(stbtt__buf *b)
  1084. {
  1085. stbtt__buf_seek(b, 0);
  1086. return stbtt__buf_get16(b);
  1087. }
  1088. static stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i)
  1089. {
  1090. int count, offsize, start, end;
  1091. stbtt__buf_seek(&b, 0);
  1092. count = stbtt__buf_get16(&b);
  1093. offsize = stbtt__buf_get8(&b);
  1094. STBTT_assert(i >= 0 && i < count);
  1095. STBTT_assert(offsize >= 1 && offsize <= 4);
  1096. stbtt__buf_skip(&b, i*offsize);
  1097. start = stbtt__buf_get(&b, offsize);
  1098. end = stbtt__buf_get(&b, offsize);
  1099. return stbtt__buf_range(&b, 2+(count+1)*offsize+start, end - start);
  1100. }
  1101. //////////////////////////////////////////////////////////////////////////
  1102. //
  1103. // accessors to parse data from file
  1104. //
  1105. // on platforms that don't allow misaligned reads, if we want to allow
  1106. // truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE
  1107. #define ttBYTE(p) (* (stbtt_uint8 *) (p))
  1108. #define ttCHAR(p) (* (stbtt_int8 *) (p))
  1109. #define ttFixed(p) ttLONG(p)
  1110. static stbtt_uint16 ttUSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; }
  1111. static stbtt_int16 ttSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; }
  1112. static stbtt_uint32 ttULONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
  1113. static stbtt_int32 ttLONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
  1114. #define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3))
  1115. #define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3])
  1116. static int stbtt__isfont(stbtt_uint8 *font)
  1117. {
  1118. // check the version number
  1119. if (stbtt_tag4(font, '1',0,0,0)) return 1; // TrueType 1
  1120. if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this!
  1121. if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF
  1122. if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0
  1123. if (stbtt_tag(font, "true")) return 1; // Apple specification for TrueType fonts
  1124. return 0;
  1125. }
  1126. // @OPTIMIZE: binary search
  1127. static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag)
  1128. {
  1129. stbtt_int32 num_tables = ttUSHORT(data+fontstart+4);
  1130. stbtt_uint32 tabledir = fontstart + 12;
  1131. stbtt_int32 i;
  1132. for (i=0; i < num_tables; ++i) {
  1133. stbtt_uint32 loc = tabledir + 16*i;
  1134. if (stbtt_tag(data+loc+0, tag))
  1135. return ttULONG(data+loc+8);
  1136. }
  1137. return 0;
  1138. }
  1139. static int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection, int index)
  1140. {
  1141. // if it's just a font, there's only one valid index
  1142. if (stbtt__isfont(font_collection))
  1143. return index == 0 ? 0 : -1;
  1144. // check if it's a TTC
  1145. if (stbtt_tag(font_collection, "ttcf")) {
  1146. // version 1?
  1147. if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {
  1148. stbtt_int32 n = ttLONG(font_collection+8);
  1149. if (index >= n)
  1150. return -1;
  1151. return ttULONG(font_collection+12+index*4);
  1152. }
  1153. }
  1154. return -1;
  1155. }
  1156. static int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection)
  1157. {
  1158. // if it's just a font, there's only one valid font
  1159. if (stbtt__isfont(font_collection))
  1160. return 1;
  1161. // check if it's a TTC
  1162. if (stbtt_tag(font_collection, "ttcf")) {
  1163. // version 1?
  1164. if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {
  1165. return ttLONG(font_collection+8);
  1166. }
  1167. }
  1168. return 0;
  1169. }
  1170. static stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict)
  1171. {
  1172. stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 };
  1173. stbtt__buf pdict;
  1174. stbtt__dict_get_ints(&fontdict, 18, 2, private_loc);
  1175. if (!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0);
  1176. pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]);
  1177. stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff);
  1178. if (!subrsoff) return stbtt__new_buf(NULL, 0);
  1179. stbtt__buf_seek(&cff, private_loc[1]+subrsoff);
  1180. return stbtt__cff_get_index(&cff);
  1181. }
  1182. static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, int fontstart)
  1183. {
  1184. stbtt_uint32 cmap, t;
  1185. stbtt_int32 i,numTables;
  1186. info->data = data;
  1187. info->fontstart = fontstart;
  1188. info->cff = stbtt__new_buf(NULL, 0);
  1189. cmap = stbtt__find_table(data, fontstart, "cmap"); // required
  1190. info->loca = stbtt__find_table(data, fontstart, "loca"); // required
  1191. info->head = stbtt__find_table(data, fontstart, "head"); // required
  1192. info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required
  1193. info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required
  1194. info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required
  1195. info->kern = stbtt__find_table(data, fontstart, "kern"); // not required
  1196. info->gpos = stbtt__find_table(data, fontstart, "GPOS"); // not required
  1197. if (!cmap || !info->head || !info->hhea || !info->hmtx)
  1198. return 0;
  1199. if (info->glyf) {
  1200. // required for truetype
  1201. if (!info->loca) return 0;
  1202. } else {
  1203. // initialization for CFF / Type2 fonts (OTF)
  1204. stbtt__buf b, topdict, topdictidx;
  1205. stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0;
  1206. stbtt_uint32 cff;
  1207. cff = stbtt__find_table(data, fontstart, "CFF ");
  1208. if (!cff) return 0;
  1209. info->fontdicts = stbtt__new_buf(NULL, 0);
  1210. info->fdselect = stbtt__new_buf(NULL, 0);
  1211. // @TODO this should use size from table (not 512MB)
  1212. info->cff = stbtt__new_buf(data+cff, 512*1024*1024);
  1213. b = info->cff;
  1214. // read the header
  1215. stbtt__buf_skip(&b, 2);
  1216. stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize
  1217. // @TODO the name INDEX could list multiple fonts,
  1218. // but we just use the first one.
  1219. stbtt__cff_get_index(&b); // name INDEX
  1220. topdictidx = stbtt__cff_get_index(&b);
  1221. topdict = stbtt__cff_index_get(topdictidx, 0);
  1222. stbtt__cff_get_index(&b); // string INDEX
  1223. info->gsubrs = stbtt__cff_get_index(&b);
  1224. stbtt__dict_get_ints(&topdict, 17, 1, &charstrings);
  1225. stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype);
  1226. stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff);
  1227. stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff);
  1228. info->subrs = stbtt__get_subrs(b, topdict);
  1229. // we only support Type 2 charstrings
  1230. if (cstype != 2) return 0;
  1231. if (charstrings == 0) return 0;
  1232. if (fdarrayoff) {
  1233. // looks like a CID font
  1234. if (!fdselectoff) return 0;
  1235. stbtt__buf_seek(&b, fdarrayoff);
  1236. info->fontdicts = stbtt__cff_get_index(&b);
  1237. info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size-fdselectoff);
  1238. }
  1239. stbtt__buf_seek(&b, charstrings);
  1240. info->charstrings = stbtt__cff_get_index(&b);
  1241. }
  1242. t = stbtt__find_table(data, fontstart, "maxp");
  1243. if (t)
  1244. info->numGlyphs = ttUSHORT(data+t+4);
  1245. else
  1246. info->numGlyphs = 0xffff;
  1247. // find a cmap encoding table we understand *now* to avoid searching
  1248. // later. (todo: could make this installable)
  1249. // the same regardless of glyph.
  1250. numTables = ttUSHORT(data + cmap + 2);
  1251. info->index_map = 0;
  1252. for (i=0; i < numTables; ++i) {
  1253. stbtt_uint32 encoding_record = cmap + 4 + 8 * i;
  1254. // find an encoding we understand:
  1255. switch(ttUSHORT(data+encoding_record)) {
  1256. case STBTT_PLATFORM_ID_MICROSOFT:
  1257. switch (ttUSHORT(data+encoding_record+2)) {
  1258. case STBTT_MS_EID_UNICODE_BMP:
  1259. case STBTT_MS_EID_UNICODE_FULL:
  1260. // MS/Unicode
  1261. info->index_map = cmap + ttULONG(data+encoding_record+4);
  1262. break;
  1263. }
  1264. break;
  1265. case STBTT_PLATFORM_ID_UNICODE:
  1266. // Mac/iOS has these
  1267. // all the encodingIDs are unicode, so we don't bother to check it
  1268. info->index_map = cmap + ttULONG(data+encoding_record+4);
  1269. break;
  1270. }
  1271. }
  1272. if (info->index_map == 0)
  1273. return 0;
  1274. info->indexToLocFormat = ttUSHORT(data+info->head + 50);
  1275. return 1;
  1276. }
  1277. STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint)
  1278. {
  1279. stbtt_uint8 *data = info->data;
  1280. stbtt_uint32 index_map = info->index_map;
  1281. stbtt_uint16 format = ttUSHORT(data + index_map + 0);
  1282. if (format == 0) { // apple byte encoding
  1283. stbtt_int32 bytes = ttUSHORT(data + index_map + 2);
  1284. if (unicode_codepoint < bytes-6)
  1285. return ttBYTE(data + index_map + 6 + unicode_codepoint);
  1286. return 0;
  1287. } else if (format == 6) {
  1288. stbtt_uint32 first = ttUSHORT(data + index_map + 6);
  1289. stbtt_uint32 count = ttUSHORT(data + index_map + 8);
  1290. if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count)
  1291. return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2);
  1292. return 0;
  1293. } else if (format == 2) {
  1294. STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean
  1295. return 0;
  1296. } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges
  1297. stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1;
  1298. stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1;
  1299. stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10);
  1300. stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1;
  1301. // do a binary search of the segments
  1302. stbtt_uint32 endCount = index_map + 14;
  1303. stbtt_uint32 search = endCount;
  1304. if (unicode_codepoint > 0xffff)
  1305. return 0;
  1306. // they lie from endCount .. endCount + segCount
  1307. // but searchRange is the nearest power of two, so...
  1308. if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2))
  1309. search += rangeShift*2;
  1310. // now decrement to bias correctly to find smallest
  1311. search -= 2;
  1312. while (entrySelector) {
  1313. stbtt_uint16 end;
  1314. searchRange >>= 1;
  1315. end = ttUSHORT(data + search + searchRange*2);
  1316. if (unicode_codepoint > end)
  1317. search += searchRange*2;
  1318. --entrySelector;
  1319. }
  1320. search += 2;
  1321. {
  1322. stbtt_uint16 offset, start;
  1323. stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1);
  1324. STBTT_assert(unicode_codepoint <= ttUSHORT(data + endCount + 2*item));
  1325. start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item);
  1326. if (unicode_codepoint < start)
  1327. return 0;
  1328. offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item);
  1329. if (offset == 0)
  1330. return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item));
  1331. return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item);
  1332. }
  1333. } else if (format == 12 || format == 13) {
  1334. stbtt_uint32 ngroups = ttULONG(data+index_map+12);
  1335. stbtt_int32 low,high;
  1336. low = 0; high = (stbtt_int32)ngroups;
  1337. // Binary search the right group.
  1338. while (low < high) {
  1339. stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high
  1340. stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12);
  1341. stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4);
  1342. if ((stbtt_uint32) unicode_codepoint < start_char)
  1343. high = mid;
  1344. else if ((stbtt_uint32) unicode_codepoint > end_char)
  1345. low = mid+1;
  1346. else {
  1347. stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8);
  1348. if (format == 12)
  1349. return start_glyph + unicode_codepoint-start_char;
  1350. else // format == 13
  1351. return start_glyph;
  1352. }
  1353. }
  1354. return 0; // not found
  1355. }
  1356. // @TODO
  1357. STBTT_assert(0);
  1358. return 0;
  1359. }
  1360. STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices)
  1361. {
  1362. return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices);
  1363. }
  1364. static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy)
  1365. {
  1366. v->type = type;
  1367. v->x = (stbtt_int16) x;
  1368. v->y = (stbtt_int16) y;
  1369. v->cx = (stbtt_int16) cx;
  1370. v->cy = (stbtt_int16) cy;
  1371. }
  1372. static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index)
  1373. {
  1374. int g1,g2;
  1375. STBTT_assert(!info->cff.size);
  1376. if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range
  1377. if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format
  1378. if (info->indexToLocFormat == 0) {
  1379. g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2;
  1380. g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2;
  1381. } else {
  1382. g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4);
  1383. g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4);
  1384. }
  1385. return g1==g2 ? -1 : g1; // if length is 0, return -1
  1386. }
  1387. static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);
  1388. STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)
  1389. {
  1390. if (info->cff.size) {
  1391. stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1);
  1392. } else {
  1393. int g = stbtt__GetGlyfOffset(info, glyph_index);
  1394. if (g < 0) return 0;
  1395. if (x0) *x0 = ttSHORT(info->data + g + 2);
  1396. if (y0) *y0 = ttSHORT(info->data + g + 4);
  1397. if (x1) *x1 = ttSHORT(info->data + g + 6);
  1398. if (y1) *y1 = ttSHORT(info->data + g + 8);
  1399. }
  1400. return 1;
  1401. }
  1402. STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1)
  1403. {
  1404. return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1);
  1405. }
  1406. STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index)
  1407. {
  1408. stbtt_int16 numberOfContours;
  1409. int g;
  1410. if (info->cff.size)
  1411. return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0;
  1412. g = stbtt__GetGlyfOffset(info, glyph_index);
  1413. if (g < 0) return 1;
  1414. numberOfContours = ttSHORT(info->data + g);
  1415. return numberOfContours == 0;
  1416. }
  1417. static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off,
  1418. stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy)
  1419. {
  1420. if (start_off) {
  1421. if (was_off)
  1422. stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy);
  1423. stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy);
  1424. } else {
  1425. if (was_off)
  1426. stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy);
  1427. else
  1428. stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0);
  1429. }
  1430. return num_vertices;
  1431. }
  1432. static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
  1433. {
  1434. stbtt_int16 numberOfContours;
  1435. stbtt_uint8 *endPtsOfContours;
  1436. stbtt_uint8 *data = info->data;
  1437. stbtt_vertex *vertices=0;
  1438. int num_vertices=0;
  1439. int g = stbtt__GetGlyfOffset(info, glyph_index);
  1440. *pvertices = NULL;
  1441. if (g < 0) return 0;
  1442. numberOfContours = ttSHORT(data + g);
  1443. if (numberOfContours > 0) {
  1444. stbtt_uint8 flags=0,flagcount;
  1445. stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0;
  1446. stbtt_int32 x,y,cx,cy,sx,sy, scx,scy;
  1447. stbtt_uint8 *points;
  1448. endPtsOfContours = (data + g + 10);
  1449. ins = ttUSHORT(data + g + 10 + numberOfContours * 2);
  1450. points = data + g + 10 + numberOfContours * 2 + 2 + ins;
  1451. n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2);
  1452. m = n + 2*numberOfContours; // a loose bound on how many vertices we might need
  1453. vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata);
  1454. if (vertices == 0)
  1455. return 0;
  1456. next_move = 0;
  1457. flagcount=0;
  1458. // in first pass, we load uninterpreted data into the allocated array
  1459. // above, shifted to the end of the array so we won't overwrite it when
  1460. // we create our final data starting from the front
  1461. off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated
  1462. // first load flags
  1463. for (i=0; i < n; ++i) {
  1464. if (flagcount == 0) {
  1465. flags = *points++;
  1466. if (flags & 8)
  1467. flagcount = *points++;
  1468. } else
  1469. --flagcount;
  1470. vertices[off+i].type = flags;
  1471. }
  1472. // now load x coordinates
  1473. x=0;
  1474. for (i=0; i < n; ++i) {
  1475. flags = vertices[off+i].type;
  1476. if (flags & 2) {
  1477. stbtt_int16 dx = *points++;
  1478. x += (flags & 16) ? dx : -dx; // ???
  1479. } else {
  1480. if (!(flags & 16)) {
  1481. x = x + (stbtt_int16) (points[0]*256 + points[1]);
  1482. points += 2;
  1483. }
  1484. }
  1485. vertices[off+i].x = (stbtt_int16) x;
  1486. }
  1487. // now load y coordinates
  1488. y=0;
  1489. for (i=0; i < n; ++i) {
  1490. flags = vertices[off+i].type;
  1491. if (flags & 4) {
  1492. stbtt_int16 dy = *points++;
  1493. y += (flags & 32) ? dy : -dy; // ???
  1494. } else {
  1495. if (!(flags & 32)) {
  1496. y = y + (stbtt_int16) (points[0]*256 + points[1]);
  1497. points += 2;
  1498. }
  1499. }
  1500. vertices[off+i].y = (stbtt_int16) y;
  1501. }
  1502. // now convert them to our format
  1503. num_vertices=0;
  1504. sx = sy = cx = cy = scx = scy = 0;
  1505. for (i=0; i < n; ++i) {
  1506. flags = vertices[off+i].type;
  1507. x = (stbtt_int16) vertices[off+i].x;
  1508. y = (stbtt_int16) vertices[off+i].y;
  1509. if (next_move == i) {
  1510. if (i != 0)
  1511. num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);
  1512. // now start the new one
  1513. start_off = !(flags & 1);
  1514. if (start_off) {
  1515. // if we start off with an off-curve point, then when we need to find a point on the curve
  1516. // where we can start, and we need to save some state for when we wraparound.
  1517. scx = x;
  1518. scy = y;
  1519. if (!(vertices[off+i+1].type & 1)) {
  1520. // next point is also a curve point, so interpolate an on-point curve
  1521. sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1;
  1522. sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1;
  1523. } else {
  1524. // otherwise just use the next point as our start point
  1525. sx = (stbtt_int32) vertices[off+i+1].x;
  1526. sy = (stbtt_int32) vertices[off+i+1].y;
  1527. ++i; // we're using point i+1 as the starting point, so skip it
  1528. }
  1529. } else {
  1530. sx = x;
  1531. sy = y;
  1532. }
  1533. stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0);
  1534. was_off = 0;
  1535. next_move = 1 + ttUSHORT(endPtsOfContours+j*2);
  1536. ++j;
  1537. } else {
  1538. if (!(flags & 1)) { // if it's a curve
  1539. if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint
  1540. stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy);
  1541. cx = x;
  1542. cy = y;
  1543. was_off = 1;
  1544. } else {
  1545. if (was_off)
  1546. stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy);
  1547. else
  1548. stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0);
  1549. was_off = 0;
  1550. }
  1551. }
  1552. }
  1553. num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);
  1554. } else if (numberOfContours == -1) {
  1555. // Compound shapes.
  1556. int more = 1;
  1557. stbtt_uint8 *comp = data + g + 10;
  1558. num_vertices = 0;
  1559. vertices = 0;
  1560. while (more) {
  1561. stbtt_uint16 flags, gidx;
  1562. int comp_num_verts = 0, i;
  1563. stbtt_vertex *comp_verts = 0, *tmp = 0;
  1564. float mtx[6] = {1,0,0,1,0,0}, m, n;
  1565. flags = ttSHORT(comp); comp+=2;
  1566. gidx = ttSHORT(comp); comp+=2;
  1567. if (flags & 2) { // XY values
  1568. if (flags & 1) { // shorts
  1569. mtx[4] = ttSHORT(comp); comp+=2;
  1570. mtx[5] = ttSHORT(comp); comp+=2;
  1571. } else {
  1572. mtx[4] = ttCHAR(comp); comp+=1;
  1573. mtx[5] = ttCHAR(comp); comp+=1;
  1574. }
  1575. }
  1576. else {
  1577. // @TODO handle matching point
  1578. STBTT_assert(0);
  1579. }
  1580. if (flags & (1<<3)) { // WE_HAVE_A_SCALE
  1581. mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
  1582. mtx[1] = mtx[2] = 0;
  1583. } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE
  1584. mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;
  1585. mtx[1] = mtx[2] = 0;
  1586. mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
  1587. } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO
  1588. mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;
  1589. mtx[1] = ttSHORT(comp)/16384.0f; comp+=2;
  1590. mtx[2] = ttSHORT(comp)/16384.0f; comp+=2;
  1591. mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
  1592. }
  1593. // Find transformation scales.
  1594. m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]);
  1595. n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]);
  1596. // Get indexed glyph.
  1597. comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts);
  1598. if (comp_num_verts > 0) {
  1599. // Transform vertices.
  1600. for (i = 0; i < comp_num_verts; ++i) {
  1601. stbtt_vertex* v = &comp_verts[i];
  1602. stbtt_vertex_type x,y;
  1603. x=v->x; y=v->y;
  1604. v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));
  1605. v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));
  1606. x=v->cx; y=v->cy;
  1607. v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));
  1608. v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));
  1609. }
  1610. // Append vertices.
  1611. tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata);
  1612. if (!tmp) {
  1613. if (vertices) STBTT_free(vertices, info->userdata);
  1614. if (comp_verts) STBTT_free(comp_verts, info->userdata);
  1615. return 0;
  1616. }
  1617. if (num_vertices > 0) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex));
  1618. STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex));
  1619. if (vertices) STBTT_free(vertices, info->userdata);
  1620. vertices = tmp;
  1621. STBTT_free(comp_verts, info->userdata);
  1622. num_vertices += comp_num_verts;
  1623. }
  1624. // More components ?
  1625. more = flags & (1<<5);
  1626. }
  1627. } else if (numberOfContours < 0) {
  1628. // @TODO other compound variations?
  1629. STBTT_assert(0);
  1630. } else {
  1631. // numberOfCounters == 0, do nothing
  1632. }
  1633. *pvertices = vertices;
  1634. return num_vertices;
  1635. }
  1636. typedef struct
  1637. {
  1638. int bounds;
  1639. int started;
  1640. float first_x, first_y;
  1641. float x, y;
  1642. stbtt_int32 min_x, max_x, min_y, max_y;
  1643. stbtt_vertex *pvertices;
  1644. int num_vertices;
  1645. } stbtt__csctx;
  1646. #define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0}
  1647. static void stbtt__track_vertex(stbtt__csctx *c, stbtt_int32 x, stbtt_int32 y)
  1648. {
  1649. if (x > c->max_x || !c->started) c->max_x = x;
  1650. if (y > c->max_y || !c->started) c->max_y = y;
  1651. if (x < c->min_x || !c->started) c->min_x = x;
  1652. if (y < c->min_y || !c->started) c->min_y = y;
  1653. c->started = 1;
  1654. }
  1655. static void stbtt__csctx_v(stbtt__csctx *c, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy, stbtt_int32 cx1, stbtt_int32 cy1)
  1656. {
  1657. if (c->bounds) {
  1658. stbtt__track_vertex(c, x, y);
  1659. if (type == STBTT_vcubic) {
  1660. stbtt__track_vertex(c, cx, cy);
  1661. stbtt__track_vertex(c, cx1, cy1);
  1662. }
  1663. } else {
  1664. stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy);
  1665. c->pvertices[c->num_vertices].cx1 = (stbtt_int16) cx1;
  1666. c->pvertices[c->num_vertices].cy1 = (stbtt_int16) cy1;
  1667. }
  1668. c->num_vertices++;
  1669. }
  1670. static void stbtt__csctx_close_shape(stbtt__csctx *ctx)
  1671. {
  1672. if (ctx->first_x != ctx->x || ctx->first_y != ctx->y)
  1673. stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0);
  1674. }
  1675. static void stbtt__csctx_rmove_to(stbtt__csctx *ctx, float dx, float dy)
  1676. {
  1677. stbtt__csctx_close_shape(ctx);
  1678. ctx->first_x = ctx->x = ctx->x + dx;
  1679. ctx->first_y = ctx->y = ctx->y + dy;
  1680. stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0);
  1681. }
  1682. static void stbtt__csctx_rline_to(stbtt__csctx *ctx, float dx, float dy)
  1683. {
  1684. ctx->x += dx;
  1685. ctx->y += dy;
  1686. stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0);
  1687. }
  1688. static void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3)
  1689. {
  1690. float cx1 = ctx->x + dx1;
  1691. float cy1 = ctx->y + dy1;
  1692. float cx2 = cx1 + dx2;
  1693. float cy2 = cy1 + dy2;
  1694. ctx->x = cx2 + dx3;
  1695. ctx->y = cy2 + dy3;
  1696. stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2);
  1697. }
  1698. static stbtt__buf stbtt__get_subr(stbtt__buf idx, int n)
  1699. {
  1700. int count = stbtt__cff_index_count(&idx);
  1701. int bias = 107;
  1702. if (count >= 33900)
  1703. bias = 32768;
  1704. else if (count >= 1240)
  1705. bias = 1131;
  1706. n += bias;
  1707. if (n < 0 || n >= count)
  1708. return stbtt__new_buf(NULL, 0);
  1709. return stbtt__cff_index_get(idx, n);
  1710. }
  1711. static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int glyph_index)
  1712. {
  1713. stbtt__buf fdselect = info->fdselect;
  1714. int nranges, start, end, v, fmt, fdselector = -1, i;
  1715. stbtt__buf_seek(&fdselect, 0);
  1716. fmt = stbtt__buf_get8(&fdselect);
  1717. if (fmt == 0) {
  1718. // untested
  1719. stbtt__buf_skip(&fdselect, glyph_index);
  1720. fdselector = stbtt__buf_get8(&fdselect);
  1721. } else if (fmt == 3) {
  1722. nranges = stbtt__buf_get16(&fdselect);
  1723. start = stbtt__buf_get16(&fdselect);
  1724. for (i = 0; i < nranges; i++) {
  1725. v = stbtt__buf_get8(&fdselect);
  1726. end = stbtt__buf_get16(&fdselect);
  1727. if (glyph_index >= start && glyph_index < end) {
  1728. fdselector = v;
  1729. break;
  1730. }
  1731. start = end;
  1732. }
  1733. }
  1734. if (fdselector == -1) stbtt__new_buf(NULL, 0);
  1735. return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector));
  1736. }
  1737. static int stbtt__run_charstring(const stbtt_fontinfo *info, int glyph_index, stbtt__csctx *c)
  1738. {
  1739. int in_header = 1, maskbits = 0, subr_stack_height = 0, sp = 0, v, i, b0;
  1740. int has_subrs = 0, clear_stack;
  1741. float s[48];
  1742. stbtt__buf subr_stack[10], subrs = info->subrs, b;
  1743. float f;
  1744. #define STBTT__CSERR(s) (0)
  1745. // this currently ignores the initial width value, which isn't needed if we have hmtx
  1746. b = stbtt__cff_index_get(info->charstrings, glyph_index);
  1747. while (b.cursor < b.size) {
  1748. i = 0;
  1749. clear_stack = 1;
  1750. b0 = stbtt__buf_get8(&b);
  1751. switch (b0) {
  1752. // @TODO implement hinting
  1753. case 0x13: // hintmask
  1754. case 0x14: // cntrmask
  1755. if (in_header)
  1756. maskbits += (sp / 2); // implicit "vstem"
  1757. in_header = 0;
  1758. stbtt__buf_skip(&b, (maskbits + 7) / 8);
  1759. break;
  1760. case 0x01: // hstem
  1761. case 0x03: // vstem
  1762. case 0x12: // hstemhm
  1763. case 0x17: // vstemhm
  1764. maskbits += (sp / 2);
  1765. break;
  1766. case 0x15: // rmoveto
  1767. in_header = 0;
  1768. if (sp < 2) return STBTT__CSERR("rmoveto stack");
  1769. stbtt__csctx_rmove_to(c, s[sp-2], s[sp-1]);
  1770. break;
  1771. case 0x04: // vmoveto
  1772. in_header = 0;
  1773. if (sp < 1) return STBTT__CSERR("vmoveto stack");
  1774. stbtt__csctx_rmove_to(c, 0, s[sp-1]);
  1775. break;
  1776. case 0x16: // hmoveto
  1777. in_header = 0;
  1778. if (sp < 1) return STBTT__CSERR("hmoveto stack");
  1779. stbtt__csctx_rmove_to(c, s[sp-1], 0);
  1780. break;
  1781. case 0x05: // rlineto
  1782. if (sp < 2) return STBTT__CSERR("rlineto stack");
  1783. for (; i + 1 < sp; i += 2)
  1784. stbtt__csctx_rline_to(c, s[i], s[i+1]);
  1785. break;
  1786. // hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical
  1787. // starting from a different place.
  1788. case 0x07: // vlineto
  1789. if (sp < 1) return STBTT__CSERR("vlineto stack");
  1790. goto vlineto;
  1791. case 0x06: // hlineto
  1792. if (sp < 1) return STBTT__CSERR("hlineto stack");
  1793. for (;;) {
  1794. if (i >= sp) break;
  1795. stbtt__csctx_rline_to(c, s[i], 0);
  1796. i++;
  1797. vlineto:
  1798. if (i >= sp) break;
  1799. stbtt__csctx_rline_to(c, 0, s[i]);
  1800. i++;
  1801. }
  1802. break;
  1803. case 0x1F: // hvcurveto
  1804. if (sp < 4) return STBTT__CSERR("hvcurveto stack");
  1805. goto hvcurveto;
  1806. case 0x1E: // vhcurveto
  1807. if (sp < 4) return STBTT__CSERR("vhcurveto stack");
  1808. for (;;) {
  1809. if (i + 3 >= sp) break;
  1810. stbtt__csctx_rccurve_to(c, 0, s[i], s[i+1], s[i+2], s[i+3], (sp - i == 5) ? s[i + 4] : 0.0f);
  1811. i += 4;
  1812. hvcurveto:
  1813. if (i + 3 >= sp) break;
  1814. stbtt__csctx_rccurve_to(c, s[i], 0, s[i+1], s[i+2], (sp - i == 5) ? s[i+4] : 0.0f, s[i+3]);
  1815. i += 4;
  1816. }
  1817. break;
  1818. case 0x08: // rrcurveto
  1819. if (sp < 6) return STBTT__CSERR("rcurveline stack");
  1820. for (; i + 5 < sp; i += 6)
  1821. stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);
  1822. break;
  1823. case 0x18: // rcurveline
  1824. if (sp < 8) return STBTT__CSERR("rcurveline stack");
  1825. for (; i + 5 < sp - 2; i += 6)
  1826. stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);
  1827. if (i + 1 >= sp) return STBTT__CSERR("rcurveline stack");
  1828. stbtt__csctx_rline_to(c, s[i], s[i+1]);
  1829. break;
  1830. case 0x19: // rlinecurve
  1831. if (sp < 8) return STBTT__CSERR("rlinecurve stack");
  1832. for (; i + 1 < sp - 6; i += 2)
  1833. stbtt__csctx_rline_to(c, s[i], s[i+1]);
  1834. if (i + 5 >= sp) return STBTT__CSERR("rlinecurve stack");
  1835. stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);
  1836. break;
  1837. case 0x1A: // vvcurveto
  1838. case 0x1B: // hhcurveto
  1839. if (sp < 4) return STBTT__CSERR("(vv|hh)curveto stack");
  1840. f = 0.0;
  1841. if (sp & 1) { f = s[i]; i++; }
  1842. for (; i + 3 < sp; i += 4) {
  1843. if (b0 == 0x1B)
  1844. stbtt__csctx_rccurve_to(c, s[i], f, s[i+1], s[i+2], s[i+3], 0.0);
  1845. else
  1846. stbtt__csctx_rccurve_to(c, f, s[i], s[i+1], s[i+2], 0.0, s[i+3]);
  1847. f = 0.0;
  1848. }
  1849. break;
  1850. case 0x0A: // callsubr
  1851. if (!has_subrs) {
  1852. if (info->fdselect.size)
  1853. subrs = stbtt__cid_get_glyph_subrs(info, glyph_index);
  1854. has_subrs = 1;
  1855. }
  1856. // fallthrough
  1857. case 0x1D: // callgsubr
  1858. if (sp < 1) return STBTT__CSERR("call(g|)subr stack");
  1859. v = (int) s[--sp];
  1860. if (subr_stack_height >= 10) return STBTT__CSERR("recursion limit");
  1861. subr_stack[subr_stack_height++] = b;
  1862. b = stbtt__get_subr(b0 == 0x0A ? subrs : info->gsubrs, v);
  1863. if (b.size == 0) return STBTT__CSERR("subr not found");
  1864. b.cursor = 0;
  1865. clear_stack = 0;
  1866. break;
  1867. case 0x0B: // return
  1868. if (subr_stack_height <= 0) return STBTT__CSERR("return outside subr");
  1869. b = subr_stack[--subr_stack_height];
  1870. clear_stack = 0;
  1871. break;
  1872. case 0x0E: // endchar
  1873. stbtt__csctx_close_shape(c);
  1874. return 1;
  1875. case 0x0C: { // two-byte escape
  1876. float dx1, dx2, dx3, dx4, dx5, dx6, dy1, dy2, dy3, dy4, dy5, dy6;
  1877. float dx, dy;
  1878. int b1 = stbtt__buf_get8(&b);
  1879. switch (b1) {
  1880. // @TODO These "flex" implementations ignore the flex-depth and resolution,
  1881. // and always draw beziers.
  1882. case 0x22: // hflex
  1883. if (sp < 7) return STBTT__CSERR("hflex stack");
  1884. dx1 = s[0];
  1885. dx2 = s[1];
  1886. dy2 = s[2];
  1887. dx3 = s[3];
  1888. dx4 = s[4];
  1889. dx5 = s[5];
  1890. dx6 = s[6];
  1891. stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0);
  1892. stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0);
  1893. break;
  1894. case 0x23: // flex
  1895. if (sp < 13) return STBTT__CSERR("flex stack");
  1896. dx1 = s[0];
  1897. dy1 = s[1];
  1898. dx2 = s[2];
  1899. dy2 = s[3];
  1900. dx3 = s[4];
  1901. dy3 = s[5];
  1902. dx4 = s[6];
  1903. dy4 = s[7];
  1904. dx5 = s[8];
  1905. dy5 = s[9];
  1906. dx6 = s[10];
  1907. dy6 = s[11];
  1908. //fd is s[12]
  1909. stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3);
  1910. stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6);
  1911. break;
  1912. case 0x24: // hflex1
  1913. if (sp < 9) return STBTT__CSERR("hflex1 stack");
  1914. dx1 = s[0];
  1915. dy1 = s[1];
  1916. dx2 = s[2];
  1917. dy2 = s[3];
  1918. dx3 = s[4];
  1919. dx4 = s[5];
  1920. dx5 = s[6];
  1921. dy5 = s[7];
  1922. dx6 = s[8];
  1923. stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0);
  1924. stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1+dy2+dy5));
  1925. break;
  1926. case 0x25: // flex1
  1927. if (sp < 11) return STBTT__CSERR("flex1 stack");
  1928. dx1 = s[0];
  1929. dy1 = s[1];
  1930. dx2 = s[2];
  1931. dy2 = s[3];
  1932. dx3 = s[4];
  1933. dy3 = s[5];
  1934. dx4 = s[6];
  1935. dy4 = s[7];
  1936. dx5 = s[8];
  1937. dy5 = s[9];
  1938. dx6 = dy6 = s[10];
  1939. dx = dx1+dx2+dx3+dx4+dx5;
  1940. dy = dy1+dy2+dy3+dy4+dy5;
  1941. if (STBTT_fabs(dx) > STBTT_fabs(dy))
  1942. dy6 = -dy;
  1943. else
  1944. dx6 = -dx;
  1945. stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3);
  1946. stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6);
  1947. break;
  1948. default:
  1949. return STBTT__CSERR("unimplemented");
  1950. }
  1951. } break;
  1952. default:
  1953. if (b0 != 255 && b0 != 28 && (b0 < 32 || b0 > 254))
  1954. return STBTT__CSERR("reserved operator");
  1955. // push immediate
  1956. if (b0 == 255) {
  1957. f = (float)(stbtt_int32)stbtt__buf_get32(&b) / 0x10000;
  1958. } else {
  1959. stbtt__buf_skip(&b, -1);
  1960. f = (float)(stbtt_int16)stbtt__cff_int(&b);
  1961. }
  1962. if (sp >= 48) return STBTT__CSERR("push stack overflow");
  1963. s[sp++] = f;
  1964. clear_stack = 0;
  1965. break;
  1966. }
  1967. if (clear_stack) sp = 0;
  1968. }
  1969. return STBTT__CSERR("no endchar");
  1970. #undef STBTT__CSERR
  1971. }
  1972. static int stbtt__GetGlyphShapeT2(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
  1973. {
  1974. // runs the charstring twice, once to count and once to output (to avoid realloc)
  1975. stbtt__csctx count_ctx = STBTT__CSCTX_INIT(1);
  1976. stbtt__csctx output_ctx = STBTT__CSCTX_INIT(0);
  1977. if (stbtt__run_charstring(info, glyph_index, &count_ctx)) {
  1978. *pvertices = (stbtt_vertex*)STBTT_malloc(count_ctx.num_vertices*sizeof(stbtt_vertex), info->userdata);
  1979. output_ctx.pvertices = *pvertices;
  1980. if (stbtt__run_charstring(info, glyph_index, &output_ctx)) {
  1981. STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices);
  1982. return output_ctx.num_vertices;
  1983. }
  1984. }
  1985. *pvertices = NULL;
  1986. return 0;
  1987. }
  1988. static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)
  1989. {
  1990. stbtt__csctx c = STBTT__CSCTX_INIT(1);
  1991. int r = stbtt__run_charstring(info, glyph_index, &c);
  1992. if (x0) *x0 = r ? c.min_x : 0;
  1993. if (y0) *y0 = r ? c.min_y : 0;
  1994. if (x1) *x1 = r ? c.max_x : 0;
  1995. if (y1) *y1 = r ? c.max_y : 0;
  1996. return r ? c.num_vertices : 0;
  1997. }
  1998. STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
  1999. {
  2000. if (!info->cff.size)
  2001. return stbtt__GetGlyphShapeTT(info, glyph_index, pvertices);
  2002. else
  2003. return stbtt__GetGlyphShapeT2(info, glyph_index, pvertices);
  2004. }
  2005. STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing)
  2006. {
  2007. stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34);
  2008. if (glyph_index < numOfLongHorMetrics) {
  2009. if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*glyph_index);
  2010. if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2);
  2011. } else {
  2012. if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1));
  2013. if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics));
  2014. }
  2015. }
  2016. static int stbtt__GetGlyphKernInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)
  2017. {
  2018. stbtt_uint8 *data = info->data + info->kern;
  2019. stbtt_uint32 needle, straw;
  2020. int l, r, m;
  2021. // we only look at the first table. it must be 'horizontal' and format 0.
  2022. if (!info->kern)
  2023. return 0;
  2024. if (ttUSHORT(data+2) < 1) // number of tables, need at least 1
  2025. return 0;
  2026. if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format
  2027. return 0;
  2028. l = 0;
  2029. r = ttUSHORT(data+10) - 1;
  2030. needle = glyph1 << 16 | glyph2;
  2031. while (l <= r) {
  2032. m = (l + r) >> 1;
  2033. straw = ttULONG(data+18+(m*6)); // note: unaligned read
  2034. if (needle < straw)
  2035. r = m - 1;
  2036. else if (needle > straw)
  2037. l = m + 1;
  2038. else
  2039. return ttSHORT(data+22+(m*6));
  2040. }
  2041. return 0;
  2042. }
  2043. static stbtt_int32 stbtt__GetCoverageIndex(stbtt_uint8 *coverageTable, int glyph)
  2044. {
  2045. stbtt_uint16 coverageFormat = ttUSHORT(coverageTable);
  2046. switch(coverageFormat) {
  2047. case 1: {
  2048. stbtt_uint16 glyphCount = ttUSHORT(coverageTable + 2);
  2049. // Binary search.
  2050. stbtt_int32 l=0, r=glyphCount-1, m;
  2051. int straw, needle=glyph;
  2052. while (l <= r) {
  2053. stbtt_uint8 *glyphArray = coverageTable + 4;
  2054. stbtt_uint16 glyphID;
  2055. m = (l + r) >> 1;
  2056. glyphID = ttUSHORT(glyphArray + 2 * m);
  2057. straw = glyphID;
  2058. if (needle < straw)
  2059. r = m - 1;
  2060. else if (needle > straw)
  2061. l = m + 1;
  2062. else {
  2063. return m;
  2064. }
  2065. }
  2066. } break;
  2067. case 2: {
  2068. stbtt_uint16 rangeCount = ttUSHORT(coverageTable + 2);
  2069. stbtt_uint8 *rangeArray = coverageTable + 4;
  2070. // Binary search.
  2071. stbtt_int32 l=0, r=rangeCount-1, m;
  2072. int strawStart, strawEnd, needle=glyph;
  2073. while (l <= r) {
  2074. stbtt_uint8 *rangeRecord;
  2075. m = (l + r) >> 1;
  2076. rangeRecord = rangeArray + 6 * m;
  2077. strawStart = ttUSHORT(rangeRecord);
  2078. strawEnd = ttUSHORT(rangeRecord + 2);
  2079. if (needle < strawStart)
  2080. r = m - 1;
  2081. else if (needle > strawEnd)
  2082. l = m + 1;
  2083. else {
  2084. stbtt_uint16 startCoverageIndex = ttUSHORT(rangeRecord + 4);
  2085. return startCoverageIndex + glyph - strawStart;
  2086. }
  2087. }
  2088. } break;
  2089. default: {
  2090. // There are no other cases.
  2091. STBTT_assert(0);
  2092. } break;
  2093. }
  2094. return -1;
  2095. }
  2096. static stbtt_int32 stbtt__GetGlyphClass(stbtt_uint8 *classDefTable, int glyph)
  2097. {
  2098. stbtt_uint16 classDefFormat = ttUSHORT(classDefTable);
  2099. switch(classDefFormat)
  2100. {
  2101. case 1: {
  2102. stbtt_uint16 startGlyphID = ttUSHORT(classDefTable + 2);
  2103. stbtt_uint16 glyphCount = ttUSHORT(classDefTable + 4);
  2104. stbtt_uint8 *classDef1ValueArray = classDefTable + 6;
  2105. if (glyph >= startGlyphID && glyph < startGlyphID + glyphCount)
  2106. return (stbtt_int32)ttUSHORT(classDef1ValueArray + 2 * (glyph - startGlyphID));
  2107. classDefTable = classDef1ValueArray + 2 * glyphCount;
  2108. } break;
  2109. case 2: {
  2110. stbtt_uint16 classRangeCount = ttUSHORT(classDefTable + 2);
  2111. stbtt_uint8 *classRangeRecords = classDefTable + 4;
  2112. // Binary search.
  2113. stbtt_int32 l=0, r=classRangeCount-1, m;
  2114. int strawStart, strawEnd, needle=glyph;
  2115. while (l <= r) {
  2116. stbtt_uint8 *classRangeRecord;
  2117. m = (l + r) >> 1;
  2118. classRangeRecord = classRangeRecords + 6 * m;
  2119. strawStart = ttUSHORT(classRangeRecord);
  2120. strawEnd = ttUSHORT(classRangeRecord + 2);
  2121. if (needle < strawStart)
  2122. r = m - 1;
  2123. else if (needle > strawEnd)
  2124. l = m + 1;
  2125. else
  2126. return (stbtt_int32)ttUSHORT(classRangeRecord + 4);
  2127. }
  2128. classDefTable = classRangeRecords + 6 * classRangeCount;
  2129. } break;
  2130. default: {
  2131. // There are no other cases.
  2132. STBTT_assert(0);
  2133. } break;
  2134. }
  2135. return -1;
  2136. }
  2137. // Define to STBTT_assert(x) if you want to break on unimplemented formats.
  2138. #define STBTT_GPOS_TODO_assert(x)
  2139. static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)
  2140. {
  2141. stbtt_uint16 lookupListOffset;
  2142. stbtt_uint8 *lookupList;
  2143. stbtt_uint16 lookupCount;
  2144. stbtt_uint8 *data;
  2145. stbtt_int32 i;
  2146. if (!info->gpos) return 0;
  2147. data = info->data + info->gpos;
  2148. if (ttUSHORT(data+0) != 1) return 0; // Major version 1
  2149. if (ttUSHORT(data+2) != 0) return 0; // Minor version 0
  2150. lookupListOffset = ttUSHORT(data+8);
  2151. lookupList = data + lookupListOffset;
  2152. lookupCount = ttUSHORT(lookupList);
  2153. for (i=0; i<lookupCount; ++i) {
  2154. stbtt_uint16 lookupOffset = ttUSHORT(lookupList + 2 + 2 * i);
  2155. stbtt_uint8 *lookupTable = lookupList + lookupOffset;
  2156. stbtt_uint16 lookupType = ttUSHORT(lookupTable);
  2157. stbtt_uint16 subTableCount = ttUSHORT(lookupTable + 4);
  2158. stbtt_uint8 *subTableOffsets = lookupTable + 6;
  2159. switch(lookupType) {
  2160. case 2: { // Pair Adjustment Positioning Subtable
  2161. stbtt_int32 sti;
  2162. for (sti=0; sti<subTableCount; sti++) {
  2163. stbtt_uint16 subtableOffset = ttUSHORT(subTableOffsets + 2 * sti);
  2164. stbtt_uint8 *table = lookupTable + subtableOffset;
  2165. stbtt_uint16 posFormat = ttUSHORT(table);
  2166. stbtt_uint16 coverageOffset = ttUSHORT(table + 2);
  2167. stbtt_int32 coverageIndex = stbtt__GetCoverageIndex(table + coverageOffset, glyph1);
  2168. if (coverageIndex == -1) continue;
  2169. switch (posFormat) {
  2170. case 1: {
  2171. stbtt_int32 l, r, m;
  2172. int straw, needle;
  2173. stbtt_uint16 valueFormat1 = ttUSHORT(table + 4);
  2174. stbtt_uint16 valueFormat2 = ttUSHORT(table + 6);
  2175. stbtt_int32 valueRecordPairSizeInBytes = 2;
  2176. stbtt_uint16 pairSetCount = ttUSHORT(table + 8);
  2177. stbtt_uint16 pairPosOffset = ttUSHORT(table + 10 + 2 * coverageIndex);
  2178. stbtt_uint8 *pairValueTable = table + pairPosOffset;
  2179. stbtt_uint16 pairValueCount = ttUSHORT(pairValueTable);
  2180. stbtt_uint8 *pairValueArray = pairValueTable + 2;
  2181. // TODO: Support more formats.
  2182. STBTT_GPOS_TODO_assert(valueFormat1 == 4);
  2183. if (valueFormat1 != 4) return 0;
  2184. STBTT_GPOS_TODO_assert(valueFormat2 == 0);
  2185. if (valueFormat2 != 0) return 0;
  2186. STBTT_assert(coverageIndex < pairSetCount);
  2187. STBTT__NOTUSED(pairSetCount);
  2188. needle=glyph2;
  2189. r=pairValueCount-1;
  2190. l=0;
  2191. // Binary search.
  2192. while (l <= r) {
  2193. stbtt_uint16 secondGlyph;
  2194. stbtt_uint8 *pairValue;
  2195. m = (l + r) >> 1;
  2196. pairValue = pairValueArray + (2 + valueRecordPairSizeInBytes) * m;
  2197. secondGlyph = ttUSHORT(pairValue);
  2198. straw = secondGlyph;
  2199. if (needle < straw)
  2200. r = m - 1;
  2201. else if (needle > straw)
  2202. l = m + 1;
  2203. else {
  2204. stbtt_int16 xAdvance = ttSHORT(pairValue + 2);
  2205. return xAdvance;
  2206. }
  2207. }
  2208. } break;
  2209. case 2: {
  2210. stbtt_uint16 valueFormat1 = ttUSHORT(table + 4);
  2211. stbtt_uint16 valueFormat2 = ttUSHORT(table + 6);
  2212. stbtt_uint16 classDef1Offset = ttUSHORT(table + 8);
  2213. stbtt_uint16 classDef2Offset = ttUSHORT(table + 10);
  2214. int glyph1class = stbtt__GetGlyphClass(table + classDef1Offset, glyph1);
  2215. int glyph2class = stbtt__GetGlyphClass(table + classDef2Offset, glyph2);
  2216. stbtt_uint16 class1Count = ttUSHORT(table + 12);
  2217. stbtt_uint16 class2Count = ttUSHORT(table + 14);
  2218. STBTT_assert(glyph1class < class1Count);
  2219. STBTT_assert(glyph2class < class2Count);
  2220. // TODO: Support more formats.
  2221. STBTT_GPOS_TODO_assert(valueFormat1 == 4);
  2222. if (valueFormat1 != 4) return 0;
  2223. STBTT_GPOS_TODO_assert(valueFormat2 == 0);
  2224. if (valueFormat2 != 0) return 0;
  2225. if (glyph1class >= 0 && glyph1class < class1Count && glyph2class >= 0 && glyph2class < class2Count) {
  2226. stbtt_uint8 *class1Records = table + 16;
  2227. stbtt_uint8 *class2Records = class1Records + 2 * (glyph1class * class2Count);
  2228. stbtt_int16 xAdvance = ttSHORT(class2Records + 2 * glyph2class);
  2229. return xAdvance;
  2230. }
  2231. } break;
  2232. default: {
  2233. // There are no other cases.
  2234. STBTT_assert(0);
  2235. break;
  2236. };
  2237. }
  2238. }
  2239. break;
  2240. };
  2241. default:
  2242. // TODO: Implement other stuff.
  2243. break;
  2244. }
  2245. }
  2246. return 0;
  2247. }
  2248. STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int g1, int g2)
  2249. {
  2250. int xAdvance = 0;
  2251. if (info->gpos)
  2252. xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2);
  2253. if (info->kern)
  2254. xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2);
  2255. return xAdvance;
  2256. }
  2257. STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2)
  2258. {
  2259. if (!info->kern && !info->gpos) // if no kerning table, don't waste time looking up both codepoint->glyphs
  2260. return 0;
  2261. return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2));
  2262. }
  2263. STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing)
  2264. {
  2265. stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing);
  2266. }
  2267. STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap)
  2268. {
  2269. if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4);
  2270. if (descent) *descent = ttSHORT(info->data+info->hhea + 6);
  2271. if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8);
  2272. }
  2273. STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap)
  2274. {
  2275. int tab = stbtt__find_table(info->data, info->fontstart, "OS/2");
  2276. if (!tab)
  2277. return 0;
  2278. if (typoAscent ) *typoAscent = ttSHORT(info->data+tab + 68);
  2279. if (typoDescent) *typoDescent = ttSHORT(info->data+tab + 70);
  2280. if (typoLineGap) *typoLineGap = ttSHORT(info->data+tab + 72);
  2281. return 1;
  2282. }
  2283. STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1)
  2284. {
  2285. *x0 = ttSHORT(info->data + info->head + 36);
  2286. *y0 = ttSHORT(info->data + info->head + 38);
  2287. *x1 = ttSHORT(info->data + info->head + 40);
  2288. *y1 = ttSHORT(info->data + info->head + 42);
  2289. }
  2290. STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height)
  2291. {
  2292. int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6);
  2293. return (float) height / fheight;
  2294. }
  2295. STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels)
  2296. {
  2297. int unitsPerEm = ttUSHORT(info->data + info->head + 18);
  2298. return pixels / unitsPerEm;
  2299. }
  2300. STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v)
  2301. {
  2302. STBTT_free(v, info->userdata);
  2303. }
  2304. //////////////////////////////////////////////////////////////////////////////
  2305. //
  2306. // antialiasing software rasterizer
  2307. //
  2308. STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1)
  2309. {
  2310. int x0=0,y0=0,x1,y1; // =0 suppresses compiler warning
  2311. if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) {
  2312. // e.g. space character
  2313. if (ix0) *ix0 = 0;
  2314. if (iy0) *iy0 = 0;
  2315. if (ix1) *ix1 = 0;
  2316. if (iy1) *iy1 = 0;
  2317. } else {
  2318. // move to integral bboxes (treating pixels as little squares, what pixels get touched)?
  2319. if (ix0) *ix0 = STBTT_ifloor( x0 * scale_x + shift_x);
  2320. if (iy0) *iy0 = STBTT_ifloor(-y1 * scale_y + shift_y);
  2321. if (ix1) *ix1 = STBTT_iceil ( x1 * scale_x + shift_x);
  2322. if (iy1) *iy1 = STBTT_iceil (-y0 * scale_y + shift_y);
  2323. }
  2324. }
  2325. STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1)
  2326. {
  2327. stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1);
  2328. }
  2329. STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1)
  2330. {
  2331. stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1);
  2332. }
  2333. STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1)
  2334. {
  2335. stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1);
  2336. }
  2337. //////////////////////////////////////////////////////////////////////////////
  2338. //
  2339. // Rasterizer
  2340. typedef struct stbtt__hheap_chunk
  2341. {
  2342. struct stbtt__hheap_chunk *next;
  2343. } stbtt__hheap_chunk;
  2344. typedef struct stbtt__hheap
  2345. {
  2346. struct stbtt__hheap_chunk *head;
  2347. void *first_free;
  2348. int num_remaining_in_head_chunk;
  2349. } stbtt__hheap;
  2350. static void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata)
  2351. {
  2352. if (hh->first_free) {
  2353. void *p = hh->first_free;
  2354. hh->first_free = * (void **) p;
  2355. return p;
  2356. } else {
  2357. if (hh->num_remaining_in_head_chunk == 0) {
  2358. int count = (size < 32 ? 2000 : size < 128 ? 800 : 100);
  2359. stbtt__hheap_chunk *c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata);
  2360. if (c == NULL)
  2361. return NULL;
  2362. c->next = hh->head;
  2363. hh->head = c;
  2364. hh->num_remaining_in_head_chunk = count;
  2365. }
  2366. --hh->num_remaining_in_head_chunk;
  2367. return (char *) (hh->head) + sizeof(stbtt__hheap_chunk) + size * hh->num_remaining_in_head_chunk;
  2368. }
  2369. }
  2370. static void stbtt__hheap_free(stbtt__hheap *hh, void *p)
  2371. {
  2372. *(void **) p = hh->first_free;
  2373. hh->first_free = p;
  2374. }
  2375. static void stbtt__hheap_cleanup(stbtt__hheap *hh, void *userdata)
  2376. {
  2377. stbtt__hheap_chunk *c = hh->head;
  2378. while (c) {
  2379. stbtt__hheap_chunk *n = c->next;
  2380. STBTT_free(c, userdata);
  2381. c = n;
  2382. }
  2383. }
  2384. typedef struct stbtt__edge {
  2385. float x0,y0, x1,y1;
  2386. int invert;
  2387. } stbtt__edge;
  2388. typedef struct stbtt__active_edge
  2389. {
  2390. struct stbtt__active_edge *next;
  2391. #if STBTT_RASTERIZER_VERSION==1
  2392. int x,dx;
  2393. float ey;
  2394. int direction;
  2395. #elif STBTT_RASTERIZER_VERSION==2
  2396. float fx,fdx,fdy;
  2397. float direction;
  2398. float sy;
  2399. float ey;
  2400. #else
  2401. #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
  2402. #endif
  2403. } stbtt__active_edge;
  2404. #if STBTT_RASTERIZER_VERSION == 1
  2405. #define STBTT_FIXSHIFT 10
  2406. #define STBTT_FIX (1 << STBTT_FIXSHIFT)
  2407. #define STBTT_FIXMASK (STBTT_FIX-1)
  2408. static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata)
  2409. {
  2410. stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata);
  2411. float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);
  2412. STBTT_assert(z != NULL);
  2413. if (!z) return z;
  2414. // round dx down to avoid overshooting
  2415. if (dxdy < 0)
  2416. z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy);
  2417. else
  2418. z->dx = STBTT_ifloor(STBTT_FIX * dxdy);
  2419. z->x = STBTT_ifloor(STBTT_FIX * e->x0 + z->dx * (start_point - e->y0)); // use z->dx so when we offset later it's by the same amount
  2420. z->x -= off_x * STBTT_FIX;
  2421. z->ey = e->y1;
  2422. z->next = 0;
  2423. z->direction = e->invert ? 1 : -1;
  2424. return z;
  2425. }
  2426. #elif STBTT_RASTERIZER_VERSION == 2
  2427. static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata)
  2428. {
  2429. stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata);
  2430. float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);
  2431. STBTT_assert(z != NULL);
  2432. //STBTT_assert(e->y0 <= start_point);
  2433. if (!z) return z;
  2434. z->fdx = dxdy;
  2435. z->fdy = dxdy != 0.0f ? (1.0f/dxdy) : 0.0f;
  2436. z->fx = e->x0 + dxdy * (start_point - e->y0);
  2437. z->fx -= off_x;
  2438. z->direction = e->invert ? 1.0f : -1.0f;
  2439. z->sy = e->y0;
  2440. z->ey = e->y1;
  2441. z->next = 0;
  2442. return z;
  2443. }
  2444. #else
  2445. #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
  2446. #endif
  2447. #if STBTT_RASTERIZER_VERSION == 1
  2448. // note: this routine clips fills that extend off the edges... ideally this
  2449. // wouldn't happen, but it could happen if the truetype glyph bounding boxes
  2450. // are wrong, or if the user supplies a too-small bitmap
  2451. static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight)
  2452. {
  2453. // non-zero winding fill
  2454. int x0=0, w=0;
  2455. while (e) {
  2456. if (w == 0) {
  2457. // if we're currently at zero, we need to record the edge start point
  2458. x0 = e->x; w += e->direction;
  2459. } else {
  2460. int x1 = e->x; w += e->direction;
  2461. // if we went to zero, we need to draw
  2462. if (w == 0) {
  2463. int i = x0 >> STBTT_FIXSHIFT;
  2464. int j = x1 >> STBTT_FIXSHIFT;
  2465. if (i < len && j >= 0) {
  2466. if (i == j) {
  2467. // x0,x1 are the same pixel, so compute combined coverage
  2468. scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> STBTT_FIXSHIFT);
  2469. } else {
  2470. if (i >= 0) // add antialiasing for x0
  2471. scanline[i] = scanline[i] + (stbtt_uint8) (((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT);
  2472. else
  2473. i = -1; // clip
  2474. if (j < len) // add antialiasing for x1
  2475. scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT);
  2476. else
  2477. j = len; // clip
  2478. for (++i; i < j; ++i) // fill pixels between x0 and x1
  2479. scanline[i] = scanline[i] + (stbtt_uint8) max_weight;
  2480. }
  2481. }
  2482. }
  2483. }
  2484. e = e->next;
  2485. }
  2486. }
  2487. static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)
  2488. {
  2489. stbtt__hheap hh = { 0, 0, 0 };
  2490. stbtt__active_edge *active = NULL;
  2491. int y,j=0;
  2492. int max_weight = (255 / vsubsample); // weight per vertical scanline
  2493. int s; // vertical subsample index
  2494. unsigned char scanline_data[512], *scanline;
  2495. if (result->w > 512)
  2496. scanline = (unsigned char *) STBTT_malloc(result->w, userdata);
  2497. else
  2498. scanline = scanline_data;
  2499. y = off_y * vsubsample;
  2500. e[n].y0 = (off_y + result->h) * (float) vsubsample + 1;
  2501. while (j < result->h) {
  2502. STBTT_memset(scanline, 0, result->w);
  2503. for (s=0; s < vsubsample; ++s) {
  2504. // find center of pixel for this scanline
  2505. float scan_y = y + 0.5f;
  2506. stbtt__active_edge **step = &active;
  2507. // update all active edges;
  2508. // remove all active edges that terminate before the center of this scanline
  2509. while (*step) {
  2510. stbtt__active_edge * z = *step;
  2511. if (z->ey <= scan_y) {
  2512. *step = z->next; // delete from list
  2513. STBTT_assert(z->direction);
  2514. z->direction = 0;
  2515. stbtt__hheap_free(&hh, z);
  2516. } else {
  2517. z->x += z->dx; // advance to position for current scanline
  2518. step = &((*step)->next); // advance through list
  2519. }
  2520. }
  2521. // resort the list if needed
  2522. for(;;) {
  2523. int changed=0;
  2524. step = &active;
  2525. while (*step && (*step)->next) {
  2526. if ((*step)->x > (*step)->next->x) {
  2527. stbtt__active_edge *t = *step;
  2528. stbtt__active_edge *q = t->next;
  2529. t->next = q->next;
  2530. q->next = t;
  2531. *step = q;
  2532. changed = 1;
  2533. }
  2534. step = &(*step)->next;
  2535. }
  2536. if (!changed) break;
  2537. }
  2538. // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline
  2539. while (e->y0 <= scan_y) {
  2540. if (e->y1 > scan_y) {
  2541. stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y, userdata);
  2542. if (z != NULL) {
  2543. // find insertion point
  2544. if (active == NULL)
  2545. active = z;
  2546. else if (z->x < active->x) {
  2547. // insert at front
  2548. z->next = active;
  2549. active = z;
  2550. } else {
  2551. // find thing to insert AFTER
  2552. stbtt__active_edge *p = active;
  2553. while (p->next && p->next->x < z->x)
  2554. p = p->next;
  2555. // at this point, p->next->x is NOT < z->x
  2556. z->next = p->next;
  2557. p->next = z;
  2558. }
  2559. }
  2560. }
  2561. ++e;
  2562. }
  2563. // now process all active edges in XOR fashion
  2564. if (active)
  2565. stbtt__fill_active_edges(scanline, result->w, active, max_weight);
  2566. ++y;
  2567. }
  2568. STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w);
  2569. ++j;
  2570. }
  2571. stbtt__hheap_cleanup(&hh, userdata);
  2572. if (scanline != scanline_data)
  2573. STBTT_free(scanline, userdata);
  2574. }
  2575. #elif STBTT_RASTERIZER_VERSION == 2
  2576. // the edge passed in here does not cross the vertical line at x or the vertical line at x+1
  2577. // (i.e. it has already been clipped to those)
  2578. static void stbtt__handle_clipped_edge(float *scanline, int x, stbtt__active_edge *e, float x0, float y0, float x1, float y1)
  2579. {
  2580. if (y0 == y1) return;
  2581. STBTT_assert(y0 < y1);
  2582. STBTT_assert(e->sy <= e->ey);
  2583. if (y0 > e->ey) return;
  2584. if (y1 < e->sy) return;
  2585. if (y0 < e->sy) {
  2586. x0 += (x1-x0) * (e->sy - y0) / (y1-y0);
  2587. y0 = e->sy;
  2588. }
  2589. if (y1 > e->ey) {
  2590. x1 += (x1-x0) * (e->ey - y1) / (y1-y0);
  2591. y1 = e->ey;
  2592. }
  2593. if (x0 == x)
  2594. STBTT_assert(x1 <= x+1);
  2595. else if (x0 == x+1)
  2596. STBTT_assert(x1 >= x);
  2597. else if (x0 <= x)
  2598. STBTT_assert(x1 <= x);
  2599. else if (x0 >= x+1)
  2600. STBTT_assert(x1 >= x+1);
  2601. else
  2602. STBTT_assert(x1 >= x && x1 <= x+1);
  2603. if (x0 <= x && x1 <= x)
  2604. scanline[x] += e->direction * (y1-y0);
  2605. else if (x0 >= x+1 && x1 >= x+1)
  2606. ;
  2607. else {
  2608. STBTT_assert(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1);
  2609. scanline[x] += e->direction * (y1-y0) * (1-((x0-x)+(x1-x))/2); // coverage = 1 - average x position
  2610. }
  2611. }
  2612. static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, stbtt__active_edge *e, float y_top)
  2613. {
  2614. float y_bottom = y_top+1;
  2615. while (e) {
  2616. // brute force every pixel
  2617. // compute intersection points with top & bottom
  2618. STBTT_assert(e->ey >= y_top);
  2619. if (e->fdx == 0) {
  2620. float x0 = e->fx;
  2621. if (x0 < len) {
  2622. if (x0 >= 0) {
  2623. stbtt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom);
  2624. stbtt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom);
  2625. } else {
  2626. stbtt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom);
  2627. }
  2628. }
  2629. } else {
  2630. float x0 = e->fx;
  2631. float dx = e->fdx;
  2632. float xb = x0 + dx;
  2633. float x_top, x_bottom;
  2634. float sy0,sy1;
  2635. float dy = e->fdy;
  2636. STBTT_assert(e->sy <= y_bottom && e->ey >= y_top);
  2637. // compute endpoints of line segment clipped to this scanline (if the
  2638. // line segment starts on this scanline. x0 is the intersection of the
  2639. // line with y_top, but that may be off the line segment.
  2640. if (e->sy > y_top) {
  2641. x_top = x0 + dx * (e->sy - y_top);
  2642. sy0 = e->sy;
  2643. } else {
  2644. x_top = x0;
  2645. sy0 = y_top;
  2646. }
  2647. if (e->ey < y_bottom) {
  2648. x_bottom = x0 + dx * (e->ey - y_top);
  2649. sy1 = e->ey;
  2650. } else {
  2651. x_bottom = xb;
  2652. sy1 = y_bottom;
  2653. }
  2654. if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) {
  2655. // from here on, we don't have to range check x values
  2656. if ((int) x_top == (int) x_bottom) {
  2657. float height;
  2658. // simple case, only spans one pixel
  2659. int x = (int) x_top;
  2660. height = sy1 - sy0;
  2661. STBTT_assert(x >= 0 && x < len);
  2662. scanline[x] += e->direction * (1-((x_top - x) + (x_bottom-x))/2) * height;
  2663. scanline_fill[x] += e->direction * height; // everything right of this pixel is filled
  2664. } else {
  2665. int x,x1,x2;
  2666. float y_crossing, step, sign, area;
  2667. // covers 2+ pixels
  2668. if (x_top > x_bottom) {
  2669. // flip scanline vertically; signed area is the same
  2670. float t;
  2671. sy0 = y_bottom - (sy0 - y_top);
  2672. sy1 = y_bottom - (sy1 - y_top);
  2673. t = sy0, sy0 = sy1, sy1 = t;
  2674. t = x_bottom, x_bottom = x_top, x_top = t;
  2675. dx = -dx;
  2676. dy = -dy;
  2677. t = x0, x0 = xb, xb = t;
  2678. }
  2679. x1 = (int) x_top;
  2680. x2 = (int) x_bottom;
  2681. // compute intersection with y axis at x1+1
  2682. y_crossing = (x1+1 - x0) * dy + y_top;
  2683. sign = e->direction;
  2684. // area of the rectangle covered from y0..y_crossing
  2685. area = sign * (y_crossing-sy0);
  2686. // area of the triangle (x_top,y0), (x+1,y0), (x+1,y_crossing)
  2687. scanline[x1] += area * (1-((x_top - x1)+(x1+1-x1))/2);
  2688. step = sign * dy;
  2689. for (x = x1+1; x < x2; ++x) {
  2690. scanline[x] += area + step/2;
  2691. area += step;
  2692. }
  2693. y_crossing += dy * (x2 - (x1+1));
  2694. STBTT_assert(STBTT_fabs(area) <= 1.01f);
  2695. scanline[x2] += area + sign * (1-((x2-x2)+(x_bottom-x2))/2) * (sy1-y_crossing);
  2696. scanline_fill[x2] += sign * (sy1-sy0);
  2697. }
  2698. } else {
  2699. // if edge goes outside of box we're drawing, we require
  2700. // clipping logic. since this does not match the intended use
  2701. // of this library, we use a different, very slow brute
  2702. // force implementation
  2703. int x;
  2704. for (x=0; x < len; ++x) {
  2705. // cases:
  2706. //
  2707. // there can be up to two intersections with the pixel. any intersection
  2708. // with left or right edges can be handled by splitting into two (or three)
  2709. // regions. intersections with top & bottom do not necessitate case-wise logic.
  2710. //
  2711. // the old way of doing this found the intersections with the left & right edges,
  2712. // then used some simple logic to produce up to three segments in sorted order
  2713. // from top-to-bottom. however, this had a problem: if an x edge was epsilon
  2714. // across the x border, then the corresponding y position might not be distinct
  2715. // from the other y segment, and it might ignored as an empty segment. to avoid
  2716. // that, we need to explicitly produce segments based on x positions.
  2717. // rename variables to clearly-defined pairs
  2718. float y0 = y_top;
  2719. float x1 = (float) (x);
  2720. float x2 = (float) (x+1);
  2721. float x3 = xb;
  2722. float y3 = y_bottom;
  2723. // x = e->x + e->dx * (y-y_top)
  2724. // (y-y_top) = (x - e->x) / e->dx
  2725. // y = (x - e->x) / e->dx + y_top
  2726. float y1 = (x - x0) / dx + y_top;
  2727. float y2 = (x+1 - x0) / dx + y_top;
  2728. if (x0 < x1 && x3 > x2) { // three segments descending down-right
  2729. stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);
  2730. stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x2,y2);
  2731. stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);
  2732. } else if (x3 < x1 && x0 > x2) { // three segments descending down-left
  2733. stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);
  2734. stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x1,y1);
  2735. stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);
  2736. } else if (x0 < x1 && x3 > x1) { // two segments across x, down-right
  2737. stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);
  2738. stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);
  2739. } else if (x3 < x1 && x0 > x1) { // two segments across x, down-left
  2740. stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);
  2741. stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);
  2742. } else if (x0 < x2 && x3 > x2) { // two segments across x+1, down-right
  2743. stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);
  2744. stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);
  2745. } else if (x3 < x2 && x0 > x2) { // two segments across x+1, down-left
  2746. stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);
  2747. stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);
  2748. } else { // one segment
  2749. stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x3,y3);
  2750. }
  2751. }
  2752. }
  2753. }
  2754. e = e->next;
  2755. }
  2756. }
  2757. // directly AA rasterize edges w/o supersampling
  2758. static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)
  2759. {
  2760. stbtt__hheap hh = { 0, 0, 0 };
  2761. stbtt__active_edge *active = NULL;
  2762. int y,j=0, i;
  2763. float scanline_data[129], *scanline, *scanline2;
  2764. STBTT__NOTUSED(vsubsample);
  2765. if (result->w > 64)
  2766. scanline = (float *) STBTT_malloc((result->w*2+1) * sizeof(float), userdata);
  2767. else
  2768. scanline = scanline_data;
  2769. scanline2 = scanline + result->w;
  2770. y = off_y;
  2771. e[n].y0 = (float) (off_y + result->h) + 1;
  2772. while (j < result->h) {
  2773. // find center of pixel for this scanline
  2774. float scan_y_top = y + 0.0f;
  2775. float scan_y_bottom = y + 1.0f;
  2776. stbtt__active_edge **step = &active;
  2777. STBTT_memset(scanline , 0, result->w*sizeof(scanline[0]));
  2778. STBTT_memset(scanline2, 0, (result->w+1)*sizeof(scanline[0]));
  2779. // update all active edges;
  2780. // remove all active edges that terminate before the top of this scanline
  2781. while (*step) {
  2782. stbtt__active_edge * z = *step;
  2783. if (z->ey <= scan_y_top) {
  2784. *step = z->next; // delete from list
  2785. STBTT_assert(z->direction);
  2786. z->direction = 0;
  2787. stbtt__hheap_free(&hh, z);
  2788. } else {
  2789. step = &((*step)->next); // advance through list
  2790. }
  2791. }
  2792. // insert all edges that start before the bottom of this scanline
  2793. while (e->y0 <= scan_y_bottom) {
  2794. if (e->y0 != e->y1) {
  2795. stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata);
  2796. if (z != NULL) {
  2797. if (j == 0 && off_y != 0) {
  2798. if (z->ey < scan_y_top) {
  2799. // this can happen due to subpixel positioning and some kind of fp rounding error i think
  2800. z->ey = scan_y_top;
  2801. }
  2802. }
  2803. STBTT_assert(z->ey >= scan_y_top); // if we get really unlucky a tiny bit of an edge can be out of bounds
  2804. // insert at front
  2805. z->next = active;
  2806. active = z;
  2807. }
  2808. }
  2809. ++e;
  2810. }
  2811. // now process all active edges
  2812. if (active)
  2813. stbtt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top);
  2814. {
  2815. float sum = 0;
  2816. for (i=0; i < result->w; ++i) {
  2817. float k;
  2818. int m;
  2819. sum += scanline2[i];
  2820. k = scanline[i] + sum;
  2821. k = (float) STBTT_fabs(k)*255 + 0.5f;
  2822. m = (int) k;
  2823. if (m > 255) m = 255;
  2824. result->pixels[j*result->stride + i] = (unsigned char) m;
  2825. }
  2826. }
  2827. // advance all the edges
  2828. step = &active;
  2829. while (*step) {
  2830. stbtt__active_edge *z = *step;
  2831. z->fx += z->fdx; // advance to position for current scanline
  2832. step = &((*step)->next); // advance through list
  2833. }
  2834. ++y;
  2835. ++j;
  2836. }
  2837. stbtt__hheap_cleanup(&hh, userdata);
  2838. if (scanline != scanline_data)
  2839. STBTT_free(scanline, userdata);
  2840. }
  2841. #else
  2842. #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
  2843. #endif
  2844. #define STBTT__COMPARE(a,b) ((a)->y0 < (b)->y0)
  2845. static void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n)
  2846. {
  2847. int i,j;
  2848. for (i=1; i < n; ++i) {
  2849. stbtt__edge t = p[i], *a = &t;
  2850. j = i;
  2851. while (j > 0) {
  2852. stbtt__edge *b = &p[j-1];
  2853. int c = STBTT__COMPARE(a,b);
  2854. if (!c) break;
  2855. p[j] = p[j-1];
  2856. --j;
  2857. }
  2858. if (i != j)
  2859. p[j] = t;
  2860. }
  2861. }
  2862. static void stbtt__sort_edges_quicksort(stbtt__edge *p, int n)
  2863. {
  2864. /* threshold for transitioning to insertion sort */
  2865. while (n > 12) {
  2866. stbtt__edge t;
  2867. int c01,c12,c,m,i,j;
  2868. /* compute median of three */
  2869. m = n >> 1;
  2870. c01 = STBTT__COMPARE(&p[0],&p[m]);
  2871. c12 = STBTT__COMPARE(&p[m],&p[n-1]);
  2872. /* if 0 >= mid >= end, or 0 < mid < end, then use mid */
  2873. if (c01 != c12) {
  2874. /* otherwise, we'll need to swap something else to middle */
  2875. int z;
  2876. c = STBTT__COMPARE(&p[0],&p[n-1]);
  2877. /* 0>mid && mid<n: 0>n => n; 0<n => 0 */
  2878. /* 0<mid && mid>n: 0>n => 0; 0<n => n */
  2879. z = (c == c12) ? 0 : n-1;
  2880. t = p[z];
  2881. p[z] = p[m];
  2882. p[m] = t;
  2883. }
  2884. /* now p[m] is the median-of-three */
  2885. /* swap it to the beginning so it won't move around */
  2886. t = p[0];
  2887. p[0] = p[m];
  2888. p[m] = t;
  2889. /* partition loop */
  2890. i=1;
  2891. j=n-1;
  2892. for(;;) {
  2893. /* handling of equality is crucial here */
  2894. /* for sentinels & efficiency with duplicates */
  2895. for (;;++i) {
  2896. if (!STBTT__COMPARE(&p[i], &p[0])) break;
  2897. }
  2898. for (;;--j) {
  2899. if (!STBTT__COMPARE(&p[0], &p[j])) break;
  2900. }
  2901. /* make sure we haven't crossed */
  2902. if (i >= j) break;
  2903. t = p[i];
  2904. p[i] = p[j];
  2905. p[j] = t;
  2906. ++i;
  2907. --j;
  2908. }
  2909. /* recurse on smaller side, iterate on larger */
  2910. if (j < (n-i)) {
  2911. stbtt__sort_edges_quicksort(p,j);
  2912. p = p+i;
  2913. n = n-i;
  2914. } else {
  2915. stbtt__sort_edges_quicksort(p+i, n-i);
  2916. n = j;
  2917. }
  2918. }
  2919. }
  2920. static void stbtt__sort_edges(stbtt__edge *p, int n)
  2921. {
  2922. stbtt__sort_edges_quicksort(p, n);
  2923. stbtt__sort_edges_ins_sort(p, n);
  2924. }
  2925. typedef struct
  2926. {
  2927. float x,y;
  2928. } stbtt__point;
  2929. static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcount, int windings, float scale_x, float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert, void *userdata)
  2930. {
  2931. float y_scale_inv = invert ? -scale_y : scale_y;
  2932. stbtt__edge *e;
  2933. int n,i,j,k,m;
  2934. #if STBTT_RASTERIZER_VERSION == 1
  2935. int vsubsample = result->h < 8 ? 15 : 5;
  2936. #elif STBTT_RASTERIZER_VERSION == 2
  2937. int vsubsample = 1;
  2938. #else
  2939. #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
  2940. #endif
  2941. // vsubsample should divide 255 evenly; otherwise we won't reach full opacity
  2942. // now we have to blow out the windings into explicit edge lists
  2943. n = 0;
  2944. for (i=0; i < windings; ++i)
  2945. n += wcount[i];
  2946. e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel
  2947. if (e == 0) return;
  2948. n = 0;
  2949. m=0;
  2950. for (i=0; i < windings; ++i) {
  2951. stbtt__point *p = pts + m;
  2952. m += wcount[i];
  2953. j = wcount[i]-1;
  2954. for (k=0; k < wcount[i]; j=k++) {
  2955. int a=k,b=j;
  2956. // skip the edge if horizontal
  2957. if (p[j].y == p[k].y)
  2958. continue;
  2959. // add edge from j to k to the list
  2960. e[n].invert = 0;
  2961. if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) {
  2962. e[n].invert = 1;
  2963. a=j,b=k;
  2964. }
  2965. e[n].x0 = p[a].x * scale_x + shift_x;
  2966. e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample;
  2967. e[n].x1 = p[b].x * scale_x + shift_x;
  2968. e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample;
  2969. ++n;
  2970. }
  2971. }
  2972. // now sort the edges by their highest point (should snap to integer, and then by x)
  2973. //STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare);
  2974. stbtt__sort_edges(e, n);
  2975. // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule
  2976. stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata);
  2977. STBTT_free(e, userdata);
  2978. }
  2979. static void stbtt__add_point(stbtt__point *points, int n, float x, float y)
  2980. {
  2981. if (!points) return; // during first pass, it's unallocated
  2982. points[n].x = x;
  2983. points[n].y = y;
  2984. }
  2985. // tessellate until threshold p is happy... @TODO warped to compensate for non-linear stretching
  2986. static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n)
  2987. {
  2988. // midpoint
  2989. float mx = (x0 + 2*x1 + x2)/4;
  2990. float my = (y0 + 2*y1 + y2)/4;
  2991. // versus directly drawn line
  2992. float dx = (x0+x2)/2 - mx;
  2993. float dy = (y0+y2)/2 - my;
  2994. if (n > 16) // 65536 segments on one curve better be enough!
  2995. return 1;
  2996. if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA
  2997. stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1);
  2998. stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1);
  2999. } else {
  3000. stbtt__add_point(points, *num_points,x2,y2);
  3001. *num_points = *num_points+1;
  3002. }
  3003. return 1;
  3004. }
  3005. static void stbtt__tesselate_cubic(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float objspace_flatness_squared, int n)
  3006. {
  3007. // @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough
  3008. float dx0 = x1-x0;
  3009. float dy0 = y1-y0;
  3010. float dx1 = x2-x1;
  3011. float dy1 = y2-y1;
  3012. float dx2 = x3-x2;
  3013. float dy2 = y3-y2;
  3014. float dx = x3-x0;
  3015. float dy = y3-y0;
  3016. float longlen = (float) (STBTT_sqrt(dx0*dx0+dy0*dy0)+STBTT_sqrt(dx1*dx1+dy1*dy1)+STBTT_sqrt(dx2*dx2+dy2*dy2));
  3017. float shortlen = (float) STBTT_sqrt(dx*dx+dy*dy);
  3018. float flatness_squared = longlen*longlen-shortlen*shortlen;
  3019. if (n > 16) // 65536 segments on one curve better be enough!
  3020. return;
  3021. if (flatness_squared > objspace_flatness_squared) {
  3022. float x01 = (x0+x1)/2;
  3023. float y01 = (y0+y1)/2;
  3024. float x12 = (x1+x2)/2;
  3025. float y12 = (y1+y2)/2;
  3026. float x23 = (x2+x3)/2;
  3027. float y23 = (y2+y3)/2;
  3028. float xa = (x01+x12)/2;
  3029. float ya = (y01+y12)/2;
  3030. float xb = (x12+x23)/2;
  3031. float yb = (y12+y23)/2;
  3032. float mx = (xa+xb)/2;
  3033. float my = (ya+yb)/2;
  3034. stbtt__tesselate_cubic(points, num_points, x0,y0, x01,y01, xa,ya, mx,my, objspace_flatness_squared,n+1);
  3035. stbtt__tesselate_cubic(points, num_points, mx,my, xb,yb, x23,y23, x3,y3, objspace_flatness_squared,n+1);
  3036. } else {
  3037. stbtt__add_point(points, *num_points,x3,y3);
  3038. *num_points = *num_points+1;
  3039. }
  3040. }
  3041. // returns number of contours
  3042. static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata)
  3043. {
  3044. stbtt__point *points=0;
  3045. int num_points=0;
  3046. float objspace_flatness_squared = objspace_flatness * objspace_flatness;
  3047. int i,n=0,start=0, pass;
  3048. // count how many "moves" there are to get the contour count
  3049. for (i=0; i < num_verts; ++i)
  3050. if (vertices[i].type == STBTT_vmove)
  3051. ++n;
  3052. *num_contours = n;
  3053. if (n == 0) return 0;
  3054. *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata);
  3055. if (*contour_lengths == 0) {
  3056. *num_contours = 0;
  3057. return 0;
  3058. }
  3059. // make two passes through the points so we don't need to realloc
  3060. for (pass=0; pass < 2; ++pass) {
  3061. float x=0,y=0;
  3062. if (pass == 1) {
  3063. points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata);
  3064. if (points == NULL) goto error;
  3065. }
  3066. num_points = 0;
  3067. n= -1;
  3068. for (i=0; i < num_verts; ++i) {
  3069. switch (vertices[i].type) {
  3070. case STBTT_vmove:
  3071. // start the next contour
  3072. if (n >= 0)
  3073. (*contour_lengths)[n] = num_points - start;
  3074. ++n;
  3075. start = num_points;
  3076. x = vertices[i].x, y = vertices[i].y;
  3077. stbtt__add_point(points, num_points++, x,y);
  3078. break;
  3079. case STBTT_vline:
  3080. x = vertices[i].x, y = vertices[i].y;
  3081. stbtt__add_point(points, num_points++, x, y);
  3082. break;
  3083. case STBTT_vcurve:
  3084. stbtt__tesselate_curve(points, &num_points, x,y,
  3085. vertices[i].cx, vertices[i].cy,
  3086. vertices[i].x, vertices[i].y,
  3087. objspace_flatness_squared, 0);
  3088. x = vertices[i].x, y = vertices[i].y;
  3089. break;
  3090. case STBTT_vcubic:
  3091. stbtt__tesselate_cubic(points, &num_points, x,y,
  3092. vertices[i].cx, vertices[i].cy,
  3093. vertices[i].cx1, vertices[i].cy1,
  3094. vertices[i].x, vertices[i].y,
  3095. objspace_flatness_squared, 0);
  3096. x = vertices[i].x, y = vertices[i].y;
  3097. break;
  3098. }
  3099. }
  3100. (*contour_lengths)[n] = num_points - start;
  3101. }
  3102. return points;
  3103. error:
  3104. STBTT_free(points, userdata);
  3105. STBTT_free(*contour_lengths, userdata);
  3106. *contour_lengths = 0;
  3107. *num_contours = 0;
  3108. return NULL;
  3109. }
  3110. STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata)
  3111. {
  3112. float scale = scale_x > scale_y ? scale_y : scale_x;
  3113. int winding_count = 0;
  3114. int *winding_lengths = NULL;
  3115. stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata);
  3116. if (windings) {
  3117. stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata);
  3118. STBTT_free(winding_lengths, userdata);
  3119. STBTT_free(windings, userdata);
  3120. }
  3121. }
  3122. STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata)
  3123. {
  3124. STBTT_free(bitmap, userdata);
  3125. }
  3126. STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff)
  3127. {
  3128. int ix0,iy0,ix1,iy1;
  3129. stbtt__bitmap gbm;
  3130. stbtt_vertex *vertices;
  3131. int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
  3132. if (scale_x == 0) scale_x = scale_y;
  3133. if (scale_y == 0) {
  3134. if (scale_x == 0) {
  3135. STBTT_free(vertices, info->userdata);
  3136. return NULL;
  3137. }
  3138. scale_y = scale_x;
  3139. }
  3140. stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1);
  3141. // now we get the size
  3142. gbm.w = (ix1 - ix0);
  3143. gbm.h = (iy1 - iy0);
  3144. gbm.pixels = NULL; // in case we error
  3145. if (width ) *width = gbm.w;
  3146. if (height) *height = gbm.h;
  3147. if (xoff ) *xoff = ix0;
  3148. if (yoff ) *yoff = iy0;
  3149. if (gbm.w && gbm.h) {
  3150. gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata);
  3151. if (gbm.pixels) {
  3152. gbm.stride = gbm.w;
  3153. stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata);
  3154. }
  3155. }
  3156. STBTT_free(vertices, info->userdata);
  3157. return gbm.pixels;
  3158. }
  3159. STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff)
  3160. {
  3161. return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff);
  3162. }
  3163. STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph)
  3164. {
  3165. int ix0,iy0;
  3166. stbtt_vertex *vertices;
  3167. int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
  3168. stbtt__bitmap gbm;
  3169. stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0);
  3170. gbm.pixels = output;
  3171. gbm.w = out_w;
  3172. gbm.h = out_h;
  3173. gbm.stride = out_stride;
  3174. if (gbm.w && gbm.h)
  3175. stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata);
  3176. STBTT_free(vertices, info->userdata);
  3177. }
  3178. STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph)
  3179. {
  3180. stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph);
  3181. }
  3182. STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff)
  3183. {
  3184. return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff);
  3185. }
  3186. STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint)
  3187. {
  3188. stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, oversample_x, oversample_y, sub_x, sub_y, stbtt_FindGlyphIndex(info,codepoint));
  3189. }
  3190. STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint)
  3191. {
  3192. stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint));
  3193. }
  3194. STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff)
  3195. {
  3196. return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff);
  3197. }
  3198. STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint)
  3199. {
  3200. stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint);
  3201. }
  3202. //////////////////////////////////////////////////////////////////////////////
  3203. //
  3204. // bitmap baking
  3205. //
  3206. // This is SUPER-CRAPPY packing to keep source code small
  3207. static int stbtt_BakeFontBitmap_internal(unsigned char *data, int offset, // font location (use offset=0 for plain .ttf)
  3208. float pixel_height, // height of font in pixels
  3209. unsigned char *pixels, int pw, int ph, // bitmap to be filled in
  3210. int first_char, int num_chars, // characters to bake
  3211. stbtt_bakedchar *chardata)
  3212. {
  3213. float scale;
  3214. int x,y,bottom_y, i;
  3215. stbtt_fontinfo f;
  3216. f.userdata = NULL;
  3217. if (!stbtt_InitFont(&f, data, offset))
  3218. return -1;
  3219. STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels
  3220. x=y=1;
  3221. bottom_y = 1;
  3222. scale = stbtt_ScaleForPixelHeight(&f, pixel_height);
  3223. for (i=0; i < num_chars; ++i) {
  3224. int advance, lsb, x0,y0,x1,y1,gw,gh;
  3225. int g = stbtt_FindGlyphIndex(&f, first_char + i);
  3226. stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb);
  3227. stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1);
  3228. gw = x1-x0;
  3229. gh = y1-y0;
  3230. if (x + gw + 1 >= pw)
  3231. y = bottom_y, x = 1; // advance to next row
  3232. if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row
  3233. return -i;
  3234. STBTT_assert(x+gw < pw);
  3235. STBTT_assert(y+gh < ph);
  3236. stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g);
  3237. chardata[i].x0 = (stbtt_int16) x;
  3238. chardata[i].y0 = (stbtt_int16) y;
  3239. chardata[i].x1 = (stbtt_int16) (x + gw);
  3240. chardata[i].y1 = (stbtt_int16) (y + gh);
  3241. chardata[i].xadvance = scale * advance;
  3242. chardata[i].xoff = (float) x0;
  3243. chardata[i].yoff = (float) y0;
  3244. x = x + gw + 1;
  3245. if (y+gh+1 > bottom_y)
  3246. bottom_y = y+gh+1;
  3247. }
  3248. return bottom_y;
  3249. }
  3250. STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule)
  3251. {
  3252. float d3d_bias = opengl_fillrule ? 0 : -0.5f;
  3253. float ipw = 1.0f / pw, iph = 1.0f / ph;
  3254. const stbtt_bakedchar *b = chardata + char_index;
  3255. int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f);
  3256. int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f);
  3257. q->x0 = round_x + d3d_bias;
  3258. q->y0 = round_y + d3d_bias;
  3259. q->x1 = round_x + b->x1 - b->x0 + d3d_bias;
  3260. q->y1 = round_y + b->y1 - b->y0 + d3d_bias;
  3261. q->s0 = b->x0 * ipw;
  3262. q->t0 = b->y0 * iph;
  3263. q->s1 = b->x1 * ipw;
  3264. q->t1 = b->y1 * iph;
  3265. *xpos += b->xadvance;
  3266. }
  3267. //////////////////////////////////////////////////////////////////////////////
  3268. //
  3269. // rectangle packing replacement routines if you don't have stb_rect_pack.h
  3270. //
  3271. #ifndef STB_RECT_PACK_VERSION
  3272. typedef int stbrp_coord;
  3273. ////////////////////////////////////////////////////////////////////////////////////
  3274. // //
  3275. // //
  3276. // COMPILER WARNING ?!?!? //
  3277. // //
  3278. // //
  3279. // if you get a compile warning due to these symbols being defined more than //
  3280. // once, move #include "stb_rect_pack.h" before #include "stb_truetype.h" //
  3281. // //
  3282. ////////////////////////////////////////////////////////////////////////////////////
  3283. typedef struct
  3284. {
  3285. int width,height;
  3286. int x,y,bottom_y;
  3287. } stbrp_context;
  3288. typedef struct
  3289. {
  3290. unsigned char x;
  3291. } stbrp_node;
  3292. struct stbrp_rect
  3293. {
  3294. stbrp_coord x,y;
  3295. int id,w,h,was_packed;
  3296. };
  3297. static void stbrp_init_target(stbrp_context *con, int pw, int ph, stbrp_node *nodes, int num_nodes)
  3298. {
  3299. con->width = pw;
  3300. con->height = ph;
  3301. con->x = 0;
  3302. con->y = 0;
  3303. con->bottom_y = 0;
  3304. STBTT__NOTUSED(nodes);
  3305. STBTT__NOTUSED(num_nodes);
  3306. }
  3307. static void stbrp_pack_rects(stbrp_context *con, stbrp_rect *rects, int num_rects)
  3308. {
  3309. int i;
  3310. for (i=0; i < num_rects; ++i) {
  3311. if (con->x + rects[i].w > con->width) {
  3312. con->x = 0;
  3313. con->y = con->bottom_y;
  3314. }
  3315. if (con->y + rects[i].h > con->height)
  3316. break;
  3317. rects[i].x = con->x;
  3318. rects[i].y = con->y;
  3319. rects[i].was_packed = 1;
  3320. con->x += rects[i].w;
  3321. if (con->y + rects[i].h > con->bottom_y)
  3322. con->bottom_y = con->y + rects[i].h;
  3323. }
  3324. for ( ; i < num_rects; ++i)
  3325. rects[i].was_packed = 0;
  3326. }
  3327. #endif
  3328. //////////////////////////////////////////////////////////////////////////////
  3329. //
  3330. // bitmap baking
  3331. //
  3332. // This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If
  3333. // stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy.
  3334. STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int pw, int ph, int stride_in_bytes, int padding, void *alloc_context)
  3335. {
  3336. stbrp_context *context = (stbrp_context *) STBTT_malloc(sizeof(*context) ,alloc_context);
  3337. int num_nodes = pw - padding;
  3338. stbrp_node *nodes = (stbrp_node *) STBTT_malloc(sizeof(*nodes ) * num_nodes,alloc_context);
  3339. if (context == NULL || nodes == NULL) {
  3340. if (context != NULL) STBTT_free(context, alloc_context);
  3341. if (nodes != NULL) STBTT_free(nodes , alloc_context);
  3342. return 0;
  3343. }
  3344. spc->user_allocator_context = alloc_context;
  3345. spc->width = pw;
  3346. spc->height = ph;
  3347. spc->pixels = pixels;
  3348. spc->pack_info = context;
  3349. spc->nodes = nodes;
  3350. spc->padding = padding;
  3351. spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw;
  3352. spc->h_oversample = 1;
  3353. spc->v_oversample = 1;
  3354. spc->skip_missing = 0;
  3355. stbrp_init_target(context, pw-padding, ph-padding, nodes, num_nodes);
  3356. if (pixels)
  3357. STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels
  3358. return 1;
  3359. }
  3360. STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc)
  3361. {
  3362. STBTT_free(spc->nodes , spc->user_allocator_context);
  3363. STBTT_free(spc->pack_info, spc->user_allocator_context);
  3364. }
  3365. STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample)
  3366. {
  3367. STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE);
  3368. STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE);
  3369. if (h_oversample <= STBTT_MAX_OVERSAMPLE)
  3370. spc->h_oversample = h_oversample;
  3371. if (v_oversample <= STBTT_MAX_OVERSAMPLE)
  3372. spc->v_oversample = v_oversample;
  3373. }
  3374. STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip)
  3375. {
  3376. spc->skip_missing = skip;
  3377. }
  3378. #define STBTT__OVER_MASK (STBTT_MAX_OVERSAMPLE-1)
  3379. static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)
  3380. {
  3381. unsigned char buffer[STBTT_MAX_OVERSAMPLE];
  3382. int safe_w = w - kernel_width;
  3383. int j;
  3384. STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze
  3385. for (j=0; j < h; ++j) {
  3386. int i;
  3387. unsigned int total;
  3388. STBTT_memset(buffer, 0, kernel_width);
  3389. total = 0;
  3390. // make kernel_width a constant in common cases so compiler can optimize out the divide
  3391. switch (kernel_width) {
  3392. case 2:
  3393. for (i=0; i <= safe_w; ++i) {
  3394. total += pixels[i] - buffer[i & STBTT__OVER_MASK];
  3395. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
  3396. pixels[i] = (unsigned char) (total / 2);
  3397. }
  3398. break;
  3399. case 3:
  3400. for (i=0; i <= safe_w; ++i) {
  3401. total += pixels[i] - buffer[i & STBTT__OVER_MASK];
  3402. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
  3403. pixels[i] = (unsigned char) (total / 3);
  3404. }
  3405. break;
  3406. case 4:
  3407. for (i=0; i <= safe_w; ++i) {
  3408. total += pixels[i] - buffer[i & STBTT__OVER_MASK];
  3409. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
  3410. pixels[i] = (unsigned char) (total / 4);
  3411. }
  3412. break;
  3413. case 5:
  3414. for (i=0; i <= safe_w; ++i) {
  3415. total += pixels[i] - buffer[i & STBTT__OVER_MASK];
  3416. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
  3417. pixels[i] = (unsigned char) (total / 5);
  3418. }
  3419. break;
  3420. default:
  3421. for (i=0; i <= safe_w; ++i) {
  3422. total += pixels[i] - buffer[i & STBTT__OVER_MASK];
  3423. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
  3424. pixels[i] = (unsigned char) (total / kernel_width);
  3425. }
  3426. break;
  3427. }
  3428. for (; i < w; ++i) {
  3429. STBTT_assert(pixels[i] == 0);
  3430. total -= buffer[i & STBTT__OVER_MASK];
  3431. pixels[i] = (unsigned char) (total / kernel_width);
  3432. }
  3433. pixels += stride_in_bytes;
  3434. }
  3435. }
  3436. static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)
  3437. {
  3438. unsigned char buffer[STBTT_MAX_OVERSAMPLE];
  3439. int safe_h = h - kernel_width;
  3440. int j;
  3441. STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze
  3442. for (j=0; j < w; ++j) {
  3443. int i;
  3444. unsigned int total;
  3445. STBTT_memset(buffer, 0, kernel_width);
  3446. total = 0;
  3447. // make kernel_width a constant in common cases so compiler can optimize out the divide
  3448. switch (kernel_width) {
  3449. case 2:
  3450. for (i=0; i <= safe_h; ++i) {
  3451. total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
  3452. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
  3453. pixels[i*stride_in_bytes] = (unsigned char) (total / 2);
  3454. }
  3455. break;
  3456. case 3:
  3457. for (i=0; i <= safe_h; ++i) {
  3458. total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
  3459. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
  3460. pixels[i*stride_in_bytes] = (unsigned char) (total / 3);
  3461. }
  3462. break;
  3463. case 4:
  3464. for (i=0; i <= safe_h; ++i) {
  3465. total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
  3466. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
  3467. pixels[i*stride_in_bytes] = (unsigned char) (total / 4);
  3468. }
  3469. break;
  3470. case 5:
  3471. for (i=0; i <= safe_h; ++i) {
  3472. total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
  3473. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
  3474. pixels[i*stride_in_bytes] = (unsigned char) (total / 5);
  3475. }
  3476. break;
  3477. default:
  3478. for (i=0; i <= safe_h; ++i) {
  3479. total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
  3480. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
  3481. pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width);
  3482. }
  3483. break;
  3484. }
  3485. for (; i < h; ++i) {
  3486. STBTT_assert(pixels[i*stride_in_bytes] == 0);
  3487. total -= buffer[i & STBTT__OVER_MASK];
  3488. pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width);
  3489. }
  3490. pixels += 1;
  3491. }
  3492. }
  3493. static float stbtt__oversample_shift(int oversample)
  3494. {
  3495. if (!oversample)
  3496. return 0.0f;
  3497. // The prefilter is a box filter of width "oversample",
  3498. // which shifts phase by (oversample - 1)/2 pixels in
  3499. // oversampled space. We want to shift in the opposite
  3500. // direction to counter this.
  3501. return (float)-(oversample - 1) / (2.0f * (float)oversample);
  3502. }
  3503. // rects array must be big enough to accommodate all characters in the given ranges
  3504. STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects)
  3505. {
  3506. int i,j,k;
  3507. k=0;
  3508. for (i=0; i < num_ranges; ++i) {
  3509. float fh = ranges[i].font_size;
  3510. float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh);
  3511. ranges[i].h_oversample = (unsigned char) spc->h_oversample;
  3512. ranges[i].v_oversample = (unsigned char) spc->v_oversample;
  3513. for (j=0; j < ranges[i].num_chars; ++j) {
  3514. int x0,y0,x1,y1;
  3515. int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j];
  3516. int glyph = stbtt_FindGlyphIndex(info, codepoint);
  3517. if (glyph == 0 && spc->skip_missing) {
  3518. rects[k].w = rects[k].h = 0;
  3519. } else {
  3520. stbtt_GetGlyphBitmapBoxSubpixel(info,glyph,
  3521. scale * spc->h_oversample,
  3522. scale * spc->v_oversample,
  3523. 0,0,
  3524. &x0,&y0,&x1,&y1);
  3525. rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1);
  3526. rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1);
  3527. }
  3528. ++k;
  3529. }
  3530. }
  3531. return k;
  3532. }
  3533. STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int prefilter_x, int prefilter_y, float *sub_x, float *sub_y, int glyph)
  3534. {
  3535. stbtt_MakeGlyphBitmapSubpixel(info,
  3536. output,
  3537. out_w - (prefilter_x - 1),
  3538. out_h - (prefilter_y - 1),
  3539. out_stride,
  3540. scale_x,
  3541. scale_y,
  3542. shift_x,
  3543. shift_y,
  3544. glyph);
  3545. if (prefilter_x > 1)
  3546. stbtt__h_prefilter(output, out_w, out_h, out_stride, prefilter_x);
  3547. if (prefilter_y > 1)
  3548. stbtt__v_prefilter(output, out_w, out_h, out_stride, prefilter_y);
  3549. *sub_x = stbtt__oversample_shift(prefilter_x);
  3550. *sub_y = stbtt__oversample_shift(prefilter_y);
  3551. }
  3552. // rects array must be big enough to accommodate all characters in the given ranges
  3553. STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects)
  3554. {
  3555. int i,j,k, return_value = 1;
  3556. // save current values
  3557. int old_h_over = spc->h_oversample;
  3558. int old_v_over = spc->v_oversample;
  3559. k = 0;
  3560. for (i=0; i < num_ranges; ++i) {
  3561. float fh = ranges[i].font_size;
  3562. float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh);
  3563. float recip_h,recip_v,sub_x,sub_y;
  3564. spc->h_oversample = ranges[i].h_oversample;
  3565. spc->v_oversample = ranges[i].v_oversample;
  3566. recip_h = 1.0f / spc->h_oversample;
  3567. recip_v = 1.0f / spc->v_oversample;
  3568. sub_x = stbtt__oversample_shift(spc->h_oversample);
  3569. sub_y = stbtt__oversample_shift(spc->v_oversample);
  3570. for (j=0; j < ranges[i].num_chars; ++j) {
  3571. stbrp_rect *r = &rects[k];
  3572. if (r->was_packed && r->w != 0 && r->h != 0) {
  3573. stbtt_packedchar *bc = &ranges[i].chardata_for_range[j];
  3574. int advance, lsb, x0,y0,x1,y1;
  3575. int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j];
  3576. int glyph = stbtt_FindGlyphIndex(info, codepoint);
  3577. stbrp_coord pad = (stbrp_coord) spc->padding;
  3578. // pad on left and top
  3579. r->x += pad;
  3580. r->y += pad;
  3581. r->w -= pad;
  3582. r->h -= pad;
  3583. stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb);
  3584. stbtt_GetGlyphBitmapBox(info, glyph,
  3585. scale * spc->h_oversample,
  3586. scale * spc->v_oversample,
  3587. &x0,&y0,&x1,&y1);
  3588. stbtt_MakeGlyphBitmapSubpixel(info,
  3589. spc->pixels + r->x + r->y*spc->stride_in_bytes,
  3590. r->w - spc->h_oversample+1,
  3591. r->h - spc->v_oversample+1,
  3592. spc->stride_in_bytes,
  3593. scale * spc->h_oversample,
  3594. scale * spc->v_oversample,
  3595. 0,0,
  3596. glyph);
  3597. if (spc->h_oversample > 1)
  3598. stbtt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes,
  3599. r->w, r->h, spc->stride_in_bytes,
  3600. spc->h_oversample);
  3601. if (spc->v_oversample > 1)
  3602. stbtt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes,
  3603. r->w, r->h, spc->stride_in_bytes,
  3604. spc->v_oversample);
  3605. bc->x0 = (stbtt_int16) r->x;
  3606. bc->y0 = (stbtt_int16) r->y;
  3607. bc->x1 = (stbtt_int16) (r->x + r->w);
  3608. bc->y1 = (stbtt_int16) (r->y + r->h);
  3609. bc->xadvance = scale * advance;
  3610. bc->xoff = (float) x0 * recip_h + sub_x;
  3611. bc->yoff = (float) y0 * recip_v + sub_y;
  3612. bc->xoff2 = (x0 + r->w) * recip_h + sub_x;
  3613. bc->yoff2 = (y0 + r->h) * recip_v + sub_y;
  3614. } else {
  3615. return_value = 0; // if any fail, report failure
  3616. }
  3617. ++k;
  3618. }
  3619. }
  3620. // restore original values
  3621. spc->h_oversample = old_h_over;
  3622. spc->v_oversample = old_v_over;
  3623. return return_value;
  3624. }
  3625. STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects)
  3626. {
  3627. stbrp_pack_rects((stbrp_context *) spc->pack_info, rects, num_rects);
  3628. }
  3629. STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges)
  3630. {
  3631. stbtt_fontinfo info;
  3632. int i,j,n, return_value = 1;
  3633. //stbrp_context *context = (stbrp_context *) spc->pack_info;
  3634. stbrp_rect *rects;
  3635. // flag all characters as NOT packed
  3636. for (i=0; i < num_ranges; ++i)
  3637. for (j=0; j < ranges[i].num_chars; ++j)
  3638. ranges[i].chardata_for_range[j].x0 =
  3639. ranges[i].chardata_for_range[j].y0 =
  3640. ranges[i].chardata_for_range[j].x1 =
  3641. ranges[i].chardata_for_range[j].y1 = 0;
  3642. n = 0;
  3643. for (i=0; i < num_ranges; ++i)
  3644. n += ranges[i].num_chars;
  3645. rects = (stbrp_rect *) STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context);
  3646. if (rects == NULL)
  3647. return 0;
  3648. info.userdata = spc->user_allocator_context;
  3649. stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index));
  3650. n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects);
  3651. stbtt_PackFontRangesPackRects(spc, rects, n);
  3652. return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects);
  3653. STBTT_free(rects, spc->user_allocator_context);
  3654. return return_value;
  3655. }
  3656. STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size,
  3657. int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range)
  3658. {
  3659. stbtt_pack_range range;
  3660. range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range;
  3661. range.array_of_unicode_codepoints = NULL;
  3662. range.num_chars = num_chars_in_range;
  3663. range.chardata_for_range = chardata_for_range;
  3664. range.font_size = font_size;
  3665. return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1);
  3666. }
  3667. STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap)
  3668. {
  3669. int i_ascent, i_descent, i_lineGap;
  3670. float scale;
  3671. stbtt_fontinfo info;
  3672. stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata, index));
  3673. scale = size > 0 ? stbtt_ScaleForPixelHeight(&info, size) : stbtt_ScaleForMappingEmToPixels(&info, -size);
  3674. stbtt_GetFontVMetrics(&info, &i_ascent, &i_descent, &i_lineGap);
  3675. *ascent = (float) i_ascent * scale;
  3676. *descent = (float) i_descent * scale;
  3677. *lineGap = (float) i_lineGap * scale;
  3678. }
  3679. STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int align_to_integer)
  3680. {
  3681. float ipw = 1.0f / pw, iph = 1.0f / ph;
  3682. const stbtt_packedchar *b = chardata + char_index;
  3683. if (align_to_integer) {
  3684. float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f);
  3685. float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f);
  3686. q->x0 = x;
  3687. q->y0 = y;
  3688. q->x1 = x + b->xoff2 - b->xoff;
  3689. q->y1 = y + b->yoff2 - b->yoff;
  3690. } else {
  3691. q->x0 = *xpos + b->xoff;
  3692. q->y0 = *ypos + b->yoff;
  3693. q->x1 = *xpos + b->xoff2;
  3694. q->y1 = *ypos + b->yoff2;
  3695. }
  3696. q->s0 = b->x0 * ipw;
  3697. q->t0 = b->y0 * iph;
  3698. q->s1 = b->x1 * ipw;
  3699. q->t1 = b->y1 * iph;
  3700. *xpos += b->xadvance;
  3701. }
  3702. //////////////////////////////////////////////////////////////////////////////
  3703. //
  3704. // sdf computation
  3705. //
  3706. #define STBTT_min(a,b) ((a) < (b) ? (a) : (b))
  3707. #define STBTT_max(a,b) ((a) < (b) ? (b) : (a))
  3708. static int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], float q1[2], float q2[2], float hits[2][2])
  3709. {
  3710. float q0perp = q0[1]*ray[0] - q0[0]*ray[1];
  3711. float q1perp = q1[1]*ray[0] - q1[0]*ray[1];
  3712. float q2perp = q2[1]*ray[0] - q2[0]*ray[1];
  3713. float roperp = orig[1]*ray[0] - orig[0]*ray[1];
  3714. float a = q0perp - 2*q1perp + q2perp;
  3715. float b = q1perp - q0perp;
  3716. float c = q0perp - roperp;
  3717. float s0 = 0., s1 = 0.;
  3718. int num_s = 0;
  3719. if (a != 0.0) {
  3720. float discr = b*b - a*c;
  3721. if (discr > 0.0) {
  3722. float rcpna = -1 / a;
  3723. float d = (float) STBTT_sqrt(discr);
  3724. s0 = (b+d) * rcpna;
  3725. s1 = (b-d) * rcpna;
  3726. if (s0 >= 0.0 && s0 <= 1.0)
  3727. num_s = 1;
  3728. if (d > 0.0 && s1 >= 0.0 && s1 <= 1.0) {
  3729. if (num_s == 0) s0 = s1;
  3730. ++num_s;
  3731. }
  3732. }
  3733. } else {
  3734. // 2*b*s + c = 0
  3735. // s = -c / (2*b)
  3736. s0 = c / (-2 * b);
  3737. if (s0 >= 0.0 && s0 <= 1.0)
  3738. num_s = 1;
  3739. }
  3740. if (num_s == 0)
  3741. return 0;
  3742. else {
  3743. float rcp_len2 = 1 / (ray[0]*ray[0] + ray[1]*ray[1]);
  3744. float rayn_x = ray[0] * rcp_len2, rayn_y = ray[1] * rcp_len2;
  3745. float q0d = q0[0]*rayn_x + q0[1]*rayn_y;
  3746. float q1d = q1[0]*rayn_x + q1[1]*rayn_y;
  3747. float q2d = q2[0]*rayn_x + q2[1]*rayn_y;
  3748. float rod = orig[0]*rayn_x + orig[1]*rayn_y;
  3749. float q10d = q1d - q0d;
  3750. float q20d = q2d - q0d;
  3751. float q0rd = q0d - rod;
  3752. hits[0][0] = q0rd + s0*(2.0f - 2.0f*s0)*q10d + s0*s0*q20d;
  3753. hits[0][1] = a*s0+b;
  3754. if (num_s > 1) {
  3755. hits[1][0] = q0rd + s1*(2.0f - 2.0f*s1)*q10d + s1*s1*q20d;
  3756. hits[1][1] = a*s1+b;
  3757. return 2;
  3758. } else {
  3759. return 1;
  3760. }
  3761. }
  3762. }
  3763. static int equal(float *a, float *b)
  3764. {
  3765. return (a[0] == b[0] && a[1] == b[1]);
  3766. }
  3767. static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex *verts)
  3768. {
  3769. int i;
  3770. float orig[2], ray[2] = { 1, 0 };
  3771. float y_frac;
  3772. int winding = 0;
  3773. orig[0] = x;
  3774. orig[1] = y;
  3775. // make sure y never passes through a vertex of the shape
  3776. y_frac = (float) STBTT_fmod(y, 1.0f);
  3777. if (y_frac < 0.01f)
  3778. y += 0.01f;
  3779. else if (y_frac > 0.99f)
  3780. y -= 0.01f;
  3781. orig[1] = y;
  3782. // test a ray from (-infinity,y) to (x,y)
  3783. for (i=0; i < nverts; ++i) {
  3784. if (verts[i].type == STBTT_vline) {
  3785. int x0 = (int) verts[i-1].x, y0 = (int) verts[i-1].y;
  3786. int x1 = (int) verts[i ].x, y1 = (int) verts[i ].y;
  3787. if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) {
  3788. float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0;
  3789. if (x_inter < x)
  3790. winding += (y0 < y1) ? 1 : -1;
  3791. }
  3792. }
  3793. if (verts[i].type == STBTT_vcurve) {
  3794. int x0 = (int) verts[i-1].x , y0 = (int) verts[i-1].y ;
  3795. int x1 = (int) verts[i ].cx, y1 = (int) verts[i ].cy;
  3796. int x2 = (int) verts[i ].x , y2 = (int) verts[i ].y ;
  3797. int ax = STBTT_min(x0,STBTT_min(x1,x2)), ay = STBTT_min(y0,STBTT_min(y1,y2));
  3798. int by = STBTT_max(y0,STBTT_max(y1,y2));
  3799. if (y > ay && y < by && x > ax) {
  3800. float q0[2],q1[2],q2[2];
  3801. float hits[2][2];
  3802. q0[0] = (float)x0;
  3803. q0[1] = (float)y0;
  3804. q1[0] = (float)x1;
  3805. q1[1] = (float)y1;
  3806. q2[0] = (float)x2;
  3807. q2[1] = (float)y2;
  3808. if (equal(q0,q1) || equal(q1,q2)) {
  3809. x0 = (int)verts[i-1].x;
  3810. y0 = (int)verts[i-1].y;
  3811. x1 = (int)verts[i ].x;
  3812. y1 = (int)verts[i ].y;
  3813. if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) {
  3814. float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0;
  3815. if (x_inter < x)
  3816. winding += (y0 < y1) ? 1 : -1;
  3817. }
  3818. } else {
  3819. int num_hits = stbtt__ray_intersect_bezier(orig, ray, q0, q1, q2, hits);
  3820. if (num_hits >= 1)
  3821. if (hits[0][0] < 0)
  3822. winding += (hits[0][1] < 0 ? -1 : 1);
  3823. if (num_hits >= 2)
  3824. if (hits[1][0] < 0)
  3825. winding += (hits[1][1] < 0 ? -1 : 1);
  3826. }
  3827. }
  3828. }
  3829. }
  3830. return winding;
  3831. }
  3832. static float stbtt__cuberoot( float x )
  3833. {
  3834. if (x<0)
  3835. return -(float) STBTT_pow(-x,1.0f/3.0f);
  3836. else
  3837. return (float) STBTT_pow( x,1.0f/3.0f);
  3838. }
  3839. // x^3 + c*x^2 + b*x + a = 0
  3840. static int stbtt__solve_cubic(float a, float b, float c, float* r)
  3841. {
  3842. float s = -a / 3;
  3843. float p = b - a*a / 3;
  3844. float q = a * (2*a*a - 9*b) / 27 + c;
  3845. float p3 = p*p*p;
  3846. float d = q*q + 4*p3 / 27;
  3847. if (d >= 0) {
  3848. float z = (float) STBTT_sqrt(d);
  3849. float u = (-q + z) / 2;
  3850. float v = (-q - z) / 2;
  3851. u = stbtt__cuberoot(u);
  3852. v = stbtt__cuberoot(v);
  3853. r[0] = s + u + v;
  3854. return 1;
  3855. } else {
  3856. float u = (float) STBTT_sqrt(-p/3);
  3857. float v = (float) STBTT_acos(-STBTT_sqrt(-27/p3) * q / 2) / 3; // p3 must be negative, since d is negative
  3858. float m = (float) STBTT_cos(v);
  3859. float n = (float) STBTT_cos(v-3.141592/2)*1.732050808f;
  3860. r[0] = s + u * 2 * m;
  3861. r[1] = s - u * (m + n);
  3862. r[2] = s - u * (m - n);
  3863. //STBTT_assert( STBTT_fabs(((r[0]+a)*r[0]+b)*r[0]+c) < 0.05f); // these asserts may not be safe at all scales, though they're in bezier t parameter units so maybe?
  3864. //STBTT_assert( STBTT_fabs(((r[1]+a)*r[1]+b)*r[1]+c) < 0.05f);
  3865. //STBTT_assert( STBTT_fabs(((r[2]+a)*r[2]+b)*r[2]+c) < 0.05f);
  3866. return 3;
  3867. }
  3868. }
  3869. STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff)
  3870. {
  3871. float scale_x = scale, scale_y = scale;
  3872. int ix0,iy0,ix1,iy1;
  3873. int w,h;
  3874. unsigned char *data;
  3875. // if one scale is 0, use same scale for both
  3876. if (scale_x == 0) scale_x = scale_y;
  3877. if (scale_y == 0) {
  3878. if (scale_x == 0) return NULL; // if both scales are 0, return NULL
  3879. scale_y = scale_x;
  3880. }
  3881. stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f,0.0f, &ix0,&iy0,&ix1,&iy1);
  3882. // if empty, return NULL
  3883. if (ix0 == ix1 || iy0 == iy1)
  3884. return NULL;
  3885. ix0 -= padding;
  3886. iy0 -= padding;
  3887. ix1 += padding;
  3888. iy1 += padding;
  3889. w = (ix1 - ix0);
  3890. h = (iy1 - iy0);
  3891. if (width ) *width = w;
  3892. if (height) *height = h;
  3893. if (xoff ) *xoff = ix0;
  3894. if (yoff ) *yoff = iy0;
  3895. // invert for y-downwards bitmaps
  3896. scale_y = -scale_y;
  3897. {
  3898. int x,y,i,j;
  3899. float *precompute;
  3900. stbtt_vertex *verts;
  3901. int num_verts = stbtt_GetGlyphShape(info, glyph, &verts);
  3902. data = (unsigned char *) STBTT_malloc(w * h, info->userdata);
  3903. precompute = (float *) STBTT_malloc(num_verts * sizeof(float), info->userdata);
  3904. for (i=0,j=num_verts-1; i < num_verts; j=i++) {
  3905. if (verts[i].type == STBTT_vline) {
  3906. float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y;
  3907. float x1 = verts[j].x*scale_x, y1 = verts[j].y*scale_y;
  3908. float dist = (float) STBTT_sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0));
  3909. precompute[i] = (dist == 0) ? 0.0f : 1.0f / dist;
  3910. } else if (verts[i].type == STBTT_vcurve) {
  3911. float x2 = verts[j].x *scale_x, y2 = verts[j].y *scale_y;
  3912. float x1 = verts[i].cx*scale_x, y1 = verts[i].cy*scale_y;
  3913. float x0 = verts[i].x *scale_x, y0 = verts[i].y *scale_y;
  3914. float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2;
  3915. float len2 = bx*bx + by*by;
  3916. if (len2 != 0.0f)
  3917. precompute[i] = 1.0f / (bx*bx + by*by);
  3918. else
  3919. precompute[i] = 0.0f;
  3920. } else
  3921. precompute[i] = 0.0f;
  3922. }
  3923. for (y=iy0; y < iy1; ++y) {
  3924. for (x=ix0; x < ix1; ++x) {
  3925. float val;
  3926. float min_dist = 999999.0f;
  3927. float sx = (float) x + 0.5f;
  3928. float sy = (float) y + 0.5f;
  3929. float x_gspace = (sx / scale_x);
  3930. float y_gspace = (sy / scale_y);
  3931. int winding = stbtt__compute_crossings_x(x_gspace, y_gspace, num_verts, verts); // @OPTIMIZE: this could just be a rasterization, but needs to be line vs. non-tesselated curves so a new path
  3932. for (i=0; i < num_verts; ++i) {
  3933. float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y;
  3934. // check against every point here rather than inside line/curve primitives -- @TODO: wrong if multiple 'moves' in a row produce a garbage point, and given culling, probably more efficient to do within line/curve
  3935. float dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy);
  3936. if (dist2 < min_dist*min_dist)
  3937. min_dist = (float) STBTT_sqrt(dist2);
  3938. if (verts[i].type == STBTT_vline) {
  3939. float x1 = verts[i-1].x*scale_x, y1 = verts[i-1].y*scale_y;
  3940. // coarse culling against bbox
  3941. //if (sx > STBTT_min(x0,x1)-min_dist && sx < STBTT_max(x0,x1)+min_dist &&
  3942. // sy > STBTT_min(y0,y1)-min_dist && sy < STBTT_max(y0,y1)+min_dist)
  3943. float dist = (float) STBTT_fabs((x1-x0)*(y0-sy) - (y1-y0)*(x0-sx)) * precompute[i];
  3944. STBTT_assert(i != 0);
  3945. if (dist < min_dist) {
  3946. // check position along line
  3947. // x' = x0 + t*(x1-x0), y' = y0 + t*(y1-y0)
  3948. // minimize (x'-sx)*(x'-sx)+(y'-sy)*(y'-sy)
  3949. float dx = x1-x0, dy = y1-y0;
  3950. float px = x0-sx, py = y0-sy;
  3951. // minimize (px+t*dx)^2 + (py+t*dy)^2 = px*px + 2*px*dx*t + t^2*dx*dx + py*py + 2*py*dy*t + t^2*dy*dy
  3952. // derivative: 2*px*dx + 2*py*dy + (2*dx*dx+2*dy*dy)*t, set to 0 and solve
  3953. float t = -(px*dx + py*dy) / (dx*dx + dy*dy);
  3954. if (t >= 0.0f && t <= 1.0f)
  3955. min_dist = dist;
  3956. }
  3957. } else if (verts[i].type == STBTT_vcurve) {
  3958. float x2 = verts[i-1].x *scale_x, y2 = verts[i-1].y *scale_y;
  3959. float x1 = verts[i ].cx*scale_x, y1 = verts[i ].cy*scale_y;
  3960. float box_x0 = STBTT_min(STBTT_min(x0,x1),x2);
  3961. float box_y0 = STBTT_min(STBTT_min(y0,y1),y2);
  3962. float box_x1 = STBTT_max(STBTT_max(x0,x1),x2);
  3963. float box_y1 = STBTT_max(STBTT_max(y0,y1),y2);
  3964. // coarse culling against bbox to avoid computing cubic unnecessarily
  3965. if (sx > box_x0-min_dist && sx < box_x1+min_dist && sy > box_y0-min_dist && sy < box_y1+min_dist) {
  3966. int num=0;
  3967. float ax = x1-x0, ay = y1-y0;
  3968. float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2;
  3969. float mx = x0 - sx, my = y0 - sy;
  3970. float res[3],px,py,t,it;
  3971. float a_inv = precompute[i];
  3972. if (a_inv == 0.0) { // if a_inv is 0, it's 2nd degree so use quadratic formula
  3973. float a = 3*(ax*bx + ay*by);
  3974. float b = 2*(ax*ax + ay*ay) + (mx*bx+my*by);
  3975. float c = mx*ax+my*ay;
  3976. if (a == 0.0) { // if a is 0, it's linear
  3977. if (b != 0.0) {
  3978. res[num++] = -c/b;
  3979. }
  3980. } else {
  3981. float discriminant = b*b - 4*a*c;
  3982. if (discriminant < 0)
  3983. num = 0;
  3984. else {
  3985. float root = (float) STBTT_sqrt(discriminant);
  3986. res[0] = (-b - root)/(2*a);
  3987. res[1] = (-b + root)/(2*a);
  3988. num = 2; // don't bother distinguishing 1-solution case, as code below will still work
  3989. }
  3990. }
  3991. } else {
  3992. float b = 3*(ax*bx + ay*by) * a_inv; // could precompute this as it doesn't depend on sample point
  3993. float c = (2*(ax*ax + ay*ay) + (mx*bx+my*by)) * a_inv;
  3994. float d = (mx*ax+my*ay) * a_inv;
  3995. num = stbtt__solve_cubic(b, c, d, res);
  3996. }
  3997. if (num >= 1 && res[0] >= 0.0f && res[0] <= 1.0f) {
  3998. t = res[0], it = 1.0f - t;
  3999. px = it*it*x0 + 2*t*it*x1 + t*t*x2;
  4000. py = it*it*y0 + 2*t*it*y1 + t*t*y2;
  4001. dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);
  4002. if (dist2 < min_dist * min_dist)
  4003. min_dist = (float) STBTT_sqrt(dist2);
  4004. }
  4005. if (num >= 2 && res[1] >= 0.0f && res[1] <= 1.0f) {
  4006. t = res[1], it = 1.0f - t;
  4007. px = it*it*x0 + 2*t*it*x1 + t*t*x2;
  4008. py = it*it*y0 + 2*t*it*y1 + t*t*y2;
  4009. dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);
  4010. if (dist2 < min_dist * min_dist)
  4011. min_dist = (float) STBTT_sqrt(dist2);
  4012. }
  4013. if (num >= 3 && res[2] >= 0.0f && res[2] <= 1.0f) {
  4014. t = res[2], it = 1.0f - t;
  4015. px = it*it*x0 + 2*t*it*x1 + t*t*x2;
  4016. py = it*it*y0 + 2*t*it*y1 + t*t*y2;
  4017. dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);
  4018. if (dist2 < min_dist * min_dist)
  4019. min_dist = (float) STBTT_sqrt(dist2);
  4020. }
  4021. }
  4022. }
  4023. }
  4024. if (winding == 0)
  4025. min_dist = -min_dist; // if outside the shape, value is negative
  4026. val = onedge_value + pixel_dist_scale * min_dist;
  4027. if (val < 0)
  4028. val = 0;
  4029. else if (val > 255)
  4030. val = 255;
  4031. data[(y-iy0)*w+(x-ix0)] = (unsigned char) val;
  4032. }
  4033. }
  4034. STBTT_free(precompute, info->userdata);
  4035. STBTT_free(verts, info->userdata);
  4036. }
  4037. return data;
  4038. }
  4039. STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff)
  4040. {
  4041. return stbtt_GetGlyphSDF(info, scale, stbtt_FindGlyphIndex(info, codepoint), padding, onedge_value, pixel_dist_scale, width, height, xoff, yoff);
  4042. }
  4043. STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata)
  4044. {
  4045. STBTT_free(bitmap, userdata);
  4046. }
  4047. //////////////////////////////////////////////////////////////////////////////
  4048. //
  4049. // font name matching -- recommended not to use this
  4050. //
  4051. // check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string
  4052. static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 *s1, stbtt_int32 len1, stbtt_uint8 *s2, stbtt_int32 len2)
  4053. {
  4054. stbtt_int32 i=0;
  4055. // convert utf16 to utf8 and compare the results while converting
  4056. while (len2) {
  4057. stbtt_uint16 ch = s2[0]*256 + s2[1];
  4058. if (ch < 0x80) {
  4059. if (i >= len1) return -1;
  4060. if (s1[i++] != ch) return -1;
  4061. } else if (ch < 0x800) {
  4062. if (i+1 >= len1) return -1;
  4063. if (s1[i++] != 0xc0 + (ch >> 6)) return -1;
  4064. if (s1[i++] != 0x80 + (ch & 0x3f)) return -1;
  4065. } else if (ch >= 0xd800 && ch < 0xdc00) {
  4066. stbtt_uint32 c;
  4067. stbtt_uint16 ch2 = s2[2]*256 + s2[3];
  4068. if (i+3 >= len1) return -1;
  4069. c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000;
  4070. if (s1[i++] != 0xf0 + (c >> 18)) return -1;
  4071. if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1;
  4072. if (s1[i++] != 0x80 + ((c >> 6) & 0x3f)) return -1;
  4073. if (s1[i++] != 0x80 + ((c ) & 0x3f)) return -1;
  4074. s2 += 2; // plus another 2 below
  4075. len2 -= 2;
  4076. } else if (ch >= 0xdc00 && ch < 0xe000) {
  4077. return -1;
  4078. } else {
  4079. if (i+2 >= len1) return -1;
  4080. if (s1[i++] != 0xe0 + (ch >> 12)) return -1;
  4081. if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1;
  4082. if (s1[i++] != 0x80 + ((ch ) & 0x3f)) return -1;
  4083. }
  4084. s2 += 2;
  4085. len2 -= 2;
  4086. }
  4087. return i;
  4088. }
  4089. static int stbtt_CompareUTF8toUTF16_bigendian_internal(char *s1, int len1, char *s2, int len2)
  4090. {
  4091. return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8*) s1, len1, (stbtt_uint8*) s2, len2);
  4092. }
  4093. // returns results in whatever encoding you request... but note that 2-byte encodings
  4094. // will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare
  4095. STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID)
  4096. {
  4097. stbtt_int32 i,count,stringOffset;
  4098. stbtt_uint8 *fc = font->data;
  4099. stbtt_uint32 offset = font->fontstart;
  4100. stbtt_uint32 nm = stbtt__find_table(fc, offset, "name");
  4101. if (!nm) return NULL;
  4102. count = ttUSHORT(fc+nm+2);
  4103. stringOffset = nm + ttUSHORT(fc+nm+4);
  4104. for (i=0; i < count; ++i) {
  4105. stbtt_uint32 loc = nm + 6 + 12 * i;
  4106. if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2)
  4107. && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) {
  4108. *length = ttUSHORT(fc+loc+8);
  4109. return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10));
  4110. }
  4111. }
  4112. return NULL;
  4113. }
  4114. static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id)
  4115. {
  4116. stbtt_int32 i;
  4117. stbtt_int32 count = ttUSHORT(fc+nm+2);
  4118. stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4);
  4119. for (i=0; i < count; ++i) {
  4120. stbtt_uint32 loc = nm + 6 + 12 * i;
  4121. stbtt_int32 id = ttUSHORT(fc+loc+6);
  4122. if (id == target_id) {
  4123. // find the encoding
  4124. stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4);
  4125. // is this a Unicode encoding?
  4126. if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) {
  4127. stbtt_int32 slen = ttUSHORT(fc+loc+8);
  4128. stbtt_int32 off = ttUSHORT(fc+loc+10);
  4129. // check if there's a prefix match
  4130. stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen);
  4131. if (matchlen >= 0) {
  4132. // check for target_id+1 immediately following, with same encoding & language
  4133. if (i+1 < count && ttUSHORT(fc+loc+12+6) == next_id && ttUSHORT(fc+loc+12) == platform && ttUSHORT(fc+loc+12+2) == encoding && ttUSHORT(fc+loc+12+4) == language) {
  4134. slen = ttUSHORT(fc+loc+12+8);
  4135. off = ttUSHORT(fc+loc+12+10);
  4136. if (slen == 0) {
  4137. if (matchlen == nlen)
  4138. return 1;
  4139. } else if (matchlen < nlen && name[matchlen] == ' ') {
  4140. ++matchlen;
  4141. if (stbtt_CompareUTF8toUTF16_bigendian_internal((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen))
  4142. return 1;
  4143. }
  4144. } else {
  4145. // if nothing immediately following
  4146. if (matchlen == nlen)
  4147. return 1;
  4148. }
  4149. }
  4150. }
  4151. // @TODO handle other encodings
  4152. }
  4153. }
  4154. return 0;
  4155. }
  4156. static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags)
  4157. {
  4158. stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name);
  4159. stbtt_uint32 nm,hd;
  4160. if (!stbtt__isfont(fc+offset)) return 0;
  4161. // check italics/bold/underline flags in macStyle...
  4162. if (flags) {
  4163. hd = stbtt__find_table(fc, offset, "head");
  4164. if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0;
  4165. }
  4166. nm = stbtt__find_table(fc, offset, "name");
  4167. if (!nm) return 0;
  4168. if (flags) {
  4169. // if we checked the macStyle flags, then just check the family and ignore the subfamily
  4170. if (stbtt__matchpair(fc, nm, name, nlen, 16, -1)) return 1;
  4171. if (stbtt__matchpair(fc, nm, name, nlen, 1, -1)) return 1;
  4172. if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1;
  4173. } else {
  4174. if (stbtt__matchpair(fc, nm, name, nlen, 16, 17)) return 1;
  4175. if (stbtt__matchpair(fc, nm, name, nlen, 1, 2)) return 1;
  4176. if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1;
  4177. }
  4178. return 0;
  4179. }
  4180. static int stbtt_FindMatchingFont_internal(unsigned char *font_collection, char *name_utf8, stbtt_int32 flags)
  4181. {
  4182. stbtt_int32 i;
  4183. for (i=0;;++i) {
  4184. stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i);
  4185. if (off < 0) return off;
  4186. if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags))
  4187. return off;
  4188. }
  4189. }
  4190. #if defined(__GNUC__) || defined(__clang__)
  4191. #pragma GCC diagnostic push
  4192. #pragma GCC diagnostic ignored "-Wcast-qual"
  4193. #endif
  4194. STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset,
  4195. float pixel_height, unsigned char *pixels, int pw, int ph,
  4196. int first_char, int num_chars, stbtt_bakedchar *chardata)
  4197. {
  4198. return stbtt_BakeFontBitmap_internal((unsigned char *) data, offset, pixel_height, pixels, pw, ph, first_char, num_chars, chardata);
  4199. }
  4200. STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index)
  4201. {
  4202. return stbtt_GetFontOffsetForIndex_internal((unsigned char *) data, index);
  4203. }
  4204. STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data)
  4205. {
  4206. return stbtt_GetNumberOfFonts_internal((unsigned char *) data);
  4207. }
  4208. STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset)
  4209. {
  4210. return stbtt_InitFont_internal(info, (unsigned char *) data, offset);
  4211. }
  4212. STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags)
  4213. {
  4214. return stbtt_FindMatchingFont_internal((unsigned char *) fontdata, (char *) name, flags);
  4215. }
  4216. STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2)
  4217. {
  4218. return stbtt_CompareUTF8toUTF16_bigendian_internal((char *) s1, len1, (char *) s2, len2);
  4219. }
  4220. #if defined(__GNUC__) || defined(__clang__)
  4221. #pragma GCC diagnostic pop
  4222. #endif
  4223. #endif // STB_TRUETYPE_IMPLEMENTATION
  4224. // FULL VERSION HISTORY
  4225. //
  4226. // 1.19 (2018-02-11) OpenType GPOS kerning (horizontal only), STBTT_fmod
  4227. // 1.18 (2018-01-29) add missing function
  4228. // 1.17 (2017-07-23) make more arguments const; doc fix
  4229. // 1.16 (2017-07-12) SDF support
  4230. // 1.15 (2017-03-03) make more arguments const
  4231. // 1.14 (2017-01-16) num-fonts-in-TTC function
  4232. // 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts
  4233. // 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual
  4234. // 1.11 (2016-04-02) fix unused-variable warning
  4235. // 1.10 (2016-04-02) allow user-defined fabs() replacement
  4236. // fix memory leak if fontsize=0.0
  4237. // fix warning from duplicate typedef
  4238. // 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges
  4239. // 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges
  4240. // 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;
  4241. // allow PackFontRanges to pack and render in separate phases;
  4242. // fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);
  4243. // fixed an assert() bug in the new rasterizer
  4244. // replace assert() with STBTT_assert() in new rasterizer
  4245. // 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine)
  4246. // also more precise AA rasterizer, except if shapes overlap
  4247. // remove need for STBTT_sort
  4248. // 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC
  4249. // 1.04 (2015-04-15) typo in example
  4250. // 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes
  4251. // 1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++
  4252. // 1.01 (2014-12-08) fix subpixel position when oversampling to exactly match
  4253. // non-oversampled; STBTT_POINT_SIZE for packed case only
  4254. // 1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling
  4255. // 0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg)
  4256. // 0.9 (2014-08-07) support certain mac/iOS fonts without an MS platformID
  4257. // 0.8b (2014-07-07) fix a warning
  4258. // 0.8 (2014-05-25) fix a few more warnings
  4259. // 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back
  4260. // 0.6c (2012-07-24) improve documentation
  4261. // 0.6b (2012-07-20) fix a few more warnings
  4262. // 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels,
  4263. // stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty
  4264. // 0.5 (2011-12-09) bugfixes:
  4265. // subpixel glyph renderer computed wrong bounding box
  4266. // first vertex of shape can be off-curve (FreeSans)
  4267. // 0.4b (2011-12-03) fixed an error in the font baking example
  4268. // 0.4 (2011-12-01) kerning, subpixel rendering (tor)
  4269. // bugfixes for:
  4270. // codepoint-to-glyph conversion using table fmt=12
  4271. // codepoint-to-glyph conversion using table fmt=4
  4272. // stbtt_GetBakedQuad with non-square texture (Zer)
  4273. // updated Hello World! sample to use kerning and subpixel
  4274. // fixed some warnings
  4275. // 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM)
  4276. // userdata, malloc-from-userdata, non-zero fill (stb)
  4277. // 0.2 (2009-03-11) Fix unsigned/signed char warnings
  4278. // 0.1 (2009-03-09) First public release
  4279. //
  4280. /*
  4281. ------------------------------------------------------------------------------
  4282. This software is available under 2 licenses -- choose whichever you prefer.
  4283. ------------------------------------------------------------------------------
  4284. ALTERNATIVE A - MIT License
  4285. Copyright (c) 2017 Sean Barrett
  4286. Permission is hereby granted, free of charge, to any person obtaining a copy of
  4287. this software and associated documentation files (the "Software"), to deal in
  4288. the Software without restriction, including without limitation the rights to
  4289. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  4290. of the Software, and to permit persons to whom the Software is furnished to do
  4291. so, subject to the following conditions:
  4292. The above copyright notice and this permission notice shall be included in all
  4293. copies or substantial portions of the Software.
  4294. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  4295. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  4296. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  4297. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  4298. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  4299. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  4300. SOFTWARE.
  4301. ------------------------------------------------------------------------------
  4302. ALTERNATIVE B - Public Domain (www.unlicense.org)
  4303. This is free and unencumbered software released into the public domain.
  4304. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
  4305. software, either in source code form or as a compiled binary, for any purpose,
  4306. commercial or non-commercial, and by any means.
  4307. In jurisdictions that recognize copyright laws, the author or authors of this
  4308. software dedicate any and all copyright interest in the software to the public
  4309. domain. We make this dedication for the benefit of the public at large and to
  4310. the detriment of our heirs and successors. We intend this dedication to be an
  4311. overt act of relinquishment in perpetuity of all present and future rights to
  4312. this software under copyright law.
  4313. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  4314. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  4315. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  4316. AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  4317. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  4318. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  4319. ------------------------------------------------------------------------------
  4320. */