stb_truetype.h
This file
Path
stb_truetype.h
5,079 lines · 194.5 KiB · C
Last changed by
Merge branch 'master' into workingSean Barrettbefore adoption6e9f34d
History of this fileTake it
1// stb_truetype.h - v1.26 - public domain2// authored from 2009-2021 by Sean Barrett / RAD Game Tools3//4// =======================================================================5//6// NO SECURITY GUARANTEE -- DO NOT USE THIS ON UNTRUSTED FONT FILES7//8// This library does no range checking of the offsets found in the file,9// meaning an attacker can use it to read arbitrary memory.10//11// =======================================================================12//13// This library processes TrueType files:14// parse files15// extract glyph metrics16// extract glyph shapes17// render glyphs to one-channel bitmaps with antialiasing (box filter)18// render glyphs to one-channel SDF bitmaps (signed-distance field/function)19//20// Todo:21// non-MS cmaps22// crashproof on bad data23// hinting? (no longer patented)24// cleartype-style AA?25// optimize: use simple memory allocator for intermediates26// optimize: build edge-list directly from curves27// optimize: rasterize directly from curves?28//29// ADDITIONAL CONTRIBUTORS30//31// Mikko Mononen: compound shape support, more cmap formats32// Tor Andersson: kerning, subpixel rendering33// Dougall Johnson: OpenType / Type 2 font handling34// Daniel Ribeiro Maciel: basic GPOS-based kerning35//36// Misc other:37// Ryan Gordon38// Simon Glass39// github:IntellectualKitty40// Imanol Celaya41// Daniel Ribeiro Maciel42//43// Bug/warning reports/fixes:44// "Zer" on mollyrocket Fabian "ryg" Giesen github:NiLuJe45// Cass Everitt Martins Mozeiko github:aloucks46// stoiko (Haemimont Games) Cap Petschulat github:oyvindjam47// Brian Hook Omar Cornut github:vassvik48// Walter van Niftrik Ryan Griege49// David Gow Peter LaValle50// David Given Sergey Popov51// Ivan-Assen Ivanov Giumo X. Clanjor52// Anthony Pesch Higor Euripedes53// Johan Duparc Thomas Fields54// Hou Qiming Derek Vinyard55// Rob Loach Cort Stratton56// Kenney Phillis Jr. Brian Costabile57// Ken Voskuil (kaesve) Yakov Galka58//59// VERSION HISTORY60//61// 1.26 (2021-08-28) fix broken rasterizer62// 1.25 (2021-07-11) many fixes63// 1.24 (2020-02-05) fix warning64// 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS)65// 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined66// 1.21 (2019-02-25) fix warning67// 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics()68// 1.19 (2018-02-11) GPOS kerning, STBTT_fmod69// 1.18 (2018-01-29) add missing function70// 1.17 (2017-07-23) make more arguments const; doc fix71// 1.16 (2017-07-12) SDF support72// 1.15 (2017-03-03) make more arguments const73// 1.14 (2017-01-16) num-fonts-in-TTC function74// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts75// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual76// 1.11 (2016-04-02) fix unused-variable warning77// 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef78// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly79// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges80// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;81// variant PackFontRanges to pack and render in separate phases;82// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);83// fixed an assert() bug in the new rasterizer84// replace assert() with STBTT_assert() in new rasterizer85//86// Full history can be found at the end of this file.87//88// LICENSE89//90// See end of file for license information.91//92// USAGE93//94// Include this file in whatever places need to refer to it. In ONE C/C++95// file, write:96// #define STB_TRUETYPE_IMPLEMENTATION97// before the #include of this file. This expands out the actual98// implementation into that C/C++ file.99//100// To make the implementation private to the file that generates the implementation,101// #define STBTT_STATIC102//103// Simple 3D API (don't ship this, but it's fine for tools and quick start)104// stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture105// stbtt_GetBakedQuad() -- compute quad to draw for a given char106//107// Improved 3D API (more shippable):108// #include "stb_rect_pack.h" -- optional, but you really want it109// stbtt_PackBegin()110// stbtt_PackSetOversampling() -- for improved quality on small fonts111// stbtt_PackFontRanges() -- pack and renders112// stbtt_PackEnd()113// stbtt_GetPackedQuad()114//115// "Load" a font file from a memory buffer (you have to keep the buffer loaded)116// stbtt_InitFont()117// stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections118// stbtt_GetNumberOfFonts() -- number of fonts for TTC font collections119//120// Render a unicode codepoint to a bitmap121// stbtt_GetCodepointBitmap() -- allocates and returns a bitmap122// stbtt_MakeCodepointBitmap() -- renders into bitmap you provide123// stbtt_GetCodepointBitmapBox() -- how big the bitmap must be124//125// Character advance/positioning126// stbtt_GetCodepointHMetrics()127// stbtt_GetFontVMetrics()128// stbtt_GetFontVMetricsOS2()129// stbtt_GetCodepointKernAdvance()130//131// Starting with version 1.06, the rasterizer was replaced with a new,132// faster and generally-more-precise rasterizer. The new rasterizer more133// accurately measures pixel coverage for anti-aliasing, except in the case134// where multiple shapes overlap, in which case it overestimates the AA pixel135// coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If136// this turns out to be a problem, you can re-enable the old rasterizer with137// #define STBTT_RASTERIZER_VERSION 1138// which will incur about a 15% speed hit.139//140// ADDITIONAL DOCUMENTATION141//142// Immediately after this block comment are a series of sample programs.143//144// After the sample programs is the "header file" section. This section145// includes documentation for each API function.146//147// Some important concepts to understand to use this library:148//149// Codepoint150// Characters are defined by unicode codepoints, e.g. 65 is151// uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is152// the hiragana for "ma".153//154// Glyph155// A visual character shape (every codepoint is rendered as156// some glyph)157//158// Glyph index159// A font-specific integer ID representing a glyph160//161// Baseline162// Glyph shapes are defined relative to a baseline, which is the163// bottom of uppercase characters. Characters extend both above164// and below the baseline.165//166// Current Point167// As you draw text to the screen, you keep track of a "current point"168// which is the origin of each character. The current point's vertical169// position is the baseline. Even "baked fonts" use this model.170//171// Vertical Font Metrics172// The vertical qualities of the font, used to vertically position173// and space the characters. See docs for stbtt_GetFontVMetrics.174//175// Font Size in Pixels or Points176// The preferred interface for specifying font sizes in stb_truetype177// is to specify how tall the font's vertical extent should be in pixels.178// If that sounds good enough, skip the next paragraph.179//180// Most font APIs instead use "points", which are a common typographic181// measurement for describing font size, defined as 72 points per inch.182// stb_truetype provides a point API for compatibility. However, true183// "per inch" conventions don't make much sense on computer displays184// since different monitors have different number of pixels per185// inch. For example, Windows traditionally uses a convention that186// there are 96 pixels per inch, thus making 'inch' measurements have187// nothing to do with inches, and thus effectively defining a point to188// be 1.333 pixels. Additionally, the TrueType font data provides189// an explicit scale factor to scale a given font's glyphs to points,190// but the author has observed that this scale factor is often wrong191// for non-commercial fonts, thus making fonts scaled in points192// according to the TrueType spec incoherently sized in practice.193//194// DETAILED USAGE:195//196// Scale:197// Select how high you want the font to be, in points or pixels.198// Call ScaleForPixelHeight or ScaleForMappingEmToPixels to compute199// a scale factor SF that will be used by all other functions.200//201// Baseline:202// You need to select a y-coordinate that is the baseline of where203// your text will appear. Call GetFontBoundingBox to get the baseline-relative204// bounding box for all characters. SF*-y0 will be the distance in pixels205// that the worst-case character could extend above the baseline, so if206// you want the top edge of characters to appear at the top of the207// screen where y=0, then you would set the baseline to SF*-y0.208//209// Current point:210// Set the current point where the first character will appear. The211// first character could extend left of the current point; this is font212// dependent. You can either choose a current point that is the leftmost213// point and hope, or add some padding, or check the bounding box or214// left-side-bearing of the first character to be displayed and set215// the current point based on that.216//217// Displaying a character:218// Compute the bounding box of the character. It will contain signed values219// relative to <current_point, baseline>. I.e. if it returns x0,y0,x1,y1,220// then the character should be displayed in the rectangle from221// <current_point+SF*x0, baseline+SF*y0> to <current_point+SF*x1,baseline+SF*y1).222//223// Advancing for the next character:224// Call GlyphHMetrics, and compute 'current_point += SF * advance'.225//226//227// ADVANCED USAGE228//229// Quality:230//231// - Use the functions with Subpixel at the end to allow your characters232// to have subpixel positioning. Since the font is anti-aliased, not233// hinted, this is very import for quality. (This is not possible with234// baked fonts.)235//236// - Kerning is now supported, and if you're supporting subpixel rendering237// then kerning is worth using to give your text a polished look.238//239// Performance:240//241// - Convert Unicode codepoints to glyph indexes and operate on the glyphs;242// if you don't do this, stb_truetype is forced to do the conversion on243// every call.244//245// - There are a lot of memory allocations. We should modify it to take246// a temp buffer and allocate from the temp buffer (without freeing),247// should help performance a lot.248//249// NOTES250//251// The system uses the raw data found in the .ttf file without changing it252// and without building auxiliary data structures. This is a bit inefficient253// on little-endian systems (the data is big-endian), but assuming you're254// caching the bitmaps or glyph shapes this shouldn't be a big deal.255//256// It appears to be very hard to programmatically determine what font a257// given file is in a general way. I provide an API for this, but I don't258// recommend it.259//260//261// PERFORMANCE MEASUREMENTS FOR 1.06:262//263// 32-bit 64-bit264// Previous release: 8.83 s 7.68 s265// Pool allocations: 7.72 s 6.34 s266// Inline sort : 6.54 s 5.65 s267// New rasterizer : 5.63 s 5.00 s268269//////////////////////////////////////////////////////////////////////////////270//////////////////////////////////////////////////////////////////////////////271////272//// SAMPLE PROGRAMS273////274//275// Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless.276// See "tests/truetype_demo_win32.c" for a complete version.277#if 0278#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation279#include "stb_truetype.h"280281unsigned char ttf_buffer[1<<20];282unsigned char temp_bitmap[512*512];283284stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs285GLuint ftex;286287void my_stbtt_initfont(void)288{289 fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb"));290 stbtt_BakeFontBitmap(ttf_buffer,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits!291 // can free ttf_buffer at this point292 glGenTextures(1, &ftex);293 glBindTexture(GL_TEXTURE_2D, ftex);294 glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap);295 // can free temp_bitmap at this point296 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);297}298299void my_stbtt_print(float x, float y, char *text)300{301 // assume orthographic projection with units = screen pixels, origin at top left302 glEnable(GL_BLEND);303 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);304 glEnable(GL_TEXTURE_2D);305 glBindTexture(GL_TEXTURE_2D, ftex);306 glBegin(GL_QUADS);307 while (*text) {308 if (*text >= 32 && *text < 128) {309 stbtt_aligned_quad q;310 stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9311 glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y0);312 glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y0);313 glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y1);314 glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y1);315 }316 ++text;317 }318 glEnd();319}320#endif321//322//323//////////////////////////////////////////////////////////////////////////////324//325// Complete program (this compiles): get a single bitmap, print as ASCII art326//327#if 0328#include <stdio.h>329#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation330#include "stb_truetype.h"331332char ttf_buffer[1<<25];333334int main(int argc, char **argv)335{336 stbtt_fontinfo font;337 unsigned char *bitmap;338 int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20);339340 fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb"));341342 stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0));343 bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0);344345 for (j=0; j < h; ++j) {346 for (i=0; i < w; ++i)347 putchar(" .:ioVM@"[bitmap[j*w+i]>>5]);348 putchar('\n');349 }350 return 0;351}352#endif353//354// Output:355//356// .ii.357// @@@@@@.358// V@Mio@@o359// :i. V@V360// :oM@@M361// :@@@MM@M362// @@o o@M363// :@@. M@M364// @@@o@@@@365// :M@@V:@@.366//367//////////////////////////////////////////////////////////////////////////////368//369// Complete program: print "Hello World!" banner, with bugs370//371#if 0372char buffer[24<<20];373unsigned char screen[20][79];374375int main(int arg, char **argv)376{377 stbtt_fontinfo font;378 int i,j,ascent,baseline,ch=0;379 float scale, xpos=2; // leave a little padding in case the character extends left380 char *text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness381382 fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb"));383 stbtt_InitFont(&font, buffer, 0);384385 scale = stbtt_ScaleForPixelHeight(&font, 15);386 stbtt_GetFontVMetrics(&font, &ascent,0,0);387 baseline = (int) (ascent*scale);388389 while (text[ch]) {390 int advance,lsb,x0,y0,x1,y1;391 float x_shift = xpos - (float) floor(xpos);392 stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb);393 stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1);394 stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]);395 // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong396 // because this API is really for baking character bitmaps into textures. if you want to render397 // a sequence of characters, you really need to render each bitmap to a temp buffer, then398 // "alpha blend" that into the working buffer399 xpos += (advance * scale);400 if (text[ch+1])401 xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]);402 ++ch;403 }404405 for (j=0; j < 20; ++j) {406 for (i=0; i < 78; ++i)407 putchar(" .:ioVM@"[screen[j][i]>>5]);408 putchar('\n');409 }410411 return 0;412}413#endif414415416//////////////////////////////////////////////////////////////////////////////417//////////////////////////////////////////////////////////////////////////////418////419//// INTEGRATION WITH YOUR CODEBASE420////421//// The following sections allow you to supply alternate definitions422//// of C library functions used by stb_truetype, e.g. if you don't423//// link with the C runtime library.424425#ifdef STB_TRUETYPE_IMPLEMENTATION426 // #define your own (u)stbtt_int8/16/32 before including to override this427 #ifndef stbtt_uint8428 typedef unsigned char stbtt_uint8;429 typedef signed char stbtt_int8;430 typedef unsigned short stbtt_uint16;431 typedef signed short stbtt_int16;432 typedef unsigned int stbtt_uint32;433 typedef signed int stbtt_int32;434 #endif435436 typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1];437 typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1];438439 // e.g. #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h440 #ifndef STBTT_ifloor441 #include <math.h>442 #define STBTT_ifloor(x) ((int) floor(x))443 #define STBTT_iceil(x) ((int) ceil(x))444 #endif445446 #ifndef STBTT_sqrt447 #include <math.h>448 #define STBTT_sqrt(x) sqrt(x)449 #define STBTT_pow(x,y) pow(x,y)450 #endif451452 #ifndef STBTT_fmod453 #include <math.h>454 #define STBTT_fmod(x,y) fmod(x,y)455 #endif456457 #ifndef STBTT_cos458 #include <math.h>459 #define STBTT_cos(x) cos(x)460 #define STBTT_acos(x) acos(x)461 #endif462463 #ifndef STBTT_fabs464 #include <math.h>465 #define STBTT_fabs(x) fabs(x)466 #endif467468 // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h469 #ifndef STBTT_malloc470 #include <stdlib.h>471 #define STBTT_malloc(x,u) ((void)(u),malloc(x))472 #define STBTT_free(x,u) ((void)(u),free(x))473 #endif474475 #ifndef STBTT_assert476 #include <assert.h>477 #define STBTT_assert(x) assert(x)478 #endif479480 #ifndef STBTT_strlen481 #include <string.h>482 #define STBTT_strlen(x) strlen(x)483 #endif484485 #ifndef STBTT_memcpy486 #include <string.h>487 #define STBTT_memcpy memcpy488 #define STBTT_memset memset489 #endif490#endif491492///////////////////////////////////////////////////////////////////////////////493///////////////////////////////////////////////////////////////////////////////494////495//// INTERFACE496////497////498499#ifndef __STB_INCLUDE_STB_TRUETYPE_H__500#define __STB_INCLUDE_STB_TRUETYPE_H__501502#ifdef STBTT_STATIC503#define STBTT_DEF static504#else505#define STBTT_DEF extern506#endif507508#ifdef __cplusplus509extern "C" {510#endif511512// private structure513typedef struct514{515 unsigned char *data;516 int cursor;517 int size;518} stbtt__buf;519520//////////////////////////////////////////////////////////////////////////////521//522// TEXTURE BAKING API523//524// If you use this API, you only have to call two functions ever.525//526527typedef struct528{529 unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap530 float xoff,yoff,xadvance;531} stbtt_bakedchar;532533STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf)534 float pixel_height, // height of font in pixels535 unsigned char *pixels, int pw, int ph, // bitmap to be filled in536 int first_char, int num_chars, // characters to bake537 stbtt_bakedchar *chardata); // you allocate this, it's num_chars long538// if return is positive, the first unused row of the bitmap539// if return is negative, returns the negative of the number of characters that fit540// if return is 0, no characters fit and no rows were used541// This uses a very crappy packing.542543typedef struct544{545 float x0,y0,s0,t0; // top-left546 float x1,y1,s1,t1; // bottom-right547} stbtt_aligned_quad;548549STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, // same data as above550 int char_index, // character to display551 float *xpos, float *ypos, // pointers to current position in screen pixel space552 stbtt_aligned_quad *q, // output: quad to draw553 int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier554// Call GetBakedQuad with char_index = 'character - first_char', and it555// creates the quad you need to draw and advances the current position.556//557// The coordinate system used assumes y increases downwards.558//559// Characters will extend both above and below the current position;560// see discussion of "BASELINE" above.561//562// It's inefficient; you might want to c&p it and optimize it.563564STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap);565// Query the font vertical metrics without having to create a font first.566567568//////////////////////////////////////////////////////////////////////////////569//570// NEW TEXTURE BAKING API571//572// This provides options for packing multiple fonts into one atlas, not573// perfectly but better than nothing.574575typedef struct576{577 unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap578 float xoff,yoff,xadvance;579 float xoff2,yoff2;580} stbtt_packedchar;581582typedef struct stbtt_pack_context stbtt_pack_context;583typedef struct stbtt_fontinfo stbtt_fontinfo;584#ifndef STB_RECT_PACK_VERSION585typedef struct stbrp_rect stbrp_rect;586#endif587588STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context);589// Initializes a packing context stored in the passed-in stbtt_pack_context.590// Future calls using this context will pack characters into the bitmap passed591// in here: a 1-channel bitmap that is width * height. stride_in_bytes is592// the distance from one row to the next (or 0 to mean they are packed tightly593// together). "padding" is the amount of padding to leave between each594// character (normally you want '1' for bitmaps you'll use as textures with595// bilinear filtering).596//597// Returns 0 on failure, 1 on success.598599STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc);600// Cleans up the packing context and frees all memory.601602#define STBTT_POINT_SIZE(x) (-(x))603604STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size,605 int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range);606// Creates character bitmaps from the font_index'th font found in fontdata (use607// font_index=0 if you don't know what that is). It creates num_chars_in_range608// bitmaps for characters with unicode values starting at first_unicode_char_in_range609// and increasing. Data for how to render them is stored in chardata_for_range;610// pass these to stbtt_GetPackedQuad to get back renderable quads.611//612// font_size is the full height of the character from ascender to descender,613// as computed by stbtt_ScaleForPixelHeight. To use a point size as computed614// by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE()615// and pass that result as 'font_size':616// ..., 20 , ... // font max minus min y is 20 pixels tall617// ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall618619typedef struct620{621 float font_size;622 int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint623 int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints624 int num_chars;625 stbtt_packedchar *chardata_for_range; // output626 unsigned char h_oversample, v_oversample; // don't set these, they're used internally627} stbtt_pack_range;628629STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges);630// Creates character bitmaps from multiple ranges of characters stored in631// ranges. This will usually create a better-packed bitmap than multiple632// calls to stbtt_PackFontRange. Note that you can call this multiple633// times within a single PackBegin/PackEnd.634635STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample);636// Oversampling a font increases the quality by allowing higher-quality subpixel637// positioning, and is especially valuable at smaller text sizes.638//639// This function sets the amount of oversampling for all following calls to640// stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given641// pack context. The default (no oversampling) is achieved by h_oversample=1642// and v_oversample=1. The total number of pixels required is643// h_oversample*v_oversample larger than the default; for example, 2x2644// oversampling requires 4x the storage of 1x1. For best results, render645// oversampled textures with bilinear filtering. Look at the readme in646// stb/tests/oversample for information about oversampled fonts647//648// To use with PackFontRangesGather etc., you must set it before calls649// call to PackFontRangesGatherRects.650651STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip);652// If skip != 0, this tells stb_truetype to skip any codepoints for which653// there is no corresponding glyph. If skip=0, which is the default, then654// codepoints without a glyph recived the font's "missing character" glyph,655// typically an empty box by convention.656657STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, // same data as above658 int char_index, // character to display659 float *xpos, float *ypos, // pointers to current position in screen pixel space660 stbtt_aligned_quad *q, // output: quad to draw661 int align_to_integer);662663STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects);664STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects);665STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects);666// Calling these functions in sequence is roughly equivalent to calling667// stbtt_PackFontRanges(). If you more control over the packing of multiple668// fonts, or if you want to pack custom data into a font texture, take a look669// at the source to of stbtt_PackFontRanges() and create a custom version670// using these functions, e.g. call GatherRects multiple times,671// building up a single array of rects, then call PackRects once,672// then call RenderIntoRects repeatedly. This may result in a673// better packing than calling PackFontRanges multiple times674// (or it may not).675676// this is an opaque structure that you shouldn't mess with which holds677// all the context needed from PackBegin to PackEnd.678struct stbtt_pack_context {679 void *user_allocator_context;680 void *pack_info;681 int width;682 int height;683 int stride_in_bytes;684 int padding;685 int skip_missing;686 unsigned int h_oversample, v_oversample;687 unsigned char *pixels;688 void *nodes;689};690691//////////////////////////////////////////////////////////////////////////////692//693// FONT LOADING694//695//696697STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data);698// This function will determine the number of fonts in a font file. TrueType699// collection (.ttc) files may contain multiple fonts, while TrueType font700// (.ttf) files only contain one font. The number of fonts can be used for701// indexing with the previous function where the index is between zero and one702// less than the total fonts. If an error occurs, -1 is returned.703704STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index);705// Each .ttf/.ttc file may have more than one font. Each font has a sequential706// index number starting from 0. Call this function to get the font offset for707// a given index; it returns -1 if the index is out of range. A regular .ttf708// file will only define one font and it always be at offset 0, so it will709// return '0' for index 0, and -1 for all other indices.710711// The following structure is defined publicly so you can declare one on712// the stack or as a global or etc, but you should treat it as opaque.713struct stbtt_fontinfo714{715 void * userdata;716 unsigned char * data; // pointer to .ttf file717 int fontstart; // offset of start of font718719 int numGlyphs; // number of glyphs, needed for range checking720721 int loca,head,glyf,hhea,hmtx,kern,gpos,svg; // table locations as offset from start of .ttf722 int index_map; // a cmap mapping for our chosen character encoding723 int indexToLocFormat; // format needed to map from glyph index to glyph724725 stbtt__buf cff; // cff font data726 stbtt__buf charstrings; // the charstring index727 stbtt__buf gsubrs; // global charstring subroutines index728 stbtt__buf subrs; // private charstring subroutines index729 stbtt__buf fontdicts; // array of font dicts730 stbtt__buf fdselect; // map from glyph to fontdict731};732733STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset);734// Given an offset into the file that defines a font, this function builds735// the necessary cached info for the rest of the system. You must allocate736// the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't737// need to do anything special to free it, because the contents are pure738// value data with no additional data structures. Returns 0 on failure.739740741//////////////////////////////////////////////////////////////////////////////742//743// CHARACTER TO GLYPH-INDEX CONVERSIOn744745STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint);746// If you're going to perform multiple operations on the same character747// and you want a speed-up, call this function with the character you're748// going to process, then use glyph-based functions instead of the749// codepoint-based functions.750// Returns 0 if the character codepoint is not defined in the font.751752753//////////////////////////////////////////////////////////////////////////////754//755// CHARACTER PROPERTIES756//757758STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels);759// computes a scale factor to produce a font whose "height" is 'pixels' tall.760// Height is measured as the distance from the highest ascender to the lowest761// descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics762// and computing:763// scale = pixels / (ascent - descent)764// so if you prefer to measure height by the ascent only, use a similar calculation.765766STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels);767// computes a scale factor to produce a font whose EM size is mapped to768// 'pixels' tall. This is probably what traditional APIs compute, but769// I'm not positive.770771STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap);772// ascent is the coordinate above the baseline the font extends; descent773// is the coordinate below the baseline the font extends (i.e. it is typically negative)774// lineGap is the spacing between one row's descent and the next row's ascent...775// so you should advance the vertical position by "*ascent - *descent + *lineGap"776// these are expressed in unscaled coordinates, so you must multiply by777// the scale factor for a given size778779STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap);780// analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2781// table (specific to MS/Windows TTF files).782//783// Returns 1 on success (table present), 0 on failure.784785STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1);786// the bounding box around all possible characters787788STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing);789// leftSideBearing is the offset from the current horizontal position to the left edge of the character790// advanceWidth is the offset from the current horizontal position to the next horizontal position791// these are expressed in unscaled coordinates792793STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2);794// an additional amount to add to the 'advance' value between ch1 and ch2795796STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1);797// Gets the bounding box of the visible part of the glyph, in unscaled coordinates798799STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing);800STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2);801STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);802// as above, but takes one or more glyph indices for greater efficiency803804typedef struct stbtt_kerningentry805{806 int glyph1; // use stbtt_FindGlyphIndex807 int glyph2;808 int advance;809} stbtt_kerningentry;810811STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info);812STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length);813// Retrieves a complete list of all of the kerning pairs provided by the font814// stbtt_GetKerningTable never writes more than table_length entries and returns how many entries it did write.815// The table will be sorted by (a.glyph1 == b.glyph1)?(a.glyph2 < b.glyph2):(a.glyph1 < b.glyph1)816817//////////////////////////////////////////////////////////////////////////////818//819// GLYPH SHAPES (you probably don't need these, but they have to go before820// the bitmaps for C declaration-order reasons)821//822823#ifndef STBTT_vmove // you can predefine these to use different values (but why?)824 enum {825 STBTT_vmove=1,826 STBTT_vline,827 STBTT_vcurve,828 STBTT_vcubic829 };830#endif831832#ifndef stbtt_vertex // you can predefine this to use different values833 // (we share this with other code at RAD)834 #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file835 typedef struct836 {837 stbtt_vertex_type x,y,cx,cy,cx1,cy1;838 unsigned char type,padding;839 } stbtt_vertex;840#endif841842STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index);843// returns non-zero if nothing is drawn for this glyph844845STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices);846STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices);847// returns # of vertices and fills *vertices with the pointer to them848// these are expressed in "unscaled" coordinates849//850// The shape is a series of contours. Each one starts with851// a STBTT_moveto, then consists of a series of mixed852// STBTT_lineto and STBTT_curveto segments. A lineto853// draws a line from previous endpoint to its x,y; a curveto854// draws a quadratic bezier from previous endpoint to855// its x,y, using cx,cy as the bezier control point.856857STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices);858// frees the data allocated above859860STBTT_DEF unsigned char *stbtt_FindSVGDoc(const stbtt_fontinfo *info, int gl);861STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg);862STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg);863// fills svg with the character's SVG data.864// returns data size or 0 if SVG not found.865866//////////////////////////////////////////////////////////////////////////////867//868// BITMAP RENDERING869//870871STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata);872// frees the bitmap allocated below873874STBTT_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);875// allocates a large-enough single-channel 8bpp bitmap and renders the876// specified character/glyph at the specified scale into it, with877// antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque).878// *width & *height are filled out with the width & height of the bitmap,879// which is stored left-to-right, top-to-bottom.880//881// xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap882883STBTT_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);884// the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel885// shift for the character886887STBTT_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);888// the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap889// in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap890// is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the891// width and height and positioning info for it first.892893STBTT_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);894// same as stbtt_MakeCodepointBitmap, but you can specify a subpixel895// shift for the character896897STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint);898// same as stbtt_MakeCodepointBitmapSubpixel, but prefiltering899// is performed (see stbtt_PackSetOversampling)900901STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);902// get the bbox of the bitmap centered around the glyph origin; so the903// bitmap width is ix1-ix0, height is iy1-iy0, and location to place904// the bitmap top left is (leftSideBearing*scale,iy0).905// (Note that the bitmap uses y-increases-down, but the shape uses906// y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.)907908STBTT_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);909// same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel910// shift for the character911912// the following functions are equivalent to the above functions, but operate913// on glyph indices instead of Unicode codepoints (for efficiency)914STBTT_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);915STBTT_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);916STBTT_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);917STBTT_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);918STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int glyph);919STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);920STBTT_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);921922923// @TODO: don't expose this structure924typedef struct925{926 int w,h,stride;927 unsigned char *pixels;928} stbtt__bitmap;929930// rasterize a shape with quadratic beziers into a bitmap931STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, // 1-channel bitmap to draw into932 float flatness_in_pixels, // allowable error of curve in pixels933 stbtt_vertex *vertices, // array of vertices defining shape934 int num_verts, // number of vertices in above array935 float scale_x, float scale_y, // scale applied to input vertices936 float shift_x, float shift_y, // translation applied to input vertices937 int x_off, int y_off, // another translation applied to input938 int invert, // if non-zero, vertically flip shape939 void *userdata); // context for to STBTT_MALLOC940941//////////////////////////////////////////////////////////////////////////////942//943// Signed Distance Function (or Field) rendering944945STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata);946// frees the SDF bitmap allocated below947948STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff);949STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff);950// These functions compute a discretized SDF field for a single character, suitable for storing951// in a single-channel texture, sampling with bilinear filtering, and testing against952// larger than some threshold to produce scalable fonts.953// info -- the font954// scale -- controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap955// glyph/codepoint -- the character to generate the SDF for956// padding -- extra "pixels" around the character which are filled with the distance to the character (not 0),957// which allows effects like bit outlines958// onedge_value -- value 0-255 to test the SDF against to reconstruct the character (i.e. the isocontour of the character)959// pixel_dist_scale -- what value the SDF should increase by when moving one SDF "pixel" away from the edge (on the 0..255 scale)960// if positive, > onedge_value is inside; if negative, < onedge_value is inside961// width,height -- output height & width of the SDF bitmap (including padding)962// xoff,yoff -- output origin of the character963// return value -- a 2D array of bytes 0..255, width*height in size964//965// pixel_dist_scale & onedge_value are a scale & bias that allows you to make966// optimal use of the limited 0..255 for your application, trading off precision967// and special effects. SDF values outside the range 0..255 are clamped to 0..255.968//969// Example:970// scale = stbtt_ScaleForPixelHeight(22)971// padding = 5972// onedge_value = 180973// pixel_dist_scale = 180/5.0 = 36.0974//975// This will create an SDF bitmap in which the character is about 22 pixels976// high but the whole bitmap is about 22+5+5=32 pixels high. To produce a filled977// shape, sample the SDF at each pixel and fill the pixel if the SDF value978// is greater than or equal to 180/255. (You'll actually want to antialias,979// which is beyond the scope of this example.) Additionally, you can compute980// offset outlines (e.g. to stroke the character border inside & outside,981// or only outside). For example, to fill outside the character up to 3 SDF982// pixels, you would compare against (180-36.0*3)/255 = 72/255. The above983// choice of variables maps a range from 5 pixels outside the shape to984// 2 pixels inside the shape to 0..255; this is intended primarily for apply985// outside effects only (the interior range is needed to allow proper986// antialiasing of the font at *smaller* sizes)987//988// The function computes the SDF analytically at each SDF pixel, not by e.g.989// building a higher-res bitmap and approximating it. In theory the quality990// should be as high as possible for an SDF of this size & representation, but991// unclear if this is true in practice (perhaps building a higher-res bitmap992// and computing from that can allow drop-out prevention).993//994// The algorithm has not been optimized at all, so expect it to be slow995// if computing lots of characters or very large sizes.996997998999//////////////////////////////////////////////////////////////////////////////1000//1001// Finding the right font...1002//1003// You should really just solve this offline, keep your own tables1004// of what font is what, and don't try to get it out of the .ttf file.1005// That's because getting it out of the .ttf file is really hard, because1006// the names in the file can appear in many possible encodings, in many1007// possible languages, and e.g. if you need a case-insensitive comparison,1008// the details of that depend on the encoding & language in a complex way1009// (actually underspecified in truetype, but also gigantic).1010//1011// But you can use the provided functions in two possible ways:1012// stbtt_FindMatchingFont() will use *case-sensitive* comparisons on1013// unicode-encoded names to try to find the font you want;1014// you can run this before calling stbtt_InitFont()1015//1016// stbtt_GetFontNameString() lets you get any of the various strings1017// from the file yourself and do your own comparisons on them.1018// You have to have called stbtt_InitFont() first.101910201021STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags);1022// returns the offset (not index) of the font that matches, or -1 if none1023// if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold".1024// if you use any other flag, use a font name like "Arial"; this checks1025// the 'macStyle' header field; i don't know if fonts set this consistently1026#define STBTT_MACSTYLE_DONTCARE 01027#define STBTT_MACSTYLE_BOLD 11028#define STBTT_MACSTYLE_ITALIC 21029#define STBTT_MACSTYLE_UNDERSCORE 41030#define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 010311032STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2);1033// returns 1/0 whether the first string interpreted as utf8 is identical to1034// the second string interpreted as big-endian utf16... useful for strings from next func10351036STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID);1037// returns the string (which may be big-endian double byte, e.g. for unicode)1038// and puts the length in bytes in *length.1039//1040// some of the values for the IDs are below; for more see the truetype spec:1041// http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html1042// http://www.microsoft.com/typography/otspec/name.htm10431044enum { // platformID1045 STBTT_PLATFORM_ID_UNICODE =0,1046 STBTT_PLATFORM_ID_MAC =1,1047 STBTT_PLATFORM_ID_ISO =2,1048 STBTT_PLATFORM_ID_MICROSOFT =31049};10501051enum { // encodingID for STBTT_PLATFORM_ID_UNICODE1052 STBTT_UNICODE_EID_UNICODE_1_0 =0,1053 STBTT_UNICODE_EID_UNICODE_1_1 =1,1054 STBTT_UNICODE_EID_ISO_10646 =2,1055 STBTT_UNICODE_EID_UNICODE_2_0_BMP=3,1056 STBTT_UNICODE_EID_UNICODE_2_0_FULL=41057};10581059enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT1060 STBTT_MS_EID_SYMBOL =0,1061 STBTT_MS_EID_UNICODE_BMP =1,1062 STBTT_MS_EID_SHIFTJIS =2,1063 STBTT_MS_EID_UNICODE_FULL =101064};10651066enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes1067 STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4,1068 STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5,1069 STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6,1070 STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =71071};10721073enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID...1074 // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs1075 STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410,1076 STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411,1077 STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412,1078 STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419,1079 STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409,1080 STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D1081};10821083enum { // languageID for STBTT_PLATFORM_ID_MAC1084 STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11,1085 STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23,1086 STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32,1087 STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 ,1088 STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 ,1089 STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33,1090 STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =191091};10921093#ifdef __cplusplus1094}1095#endif10961097#endif // __STB_INCLUDE_STB_TRUETYPE_H__10981099///////////////////////////////////////////////////////////////////////////////1100///////////////////////////////////////////////////////////////////////////////1101////1102//// IMPLEMENTATION1103////1104////11051106#ifdef STB_TRUETYPE_IMPLEMENTATION11071108#ifndef STBTT_MAX_OVERSAMPLE1109#define STBTT_MAX_OVERSAMPLE 81110#endif11111112#if STBTT_MAX_OVERSAMPLE > 2551113#error "STBTT_MAX_OVERSAMPLE cannot be > 255"1114#endif11151116typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1];11171118#ifndef STBTT_RASTERIZER_VERSION1119#define STBTT_RASTERIZER_VERSION 21120#endif11211122#ifdef _MSC_VER1123#define STBTT__NOTUSED(v) (void)(v)1124#else1125#define STBTT__NOTUSED(v) (void)sizeof(v)1126#endif11271128//////////////////////////////////////////////////////////////////////////1129//1130// stbtt__buf helpers to parse data from file1131//11321133static stbtt_uint8 stbtt__buf_get8(stbtt__buf *b)1134{1135 if (b->cursor >= b->size)1136 return 0;1137 return b->data[b->cursor++];1138}11391140static stbtt_uint8 stbtt__buf_peek8(stbtt__buf *b)1141{1142 if (b->cursor >= b->size)1143 return 0;1144 return b->data[b->cursor];1145}11461147static void stbtt__buf_seek(stbtt__buf *b, int o)1148{1149 STBTT_assert(!(o > b->size || o < 0));1150 b->cursor = (o > b->size || o < 0) ? b->size : o;1151}11521153static void stbtt__buf_skip(stbtt__buf *b, int o)1154{1155 stbtt__buf_seek(b, b->cursor + o);1156}11571158static stbtt_uint32 stbtt__buf_get(stbtt__buf *b, int n)1159{1160 stbtt_uint32 v = 0;1161 int i;1162 STBTT_assert(n >= 1 && n <= 4);1163 for (i = 0; i < n; i++)1164 v = (v << 8) | stbtt__buf_get8(b);1165 return v;1166}11671168static stbtt__buf stbtt__new_buf(const void *p, size_t size)1169{1170 stbtt__buf r;1171 STBTT_assert(size < 0x40000000);1172 r.data = (stbtt_uint8*) p;1173 r.size = (int) size;1174 r.cursor = 0;1175 return r;1176}11771178#define stbtt__buf_get16(b) stbtt__buf_get((b), 2)1179#define stbtt__buf_get32(b) stbtt__buf_get((b), 4)11801181static stbtt__buf stbtt__buf_range(const stbtt__buf *b, int o, int s)1182{1183 stbtt__buf r = stbtt__new_buf(NULL, 0);1184 if (o < 0 || s < 0 || o > b->size || s > b->size - o) return r;1185 r.data = b->data + o;1186 r.size = s;1187 return r;1188}11891190static stbtt__buf stbtt__cff_get_index(stbtt__buf *b)1191{1192 int count, start, offsize;1193 start = b->cursor;1194 count = stbtt__buf_get16(b);1195 if (count) {1196 offsize = stbtt__buf_get8(b);1197 STBTT_assert(offsize >= 1 && offsize <= 4);1198 stbtt__buf_skip(b, offsize * count);1199 stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1);1200 }1201 return stbtt__buf_range(b, start, b->cursor - start);1202}12031204static stbtt_uint32 stbtt__cff_int(stbtt__buf *b)1205{1206 int b0 = stbtt__buf_get8(b);1207 if (b0 >= 32 && b0 <= 246) return b0 - 139;1208 else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108;1209 else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108;1210 else if (b0 == 28) return stbtt__buf_get16(b);1211 else if (b0 == 29) return stbtt__buf_get32(b);1212 STBTT_assert(0);1213 return 0;1214}12151216static void stbtt__cff_skip_operand(stbtt__buf *b) {1217 int v, b0 = stbtt__buf_peek8(b);1218 STBTT_assert(b0 >= 28);1219 if (b0 == 30) {1220 stbtt__buf_skip(b, 1);1221 while (b->cursor < b->size) {1222 v = stbtt__buf_get8(b);1223 if ((v & 0xF) == 0xF || (v >> 4) == 0xF)1224 break;1225 }1226 } else {1227 stbtt__cff_int(b);1228 }1229}12301231static stbtt__buf stbtt__dict_get(stbtt__buf *b, int key)1232{1233 stbtt__buf_seek(b, 0);1234 while (b->cursor < b->size) {1235 int start = b->cursor, end, op;1236 while (stbtt__buf_peek8(b) >= 28)1237 stbtt__cff_skip_operand(b);1238 end = b->cursor;1239 op = stbtt__buf_get8(b);1240 if (op == 12) op = stbtt__buf_get8(b) | 0x100;1241 if (op == key) return stbtt__buf_range(b, start, end-start);1242 }1243 return stbtt__buf_range(b, 0, 0);1244}12451246static void stbtt__dict_get_ints(stbtt__buf *b, int key, int outcount, stbtt_uint32 *out)1247{1248 int i;1249 stbtt__buf operands = stbtt__dict_get(b, key);1250 for (i = 0; i < outcount && operands.cursor < operands.size; i++)1251 out[i] = stbtt__cff_int(&operands);1252}12531254static int stbtt__cff_index_count(stbtt__buf *b)1255{1256 stbtt__buf_seek(b, 0);1257 return stbtt__buf_get16(b);1258}12591260static stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i)1261{1262 int count, offsize, start, end;1263 stbtt__buf_seek(&b, 0);1264 count = stbtt__buf_get16(&b);1265 offsize = stbtt__buf_get8(&b);1266 STBTT_assert(i >= 0 && i < count);1267 STBTT_assert(offsize >= 1 && offsize <= 4);1268 stbtt__buf_skip(&b, i*offsize);1269 start = stbtt__buf_get(&b, offsize);1270 end = stbtt__buf_get(&b, offsize);1271 return stbtt__buf_range(&b, 2+(count+1)*offsize+start, end - start);1272}12731274//////////////////////////////////////////////////////////////////////////1275//1276// accessors to parse data from file1277//12781279// on platforms that don't allow misaligned reads, if we want to allow1280// truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE12811282#define ttBYTE(p) (* (stbtt_uint8 *) (p))1283#define ttCHAR(p) (* (stbtt_int8 *) (p))1284#define ttFixed(p) ttLONG(p)12851286static stbtt_uint16 ttUSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; }1287static stbtt_int16 ttSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; }1288static stbtt_uint32 ttULONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }1289static stbtt_int32 ttLONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }12901291#define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3))1292#define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3])12931294static int stbtt__isfont(stbtt_uint8 *font)1295{1296 // check the version number1297 if (stbtt_tag4(font, '1',0,0,0)) return 1; // TrueType 11298 if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this!1299 if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF1300 if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.01301 if (stbtt_tag(font, "true")) return 1; // Apple specification for TrueType fonts1302 return 0;1303}13041305// @OPTIMIZE: binary search1306static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag)1307{1308 stbtt_int32 num_tables = ttUSHORT(data+fontstart+4);1309 stbtt_uint32 tabledir = fontstart + 12;1310 stbtt_int32 i;1311 for (i=0; i < num_tables; ++i) {1312 stbtt_uint32 loc = tabledir + 16*i;1313 if (stbtt_tag(data+loc+0, tag))1314 return ttULONG(data+loc+8);1315 }1316 return 0;1317}13181319static int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection, int index)1320{1321 // if it's just a font, there's only one valid index1322 if (stbtt__isfont(font_collection))1323 return index == 0 ? 0 : -1;13241325 // check if it's a TTC1326 if (stbtt_tag(font_collection, "ttcf")) {1327 // version 1?1328 if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {1329 stbtt_int32 n = ttLONG(font_collection+8);1330 if (index >= n)1331 return -1;1332 return ttULONG(font_collection+12+index*4);1333 }1334 }1335 return -1;1336}13371338static int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection)1339{1340 // if it's just a font, there's only one valid font1341 if (stbtt__isfont(font_collection))1342 return 1;13431344 // check if it's a TTC1345 if (stbtt_tag(font_collection, "ttcf")) {1346 // version 1?1347 if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {1348 return ttLONG(font_collection+8);1349 }1350 }1351 return 0;1352}13531354static stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict)1355{1356 stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 };1357 stbtt__buf pdict;1358 stbtt__dict_get_ints(&fontdict, 18, 2, private_loc);1359 if (!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0);1360 pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]);1361 stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff);1362 if (!subrsoff) return stbtt__new_buf(NULL, 0);1363 stbtt__buf_seek(&cff, private_loc[1]+subrsoff);1364 return stbtt__cff_get_index(&cff);1365}13661367// since most people won't use this, find this table the first time it's needed1368static int stbtt__get_svg(stbtt_fontinfo *info)1369{1370 stbtt_uint32 t;1371 if (info->svg < 0) {1372 t = stbtt__find_table(info->data, info->fontstart, "SVG ");1373 if (t) {1374 stbtt_uint32 offset = ttULONG(info->data + t + 2);1375 info->svg = t + offset;1376 } else {1377 info->svg = 0;1378 }1379 }1380 return info->svg;1381}13821383static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, int fontstart)1384{1385 stbtt_uint32 cmap, t;1386 stbtt_int32 i,numTables;13871388 info->data = data;1389 info->fontstart = fontstart;1390 info->cff = stbtt__new_buf(NULL, 0);13911392 cmap = stbtt__find_table(data, fontstart, "cmap"); // required1393 info->loca = stbtt__find_table(data, fontstart, "loca"); // required1394 info->head = stbtt__find_table(data, fontstart, "head"); // required1395 info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required1396 info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required1397 info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required1398 info->kern = stbtt__find_table(data, fontstart, "kern"); // not required1399 info->gpos = stbtt__find_table(data, fontstart, "GPOS"); // not required14001401 if (!cmap || !info->head || !info->hhea || !info->hmtx)1402 return 0;1403 if (info->glyf) {1404 // required for truetype1405 if (!info->loca) return 0;1406 } else {1407 // initialization for CFF / Type2 fonts (OTF)1408 stbtt__buf b, topdict, topdictidx;1409 stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0;1410 stbtt_uint32 cff;14111412 cff = stbtt__find_table(data, fontstart, "CFF ");1413 if (!cff) return 0;14141415 info->fontdicts = stbtt__new_buf(NULL, 0);1416 info->fdselect = stbtt__new_buf(NULL, 0);14171418 // @TODO this should use size from table (not 512MB)1419 info->cff = stbtt__new_buf(data+cff, 512*1024*1024);1420 b = info->cff;14211422 // read the header1423 stbtt__buf_skip(&b, 2);1424 stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize14251426 // @TODO the name INDEX could list multiple fonts,1427 // but we just use the first one.1428 stbtt__cff_get_index(&b); // name INDEX1429 topdictidx = stbtt__cff_get_index(&b);1430 topdict = stbtt__cff_index_get(topdictidx, 0);1431 stbtt__cff_get_index(&b); // string INDEX1432 info->gsubrs = stbtt__cff_get_index(&b);14331434 stbtt__dict_get_ints(&topdict, 17, 1, &charstrings);1435 stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype);1436 stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff);1437 stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff);1438 info->subrs = stbtt__get_subrs(b, topdict);14391440 // we only support Type 2 charstrings1441 if (cstype != 2) return 0;1442 if (charstrings == 0) return 0;14431444 if (fdarrayoff) {1445 // looks like a CID font1446 if (!fdselectoff) return 0;1447 stbtt__buf_seek(&b, fdarrayoff);1448 info->fontdicts = stbtt__cff_get_index(&b);1449 info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size-fdselectoff);1450 }14511452 stbtt__buf_seek(&b, charstrings);1453 info->charstrings = stbtt__cff_get_index(&b);1454 }14551456 t = stbtt__find_table(data, fontstart, "maxp");1457 if (t)1458 info->numGlyphs = ttUSHORT(data+t+4);1459 else1460 info->numGlyphs = 0xffff;14611462 info->svg = -1;14631464 // find a cmap encoding table we understand *now* to avoid searching1465 // later. (todo: could make this installable)1466 // the same regardless of glyph.1467 numTables = ttUSHORT(data + cmap + 2);1468 info->index_map = 0;1469 for (i=0; i < numTables; ++i) {1470 stbtt_uint32 encoding_record = cmap + 4 + 8 * i;1471 // find an encoding we understand:1472 switch(ttUSHORT(data+encoding_record)) {1473 case STBTT_PLATFORM_ID_MICROSOFT:1474 switch (ttUSHORT(data+encoding_record+2)) {1475 case STBTT_MS_EID_UNICODE_BMP:1476 case STBTT_MS_EID_UNICODE_FULL:1477 // MS/Unicode1478 info->index_map = cmap + ttULONG(data+encoding_record+4);1479 break;1480 }1481 break;1482 case STBTT_PLATFORM_ID_UNICODE:1483 // Mac/iOS has these1484 // all the encodingIDs are unicode, so we don't bother to check it1485 info->index_map = cmap + ttULONG(data+encoding_record+4);1486 break;1487 }1488 }1489 if (info->index_map == 0)1490 return 0;14911492 info->indexToLocFormat = ttUSHORT(data+info->head + 50);1493 return 1;1494}14951496STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint)1497{1498 stbtt_uint8 *data = info->data;1499 stbtt_uint32 index_map = info->index_map;15001501 stbtt_uint16 format = ttUSHORT(data + index_map + 0);1502 if (format == 0) { // apple byte encoding1503 stbtt_int32 bytes = ttUSHORT(data + index_map + 2);1504 if (unicode_codepoint < bytes-6)1505 return ttBYTE(data + index_map + 6 + unicode_codepoint);1506 return 0;1507 } else if (format == 6) {1508 stbtt_uint32 first = ttUSHORT(data + index_map + 6);1509 stbtt_uint32 count = ttUSHORT(data + index_map + 8);1510 if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count)1511 return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2);1512 return 0;1513 } else if (format == 2) {1514 STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean1515 return 0;1516 } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges1517 stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1;1518 stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1;1519 stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10);1520 stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1;15211522 // do a binary search of the segments1523 stbtt_uint32 endCount = index_map + 14;1524 stbtt_uint32 search = endCount;15251526 if (unicode_codepoint > 0xffff)1527 return 0;15281529 // they lie from endCount .. endCount + segCount1530 // but searchRange is the nearest power of two, so...1531 if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2))1532 search += rangeShift*2;15331534 // now decrement to bias correctly to find smallest1535 search -= 2;1536 while (entrySelector) {1537 stbtt_uint16 end;1538 searchRange >>= 1;1539 end = ttUSHORT(data + search + searchRange*2);1540 if (unicode_codepoint > end)1541 search += searchRange*2;1542 --entrySelector;1543 }1544 search += 2;15451546 {1547 stbtt_uint16 offset, start, last;1548 stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1);15491550 start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item);1551 last = ttUSHORT(data + endCount + 2*item);1552 if (unicode_codepoint < start || unicode_codepoint > last)1553 return 0;15541555 offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item);1556 if (offset == 0)1557 return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item));15581559 return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item);1560 }1561 } else if (format == 12 || format == 13) {1562 stbtt_uint32 ngroups = ttULONG(data+index_map+12);1563 stbtt_int32 low,high;1564 low = 0; high = (stbtt_int32)ngroups;1565 // Binary search the right group.1566 while (low < high) {1567 stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high1568 stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12);1569 stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4);1570 if ((stbtt_uint32) unicode_codepoint < start_char)1571 high = mid;1572 else if ((stbtt_uint32) unicode_codepoint > end_char)1573 low = mid+1;1574 else {1575 stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8);1576 if (format == 12)1577 return start_glyph + unicode_codepoint-start_char;1578 else // format == 131579 return start_glyph;1580 }1581 }1582 return 0; // not found1583 }1584 // @TODO1585 STBTT_assert(0);1586 return 0;1587}15881589STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices)1590{1591 return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices);1592}15931594static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy)1595{1596 v->type = type;1597 v->x = (stbtt_int16) x;1598 v->y = (stbtt_int16) y;1599 v->cx = (stbtt_int16) cx;1600 v->cy = (stbtt_int16) cy;1601}16021603static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index)1604{1605 int g1,g2;16061607 STBTT_assert(!info->cff.size);16081609 if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range1610 if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format16111612 if (info->indexToLocFormat == 0) {1613 g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2;1614 g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2;1615 } else {1616 g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4);1617 g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4);1618 }16191620 return g1==g2 ? -1 : g1; // if length is 0, return -11621}16221623static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);16241625STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)1626{1627 if (info->cff.size) {1628 stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1);1629 } else {1630 int g = stbtt__GetGlyfOffset(info, glyph_index);1631 if (g < 0) return 0;16321633 if (x0) *x0 = ttSHORT(info->data + g + 2);1634 if (y0) *y0 = ttSHORT(info->data + g + 4);1635 if (x1) *x1 = ttSHORT(info->data + g + 6);1636 if (y1) *y1 = ttSHORT(info->data + g + 8);1637 }1638 return 1;1639}16401641STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1)1642{1643 return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1);1644}16451646STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index)1647{1648 stbtt_int16 numberOfContours;1649 int g;1650 if (info->cff.size)1651 return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0;1652 g = stbtt__GetGlyfOffset(info, glyph_index);1653 if (g < 0) return 1;1654 numberOfContours = ttSHORT(info->data + g);1655 return numberOfContours == 0;1656}16571658static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off,1659 stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy)1660{1661 if (start_off) {1662 if (was_off)1663 stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy);1664 stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy);1665 } else {1666 if (was_off)1667 stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy);1668 else1669 stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0);1670 }1671 return num_vertices;1672}16731674static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)1675{1676 stbtt_int16 numberOfContours;1677 stbtt_uint8 *endPtsOfContours;1678 stbtt_uint8 *data = info->data;1679 stbtt_vertex *vertices=0;1680 int num_vertices=0;1681 int g = stbtt__GetGlyfOffset(info, glyph_index);16821683 *pvertices = NULL;16841685 if (g < 0) return 0;16861687 numberOfContours = ttSHORT(data + g);16881689 if (numberOfContours > 0) {1690 stbtt_uint8 flags=0,flagcount;1691 stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0;1692 stbtt_int32 x,y,cx,cy,sx,sy, scx,scy;1693 stbtt_uint8 *points;1694 endPtsOfContours = (data + g + 10);1695 ins = ttUSHORT(data + g + 10 + numberOfContours * 2);1696 points = data + g + 10 + numberOfContours * 2 + 2 + ins;16971698 n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2);16991700 m = n + 2*numberOfContours; // a loose bound on how many vertices we might need1701 vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata);1702 if (vertices == 0)1703 return 0;17041705 next_move = 0;1706 flagcount=0;17071708 // in first pass, we load uninterpreted data into the allocated array1709 // above, shifted to the end of the array so we won't overwrite it when1710 // we create our final data starting from the front17111712 off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated17131714 // first load flags17151716 for (i=0; i < n; ++i) {1717 if (flagcount == 0) {1718 flags = *points++;1719 if (flags & 8)1720 flagcount = *points++;1721 } else1722 --flagcount;1723 vertices[off+i].type = flags;1724 }17251726 // now load x coordinates1727 x=0;1728 for (i=0; i < n; ++i) {1729 flags = vertices[off+i].type;1730 if (flags & 2) {1731 stbtt_int16 dx = *points++;1732 x += (flags & 16) ? dx : -dx; // ???1733 } else {1734 if (!(flags & 16)) {1735 x = x + (stbtt_int16) (points[0]*256 + points[1]);1736 points += 2;1737 }1738 }1739 vertices[off+i].x = (stbtt_int16) x;1740 }17411742 // now load y coordinates1743 y=0;1744 for (i=0; i < n; ++i) {1745 flags = vertices[off+i].type;1746 if (flags & 4) {1747 stbtt_int16 dy = *points++;1748 y += (flags & 32) ? dy : -dy; // ???1749 } else {1750 if (!(flags & 32)) {1751 y = y + (stbtt_int16) (points[0]*256 + points[1]);1752 points += 2;1753 }1754 }1755 vertices[off+i].y = (stbtt_int16) y;1756 }17571758 // now convert them to our format1759 num_vertices=0;1760 sx = sy = cx = cy = scx = scy = 0;1761 for (i=0; i < n; ++i) {1762 flags = vertices[off+i].type;1763 x = (stbtt_int16) vertices[off+i].x;1764 y = (stbtt_int16) vertices[off+i].y;17651766 if (next_move == i) {1767 if (i != 0)1768 num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);17691770 // now start the new one1771 start_off = !(flags & 1);1772 if (start_off) {1773 // if we start off with an off-curve point, then when we need to find a point on the curve1774 // where we can start, and we need to save some state for when we wraparound.1775 scx = x;1776 scy = y;1777 if (!(vertices[off+i+1].type & 1)) {1778 // next point is also a curve point, so interpolate an on-point curve1779 sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1;1780 sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1;1781 } else {1782 // otherwise just use the next point as our start point1783 sx = (stbtt_int32) vertices[off+i+1].x;1784 sy = (stbtt_int32) vertices[off+i+1].y;1785 ++i; // we're using point i+1 as the starting point, so skip it1786 }1787 } else {1788 sx = x;1789 sy = y;1790 }1791 stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0);1792 was_off = 0;1793 next_move = 1 + ttUSHORT(endPtsOfContours+j*2);1794 ++j;1795 } else {1796 if (!(flags & 1)) { // if it's a curve1797 if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint1798 stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy);1799 cx = x;1800 cy = y;1801 was_off = 1;1802 } else {1803 if (was_off)1804 stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy);1805 else1806 stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0);1807 was_off = 0;1808 }1809 }1810 }1811 num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);1812 } else if (numberOfContours < 0) {1813 // Compound shapes.1814 int more = 1;1815 stbtt_uint8 *comp = data + g + 10;1816 num_vertices = 0;1817 vertices = 0;1818 while (more) {1819 stbtt_uint16 flags, gidx;1820 int comp_num_verts = 0, i;1821 stbtt_vertex *comp_verts = 0, *tmp = 0;1822 float mtx[6] = {1,0,0,1,0,0}, m, n;18231824 flags = ttSHORT(comp); comp+=2;1825 gidx = ttSHORT(comp); comp+=2;18261827 if (flags & 2) { // XY values1828 if (flags & 1) { // shorts1829 mtx[4] = ttSHORT(comp); comp+=2;1830 mtx[5] = ttSHORT(comp); comp+=2;1831 } else {1832 mtx[4] = ttCHAR(comp); comp+=1;1833 mtx[5] = ttCHAR(comp); comp+=1;1834 }1835 }1836 else {1837 // @TODO handle matching point1838 STBTT_assert(0);1839 }1840 if (flags & (1<<3)) { // WE_HAVE_A_SCALE1841 mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;1842 mtx[1] = mtx[2] = 0;1843 } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE1844 mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;1845 mtx[1] = mtx[2] = 0;1846 mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;1847 } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO1848 mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;1849 mtx[1] = ttSHORT(comp)/16384.0f; comp+=2;1850 mtx[2] = ttSHORT(comp)/16384.0f; comp+=2;1851 mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;1852 }18531854 // Find transformation scales.1855 m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]);1856 n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]);18571858 // Get indexed glyph.1859 comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts);1860 if (comp_num_verts > 0) {1861 // Transform vertices.1862 for (i = 0; i < comp_num_verts; ++i) {1863 stbtt_vertex* v = &comp_verts[i];1864 stbtt_vertex_type x,y;1865 x=v->x; y=v->y;1866 v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));1867 v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));1868 x=v->cx; y=v->cy;1869 v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));1870 v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));1871 }1872 // Append vertices.1873 tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata);1874 if (!tmp) {1875 if (vertices) STBTT_free(vertices, info->userdata);1876 if (comp_verts) STBTT_free(comp_verts, info->userdata);1877 return 0;1878 }1879 if (num_vertices > 0 && vertices) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex));1880 STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex));1881 if (vertices) STBTT_free(vertices, info->userdata);1882 vertices = tmp;1883 STBTT_free(comp_verts, info->userdata);1884 num_vertices += comp_num_verts;1885 }1886 // More components ?1887 more = flags & (1<<5);1888 }1889 } else {1890 // numberOfCounters == 0, do nothing1891 }18921893 *pvertices = vertices;1894 return num_vertices;1895}18961897typedef struct1898{1899 int bounds;1900 int started;1901 float first_x, first_y;1902 float x, y;1903 stbtt_int32 min_x, max_x, min_y, max_y;19041905 stbtt_vertex *pvertices;1906 int num_vertices;1907} stbtt__csctx;19081909#define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0}19101911static void stbtt__track_vertex(stbtt__csctx *c, stbtt_int32 x, stbtt_int32 y)1912{1913 if (x > c->max_x || !c->started) c->max_x = x;1914 if (y > c->max_y || !c->started) c->max_y = y;1915 if (x < c->min_x || !c->started) c->min_x = x;1916 if (y < c->min_y || !c->started) c->min_y = y;1917 c->started = 1;1918}19191920static void stbtt__csctx_v(stbtt__csctx *c, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy, stbtt_int32 cx1, stbtt_int32 cy1)1921{1922 if (c->bounds) {1923 stbtt__track_vertex(c, x, y);1924 if (type == STBTT_vcubic) {1925 stbtt__track_vertex(c, cx, cy);1926 stbtt__track_vertex(c, cx1, cy1);1927 }1928 } else {1929 stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy);1930 c->pvertices[c->num_vertices].cx1 = (stbtt_int16) cx1;1931 c->pvertices[c->num_vertices].cy1 = (stbtt_int16) cy1;1932 }1933 c->num_vertices++;1934}19351936static void stbtt__csctx_close_shape(stbtt__csctx *ctx)1937{1938 if (ctx->first_x != ctx->x || ctx->first_y != ctx->y)1939 stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0);1940}19411942static void stbtt__csctx_rmove_to(stbtt__csctx *ctx, float dx, float dy)1943{1944 stbtt__csctx_close_shape(ctx);1945 ctx->first_x = ctx->x = ctx->x + dx;1946 ctx->first_y = ctx->y = ctx->y + dy;1947 stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0);1948}19491950static void stbtt__csctx_rline_to(stbtt__csctx *ctx, float dx, float dy)1951{1952 ctx->x += dx;1953 ctx->y += dy;1954 stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0);1955}19561957static void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3)1958{1959 float cx1 = ctx->x + dx1;1960 float cy1 = ctx->y + dy1;1961 float cx2 = cx1 + dx2;1962 float cy2 = cy1 + dy2;1963 ctx->x = cx2 + dx3;1964 ctx->y = cy2 + dy3;1965 stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2);1966}19671968static stbtt__buf stbtt__get_subr(stbtt__buf idx, int n)1969{1970 int count = stbtt__cff_index_count(&idx);1971 int bias = 107;1972 if (count >= 33900)1973 bias = 32768;1974 else if (count >= 1240)1975 bias = 1131;1976 n += bias;1977 if (n < 0 || n >= count)1978 return stbtt__new_buf(NULL, 0);1979 return stbtt__cff_index_get(idx, n);1980}19811982static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int glyph_index)1983{1984 stbtt__buf fdselect = info->fdselect;1985 int nranges, start, end, v, fmt, fdselector = -1, i;19861987 stbtt__buf_seek(&fdselect, 0);1988 fmt = stbtt__buf_get8(&fdselect);1989 if (fmt == 0) {1990 // untested1991 stbtt__buf_skip(&fdselect, glyph_index);1992 fdselector = stbtt__buf_get8(&fdselect);1993 } else if (fmt == 3) {1994 nranges = stbtt__buf_get16(&fdselect);1995 start = stbtt__buf_get16(&fdselect);1996 for (i = 0; i < nranges; i++) {1997 v = stbtt__buf_get8(&fdselect);1998 end = stbtt__buf_get16(&fdselect);1999 if (glyph_index >= start && glyph_index < end) {2000 fdselector = v;The first 2,000 of 5,079 lines.