b1f81ed3f1baf2b6e51074f4a55f0c7252dc3269
[ipdf/code.git] / src / stb_truetype.h
1 // stb_truetype.h - v0.8 - public domain
2 // authored from 2009-2013 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:
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 //
35 // VERSION HISTORY
36 //
37 //   0.8  (2014-05-25) fix a few more warnings
38 //   0.7  (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back
39 //   0.6c (2012-07-24) improve documentation
40 //   0.6b (2012-07-20) fix a few more warnings
41 //   0.6  (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels,
42 //                        stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty
43 //   0.5  (2011-12-09) bugfixes:
44 //                        subpixel glyph renderer computed wrong bounding box
45 //                        first vertex of shape can be off-curve (FreeSans)
46 //   0.4b (2011-12-03) fixed an error in the font baking example
47 //   0.4  (2011-12-01) kerning, subpixel rendering (tor)
48 //                    bugfixes for:
49 //                        codepoint-to-glyph conversion using table fmt=12
50 //                        codepoint-to-glyph conversion using table fmt=4
51 //                        stbtt_GetBakedQuad with non-square texture (Zer)
52 //                    updated Hello World! sample to use kerning and subpixel
53 //                    fixed some warnings
54 //   0.3  (2009-06-24) cmap fmt=12, compound shapes (MM)
55 //                    userdata, malloc-from-userdata, non-zero fill (STB)
56 //   0.2  (2009-03-11) Fix unsigned/signed char warnings
57 //   0.1  (2009-03-09) First public release
58 //
59 // LICENSE
60 //
61 //   This software is in the public domain. Where that dedication is not
62 //   recognized, you are granted a perpetual, irrevokable license to copy
63 //   and modify this file as you see fit.
64 //
65 // USAGE
66 //
67 //   Include this file in whatever places neeed to refer to it. In ONE C/C++
68 //   file, write:
69 //      #define STB_TRUETYPE_IMPLEMENTATION
70 //   before the #include of this file. This expands out the actual
71 //   implementation into that C/C++ file.
72 //
73 //   Simple 3D API (don't ship this, but it's fine for tools and quick start,
74 //                  and you can cut and paste from it to move to more advanced)
75 //           stbtt_BakeFontBitmap()               -- bake a font to a bitmap for use as texture
76 //           stbtt_GetBakedQuad()                 -- compute quad to draw for a given char
77 //
78 //   "Load" a font file from a memory buffer (you have to keep the buffer loaded)
79 //           stbtt_InitFont()
80 //           stbtt_GetFontOffsetForIndex()        -- use for TTC font collections
81 //
82 //   Render a unicode codepoint to a bitmap
83 //           stbtt_GetCodepointBitmap()           -- allocates and returns a bitmap
84 //           stbtt_MakeCodepointBitmap()          -- renders into bitmap you provide
85 //           stbtt_GetCodepointBitmapBox()        -- how big the bitmap must be
86 //
87 //   Character advance/positioning
88 //           stbtt_GetCodepointHMetrics()
89 //           stbtt_GetFontVMetrics()
90 //           stbtt_GetCodepointKernAdvance()
91 //
92 // ADDITIONAL DOCUMENTATION
93 //
94 //   Immediately after this block comment are a series of sample programs.
95 //
96 //   After the sample programs is the "header file" section. This section
97 //   includes documentation for each API function.
98 //
99 //   Some important concepts to understand to use this library:
100 //
101 //      Codepoint
102 //         Characters are defined by unicode codepoints, e.g. 65 is
103 //         uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is
104 //         the hiragana for "ma".
105 //
106 //      Glyph
107 //         A visual character shape (every codepoint is rendered as
108 //         some glyph)
109 //
110 //      Glyph index
111 //         A font-specific integer ID representing a glyph
112 //
113 //      Baseline
114 //         Glyph shapes are defined relative to a baseline, which is the
115 //         bottom of uppercase characters. Characters extend both above
116 //         and below the baseline.
117 //
118 //      Current Point
119 //         As you draw text to the screen, you keep track of a "current point"
120 //         which is the origin of each character. The current point's vertical
121 //         position is the baseline. Even "baked fonts" use this model.
122 //
123 //      Vertical Font Metrics
124 //         The vertical qualities of the font, used to vertically position
125 //         and space the characters. See docs for stbtt_GetFontVMetrics.
126 //
127 //      Font Size in Pixels or Points
128 //         The preferred interface for specifying font sizes in stb_truetype
129 //         is to specify how tall the font's vertical extent should be in pixels.
130 //         If that sounds good enough, skip the next paragraph.
131 //
132 //         Most font APIs instead use "points", which are a common typographic
133 //         measurement for describing font size, defined as 72 points per inch.
134 //         stb_truetype provides a point API for compatibility. However, true
135 //         "per inch" conventions don't make much sense on computer displays
136 //         since they different monitors have different number of pixels per
137 //         inch. For example, Windows traditionally uses a convention that
138 //         there are 96 pixels per inch, thus making 'inch' measurements have
139 //         nothing to do with inches, and thus effectively defining a point to
140 //         be 1.333 pixels. Additionally, the TrueType font data provides
141 //         an explicit scale factor to scale a given font's glyphs to points,
142 //         but the author has observed that this scale factor is often wrong
143 //         for non-commercial fonts, thus making fonts scaled in points
144 //         according to the TrueType spec incoherently sized in practice.
145 //
146 // ADVANCED USAGE
147 //
148 //   Quality:
149 //
150 //    - Use the functions with Subpixel at the end to allow your characters
151 //      to have subpixel positioning. Since the font is anti-aliased, not
152 //      hinted, this is very import for quality. (This is not possible with
153 //      baked fonts.)
154 //
155 //    - Kerning is now supported, and if you're supporting subpixel rendering
156 //      then kerning is worth using to give your text a polished look.
157 //
158 //   Performance:
159 //
160 //    - Convert Unicode codepoints to glyph indexes and operate on the glyphs;
161 //      if you don't do this, stb_truetype is forced to do the conversion on
162 //      every call.
163 //
164 //    - There are a lot of memory allocations. We should modify it to take
165 //      a temp buffer and allocate from the temp buffer (without freeing),
166 //      should help performance a lot.
167 //
168 // NOTES
169 //
170 //   The system uses the raw data found in the .ttf file without changing it
171 //   and without building auxiliary data structures. This is a bit inefficient
172 //   on little-endian systems (the data is big-endian), but assuming you're
173 //   caching the bitmaps or glyph shapes this shouldn't be a big deal.
174 //
175 //   It appears to be very hard to programmatically determine what font a
176 //   given file is in a general way. I provide an API for this, but I don't
177 //   recommend it.
178 //
179 //
180 // SOURCE STATISTICS (based on v0.6c, 2050 LOC)
181 //
182 //   Documentation & header file        520 LOC  \___ 660 LOC documentation
183 //   Sample code                        140 LOC  /
184 //   Truetype parsing                   620 LOC  ---- 620 LOC TrueType
185 //   Software rasterization             240 LOC  \                           .
186 //   Curve tesselation                  120 LOC   \__ 550 LOC Bitmap creation
187 //   Bitmap management                  100 LOC   /
188 //   Baked bitmap interface              70 LOC  /
189 //   Font name matching & access        150 LOC  ---- 150 
190 //   C runtime library abstraction       60 LOC  ----  60
191
192
193 //////////////////////////////////////////////////////////////////////////////
194 //////////////////////////////////////////////////////////////////////////////
195 ////
196 ////  SAMPLE PROGRAMS
197 ////
198 //
199 //  Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless
200 //
201 #if 0
202 #define STB_TRUETYPE_IMPLEMENTATION  // force following include to generate implementation
203 #include "stb_truetype.h"
204
205 char ttf_buffer[1<<20];
206 unsigned char temp_bitmap[512*512];
207
208 stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs
209 GLstbtt_uint ftex;
210
211 void my_stbtt_initfont(void)
212 {
213    fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb"));
214    stbtt_BakeFontBitmap(data,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits!
215    // can free ttf_buffer at this point
216    glGenTextures(1, &ftex);
217    glBindTexture(GL_TEXTURE_2D, ftex);
218    glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap);
219    // can free temp_bitmap at this point
220    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
221 }
222
223 void my_stbtt_print(float x, float y, char *text)
224 {
225    // assume orthographic projection with units = screen pixels, origin at top left
226    glBindTexture(GL_TEXTURE_2D, ftex);
227    glBegin(GL_QUADS);
228    while (*text) {
229       if (*text >= 32 && *text < 128) {
230          stbtt_aligned_quad q;
231          stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9
232          glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y0);
233          glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y0);
234          glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y1);
235          glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y1);
236       }
237       ++text;
238    }
239    glEnd();
240 }
241 #endif
242 //
243 //
244 //////////////////////////////////////////////////////////////////////////////
245 //
246 // Complete program (this compiles): get a single bitmap, print as ASCII art
247 //
248 #if 0
249 #include <stdio.h>
250 #define STB_TRUETYPE_IMPLEMENTATION  // force following include to generate implementation
251 #include "stb_truetype.h"
252
253 char ttf_buffer[1<<25];
254
255 int main(int argc, char **argv)
256 {
257    stbtt_fontinfo font;
258    unsigned char *bitmap;
259    int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20);
260
261    fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb"));
262
263    stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0));
264    bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0);
265
266    for (j=0; j < h; ++j) {
267       for (i=0; i < w; ++i)
268          putchar(" .:ioVM@"[bitmap[j*w+i]>>5]);
269       putchar('\n');
270    }
271    return 0;
272 }
273 #endif 
274 //
275 // Output:
276 //
277 //     .ii.
278 //    @@@@@@.
279 //   V@Mio@@o
280 //   :i.  V@V
281 //     :oM@@M
282 //   :@@@MM@M
283 //   @@o  o@M
284 //  :@@.  M@M
285 //   @@@o@@@@
286 //   :M@@V:@@.
287 //  
288 //////////////////////////////////////////////////////////////////////////////
289 // 
290 // Complete program: print "Hello World!" banner, with bugs
291 //
292 #if 0
293 char buffer[24<<20];
294 unsigned char screen[20][79];
295
296 int main(int arg, char **argv)
297 {
298    stbtt_fontinfo font;
299    int i,j,ascent,baseline,ch=0;
300    float scale, xpos=2; // leave a little padding in case the character extends left
301    char *text = "Heljo World!";
302
303    fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb"));
304    stbtt_InitFont(&font, buffer, 0);
305
306    scale = stbtt_ScaleForPixelHeight(&font, 15);
307    stbtt_GetFontVMetrics(&font, &ascent,0,0);
308    baseline = (int) (ascent*scale);
309
310    while (text[ch]) {
311       int advance,lsb,x0,y0,x1,y1;
312       float x_shift = xpos - (float) floor(xpos);
313       stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb);
314       stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1);
315       stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]);
316       // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong
317       // because this API is really for baking character bitmaps into textures. if you want to render
318       // a sequence of characters, you really need to render each bitmap to a temp buffer, then
319       // "alpha blend" that into the working buffer
320       xpos += (advance * scale);
321       if (text[ch+1])
322          xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]);
323       ++ch;
324    }
325
326    for (j=0; j < 20; ++j) {
327       for (i=0; i < 78; ++i)
328          putchar(" .:ioVM@"[screen[j][i]>>5]);
329       putchar('\n');
330    }
331
332    return 0;
333 }
334 #endif
335
336
337 //////////////////////////////////////////////////////////////////////////////
338 //////////////////////////////////////////////////////////////////////////////
339 ////
340 ////   INTEGRATION WITH YOUR CODEBASE
341 ////
342 ////   The following sections allow you to supply alternate definitions
343 ////   of C library functions used by stb_truetype.
344
345 #ifdef STB_TRUETYPE_IMPLEMENTATION
346    // #define your own (u)stbtt_int8/16/32 before including to override this
347    #ifndef stbtt_uint8
348    typedef unsigned char   stbtt_uint8;
349    typedef signed   char   stbtt_int8;
350    typedef unsigned short  stbtt_uint16;
351    typedef signed   short  stbtt_int16;
352    typedef unsigned int    stbtt_uint32;
353    typedef signed   int    stbtt_int32;
354    #endif
355
356    typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1];
357    typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1];
358
359    // #define your own STBTT_sort() to override this to avoid qsort
360    #ifndef STBTT_sort
361    #include <stdlib.h>
362    #define STBTT_sort(data,num_items,item_size,compare_func)   qsort(data,num_items,item_size,compare_func)
363    #endif
364
365    // #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h
366    #ifndef STBTT_ifloor
367    #include <math.h>
368    #define STBTT_ifloor(x)   ((int) floor(x))
369    #define STBTT_iceil(x)    ((int) ceil(x))
370    #endif
371
372    #ifndef STBTT_sqrt
373    #include <math.h>
374    #define STBTT_sqrt(x)      sqrt(x)
375    #endif
376
377    // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h
378    #ifndef STBTT_malloc
379    #include <stdlib.h>
380    #define STBTT_malloc(x,u)  ((void)(u),malloc(x))
381    #define STBTT_free(x,u)    free(x)
382    #endif
383
384    #ifndef STBTT_assert
385    #include <assert.h>
386    #define STBTT_assert(x)    assert(x)
387    #endif
388
389    #ifndef STBTT_strlen
390    #include <string.h>
391    #define STBTT_strlen(x)    strlen(x)
392    #endif
393
394    #ifndef STBTT_memcpy
395    #include <memory.h>
396    #define STBTT_memcpy       memcpy
397    #define STBTT_memset       memset
398    #endif
399 #endif
400
401 ///////////////////////////////////////////////////////////////////////////////
402 ///////////////////////////////////////////////////////////////////////////////
403 ////
404 ////   INTERFACE
405 ////
406 ////
407
408 #ifndef __STB_INCLUDE_STB_TRUETYPE_H__
409 #define __STB_INCLUDE_STB_TRUETYPE_H__
410
411 #ifdef __cplusplus
412 extern "C" {
413 #endif
414
415 //////////////////////////////////////////////////////////////////////////////
416 //
417 // TEXTURE BAKING API
418 //
419 // If you use this API, you only have to call two functions ever.
420 //
421
422 typedef struct
423 {
424    unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap
425    float xoff,yoff,xadvance;   
426 } stbtt_bakedchar;
427
428 extern int stbtt_BakeFontBitmap(const unsigned char *data, int offset,  // font location (use offset=0 for plain .ttf)
429                                 float pixel_height,                     // height of font in pixels
430                                 unsigned char *pixels, int pw, int ph,  // bitmap to be filled in
431                                 int first_char, int num_chars,          // characters to bake
432                                 stbtt_bakedchar *chardata);             // you allocate this, it's num_chars long
433 // if return is positive, the first unused row of the bitmap
434 // if return is negative, returns the negative of the number of characters that fit
435 // if return is 0, no characters fit and no rows were used
436 // This uses a very crappy packing.
437
438 typedef struct
439 {
440    float x0,y0,s0,t0; // top-left
441    float x1,y1,s1,t1; // bottom-right
442 } stbtt_aligned_quad;
443
444 extern void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph,  // same data as above
445                                int char_index,             // character to display
446                                float *xpos, float *ypos,   // pointers to current position in screen pixel space
447                                stbtt_aligned_quad *q,      // output: quad to draw
448                                int opengl_fillrule);       // true if opengl fill rule; false if DX9 or earlier
449 // Call GetBakedQuad with char_index = 'character - first_char', and it
450 // creates the quad you need to draw and advances the current position.
451 //
452 // The coordinate system used assumes y increases downwards.
453 //
454 // Characters will extend both above and below the current position;
455 // see discussion of "BASELINE" above.
456 //
457 // It's inefficient; you might want to c&p it and optimize it.
458
459
460 //////////////////////////////////////////////////////////////////////////////
461 //
462 // FONT LOADING
463 //
464 //
465
466 extern int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index);
467 // Each .ttf/.ttc file may have more than one font. Each font has a sequential
468 // index number starting from 0. Call this function to get the font offset for
469 // a given index; it returns -1 if the index is out of range. A regular .ttf
470 // file will only define one font and it always be at offset 0, so it will
471 // return '0' for index 0, and -1 for all other indices. You can just skip
472 // this step if you know it's that kind of font.
473
474
475 // The following structure is defined publically so you can declare one on
476 // the stack or as a global or etc, but you should treat it as opaque.
477 typedef struct stbtt_fontinfo
478 {
479    void           * userdata;
480    unsigned char  * data;              // pointer to .ttf file
481    int              fontstart;         // offset of start of font
482
483    int numGlyphs;                     // number of glyphs, needed for range checking
484
485    int loca,head,glyf,hhea,hmtx,kern; // table locations as offset from start of .ttf
486    int index_map;                     // a cmap mapping for our chosen character encoding
487    int indexToLocFormat;              // format needed to map from glyph index to glyph
488 } stbtt_fontinfo;
489
490 extern int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset);
491 // Given an offset into the file that defines a font, this function builds
492 // the necessary cached info for the rest of the system. You must allocate
493 // the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't
494 // need to do anything special to free it, because the contents are pure
495 // value data with no additional data structures. Returns 0 on failure.
496
497
498 //////////////////////////////////////////////////////////////////////////////
499 //
500 // CHARACTER TO GLYPH-INDEX CONVERSIOn
501
502 int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint);
503 // If you're going to perform multiple operations on the same character
504 // and you want a speed-up, call this function with the character you're
505 // going to process, then use glyph-based functions instead of the
506 // codepoint-based functions.
507
508
509 //////////////////////////////////////////////////////////////////////////////
510 //
511 // CHARACTER PROPERTIES
512 //
513
514 extern float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels);
515 // computes a scale factor to produce a font whose "height" is 'pixels' tall.
516 // Height is measured as the distance from the highest ascender to the lowest
517 // descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics
518 // and computing:
519 //       scale = pixels / (ascent - descent)
520 // so if you prefer to measure height by the ascent only, use a similar calculation.
521
522 extern float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels);
523 // computes a scale factor to produce a font whose EM size is mapped to
524 // 'pixels' tall. This is probably what traditional APIs compute, but
525 // I'm not positive.
526
527 extern void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap);
528 // ascent is the coordinate above the baseline the font extends; descent
529 // is the coordinate below the baseline the font extends (i.e. it is typically negative)
530 // lineGap is the spacing between one row's descent and the next row's ascent...
531 // so you should advance the vertical position by "*ascent - *descent + *lineGap"
532 //   these are expressed in unscaled coordinates, so you must multiply by
533 //   the scale factor for a given size
534
535 extern void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1);
536 // the bounding box around all possible characters
537
538 extern void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing);
539 // leftSideBearing is the offset from the current horizontal position to the left edge of the character
540 // advanceWidth is the offset from the current horizontal position to the next horizontal position
541 //   these are expressed in unscaled coordinates
542
543 extern int  stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2);
544 // an additional amount to add to the 'advance' value between ch1 and ch2
545
546 extern int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1);
547 // Gets the bounding box of the visible part of the glyph, in unscaled coordinates
548
549 extern void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing);
550 extern int  stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2);
551 extern int  stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);
552 // as above, but takes one or more glyph indices for greater efficiency
553
554
555 //////////////////////////////////////////////////////////////////////////////
556 //
557 // GLYPH SHAPES (you probably don't need these, but they have to go before
558 // the bitmaps for C declaration-order reasons)
559 //
560
561 #ifndef STBTT_vmove // you can predefine these to use different values (but why?)
562    enum {
563       STBTT_vmove=1,
564       STBTT_vline,
565       STBTT_vcurve
566    };
567 #endif
568
569 #ifndef stbtt_vertex // you can predefine this to use different values
570                    // (we share this with other code at RAD)
571    #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file
572    typedef struct
573    {
574       stbtt_vertex_type x,y,cx,cy;
575       unsigned char type,padding;
576    } stbtt_vertex;
577 #endif
578
579 extern int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index);
580 // returns non-zero if nothing is drawn for this glyph
581
582 extern int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices);
583 extern int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices);
584 // returns # of vertices and fills *vertices with the pointer to them
585 //   these are expressed in "unscaled" coordinates
586 //
587 // The shape is a series of countours. Each one starts with
588 // a STBTT_moveto, then consists of a series of mixed
589 // STBTT_lineto and STBTT_curveto segments. A lineto
590 // draws a line from previous endpoint to its x,y; a curveto
591 // draws a quadratic bezier from previous endpoint to
592 // its x,y, using cx,cy as the bezier control point.
593
594 extern void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices);
595 // frees the data allocated above
596
597 //////////////////////////////////////////////////////////////////////////////
598 //
599 // BITMAP RENDERING
600 //
601
602 extern void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata);
603 // frees the bitmap allocated below
604
605 extern unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff);
606 // allocates a large-enough single-channel 8bpp bitmap and renders the
607 // specified character/glyph at the specified scale into it, with
608 // antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque).
609 // *width & *height are filled out with the width & height of the bitmap,
610 // which is stored left-to-right, top-to-bottom.
611 //
612 // xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap
613
614 extern 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);
615 // the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel
616 // shift for the character
617
618 extern 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);
619 // the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap
620 // in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap
621 // is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the
622 // width and height and positioning info for it first.
623
624 extern 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);
625 // same as stbtt_MakeCodepointBitmap, but you can specify a subpixel
626 // shift for the character
627
628 extern void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);
629 // get the bbox of the bitmap centered around the glyph origin; so the
630 // bitmap width is ix1-ix0, height is iy1-iy0, and location to place
631 // the bitmap top left is (leftSideBearing*scale,iy0).
632 // (Note that the bitmap uses y-increases-down, but the shape uses
633 // y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.)
634
635 extern 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);
636 // same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel
637 // shift for the character
638
639 // the following functions are equivalent to the above functions, but operate
640 // on glyph indices instead of Unicode codepoints (for efficiency)
641 extern unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff);
642 extern 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);
643 extern 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);
644 extern 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);
645 extern void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);
646 extern 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);
647
648
649 // @TODO: don't expose this structure
650 typedef struct
651 {
652    int w,h,stride;
653    unsigned char *pixels;
654 } stbtt__bitmap;
655
656 extern 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);
657
658 //////////////////////////////////////////////////////////////////////////////
659 //
660 // Finding the right font...
661 //
662 // You should really just solve this offline, keep your own tables
663 // of what font is what, and don't try to get it out of the .ttf file.
664 // That's because getting it out of the .ttf file is really hard, because
665 // the names in the file can appear in many possible encodings, in many
666 // possible languages, and e.g. if you need a case-insensitive comparison,
667 // the details of that depend on the encoding & language in a complex way
668 // (actually underspecified in truetype, but also gigantic).
669 //
670 // But you can use the provided functions in two possible ways:
671 //     stbtt_FindMatchingFont() will use *case-sensitive* comparisons on
672 //             unicode-encoded names to try to find the font you want;
673 //             you can run this before calling stbtt_InitFont()
674 //
675 //     stbtt_GetFontNameString() lets you get any of the various strings
676 //             from the file yourself and do your own comparisons on them.
677 //             You have to have called stbtt_InitFont() first.
678
679
680 extern int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags);
681 // returns the offset (not index) of the font that matches, or -1 if none
682 //   if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold".
683 //   if you use any other flag, use a font name like "Arial"; this checks
684 //     the 'macStyle' header field; i don't know if fonts set this consistently
685 #define STBTT_MACSTYLE_DONTCARE     0
686 #define STBTT_MACSTYLE_BOLD         1
687 #define STBTT_MACSTYLE_ITALIC       2
688 #define STBTT_MACSTYLE_UNDERSCORE   4
689 #define STBTT_MACSTYLE_NONE         8   // <= not same as 0, this makes us check the bitfield is 0
690
691 extern int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2);
692 // returns 1/0 whether the first string interpreted as utf8 is identical to
693 // the second string interpreted as big-endian utf16... useful for strings from next func
694
695 extern const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID);
696 // returns the string (which may be big-endian double byte, e.g. for unicode)
697 // and puts the length in bytes in *length.
698 //
699 // some of the values for the IDs are below; for more see the truetype spec:
700 //     http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html
701 //     http://www.microsoft.com/typography/otspec/name.htm
702
703 enum { // platformID
704    STBTT_PLATFORM_ID_UNICODE   =0,
705    STBTT_PLATFORM_ID_MAC       =1,
706    STBTT_PLATFORM_ID_ISO       =2,
707    STBTT_PLATFORM_ID_MICROSOFT =3
708 };
709
710 enum { // encodingID for STBTT_PLATFORM_ID_UNICODE
711    STBTT_UNICODE_EID_UNICODE_1_0    =0,
712    STBTT_UNICODE_EID_UNICODE_1_1    =1,
713    STBTT_UNICODE_EID_ISO_10646      =2,
714    STBTT_UNICODE_EID_UNICODE_2_0_BMP=3,
715    STBTT_UNICODE_EID_UNICODE_2_0_FULL=4
716 };
717
718 enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT
719    STBTT_MS_EID_SYMBOL        =0,
720    STBTT_MS_EID_UNICODE_BMP   =1,
721    STBTT_MS_EID_SHIFTJIS      =2,
722    STBTT_MS_EID_UNICODE_FULL  =10
723 };
724
725 enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes
726    STBTT_MAC_EID_ROMAN        =0,   STBTT_MAC_EID_ARABIC       =4,
727    STBTT_MAC_EID_JAPANESE     =1,   STBTT_MAC_EID_HEBREW       =5,
728    STBTT_MAC_EID_CHINESE_TRAD =2,   STBTT_MAC_EID_GREEK        =6,
729    STBTT_MAC_EID_KOREAN       =3,   STBTT_MAC_EID_RUSSIAN      =7
730 };
731
732 enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID...
733        // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs
734    STBTT_MS_LANG_ENGLISH     =0x0409,   STBTT_MS_LANG_ITALIAN     =0x0410,
735    STBTT_MS_LANG_CHINESE     =0x0804,   STBTT_MS_LANG_JAPANESE    =0x0411,
736    STBTT_MS_LANG_DUTCH       =0x0413,   STBTT_MS_LANG_KOREAN      =0x0412,
737    STBTT_MS_LANG_FRENCH      =0x040c,   STBTT_MS_LANG_RUSSIAN     =0x0419,
738    STBTT_MS_LANG_GERMAN      =0x0407,   STBTT_MS_LANG_SPANISH     =0x0409,
739    STBTT_MS_LANG_HEBREW      =0x040d,   STBTT_MS_LANG_SWEDISH     =0x041D
740 };
741
742 enum { // languageID for STBTT_PLATFORM_ID_MAC
743    STBTT_MAC_LANG_ENGLISH      =0 ,   STBTT_MAC_LANG_JAPANESE     =11,
744    STBTT_MAC_LANG_ARABIC       =12,   STBTT_MAC_LANG_KOREAN       =23,
745    STBTT_MAC_LANG_DUTCH        =4 ,   STBTT_MAC_LANG_RUSSIAN      =32,
746    STBTT_MAC_LANG_FRENCH       =1 ,   STBTT_MAC_LANG_SPANISH      =6 ,
747    STBTT_MAC_LANG_GERMAN       =2 ,   STBTT_MAC_LANG_SWEDISH      =5 ,
748    STBTT_MAC_LANG_HEBREW       =10,   STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33,
749    STBTT_MAC_LANG_ITALIAN      =3 ,   STBTT_MAC_LANG_CHINESE_TRAD =19
750 };
751
752 #ifdef __cplusplus
753 }
754 #endif
755
756 #endif // __STB_INCLUDE_STB_TRUETYPE_H__
757
758 ///////////////////////////////////////////////////////////////////////////////
759 ///////////////////////////////////////////////////////////////////////////////
760 ////
761 ////   IMPLEMENTATION
762 ////
763 ////
764
765 #ifdef STB_TRUETYPE_IMPLEMENTATION
766
767 //////////////////////////////////////////////////////////////////////////
768 //
769 // accessors to parse data from file
770 //
771
772 // on platforms that don't allow misaligned reads, if we want to allow
773 // truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE
774
775 #define ttBYTE(p)     (* (stbtt_uint8 *) (p))
776 #define ttCHAR(p)     (* (stbtt_int8 *) (p))
777 #define ttFixed(p)    ttLONG(p)
778
779 #if defined(STB_TRUETYPE_BIGENDIAN) && !defined(ALLOW_UNALIGNED_TRUETYPE)
780
781    #define ttUSHORT(p)   (* (stbtt_uint16 *) (p))
782    #define ttSHORT(p)    (* (stbtt_int16 *) (p))
783    #define ttULONG(p)    (* (stbtt_uint32 *) (p))
784    #define ttLONG(p)     (* (stbtt_int32 *) (p))
785
786 #else
787
788    stbtt_uint16 ttUSHORT(const stbtt_uint8 *p) { return p[0]*256 + p[1]; }
789    stbtt_int16 ttSHORT(const stbtt_uint8 *p)   { return p[0]*256 + p[1]; }
790    stbtt_uint32 ttULONG(const stbtt_uint8 *p)  { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
791    stbtt_int32 ttLONG(const stbtt_uint8 *p)    { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
792
793 #endif
794
795 #define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3))
796 #define stbtt_tag(p,str)           stbtt_tag4(p,str[0],str[1],str[2],str[3])
797
798 static int stbtt__isfont(const stbtt_uint8 *font)
799 {
800    // check the version number
801    if (stbtt_tag4(font, '1',0,0,0))  return 1; // TrueType 1
802    if (stbtt_tag(font, "typ1"))   return 1; // TrueType with type 1 font -- we don't support this!
803    if (stbtt_tag(font, "OTTO"))   return 1; // OpenType with CFF
804    if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0
805    return 0;
806 }
807
808 // @OPTIMIZE: binary search
809 static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag)
810 {
811    stbtt_int32 num_tables = ttUSHORT(data+fontstart+4);
812    stbtt_uint32 tabledir = fontstart + 12;
813    stbtt_int32 i;
814    for (i=0; i < num_tables; ++i) {
815       stbtt_uint32 loc = tabledir + 16*i;
816       if (stbtt_tag(data+loc+0, tag))
817          return ttULONG(data+loc+8);
818    }
819    return 0;
820 }
821
822 int stbtt_GetFontOffsetForIndex(const unsigned char *font_collection, int index)
823 {
824    // if it's just a font, there's only one valid index
825    if (stbtt__isfont(font_collection))
826       return index == 0 ? 0 : -1;
827
828    // check if it's a TTC
829    if (stbtt_tag(font_collection, "ttcf")) {
830       // version 1?
831       if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {
832          stbtt_int32 n = ttLONG(font_collection+8);
833          if (index >= n)
834             return -1;
835          return ttULONG(font_collection+12+index*14);
836       }
837    }
838    return -1;
839 }
840
841 int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data2, int fontstart)
842 {
843    stbtt_uint8 *data = (stbtt_uint8 *) data2;
844    stbtt_uint32 cmap, t;
845    stbtt_int32 i,numTables;
846
847    info->data = data;
848    info->fontstart = fontstart;
849
850    cmap = stbtt__find_table(data, fontstart, "cmap");       // required
851    info->loca = stbtt__find_table(data, fontstart, "loca"); // required
852    info->head = stbtt__find_table(data, fontstart, "head"); // required
853    info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required
854    info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required
855    info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required
856    info->kern = stbtt__find_table(data, fontstart, "kern"); // not required
857    if (!cmap || !info->loca || !info->head || !info->glyf || !info->hhea || !info->hmtx)
858       return 0;
859
860    t = stbtt__find_table(data, fontstart, "maxp");
861    if (t)
862       info->numGlyphs = ttUSHORT(data+t+4);
863    else
864       info->numGlyphs = 0xffff;
865
866    // find a cmap encoding table we understand *now* to avoid searching
867    // later. (todo: could make this installable)
868    // the same regardless of glyph.
869    numTables = ttUSHORT(data + cmap + 2);
870    info->index_map = 0;
871    for (i=0; i < numTables; ++i) {
872       stbtt_uint32 encoding_record = cmap + 4 + 8 * i;
873       // find an encoding we understand:
874       switch(ttUSHORT(data+encoding_record)) {
875          case STBTT_PLATFORM_ID_MICROSOFT:
876             switch (ttUSHORT(data+encoding_record+2)) {
877                case STBTT_MS_EID_UNICODE_BMP:
878                case STBTT_MS_EID_UNICODE_FULL:
879                   // MS/Unicode
880                   info->index_map = cmap + ttULONG(data+encoding_record+4);
881                   break;
882             }
883             break;
884       }
885    }
886    if (info->index_map == 0)
887       return 0;
888
889    info->indexToLocFormat = ttUSHORT(data+info->head + 50);
890    return 1;
891 }
892
893 int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint)
894 {
895    stbtt_uint8 *data = info->data;
896    stbtt_uint32 index_map = info->index_map;
897
898    stbtt_uint16 format = ttUSHORT(data + index_map + 0);
899    if (format == 0) { // apple byte encoding
900       stbtt_int32 bytes = ttUSHORT(data + index_map + 2);
901       if (unicode_codepoint < bytes-6)
902          return ttBYTE(data + index_map + 6 + unicode_codepoint);
903       return 0;
904    } else if (format == 6) {
905       stbtt_uint32 first = ttUSHORT(data + index_map + 6);
906       stbtt_uint32 count = ttUSHORT(data + index_map + 8);
907       if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count)
908          return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2);
909       return 0;
910    } else if (format == 2) {
911       STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean
912       return 0;
913    } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges
914       stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1;
915       stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1;
916       stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10);
917       stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1;
918       stbtt_uint16 item, offset, start, end;
919
920       // do a binary search of the segments
921       stbtt_uint32 endCount = index_map + 14;
922       stbtt_uint32 search = endCount;
923
924       if (unicode_codepoint > 0xffff)
925          return 0;
926
927       // they lie from endCount .. endCount + segCount
928       // but searchRange is the nearest power of two, so...
929       if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2))
930          search += rangeShift*2;
931
932       // now decrement to bias correctly to find smallest
933       search -= 2;
934       while (entrySelector) {
935          searchRange >>= 1;
936          start = ttUSHORT(data + search + searchRange*2 + segcount*2 + 2);
937          end = ttUSHORT(data + search + searchRange*2);
938          if (unicode_codepoint > end)
939             search += searchRange*2;
940          --entrySelector;
941       }
942       search += 2;
943
944       item = (stbtt_uint16) ((search - endCount) >> 1);
945
946       STBTT_assert(unicode_codepoint <= ttUSHORT(data + endCount + 2*item));
947       start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item);
948       end = ttUSHORT(data + index_map + 14 + 2 + 2*item);
949       if (unicode_codepoint < start)
950          return 0;
951
952       offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item);
953       if (offset == 0)
954          return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item));
955
956       return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item);
957    } else if (format == 12 || format == 13) {
958       stbtt_uint32 ngroups = ttULONG(data+index_map+12);
959       stbtt_int32 low,high;
960       low = 0; high = (stbtt_int32)ngroups;
961       // Binary search the right group.
962       while (low < high) {
963          stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high
964          stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12);
965          stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4);
966          if ((stbtt_uint32) unicode_codepoint < start_char)
967             high = mid;
968          else if ((stbtt_uint32) unicode_codepoint > end_char)
969             low = mid+1;
970          else {
971             stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8);
972             if (format == 12)
973                return start_glyph + unicode_codepoint-start_char;
974             else // format == 13
975                return start_glyph;
976          }
977       }
978       return 0; // not found
979    }
980    // @TODO
981    STBTT_assert(0);
982    return 0;
983 }
984
985 int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices)
986 {
987    return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices);
988 }
989
990 static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy)
991 {
992    v->type = type;
993    v->x = (stbtt_int16) x;
994    v->y = (stbtt_int16) y;
995    v->cx = (stbtt_int16) cx;
996    v->cy = (stbtt_int16) cy;
997 }
998
999 static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index)
1000 {
1001    int g1,g2;
1002
1003    if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range
1004    if (info->indexToLocFormat >= 2)    return -1; // unknown index->glyph map format
1005
1006    if (info->indexToLocFormat == 0) {
1007       g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2;
1008       g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2;
1009    } else {
1010       g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4);
1011       g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4);
1012    }
1013
1014    return g1==g2 ? -1 : g1; // if length is 0, return -1
1015 }
1016
1017 int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)
1018 {
1019    int g = stbtt__GetGlyfOffset(info, glyph_index);
1020    if (g < 0) return 0;
1021
1022    if (x0) *x0 = ttSHORT(info->data + g + 2);
1023    if (y0) *y0 = ttSHORT(info->data + g + 4);
1024    if (x1) *x1 = ttSHORT(info->data + g + 6);
1025    if (y1) *y1 = ttSHORT(info->data + g + 8);
1026    return 1;
1027 }
1028
1029 int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1)
1030 {
1031    return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1);
1032 }
1033
1034 int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index)
1035 {
1036    stbtt_int16 numberOfContours;
1037    int g = stbtt__GetGlyfOffset(info, glyph_index);
1038    if (g < 0) return 1;
1039    numberOfContours = ttSHORT(info->data + g);
1040    return numberOfContours == 0;
1041 }
1042
1043 static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off,
1044     stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy)
1045 {
1046    if (start_off) {
1047       if (was_off)
1048          stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy);
1049       stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy);
1050    } else {
1051       if (was_off)
1052          stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy);
1053       else
1054          stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0);
1055    }
1056    return num_vertices;
1057 }
1058
1059 int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
1060 {
1061    stbtt_int16 numberOfContours;
1062    stbtt_uint8 *endPtsOfContours;
1063    stbtt_uint8 *data = info->data;
1064    stbtt_vertex *vertices=0;
1065    int num_vertices=0;
1066    int g = stbtt__GetGlyfOffset(info, glyph_index);
1067
1068    *pvertices = NULL;
1069
1070    if (g < 0) return 0;
1071
1072    numberOfContours = ttSHORT(data + g);
1073
1074    if (numberOfContours > 0) {
1075       stbtt_uint8 flags=0,flagcount;
1076       stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0;
1077       stbtt_int32 x,y,cx,cy,sx,sy, scx,scy;
1078       stbtt_uint8 *points;
1079       endPtsOfContours = (data + g + 10);
1080       ins = ttUSHORT(data + g + 10 + numberOfContours * 2);
1081       points = data + g + 10 + numberOfContours * 2 + 2 + ins;
1082
1083       n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2);
1084
1085       m = n + 2*numberOfContours;  // a loose bound on how many vertices we might need
1086       vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata);
1087       if (vertices == 0)
1088          return 0;
1089
1090       next_move = 0;
1091       flagcount=0;
1092
1093       // in first pass, we load uninterpreted data into the allocated array
1094       // above, shifted to the end of the array so we won't overwrite it when
1095       // we create our final data starting from the front
1096
1097       off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated
1098
1099       // first load flags
1100
1101       for (i=0; i < n; ++i) {
1102          if (flagcount == 0) {
1103             flags = *points++;
1104             if (flags & 8)
1105                flagcount = *points++;
1106          } else
1107             --flagcount;
1108          vertices[off+i].type = flags;
1109       }
1110
1111       // now load x coordinates
1112       x=0;
1113       for (i=0; i < n; ++i) {
1114          flags = vertices[off+i].type;
1115          if (flags & 2) {
1116             stbtt_int16 dx = *points++;
1117             x += (flags & 16) ? dx : -dx; // ???
1118          } else {
1119             if (!(flags & 16)) {
1120                x = x + (stbtt_int16) (points[0]*256 + points[1]);
1121                points += 2;
1122             }
1123          }
1124          vertices[off+i].x = (stbtt_int16) x;
1125       }
1126
1127       // now load y coordinates
1128       y=0;
1129       for (i=0; i < n; ++i) {
1130          flags = vertices[off+i].type;
1131          if (flags & 4) {
1132             stbtt_int16 dy = *points++;
1133             y += (flags & 32) ? dy : -dy; // ???
1134          } else {
1135             if (!(flags & 32)) {
1136                y = y + (stbtt_int16) (points[0]*256 + points[1]);
1137                points += 2;
1138             }
1139          }
1140          vertices[off+i].y = (stbtt_int16) y;
1141       }
1142
1143       // now convert them to our format
1144       num_vertices=0;
1145       sx = sy = cx = cy = scx = scy = 0;
1146       for (i=0; i < n; ++i) {
1147          flags = vertices[off+i].type;
1148          x     = (stbtt_int16) vertices[off+i].x;
1149          y     = (stbtt_int16) vertices[off+i].y;
1150
1151          if (next_move == i) {
1152             if (i != 0)
1153                num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);
1154
1155             // now start the new one               
1156             start_off = !(flags & 1);
1157             if (start_off) {
1158                // if we start off with an off-curve point, then when we need to find a point on the curve
1159                // where we can start, and we need to save some state for when we wraparound.
1160                scx = x;
1161                scy = y;
1162                if (!(vertices[off+i+1].type & 1)) {
1163                   // next point is also a curve point, so interpolate an on-point curve
1164                   sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1;
1165                   sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1;
1166                } else {
1167                   // otherwise just use the next point as our start point
1168                   sx = (stbtt_int32) vertices[off+i+1].x;
1169                   sy = (stbtt_int32) vertices[off+i+1].y;
1170                   ++i; // we're using point i+1 as the starting point, so skip it
1171                }
1172             } else {
1173                sx = x;
1174                sy = y;
1175             }
1176             stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0);
1177             was_off = 0;
1178             next_move = 1 + ttUSHORT(endPtsOfContours+j*2);
1179             ++j;
1180          } else {
1181             if (!(flags & 1)) { // if it's a curve
1182                if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint
1183                   stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy);
1184                cx = x;
1185                cy = y;
1186                was_off = 1;
1187             } else {
1188                if (was_off)
1189                   stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy);
1190                else
1191                   stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0);
1192                was_off = 0;
1193             }
1194          }
1195       }
1196       num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);
1197    } else if (numberOfContours == -1) {
1198       // Compound shapes.
1199       int more = 1;
1200       stbtt_uint8 *comp = data + g + 10;
1201       num_vertices = 0;
1202       vertices = 0;
1203       while (more) {
1204          stbtt_uint16 flags, gidx;
1205          int comp_num_verts = 0, i;
1206          stbtt_vertex *comp_verts = 0, *tmp = 0;
1207          float mtx[6] = {1,0,0,1,0,0}, m, n;
1208          
1209          flags = ttSHORT(comp); comp+=2;
1210          gidx = ttSHORT(comp); comp+=2;
1211
1212          if (flags & 2) { // XY values
1213             if (flags & 1) { // shorts
1214                mtx[4] = ttSHORT(comp); comp+=2;
1215                mtx[5] = ttSHORT(comp); comp+=2;
1216             } else {
1217                mtx[4] = ttCHAR(comp); comp+=1;
1218                mtx[5] = ttCHAR(comp); comp+=1;
1219             }
1220          }
1221          else {
1222             // @TODO handle matching point
1223             STBTT_assert(0);
1224          }
1225          if (flags & (1<<3)) { // WE_HAVE_A_SCALE
1226             mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
1227             mtx[1] = mtx[2] = 0;
1228          } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE
1229             mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;
1230             mtx[1] = mtx[2] = 0;
1231             mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
1232          } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO
1233             mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;
1234             mtx[1] = ttSHORT(comp)/16384.0f; comp+=2;
1235             mtx[2] = ttSHORT(comp)/16384.0f; comp+=2;
1236             mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
1237          }
1238          
1239          // Find transformation scales.
1240          m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]);
1241          n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]);
1242
1243          // Get indexed glyph.
1244          comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts);
1245          if (comp_num_verts > 0) {
1246             // Transform vertices.
1247             for (i = 0; i < comp_num_verts; ++i) {
1248                stbtt_vertex* v = &comp_verts[i];
1249                stbtt_vertex_type x,y;
1250                x=v->x; y=v->y;
1251                v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));
1252                v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));
1253                x=v->cx; y=v->cy;
1254                v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));
1255                v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));
1256             }
1257             // Append vertices.
1258             tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata);
1259             if (!tmp) {
1260                if (vertices) STBTT_free(vertices, info->userdata);
1261                if (comp_verts) STBTT_free(comp_verts, info->userdata);
1262                return 0;
1263             }
1264             if (num_vertices > 0) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex));
1265             STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex));
1266             if (vertices) STBTT_free(vertices, info->userdata);
1267             vertices = tmp;
1268             STBTT_free(comp_verts, info->userdata);
1269             num_vertices += comp_num_verts;
1270          }
1271          // More components ?
1272          more = flags & (1<<5);
1273       }
1274    } else if (numberOfContours < 0) {
1275       // @TODO other compound variations?
1276       STBTT_assert(0);
1277    } else {
1278       // numberOfCounters == 0, do nothing
1279    }
1280
1281    *pvertices = vertices;
1282    return num_vertices;
1283 }
1284
1285 void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing)
1286 {
1287    stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34);
1288    if (glyph_index < numOfLongHorMetrics) {
1289       if (advanceWidth)     *advanceWidth    = ttSHORT(info->data + info->hmtx + 4*glyph_index);
1290       if (leftSideBearing)  *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2);
1291    } else {
1292       if (advanceWidth)     *advanceWidth    = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1));
1293       if (leftSideBearing)  *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics));
1294    }
1295 }
1296
1297 int  stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)
1298 {
1299    stbtt_uint8 *data = info->data + info->kern;
1300    stbtt_uint32 needle, straw;
1301    int l, r, m;
1302
1303    // we only look at the first table. it must be 'horizontal' and format 0.
1304    if (!info->kern)
1305       return 0;
1306    if (ttUSHORT(data+2) < 1) // number of tables, need at least 1
1307       return 0;
1308    if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format
1309       return 0;
1310
1311    l = 0;
1312    r = ttUSHORT(data+10) - 1;
1313    needle = glyph1 << 16 | glyph2;
1314    while (l <= r) {
1315       m = (l + r) >> 1;
1316       straw = ttULONG(data+18+(m*6)); // note: unaligned read
1317       if (needle < straw)
1318          r = m - 1;
1319       else if (needle > straw)
1320          l = m + 1;
1321       else
1322          return ttSHORT(data+22+(m*6));
1323    }
1324    return 0;
1325 }
1326
1327 int  stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2)
1328 {
1329    if (!info->kern) // if no kerning table, don't waste time looking up both codepoint->glyphs
1330       return 0;
1331    return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2));
1332 }
1333
1334 void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing)
1335 {
1336    stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing);
1337 }
1338
1339 void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap)
1340 {
1341    if (ascent ) *ascent  = ttSHORT(info->data+info->hhea + 4);
1342    if (descent) *descent = ttSHORT(info->data+info->hhea + 6);
1343    if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8);
1344 }
1345
1346 void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1)
1347 {
1348    *x0 = ttSHORT(info->data + info->head + 36);
1349    *y0 = ttSHORT(info->data + info->head + 38);
1350    *x1 = ttSHORT(info->data + info->head + 40);
1351    *y1 = ttSHORT(info->data + info->head + 42);
1352 }
1353
1354 float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height)
1355 {
1356    int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6);
1357    return (float) height / fheight;
1358 }
1359
1360 float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels)
1361 {
1362    int unitsPerEm = ttUSHORT(info->data + info->head + 18);
1363    return pixels / unitsPerEm;
1364 }
1365
1366 void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v)
1367 {
1368    STBTT_free(v, info->userdata);
1369 }
1370
1371 //////////////////////////////////////////////////////////////////////////////
1372 //
1373 // antialiasing software rasterizer
1374 //
1375
1376 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)
1377 {
1378    int x0,y0,x1,y1;
1379    if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1))
1380       x0=y0=x1=y1=0; // e.g. space character
1381    // now move to integral bboxes (treating pixels as little squares, what pixels get touched)?
1382    if (ix0) *ix0 =  STBTT_ifloor(x0 * scale_x + shift_x);
1383    if (iy0) *iy0 = -STBTT_iceil (y1 * scale_y + shift_y);
1384    if (ix1) *ix1 =  STBTT_iceil (x1 * scale_x + shift_x);
1385    if (iy1) *iy1 = -STBTT_ifloor(y0 * scale_y + shift_y);
1386 }
1387 void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1)
1388 {
1389    stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1);
1390 }
1391
1392 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)
1393 {
1394    stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1);
1395 }
1396
1397 void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1)
1398 {
1399    stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1);
1400 }
1401
1402 typedef struct stbtt__edge {
1403    float x0,y0, x1,y1;
1404    int invert;
1405 } stbtt__edge;
1406
1407 typedef struct stbtt__active_edge
1408 {
1409    int x,dx;
1410    float ey;
1411    struct stbtt__active_edge *next;
1412    int valid;
1413 } stbtt__active_edge;
1414
1415 #define FIXSHIFT   10
1416 #define FIX        (1 << FIXSHIFT)
1417 #define FIXMASK    (FIX-1)
1418
1419 static stbtt__active_edge *new_active(stbtt__edge *e, int off_x, float start_point, void *userdata)
1420 {
1421    stbtt__active_edge *z = (stbtt__active_edge *) STBTT_malloc(sizeof(*z), userdata); // @TODO: make a pool of these!!!
1422    float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);
1423    STBTT_assert(e->y0 <= start_point);
1424    if (!z) return z;
1425    // round dx down to avoid going too far
1426    if (dxdy < 0)
1427       z->dx = -STBTT_ifloor(FIX * -dxdy);
1428    else
1429       z->dx = STBTT_ifloor(FIX * dxdy);
1430    z->x = STBTT_ifloor(FIX * (e->x0 + dxdy * (start_point - e->y0)));
1431    z->x -= off_x * FIX;
1432    z->ey = e->y1;
1433    z->next = 0;
1434    z->valid = e->invert ? 1 : -1;
1435    return z;
1436 }
1437
1438 // note: this routine clips fills that extend off the edges... ideally this
1439 // wouldn't happen, but it could happen if the truetype glyph bounding boxes
1440 // are wrong, or if the user supplies a too-small bitmap
1441 static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight)
1442 {
1443    // non-zero winding fill
1444    int x0=0, w=0;
1445
1446    while (e) {
1447       if (w == 0) {
1448          // if we're currently at zero, we need to record the edge start point
1449          x0 = e->x; w += e->valid;
1450       } else {
1451          int x1 = e->x; w += e->valid;
1452          // if we went to zero, we need to draw
1453          if (w == 0) {
1454             int i = x0 >> FIXSHIFT;
1455             int j = x1 >> FIXSHIFT;
1456
1457             if (i < len && j >= 0) {
1458                if (i == j) {
1459                   // x0,x1 are the same pixel, so compute combined coverage
1460                   scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> FIXSHIFT);
1461                } else {
1462                   if (i >= 0) // add antialiasing for x0
1463                      scanline[i] = scanline[i] + (stbtt_uint8) (((FIX - (x0 & FIXMASK)) * max_weight) >> FIXSHIFT);
1464                   else
1465                      i = -1; // clip
1466
1467                   if (j < len) // add antialiasing for x1
1468                      scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & FIXMASK) * max_weight) >> FIXSHIFT);
1469                   else
1470                      j = len; // clip
1471
1472                   for (++i; i < j; ++i) // fill pixels between x0 and x1
1473                      scanline[i] = scanline[i] + (stbtt_uint8) max_weight;
1474                }
1475             }
1476          }
1477       }
1478       
1479       e = e->next;
1480    }
1481 }
1482
1483 static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)
1484 {
1485    stbtt__active_edge *active = NULL;
1486    int y,j=0;
1487    int max_weight = (255 / vsubsample);  // weight per vertical scanline
1488    int s; // vertical subsample index
1489    unsigned char scanline_data[512], *scanline;
1490
1491    if (result->w > 512)
1492       scanline = (unsigned char *) STBTT_malloc(result->w, userdata);
1493    else
1494       scanline = scanline_data;
1495
1496    y = off_y * vsubsample;
1497    e[n].y0 = (off_y + result->h) * (float) vsubsample + 1;
1498
1499    while (j < result->h) {
1500       STBTT_memset(scanline, 0, result->w);
1501       for (s=0; s < vsubsample; ++s) {
1502          // find center of pixel for this scanline
1503          float scan_y = y + 0.5f;
1504          stbtt__active_edge **step = &active;
1505
1506          // update all active edges;
1507          // remove all active edges that terminate before the center of this scanline
1508          while (*step) {
1509             stbtt__active_edge * z = *step;
1510             if (z->ey <= scan_y) {
1511                *step = z->next; // delete from list
1512                STBTT_assert(z->valid);
1513                z->valid = 0;
1514                STBTT_free(z, userdata);
1515             } else {
1516                z->x += z->dx; // advance to position for current scanline
1517                step = &((*step)->next); // advance through list
1518             }
1519          }
1520
1521          // resort the list if needed
1522          for(;;) {
1523             int changed=0;
1524             step = &active;
1525             while (*step && (*step)->next) {
1526                if ((*step)->x > (*step)->next->x) {
1527                   stbtt__active_edge *t = *step;
1528                   stbtt__active_edge *q = t->next;
1529
1530                   t->next = q->next;
1531                   q->next = t;
1532                   *step = q;
1533                   changed = 1;
1534                }
1535                step = &(*step)->next;
1536             }
1537             if (!changed) break;
1538          }
1539
1540          // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline
1541          while (e->y0 <= scan_y) {
1542             if (e->y1 > scan_y) {
1543                stbtt__active_edge *z = new_active(e, off_x, scan_y, userdata);
1544                // find insertion point
1545                if (active == NULL)
1546                   active = z;
1547                else if (z->x < active->x) {
1548                   // insert at front
1549                   z->next = active;
1550                   active = z;
1551                } else {
1552                   // find thing to insert AFTER
1553                   stbtt__active_edge *p = active;
1554                   while (p->next && p->next->x < z->x)
1555                      p = p->next;
1556                   // at this point, p->next->x is NOT < z->x
1557                   z->next = p->next;
1558                   p->next = z;
1559                }
1560             }
1561             ++e;
1562          }
1563
1564          // now process all active edges in XOR fashion
1565          if (active)
1566             stbtt__fill_active_edges(scanline, result->w, active, max_weight);
1567
1568          ++y;
1569       }
1570       STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w);
1571       ++j;
1572    }
1573
1574    while (active) {
1575       stbtt__active_edge *z = active;
1576       active = active->next;
1577       STBTT_free(z, userdata);
1578    }
1579
1580    if (scanline != scanline_data)
1581       STBTT_free(scanline, userdata);
1582 }
1583
1584 static int stbtt__edge_compare(const void *p, const void *q)
1585 {
1586    stbtt__edge *a = (stbtt__edge *) p;
1587    stbtt__edge *b = (stbtt__edge *) q;
1588
1589    if (a->y0 < b->y0) return -1;
1590    if (a->y0 > b->y0) return  1;
1591    return 0;
1592 }
1593
1594 typedef struct
1595 {
1596    float x,y;
1597 } stbtt__point;
1598
1599 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)
1600 {
1601    float y_scale_inv = invert ? -scale_y : scale_y;
1602    stbtt__edge *e;
1603    int n,i,j,k,m;
1604    int vsubsample = result->h < 8 ? 15 : 5;
1605    // vsubsample should divide 255 evenly; otherwise we won't reach full opacity
1606
1607    // now we have to blow out the windings into explicit edge lists
1608    n = 0;
1609    for (i=0; i < windings; ++i)
1610       n += wcount[i];
1611
1612    e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel
1613    if (e == 0) return;
1614    n = 0;
1615
1616    m=0;
1617    for (i=0; i < windings; ++i) {
1618       stbtt__point *p = pts + m;
1619       m += wcount[i];
1620       j = wcount[i]-1;
1621       for (k=0; k < wcount[i]; j=k++) {
1622          int a=k,b=j;
1623          // skip the edge if horizontal
1624          if (p[j].y == p[k].y)
1625             continue;
1626          // add edge from j to k to the list
1627          e[n].invert = 0;
1628          if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) {
1629             e[n].invert = 1;
1630             a=j,b=k;
1631          }
1632          e[n].x0 = p[a].x * scale_x + shift_x;
1633          e[n].y0 = p[a].y * y_scale_inv * vsubsample + shift_y;
1634          e[n].x1 = p[b].x * scale_x + shift_x;
1635          e[n].y1 = p[b].y * y_scale_inv * vsubsample + shift_y;
1636          ++n;
1637       }
1638    }
1639
1640    // now sort the edges by their highest point (should snap to integer, and then by x)
1641    STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare);
1642
1643    // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule
1644    stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata);
1645
1646    STBTT_free(e, userdata);
1647 }
1648
1649 static void stbtt__add_point(stbtt__point *points, int n, float x, float y)
1650 {
1651    if (!points) return; // during first pass, it's unallocated
1652    points[n].x = x;
1653    points[n].y = y;
1654 }
1655
1656 // tesselate until threshhold p is happy... @TODO warped to compensate for non-linear stretching
1657 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)
1658 {
1659    // midpoint
1660    float mx = (x0 + 2*x1 + x2)/4;
1661    float my = (y0 + 2*y1 + y2)/4;
1662    // versus directly drawn line
1663    float dx = (x0+x2)/2 - mx;
1664    float dy = (y0+y2)/2 - my;
1665    if (n > 16) // 65536 segments on one curve better be enough!
1666       return 1;
1667    if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA
1668       stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1);
1669       stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1);
1670    } else {
1671       stbtt__add_point(points, *num_points,x2,y2);
1672       *num_points = *num_points+1;
1673    }
1674    return 1;
1675 }
1676
1677 // returns number of contours
1678 stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata)
1679 {
1680    stbtt__point *points=0;
1681    int num_points=0;
1682
1683    float objspace_flatness_squared = objspace_flatness * objspace_flatness;
1684    int i,n=0,start=0, pass;
1685
1686    // count how many "moves" there are to get the contour count
1687    for (i=0; i < num_verts; ++i)
1688       if (vertices[i].type == STBTT_vmove)
1689          ++n;
1690
1691    *num_contours = n;
1692    if (n == 0) return 0;
1693
1694    *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata);
1695
1696    if (*contour_lengths == 0) {
1697       *num_contours = 0;
1698       return 0;
1699    }
1700
1701    // make two passes through the points so we don't need to realloc
1702    for (pass=0; pass < 2; ++pass) {
1703       float x=0,y=0;
1704       if (pass == 1) {
1705          points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata);
1706          if (points == NULL) goto error;
1707       }
1708       num_points = 0;
1709       n= -1;
1710       for (i=0; i < num_verts; ++i) {
1711          switch (vertices[i].type) {
1712             case STBTT_vmove:
1713                // start the next contour
1714                if (n >= 0)
1715                   (*contour_lengths)[n] = num_points - start;
1716                ++n;
1717                start = num_points;
1718
1719                x = vertices[i].x, y = vertices[i].y;
1720                stbtt__add_point(points, num_points++, x,y);
1721                break;
1722             case STBTT_vline:
1723                x = vertices[i].x, y = vertices[i].y;
1724                stbtt__add_point(points, num_points++, x, y);
1725                break;
1726             case STBTT_vcurve:
1727                stbtt__tesselate_curve(points, &num_points, x,y,
1728                                         vertices[i].cx, vertices[i].cy,
1729                                         vertices[i].x,  vertices[i].y,
1730                                         objspace_flatness_squared, 0);
1731                x = vertices[i].x, y = vertices[i].y;
1732                break;
1733          }
1734       }
1735       (*contour_lengths)[n] = num_points - start;
1736    }
1737
1738    return points;
1739 error:
1740    STBTT_free(points, userdata);
1741    STBTT_free(*contour_lengths, userdata);
1742    *contour_lengths = 0;
1743    *num_contours = 0;
1744    return NULL;
1745 }
1746
1747 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)
1748 {
1749    float scale = scale_x > scale_y ? scale_y : scale_x;
1750    int winding_count, *winding_lengths;
1751    stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata);
1752    if (windings) {
1753       stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata);
1754       STBTT_free(winding_lengths, userdata);
1755       STBTT_free(windings, userdata);
1756    }
1757 }
1758
1759 void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata)
1760 {
1761    STBTT_free(bitmap, userdata);
1762 }
1763
1764 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)
1765 {
1766    int ix0,iy0,ix1,iy1;
1767    stbtt__bitmap gbm;
1768    stbtt_vertex *vertices;   
1769    int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
1770
1771    if (scale_x == 0) scale_x = scale_y;
1772    if (scale_y == 0) {
1773       if (scale_x == 0) return NULL;
1774       scale_y = scale_x;
1775    }
1776
1777    stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1);
1778
1779    // now we get the size
1780    gbm.w = (ix1 - ix0);
1781    gbm.h = (iy1 - iy0);
1782    gbm.pixels = NULL; // in case we error
1783
1784    if (width ) *width  = gbm.w;
1785    if (height) *height = gbm.h;
1786    if (xoff  ) *xoff   = ix0;
1787    if (yoff  ) *yoff   = iy0;
1788    
1789    if (gbm.w && gbm.h) {
1790       gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata);
1791       if (gbm.pixels) {
1792          gbm.stride = gbm.w;
1793
1794          stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata);
1795       }
1796    }
1797    STBTT_free(vertices, info->userdata);
1798    return gbm.pixels;
1799 }   
1800
1801 unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff)
1802 {
1803    return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff);
1804 }
1805
1806 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)
1807 {
1808    int ix0,iy0;
1809    stbtt_vertex *vertices;
1810    int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
1811    stbtt__bitmap gbm;   
1812
1813    stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0);
1814    gbm.pixels = output;
1815    gbm.w = out_w;
1816    gbm.h = out_h;
1817    gbm.stride = out_stride;
1818
1819    if (gbm.w && gbm.h)
1820       stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata);
1821
1822    STBTT_free(vertices, info->userdata);
1823 }
1824
1825 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)
1826 {
1827    stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph);
1828 }
1829
1830 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)
1831 {
1832    return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff);
1833 }   
1834
1835 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)
1836 {
1837    stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint));
1838 }
1839
1840 unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff)
1841 {
1842    return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff);
1843 }   
1844
1845 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)
1846 {
1847    stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint);
1848 }
1849
1850 //////////////////////////////////////////////////////////////////////////////
1851 //
1852 // bitmap baking
1853 //
1854 // This is SUPER-CRAPPY packing to keep source code small
1855
1856 extern int stbtt_BakeFontBitmap(const unsigned char *data, int offset,  // font location (use offset=0 for plain .ttf)
1857                                 float pixel_height,                     // height of font in pixels
1858                                 unsigned char *pixels, int pw, int ph,  // bitmap to be filled in
1859                                 int first_char, int num_chars,          // characters to bake
1860                                 stbtt_bakedchar *chardata)
1861 {
1862    float scale;
1863    int x,y,bottom_y, i;
1864    stbtt_fontinfo f;
1865    stbtt_InitFont(&f, data, offset);
1866    STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels
1867    x=y=1;
1868    bottom_y = 1;
1869
1870    scale = stbtt_ScaleForPixelHeight(&f, pixel_height);
1871
1872    for (i=0; i < num_chars; ++i) {
1873       int advance, lsb, x0,y0,x1,y1,gw,gh;
1874       int g = stbtt_FindGlyphIndex(&f, first_char + i);
1875       stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb);
1876       stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1);
1877       gw = x1-x0;
1878       gh = y1-y0;
1879       if (x + gw + 1 >= pw)
1880          y = bottom_y, x = 1; // advance to next row
1881       if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row
1882          return -i;
1883       STBTT_assert(x+gw < pw);
1884       STBTT_assert(y+gh < ph);
1885       stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g);
1886       chardata[i].x0 = (stbtt_int16) x;
1887       chardata[i].y0 = (stbtt_int16) y;
1888       chardata[i].x1 = (stbtt_int16) (x + gw);
1889       chardata[i].y1 = (stbtt_int16) (y + gh);
1890       chardata[i].xadvance = scale * advance;
1891       chardata[i].xoff     = (float) x0;
1892       chardata[i].yoff     = (float) y0;
1893       x = x + gw + 2;
1894       if (y+gh+2 > bottom_y)
1895          bottom_y = y+gh+2;
1896    }
1897    return bottom_y;
1898 }
1899
1900 void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule)
1901 {
1902    float d3d_bias = opengl_fillrule ? 0 : -0.5f;
1903    float ipw = 1.0f / pw, iph = 1.0f / ph;
1904    stbtt_bakedchar *b = chardata + char_index;
1905    int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5);
1906    int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5);
1907
1908    q->x0 = round_x + d3d_bias;
1909    q->y0 = round_y + d3d_bias;
1910    q->x1 = round_x + b->x1 - b->x0 + d3d_bias;
1911    q->y1 = round_y + b->y1 - b->y0 + d3d_bias;
1912
1913    q->s0 = b->x0 * ipw;
1914    q->t0 = b->y0 * iph;
1915    q->s1 = b->x1 * ipw;
1916    q->t1 = b->y1 * iph;
1917
1918    *xpos += b->xadvance;
1919 }
1920
1921 //////////////////////////////////////////////////////////////////////////////
1922 //
1923 // font name matching -- recommended not to use this
1924 //
1925
1926 // check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string
1927 static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(const stbtt_uint8 *s1, stbtt_int32 len1, const stbtt_uint8 *s2, stbtt_int32 len2) 
1928 {
1929    stbtt_int32 i=0;
1930
1931    // convert utf16 to utf8 and compare the results while converting
1932    while (len2) {
1933       stbtt_uint16 ch = s2[0]*256 + s2[1];
1934       if (ch < 0x80) {
1935          if (i >= len1) return -1;
1936          if (s1[i++] != ch) return -1;
1937       } else if (ch < 0x800) {
1938          if (i+1 >= len1) return -1;
1939          if (s1[i++] != 0xc0 + (ch >> 6)) return -1;
1940          if (s1[i++] != 0x80 + (ch & 0x3f)) return -1;
1941       } else if (ch >= 0xd800 && ch < 0xdc00) {
1942          stbtt_uint32 c;
1943          stbtt_uint16 ch2 = s2[2]*256 + s2[3];
1944          if (i+3 >= len1) return -1;
1945          c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000;
1946          if (s1[i++] != 0xf0 + (c >> 18)) return -1;
1947          if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1;
1948          if (s1[i++] != 0x80 + ((c >>  6) & 0x3f)) return -1;
1949          if (s1[i++] != 0x80 + ((c      ) & 0x3f)) return -1;
1950          s2 += 2; // plus another 2 below
1951          len2 -= 2;
1952       } else if (ch >= 0xdc00 && ch < 0xe000) {
1953          return -1;
1954       } else {
1955          if (i+2 >= len1) return -1;
1956          if (s1[i++] != 0xe0 + (ch >> 12)) return -1;
1957          if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1;
1958          if (s1[i++] != 0x80 + ((ch     ) & 0x3f)) return -1;
1959       }
1960       s2 += 2;
1961       len2 -= 2;
1962    }
1963    return i;
1964 }
1965
1966 int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2) 
1967 {
1968    return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((const stbtt_uint8*) s1, len1, (const stbtt_uint8*) s2, len2);
1969 }
1970
1971 // returns results in whatever encoding you request... but note that 2-byte encodings
1972 // will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare
1973 const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID)
1974 {
1975    stbtt_int32 i,count,stringOffset;
1976    stbtt_uint8 *fc = font->data;
1977    stbtt_uint32 offset = font->fontstart;
1978    stbtt_uint32 nm = stbtt__find_table(fc, offset, "name");
1979    if (!nm) return NULL;
1980
1981    count = ttUSHORT(fc+nm+2);
1982    stringOffset = nm + ttUSHORT(fc+nm+4);
1983    for (i=0; i < count; ++i) {
1984       stbtt_uint32 loc = nm + 6 + 12 * i;
1985       if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2)
1986           && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) {
1987          *length = ttUSHORT(fc+loc+8);
1988          return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10));
1989       }
1990    }
1991    return NULL;
1992 }
1993
1994 static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id)
1995 {
1996    stbtt_int32 i;
1997    stbtt_int32 count = ttUSHORT(fc+nm+2);
1998    stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4);
1999
2000    for (i=0; i < count; ++i) {
2001       stbtt_uint32 loc = nm + 6 + 12 * i;
2002       stbtt_int32 id = ttUSHORT(fc+loc+6);
2003       if (id == target_id) {
2004          // find the encoding
2005          stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4);
2006
2007          // is this a Unicode encoding?
2008          if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) {
2009             stbtt_int32 slen = ttUSHORT(fc+loc+8);
2010             stbtt_int32 off = ttUSHORT(fc+loc+10);
2011
2012             // check if there's a prefix match
2013             stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen);
2014             if (matchlen >= 0) {
2015                // check for target_id+1 immediately following, with same encoding & language
2016                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) {
2017                   slen = ttUSHORT(fc+loc+12+8);
2018                   off = ttUSHORT(fc+loc+12+10);
2019                   if (slen == 0) {
2020                      if (matchlen == nlen)
2021                         return 1;
2022                   } else if (matchlen < nlen && name[matchlen] == ' ') {
2023                      ++matchlen;
2024                      if (stbtt_CompareUTF8toUTF16_bigendian((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen))
2025                         return 1;
2026                   }
2027                } else {
2028                   // if nothing immediately following
2029                   if (matchlen == nlen)
2030                      return 1;
2031                }
2032             }
2033          }
2034
2035          // @TODO handle other encodings
2036       }
2037    }
2038    return 0;
2039 }
2040
2041 static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags)
2042 {
2043    stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name);
2044    stbtt_uint32 nm,hd;
2045    if (!stbtt__isfont(fc+offset)) return 0;
2046
2047    // check italics/bold/underline flags in macStyle...
2048    if (flags) {
2049       hd = stbtt__find_table(fc, offset, "head");
2050       if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0;
2051    }
2052
2053    nm = stbtt__find_table(fc, offset, "name");
2054    if (!nm) return 0;
2055
2056    if (flags) {
2057       // if we checked the macStyle flags, then just check the family and ignore the subfamily
2058       if (stbtt__matchpair(fc, nm, name, nlen, 16, -1))  return 1;
2059       if (stbtt__matchpair(fc, nm, name, nlen,  1, -1))  return 1;
2060       if (stbtt__matchpair(fc, nm, name, nlen,  3, -1))  return 1;
2061    } else {
2062       if (stbtt__matchpair(fc, nm, name, nlen, 16, 17))  return 1;
2063       if (stbtt__matchpair(fc, nm, name, nlen,  1,  2))  return 1;
2064       if (stbtt__matchpair(fc, nm, name, nlen,  3, -1))  return 1;
2065    }
2066
2067    return 0;
2068 }
2069
2070 int stbtt_FindMatchingFont(const unsigned char *font_collection, const char *name_utf8, stbtt_int32 flags)
2071 {
2072    stbtt_int32 i;
2073    for (i=0;;++i) {
2074       stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i);
2075       if (off < 0) return off;
2076       if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags))
2077          return off;
2078    }
2079 }
2080
2081 #endif // STB_TRUETYPE_IMPLEMENTATION

UCC git Repository :: git.ucc.asn.au