stb_truetype.h 124 KB

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