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

stb_truetype.h 124KB

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