global: Migrate CONFIG_STACKBASE to CFG
[platform/kernel/u-boot.git] / drivers / video / stb_truetype.h
1 // stb_truetype.h - v1.08 - public domain
2 // authored from 2009-2015 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 //
10 //   Todo:
11 //        non-MS cmaps
12 //        crashproof on bad data
13 //        hinting? (no longer patented)
14 //        cleartype-style AA?
15 //        optimize: use simple memory allocator for intermediates
16 //        optimize: build edge-list directly from curves
17 //        optimize: rasterize directly from curves?
18 //
19 // ADDITIONAL CONTRIBUTORS
20 //
21 //   Mikko Mononen: compound shape support, more cmap formats
22 //   Tor Andersson: kerning, subpixel rendering
23 //
24 //   Bug/warning reports/fixes:
25 //       "Zer" on mollyrocket (with fix)
26 //       Cass Everitt
27 //       stoiko (Haemimont Games)
28 //       Brian Hook 
29 //       Walter van Niftrik
30 //       David Gow
31 //       David Given
32 //       Ivan-Assen Ivanov
33 //       Anthony Pesch
34 //       Johan Duparc
35 //       Hou Qiming
36 //       Fabian "ryg" Giesen
37 //       Martins Mozeiko
38 //       Cap Petschulat
39 //       Omar Cornut
40 //       github:aloucks
41 //       Peter LaValle
42 //       Sergey Popov
43 //       Giumo X. Clanjor
44 //       Higor Euripedes
45 //
46 //   Misc other:
47 //       Ryan Gordon
48 //
49 // VERSION HISTORY
50 //
51 //   1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges
52 //   1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;
53 //                     variant PackFontRanges to pack and render in separate phases;
54 //                     fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);
55 //                     fixed an assert() bug in the new rasterizer
56 //                     replace assert() with STBTT_assert() in new rasterizer
57 //   1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine)
58 //                     also more precise AA rasterizer, except if shapes overlap
59 //                     remove need for STBTT_sort
60 //   1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC
61 //   1.04 (2015-04-15) typo in example
62 //   1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes
63 //
64 //   Full history can be found at the end of this file.
65 //
66 // LICENSE
67 //
68 //   This software is in the public domain. Where that dedication is not
69 //   recognized, you are granted a perpetual, irrevocable license to copy,
70 //   distribute, and modify this file as you see fit.
71 //
72 // USAGE
73 //
74 //   Include this file in whatever places neeed to refer to it. In ONE C/C++
75 //   file, write:
76 //      #define STB_TRUETYPE_IMPLEMENTATION
77 //   before the #include of this file. This expands out the actual
78 //   implementation into that C/C++ file.
79 //
80 //   To make the implementation private to the file that generates the implementation,
81 //      #define STBTT_STATIC
82 //
83 //   Simple 3D API (don't ship this, but it's fine for tools and quick start)
84 //           stbtt_BakeFontBitmap()               -- bake a font to a bitmap for use as texture
85 //           stbtt_GetBakedQuad()                 -- compute quad to draw for a given char
86 //
87 //   Improved 3D API (more shippable):
88 //           #include "stb_rect_pack.h"           -- optional, but you really want it
89 //           stbtt_PackBegin()
90 //           stbtt_PackSetOversample()            -- for improved quality on small fonts
91 //           stbtt_PackFontRanges()               -- pack and renders
92 //           stbtt_PackEnd()
93 //           stbtt_GetPackedQuad()
94 //
95 //   "Load" a font file from a memory buffer (you have to keep the buffer loaded)
96 //           stbtt_InitFont()
97 //           stbtt_GetFontOffsetForIndex()        -- use for TTC font collections
98 //
99 //   Render a unicode codepoint to a bitmap
100 //           stbtt_GetCodepointBitmap()           -- allocates and returns a bitmap
101 //           stbtt_MakeCodepointBitmap()          -- renders into bitmap you provide
102 //           stbtt_GetCodepointBitmapBox()        -- how big the bitmap must be
103 //
104 //   Character advance/positioning
105 //           stbtt_GetCodepointHMetrics()
106 //           stbtt_GetFontVMetrics()
107 //           stbtt_GetCodepointKernAdvance()
108 //
109 //   Starting with version 1.06, the rasterizer was replaced with a new,
110 //   faster and generally-more-precise rasterizer. The new rasterizer more
111 //   accurately measures pixel coverage for anti-aliasing, except in the case
112 //   where multiple shapes overlap, in which case it overestimates the AA pixel
113 //   coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If
114 //   this turns out to be a problem, you can re-enable the old rasterizer with
115 //        #define STBTT_RASTERIZER_VERSION 1
116 //   which will incur about a 15% speed hit.
117 //
118 // ADDITIONAL DOCUMENTATION
119 //
120 //   Immediately after this block comment are a series of sample programs.
121 //
122 //   After the sample programs is the "header file" section. This section
123 //   includes documentation for each API function.
124 //
125 //   Some important concepts to understand to use this library:
126 //
127 //      Codepoint
128 //         Characters are defined by unicode codepoints, e.g. 65 is
129 //         uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is
130 //         the hiragana for "ma".
131 //
132 //      Glyph
133 //         A visual character shape (every codepoint is rendered as
134 //         some glyph)
135 //
136 //      Glyph index
137 //         A font-specific integer ID representing a glyph
138 //
139 //      Baseline
140 //         Glyph shapes are defined relative to a baseline, which is the
141 //         bottom of uppercase characters. Characters extend both above
142 //         and below the baseline.
143 //
144 //      Current Point
145 //         As you draw text to the screen, you keep track of a "current point"
146 //         which is the origin of each character. The current point's vertical
147 //         position is the baseline. Even "baked fonts" use this model.
148 //
149 //      Vertical Font Metrics
150 //         The vertical qualities of the font, used to vertically position
151 //         and space the characters. See docs for stbtt_GetFontVMetrics.
152 //
153 //      Font Size in Pixels or Points
154 //         The preferred interface for specifying font sizes in stb_truetype
155 //         is to specify how tall the font's vertical extent should be in pixels.
156 //         If that sounds good enough, skip the next paragraph.
157 //
158 //         Most font APIs instead use "points", which are a common typographic
159 //         measurement for describing font size, defined as 72 points per inch.
160 //         stb_truetype provides a point API for compatibility. However, true
161 //         "per inch" conventions don't make much sense on computer displays
162 //         since they different monitors have different number of pixels per
163 //         inch. For example, Windows traditionally uses a convention that
164 //         there are 96 pixels per inch, thus making 'inch' measurements have
165 //         nothing to do with inches, and thus effectively defining a point to
166 //         be 1.333 pixels. Additionally, the TrueType font data provides
167 //         an explicit scale factor to scale a given font's glyphs to points,
168 //         but the author has observed that this scale factor is often wrong
169 //         for non-commercial fonts, thus making fonts scaled in points
170 //         according to the TrueType spec incoherently sized in practice.
171 //
172 // ADVANCED USAGE
173 //
174 //   Quality:
175 //
176 //    - Use the functions with Subpixel at the end to allow your characters
177 //      to have subpixel positioning. Since the font is anti-aliased, not
178 //      hinted, this is very import for quality. (This is not possible with
179 //      baked fonts.)
180 //
181 //    - Kerning is now supported, and if you're supporting subpixel rendering
182 //      then kerning is worth using to give your text a polished look.
183 //
184 //   Performance:
185 //
186 //    - Convert Unicode codepoints to glyph indexes and operate on the glyphs;
187 //      if you don't do this, stb_truetype is forced to do the conversion on
188 //      every call.
189 //
190 //    - There are a lot of memory allocations. We should modify it to take
191 //      a temp buffer and allocate from the temp buffer (without freeing),
192 //      should help performance a lot.
193 //
194 // NOTES
195 //
196 //   The system uses the raw data found in the .ttf file without changing it
197 //   and without building auxiliary data structures. This is a bit inefficient
198 //   on little-endian systems (the data is big-endian), but assuming you're
199 //   caching the bitmaps or glyph shapes this shouldn't be a big deal.
200 //
201 //   It appears to be very hard to programmatically determine what font a
202 //   given file is in a general way. I provide an API for this, but I don't
203 //   recommend it.
204 //
205 //
206 // SOURCE STATISTICS (based on v0.6c, 2050 LOC)
207 //
208 //   Documentation & header file        520 LOC  \___ 660 LOC documentation
209 //   Sample code                        140 LOC  /
210 //   Truetype parsing                   620 LOC  ---- 620 LOC TrueType
211 //   Software rasterization             240 LOC  \                           .
212 //   Curve tesselation                  120 LOC   \__ 550 LOC Bitmap creation
213 //   Bitmap management                  100 LOC   /
214 //   Baked bitmap interface              70 LOC  /
215 //   Font name matching & access        150 LOC  ---- 150 
216 //   C runtime library abstraction       60 LOC  ----  60
217 //
218 //
219 // PERFORMANCE MEASUREMENTS FOR 1.06:
220 //
221 //                      32-bit     64-bit
222 //   Previous release:  8.83 s     7.68 s
223 //   Pool allocations:  7.72 s     6.34 s
224 //   Inline sort     :  6.54 s     5.65 s
225 //   New rasterizer  :  5.63 s     5.00 s
226
227 //////////////////////////////////////////////////////////////////////////////
228 //////////////////////////////////////////////////////////////////////////////
229 ////
230 ////  SAMPLE PROGRAMS
231 ////
232 //
233 //  Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless
234 //
235 #if 0
236 #define STB_TRUETYPE_IMPLEMENTATION  // force following include to generate implementation
237 #include "stb_truetype.h"
238
239 unsigned char ttf_buffer[1<<20];
240 unsigned char temp_bitmap[512*512];
241
242 stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs
243 GLuint ftex;
244
245 void my_stbtt_initfont(void)
246 {
247    fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb"));
248    stbtt_BakeFontBitmap(ttf_buffer,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits!
249    // can free ttf_buffer at this point
250    glGenTextures(1, &ftex);
251    glBindTexture(GL_TEXTURE_2D, ftex);
252    glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap);
253    // can free temp_bitmap at this point
254    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
255 }
256
257 void my_stbtt_print(float x, float y, char *text)
258 {
259    // assume orthographic projection with units = screen pixels, origin at top left
260    glEnable(GL_TEXTURE_2D);
261    glBindTexture(GL_TEXTURE_2D, ftex);
262    glBegin(GL_QUADS);
263    while (*text) {
264       if (*text >= 32 && *text < 128) {
265          stbtt_aligned_quad q;
266          stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9
267          glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y0);
268          glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y0);
269          glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y1);
270          glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y1);
271       }
272       ++text;
273    }
274    glEnd();
275 }
276 #endif
277 //
278 //
279 //////////////////////////////////////////////////////////////////////////////
280 //
281 // Complete program (this compiles): get a single bitmap, print as ASCII art
282 //
283 #if 0
284 #include <stdio.h>
285 #define STB_TRUETYPE_IMPLEMENTATION  // force following include to generate implementation
286 #include "stb_truetype.h"
287
288 char ttf_buffer[1<<25];
289
290 int main(int argc, char **argv)
291 {
292    stbtt_fontinfo font;
293    unsigned char *bitmap;
294    int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20);
295
296    fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb"));
297
298    stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0));
299    bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0);
300
301    for (j=0; j < h; ++j) {
302       for (i=0; i < w; ++i)
303          putchar(" .:ioVM@"[bitmap[j*w+i]>>5]);
304       putchar('\n');
305    }
306    return 0;
307 }
308 #endif 
309 //
310 // Output:
311 //
312 //     .ii.
313 //    @@@@@@.
314 //   V@Mio@@o
315 //   :i.  V@V
316 //     :oM@@M
317 //   :@@@MM@M
318 //   @@o  o@M
319 //  :@@.  M@M
320 //   @@@o@@@@
321 //   :M@@V:@@.
322 //  
323 //////////////////////////////////////////////////////////////////////////////
324 // 
325 // Complete program: print "Hello World!" banner, with bugs
326 //
327 #if 0
328 char buffer[24<<20];
329 unsigned char screen[20][79];
330
331 int main(int arg, char **argv)
332 {
333    stbtt_fontinfo font;
334    int i,j,ascent,baseline,ch=0;
335    float scale, xpos=2; // leave a little padding in case the character extends left
336    char *text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness
337
338    fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb"));
339    stbtt_InitFont(&font, buffer, 0);
340
341    scale = stbtt_ScaleForPixelHeight(&font, 15);
342    stbtt_GetFontVMetrics(&font, &ascent,0,0);
343    baseline = (int) (ascent*scale);
344
345    while (text[ch]) {
346       int advance,lsb,x0,y0,x1,y1;
347       float x_shift = xpos - (float) floor(xpos);
348       stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb);
349       stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1);
350       stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]);
351       // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong
352       // because this API is really for baking character bitmaps into textures. if you want to render
353       // a sequence of characters, you really need to render each bitmap to a temp buffer, then
354       // "alpha blend" that into the working buffer
355       xpos += (advance * scale);
356       if (text[ch+1])
357          xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]);
358       ++ch;
359    }
360
361    for (j=0; j < 20; ++j) {
362       for (i=0; i < 78; ++i)
363          putchar(" .:ioVM@"[screen[j][i]>>5]);
364       putchar('\n');
365    }
366
367    return 0;
368 }
369 #endif
370
371
372 //////////////////////////////////////////////////////////////////////////////
373 //////////////////////////////////////////////////////////////////////////////
374 ////
375 ////   INTEGRATION WITH YOUR CODEBASE
376 ////
377 ////   The following sections allow you to supply alternate definitions
378 ////   of C library functions used by stb_truetype.
379
380 #ifdef STB_TRUETYPE_IMPLEMENTATION
381    // #define your own (u)stbtt_int8/16/32 before including to override this
382    #ifndef stbtt_uint8
383    typedef unsigned char   stbtt_uint8;
384    typedef signed   char   stbtt_int8;
385    typedef unsigned short  stbtt_uint16;
386    typedef signed   short  stbtt_int16;
387    typedef unsigned int    stbtt_uint32;
388    typedef signed   int    stbtt_int32;
389    #endif
390
391    typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1];
392    typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1];
393
394    // #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h
395    #ifndef STBTT_ifloor
396    #include <math.h>
397    #define STBTT_ifloor(x)   ((int) floor(x))
398    #define STBTT_iceil(x)    ((int) ceil(x))
399    #endif
400
401    #ifndef STBTT_sqrt
402    #include <math.h>
403    #define STBTT_sqrt(x)      sqrt(x)
404    #endif
405
406    #ifndef STBTT_fabs
407    #include <math.h>
408    #define STBTT_fabs(x)      fabs(x)
409    #endif
410
411    // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h
412    #ifndef STBTT_malloc
413    #include <stdlib.h>
414    #define STBTT_malloc(x,u)  ((void)(u),malloc(x))
415    #define STBTT_free(x,u)    ((void)(u),free(x))
416    #endif
417
418    #ifndef STBTT_assert
419    #include <assert.h>
420    #define STBTT_assert(x)    assert(x)
421    #endif
422
423    #ifndef STBTT_strlen
424    #include <string.h>
425    #define STBTT_strlen(x)    strlen(x)
426    #endif
427
428    #ifndef STBTT_memcpy
429    #include <memory.h>
430    #define STBTT_memcpy       memcpy
431    #define STBTT_memset       memset
432    #endif
433 #endif
434
435 ///////////////////////////////////////////////////////////////////////////////
436 ///////////////////////////////////////////////////////////////////////////////
437 ////
438 ////   INTERFACE
439 ////
440 ////
441
442 #ifndef __STB_INCLUDE_STB_TRUETYPE_H__
443 #define __STB_INCLUDE_STB_TRUETYPE_H__
444
445 #ifdef STBTT_STATIC
446 #define STBTT_DEF static
447 #else
448 #define STBTT_DEF extern
449 #endif
450
451 #ifdef __cplusplus
452 extern "C" {
453 #endif
454
455 //////////////////////////////////////////////////////////////////////////////
456 //
457 // TEXTURE BAKING API
458 //
459 // If you use this API, you only have to call two functions ever.
460 //
461
462 typedef struct
463 {
464    unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap
465    float xoff,yoff,xadvance;
466 } stbtt_bakedchar;
467
468 STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset,  // font location (use offset=0 for plain .ttf)
469                                 float pixel_height,                     // height of font in pixels
470                                 unsigned char *pixels, int pw, int ph,  // bitmap to be filled in
471                                 int first_char, int num_chars,          // characters to bake
472                                 stbtt_bakedchar *chardata);             // you allocate this, it's num_chars long
473 // if return is positive, the first unused row of the bitmap
474 // if return is negative, returns the negative of the number of characters that fit
475 // if return is 0, no characters fit and no rows were used
476 // This uses a very crappy packing.
477
478 typedef struct
479 {
480    float x0,y0,s0,t0; // top-left
481    float x1,y1,s1,t1; // bottom-right
482 } stbtt_aligned_quad;
483
484 STBTT_DEF void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph,  // same data as above
485                                int char_index,             // character to display
486                                float *xpos, float *ypos,   // pointers to current position in screen pixel space
487                                stbtt_aligned_quad *q,      // output: quad to draw
488                                int opengl_fillrule);       // true if opengl fill rule; false if DX9 or earlier
489 // Call GetBakedQuad with char_index = 'character - first_char', and it
490 // creates the quad you need to draw and advances the current position.
491 //
492 // The coordinate system used assumes y increases downwards.
493 //
494 // Characters will extend both above and below the current position;
495 // see discussion of "BASELINE" above.
496 //
497 // It's inefficient; you might want to c&p it and optimize it.
498
499
500 //////////////////////////////////////////////////////////////////////////////
501 //
502 // NEW TEXTURE BAKING API
503 //
504 // This provides options for packing multiple fonts into one atlas, not
505 // perfectly but better than nothing.
506
507 typedef struct
508 {
509    unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap
510    float xoff,yoff,xadvance;
511    float xoff2,yoff2;
512 } stbtt_packedchar;
513
514 typedef struct stbtt_pack_context stbtt_pack_context;
515 typedef struct stbtt_fontinfo stbtt_fontinfo;
516 #ifndef STB_RECT_PACK_VERSION
517 typedef struct stbrp_rect stbrp_rect;
518 #endif
519
520 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);
521 // Initializes a packing context stored in the passed-in stbtt_pack_context.
522 // Future calls using this context will pack characters into the bitmap passed
523 // in here: a 1-channel bitmap that is weight x height. stride_in_bytes is
524 // the distance from one row to the next (or 0 to mean they are packed tightly
525 // together). "padding" is the amount of padding to leave between each
526 // character (normally you want '1' for bitmaps you'll use as textures with
527 // bilinear filtering).
528 //
529 // Returns 0 on failure, 1 on success.
530
531 STBTT_DEF void stbtt_PackEnd  (stbtt_pack_context *spc);
532 // Cleans up the packing context and frees all memory.
533
534 #define STBTT_POINT_SIZE(x)   (-(x))
535
536 STBTT_DEF int  stbtt_PackFontRange(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, float font_size,
537                                 int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range);
538 // Creates character bitmaps from the font_index'th font found in fontdata (use
539 // font_index=0 if you don't know what that is). It creates num_chars_in_range
540 // bitmaps for characters with unicode values starting at first_unicode_char_in_range
541 // and increasing. Data for how to render them is stored in chardata_for_range;
542 // pass these to stbtt_GetPackedQuad to get back renderable quads.
543 //
544 // font_size is the full height of the character from ascender to descender,
545 // as computed by stbtt_ScaleForPixelHeight. To use a point size as computed
546 // by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE()
547 // and pass that result as 'font_size':
548 //       ...,                  20 , ... // font max minus min y is 20 pixels tall
549 //       ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall
550
551 typedef struct
552 {
553    float font_size;
554    int first_unicode_codepoint_in_range;  // if non-zero, then the chars are continuous, and this is the first codepoint
555    int *array_of_unicode_codepoints;       // if non-zero, then this is an array of unicode codepoints
556    int num_chars;
557    stbtt_packedchar *chardata_for_range; // output
558    unsigned char h_oversample, v_oversample; // don't set these, they're used internally
559 } stbtt_pack_range;
560
561 STBTT_DEF int  stbtt_PackFontRanges(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges);
562 // Creates character bitmaps from multiple ranges of characters stored in
563 // ranges. This will usually create a better-packed bitmap than multiple
564 // calls to stbtt_PackFontRange. Note that you can call this multiple
565 // times within a single PackBegin/PackEnd.
566
567 STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample);
568 // Oversampling a font increases the quality by allowing higher-quality subpixel
569 // positioning, and is especially valuable at smaller text sizes.
570 //
571 // This function sets the amount of oversampling for all following calls to
572 // stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given
573 // pack context. The default (no oversampling) is achieved by h_oversample=1
574 // and v_oversample=1. The total number of pixels required is
575 // h_oversample*v_oversample larger than the default; for example, 2x2
576 // oversampling requires 4x the storage of 1x1. For best results, render
577 // oversampled textures with bilinear filtering. Look at the readme in
578 // stb/tests/oversample for information about oversampled fonts
579 //
580 // To use with PackFontRangesGather etc., you must set it before calls
581 // call to PackFontRangesGatherRects.
582
583 STBTT_DEF void stbtt_GetPackedQuad(stbtt_packedchar *chardata, int pw, int ph,  // same data as above
584                                int char_index,             // character to display
585                                float *xpos, float *ypos,   // pointers to current position in screen pixel space
586                                stbtt_aligned_quad *q,      // output: quad to draw
587                                int align_to_integer);
588
589 STBTT_DEF int  stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects);
590 STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects);
591 STBTT_DEF int  stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects);
592 // Calling these functions in sequence is roughly equivalent to calling
593 // stbtt_PackFontRanges(). If you more control over the packing of multiple
594 // fonts, or if you want to pack custom data into a font texture, take a look
595 // at the source to of stbtt_PackFontRanges() and create a custom version 
596 // using these functions, e.g. call GatherRects multiple times,
597 // building up a single array of rects, then call PackRects once,
598 // then call RenderIntoRects repeatedly. This may result in a
599 // better packing than calling PackFontRanges multiple times
600 // (or it may not).
601
602 // this is an opaque structure that you shouldn't mess with which holds
603 // all the context needed from PackBegin to PackEnd.
604 struct stbtt_pack_context {
605    void *user_allocator_context;
606    void *pack_info;
607    int   width;
608    int   height;
609    int   stride_in_bytes;
610    int   padding;
611    unsigned int   h_oversample, v_oversample;
612    unsigned char *pixels;
613    void  *nodes;
614 };
615
616 //////////////////////////////////////////////////////////////////////////////
617 //
618 // FONT LOADING
619 //
620 //
621
622 STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index);
623 // Each .ttf/.ttc file may have more than one font. Each font has a sequential
624 // index number starting from 0. Call this function to get the font offset for
625 // a given index; it returns -1 if the index is out of range. A regular .ttf
626 // file will only define one font and it always be at offset 0, so it will
627 // return '0' for index 0, and -1 for all other indices. You can just skip
628 // this step if you know it's that kind of font.
629
630
631 // The following structure is defined publically so you can declare one on
632 // the stack or as a global or etc, but you should treat it as opaque.
633 typedef struct stbtt_fontinfo
634 {
635    void           * userdata;
636    unsigned char  * data;              // pointer to .ttf file
637    int              fontstart;         // offset of start of font
638
639    int numGlyphs;                     // number of glyphs, needed for range checking
640
641    int loca,head,glyf,hhea,hmtx,kern; // table locations as offset from start of .ttf
642    int index_map;                     // a cmap mapping for our chosen character encoding
643    int indexToLocFormat;              // format needed to map from glyph index to glyph
644 } stbtt_fontinfo;
645
646 STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset);
647 // Given an offset into the file that defines a font, this function builds
648 // the necessary cached info for the rest of the system. You must allocate
649 // the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't
650 // need to do anything special to free it, because the contents are pure
651 // value data with no additional data structures. Returns 0 on failure.
652
653
654 //////////////////////////////////////////////////////////////////////////////
655 //
656 // CHARACTER TO GLYPH-INDEX CONVERSIOn
657
658 STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint);
659 // If you're going to perform multiple operations on the same character
660 // and you want a speed-up, call this function with the character you're
661 // going to process, then use glyph-based functions instead of the
662 // codepoint-based functions.
663
664
665 //////////////////////////////////////////////////////////////////////////////
666 //
667 // CHARACTER PROPERTIES
668 //
669
670 STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels);
671 // computes a scale factor to produce a font whose "height" is 'pixels' tall.
672 // Height is measured as the distance from the highest ascender to the lowest
673 // descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics
674 // and computing:
675 //       scale = pixels / (ascent - descent)
676 // so if you prefer to measure height by the ascent only, use a similar calculation.
677
678 STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels);
679 // computes a scale factor to produce a font whose EM size is mapped to
680 // 'pixels' tall. This is probably what traditional APIs compute, but
681 // I'm not positive.
682
683 STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap);
684 // ascent is the coordinate above the baseline the font extends; descent
685 // is the coordinate below the baseline the font extends (i.e. it is typically negative)
686 // lineGap is the spacing between one row's descent and the next row's ascent...
687 // so you should advance the vertical position by "*ascent - *descent + *lineGap"
688 //   these are expressed in unscaled coordinates, so you must multiply by
689 //   the scale factor for a given size
690
691 STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1);
692 // the bounding box around all possible characters
693
694 STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing);
695 // leftSideBearing is the offset from the current horizontal position to the left edge of the character
696 // advanceWidth is the offset from the current horizontal position to the next horizontal position
697 //   these are expressed in unscaled coordinates
698
699 STBTT_DEF int  stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2);
700 // an additional amount to add to the 'advance' value between ch1 and ch2
701
702 STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1);
703 // Gets the bounding box of the visible part of the glyph, in unscaled coordinates
704
705 STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing);
706 STBTT_DEF int  stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2);
707 STBTT_DEF int  stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);
708 // as above, but takes one or more glyph indices for greater efficiency
709
710
711 //////////////////////////////////////////////////////////////////////////////
712 //
713 // GLYPH SHAPES (you probably don't need these, but they have to go before
714 // the bitmaps for C declaration-order reasons)
715 //
716
717 #ifndef STBTT_vmove // you can predefine these to use different values (but why?)
718    enum {
719       STBTT_vmove=1,
720       STBTT_vline,
721       STBTT_vcurve
722    };
723 #endif
724
725 #ifndef stbtt_vertex // you can predefine this to use different values
726                    // (we share this with other code at RAD)
727    #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file
728    typedef struct
729    {
730       stbtt_vertex_type x,y,cx,cy;
731       unsigned char type,padding;
732    } stbtt_vertex;
733 #endif
734
735 STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index);
736 // returns non-zero if nothing is drawn for this glyph
737
738 STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices);
739 STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices);
740 // returns # of vertices and fills *vertices with the pointer to them
741 //   these are expressed in "unscaled" coordinates
742 //
743 // The shape is a series of countours. Each one starts with
744 // a STBTT_moveto, then consists of a series of mixed
745 // STBTT_lineto and STBTT_curveto segments. A lineto
746 // draws a line from previous endpoint to its x,y; a curveto
747 // draws a quadratic bezier from previous endpoint to
748 // its x,y, using cx,cy as the bezier control point.
749
750 STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices);
751 // frees the data allocated above
752
753 //////////////////////////////////////////////////////////////////////////////
754 //
755 // BITMAP RENDERING
756 //
757
758 STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata);
759 // frees the bitmap allocated below
760
761 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);
762 // allocates a large-enough single-channel 8bpp bitmap and renders the
763 // specified character/glyph at the specified scale into it, with
764 // antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque).
765 // *width & *height are filled out with the width & height of the bitmap,
766 // which is stored left-to-right, top-to-bottom.
767 //
768 // xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap
769
770 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);
771 // the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel
772 // shift for the character
773
774 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);
775 // the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap
776 // in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap
777 // is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the
778 // width and height and positioning info for it first.
779
780 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);
781 // same as stbtt_MakeCodepointBitmap, but you can specify a subpixel
782 // shift for the character
783
784 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);
785 // get the bbox of the bitmap centered around the glyph origin; so the
786 // bitmap width is ix1-ix0, height is iy1-iy0, and location to place
787 // the bitmap top left is (leftSideBearing*scale,iy0).
788 // (Note that the bitmap uses y-increases-down, but the shape uses
789 // y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.)
790
791 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);
792 // same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel
793 // shift for the character
794
795 // the following functions are equivalent to the above functions, but operate
796 // on glyph indices instead of Unicode codepoints (for efficiency)
797 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);
798 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);
799 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);
800 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);
801 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);
802 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);
803
804
805 // @TODO: don't expose this structure
806 typedef struct
807 {
808    int w,h,stride;
809    unsigned char *pixels;
810 } stbtt__bitmap;
811
812 // rasterize a shape with quadratic beziers into a bitmap
813 STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result,        // 1-channel bitmap to draw into
814                                float flatness_in_pixels,     // allowable error of curve in pixels
815                                stbtt_vertex *vertices,       // array of vertices defining shape
816                                int num_verts,                // number of vertices in above array
817                                float scale_x, float scale_y, // scale applied to input vertices
818                                float shift_x, float shift_y, // translation applied to input vertices
819                                int x_off, int y_off,         // another translation applied to input
820                                int invert,                   // if non-zero, vertically flip shape
821                                void *userdata);              // context for to STBTT_MALLOC
822
823 //////////////////////////////////////////////////////////////////////////////
824 //
825 // Finding the right font...
826 //
827 // You should really just solve this offline, keep your own tables
828 // of what font is what, and don't try to get it out of the .ttf file.
829 // That's because getting it out of the .ttf file is really hard, because
830 // the names in the file can appear in many possible encodings, in many
831 // possible languages, and e.g. if you need a case-insensitive comparison,
832 // the details of that depend on the encoding & language in a complex way
833 // (actually underspecified in truetype, but also gigantic).
834 //
835 // But you can use the provided functions in two possible ways:
836 //     stbtt_FindMatchingFont() will use *case-sensitive* comparisons on
837 //             unicode-encoded names to try to find the font you want;
838 //             you can run this before calling stbtt_InitFont()
839 //
840 //     stbtt_GetFontNameString() lets you get any of the various strings
841 //             from the file yourself and do your own comparisons on them.
842 //             You have to have called stbtt_InitFont() first.
843
844
845 STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags);
846 // returns the offset (not index) of the font that matches, or -1 if none
847 //   if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold".
848 //   if you use any other flag, use a font name like "Arial"; this checks
849 //     the 'macStyle' header field; i don't know if fonts set this consistently
850 #define STBTT_MACSTYLE_DONTCARE     0
851 #define STBTT_MACSTYLE_BOLD         1
852 #define STBTT_MACSTYLE_ITALIC       2
853 #define STBTT_MACSTYLE_UNDERSCORE   4
854 #define STBTT_MACSTYLE_NONE         8   // <= not same as 0, this makes us check the bitfield is 0
855
856 STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2);
857 // returns 1/0 whether the first string interpreted as utf8 is identical to
858 // the second string interpreted as big-endian utf16... useful for strings from next func
859
860 STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID);
861 // returns the string (which may be big-endian double byte, e.g. for unicode)
862 // and puts the length in bytes in *length.
863 //
864 // some of the values for the IDs are below; for more see the truetype spec:
865 //     http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html
866 //     http://www.microsoft.com/typography/otspec/name.htm
867
868 enum { // platformID
869    STBTT_PLATFORM_ID_UNICODE   =0,
870    STBTT_PLATFORM_ID_MAC       =1,
871    STBTT_PLATFORM_ID_ISO       =2,
872    STBTT_PLATFORM_ID_MICROSOFT =3
873 };
874
875 enum { // encodingID for STBTT_PLATFORM_ID_UNICODE
876    STBTT_UNICODE_EID_UNICODE_1_0    =0,
877    STBTT_UNICODE_EID_UNICODE_1_1    =1,
878    STBTT_UNICODE_EID_ISO_10646      =2,
879    STBTT_UNICODE_EID_UNICODE_2_0_BMP=3,
880    STBTT_UNICODE_EID_UNICODE_2_0_FULL=4
881 };
882
883 enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT
884    STBTT_MS_EID_SYMBOL        =0,
885    STBTT_MS_EID_UNICODE_BMP   =1,
886    STBTT_MS_EID_SHIFTJIS      =2,
887    STBTT_MS_EID_UNICODE_FULL  =10
888 };
889
890 enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes
891    STBTT_MAC_EID_ROMAN        =0,   STBTT_MAC_EID_ARABIC       =4,
892    STBTT_MAC_EID_JAPANESE     =1,   STBTT_MAC_EID_HEBREW       =5,
893    STBTT_MAC_EID_CHINESE_TRAD =2,   STBTT_MAC_EID_GREEK        =6,
894    STBTT_MAC_EID_KOREAN       =3,   STBTT_MAC_EID_RUSSIAN      =7
895 };
896
897 enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID...
898        // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs
899    STBTT_MS_LANG_ENGLISH     =0x0409,   STBTT_MS_LANG_ITALIAN     =0x0410,
900    STBTT_MS_LANG_CHINESE     =0x0804,   STBTT_MS_LANG_JAPANESE    =0x0411,
901    STBTT_MS_LANG_DUTCH       =0x0413,   STBTT_MS_LANG_KOREAN      =0x0412,
902    STBTT_MS_LANG_FRENCH      =0x040c,   STBTT_MS_LANG_RUSSIAN     =0x0419,
903    STBTT_MS_LANG_GERMAN      =0x0407,   STBTT_MS_LANG_SPANISH     =0x0409,
904    STBTT_MS_LANG_HEBREW      =0x040d,   STBTT_MS_LANG_SWEDISH     =0x041D
905 };
906
907 enum { // languageID for STBTT_PLATFORM_ID_MAC
908    STBTT_MAC_LANG_ENGLISH      =0 ,   STBTT_MAC_LANG_JAPANESE     =11,
909    STBTT_MAC_LANG_ARABIC       =12,   STBTT_MAC_LANG_KOREAN       =23,
910    STBTT_MAC_LANG_DUTCH        =4 ,   STBTT_MAC_LANG_RUSSIAN      =32,
911    STBTT_MAC_LANG_FRENCH       =1 ,   STBTT_MAC_LANG_SPANISH      =6 ,
912    STBTT_MAC_LANG_GERMAN       =2 ,   STBTT_MAC_LANG_SWEDISH      =5 ,
913    STBTT_MAC_LANG_HEBREW       =10,   STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33,
914    STBTT_MAC_LANG_ITALIAN      =3 ,   STBTT_MAC_LANG_CHINESE_TRAD =19
915 };
916
917 #ifdef __cplusplus
918 }
919 #endif
920
921 #endif // __STB_INCLUDE_STB_TRUETYPE_H__
922
923 ///////////////////////////////////////////////////////////////////////////////
924 ///////////////////////////////////////////////////////////////////////////////
925 ////
926 ////   IMPLEMENTATION
927 ////
928 ////
929
930 #ifdef STB_TRUETYPE_IMPLEMENTATION
931
932 #ifndef STBTT_MAX_OVERSAMPLE
933 #define STBTT_MAX_OVERSAMPLE   8
934 #endif
935
936 #if STBTT_MAX_OVERSAMPLE > 255
937 #error "STBTT_MAX_OVERSAMPLE cannot be > 255"
938 #endif
939
940 typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1];
941
942 #ifndef STBTT_RASTERIZER_VERSION
943 #define STBTT_RASTERIZER_VERSION 2
944 #endif
945
946 //////////////////////////////////////////////////////////////////////////
947 //
948 // accessors to parse data from file
949 //
950
951 // on platforms that don't allow misaligned reads, if we want to allow
952 // truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE
953
954 #define ttBYTE(p)     (* (stbtt_uint8 *) (p))
955 #define ttCHAR(p)     (* (stbtt_int8 *) (p))
956 #define ttFixed(p)    ttLONG(p)
957
958 #if defined(STB_TRUETYPE_BIGENDIAN) && !defined(ALLOW_UNALIGNED_TRUETYPE)
959
960    #define ttUSHORT(p)   (* (stbtt_uint16 *) (p))
961    #define ttSHORT(p)    (* (stbtt_int16 *) (p))
962    #define ttULONG(p)    (* (stbtt_uint32 *) (p))
963    #define ttLONG(p)     (* (stbtt_int32 *) (p))
964
965 #else
966
967    static stbtt_uint16 ttUSHORT(const stbtt_uint8 *p) { return p[0]*256 + p[1]; }
968    static stbtt_int16 ttSHORT(const stbtt_uint8 *p)   { return p[0]*256 + p[1]; }
969    static stbtt_uint32 ttULONG(const stbtt_uint8 *p)  { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
970    static stbtt_int32 ttLONG(const stbtt_uint8 *p)    { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
971
972 #endif
973
974 #define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3))
975 #define stbtt_tag(p,str)           stbtt_tag4(p,str[0],str[1],str[2],str[3])
976
977 static int stbtt__isfont(const stbtt_uint8 *font)
978 {
979    // check the version number
980    if (stbtt_tag4(font, '1',0,0,0))  return 1; // TrueType 1
981    if (stbtt_tag(font, "typ1"))   return 1; // TrueType with type 1 font -- we don't support this!
982    if (stbtt_tag(font, "OTTO"))   return 1; // OpenType with CFF
983    if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0
984    return 0;
985 }
986
987 // @OPTIMIZE: binary search
988 static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag)
989 {
990    stbtt_int32 num_tables = ttUSHORT(data+fontstart+4);
991    stbtt_uint32 tabledir = fontstart + 12;
992    stbtt_int32 i;
993    for (i=0; i < num_tables; ++i) {
994       stbtt_uint32 loc = tabledir + 16*i;
995       if (stbtt_tag(data+loc+0, tag))
996          return ttULONG(data+loc+8);
997    }
998    return 0;
999 }
1000
1001 STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *font_collection, int index)
1002 {
1003    // if it's just a font, there's only one valid index
1004    if (stbtt__isfont(font_collection))
1005       return index == 0 ? 0 : -1;
1006
1007    // check if it's a TTC
1008    if (stbtt_tag(font_collection, "ttcf")) {
1009       // version 1?
1010       if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {
1011          stbtt_int32 n = ttLONG(font_collection+8);
1012          if (index >= n)
1013             return -1;
1014          return ttULONG(font_collection+12+index*4);
1015       }
1016    }
1017    return -1;
1018 }
1019
1020 STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data2, int fontstart)
1021 {
1022    stbtt_uint8 *data = (stbtt_uint8 *) data2;
1023    stbtt_uint32 cmap, t;
1024    stbtt_int32 i,numTables;
1025
1026    info->data = data;
1027    info->fontstart = fontstart;
1028
1029    cmap = stbtt__find_table(data, fontstart, "cmap");       // required
1030    info->loca = stbtt__find_table(data, fontstart, "loca"); // required
1031    info->head = stbtt__find_table(data, fontstart, "head"); // required
1032    info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required
1033    info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required
1034    info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required
1035    info->kern = stbtt__find_table(data, fontstart, "kern"); // not required
1036    if (!cmap || !info->loca || !info->head || !info->glyf || !info->hhea || !info->hmtx)
1037       return 0;
1038
1039    t = stbtt__find_table(data, fontstart, "maxp");
1040    if (t)
1041       info->numGlyphs = ttUSHORT(data+t+4);
1042    else
1043       info->numGlyphs = 0xffff;
1044
1045    // find a cmap encoding table we understand *now* to avoid searching
1046    // later. (todo: could make this installable)
1047    // the same regardless of glyph.
1048    numTables = ttUSHORT(data + cmap + 2);
1049    info->index_map = 0;
1050    for (i=0; i < numTables; ++i) {
1051       stbtt_uint32 encoding_record = cmap + 4 + 8 * i;
1052       // find an encoding we understand:
1053       switch(ttUSHORT(data+encoding_record)) {
1054          case STBTT_PLATFORM_ID_MICROSOFT:
1055             switch (ttUSHORT(data+encoding_record+2)) {
1056                case STBTT_MS_EID_UNICODE_BMP:
1057                case STBTT_MS_EID_UNICODE_FULL:
1058                   // MS/Unicode
1059                   info->index_map = cmap + ttULONG(data+encoding_record+4);
1060                   break;
1061             }
1062             break;
1063         case STBTT_PLATFORM_ID_UNICODE:
1064             // Mac/iOS has these
1065             // all the encodingIDs are unicode, so we don't bother to check it
1066             info->index_map = cmap + ttULONG(data+encoding_record+4);
1067             break;
1068       }
1069    }
1070    if (info->index_map == 0)
1071       return 0;
1072
1073    info->indexToLocFormat = ttUSHORT(data+info->head + 50);
1074    return 1;
1075 }
1076
1077 STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint)
1078 {
1079    stbtt_uint8 *data = info->data;
1080    stbtt_uint32 index_map = info->index_map;
1081
1082    stbtt_uint16 format = ttUSHORT(data + index_map + 0);
1083    if (format == 0) { // apple byte encoding
1084       stbtt_int32 bytes = ttUSHORT(data + index_map + 2);
1085       if (unicode_codepoint < bytes-6)
1086          return ttBYTE(data + index_map + 6 + unicode_codepoint);
1087       return 0;
1088    } else if (format == 6) {
1089       stbtt_uint32 first = ttUSHORT(data + index_map + 6);
1090       stbtt_uint32 count = ttUSHORT(data + index_map + 8);
1091       if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count)
1092          return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2);
1093       return 0;
1094    } else if (format == 2) {
1095       STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean
1096       return 0;
1097    } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges
1098       stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1;
1099       stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1;
1100       stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10);
1101       stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1;
1102
1103       // do a binary search of the segments
1104       stbtt_uint32 endCount = index_map + 14;
1105       stbtt_uint32 search = endCount;
1106
1107       if (unicode_codepoint > 0xffff)
1108          return 0;
1109
1110       // they lie from endCount .. endCount + segCount
1111       // but searchRange is the nearest power of two, so...
1112       if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2))
1113          search += rangeShift*2;
1114
1115       // now decrement to bias correctly to find smallest
1116       search -= 2;
1117       while (entrySelector) {
1118          stbtt_uint16 end;
1119          searchRange >>= 1;
1120          end = ttUSHORT(data + search + searchRange*2);
1121          if (unicode_codepoint > end)
1122             search += searchRange*2;
1123          --entrySelector;
1124       }
1125       search += 2;
1126
1127       {
1128          stbtt_uint16 offset, start;
1129          stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1);
1130
1131          STBTT_assert(unicode_codepoint <= ttUSHORT(data + endCount + 2*item));
1132          start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item);
1133          if (unicode_codepoint < start)
1134             return 0;
1135
1136          offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item);
1137          if (offset == 0)
1138             return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item));
1139
1140          return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item);
1141       }
1142    } else if (format == 12 || format == 13) {
1143       stbtt_uint32 ngroups = ttULONG(data+index_map+12);
1144       stbtt_int32 low,high;
1145       low = 0; high = (stbtt_int32)ngroups;
1146       // Binary search the right group.
1147       while (low < high) {
1148          stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high
1149          stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12);
1150          stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4);
1151          if ((stbtt_uint32) unicode_codepoint < start_char)
1152             high = mid;
1153          else if ((stbtt_uint32) unicode_codepoint > end_char)
1154             low = mid+1;
1155          else {
1156             stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8);
1157             if (format == 12)
1158                return start_glyph + unicode_codepoint-start_char;
1159             else // format == 13
1160                return start_glyph;
1161          }
1162       }
1163       return 0; // not found
1164    }
1165    // @TODO
1166    STBTT_assert(0);
1167    return 0;
1168 }
1169
1170 STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices)
1171 {
1172    return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices);
1173 }
1174
1175 static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy)
1176 {
1177    v->type = type;
1178    v->x = (stbtt_int16) x;
1179    v->y = (stbtt_int16) y;
1180    v->cx = (stbtt_int16) cx;
1181    v->cy = (stbtt_int16) cy;
1182 }
1183
1184 static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index)
1185 {
1186    int g1,g2;
1187
1188    if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range
1189    if (info->indexToLocFormat >= 2)    return -1; // unknown index->glyph map format
1190
1191    if (info->indexToLocFormat == 0) {
1192       g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2;
1193       g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2;
1194    } else {
1195       g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4);
1196       g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4);
1197    }
1198
1199    return g1==g2 ? -1 : g1; // if length is 0, return -1
1200 }
1201
1202 STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)
1203 {
1204    int g = stbtt__GetGlyfOffset(info, glyph_index);
1205    if (g < 0) return 0;
1206
1207    if (x0) *x0 = ttSHORT(info->data + g + 2);
1208    if (y0) *y0 = ttSHORT(info->data + g + 4);
1209    if (x1) *x1 = ttSHORT(info->data + g + 6);
1210    if (y1) *y1 = ttSHORT(info->data + g + 8);
1211    return 1;
1212 }
1213
1214 STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1)
1215 {
1216    return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1);
1217 }
1218
1219 STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index)
1220 {
1221    stbtt_int16 numberOfContours;
1222    int g = stbtt__GetGlyfOffset(info, glyph_index);
1223    if (g < 0) return 1;
1224    numberOfContours = ttSHORT(info->data + g);
1225    return numberOfContours == 0;
1226 }
1227
1228 static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off,
1229     stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy)
1230 {
1231    if (start_off) {
1232       if (was_off)
1233          stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy);
1234       stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy);
1235    } else {
1236       if (was_off)
1237          stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy);
1238       else
1239          stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0);
1240    }
1241    return num_vertices;
1242 }
1243
1244 STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
1245 {
1246    stbtt_int16 numberOfContours;
1247    stbtt_uint8 *endPtsOfContours;
1248    stbtt_uint8 *data = info->data;
1249    stbtt_vertex *vertices=0;
1250    int num_vertices=0;
1251    int g = stbtt__GetGlyfOffset(info, glyph_index);
1252
1253    *pvertices = NULL;
1254
1255    if (g < 0) return 0;
1256
1257    numberOfContours = ttSHORT(data + g);
1258
1259    if (numberOfContours > 0) {
1260       stbtt_uint8 flags=0,flagcount;
1261       stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0;
1262       stbtt_int32 x,y,cx,cy,sx,sy, scx,scy;
1263       stbtt_uint8 *points;
1264       endPtsOfContours = (data + g + 10);
1265       ins = ttUSHORT(data + g + 10 + numberOfContours * 2);
1266       points = data + g + 10 + numberOfContours * 2 + 2 + ins;
1267
1268       n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2);
1269
1270       m = n + 2*numberOfContours;  // a loose bound on how many vertices we might need
1271       vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata);
1272       if (vertices == 0)
1273          return 0;
1274
1275       next_move = 0;
1276       flagcount=0;
1277
1278       // in first pass, we load uninterpreted data into the allocated array
1279       // above, shifted to the end of the array so we won't overwrite it when
1280       // we create our final data starting from the front
1281
1282       off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated
1283
1284       // first load flags
1285
1286       for (i=0; i < n; ++i) {
1287          if (flagcount == 0) {
1288             flags = *points++;
1289             if (flags & 8)
1290                flagcount = *points++;
1291          } else
1292             --flagcount;
1293          vertices[off+i].type = flags;
1294       }
1295
1296       // now load x coordinates
1297       x=0;
1298       for (i=0; i < n; ++i) {
1299          flags = vertices[off+i].type;
1300          if (flags & 2) {
1301             stbtt_int16 dx = *points++;
1302             x += (flags & 16) ? dx : -dx; // ???
1303          } else {
1304             if (!(flags & 16)) {
1305                x = x + (stbtt_int16) (points[0]*256 + points[1]);
1306                points += 2;
1307             }
1308          }
1309          vertices[off+i].x = (stbtt_int16) x;
1310       }
1311
1312       // now load y coordinates
1313       y=0;
1314       for (i=0; i < n; ++i) {
1315          flags = vertices[off+i].type;
1316          if (flags & 4) {
1317             stbtt_int16 dy = *points++;
1318             y += (flags & 32) ? dy : -dy; // ???
1319          } else {
1320             if (!(flags & 32)) {
1321                y = y + (stbtt_int16) (points[0]*256 + points[1]);
1322                points += 2;
1323             }
1324          }
1325          vertices[off+i].y = (stbtt_int16) y;
1326       }
1327
1328       // now convert them to our format
1329       num_vertices=0;
1330       sx = sy = cx = cy = scx = scy = 0;
1331       for (i=0; i < n; ++i) {
1332          flags = vertices[off+i].type;
1333          x     = (stbtt_int16) vertices[off+i].x;
1334          y     = (stbtt_int16) vertices[off+i].y;
1335
1336          if (next_move == i) {
1337             if (i != 0)
1338                num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);
1339
1340             // now start the new one               
1341             start_off = !(flags & 1);
1342             if (start_off) {
1343                // if we start off with an off-curve point, then when we need to find a point on the curve
1344                // where we can start, and we need to save some state for when we wraparound.
1345                scx = x;
1346                scy = y;
1347                if (!(vertices[off+i+1].type & 1)) {
1348                   // next point is also a curve point, so interpolate an on-point curve
1349                   sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1;
1350                   sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1;
1351                } else {
1352                   // otherwise just use the next point as our start point
1353                   sx = (stbtt_int32) vertices[off+i+1].x;
1354                   sy = (stbtt_int32) vertices[off+i+1].y;
1355                   ++i; // we're using point i+1 as the starting point, so skip it
1356                }
1357             } else {
1358                sx = x;
1359                sy = y;
1360             }
1361             stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0);
1362             was_off = 0;
1363             next_move = 1 + ttUSHORT(endPtsOfContours+j*2);
1364             ++j;
1365          } else {
1366             if (!(flags & 1)) { // if it's a curve
1367                if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint
1368                   stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy);
1369                cx = x;
1370                cy = y;
1371                was_off = 1;
1372             } else {
1373                if (was_off)
1374                   stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy);
1375                else
1376                   stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0);
1377                was_off = 0;
1378             }
1379          }
1380       }
1381       num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);
1382    } else if (numberOfContours == -1) {
1383       // Compound shapes.
1384       int more = 1;
1385       stbtt_uint8 *comp = data + g + 10;
1386       num_vertices = 0;
1387       vertices = 0;
1388       while (more) {
1389          stbtt_uint16 flags, gidx;
1390          int comp_num_verts = 0, i;
1391          stbtt_vertex *comp_verts = 0, *tmp = 0;
1392          float mtx[6] = {1,0,0,1,0,0}, m, n;
1393          
1394          flags = ttSHORT(comp); comp+=2;
1395          gidx = ttSHORT(comp); comp+=2;
1396
1397          if (flags & 2) { // XY values
1398             if (flags & 1) { // shorts
1399                mtx[4] = ttSHORT(comp); comp+=2;
1400                mtx[5] = ttSHORT(comp); comp+=2;
1401             } else {
1402                mtx[4] = ttCHAR(comp); comp+=1;
1403                mtx[5] = ttCHAR(comp); comp+=1;
1404             }
1405          }
1406          else {
1407             // @TODO handle matching point
1408             STBTT_assert(0);
1409          }
1410          if (flags & (1<<3)) { // WE_HAVE_A_SCALE
1411             mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
1412             mtx[1] = mtx[2] = 0;
1413          } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE
1414             mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;
1415             mtx[1] = mtx[2] = 0;
1416             mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
1417          } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO
1418             mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;
1419             mtx[1] = ttSHORT(comp)/16384.0f; comp+=2;
1420             mtx[2] = ttSHORT(comp)/16384.0f; comp+=2;
1421             mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
1422          }
1423          
1424          // Find transformation scales.
1425          m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]);
1426          n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]);
1427
1428          // Get indexed glyph.
1429          comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts);
1430          if (comp_num_verts > 0) {
1431             // Transform vertices.
1432             for (i = 0; i < comp_num_verts; ++i) {
1433                stbtt_vertex* v = &comp_verts[i];
1434                stbtt_vertex_type x,y;
1435                x=v->x; y=v->y;
1436                v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));
1437                v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));
1438                x=v->cx; y=v->cy;
1439                v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));
1440                v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));
1441             }
1442             // Append vertices.
1443             tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata);
1444             if (!tmp) {
1445                if (vertices) STBTT_free(vertices, info->userdata);
1446                if (comp_verts) STBTT_free(comp_verts, info->userdata);
1447                return 0;
1448             }
1449             if (num_vertices > 0) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex));
1450             STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex));
1451             if (vertices) STBTT_free(vertices, info->userdata);
1452             vertices = tmp;
1453             STBTT_free(comp_verts, info->userdata);
1454             num_vertices += comp_num_verts;
1455          }
1456          // More components ?
1457          more = flags & (1<<5);
1458       }
1459    } else if (numberOfContours < 0) {
1460       // @TODO other compound variations?
1461       STBTT_assert(0);
1462    } else {
1463       // numberOfCounters == 0, do nothing
1464    }
1465
1466    *pvertices = vertices;
1467    return num_vertices;
1468 }
1469
1470 STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing)
1471 {
1472    stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34);
1473    if (glyph_index < numOfLongHorMetrics) {
1474       if (advanceWidth)     *advanceWidth    = ttSHORT(info->data + info->hmtx + 4*glyph_index);
1475       if (leftSideBearing)  *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2);
1476    } else {
1477       if (advanceWidth)     *advanceWidth    = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1));
1478       if (leftSideBearing)  *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics));
1479    }
1480 }
1481
1482 STBTT_DEF int  stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)
1483 {
1484    stbtt_uint8 *data = info->data + info->kern;
1485    stbtt_uint32 needle, straw;
1486    int l, r, m;
1487
1488    // we only look at the first table. it must be 'horizontal' and format 0.
1489    if (!info->kern)
1490       return 0;
1491    if (ttUSHORT(data+2) < 1) // number of tables, need at least 1
1492       return 0;
1493    if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format
1494       return 0;
1495
1496    l = 0;
1497    r = ttUSHORT(data+10) - 1;
1498    needle = glyph1 << 16 | glyph2;
1499    while (l <= r) {
1500       m = (l + r) >> 1;
1501       straw = ttULONG(data+18+(m*6)); // note: unaligned read
1502       if (needle < straw)
1503          r = m - 1;
1504       else if (needle > straw)
1505          l = m + 1;
1506       else
1507          return ttSHORT(data+22+(m*6));
1508    }
1509    return 0;
1510 }
1511
1512 STBTT_DEF int  stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2)
1513 {
1514    if (!info->kern) // if no kerning table, don't waste time looking up both codepoint->glyphs
1515       return 0;
1516    return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2));
1517 }
1518
1519 STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing)
1520 {
1521    stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing);
1522 }
1523
1524 STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap)
1525 {
1526    if (ascent ) *ascent  = ttSHORT(info->data+info->hhea + 4);
1527    if (descent) *descent = ttSHORT(info->data+info->hhea + 6);
1528    if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8);
1529 }
1530
1531 STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1)
1532 {
1533    *x0 = ttSHORT(info->data + info->head + 36);
1534    *y0 = ttSHORT(info->data + info->head + 38);
1535    *x1 = ttSHORT(info->data + info->head + 40);
1536    *y1 = ttSHORT(info->data + info->head + 42);
1537 }
1538
1539 STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height)
1540 {
1541    int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6);
1542    return (float) height / fheight;
1543 }
1544
1545 STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels)
1546 {
1547    int unitsPerEm = ttUSHORT(info->data + info->head + 18);
1548    return pixels / unitsPerEm;
1549 }
1550
1551 STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v)
1552 {
1553    STBTT_free(v, info->userdata);
1554 }
1555
1556 //////////////////////////////////////////////////////////////////////////////
1557 //
1558 // antialiasing software rasterizer
1559 //
1560
1561 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)
1562 {
1563    int x0,y0,x1,y1;
1564    if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) {
1565       // e.g. space character
1566       if (ix0) *ix0 = 0;
1567       if (iy0) *iy0 = 0;
1568       if (ix1) *ix1 = 0;
1569       if (iy1) *iy1 = 0;
1570    } else {
1571       // move to integral bboxes (treating pixels as little squares, what pixels get touched)?
1572       if (ix0) *ix0 = STBTT_ifloor( x0 * scale_x + shift_x);
1573       if (iy0) *iy0 = STBTT_ifloor(-y1 * scale_y + shift_y);
1574       if (ix1) *ix1 = STBTT_iceil ( x1 * scale_x + shift_x);
1575       if (iy1) *iy1 = STBTT_iceil (-y0 * scale_y + shift_y);
1576    }
1577 }
1578
1579 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)
1580 {
1581    stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1);
1582 }
1583
1584 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)
1585 {
1586    stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1);
1587 }
1588
1589 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)
1590 {
1591    stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1);
1592 }
1593
1594 //////////////////////////////////////////////////////////////////////////////
1595 //
1596 //  Rasterizer
1597
1598 typedef struct stbtt__hheap_chunk
1599 {
1600    struct stbtt__hheap_chunk *next;
1601 } stbtt__hheap_chunk;
1602
1603 typedef struct stbtt__hheap
1604 {
1605    struct stbtt__hheap_chunk *head;
1606    void   *first_free;
1607    int    num_remaining_in_head_chunk;
1608 } stbtt__hheap;
1609
1610 static void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata)
1611 {
1612    if (hh->first_free) {
1613       void *p = hh->first_free;
1614       hh->first_free = * (void **) p;
1615       return p;
1616    } else {
1617       if (hh->num_remaining_in_head_chunk == 0) {
1618          int count = (size < 32 ? 2000 : size < 128 ? 800 : 100);
1619          stbtt__hheap_chunk *c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata);
1620          if (c == NULL)
1621             return NULL;
1622          c->next = hh->head;
1623          hh->head = c;
1624          hh->num_remaining_in_head_chunk = count;
1625       }
1626       --hh->num_remaining_in_head_chunk;
1627       return (char *) (hh->head) + size * hh->num_remaining_in_head_chunk;
1628    }
1629 }
1630
1631 static void stbtt__hheap_free(stbtt__hheap *hh, void *p)
1632 {
1633    *(void **) p = hh->first_free;
1634    hh->first_free = p;
1635 }
1636
1637 static void stbtt__hheap_cleanup(stbtt__hheap *hh, void *userdata)
1638 {
1639    stbtt__hheap_chunk *c = hh->head;
1640    while (c) {
1641       stbtt__hheap_chunk *n = c->next;
1642       STBTT_free(c, userdata);
1643       c = n;
1644    }
1645 }
1646
1647 typedef struct stbtt__edge {
1648    float x0,y0, x1,y1;
1649    int invert;
1650 } stbtt__edge;
1651
1652
1653 typedef struct stbtt__active_edge
1654 {
1655    struct stbtt__active_edge *next;
1656    #if STBTT_RASTERIZER_VERSION==1
1657    int x,dx;
1658    float ey;
1659    int direction;
1660    #elif STBTT_RASTERIZER_VERSION==2
1661    float fx,fdx,fdy;
1662    float direction;
1663    float sy;
1664    float ey;
1665    #else
1666    #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
1667    #endif
1668 } stbtt__active_edge;
1669
1670 #if STBTT_RASTERIZER_VERSION == 1
1671 #define STBTT_FIXSHIFT   10
1672 #define STBTT_FIX        (1 << STBTT_FIXSHIFT)
1673 #define STBTT_FIXMASK    (STBTT_FIX-1)
1674
1675 static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata)
1676 {
1677    stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata);
1678    float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);
1679    if (!z) return z;
1680    
1681    // round dx down to avoid overshooting
1682    if (dxdy < 0)
1683       z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy);
1684    else
1685       z->dx = STBTT_ifloor(STBTT_FIX * dxdy);
1686
1687    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
1688    z->x -= off_x * STBTT_FIX;
1689
1690    z->ey = e->y1;
1691    z->next = 0;
1692    z->direction = e->invert ? 1 : -1;
1693    return z;
1694 }
1695 #elif STBTT_RASTERIZER_VERSION == 2
1696 static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata)
1697 {
1698    stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata);
1699    float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);
1700    //STBTT_assert(e->y0 <= start_point);
1701    if (!z) return z;
1702    z->fdx = dxdy;
1703    z->fdy = dxdy != 0.0f ? (1.0f/dxdy) : 0.0f;
1704    z->fx = e->x0 + dxdy * (start_point - e->y0);
1705    z->fx -= off_x;
1706    z->direction = e->invert ? 1.0f : -1.0f;
1707    z->sy = e->y0;
1708    z->ey = e->y1;
1709    z->next = 0;
1710    return z;
1711 }
1712 #else
1713 #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
1714 #endif
1715
1716 #if STBTT_RASTERIZER_VERSION == 1
1717 // note: this routine clips fills that extend off the edges... ideally this
1718 // wouldn't happen, but it could happen if the truetype glyph bounding boxes
1719 // are wrong, or if the user supplies a too-small bitmap
1720 static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight)
1721 {
1722    // non-zero winding fill
1723    int x0=0, w=0;
1724
1725    while (e) {
1726       if (w == 0) {
1727          // if we're currently at zero, we need to record the edge start point
1728          x0 = e->x; w += e->direction;
1729       } else {
1730          int x1 = e->x; w += e->direction;
1731          // if we went to zero, we need to draw
1732          if (w == 0) {
1733             int i = x0 >> STBTT_FIXSHIFT;
1734             int j = x1 >> STBTT_FIXSHIFT;
1735
1736             if (i < len && j >= 0) {
1737                if (i == j) {
1738                   // x0,x1 are the same pixel, so compute combined coverage
1739                   scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> STBTT_FIXSHIFT);
1740                } else {
1741                   if (i >= 0) // add antialiasing for x0
1742                      scanline[i] = scanline[i] + (stbtt_uint8) (((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT);
1743                   else
1744                      i = -1; // clip
1745
1746                   if (j < len) // add antialiasing for x1
1747                      scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT);
1748                   else
1749                      j = len; // clip
1750
1751                   for (++i; i < j; ++i) // fill pixels between x0 and x1
1752                      scanline[i] = scanline[i] + (stbtt_uint8) max_weight;
1753                }
1754             }
1755          }
1756       }
1757       
1758       e = e->next;
1759    }
1760 }
1761
1762 static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)
1763 {
1764    stbtt__hheap hh = { 0, 0, 0 };
1765    stbtt__active_edge *active = NULL;
1766    int y,j=0;
1767    int max_weight = (255 / vsubsample);  // weight per vertical scanline
1768    int s; // vertical subsample index
1769    unsigned char scanline_data[512], *scanline;
1770
1771    if (result->w > 512) {
1772       scanline = (unsigned char *) STBTT_malloc(result->w, userdata);
1773       if (!scanline)
1774          return;
1775    } else {
1776       scanline = scanline_data;
1777    }
1778
1779    y = off_y * vsubsample;
1780    e[n].y0 = (off_y + result->h) * (float) vsubsample + 1;
1781
1782    while (j < result->h) {
1783       STBTT_memset(scanline, 0, result->w);
1784       for (s=0; s < vsubsample; ++s) {
1785          // find center of pixel for this scanline
1786          float scan_y = y + 0.5f;
1787          stbtt__active_edge **step = &active;
1788
1789          // update all active edges;
1790          // remove all active edges that terminate before the center of this scanline
1791          while (*step) {
1792             stbtt__active_edge * z = *step;
1793             if (z->ey <= scan_y) {
1794                *step = z->next; // delete from list
1795                STBTT_assert(z->direction);
1796                z->direction = 0;
1797                stbtt__hheap_free(&hh, z);
1798             } else {
1799                z->x += z->dx; // advance to position for current scanline
1800                step = &((*step)->next); // advance through list
1801             }
1802          }
1803
1804          // resort the list if needed
1805          for(;;) {
1806             int changed=0;
1807             step = &active;
1808             while (*step && (*step)->next) {
1809                if ((*step)->x > (*step)->next->x) {
1810                   stbtt__active_edge *t = *step;
1811                   stbtt__active_edge *q = t->next;
1812
1813                   t->next = q->next;
1814                   q->next = t;
1815                   *step = q;
1816                   changed = 1;
1817                }
1818                step = &(*step)->next;
1819             }
1820             if (!changed) break;
1821          }
1822
1823          // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline
1824          while (e->y0 <= scan_y) {
1825             if (e->y1 > scan_y) {
1826                stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y, userdata);
1827                if (!z)
1828                   return;
1829                // find insertion point
1830                if (active == NULL)
1831                   active = z;
1832                else if (z->x < active->x) {
1833                   // insert at front
1834                   z->next = active;
1835                   active = z;
1836                } else {
1837                   // find thing to insert AFTER
1838                   stbtt__active_edge *p = active;
1839                   while (p->next && p->next->x < z->x)
1840                      p = p->next;
1841                   // at this point, p->next->x is NOT < z->x
1842                   z->next = p->next;
1843                   p->next = z;
1844                }
1845             }
1846             ++e;
1847          }
1848
1849          // now process all active edges in XOR fashion
1850          if (active)
1851             stbtt__fill_active_edges(scanline, result->w, active, max_weight);
1852
1853          ++y;
1854       }
1855       STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w);
1856       ++j;
1857    }
1858
1859    stbtt__hheap_cleanup(&hh, userdata);
1860
1861    if (scanline != scanline_data)
1862       STBTT_free(scanline, userdata);
1863 }
1864
1865 #elif STBTT_RASTERIZER_VERSION == 2
1866
1867 // the edge passed in here does not cross the vertical line at x or the vertical line at x+1
1868 // (i.e. it has already been clipped to those)
1869 static void stbtt__handle_clipped_edge(float *scanline, int x, stbtt__active_edge *e, float x0, float y0, float x1, float y1)
1870 {
1871    if (y0 == y1) return;
1872    STBTT_assert(y0 < y1);
1873    STBTT_assert(e->sy <= e->ey);
1874    if (y0 > e->ey) return;
1875    if (y1 < e->sy) return;
1876    if (y0 < e->sy) {
1877       x0 += (x1-x0) * (e->sy - y0) / (y1-y0);
1878       y0 = e->sy;
1879    }
1880    if (y1 > e->ey) {
1881       x1 += (x1-x0) * (e->ey - y1) / (y1-y0);
1882       y1 = e->ey;
1883    }
1884
1885    if (x0 == x)
1886       STBTT_assert(x1 <= x+1);
1887    else if (x0 == x+1)
1888       STBTT_assert(x1 >= x);
1889    else if (x0 <= x)
1890       STBTT_assert(x1 <= x);
1891    else if (x0 >= x+1)
1892       STBTT_assert(x1 >= x+1);
1893    else
1894       STBTT_assert(x1 >= x && x1 <= x+1);
1895
1896    if (x0 <= x && x1 <= x)
1897       scanline[x] += e->direction * (y1-y0);
1898    else if (x0 >= x+1 && x1 >= x+1)
1899       ;
1900    else {
1901       STBTT_assert(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1);
1902       scanline[x] += e->direction * (y1-y0) * (1-((x0-x)+(x1-x))/2); // coverage = 1 - average x position
1903    }
1904 }
1905
1906 static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, stbtt__active_edge *e, float y_top)
1907 {
1908    float y_bottom = y_top+1;
1909
1910    while (e) {
1911       // brute force every pixel
1912
1913       // compute intersection points with top & bottom
1914       STBTT_assert(e->ey >= y_top);
1915
1916       if (e->fdx == 0) {
1917          float x0 = e->fx;
1918          if (x0 < len) {
1919             if (x0 >= 0) {
1920                stbtt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom);
1921                stbtt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom);
1922             } else {
1923                stbtt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom);
1924             }
1925          }
1926       } else {
1927          float x0 = e->fx;
1928          float dx = e->fdx;
1929          float xb = x0 + dx;
1930          float x_top, x_bottom;
1931          float sy0,sy1;
1932          float dy = e->fdy;
1933          STBTT_assert(e->sy <= y_bottom && e->ey >= y_top);
1934
1935          // compute endpoints of line segment clipped to this scanline (if the
1936          // line segment starts on this scanline. x0 is the intersection of the
1937          // line with y_top, but that may be off the line segment.
1938          if (e->sy > y_top) {
1939             x_top = x0 + dx * (e->sy - y_top);
1940             sy0 = e->sy;
1941          } else {
1942             x_top = x0;
1943             sy0 = y_top;
1944          }
1945          if (e->ey < y_bottom) {
1946             x_bottom = x0 + dx * (e->ey - y_top);
1947             sy1 = e->ey;
1948          } else {
1949             x_bottom = xb;
1950             sy1 = y_bottom;
1951          }
1952
1953          if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) {
1954             // from here on, we don't have to range check x values
1955
1956             if ((int) x_top == (int) x_bottom) {
1957                float height;
1958                // simple case, only spans one pixel
1959                int x = (int) x_top;
1960                height = sy1 - sy0;
1961                STBTT_assert(x >= 0 && x < len);
1962                scanline[x] += e->direction * (1-((x_top - x) + (x_bottom-x))/2)  * height;
1963                scanline_fill[x] += e->direction * height; // everything right of this pixel is filled
1964             } else {
1965                int x,x1,x2;
1966                float y_crossing, step, sign, area;
1967                // covers 2+ pixels
1968                if (x_top > x_bottom) {
1969                   // flip scanline vertically; signed area is the same
1970                   float t;
1971                   sy0 = y_bottom - (sy0 - y_top);
1972                   sy1 = y_bottom - (sy1 - y_top);
1973                   t = sy0, sy0 = sy1, sy1 = t;
1974                   t = x_bottom, x_bottom = x_top, x_top = t;
1975                   dx = -dx;
1976                   dy = -dy;
1977                   t = x0, x0 = xb, xb = t;
1978                }
1979
1980                x1 = (int) x_top;
1981                x2 = (int) x_bottom;
1982                // compute intersection with y axis at x1+1
1983                y_crossing = (x1+1 - x0) * dy + y_top;
1984
1985                sign = e->direction;
1986                // area of the rectangle covered from y0..y_crossing
1987                area = sign * (y_crossing-sy0);
1988                // area of the triangle (x_top,y0), (x+1,y0), (x+1,y_crossing)
1989                scanline[x1] += area * (1-((x_top - x1)+(x1+1-x1))/2);
1990
1991                step = sign * dy;
1992                for (x = x1+1; x < x2; ++x) {
1993                   scanline[x] += area + step/2;
1994                   area += step;
1995                }
1996                y_crossing += dy * (x2 - (x1+1));
1997
1998                STBTT_assert(fabs(area) <= 1.01f);
1999
2000                scanline[x2] += area + sign * (1-(x_bottom-x2)/2) * (sy1-y_crossing);
2001
2002                scanline_fill[x2] += sign * (sy1-sy0);
2003             }
2004          } else {
2005             // if edge goes outside of box we're drawing, we require
2006             // clipping logic. since this does not match the intended use
2007             // of this library, we use a different, very slow brute
2008             // force implementation
2009             int x;
2010             for (x=0; x < len; ++x) {
2011                // cases:
2012                //
2013                // there can be up to two intersections with the pixel. any intersection
2014                // with left or right edges can be handled by splitting into two (or three)
2015                // regions. intersections with top & bottom do not necessitate case-wise logic.
2016                //
2017                // the old way of doing this found the intersections with the left & right edges,
2018                // then used some simple logic to produce up to three segments in sorted order
2019                // from top-to-bottom. however, this had a problem: if an x edge was epsilon
2020                // across the x border, then the corresponding y position might not be distinct
2021                // from the other y segment, and it might ignored as an empty segment. to avoid
2022                // that, we need to explicitly produce segments based on x positions.
2023
2024                // rename variables to clear pairs
2025                float y0 = y_top;
2026                float x1 = (float) (x);
2027                float x2 = (float) (x+1);
2028                float x3 = xb;
2029                float y3 = y_bottom;
2030                float y1,y2;
2031
2032                // x = e->x + e->dx * (y-y_top)
2033                // (y-y_top) = (x - e->x) / e->dx
2034                // y = (x - e->x) / e->dx + y_top
2035                y1 = (x - x0) / dx + y_top;
2036                y2 = (x+1 - x0) / dx + y_top;
2037
2038                if (x0 < x1 && x3 > x2) {         // three segments descending down-right
2039                   stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);
2040                   stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x2,y2);
2041                   stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);
2042                } else if (x3 < x1 && x0 > x2) {  // three segments descending down-left
2043                   stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);
2044                   stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x1,y1);
2045                   stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);
2046                } else if (x0 < x1 && x3 > x1) {  // two segments across x, down-right
2047                   stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);
2048                   stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);
2049                } else if (x3 < x1 && x0 > x1) {  // two segments across x, down-left
2050                   stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);
2051                   stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);
2052                } else if (x0 < x2 && x3 > x2) {  // two segments across x+1, down-right
2053                   stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);
2054                   stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);
2055                } else if (x3 < x2 && x0 > x2) {  // two segments across x+1, down-left
2056                   stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);
2057                   stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);
2058                } else {  // one segment
2059                   stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x3,y3);
2060                }
2061             }
2062          }
2063       }
2064       e = e->next;
2065    }
2066 }
2067
2068 // directly AA rasterize edges w/o supersampling
2069 static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)
2070 {
2071    stbtt__hheap hh = { 0, 0, 0 };
2072    stbtt__active_edge *active = NULL;
2073    int y,j=0, i;
2074    float scanline_data[129], *scanline, *scanline2;
2075
2076    if (result->w > 64) {
2077       scanline = (float *) STBTT_malloc((result->w*2+1) * sizeof(float), userdata);
2078       if (!scanline)
2079          return;
2080    } else {
2081       scanline = scanline_data;
2082    }
2083
2084    scanline2 = scanline + result->w;
2085
2086    y = off_y;
2087    e[n].y0 = (float) (off_y + result->h) + 1;
2088
2089    while (j < result->h) {
2090       // find center of pixel for this scanline
2091       float scan_y_top    = y + 0.0f;
2092       float scan_y_bottom = y + 1.0f;
2093       stbtt__active_edge **step = &active;
2094
2095       STBTT_memset(scanline , 0, result->w*sizeof(scanline[0]));
2096       STBTT_memset(scanline2, 0, (result->w+1)*sizeof(scanline[0]));
2097
2098       // update all active edges;
2099       // remove all active edges that terminate before the top of this scanline
2100       while (*step) {
2101          stbtt__active_edge * z = *step;
2102          if (z->ey <= scan_y_top) {
2103             *step = z->next; // delete from list
2104             STBTT_assert(z->direction);
2105             z->direction = 0;
2106             stbtt__hheap_free(&hh, z);
2107          } else {
2108             step = &((*step)->next); // advance through list
2109          }
2110       }
2111
2112       // insert all edges that start before the bottom of this scanline
2113       while (e->y0 <= scan_y_bottom) {
2114          if (e->y0 != e->y1) {
2115             stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata);
2116             if (!z)
2117                return;
2118             STBTT_assert(z->ey >= scan_y_top);
2119             // insert at front
2120             z->next = active;
2121             active = z;
2122          }
2123          ++e;
2124       }
2125
2126       // now process all active edges
2127       if (active)
2128          stbtt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top);
2129
2130       {
2131          float sum = 0;
2132          for (i=0; i < result->w; ++i) {
2133             float k;
2134             int m;
2135             sum += scanline2[i];
2136             k = scanline[i] + sum;
2137             k = (float) STBTT_fabs(k)*255 + 0.5f;
2138             m = (int) k;
2139             if (m > 255) m = 255;
2140             result->pixels[j*result->stride + i] = (unsigned char) m;
2141          }
2142       }
2143       // advance all the edges
2144       step = &active;
2145       while (*step) {
2146          stbtt__active_edge *z = *step;
2147          z->fx += z->fdx; // advance to position for current scanline
2148          step = &((*step)->next); // advance through list
2149       }
2150
2151       ++y;
2152       ++j;
2153    }
2154
2155    stbtt__hheap_cleanup(&hh, userdata);
2156
2157    if (scanline != scanline_data)
2158       STBTT_free(scanline, userdata);
2159 }
2160 #else
2161 #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
2162 #endif
2163
2164 #define STBTT__COMPARE(a,b)  ((a)->y0 < (b)->y0)
2165
2166 static void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n)
2167 {
2168    int i,j;
2169    for (i=1; i < n; ++i) {
2170       stbtt__edge t = p[i], *a = &t;
2171       j = i;
2172       while (j > 0) {
2173          stbtt__edge *b = &p[j-1];
2174          int c = STBTT__COMPARE(a,b);
2175          if (!c) break;
2176          p[j] = p[j-1];
2177          --j;
2178       }
2179       if (i != j)
2180          p[j] = t;
2181    }
2182 }
2183
2184 static void stbtt__sort_edges_quicksort(stbtt__edge *p, int n)
2185 {
2186    /* threshhold for transitioning to insertion sort */
2187    while (n > 12) {
2188       stbtt__edge t;
2189       int c01,c12,c,m,i,j;
2190
2191       /* compute median of three */
2192       m = n >> 1;
2193       c01 = STBTT__COMPARE(&p[0],&p[m]);
2194       c12 = STBTT__COMPARE(&p[m],&p[n-1]);
2195       /* if 0 >= mid >= end, or 0 < mid < end, then use mid */
2196       if (c01 != c12) {
2197          /* otherwise, we'll need to swap something else to middle */
2198          int z;
2199          c = STBTT__COMPARE(&p[0],&p[n-1]);
2200          /* 0>mid && mid<n:  0>n => n; 0<n => 0 */
2201          /* 0<mid && mid>n:  0>n => 0; 0<n => n */
2202          z = (c == c12) ? 0 : n-1;
2203          t = p[z];
2204          p[z] = p[m];
2205          p[m] = t;
2206       }
2207       /* now p[m] is the median-of-three */
2208       /* swap it to the beginning so it won't move around */
2209       t = p[0];
2210       p[0] = p[m];
2211       p[m] = t;
2212
2213       /* partition loop */
2214       i=1;
2215       j=n-1;
2216       for(;;) {
2217          /* handling of equality is crucial here */
2218          /* for sentinels & efficiency with duplicates */
2219          for (;;++i) {
2220             if (!STBTT__COMPARE(&p[i], &p[0])) break;
2221          }
2222          for (;;--j) {
2223             if (!STBTT__COMPARE(&p[0], &p[j])) break;
2224          }
2225          /* make sure we haven't crossed */
2226          if (i >= j) break;
2227          t = p[i];
2228          p[i] = p[j];
2229          p[j] = t;
2230
2231          ++i;
2232          --j;
2233       }
2234       /* recurse on smaller side, iterate on larger */
2235       if (j < (n-i)) {
2236          stbtt__sort_edges_quicksort(p,j);
2237          p = p+i;
2238          n = n-i;
2239       } else {
2240          stbtt__sort_edges_quicksort(p+i, n-i);
2241          n = j;
2242       }
2243    }
2244 }
2245
2246 static void stbtt__sort_edges(stbtt__edge *p, int n)
2247 {
2248    stbtt__sort_edges_quicksort(p, n);
2249    stbtt__sort_edges_ins_sort(p, n);
2250 }
2251
2252 typedef struct
2253 {
2254    float x,y;
2255 } stbtt__point;
2256
2257 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)
2258 {
2259    float y_scale_inv = invert ? -scale_y : scale_y;
2260    stbtt__edge *e;
2261    int n,i,j,k,m;
2262 #if STBTT_RASTERIZER_VERSION == 1
2263    int vsubsample = result->h < 8 ? 15 : 5;
2264 #elif STBTT_RASTERIZER_VERSION == 2
2265    int vsubsample = 1;
2266 #else
2267    #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
2268 #endif
2269    // vsubsample should divide 255 evenly; otherwise we won't reach full opacity
2270
2271    // now we have to blow out the windings into explicit edge lists
2272    n = 0;
2273    for (i=0; i < windings; ++i)
2274       n += wcount[i];
2275
2276    e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel
2277    if (e == 0) return;
2278    n = 0;
2279
2280    m=0;
2281    for (i=0; i < windings; ++i) {
2282       stbtt__point *p = pts + m;
2283       m += wcount[i];
2284       j = wcount[i]-1;
2285       for (k=0; k < wcount[i]; j=k++) {
2286          int a=k,b=j;
2287          // skip the edge if horizontal
2288          if (p[j].y == p[k].y)
2289             continue;
2290          // add edge from j to k to the list
2291          e[n].invert = 0;
2292          if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) {
2293             e[n].invert = 1;
2294             a=j,b=k;
2295          }
2296          e[n].x0 = p[a].x * scale_x + shift_x;
2297          e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample;
2298          e[n].x1 = p[b].x * scale_x + shift_x;
2299          e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample;
2300          ++n;
2301       }
2302    }
2303
2304    // now sort the edges by their highest point (should snap to integer, and then by x)
2305    //STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare);
2306    stbtt__sort_edges(e, n);
2307
2308    // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule
2309    stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata);
2310
2311    STBTT_free(e, userdata);
2312 }
2313
2314 static void stbtt__add_point(stbtt__point *points, int n, float x, float y)
2315 {
2316    if (!points) return; // during first pass, it's unallocated
2317    points[n].x = x;
2318    points[n].y = y;
2319 }
2320
2321 // tesselate until threshhold p is happy... @TODO warped to compensate for non-linear stretching
2322 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)
2323 {
2324    // midpoint
2325    float mx = (x0 + 2*x1 + x2)/4;
2326    float my = (y0 + 2*y1 + y2)/4;
2327    // versus directly drawn line
2328    float dx = (x0+x2)/2 - mx;
2329    float dy = (y0+y2)/2 - my;
2330    if (n > 16) // 65536 segments on one curve better be enough!
2331       return 1;
2332    if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA
2333       stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1);
2334       stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1);
2335    } else {
2336       stbtt__add_point(points, *num_points,x2,y2);
2337       *num_points = *num_points+1;
2338    }
2339    return 1;
2340 }
2341
2342 // returns number of contours
2343 static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata)
2344 {
2345    stbtt__point *points=0;
2346    int num_points=0;
2347
2348    float objspace_flatness_squared = objspace_flatness * objspace_flatness;
2349    int i,n=0,start=0, pass;
2350
2351    // count how many "moves" there are to get the contour count
2352    for (i=0; i < num_verts; ++i)
2353       if (vertices[i].type == STBTT_vmove)
2354          ++n;
2355
2356    *num_contours = n;
2357    if (n == 0) return 0;
2358
2359    *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata);
2360
2361    if (*contour_lengths == 0) {
2362       *num_contours = 0;
2363       return 0;
2364    }
2365
2366    // make two passes through the points so we don't need to realloc
2367    for (pass=0; pass < 2; ++pass) {
2368       float x=0,y=0;
2369       if (pass == 1) {
2370          points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata);
2371          if (points == NULL) goto error;
2372       }
2373       num_points = 0;
2374       n= -1;
2375       for (i=0; i < num_verts; ++i) {
2376          switch (vertices[i].type) {
2377             case STBTT_vmove:
2378                // start the next contour
2379                if (n >= 0)
2380                   (*contour_lengths)[n] = num_points - start;
2381                ++n;
2382                start = num_points;
2383
2384                x = vertices[i].x, y = vertices[i].y;
2385                stbtt__add_point(points, num_points++, x,y);
2386                break;
2387             case STBTT_vline:
2388                x = vertices[i].x, y = vertices[i].y;
2389                stbtt__add_point(points, num_points++, x, y);
2390                break;
2391             case STBTT_vcurve:
2392                stbtt__tesselate_curve(points, &num_points, x,y,
2393                                         vertices[i].cx, vertices[i].cy,
2394                                         vertices[i].x,  vertices[i].y,
2395                                         objspace_flatness_squared, 0);
2396                x = vertices[i].x, y = vertices[i].y;
2397                break;
2398          }
2399       }
2400       (*contour_lengths)[n] = num_points - start;
2401    }
2402
2403    return points;
2404 error:
2405    STBTT_free(points, userdata);
2406    STBTT_free(*contour_lengths, userdata);
2407    *contour_lengths = 0;
2408    *num_contours = 0;
2409    return NULL;
2410 }
2411
2412 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)
2413 {
2414    float scale = scale_x > scale_y ? scale_y : scale_x;
2415    int winding_count, *winding_lengths;
2416    stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata);
2417    if (windings) {
2418       stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata);
2419       STBTT_free(winding_lengths, userdata);
2420       STBTT_free(windings, userdata);
2421    }
2422 }
2423
2424 STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata)
2425 {
2426    STBTT_free(bitmap, userdata);
2427 }
2428
2429 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)
2430 {
2431    int ix0,iy0,ix1,iy1;
2432    stbtt__bitmap gbm;
2433    stbtt_vertex *vertices;   
2434    int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
2435
2436    if (scale_x == 0) scale_x = scale_y;
2437    if (scale_y == 0) {
2438       if (scale_x == 0) {
2439          STBTT_free(vertices, info->userdata);
2440          return NULL;
2441       }
2442       scale_y = scale_x;
2443    }
2444
2445    stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1);
2446
2447    // now we get the size
2448    gbm.w = (ix1 - ix0);
2449    gbm.h = (iy1 - iy0);
2450    gbm.pixels = NULL; // in case we error
2451
2452    if (width ) *width  = gbm.w;
2453    if (height) *height = gbm.h;
2454    if (xoff  ) *xoff   = ix0;
2455    if (yoff  ) *yoff   = iy0;
2456    
2457    if (gbm.w && gbm.h) {
2458       gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata);
2459       if (gbm.pixels) {
2460          gbm.stride = gbm.w;
2461
2462          stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata);
2463       }
2464    }
2465    STBTT_free(vertices, info->userdata);
2466    return gbm.pixels;
2467 }   
2468
2469 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)
2470 {
2471    return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff);
2472 }
2473
2474 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)
2475 {
2476    int ix0,iy0;
2477    stbtt_vertex *vertices;
2478    int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
2479    stbtt__bitmap gbm;   
2480
2481    stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0);
2482    gbm.pixels = output;
2483    gbm.w = out_w;
2484    gbm.h = out_h;
2485    gbm.stride = out_stride;
2486
2487    if (gbm.w && gbm.h)
2488       stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata);
2489
2490    STBTT_free(vertices, info->userdata);
2491 }
2492
2493 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)
2494 {
2495    stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph);
2496 }
2497
2498 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)
2499 {
2500    return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff);
2501 }   
2502
2503 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)
2504 {
2505    stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint));
2506 }
2507
2508 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)
2509 {
2510    return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff);
2511 }   
2512
2513 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)
2514 {
2515    stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint);
2516 }
2517
2518 //////////////////////////////////////////////////////////////////////////////
2519 //
2520 // bitmap baking
2521 //
2522 // This is SUPER-CRAPPY packing to keep source code small
2523
2524 STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset,  // font location (use offset=0 for plain .ttf)
2525                                 float pixel_height,                     // height of font in pixels
2526                                 unsigned char *pixels, int pw, int ph,  // bitmap to be filled in
2527                                 int first_char, int num_chars,          // characters to bake
2528                                 stbtt_bakedchar *chardata)
2529 {
2530    float scale;
2531    int x,y,bottom_y, i;
2532    stbtt_fontinfo f;
2533    if (!stbtt_InitFont(&f, data, offset))
2534       return -1;
2535    STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels
2536    x=y=1;
2537    bottom_y = 1;
2538
2539    scale = stbtt_ScaleForPixelHeight(&f, pixel_height);
2540
2541    for (i=0; i < num_chars; ++i) {
2542       int advance, lsb, x0,y0,x1,y1,gw,gh;
2543       int g = stbtt_FindGlyphIndex(&f, first_char + i);
2544       stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb);
2545       stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1);
2546       gw = x1-x0;
2547       gh = y1-y0;
2548       if (x + gw + 1 >= pw)
2549          y = bottom_y, x = 1; // advance to next row
2550       if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row
2551          return -i;
2552       STBTT_assert(x+gw < pw);
2553       STBTT_assert(y+gh < ph);
2554       stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g);
2555       chardata[i].x0 = (stbtt_int16) x;
2556       chardata[i].y0 = (stbtt_int16) y;
2557       chardata[i].x1 = (stbtt_int16) (x + gw);
2558       chardata[i].y1 = (stbtt_int16) (y + gh);
2559       chardata[i].xadvance = scale * advance;
2560       chardata[i].xoff     = (float) x0;
2561       chardata[i].yoff     = (float) y0;
2562       x = x + gw + 1;
2563       if (y+gh+1 > bottom_y)
2564          bottom_y = y+gh+1;
2565    }
2566    return bottom_y;
2567 }
2568
2569 STBTT_DEF void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule)
2570 {
2571    float d3d_bias = opengl_fillrule ? 0 : -0.5f;
2572    float ipw = 1.0f / pw, iph = 1.0f / ph;
2573    stbtt_bakedchar *b = chardata + char_index;
2574    int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f);
2575    int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f);
2576
2577    q->x0 = round_x + d3d_bias;
2578    q->y0 = round_y + d3d_bias;
2579    q->x1 = round_x + b->x1 - b->x0 + d3d_bias;
2580    q->y1 = round_y + b->y1 - b->y0 + d3d_bias;
2581
2582    q->s0 = b->x0 * ipw;
2583    q->t0 = b->y0 * iph;
2584    q->s1 = b->x1 * ipw;
2585    q->t1 = b->y1 * iph;
2586
2587    *xpos += b->xadvance;
2588 }
2589
2590 //////////////////////////////////////////////////////////////////////////////
2591 //
2592 // rectangle packing replacement routines if you don't have stb_rect_pack.h
2593 //
2594
2595 #ifndef STB_RECT_PACK_VERSION
2596 #ifdef _MSC_VER
2597 #define STBTT__NOTUSED(v)  (void)(v)
2598 #else
2599 #define STBTT__NOTUSED(v)  (void)sizeof(v)
2600 #endif
2601
2602 typedef int stbrp_coord;
2603
2604 ////////////////////////////////////////////////////////////////////////////////////
2605 //                                                                                //
2606 //                                                                                //
2607 // COMPILER WARNING ?!?!?                                                         //
2608 //                                                                                //
2609 //                                                                                //
2610 // if you get a compile warning due to these symbols being defined more than      //
2611 // once, move #include "stb_rect_pack.h" before #include "stb_truetype.h"         //
2612 //                                                                                //
2613 ////////////////////////////////////////////////////////////////////////////////////
2614
2615 typedef struct
2616 {
2617    int width,height;
2618    int x,y,bottom_y;
2619 } stbrp_context;
2620
2621 typedef struct
2622 {
2623    unsigned char x;
2624 } stbrp_node;
2625
2626 struct stbrp_rect
2627 {
2628    stbrp_coord x,y;
2629    int id,w,h,was_packed;
2630 };
2631
2632 static void stbrp_init_target(stbrp_context *con, int pw, int ph, stbrp_node *nodes, int num_nodes)
2633 {
2634    con->width  = pw;
2635    con->height = ph;
2636    con->x = 0;
2637    con->y = 0;
2638    con->bottom_y = 0;
2639    STBTT__NOTUSED(nodes);
2640    STBTT__NOTUSED(num_nodes);   
2641 }
2642
2643 static void stbrp_pack_rects(stbrp_context *con, stbrp_rect *rects, int num_rects)
2644 {
2645    int i;
2646    for (i=0; i < num_rects; ++i) {
2647       if (con->x + rects[i].w > con->width) {
2648          con->x = 0;
2649          con->y = con->bottom_y;
2650       }
2651       if (con->y + rects[i].h > con->height)
2652          break;
2653       rects[i].x = con->x;
2654       rects[i].y = con->y;
2655       rects[i].was_packed = 1;
2656       con->x += rects[i].w;
2657       if (con->y + rects[i].h > con->bottom_y)
2658          con->bottom_y = con->y + rects[i].h;
2659    }
2660    for (   ; i < num_rects; ++i)
2661       rects[i].was_packed = 0;
2662 }
2663 #endif
2664
2665 //////////////////////////////////////////////////////////////////////////////
2666 //
2667 // bitmap baking
2668 //
2669 // This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If
2670 // stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy.
2671
2672 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)
2673 {
2674    stbrp_context *context = (stbrp_context *) STBTT_malloc(sizeof(*context)            ,alloc_context);
2675    int            num_nodes = pw - padding;
2676    stbrp_node    *nodes   = (stbrp_node    *) STBTT_malloc(sizeof(*nodes  ) * num_nodes,alloc_context);
2677
2678    if (context == NULL || nodes == NULL) {
2679       if (context != NULL) STBTT_free(context, alloc_context);
2680       if (nodes   != NULL) STBTT_free(nodes  , alloc_context);
2681       return 0;
2682    }
2683
2684    spc->user_allocator_context = alloc_context;
2685    spc->width = pw;
2686    spc->height = ph;
2687    spc->pixels = pixels;
2688    spc->pack_info = context;
2689    spc->nodes = nodes;
2690    spc->padding = padding;
2691    spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw;
2692    spc->h_oversample = 1;
2693    spc->v_oversample = 1;
2694
2695    stbrp_init_target(context, pw-padding, ph-padding, nodes, num_nodes);
2696
2697    if (pixels)
2698       STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels
2699
2700    return 1;
2701 }
2702
2703 STBTT_DEF void stbtt_PackEnd  (stbtt_pack_context *spc)
2704 {
2705    STBTT_free(spc->nodes    , spc->user_allocator_context);
2706    STBTT_free(spc->pack_info, spc->user_allocator_context);
2707 }
2708
2709 STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample)
2710 {
2711    STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE);
2712    STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE);
2713    if (h_oversample <= STBTT_MAX_OVERSAMPLE)
2714       spc->h_oversample = h_oversample;
2715    if (v_oversample <= STBTT_MAX_OVERSAMPLE)
2716       spc->v_oversample = v_oversample;
2717 }
2718
2719 #define STBTT__OVER_MASK  (STBTT_MAX_OVERSAMPLE-1)
2720
2721 static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)
2722 {
2723    unsigned char buffer[STBTT_MAX_OVERSAMPLE];
2724    int safe_w = w - kernel_width;
2725    int j;
2726    for (j=0; j < h; ++j) {
2727       int i;
2728       unsigned int total;
2729       STBTT_memset(buffer, 0, kernel_width);
2730
2731       total = 0;
2732
2733       // make kernel_width a constant in common cases so compiler can optimize out the divide
2734       switch (kernel_width) {
2735          case 2:
2736             for (i=0; i <= safe_w; ++i) {
2737                total += pixels[i] - buffer[i & STBTT__OVER_MASK];
2738                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
2739                pixels[i] = (unsigned char) (total / 2);
2740             }
2741             break;
2742          case 3:
2743             for (i=0; i <= safe_w; ++i) {
2744                total += pixels[i] - buffer[i & STBTT__OVER_MASK];
2745                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
2746                pixels[i] = (unsigned char) (total / 3);
2747             }
2748             break;
2749          case 4:
2750             for (i=0; i <= safe_w; ++i) {
2751                total += pixels[i] - buffer[i & STBTT__OVER_MASK];
2752                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
2753                pixels[i] = (unsigned char) (total / 4);
2754             }
2755             break;
2756          case 5:
2757             for (i=0; i <= safe_w; ++i) {
2758                total += pixels[i] - buffer[i & STBTT__OVER_MASK];
2759                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
2760                pixels[i] = (unsigned char) (total / 5);
2761             }
2762             break;
2763          default:
2764             for (i=0; i <= safe_w; ++i) {
2765                total += pixels[i] - buffer[i & STBTT__OVER_MASK];
2766                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
2767                pixels[i] = (unsigned char) (total / kernel_width);
2768             }
2769             break;
2770       }
2771
2772       for (; i < w; ++i) {
2773          STBTT_assert(pixels[i] == 0);
2774          total -= buffer[i & STBTT__OVER_MASK];
2775          pixels[i] = (unsigned char) (total / kernel_width);
2776       }
2777
2778       pixels += stride_in_bytes;
2779    }
2780 }
2781
2782 static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)
2783 {
2784    unsigned char buffer[STBTT_MAX_OVERSAMPLE];
2785    int safe_h = h - kernel_width;
2786    int j;
2787    for (j=0; j < w; ++j) {
2788       int i;
2789       unsigned int total;
2790       STBTT_memset(buffer, 0, kernel_width);
2791
2792       total = 0;
2793
2794       // make kernel_width a constant in common cases so compiler can optimize out the divide
2795       switch (kernel_width) {
2796          case 2:
2797             for (i=0; i <= safe_h; ++i) {
2798                total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
2799                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
2800                pixels[i*stride_in_bytes] = (unsigned char) (total / 2);
2801             }
2802             break;
2803          case 3:
2804             for (i=0; i <= safe_h; ++i) {
2805                total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
2806                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
2807                pixels[i*stride_in_bytes] = (unsigned char) (total / 3);
2808             }
2809             break;
2810          case 4:
2811             for (i=0; i <= safe_h; ++i) {
2812                total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
2813                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
2814                pixels[i*stride_in_bytes] = (unsigned char) (total / 4);
2815             }
2816             break;
2817          case 5:
2818             for (i=0; i <= safe_h; ++i) {
2819                total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
2820                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
2821                pixels[i*stride_in_bytes] = (unsigned char) (total / 5);
2822             }
2823             break;
2824          default:
2825             for (i=0; i <= safe_h; ++i) {
2826                total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
2827                buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
2828                pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width);
2829             }
2830             break;
2831       }
2832
2833       for (; i < h; ++i) {
2834          STBTT_assert(pixels[i*stride_in_bytes] == 0);
2835          total -= buffer[i & STBTT__OVER_MASK];
2836          pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width);
2837       }
2838
2839       pixels += 1;
2840    }
2841 }
2842
2843 static float stbtt__oversample_shift(int oversample)
2844 {
2845    if (!oversample)
2846       return 0.0f;
2847
2848    // The prefilter is a box filter of width "oversample",
2849    // which shifts phase by (oversample - 1)/2 pixels in
2850    // oversampled space. We want to shift in the opposite
2851    // direction to counter this.
2852    return (float)-(oversample - 1) / (2.0f * (float)oversample);
2853 }
2854
2855 // rects array must be big enough to accommodate all characters in the given ranges
2856 STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects)
2857 {
2858    int i,j,k;
2859
2860    k=0;
2861    for (i=0; i < num_ranges; ++i) {
2862       float fh = ranges[i].font_size;
2863       float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh);
2864       ranges[i].h_oversample = (unsigned char) spc->h_oversample;
2865       ranges[i].v_oversample = (unsigned char) spc->v_oversample;
2866       for (j=0; j < ranges[i].num_chars; ++j) {
2867          int x0,y0,x1,y1;
2868          int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j];
2869          int glyph = stbtt_FindGlyphIndex(info, codepoint);
2870          stbtt_GetGlyphBitmapBoxSubpixel(info,glyph,
2871                                          scale * spc->h_oversample,
2872                                          scale * spc->v_oversample,
2873                                          0,0,
2874                                          &x0,&y0,&x1,&y1);
2875          rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1);
2876          rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1);
2877          ++k;
2878       }
2879    }
2880
2881    return k;
2882 }
2883
2884 // rects array must be big enough to accommodate all characters in the given ranges
2885 STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects)
2886 {
2887    int i,j,k, return_value = 1;
2888
2889    // save current values
2890    int old_h_over = spc->h_oversample;
2891    int old_v_over = spc->v_oversample;
2892
2893    k = 0;
2894    for (i=0; i < num_ranges; ++i) {
2895       float fh = ranges[i].font_size;
2896       float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh);
2897       float recip_h,recip_v,sub_x,sub_y;
2898       spc->h_oversample = ranges[i].h_oversample;
2899       spc->v_oversample = ranges[i].v_oversample;
2900       recip_h = 1.0f / spc->h_oversample;
2901       recip_v = 1.0f / spc->v_oversample;
2902       sub_x = stbtt__oversample_shift(spc->h_oversample);
2903       sub_y = stbtt__oversample_shift(spc->v_oversample);
2904       for (j=0; j < ranges[i].num_chars; ++j) {
2905          stbrp_rect *r = &rects[k];
2906          if (r->was_packed) {
2907             stbtt_packedchar *bc = &ranges[i].chardata_for_range[j];
2908             int advance, lsb, x0,y0,x1,y1;
2909             int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j];
2910             int glyph = stbtt_FindGlyphIndex(info, codepoint);
2911             stbrp_coord pad = (stbrp_coord) spc->padding;
2912
2913             // pad on left and top
2914             r->x += pad;
2915             r->y += pad;
2916             r->w -= pad;
2917             r->h -= pad;
2918             stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb);
2919             stbtt_GetGlyphBitmapBox(info, glyph,
2920                                     scale * spc->h_oversample,
2921                                     scale * spc->v_oversample,
2922                                     &x0,&y0,&x1,&y1);
2923             stbtt_MakeGlyphBitmapSubpixel(info,
2924                                           spc->pixels + r->x + r->y*spc->stride_in_bytes,
2925                                           r->w - spc->h_oversample+1,
2926                                           r->h - spc->v_oversample+1,
2927                                           spc->stride_in_bytes,
2928                                           scale * spc->h_oversample,
2929                                           scale * spc->v_oversample,
2930                                           0,0,
2931                                           glyph);
2932
2933             if (spc->h_oversample > 1)
2934                stbtt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes,
2935                                   r->w, r->h, spc->stride_in_bytes,
2936                                   spc->h_oversample);
2937
2938             if (spc->v_oversample > 1)
2939                stbtt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes,
2940                                   r->w, r->h, spc->stride_in_bytes,
2941                                   spc->v_oversample);
2942
2943             bc->x0       = (stbtt_int16)  r->x;
2944             bc->y0       = (stbtt_int16)  r->y;
2945             bc->x1       = (stbtt_int16) (r->x + r->w);
2946             bc->y1       = (stbtt_int16) (r->y + r->h);
2947             bc->xadvance =                scale * advance;
2948             bc->xoff     =       (float)  x0 * recip_h + sub_x;
2949             bc->yoff     =       (float)  y0 * recip_v + sub_y;
2950             bc->xoff2    =                (x0 + r->w) * recip_h + sub_x;
2951             bc->yoff2    =                (y0 + r->h) * recip_v + sub_y;
2952          } else {
2953             return_value = 0; // if any fail, report failure
2954          }
2955
2956          ++k;
2957       }
2958    }
2959
2960    // restore original values
2961    spc->h_oversample = old_h_over;
2962    spc->v_oversample = old_v_over;
2963
2964    return return_value;
2965 }
2966
2967 STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects)
2968 {
2969    stbrp_pack_rects((stbrp_context *) spc->pack_info, rects, num_rects);
2970 }
2971
2972 STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges)
2973 {
2974    stbtt_fontinfo info;
2975    int i,j,n, return_value = 1;
2976    //stbrp_context *context = (stbrp_context *) spc->pack_info;
2977    stbrp_rect    *rects;
2978
2979    // flag all characters as NOT packed
2980    for (i=0; i < num_ranges; ++i)
2981       for (j=0; j < ranges[i].num_chars; ++j)
2982          ranges[i].chardata_for_range[j].x0 =
2983          ranges[i].chardata_for_range[j].y0 =
2984          ranges[i].chardata_for_range[j].x1 =
2985          ranges[i].chardata_for_range[j].y1 = 0;
2986
2987    n = 0;
2988    for (i=0; i < num_ranges; ++i)
2989       n += ranges[i].num_chars;
2990          
2991    rects = (stbrp_rect *) STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context);
2992    if (rects == NULL)
2993       return 0;
2994
2995    stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index));
2996
2997    n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects);
2998
2999    stbtt_PackFontRangesPackRects(spc, rects, n);
3000   
3001    return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects);
3002
3003    STBTT_free(rects, spc->user_allocator_context);
3004    return return_value;
3005 }
3006
3007 STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, float font_size,
3008             int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range)
3009 {
3010    stbtt_pack_range range;
3011    range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range;
3012    range.array_of_unicode_codepoints = NULL;
3013    range.num_chars                   = num_chars_in_range;
3014    range.chardata_for_range          = chardata_for_range;
3015    range.font_size                   = font_size;
3016    return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1);
3017 }
3018
3019 STBTT_DEF void stbtt_GetPackedQuad(stbtt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int align_to_integer)
3020 {
3021    float ipw = 1.0f / pw, iph = 1.0f / ph;
3022    stbtt_packedchar *b = chardata + char_index;
3023
3024    if (align_to_integer) {
3025       float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f);
3026       float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f);
3027       q->x0 = x;
3028       q->y0 = y;
3029       q->x1 = x + b->xoff2 - b->xoff;
3030       q->y1 = y + b->yoff2 - b->yoff;
3031    } else {
3032       q->x0 = *xpos + b->xoff;
3033       q->y0 = *ypos + b->yoff;
3034       q->x1 = *xpos + b->xoff2;
3035       q->y1 = *ypos + b->yoff2;
3036    }
3037
3038    q->s0 = b->x0 * ipw;
3039    q->t0 = b->y0 * iph;
3040    q->s1 = b->x1 * ipw;
3041    q->t1 = b->y1 * iph;
3042
3043    *xpos += b->xadvance;
3044 }
3045
3046
3047 //////////////////////////////////////////////////////////////////////////////
3048 //
3049 // font name matching -- recommended not to use this
3050 //
3051
3052 // check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string
3053 static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(const stbtt_uint8 *s1, stbtt_int32 len1, const stbtt_uint8 *s2, stbtt_int32 len2) 
3054 {
3055    stbtt_int32 i=0;
3056
3057    // convert utf16 to utf8 and compare the results while converting
3058    while (len2) {
3059       stbtt_uint16 ch = s2[0]*256 + s2[1];
3060       if (ch < 0x80) {
3061          if (i >= len1) return -1;
3062          if (s1[i++] != ch) return -1;
3063       } else if (ch < 0x800) {
3064          if (i+1 >= len1) return -1;
3065          if (s1[i++] != 0xc0 + (ch >> 6)) return -1;
3066          if (s1[i++] != 0x80 + (ch & 0x3f)) return -1;
3067       } else if (ch >= 0xd800 && ch < 0xdc00) {
3068          stbtt_uint32 c;
3069          stbtt_uint16 ch2 = s2[2]*256 + s2[3];
3070          if (i+3 >= len1) return -1;
3071          c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000;
3072          if (s1[i++] != 0xf0 + (c >> 18)) return -1;
3073          if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1;
3074          if (s1[i++] != 0x80 + ((c >>  6) & 0x3f)) return -1;
3075          if (s1[i++] != 0x80 + ((c      ) & 0x3f)) return -1;
3076          s2 += 2; // plus another 2 below
3077          len2 -= 2;
3078       } else if (ch >= 0xdc00 && ch < 0xe000) {
3079          return -1;
3080       } else {
3081          if (i+2 >= len1) return -1;
3082          if (s1[i++] != 0xe0 + (ch >> 12)) return -1;
3083          if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1;
3084          if (s1[i++] != 0x80 + ((ch     ) & 0x3f)) return -1;
3085       }
3086       s2 += 2;
3087       len2 -= 2;
3088    }
3089    return i;
3090 }
3091
3092 STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2) 
3093 {
3094    return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((const stbtt_uint8*) s1, len1, (const stbtt_uint8*) s2, len2);
3095 }
3096
3097 // returns results in whatever encoding you request... but note that 2-byte encodings
3098 // will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare
3099 STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID)
3100 {
3101    stbtt_int32 i,count,stringOffset;
3102    stbtt_uint8 *fc = font->data;
3103    stbtt_uint32 offset = font->fontstart;
3104    stbtt_uint32 nm = stbtt__find_table(fc, offset, "name");
3105    if (!nm) return NULL;
3106
3107    count = ttUSHORT(fc+nm+2);
3108    stringOffset = nm + ttUSHORT(fc+nm+4);
3109    for (i=0; i < count; ++i) {
3110       stbtt_uint32 loc = nm + 6 + 12 * i;
3111       if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2)
3112           && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) {
3113          *length = ttUSHORT(fc+loc+8);
3114          return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10));
3115       }
3116    }
3117    return NULL;
3118 }
3119
3120 static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id)
3121 {
3122    stbtt_int32 i;
3123    stbtt_int32 count = ttUSHORT(fc+nm+2);
3124    stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4);
3125
3126    for (i=0; i < count; ++i) {
3127       stbtt_uint32 loc = nm + 6 + 12 * i;
3128       stbtt_int32 id = ttUSHORT(fc+loc+6);
3129       if (id == target_id) {
3130          // find the encoding
3131          stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4);
3132
3133          // is this a Unicode encoding?
3134          if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) {
3135             stbtt_int32 slen = ttUSHORT(fc+loc+8);
3136             stbtt_int32 off = ttUSHORT(fc+loc+10);
3137
3138             // check if there's a prefix match
3139             stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen);
3140             if (matchlen >= 0) {
3141                // check for target_id+1 immediately following, with same encoding & language
3142                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) {
3143                   slen = ttUSHORT(fc+loc+12+8);
3144                   off = ttUSHORT(fc+loc+12+10);
3145                   if (slen == 0) {
3146                      if (matchlen == nlen)
3147                         return 1;
3148                   } else if (matchlen < nlen && name[matchlen] == ' ') {
3149                      ++matchlen;
3150                      if (stbtt_CompareUTF8toUTF16_bigendian((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen))
3151                         return 1;
3152                   }
3153                } else {
3154                   // if nothing immediately following
3155                   if (matchlen == nlen)
3156                      return 1;
3157                }
3158             }
3159          }
3160
3161          // @TODO handle other encodings
3162       }
3163    }
3164    return 0;
3165 }
3166
3167 static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags)
3168 {
3169    stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name);
3170    stbtt_uint32 nm,hd;
3171    if (!stbtt__isfont(fc+offset)) return 0;
3172
3173    // check italics/bold/underline flags in macStyle...
3174    if (flags) {
3175       hd = stbtt__find_table(fc, offset, "head");
3176       if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0;
3177    }
3178
3179    nm = stbtt__find_table(fc, offset, "name");
3180    if (!nm) return 0;
3181
3182    if (flags) {
3183       // if we checked the macStyle flags, then just check the family and ignore the subfamily
3184       if (stbtt__matchpair(fc, nm, name, nlen, 16, -1))  return 1;
3185       if (stbtt__matchpair(fc, nm, name, nlen,  1, -1))  return 1;
3186       if (stbtt__matchpair(fc, nm, name, nlen,  3, -1))  return 1;
3187    } else {
3188       if (stbtt__matchpair(fc, nm, name, nlen, 16, 17))  return 1;
3189       if (stbtt__matchpair(fc, nm, name, nlen,  1,  2))  return 1;
3190       if (stbtt__matchpair(fc, nm, name, nlen,  3, -1))  return 1;
3191    }
3192
3193    return 0;
3194 }
3195
3196 STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *font_collection, const char *name_utf8, stbtt_int32 flags)
3197 {
3198    stbtt_int32 i;
3199    for (i=0;;++i) {
3200       stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i);
3201       if (off < 0) return off;
3202       if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags))
3203          return off;
3204    }
3205 }
3206
3207 #endif // STB_TRUETYPE_IMPLEMENTATION
3208
3209
3210 // FULL VERSION HISTORY
3211 //
3212 //   1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges
3213 //   1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;
3214 //                     allow PackFontRanges to pack and render in separate phases;
3215 //                     fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);
3216 //                     fixed an assert() bug in the new rasterizer
3217 //                     replace assert() with STBTT_assert() in new rasterizer
3218 //   1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine)
3219 //                     also more precise AA rasterizer, except if shapes overlap
3220 //                     remove need for STBTT_sort
3221 //   1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC
3222 //   1.04 (2015-04-15) typo in example
3223 //   1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes
3224 //   1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++
3225 //   1.01 (2014-12-08) fix subpixel position when oversampling to exactly match
3226 //                        non-oversampled; STBTT_POINT_SIZE for packed case only
3227 //   1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling
3228 //   0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg)
3229 //   0.9  (2014-08-07) support certain mac/iOS fonts without an MS platformID
3230 //   0.8b (2014-07-07) fix a warning
3231 //   0.8  (2014-05-25) fix a few more warnings
3232 //   0.7  (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back
3233 //   0.6c (2012-07-24) improve documentation
3234 //   0.6b (2012-07-20) fix a few more warnings
3235 //   0.6  (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels,
3236 //                        stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty
3237 //   0.5  (2011-12-09) bugfixes:
3238 //                        subpixel glyph renderer computed wrong bounding box
3239 //                        first vertex of shape can be off-curve (FreeSans)
3240 //   0.4b (2011-12-03) fixed an error in the font baking example
3241 //   0.4  (2011-12-01) kerning, subpixel rendering (tor)
3242 //                    bugfixes for:
3243 //                        codepoint-to-glyph conversion using table fmt=12
3244 //                        codepoint-to-glyph conversion using table fmt=4
3245 //                        stbtt_GetBakedQuad with non-square texture (Zer)
3246 //                    updated Hello World! sample to use kerning and subpixel
3247 //                    fixed some warnings
3248 //   0.3  (2009-06-24) cmap fmt=12, compound shapes (MM)
3249 //                    userdata, malloc-from-userdata, non-zero fill (stb)
3250 //   0.2  (2009-03-11) Fix unsigned/signed char warnings
3251 //   0.1  (2009-03-09) First public release
3252 //