2
0

imstb_truetype.h 186 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860
  1. // [ImGui] this is a slightly modified version of stb_truetype.h 1.19. Those changes would need to be pushed into nothings/stb
  2. // grep for [ImGui] to find the changes.
  3. // stb_truetype.h - v1.19 - public domain
  4. // authored from 2009-2016 by Sean Barrett / RAD Game Tools
  5. //
  6. // This library processes TrueType files:
  7. // parse files
  8. // extract glyph metrics
  9. // extract glyph shapes
  10. // render glyphs to one-channel bitmaps with antialiasing (box filter)
  11. // render glyphs to one-channel SDF bitmaps (signed-distance field/function)
  12. //
  13. // Todo:
  14. // non-MS cmaps
  15. // crashproof on bad data
  16. // hinting? (no longer patented)
  17. // cleartype-style AA?
  18. // optimize: use simple memory allocator for intermediates
  19. // optimize: build edge-list directly from curves
  20. // optimize: rasterize directly from curves?
  21. //
  22. // ADDITIONAL CONTRIBUTORS
  23. //
  24. // Mikko Mononen: compound shape support, more cmap formats
  25. // Tor Andersson: kerning, subpixel rendering
  26. // Dougall Johnson: OpenType / Type 2 font handling
  27. // Daniel Ribeiro Maciel: basic GPOS-based kerning
  28. //
  29. // Misc other:
  30. // Ryan Gordon
  31. // Simon Glass
  32. // github:IntellectualKitty
  33. // Imanol Celaya
  34. // Daniel Ribeiro Maciel
  35. //
  36. // Bug/warning reports/fixes:
  37. // "Zer" on mollyrocket Fabian "ryg" Giesen
  38. // Cass Everitt Martins Mozeiko
  39. // stoiko (Haemimont Games) Cap Petschulat
  40. // Brian Hook Omar Cornut
  41. // Walter van Niftrik github:aloucks
  42. // David Gow Peter LaValle
  43. // David Given Sergey Popov
  44. // Ivan-Assen Ivanov Giumo X. Clanjor
  45. // Anthony Pesch Higor Euripedes
  46. // Johan Duparc Thomas Fields
  47. // Hou Qiming Derek Vinyard
  48. // Rob Loach Cort Stratton
  49. // Kenney Phillis Jr. github:oyvindjam
  50. // Brian Costabile github:vassvik
  51. //
  52. // VERSION HISTORY
  53. //
  54. // 1.19 (2018-02-11) GPOS kerning, STBTT_fmod
  55. // 1.18 (2018-01-29) add missing function
  56. // 1.17 (2017-07-23) make more arguments const; doc fix
  57. // 1.16 (2017-07-12) SDF support
  58. // 1.15 (2017-03-03) make more arguments const
  59. // 1.14 (2017-01-16) num-fonts-in-TTC function
  60. // 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts
  61. // 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual
  62. // 1.11 (2016-04-02) fix unused-variable warning
  63. // 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef
  64. // 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly
  65. // 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges
  66. // 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;
  67. // variant PackFontRanges to pack and render in separate phases;
  68. // fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);
  69. // fixed an assert() bug in the new rasterizer
  70. // replace assert() with STBTT_assert() in new rasterizer
  71. //
  72. // Full history can be found at the end of this file.
  73. //
  74. // LICENSE
  75. //
  76. // See end of file for license information.
  77. //
  78. // USAGE
  79. //
  80. // Include this file in whatever places neeed to refer to it. In ONE C/C++
  81. // file, write:
  82. // #define STB_TRUETYPE_IMPLEMENTATION
  83. // before the #include of this file. This expands out the actual
  84. // implementation into that C/C++ file.
  85. //
  86. // To make the implementation private to the file that generates the implementation,
  87. // #define STBTT_STATIC
  88. //
  89. // Simple 3D API (don't ship this, but it's fine for tools and quick start)
  90. // stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture
  91. // stbtt_GetBakedQuad() -- compute quad to draw for a given char
  92. //
  93. // Improved 3D API (more shippable):
  94. // #include "stb_rect_pack.h" -- optional, but you really want it
  95. // stbtt_PackBegin()
  96. // stbtt_PackSetOversampling() -- for improved quality on small fonts
  97. // stbtt_PackFontRanges() -- pack and renders
  98. // stbtt_PackEnd()
  99. // stbtt_GetPackedQuad()
  100. //
  101. // "Load" a font file from a memory buffer (you have to keep the buffer loaded)
  102. // stbtt_InitFont()
  103. // stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections
  104. // stbtt_GetNumberOfFonts() -- number of fonts for TTC font collections
  105. //
  106. // Render a unicode codepoint to a bitmap
  107. // stbtt_GetCodepointBitmap() -- allocates and returns a bitmap
  108. // stbtt_MakeCodepointBitmap() -- renders into bitmap you provide
  109. // stbtt_GetCodepointBitmapBox() -- how big the bitmap must be
  110. //
  111. // Character advance/positioning
  112. // stbtt_GetCodepointHMetrics()
  113. // stbtt_GetFontVMetrics()
  114. // stbtt_GetFontVMetricsOS2()
  115. // stbtt_GetCodepointKernAdvance()
  116. //
  117. // Starting with version 1.06, the rasterizer was replaced with a new,
  118. // faster and generally-more-precise rasterizer. The new rasterizer more
  119. // accurately measures pixel coverage for anti-aliasing, except in the case
  120. // where multiple shapes overlap, in which case it overestimates the AA pixel
  121. // coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If
  122. // this turns out to be a problem, you can re-enable the old rasterizer with
  123. // #define STBTT_RASTERIZER_VERSION 1
  124. // which will incur about a 15% speed hit.
  125. //
  126. // ADDITIONAL DOCUMENTATION
  127. //
  128. // Immediately after this block comment are a series of sample programs.
  129. //
  130. // After the sample programs is the "header file" section. This section
  131. // includes documentation for each API function.
  132. //
  133. // Some important concepts to understand to use this library:
  134. //
  135. // Codepoint
  136. // Characters are defined by unicode codepoints, e.g. 65 is
  137. // uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is
  138. // the hiragana for "ma".
  139. //
  140. // Glyph
  141. // A visual character shape (every codepoint is rendered as
  142. // some glyph)
  143. //
  144. // Glyph index
  145. // A font-specific integer ID representing a glyph
  146. //
  147. // Baseline
  148. // Glyph shapes are defined relative to a baseline, which is the
  149. // bottom of uppercase characters. Characters extend both above
  150. // and below the baseline.
  151. //
  152. // Current Point
  153. // As you draw text to the screen, you keep track of a "current point"
  154. // which is the origin of each character. The current point's vertical
  155. // position is the baseline. Even "baked fonts" use this model.
  156. //
  157. // Vertical Font Metrics
  158. // The vertical qualities of the font, used to vertically position
  159. // and space the characters. See docs for stbtt_GetFontVMetrics.
  160. //
  161. // Font Size in Pixels or Points
  162. // The preferred interface for specifying font sizes in stb_truetype
  163. // is to specify how tall the font's vertical extent should be in pixels.
  164. // If that sounds good enough, skip the next paragraph.
  165. //
  166. // Most font APIs instead use "points", which are a common typographic
  167. // measurement for describing font size, defined as 72 points per inch.
  168. // stb_truetype provides a point API for compatibility. However, true
  169. // "per inch" conventions don't make much sense on computer displays
  170. // since different monitors have different number of pixels per
  171. // inch. For example, Windows traditionally uses a convention that
  172. // there are 96 pixels per inch, thus making 'inch' measurements have
  173. // nothing to do with inches, and thus effectively defining a point to
  174. // be 1.333 pixels. Additionally, the TrueType font data provides
  175. // an explicit scale factor to scale a given font's glyphs to points,
  176. // but the author has observed that this scale factor is often wrong
  177. // for non-commercial fonts, thus making fonts scaled in points
  178. // according to the TrueType spec incoherently sized in practice.
  179. //
  180. // DETAILED USAGE:
  181. //
  182. // Scale:
  183. // Select how high you want the font to be, in points or pixels.
  184. // Call ScaleForPixelHeight or ScaleForMappingEmToPixels to compute
  185. // a scale factor SF that will be used by all other functions.
  186. //
  187. // Baseline:
  188. // You need to select a y-coordinate that is the baseline of where
  189. // your text will appear. Call GetFontBoundingBox to get the baseline-relative
  190. // bounding box for all characters. SF*-y0 will be the distance in pixels
  191. // that the worst-case character could extend above the baseline, so if
  192. // you want the top edge of characters to appear at the top of the
  193. // screen where y=0, then you would set the baseline to SF*-y0.
  194. //
  195. // Current point:
  196. // Set the current point where the first character will appear. The
  197. // first character could extend left of the current point; this is font
  198. // dependent. You can either choose a current point that is the leftmost
  199. // point and hope, or add some padding, or check the bounding box or
  200. // left-side-bearing of the first character to be displayed and set
  201. // the current point based on that.
  202. //
  203. // Displaying a character:
  204. // Compute the bounding box of the character. It will contain signed values
  205. // relative to <current_point, baseline>. I.e. if it returns x0,y0,x1,y1,
  206. // then the character should be displayed in the rectangle from
  207. // <current_point+SF*x0, baseline+SF*y0> to <current_point+SF*x1,baseline+SF*y1).
  208. //
  209. // Advancing for the next character:
  210. // Call GlyphHMetrics, and compute 'current_point += SF * advance'.
  211. //
  212. //
  213. // ADVANCED USAGE
  214. //
  215. // Quality:
  216. //
  217. // - Use the functions with Subpixel at the end to allow your characters
  218. // to have subpixel positioning. Since the font is anti-aliased, not
  219. // hinted, this is very import for quality. (This is not possible with
  220. // baked fonts.)
  221. //
  222. // - Kerning is now supported, and if you're supporting subpixel rendering
  223. // then kerning is worth using to give your text a polished look.
  224. //
  225. // Performance:
  226. //
  227. // - Convert Unicode codepoints to glyph indexes and operate on the glyphs;
  228. // if you don't do this, stb_truetype is forced to do the conversion on
  229. // every call.
  230. //
  231. // - There are a lot of memory allocations. We should modify it to take
  232. // a temp buffer and allocate from the temp buffer (without freeing),
  233. // should help performance a lot.
  234. //
  235. // NOTES
  236. //
  237. // The system uses the raw data found in the .ttf file without changing it
  238. // and without building auxiliary data structures. This is a bit inefficient
  239. // on little-endian systems (the data is big-endian), but assuming you're
  240. // caching the bitmaps or glyph shapes this shouldn't be a big deal.
  241. //
  242. // It appears to be very hard to programmatically determine what font a
  243. // given file is in a general way. I provide an API for this, but I don't
  244. // recommend it.
  245. //
  246. //
  247. // SOURCE STATISTICS (based on v0.6c, 2050 LOC)
  248. //
  249. // Documentation & header file 520 LOC \___ 660 LOC documentation
  250. // Sample code 140 LOC /
  251. // Truetype parsing 620 LOC ---- 620 LOC TrueType
  252. // Software rasterization 240 LOC \ .
  253. // Curve tesselation 120 LOC \__ 550 LOC Bitmap creation
  254. // Bitmap management 100 LOC /
  255. // Baked bitmap interface 70 LOC /
  256. // Font name matching & access 150 LOC ---- 150
  257. // C runtime library abstraction 60 LOC ---- 60
  258. //
  259. //
  260. // PERFORMANCE MEASUREMENTS FOR 1.06:
  261. //
  262. // 32-bit 64-bit
  263. // Previous release: 8.83 s 7.68 s
  264. // Pool allocations: 7.72 s 6.34 s
  265. // Inline sort : 6.54 s 5.65 s
  266. // New rasterizer : 5.63 s 5.00 s
  267. //////////////////////////////////////////////////////////////////////////////
  268. //////////////////////////////////////////////////////////////////////////////
  269. ////
  270. //// SAMPLE PROGRAMS
  271. ////
  272. //
  273. // Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless
  274. //
  275. #if 0
  276. #define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation
  277. #include "stb_truetype.h"
  278. unsigned char ttf_buffer[1<<20];
  279. unsigned char temp_bitmap[512*512];
  280. stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs
  281. GLuint ftex;
  282. void my_stbtt_initfont(void)
  283. {
  284. fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb"));
  285. stbtt_BakeFontBitmap(ttf_buffer,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits!
  286. // can free ttf_buffer at this point
  287. glGenTextures(1, &ftex);
  288. glBindTexture(GL_TEXTURE_2D, ftex);
  289. glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap);
  290. // can free temp_bitmap at this point
  291. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  292. }
  293. void my_stbtt_print(float x, float y, char *text)
  294. {
  295. // assume orthographic projection with units = screen pixels, origin at top left
  296. glEnable(GL_TEXTURE_2D);
  297. glBindTexture(GL_TEXTURE_2D, ftex);
  298. glBegin(GL_QUADS);
  299. while (*text) {
  300. if (*text >= 32 && *text < 128) {
  301. stbtt_aligned_quad q;
  302. stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9
  303. glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y0);
  304. glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y0);
  305. glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y1);
  306. glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y1);
  307. }
  308. ++text;
  309. }
  310. glEnd();
  311. }
  312. #endif
  313. //
  314. //
  315. //////////////////////////////////////////////////////////////////////////////
  316. //
  317. // Complete program (this compiles): get a single bitmap, print as ASCII art
  318. //
  319. #if 0
  320. #include <stdio.h>
  321. #define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation
  322. #include "stb_truetype.h"
  323. char ttf_buffer[1<<25];
  324. int main(int argc, char **argv)
  325. {
  326. stbtt_fontinfo font;
  327. unsigned char *bitmap;
  328. int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20);
  329. fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb"));
  330. stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0));
  331. bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0);
  332. for (j=0; j < h; ++j) {
  333. for (i=0; i < w; ++i)
  334. putchar(" .:ioVM@"[bitmap[j*w+i]>>5]);
  335. putchar('\n');
  336. }
  337. return 0;
  338. }
  339. #endif
  340. //
  341. // Output:
  342. //
  343. // .ii.
  344. // @@@@@@.
  345. // V@Mio@@o
  346. // :i. V@V
  347. // :oM@@M
  348. // :@@@MM@M
  349. // @@o o@M
  350. // :@@. M@M
  351. // @@@o@@@@
  352. // :M@@V:@@.
  353. //
  354. //////////////////////////////////////////////////////////////////////////////
  355. //
  356. // Complete program: print "Hello World!" banner, with bugs
  357. //
  358. #if 0
  359. char buffer[24<<20];
  360. unsigned char screen[20][79];
  361. int main(int arg, char **argv)
  362. {
  363. stbtt_fontinfo font;
  364. int i,j,ascent,baseline,ch=0;
  365. float scale, xpos=2; // leave a little padding in case the character extends left
  366. char *text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness
  367. fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb"));
  368. stbtt_InitFont(&font, buffer, 0);
  369. scale = stbtt_ScaleForPixelHeight(&font, 15);
  370. stbtt_GetFontVMetrics(&font, &ascent,0,0);
  371. baseline = (int) (ascent*scale);
  372. while (text[ch]) {
  373. int advance,lsb,x0,y0,x1,y1;
  374. float x_shift = xpos - (float) floor(xpos);
  375. stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb);
  376. stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1);
  377. stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]);
  378. // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong
  379. // because this API is really for baking character bitmaps into textures. if you want to render
  380. // a sequence of characters, you really need to render each bitmap to a temp buffer, then
  381. // "alpha blend" that into the working buffer
  382. xpos += (advance * scale);
  383. if (text[ch+1])
  384. xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]);
  385. ++ch;
  386. }
  387. for (j=0; j < 20; ++j) {
  388. for (i=0; i < 78; ++i)
  389. putchar(" .:ioVM@"[screen[j][i]>>5]);
  390. putchar('\n');
  391. }
  392. return 0;
  393. }
  394. #endif
  395. //////////////////////////////////////////////////////////////////////////////
  396. //////////////////////////////////////////////////////////////////////////////
  397. ////
  398. //// INTEGRATION WITH YOUR CODEBASE
  399. ////
  400. //// The following sections allow you to supply alternate definitions
  401. //// of C library functions used by stb_truetype, e.g. if you don't
  402. //// link with the C runtime library.
  403. #ifdef STB_TRUETYPE_IMPLEMENTATION
  404. // #define your own (u)stbtt_int8/16/32 before including to override this
  405. #ifndef stbtt_uint8
  406. typedef unsigned char stbtt_uint8;
  407. typedef signed char stbtt_int8;
  408. typedef unsigned short stbtt_uint16;
  409. typedef signed short stbtt_int16;
  410. typedef unsigned int stbtt_uint32;
  411. typedef signed int stbtt_int32;
  412. #endif
  413. typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1];
  414. typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1];
  415. // e.g. #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h
  416. #ifndef STBTT_ifloor
  417. #include <math.h>
  418. #define STBTT_ifloor(x) ((int) floor(x))
  419. #define STBTT_iceil(x) ((int) ceil(x))
  420. #endif
  421. #ifndef STBTT_sqrt
  422. #include <math.h>
  423. #define STBTT_sqrt(x) sqrt(x)
  424. #define STBTT_pow(x,y) pow(x,y)
  425. #endif
  426. #ifndef STBTT_fmod
  427. #include <math.h>
  428. #define STBTT_fmod(x,y) fmod(x,y)
  429. #endif
  430. #ifndef STBTT_cos
  431. #include <math.h>
  432. #define STBTT_cos(x) cos(x)
  433. #define STBTT_acos(x) acos(x)
  434. #endif
  435. #ifndef STBTT_fabs
  436. #include <math.h>
  437. #define STBTT_fabs(x) fabs(x)
  438. #endif
  439. // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h
  440. #ifndef STBTT_malloc
  441. #include <stdlib.h>
  442. #define STBTT_malloc(x,u) ((void)(u),malloc(x))
  443. #define STBTT_free(x,u) ((void)(u),free(x))
  444. #endif
  445. #ifndef STBTT_assert
  446. #include <assert.h>
  447. #define STBTT_assert(x) assert(x)
  448. #endif
  449. #ifndef STBTT_strlen
  450. #include <string.h>
  451. #define STBTT_strlen(x) strlen(x)
  452. #endif
  453. #ifndef STBTT_memcpy
  454. #include <string.h>
  455. #define STBTT_memcpy memcpy
  456. #define STBTT_memset memset
  457. #endif
  458. #endif
  459. ///////////////////////////////////////////////////////////////////////////////
  460. ///////////////////////////////////////////////////////////////////////////////
  461. ////
  462. //// INTERFACE
  463. ////
  464. ////
  465. #ifndef __STB_INCLUDE_STB_TRUETYPE_H__
  466. #define __STB_INCLUDE_STB_TRUETYPE_H__
  467. #ifdef STBTT_STATIC
  468. #define STBTT_DEF static
  469. #else
  470. #define STBTT_DEF extern
  471. #endif
  472. #ifdef __cplusplus
  473. extern "C" {
  474. #endif
  475. // private structure
  476. typedef struct
  477. {
  478. unsigned char *data;
  479. int cursor;
  480. int size;
  481. } stbtt__buf;
  482. //////////////////////////////////////////////////////////////////////////////
  483. //
  484. // TEXTURE BAKING API
  485. //
  486. // If you use this API, you only have to call two functions ever.
  487. //
  488. typedef struct
  489. {
  490. unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap
  491. float xoff,yoff,xadvance;
  492. } stbtt_bakedchar;
  493. STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf)
  494. float pixel_height, // height of font in pixels
  495. unsigned char *pixels, int pw, int ph, // bitmap to be filled in
  496. int first_char, int num_chars, // characters to bake
  497. stbtt_bakedchar *chardata); // you allocate this, it's num_chars long
  498. // if return is positive, the first unused row of the bitmap
  499. // if return is negative, returns the negative of the number of characters that fit
  500. // if return is 0, no characters fit and no rows were used
  501. // This uses a very crappy packing.
  502. typedef struct
  503. {
  504. float x0,y0,s0,t0; // top-left
  505. float x1,y1,s1,t1; // bottom-right
  506. } stbtt_aligned_quad;
  507. STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, // same data as above
  508. int char_index, // character to display
  509. float *xpos, float *ypos, // pointers to current position in screen pixel space
  510. stbtt_aligned_quad *q, // output: quad to draw
  511. int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier
  512. // Call GetBakedQuad with char_index = 'character - first_char', and it
  513. // creates the quad you need to draw and advances the current position.
  514. //
  515. // The coordinate system used assumes y increases downwards.
  516. //
  517. // Characters will extend both above and below the current position;
  518. // see discussion of "BASELINE" above.
  519. //
  520. // It's inefficient; you might want to c&p it and optimize it.
  521. //////////////////////////////////////////////////////////////////////////////
  522. //
  523. // NEW TEXTURE BAKING API
  524. //
  525. // This provides options for packing multiple fonts into one atlas, not
  526. // perfectly but better than nothing.
  527. typedef struct
  528. {
  529. unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap
  530. float xoff,yoff,xadvance;
  531. float xoff2,yoff2;
  532. } stbtt_packedchar;
  533. typedef struct stbtt_pack_context stbtt_pack_context;
  534. typedef struct stbtt_fontinfo stbtt_fontinfo;
  535. #ifndef STB_RECT_PACK_VERSION
  536. typedef struct stbrp_rect stbrp_rect;
  537. #endif
  538. 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);
  539. // Initializes a packing context stored in the passed-in stbtt_pack_context.
  540. // Future calls using this context will pack characters into the bitmap passed
  541. // in here: a 1-channel bitmap that is width * height. stride_in_bytes is
  542. // the distance from one row to the next (or 0 to mean they are packed tightly
  543. // together). "padding" is the amount of padding to leave between each
  544. // character (normally you want '1' for bitmaps you'll use as textures with
  545. // bilinear filtering).
  546. //
  547. // Returns 0 on failure, 1 on success.
  548. STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc);
  549. // Cleans up the packing context and frees all memory.
  550. #define STBTT_POINT_SIZE(x) (-(x))
  551. STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size,
  552. int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range);
  553. // Creates character bitmaps from the font_index'th font found in fontdata (use
  554. // font_index=0 if you don't know what that is). It creates num_chars_in_range
  555. // bitmaps for characters with unicode values starting at first_unicode_char_in_range
  556. // and increasing. Data for how to render them is stored in chardata_for_range;
  557. // pass these to stbtt_GetPackedQuad to get back renderable quads.
  558. //
  559. // font_size is the full height of the character from ascender to descender,
  560. // as computed by stbtt_ScaleForPixelHeight. To use a point size as computed
  561. // by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE()
  562. // and pass that result as 'font_size':
  563. // ..., 20 , ... // font max minus min y is 20 pixels tall
  564. // ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall
  565. typedef struct
  566. {
  567. float font_size;
  568. int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint
  569. int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints
  570. int num_chars;
  571. stbtt_packedchar *chardata_for_range; // output
  572. unsigned char h_oversample, v_oversample; // don't set these, they're used internally
  573. } stbtt_pack_range;
  574. STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges);
  575. // Creates character bitmaps from multiple ranges of characters stored in
  576. // ranges. This will usually create a better-packed bitmap than multiple
  577. // calls to stbtt_PackFontRange. Note that you can call this multiple
  578. // times within a single PackBegin/PackEnd.
  579. STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample);
  580. // Oversampling a font increases the quality by allowing higher-quality subpixel
  581. // positioning, and is especially valuable at smaller text sizes.
  582. //
  583. // This function sets the amount of oversampling for all following calls to
  584. // stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given
  585. // pack context. The default (no oversampling) is achieved by h_oversample=1
  586. // and v_oversample=1. The total number of pixels required is
  587. // h_oversample*v_oversample larger than the default; for example, 2x2
  588. // oversampling requires 4x the storage of 1x1. For best results, render
  589. // oversampled textures with bilinear filtering. Look at the readme in
  590. // stb/tests/oversample for information about oversampled fonts
  591. //
  592. // To use with PackFontRangesGather etc., you must set it before calls
  593. // call to PackFontRangesGatherRects.
  594. STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, // same data as above
  595. int char_index, // character to display
  596. float *xpos, float *ypos, // pointers to current position in screen pixel space
  597. stbtt_aligned_quad *q, // output: quad to draw
  598. int align_to_integer);
  599. STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects);
  600. STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects);
  601. STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects);
  602. // Calling these functions in sequence is roughly equivalent to calling
  603. // stbtt_PackFontRanges(). If you more control over the packing of multiple
  604. // fonts, or if you want to pack custom data into a font texture, take a look
  605. // at the source to of stbtt_PackFontRanges() and create a custom version
  606. // using these functions, e.g. call GatherRects multiple times,
  607. // building up a single array of rects, then call PackRects once,
  608. // then call RenderIntoRects repeatedly. This may result in a
  609. // better packing than calling PackFontRanges multiple times
  610. // (or it may not).
  611. // this is an opaque structure that you shouldn't mess with which holds
  612. // all the context needed from PackBegin to PackEnd.
  613. struct stbtt_pack_context {
  614. void *user_allocator_context;
  615. void *pack_info;
  616. int width;
  617. int height;
  618. int stride_in_bytes;
  619. int padding;
  620. unsigned int h_oversample, v_oversample;
  621. unsigned char *pixels;
  622. void *nodes;
  623. };
  624. //////////////////////////////////////////////////////////////////////////////
  625. //
  626. // FONT LOADING
  627. //
  628. //
  629. STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data);
  630. // This function will determine the number of fonts in a font file. TrueType
  631. // collection (.ttc) files may contain multiple fonts, while TrueType font
  632. // (.ttf) files only contain one font. The number of fonts can be used for
  633. // indexing with the previous function where the index is between zero and one
  634. // less than the total fonts. If an error occurs, -1 is returned.
  635. STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index);
  636. // Each .ttf/.ttc file may have more than one font. Each font has a sequential
  637. // index number starting from 0. Call this function to get the font offset for
  638. // a given index; it returns -1 if the index is out of range. A regular .ttf
  639. // file will only define one font and it always be at offset 0, so it will
  640. // return '0' for index 0, and -1 for all other indices.
  641. // The following structure is defined publically so you can declare one on
  642. // the stack or as a global or etc, but you should treat it as opaque.
  643. struct stbtt_fontinfo
  644. {
  645. void * userdata;
  646. unsigned char * data; // pointer to .ttf file
  647. int fontstart; // offset of start of font
  648. int numGlyphs; // number of glyphs, needed for range checking
  649. int loca,head,glyf,hhea,hmtx,kern,gpos; // table locations as offset from start of .ttf
  650. int index_map; // a cmap mapping for our chosen character encoding
  651. int indexToLocFormat; // format needed to map from glyph index to glyph
  652. stbtt__buf cff; // cff font data
  653. stbtt__buf charstrings; // the charstring index
  654. stbtt__buf gsubrs; // global charstring subroutines index
  655. stbtt__buf subrs; // private charstring subroutines index
  656. stbtt__buf fontdicts; // array of font dicts
  657. stbtt__buf fdselect; // map from glyph to fontdict
  658. };
  659. STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset);
  660. // Given an offset into the file that defines a font, this function builds
  661. // the necessary cached info for the rest of the system. You must allocate
  662. // the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't
  663. // need to do anything special to free it, because the contents are pure
  664. // value data with no additional data structures. Returns 0 on failure.
  665. //////////////////////////////////////////////////////////////////////////////
  666. //
  667. // CHARACTER TO GLYPH-INDEX CONVERSIOn
  668. STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint);
  669. // If you're going to perform multiple operations on the same character
  670. // and you want a speed-up, call this function with the character you're
  671. // going to process, then use glyph-based functions instead of the
  672. // codepoint-based functions.
  673. //////////////////////////////////////////////////////////////////////////////
  674. //
  675. // CHARACTER PROPERTIES
  676. //
  677. STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels);
  678. // computes a scale factor to produce a font whose "height" is 'pixels' tall.
  679. // Height is measured as the distance from the highest ascender to the lowest
  680. // descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics
  681. // and computing:
  682. // scale = pixels / (ascent - descent)
  683. // so if you prefer to measure height by the ascent only, use a similar calculation.
  684. STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels);
  685. // computes a scale factor to produce a font whose EM size is mapped to
  686. // 'pixels' tall. This is probably what traditional APIs compute, but
  687. // I'm not positive.
  688. STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap);
  689. // ascent is the coordinate above the baseline the font extends; descent
  690. // is the coordinate below the baseline the font extends (i.e. it is typically negative)
  691. // lineGap is the spacing between one row's descent and the next row's ascent...
  692. // so you should advance the vertical position by "*ascent - *descent + *lineGap"
  693. // these are expressed in unscaled coordinates, so you must multiply by
  694. // the scale factor for a given size
  695. STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap);
  696. // analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2
  697. // table (specific to MS/Windows TTF files).
  698. //
  699. // Returns 1 on success (table present), 0 on failure.
  700. STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1);
  701. // the bounding box around all possible characters
  702. STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing);
  703. // leftSideBearing is the offset from the current horizontal position to the left edge of the character
  704. // advanceWidth is the offset from the current horizontal position to the next horizontal position
  705. // these are expressed in unscaled coordinates
  706. STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2);
  707. // an additional amount to add to the 'advance' value between ch1 and ch2
  708. STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1);
  709. // Gets the bounding box of the visible part of the glyph, in unscaled coordinates
  710. STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing);
  711. STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2);
  712. STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);
  713. // as above, but takes one or more glyph indices for greater efficiency
  714. //////////////////////////////////////////////////////////////////////////////
  715. //
  716. // GLYPH SHAPES (you probably don't need these, but they have to go before
  717. // the bitmaps for C declaration-order reasons)
  718. //
  719. #ifndef STBTT_vmove // you can predefine these to use different values (but why?)
  720. enum {
  721. STBTT_vmove=1,
  722. STBTT_vline,
  723. STBTT_vcurve,
  724. STBTT_vcubic
  725. };
  726. #endif
  727. #ifndef stbtt_vertex // you can predefine this to use different values
  728. // (we share this with other code at RAD)
  729. #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file
  730. typedef struct
  731. {
  732. stbtt_vertex_type x,y,cx,cy,cx1,cy1;
  733. unsigned char type,padding;
  734. } stbtt_vertex;
  735. #endif
  736. STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index);
  737. // returns non-zero if nothing is drawn for this glyph
  738. STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices);
  739. STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices);
  740. // returns # of vertices and fills *vertices with the pointer to them
  741. // these are expressed in "unscaled" coordinates
  742. //
  743. // The shape is a series of countours. Each one starts with
  744. // a STBTT_moveto, then consists of a series of mixed
  745. // STBTT_lineto and STBTT_curveto segments. A lineto
  746. // draws a line from previous endpoint to its x,y; a curveto
  747. // draws a quadratic bezier from previous endpoint to
  748. // its x,y, using cx,cy as the bezier control point.
  749. STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices);
  750. // frees the data allocated above
  751. //////////////////////////////////////////////////////////////////////////////
  752. //
  753. // BITMAP RENDERING
  754. //
  755. STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata);
  756. // frees the bitmap allocated below
  757. 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);
  758. // allocates a large-enough single-channel 8bpp bitmap and renders the
  759. // specified character/glyph at the specified scale into it, with
  760. // antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque).
  761. // *width & *height are filled out with the width & height of the bitmap,
  762. // which is stored left-to-right, top-to-bottom.
  763. //
  764. // xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap
  765. 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);
  766. // the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel
  767. // shift for the character
  768. 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);
  769. // the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap
  770. // in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap
  771. // is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the
  772. // width and height and positioning info for it first.
  773. 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);
  774. // same as stbtt_MakeCodepointBitmap, but you can specify a subpixel
  775. // shift for the character
  776. STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint);
  777. // same as stbtt_MakeCodepointBitmapSubpixel, but prefiltering
  778. // is performed (see stbtt_PackSetOversampling)
  779. 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);
  780. // get the bbox of the bitmap centered around the glyph origin; so the
  781. // bitmap width is ix1-ix0, height is iy1-iy0, and location to place
  782. // the bitmap top left is (leftSideBearing*scale,iy0).
  783. // (Note that the bitmap uses y-increases-down, but the shape uses
  784. // y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.)
  785. 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);
  786. // same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel
  787. // shift for the character
  788. // the following functions are equivalent to the above functions, but operate
  789. // on glyph indices instead of Unicode codepoints (for efficiency)
  790. 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);
  791. 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);
  792. 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);
  793. 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);
  794. STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int glyph);
  795. 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);
  796. 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);
  797. // @TODO: don't expose this structure
  798. typedef struct
  799. {
  800. int w,h,stride;
  801. unsigned char *pixels;
  802. } stbtt__bitmap;
  803. // rasterize a shape with quadratic beziers into a bitmap
  804. STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, // 1-channel bitmap to draw into
  805. float flatness_in_pixels, // allowable error of curve in pixels
  806. stbtt_vertex *vertices, // array of vertices defining shape
  807. int num_verts, // number of vertices in above array
  808. float scale_x, float scale_y, // scale applied to input vertices
  809. float shift_x, float shift_y, // translation applied to input vertices
  810. int x_off, int y_off, // another translation applied to input
  811. int invert, // if non-zero, vertically flip shape
  812. void *userdata); // context for to STBTT_MALLOC
  813. //////////////////////////////////////////////////////////////////////////////
  814. //
  815. // Signed Distance Function (or Field) rendering
  816. STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata);
  817. // frees the SDF bitmap allocated below
  818. STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff);
  819. STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff);
  820. // These functions compute a discretized SDF field for a single character, suitable for storing
  821. // in a single-channel texture, sampling with bilinear filtering, and testing against
  822. // larger than some threshhold to produce scalable fonts.
  823. // info -- the font
  824. // scale -- controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap
  825. // glyph/codepoint -- the character to generate the SDF for
  826. // padding -- extra "pixels" around the character which are filled with the distance to the character (not 0),
  827. // which allows effects like bit outlines
  828. // onedge_value -- value 0-255 to test the SDF against to reconstruct the character (i.e. the isocontour of the character)
  829. // pixel_dist_scale -- what value the SDF should increase by when moving one SDF "pixel" away from the edge (on the 0..255 scale)
  830. // if positive, > onedge_value is inside; if negative, < onedge_value is inside
  831. // width,height -- output height & width of the SDF bitmap (including padding)
  832. // xoff,yoff -- output origin of the character
  833. // return value -- a 2D array of bytes 0..255, width*height in size
  834. //
  835. // pixel_dist_scale & onedge_value are a scale & bias that allows you to make
  836. // optimal use of the limited 0..255 for your application, trading off precision
  837. // and special effects. SDF values outside the range 0..255 are clamped to 0..255.
  838. //
  839. // Example:
  840. // scale = stbtt_ScaleForPixelHeight(22)
  841. // padding = 5
  842. // onedge_value = 180
  843. // pixel_dist_scale = 180/5.0 = 36.0
  844. //
  845. // This will create an SDF bitmap in which the character is about 22 pixels
  846. // high but the whole bitmap is about 22+5+5=32 pixels high. To produce a filled
  847. // shape, sample the SDF at each pixel and fill the pixel if the SDF value
  848. // is greater than or equal to 180/255. (You'll actually want to antialias,
  849. // which is beyond the scope of this example.) Additionally, you can compute
  850. // offset outlines (e.g. to stroke the character border inside & outside,
  851. // or only outside). For example, to fill outside the character up to 3 SDF
  852. // pixels, you would compare against (180-36.0*3)/255 = 72/255. The above
  853. // choice of variables maps a range from 5 pixels outside the shape to
  854. // 2 pixels inside the shape to 0..255; this is intended primarily for apply
  855. // outside effects only (the interior range is needed to allow proper
  856. // antialiasing of the font at *smaller* sizes)
  857. //
  858. // The function computes the SDF analytically at each SDF pixel, not by e.g.
  859. // building a higher-res bitmap and approximating it. In theory the quality
  860. // should be as high as possible for an SDF of this size & representation, but
  861. // unclear if this is true in practice (perhaps building a higher-res bitmap
  862. // and computing from that can allow drop-out prevention).
  863. //
  864. // The algorithm has not been optimized at all, so expect it to be slow
  865. // if computing lots of characters or very large sizes.
  866. //////////////////////////////////////////////////////////////////////////////
  867. //
  868. // Finding the right font...
  869. //
  870. // You should really just solve this offline, keep your own tables
  871. // of what font is what, and don't try to get it out of the .ttf file.
  872. // That's because getting it out of the .ttf file is really hard, because
  873. // the names in the file can appear in many possible encodings, in many
  874. // possible languages, and e.g. if you need a case-insensitive comparison,
  875. // the details of that depend on the encoding & language in a complex way
  876. // (actually underspecified in truetype, but also gigantic).
  877. //
  878. // But you can use the provided functions in two possible ways:
  879. // stbtt_FindMatchingFont() will use *case-sensitive* comparisons on
  880. // unicode-encoded names to try to find the font you want;
  881. // you can run this before calling stbtt_InitFont()
  882. //
  883. // stbtt_GetFontNameString() lets you get any of the various strings
  884. // from the file yourself and do your own comparisons on them.
  885. // You have to have called stbtt_InitFont() first.
  886. STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags);
  887. // returns the offset (not index) of the font that matches, or -1 if none
  888. // if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold".
  889. // if you use any other flag, use a font name like "Arial"; this checks
  890. // the 'macStyle' header field; i don't know if fonts set this consistently
  891. #define STBTT_MACSTYLE_DONTCARE 0
  892. #define STBTT_MACSTYLE_BOLD 1
  893. #define STBTT_MACSTYLE_ITALIC 2
  894. #define STBTT_MACSTYLE_UNDERSCORE 4
  895. #define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0
  896. STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2);
  897. // returns 1/0 whether the first string interpreted as utf8 is identical to
  898. // the second string interpreted as big-endian utf16... useful for strings from next func
  899. STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID);
  900. // returns the string (which may be big-endian double byte, e.g. for unicode)
  901. // and puts the length in bytes in *length.
  902. //
  903. // some of the values for the IDs are below; for more see the truetype spec:
  904. // http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html
  905. // http://www.microsoft.com/typography/otspec/name.htm
  906. enum { // platformID
  907. STBTT_PLATFORM_ID_UNICODE =0,
  908. STBTT_PLATFORM_ID_MAC =1,
  909. STBTT_PLATFORM_ID_ISO =2,
  910. STBTT_PLATFORM_ID_MICROSOFT =3
  911. };
  912. enum { // encodingID for STBTT_PLATFORM_ID_UNICODE
  913. STBTT_UNICODE_EID_UNICODE_1_0 =0,
  914. STBTT_UNICODE_EID_UNICODE_1_1 =1,
  915. STBTT_UNICODE_EID_ISO_10646 =2,
  916. STBTT_UNICODE_EID_UNICODE_2_0_BMP=3,
  917. STBTT_UNICODE_EID_UNICODE_2_0_FULL=4
  918. };
  919. enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT
  920. STBTT_MS_EID_SYMBOL =0,
  921. STBTT_MS_EID_UNICODE_BMP =1,
  922. STBTT_MS_EID_SHIFTJIS =2,
  923. STBTT_MS_EID_UNICODE_FULL =10
  924. };
  925. enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes
  926. STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4,
  927. STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5,
  928. STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6,
  929. STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7
  930. };
  931. enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID...
  932. // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs
  933. STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410,
  934. STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411,
  935. STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412,
  936. STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419,
  937. STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409,
  938. STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D
  939. };
  940. enum { // languageID for STBTT_PLATFORM_ID_MAC
  941. STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11,
  942. STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23,
  943. STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32,
  944. STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 ,
  945. STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 ,
  946. STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33,
  947. STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19
  948. };
  949. #ifdef __cplusplus
  950. }
  951. #endif
  952. #endif // __STB_INCLUDE_STB_TRUETYPE_H__
  953. ///////////////////////////////////////////////////////////////////////////////
  954. ///////////////////////////////////////////////////////////////////////////////
  955. ////
  956. //// IMPLEMENTATION
  957. ////
  958. ////
  959. #ifdef STB_TRUETYPE_IMPLEMENTATION
  960. #ifndef STBTT_MAX_OVERSAMPLE
  961. #define STBTT_MAX_OVERSAMPLE 8
  962. #endif
  963. #if STBTT_MAX_OVERSAMPLE > 255
  964. #error "STBTT_MAX_OVERSAMPLE cannot be > 255"
  965. #endif
  966. typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1];
  967. #ifndef STBTT_RASTERIZER_VERSION
  968. #define STBTT_RASTERIZER_VERSION 2
  969. #endif
  970. #ifdef _MSC_VER
  971. #define STBTT__NOTUSED(v) (void)(v)
  972. #else
  973. #define STBTT__NOTUSED(v) (void)sizeof(v)
  974. #endif
  975. //////////////////////////////////////////////////////////////////////////
  976. //
  977. // stbtt__buf helpers to parse data from file
  978. //
  979. static stbtt_uint8 stbtt__buf_get8(stbtt__buf *b)
  980. {
  981. if (b->cursor >= b->size)
  982. return 0;
  983. return b->data[b->cursor++];
  984. }
  985. static stbtt_uint8 stbtt__buf_peek8(stbtt__buf *b)
  986. {
  987. if (b->cursor >= b->size)
  988. return 0;
  989. return b->data[b->cursor];
  990. }
  991. static void stbtt__buf_seek(stbtt__buf *b, int o)
  992. {
  993. STBTT_assert(!(o > b->size || o < 0));
  994. b->cursor = (o > b->size || o < 0) ? b->size : o;
  995. }
  996. static void stbtt__buf_skip(stbtt__buf *b, int o)
  997. {
  998. stbtt__buf_seek(b, b->cursor + o);
  999. }
  1000. static stbtt_uint32 stbtt__buf_get(stbtt__buf *b, int n)
  1001. {
  1002. stbtt_uint32 v = 0;
  1003. int i;
  1004. STBTT_assert(n >= 1 && n <= 4);
  1005. for (i = 0; i < n; i++)
  1006. v = (v << 8) | stbtt__buf_get8(b);
  1007. return v;
  1008. }
  1009. static stbtt__buf stbtt__new_buf(const void *p, size_t size)
  1010. {
  1011. stbtt__buf r;
  1012. STBTT_assert(size < 0x40000000);
  1013. r.data = (stbtt_uint8*) p;
  1014. r.size = (int) size;
  1015. r.cursor = 0;
  1016. return r;
  1017. }
  1018. #define stbtt__buf_get16(b) stbtt__buf_get((b), 2)
  1019. #define stbtt__buf_get32(b) stbtt__buf_get((b), 4)
  1020. static stbtt__buf stbtt__buf_range(const stbtt__buf *b, int o, int s)
  1021. {
  1022. stbtt__buf r = stbtt__new_buf(NULL, 0);
  1023. if (o < 0 || s < 0 || o > b->size || s > b->size - o) return r;
  1024. r.data = b->data + o;
  1025. r.size = s;
  1026. return r;
  1027. }
  1028. static stbtt__buf stbtt__cff_get_index(stbtt__buf *b)
  1029. {
  1030. int count, start, offsize;
  1031. start = b->cursor;
  1032. count = stbtt__buf_get16(b);
  1033. if (count) {
  1034. offsize = stbtt__buf_get8(b);
  1035. STBTT_assert(offsize >= 1 && offsize <= 4);
  1036. stbtt__buf_skip(b, offsize * count);
  1037. stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1);
  1038. }
  1039. return stbtt__buf_range(b, start, b->cursor - start);
  1040. }
  1041. static stbtt_uint32 stbtt__cff_int(stbtt__buf *b)
  1042. {
  1043. int b0 = stbtt__buf_get8(b);
  1044. if (b0 >= 32 && b0 <= 246) return b0 - 139;
  1045. else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108;
  1046. else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108;
  1047. else if (b0 == 28) return stbtt__buf_get16(b);
  1048. else if (b0 == 29) return stbtt__buf_get32(b);
  1049. STBTT_assert(0);
  1050. return 0;
  1051. }
  1052. static void stbtt__cff_skip_operand(stbtt__buf *b) {
  1053. int v, b0 = stbtt__buf_peek8(b);
  1054. STBTT_assert(b0 >= 28);
  1055. if (b0 == 30) {
  1056. stbtt__buf_skip(b, 1);
  1057. while (b->cursor < b->size) {
  1058. v = stbtt__buf_get8(b);
  1059. if ((v & 0xF) == 0xF || (v >> 4) == 0xF)
  1060. break;
  1061. }
  1062. } else {
  1063. stbtt__cff_int(b);
  1064. }
  1065. }
  1066. static stbtt__buf stbtt__dict_get(stbtt__buf *b, int key)
  1067. {
  1068. stbtt__buf_seek(b, 0);
  1069. while (b->cursor < b->size) {
  1070. int start = b->cursor, end, op;
  1071. while (stbtt__buf_peek8(b) >= 28)
  1072. stbtt__cff_skip_operand(b);
  1073. end = b->cursor;
  1074. op = stbtt__buf_get8(b);
  1075. if (op == 12) op = stbtt__buf_get8(b) | 0x100;
  1076. if (op == key) return stbtt__buf_range(b, start, end-start);
  1077. }
  1078. return stbtt__buf_range(b, 0, 0);
  1079. }
  1080. static void stbtt__dict_get_ints(stbtt__buf *b, int key, int outcount, stbtt_uint32 *out)
  1081. {
  1082. int i;
  1083. stbtt__buf operands = stbtt__dict_get(b, key);
  1084. for (i = 0; i < outcount && operands.cursor < operands.size; i++)
  1085. out[i] = stbtt__cff_int(&operands);
  1086. }
  1087. static int stbtt__cff_index_count(stbtt__buf *b)
  1088. {
  1089. stbtt__buf_seek(b, 0);
  1090. return stbtt__buf_get16(b);
  1091. }
  1092. static stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i)
  1093. {
  1094. int count, offsize, start, end;
  1095. stbtt__buf_seek(&b, 0);
  1096. count = stbtt__buf_get16(&b);
  1097. offsize = stbtt__buf_get8(&b);
  1098. STBTT_assert(i >= 0 && i < count);
  1099. STBTT_assert(offsize >= 1 && offsize <= 4);
  1100. stbtt__buf_skip(&b, i*offsize);
  1101. start = stbtt__buf_get(&b, offsize);
  1102. end = stbtt__buf_get(&b, offsize);
  1103. return stbtt__buf_range(&b, 2+(count+1)*offsize+start, end - start);
  1104. }
  1105. //////////////////////////////////////////////////////////////////////////
  1106. //
  1107. // accessors to parse data from file
  1108. //
  1109. // on platforms that don't allow misaligned reads, if we want to allow
  1110. // truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE
  1111. #define ttBYTE(p) (* (stbtt_uint8 *) (p))
  1112. #define ttCHAR(p) (* (stbtt_int8 *) (p))
  1113. #define ttFixed(p) ttLONG(p)
  1114. static stbtt_uint16 ttUSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; }
  1115. static stbtt_int16 ttSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; }
  1116. static stbtt_uint32 ttULONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
  1117. static stbtt_int32 ttLONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
  1118. #define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3))
  1119. #define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3])
  1120. static int stbtt__isfont(stbtt_uint8 *font)
  1121. {
  1122. // check the version number
  1123. if (stbtt_tag4(font, '1',0,0,0)) return 1; // TrueType 1
  1124. if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this!
  1125. if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF
  1126. if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0
  1127. if (stbtt_tag(font, "true")) return 1; // Apple specification for TrueType fonts
  1128. return 0;
  1129. }
  1130. // @OPTIMIZE: binary search
  1131. static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag)
  1132. {
  1133. stbtt_int32 num_tables = ttUSHORT(data+fontstart+4);
  1134. stbtt_uint32 tabledir = fontstart + 12;
  1135. stbtt_int32 i;
  1136. for (i=0; i < num_tables; ++i) {
  1137. stbtt_uint32 loc = tabledir + 16*i;
  1138. if (stbtt_tag(data+loc+0, tag))
  1139. return ttULONG(data+loc+8);
  1140. }
  1141. return 0;
  1142. }
  1143. static int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection, int index)
  1144. {
  1145. // if it's just a font, there's only one valid index
  1146. if (stbtt__isfont(font_collection))
  1147. return index == 0 ? 0 : -1;
  1148. // check if it's a TTC
  1149. if (stbtt_tag(font_collection, "ttcf")) {
  1150. // version 1?
  1151. if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {
  1152. stbtt_int32 n = ttLONG(font_collection+8);
  1153. if (index >= n)
  1154. return -1;
  1155. return ttULONG(font_collection+12+index*4);
  1156. }
  1157. }
  1158. return -1;
  1159. }
  1160. static int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection)
  1161. {
  1162. // if it's just a font, there's only one valid font
  1163. if (stbtt__isfont(font_collection))
  1164. return 1;
  1165. // check if it's a TTC
  1166. if (stbtt_tag(font_collection, "ttcf")) {
  1167. // version 1?
  1168. if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {
  1169. return ttLONG(font_collection+8);
  1170. }
  1171. }
  1172. return 0;
  1173. }
  1174. static stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict)
  1175. {
  1176. stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 };
  1177. stbtt__buf pdict;
  1178. stbtt__dict_get_ints(&fontdict, 18, 2, private_loc);
  1179. if (!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0);
  1180. pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]);
  1181. stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff);
  1182. if (!subrsoff) return stbtt__new_buf(NULL, 0);
  1183. stbtt__buf_seek(&cff, private_loc[1]+subrsoff);
  1184. return stbtt__cff_get_index(&cff);
  1185. }
  1186. static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, int fontstart)
  1187. {
  1188. stbtt_uint32 cmap, t;
  1189. stbtt_int32 i,numTables;
  1190. info->data = data;
  1191. info->fontstart = fontstart;
  1192. info->cff = stbtt__new_buf(NULL, 0);
  1193. cmap = stbtt__find_table(data, fontstart, "cmap"); // required
  1194. info->loca = stbtt__find_table(data, fontstart, "loca"); // required
  1195. info->head = stbtt__find_table(data, fontstart, "head"); // required
  1196. info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required
  1197. info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required
  1198. info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required
  1199. info->kern = stbtt__find_table(data, fontstart, "kern"); // not required
  1200. info->gpos = stbtt__find_table(data, fontstart, "GPOS"); // not required
  1201. if (!cmap || !info->head || !info->hhea || !info->hmtx)
  1202. return 0;
  1203. if (info->glyf) {
  1204. // required for truetype
  1205. if (!info->loca) return 0;
  1206. } else {
  1207. // initialization for CFF / Type2 fonts (OTF)
  1208. stbtt__buf b, topdict, topdictidx;
  1209. stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0;
  1210. stbtt_uint32 cff;
  1211. cff = stbtt__find_table(data, fontstart, "CFF ");
  1212. if (!cff) return 0;
  1213. info->fontdicts = stbtt__new_buf(NULL, 0);
  1214. info->fdselect = stbtt__new_buf(NULL, 0);
  1215. // @TODO this should use size from table (not 512MB)
  1216. info->cff = stbtt__new_buf(data+cff, 512*1024*1024);
  1217. b = info->cff;
  1218. // read the header
  1219. stbtt__buf_skip(&b, 2);
  1220. stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize
  1221. // @TODO the name INDEX could list multiple fonts,
  1222. // but we just use the first one.
  1223. stbtt__cff_get_index(&b); // name INDEX
  1224. topdictidx = stbtt__cff_get_index(&b);
  1225. topdict = stbtt__cff_index_get(topdictidx, 0);
  1226. stbtt__cff_get_index(&b); // string INDEX
  1227. info->gsubrs = stbtt__cff_get_index(&b);
  1228. stbtt__dict_get_ints(&topdict, 17, 1, &charstrings);
  1229. stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype);
  1230. stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff);
  1231. stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff);
  1232. info->subrs = stbtt__get_subrs(b, topdict);
  1233. // we only support Type 2 charstrings
  1234. if (cstype != 2) return 0;
  1235. if (charstrings == 0) return 0;
  1236. if (fdarrayoff) {
  1237. // looks like a CID font
  1238. if (!fdselectoff) return 0;
  1239. stbtt__buf_seek(&b, fdarrayoff);
  1240. info->fontdicts = stbtt__cff_get_index(&b);
  1241. info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size-fdselectoff);
  1242. }
  1243. stbtt__buf_seek(&b, charstrings);
  1244. info->charstrings = stbtt__cff_get_index(&b);
  1245. }
  1246. t = stbtt__find_table(data, fontstart, "maxp");
  1247. if (t)
  1248. info->numGlyphs = ttUSHORT(data+t+4);
  1249. else
  1250. info->numGlyphs = 0xffff;
  1251. // find a cmap encoding table we understand *now* to avoid searching
  1252. // later. (todo: could make this installable)
  1253. // the same regardless of glyph.
  1254. numTables = ttUSHORT(data + cmap + 2);
  1255. info->index_map = 0;
  1256. for (i=0; i < numTables; ++i) {
  1257. stbtt_uint32 encoding_record = cmap + 4 + 8 * i;
  1258. // find an encoding we understand:
  1259. switch(ttUSHORT(data+encoding_record)) {
  1260. case STBTT_PLATFORM_ID_MICROSOFT:
  1261. switch (ttUSHORT(data+encoding_record+2)) {
  1262. case STBTT_MS_EID_UNICODE_BMP:
  1263. case STBTT_MS_EID_UNICODE_FULL:
  1264. // MS/Unicode
  1265. info->index_map = cmap + ttULONG(data+encoding_record+4);
  1266. break;
  1267. }
  1268. break;
  1269. case STBTT_PLATFORM_ID_UNICODE:
  1270. // Mac/iOS has these
  1271. // all the encodingIDs are unicode, so we don't bother to check it
  1272. info->index_map = cmap + ttULONG(data+encoding_record+4);
  1273. break;
  1274. }
  1275. }
  1276. if (info->index_map == 0)
  1277. return 0;
  1278. info->indexToLocFormat = ttUSHORT(data+info->head + 50);
  1279. return 1;
  1280. }
  1281. STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint)
  1282. {
  1283. stbtt_uint8 *data = info->data;
  1284. stbtt_uint32 index_map = info->index_map;
  1285. stbtt_uint16 format = ttUSHORT(data + index_map + 0);
  1286. if (format == 0) { // apple byte encoding
  1287. stbtt_int32 bytes = ttUSHORT(data + index_map + 2);
  1288. if (unicode_codepoint < bytes-6)
  1289. return ttBYTE(data + index_map + 6 + unicode_codepoint);
  1290. return 0;
  1291. } else if (format == 6) {
  1292. stbtt_uint32 first = ttUSHORT(data + index_map + 6);
  1293. stbtt_uint32 count = ttUSHORT(data + index_map + 8);
  1294. if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count)
  1295. return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2);
  1296. return 0;
  1297. } else if (format == 2) {
  1298. STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean
  1299. return 0;
  1300. } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges
  1301. stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1;
  1302. stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1;
  1303. stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10);
  1304. stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1;
  1305. // do a binary search of the segments
  1306. stbtt_uint32 endCount = index_map + 14;
  1307. stbtt_uint32 search = endCount;
  1308. if (unicode_codepoint > 0xffff)
  1309. return 0;
  1310. // they lie from endCount .. endCount + segCount
  1311. // but searchRange is the nearest power of two, so...
  1312. if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2))
  1313. search += rangeShift*2;
  1314. // now decrement to bias correctly to find smallest
  1315. search -= 2;
  1316. while (entrySelector) {
  1317. stbtt_uint16 end;
  1318. searchRange >>= 1;
  1319. end = ttUSHORT(data + search + searchRange*2);
  1320. if (unicode_codepoint > end)
  1321. search += searchRange*2;
  1322. --entrySelector;
  1323. }
  1324. search += 2;
  1325. {
  1326. stbtt_uint16 offset, start;
  1327. stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1);
  1328. STBTT_assert(unicode_codepoint <= ttUSHORT(data + endCount + 2*item));
  1329. start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item);
  1330. if (unicode_codepoint < start)
  1331. return 0;
  1332. offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item);
  1333. if (offset == 0)
  1334. return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item));
  1335. return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item);
  1336. }
  1337. } else if (format == 12 || format == 13) {
  1338. stbtt_uint32 ngroups = ttULONG(data+index_map+12);
  1339. stbtt_int32 low,high;
  1340. low = 0; high = (stbtt_int32)ngroups;
  1341. // Binary search the right group.
  1342. while (low < high) {
  1343. stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high
  1344. stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12);
  1345. stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4);
  1346. if ((stbtt_uint32) unicode_codepoint < start_char)
  1347. high = mid;
  1348. else if ((stbtt_uint32) unicode_codepoint > end_char)
  1349. low = mid+1;
  1350. else {
  1351. stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8);
  1352. if (format == 12)
  1353. return start_glyph + unicode_codepoint-start_char;
  1354. else // format == 13
  1355. return start_glyph;
  1356. }
  1357. }
  1358. return 0; // not found
  1359. }
  1360. // @TODO
  1361. STBTT_assert(0);
  1362. return 0;
  1363. }
  1364. STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices)
  1365. {
  1366. return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices);
  1367. }
  1368. static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy)
  1369. {
  1370. v->type = type;
  1371. v->x = (stbtt_int16) x;
  1372. v->y = (stbtt_int16) y;
  1373. v->cx = (stbtt_int16) cx;
  1374. v->cy = (stbtt_int16) cy;
  1375. }
  1376. static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index)
  1377. {
  1378. int g1,g2;
  1379. STBTT_assert(!info->cff.size);
  1380. if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range
  1381. if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format
  1382. if (info->indexToLocFormat == 0) {
  1383. g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2;
  1384. g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2;
  1385. } else {
  1386. g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4);
  1387. g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4);
  1388. }
  1389. return g1==g2 ? -1 : g1; // if length is 0, return -1
  1390. }
  1391. static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);
  1392. STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)
  1393. {
  1394. if (info->cff.size) {
  1395. stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1);
  1396. } else {
  1397. int g = stbtt__GetGlyfOffset(info, glyph_index);
  1398. if (g < 0) return 0;
  1399. if (x0) *x0 = ttSHORT(info->data + g + 2);
  1400. if (y0) *y0 = ttSHORT(info->data + g + 4);
  1401. if (x1) *x1 = ttSHORT(info->data + g + 6);
  1402. if (y1) *y1 = ttSHORT(info->data + g + 8);
  1403. }
  1404. return 1;
  1405. }
  1406. STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1)
  1407. {
  1408. return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1);
  1409. }
  1410. STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index)
  1411. {
  1412. stbtt_int16 numberOfContours;
  1413. int g;
  1414. if (info->cff.size)
  1415. return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0;
  1416. g = stbtt__GetGlyfOffset(info, glyph_index);
  1417. if (g < 0) return 1;
  1418. numberOfContours = ttSHORT(info->data + g);
  1419. return numberOfContours == 0;
  1420. }
  1421. static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off,
  1422. stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy)
  1423. {
  1424. if (start_off) {
  1425. if (was_off)
  1426. stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy);
  1427. stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy);
  1428. } else {
  1429. if (was_off)
  1430. stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy);
  1431. else
  1432. stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0);
  1433. }
  1434. return num_vertices;
  1435. }
  1436. static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
  1437. {
  1438. stbtt_int16 numberOfContours;
  1439. stbtt_uint8 *endPtsOfContours;
  1440. stbtt_uint8 *data = info->data;
  1441. stbtt_vertex *vertices=0;
  1442. int num_vertices=0;
  1443. int g = stbtt__GetGlyfOffset(info, glyph_index);
  1444. *pvertices = NULL;
  1445. if (g < 0) return 0;
  1446. numberOfContours = ttSHORT(data + g);
  1447. if (numberOfContours > 0) {
  1448. stbtt_uint8 flags=0,flagcount;
  1449. stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0;
  1450. stbtt_int32 x,y,cx,cy,sx,sy, scx,scy;
  1451. stbtt_uint8 *points;
  1452. endPtsOfContours = (data + g + 10);
  1453. ins = ttUSHORT(data + g + 10 + numberOfContours * 2);
  1454. points = data + g + 10 + numberOfContours * 2 + 2 + ins;
  1455. n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2);
  1456. m = n + 2*numberOfContours; // a loose bound on how many vertices we might need
  1457. vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata);
  1458. if (vertices == 0)
  1459. return 0;
  1460. next_move = 0;
  1461. flagcount=0;
  1462. // in first pass, we load uninterpreted data into the allocated array
  1463. // above, shifted to the end of the array so we won't overwrite it when
  1464. // we create our final data starting from the front
  1465. off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated
  1466. // first load flags
  1467. for (i=0; i < n; ++i) {
  1468. if (flagcount == 0) {
  1469. flags = *points++;
  1470. if (flags & 8)
  1471. flagcount = *points++;
  1472. } else
  1473. --flagcount;
  1474. vertices[off+i].type = flags;
  1475. }
  1476. // now load x coordinates
  1477. x=0;
  1478. for (i=0; i < n; ++i) {
  1479. flags = vertices[off+i].type;
  1480. if (flags & 2) {
  1481. stbtt_int16 dx = *points++;
  1482. x += (flags & 16) ? dx : -dx; // ???
  1483. } else {
  1484. if (!(flags & 16)) {
  1485. x = x + (stbtt_int16) (points[0]*256 + points[1]);
  1486. points += 2;
  1487. }
  1488. }
  1489. vertices[off+i].x = (stbtt_int16) x;
  1490. }
  1491. // now load y coordinates
  1492. y=0;
  1493. for (i=0; i < n; ++i) {
  1494. flags = vertices[off+i].type;
  1495. if (flags & 4) {
  1496. stbtt_int16 dy = *points++;
  1497. y += (flags & 32) ? dy : -dy; // ???
  1498. } else {
  1499. if (!(flags & 32)) {
  1500. y = y + (stbtt_int16) (points[0]*256 + points[1]);
  1501. points += 2;
  1502. }
  1503. }
  1504. vertices[off+i].y = (stbtt_int16) y;
  1505. }
  1506. // now convert them to our format
  1507. num_vertices=0;
  1508. sx = sy = cx = cy = scx = scy = 0;
  1509. for (i=0; i < n; ++i) {
  1510. flags = vertices[off+i].type;
  1511. x = (stbtt_int16) vertices[off+i].x;
  1512. y = (stbtt_int16) vertices[off+i].y;
  1513. if (next_move == i) {
  1514. if (i != 0)
  1515. num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);
  1516. // now start the new one
  1517. start_off = !(flags & 1);
  1518. if (start_off) {
  1519. // if we start off with an off-curve point, then when we need to find a point on the curve
  1520. // where we can start, and we need to save some state for when we wraparound.
  1521. scx = x;
  1522. scy = y;
  1523. if (!(vertices[off+i+1].type & 1)) {
  1524. // next point is also a curve point, so interpolate an on-point curve
  1525. sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1;
  1526. sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1;
  1527. } else {
  1528. // otherwise just use the next point as our start point
  1529. sx = (stbtt_int32) vertices[off+i+1].x;
  1530. sy = (stbtt_int32) vertices[off+i+1].y;
  1531. ++i; // we're using point i+1 as the starting point, so skip it
  1532. }
  1533. } else {
  1534. sx = x;
  1535. sy = y;
  1536. }
  1537. stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0);
  1538. was_off = 0;
  1539. next_move = 1 + ttUSHORT(endPtsOfContours+j*2);
  1540. ++j;
  1541. } else {
  1542. if (!(flags & 1)) { // if it's a curve
  1543. if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint
  1544. stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy);
  1545. cx = x;
  1546. cy = y;
  1547. was_off = 1;
  1548. } else {
  1549. if (was_off)
  1550. stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy);
  1551. else
  1552. stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0);
  1553. was_off = 0;
  1554. }
  1555. }
  1556. }
  1557. num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);
  1558. } else if (numberOfContours == -1) {
  1559. // Compound shapes.
  1560. int more = 1;
  1561. stbtt_uint8 *comp = data + g + 10;
  1562. num_vertices = 0;
  1563. vertices = 0;
  1564. while (more) {
  1565. stbtt_uint16 flags, gidx;
  1566. int comp_num_verts = 0, i;
  1567. stbtt_vertex *comp_verts = 0, *tmp = 0;
  1568. float mtx[6] = {1,0,0,1,0,0}, m, n;
  1569. flags = ttSHORT(comp); comp+=2;
  1570. gidx = ttSHORT(comp); comp+=2;
  1571. if (flags & 2) { // XY values
  1572. if (flags & 1) { // shorts
  1573. mtx[4] = ttSHORT(comp); comp+=2;
  1574. mtx[5] = ttSHORT(comp); comp+=2;
  1575. } else {
  1576. mtx[4] = ttCHAR(comp); comp+=1;
  1577. mtx[5] = ttCHAR(comp); comp+=1;
  1578. }
  1579. }
  1580. else {
  1581. // @TODO handle matching point
  1582. STBTT_assert(0);
  1583. }
  1584. if (flags & (1<<3)) { // WE_HAVE_A_SCALE
  1585. mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
  1586. mtx[1] = mtx[2] = 0;
  1587. } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE
  1588. mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;
  1589. mtx[1] = mtx[2] = 0;
  1590. mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
  1591. } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO
  1592. mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;
  1593. mtx[1] = ttSHORT(comp)/16384.0f; comp+=2;
  1594. mtx[2] = ttSHORT(comp)/16384.0f; comp+=2;
  1595. mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
  1596. }
  1597. // Find transformation scales.
  1598. m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]);
  1599. n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]);
  1600. // Get indexed glyph.
  1601. comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts);
  1602. if (comp_num_verts > 0) {
  1603. // Transform vertices.
  1604. for (i = 0; i < comp_num_verts; ++i) {
  1605. stbtt_vertex* v = &comp_verts[i];
  1606. stbtt_vertex_type x,y;
  1607. x=v->x; y=v->y;
  1608. v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));
  1609. v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));
  1610. x=v->cx; y=v->cy;
  1611. v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));
  1612. v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));
  1613. }
  1614. // Append vertices.
  1615. tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata);
  1616. if (!tmp) {
  1617. if (vertices) STBTT_free(vertices, info->userdata);
  1618. if (comp_verts) STBTT_free(comp_verts, info->userdata);
  1619. return 0;
  1620. }
  1621. if (num_vertices > 0) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex));
  1622. STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex));
  1623. if (vertices) STBTT_free(vertices, info->userdata);
  1624. vertices = tmp;
  1625. STBTT_free(comp_verts, info->userdata);
  1626. num_vertices += comp_num_verts;
  1627. }
  1628. // More components ?
  1629. more = flags & (1<<5);
  1630. }
  1631. } else if (numberOfContours < 0) {
  1632. // @TODO other compound variations?
  1633. STBTT_assert(0);
  1634. } else {
  1635. // numberOfCounters == 0, do nothing
  1636. }
  1637. *pvertices = vertices;
  1638. return num_vertices;
  1639. }
  1640. typedef struct
  1641. {
  1642. int bounds;
  1643. int started;
  1644. float first_x, first_y;
  1645. float x, y;
  1646. stbtt_int32 min_x, max_x, min_y, max_y;
  1647. stbtt_vertex *pvertices;
  1648. int num_vertices;
  1649. } stbtt__csctx;
  1650. #define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0}
  1651. static void stbtt__track_vertex(stbtt__csctx *c, stbtt_int32 x, stbtt_int32 y)
  1652. {
  1653. if (x > c->max_x || !c->started) c->max_x = x;
  1654. if (y > c->max_y || !c->started) c->max_y = y;
  1655. if (x < c->min_x || !c->started) c->min_x = x;
  1656. if (y < c->min_y || !c->started) c->min_y = y;
  1657. c->started = 1;
  1658. }
  1659. static void stbtt__csctx_v(stbtt__csctx *c, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy, stbtt_int32 cx1, stbtt_int32 cy1)
  1660. {
  1661. if (c->bounds) {
  1662. stbtt__track_vertex(c, x, y);
  1663. if (type == STBTT_vcubic) {
  1664. stbtt__track_vertex(c, cx, cy);
  1665. stbtt__track_vertex(c, cx1, cy1);
  1666. }
  1667. } else {
  1668. stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy);
  1669. c->pvertices[c->num_vertices].cx1 = (stbtt_int16) cx1;
  1670. c->pvertices[c->num_vertices].cy1 = (stbtt_int16) cy1;
  1671. }
  1672. c->num_vertices++;
  1673. }
  1674. static void stbtt__csctx_close_shape(stbtt__csctx *ctx)
  1675. {
  1676. if (ctx->first_x != ctx->x || ctx->first_y != ctx->y)
  1677. stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0);
  1678. }
  1679. static void stbtt__csctx_rmove_to(stbtt__csctx *ctx, float dx, float dy)
  1680. {
  1681. stbtt__csctx_close_shape(ctx);
  1682. ctx->first_x = ctx->x = ctx->x + dx;
  1683. ctx->first_y = ctx->y = ctx->y + dy;
  1684. stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0);
  1685. }
  1686. static void stbtt__csctx_rline_to(stbtt__csctx *ctx, float dx, float dy)
  1687. {
  1688. ctx->x += dx;
  1689. ctx->y += dy;
  1690. stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0);
  1691. }
  1692. static void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3)
  1693. {
  1694. float cx1 = ctx->x + dx1;
  1695. float cy1 = ctx->y + dy1;
  1696. float cx2 = cx1 + dx2;
  1697. float cy2 = cy1 + dy2;
  1698. ctx->x = cx2 + dx3;
  1699. ctx->y = cy2 + dy3;
  1700. stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2);
  1701. }
  1702. static stbtt__buf stbtt__get_subr(stbtt__buf idx, int n)
  1703. {
  1704. int count = stbtt__cff_index_count(&idx);
  1705. int bias = 107;
  1706. if (count >= 33900)
  1707. bias = 32768;
  1708. else if (count >= 1240)
  1709. bias = 1131;
  1710. n += bias;
  1711. if (n < 0 || n >= count)
  1712. return stbtt__new_buf(NULL, 0);
  1713. return stbtt__cff_index_get(idx, n);
  1714. }
  1715. static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int glyph_index)
  1716. {
  1717. stbtt__buf fdselect = info->fdselect;
  1718. int nranges, start, end, v, fmt, fdselector = -1, i;
  1719. stbtt__buf_seek(&fdselect, 0);
  1720. fmt = stbtt__buf_get8(&fdselect);
  1721. if (fmt == 0) {
  1722. // untested
  1723. stbtt__buf_skip(&fdselect, glyph_index);
  1724. fdselector = stbtt__buf_get8(&fdselect);
  1725. } else if (fmt == 3) {
  1726. nranges = stbtt__buf_get16(&fdselect);
  1727. start = stbtt__buf_get16(&fdselect);
  1728. for (i = 0; i < nranges; i++) {
  1729. v = stbtt__buf_get8(&fdselect);
  1730. end = stbtt__buf_get16(&fdselect);
  1731. if (glyph_index >= start && glyph_index < end) {
  1732. fdselector = v;
  1733. break;
  1734. }
  1735. start = end;
  1736. }
  1737. }
  1738. if (fdselector == -1) stbtt__new_buf(NULL, 0);
  1739. return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector));
  1740. }
  1741. static int stbtt__run_charstring(const stbtt_fontinfo *info, int glyph_index, stbtt__csctx *c)
  1742. {
  1743. int in_header = 1, maskbits = 0, subr_stack_height = 0, sp = 0, v, i, b0;
  1744. int has_subrs = 0, clear_stack;
  1745. float s[48];
  1746. stbtt__buf subr_stack[10], subrs = info->subrs, b;
  1747. float f;
  1748. #define STBTT__CSERR(s) (0)
  1749. // this currently ignores the initial width value, which isn't needed if we have hmtx
  1750. b = stbtt__cff_index_get(info->charstrings, glyph_index);
  1751. while (b.cursor < b.size) {
  1752. i = 0;
  1753. clear_stack = 1;
  1754. b0 = stbtt__buf_get8(&b);
  1755. switch (b0) {
  1756. // @TODO implement hinting
  1757. case 0x13: // hintmask
  1758. case 0x14: // cntrmask
  1759. if (in_header)
  1760. maskbits += (sp / 2); // implicit "vstem"
  1761. in_header = 0;
  1762. stbtt__buf_skip(&b, (maskbits + 7) / 8);
  1763. break;
  1764. case 0x01: // hstem
  1765. case 0x03: // vstem
  1766. case 0x12: // hstemhm
  1767. case 0x17: // vstemhm
  1768. maskbits += (sp / 2);
  1769. break;
  1770. case 0x15: // rmoveto
  1771. in_header = 0;
  1772. if (sp < 2) return STBTT__CSERR("rmoveto stack");
  1773. stbtt__csctx_rmove_to(c, s[sp-2], s[sp-1]);
  1774. break;
  1775. case 0x04: // vmoveto
  1776. in_header = 0;
  1777. if (sp < 1) return STBTT__CSERR("vmoveto stack");
  1778. stbtt__csctx_rmove_to(c, 0, s[sp-1]);
  1779. break;
  1780. case 0x16: // hmoveto
  1781. in_header = 0;
  1782. if (sp < 1) return STBTT__CSERR("hmoveto stack");
  1783. stbtt__csctx_rmove_to(c, s[sp-1], 0);
  1784. break;
  1785. case 0x05: // rlineto
  1786. if (sp < 2) return STBTT__CSERR("rlineto stack");
  1787. for (; i + 1 < sp; i += 2)
  1788. stbtt__csctx_rline_to(c, s[i], s[i+1]);
  1789. break;
  1790. // hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical
  1791. // starting from a different place.
  1792. case 0x07: // vlineto
  1793. if (sp < 1) return STBTT__CSERR("vlineto stack");
  1794. goto vlineto;
  1795. case 0x06: // hlineto
  1796. if (sp < 1) return STBTT__CSERR("hlineto stack");
  1797. for (;;) {
  1798. if (i >= sp) break;
  1799. stbtt__csctx_rline_to(c, s[i], 0);
  1800. i++;
  1801. vlineto:
  1802. if (i >= sp) break;
  1803. stbtt__csctx_rline_to(c, 0, s[i]);
  1804. i++;
  1805. }
  1806. break;
  1807. case 0x1F: // hvcurveto
  1808. if (sp < 4) return STBTT__CSERR("hvcurveto stack");
  1809. goto hvcurveto;
  1810. case 0x1E: // vhcurveto
  1811. if (sp < 4) return STBTT__CSERR("vhcurveto stack");
  1812. for (;;) {
  1813. if (i + 3 >= sp) break;
  1814. stbtt__csctx_rccurve_to(c, 0, s[i], s[i+1], s[i+2], s[i+3], (sp - i == 5) ? s[i + 4] : 0.0f);
  1815. i += 4;
  1816. hvcurveto:
  1817. if (i + 3 >= sp) break;
  1818. stbtt__csctx_rccurve_to(c, s[i], 0, s[i+1], s[i+2], (sp - i == 5) ? s[i+4] : 0.0f, s[i+3]);
  1819. i += 4;
  1820. }
  1821. break;
  1822. case 0x08: // rrcurveto
  1823. if (sp < 6) return STBTT__CSERR("rcurveline stack");
  1824. for (; i + 5 < sp; i += 6)
  1825. stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);
  1826. break;
  1827. case 0x18: // rcurveline
  1828. if (sp < 8) return STBTT__CSERR("rcurveline stack");
  1829. for (; i + 5 < sp - 2; i += 6)
  1830. stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);
  1831. if (i + 1 >= sp) return STBTT__CSERR("rcurveline stack");
  1832. stbtt__csctx_rline_to(c, s[i], s[i+1]);
  1833. break;
  1834. case 0x19: // rlinecurve
  1835. if (sp < 8) return STBTT__CSERR("rlinecurve stack");
  1836. for (; i + 1 < sp - 6; i += 2)
  1837. stbtt__csctx_rline_to(c, s[i], s[i+1]);
  1838. if (i + 5 >= sp) return STBTT__CSERR("rlinecurve stack");
  1839. stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);
  1840. break;
  1841. case 0x1A: // vvcurveto
  1842. case 0x1B: // hhcurveto
  1843. if (sp < 4) return STBTT__CSERR("(vv|hh)curveto stack");
  1844. f = 0.0;
  1845. if (sp & 1) { f = s[i]; i++; }
  1846. for (; i + 3 < sp; i += 4) {
  1847. if (b0 == 0x1B)
  1848. stbtt__csctx_rccurve_to(c, s[i], f, s[i+1], s[i+2], s[i+3], 0.0);
  1849. else
  1850. stbtt__csctx_rccurve_to(c, f, s[i], s[i+1], s[i+2], 0.0, s[i+3]);
  1851. f = 0.0;
  1852. }
  1853. break;
  1854. case 0x0A: // callsubr
  1855. if (!has_subrs) {
  1856. if (info->fdselect.size)
  1857. subrs = stbtt__cid_get_glyph_subrs(info, glyph_index);
  1858. has_subrs = 1;
  1859. }
  1860. // fallthrough
  1861. case 0x1D: // callgsubr
  1862. if (sp < 1) return STBTT__CSERR("call(g|)subr stack");
  1863. v = (int) s[--sp];
  1864. if (subr_stack_height >= 10) return STBTT__CSERR("recursion limit");
  1865. subr_stack[subr_stack_height++] = b;
  1866. b = stbtt__get_subr(b0 == 0x0A ? subrs : info->gsubrs, v);
  1867. if (b.size == 0) return STBTT__CSERR("subr not found");
  1868. b.cursor = 0;
  1869. clear_stack = 0;
  1870. break;
  1871. case 0x0B: // return
  1872. if (subr_stack_height <= 0) return STBTT__CSERR("return outside subr");
  1873. b = subr_stack[--subr_stack_height];
  1874. clear_stack = 0;
  1875. break;
  1876. case 0x0E: // endchar
  1877. stbtt__csctx_close_shape(c);
  1878. return 1;
  1879. case 0x0C: { // two-byte escape
  1880. float dx1, dx2, dx3, dx4, dx5, dx6, dy1, dy2, dy3, dy4, dy5, dy6;
  1881. float dx, dy;
  1882. int b1 = stbtt__buf_get8(&b);
  1883. switch (b1) {
  1884. // @TODO These "flex" implementations ignore the flex-depth and resolution,
  1885. // and always draw beziers.
  1886. case 0x22: // hflex
  1887. if (sp < 7) return STBTT__CSERR("hflex stack");
  1888. dx1 = s[0];
  1889. dx2 = s[1];
  1890. dy2 = s[2];
  1891. dx3 = s[3];
  1892. dx4 = s[4];
  1893. dx5 = s[5];
  1894. dx6 = s[6];
  1895. stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0);
  1896. stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0);
  1897. break;
  1898. case 0x23: // flex
  1899. if (sp < 13) return STBTT__CSERR("flex stack");
  1900. dx1 = s[0];
  1901. dy1 = s[1];
  1902. dx2 = s[2];
  1903. dy2 = s[3];
  1904. dx3 = s[4];
  1905. dy3 = s[5];
  1906. dx4 = s[6];
  1907. dy4 = s[7];
  1908. dx5 = s[8];
  1909. dy5 = s[9];
  1910. dx6 = s[10];
  1911. dy6 = s[11];
  1912. //fd is s[12]
  1913. stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3);
  1914. stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6);
  1915. break;
  1916. case 0x24: // hflex1
  1917. if (sp < 9) return STBTT__CSERR("hflex1 stack");
  1918. dx1 = s[0];
  1919. dy1 = s[1];
  1920. dx2 = s[2];
  1921. dy2 = s[3];
  1922. dx3 = s[4];
  1923. dx4 = s[5];
  1924. dx5 = s[6];
  1925. dy5 = s[7];
  1926. dx6 = s[8];
  1927. stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0);
  1928. stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1+dy2+dy5));
  1929. break;
  1930. case 0x25: // flex1
  1931. if (sp < 11) return STBTT__CSERR("flex1 stack");
  1932. dx1 = s[0];
  1933. dy1 = s[1];
  1934. dx2 = s[2];
  1935. dy2 = s[3];
  1936. dx3 = s[4];
  1937. dy3 = s[5];
  1938. dx4 = s[6];
  1939. dy4 = s[7];
  1940. dx5 = s[8];
  1941. dy5 = s[9];
  1942. dx6 = dy6 = s[10];
  1943. dx = dx1+dx2+dx3+dx4+dx5;
  1944. dy = dy1+dy2+dy3+dy4+dy5;
  1945. if (STBTT_fabs(dx) > STBTT_fabs(dy))
  1946. dy6 = -dy;
  1947. else
  1948. dx6 = -dx;
  1949. stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3);
  1950. stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6);
  1951. break;
  1952. default:
  1953. return STBTT__CSERR("unimplemented");
  1954. }
  1955. } break;
  1956. default:
  1957. if (b0 != 255 && b0 != 28 && (b0 < 32 || b0 > 254))
  1958. return STBTT__CSERR("reserved operator");
  1959. // push immediate
  1960. if (b0 == 255) {
  1961. f = (float)(stbtt_int32)stbtt__buf_get32(&b) / 0x10000;
  1962. } else {
  1963. stbtt__buf_skip(&b, -1);
  1964. f = (float)(stbtt_int16)stbtt__cff_int(&b);
  1965. }
  1966. if (sp >= 48) return STBTT__CSERR("push stack overflow");
  1967. s[sp++] = f;
  1968. clear_stack = 0;
  1969. break;
  1970. }
  1971. if (clear_stack) sp = 0;
  1972. }
  1973. return STBTT__CSERR("no endchar");
  1974. #undef STBTT__CSERR
  1975. }
  1976. static int stbtt__GetGlyphShapeT2(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
  1977. {
  1978. // runs the charstring twice, once to count and once to output (to avoid realloc)
  1979. stbtt__csctx count_ctx = STBTT__CSCTX_INIT(1);
  1980. stbtt__csctx output_ctx = STBTT__CSCTX_INIT(0);
  1981. if (stbtt__run_charstring(info, glyph_index, &count_ctx)) {
  1982. *pvertices = (stbtt_vertex*)STBTT_malloc(count_ctx.num_vertices*sizeof(stbtt_vertex), info->userdata);
  1983. output_ctx.pvertices = *pvertices;
  1984. if (stbtt__run_charstring(info, glyph_index, &output_ctx)) {
  1985. STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices);
  1986. return output_ctx.num_vertices;
  1987. }
  1988. }
  1989. *pvertices = NULL;
  1990. return 0;
  1991. }
  1992. static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)
  1993. {
  1994. stbtt__csctx c = STBTT__CSCTX_INIT(1);
  1995. int r = stbtt__run_charstring(info, glyph_index, &c);
  1996. if (x0) *x0 = r ? c.min_x : 0;
  1997. if (y0) *y0 = r ? c.min_y : 0;
  1998. if (x1) *x1 = r ? c.max_x : 0;
  1999. if (y1) *y1 = r ? c.max_y : 0;
  2000. return r ? c.num_vertices : 0;
  2001. }
  2002. STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
  2003. {
  2004. if (!info->cff.size)
  2005. return stbtt__GetGlyphShapeTT(info, glyph_index, pvertices);
  2006. else
  2007. return stbtt__GetGlyphShapeT2(info, glyph_index, pvertices);
  2008. }
  2009. STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing)
  2010. {
  2011. stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34);
  2012. if (glyph_index < numOfLongHorMetrics) {
  2013. if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*glyph_index);
  2014. if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2);
  2015. } else {
  2016. if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1));
  2017. if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics));
  2018. }
  2019. }
  2020. static int stbtt__GetGlyphKernInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)
  2021. {
  2022. stbtt_uint8 *data = info->data + info->kern;
  2023. stbtt_uint32 needle, straw;
  2024. int l, r, m;
  2025. // we only look at the first table. it must be 'horizontal' and format 0.
  2026. if (!info->kern)
  2027. return 0;
  2028. if (ttUSHORT(data+2) < 1) // number of tables, need at least 1
  2029. return 0;
  2030. if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format
  2031. return 0;
  2032. l = 0;
  2033. r = ttUSHORT(data+10) - 1;
  2034. needle = glyph1 << 16 | glyph2;
  2035. while (l <= r) {
  2036. m = (l + r) >> 1;
  2037. straw = ttULONG(data+18+(m*6)); // note: unaligned read
  2038. if (needle < straw)
  2039. r = m - 1;
  2040. else if (needle > straw)
  2041. l = m + 1;
  2042. else
  2043. return ttSHORT(data+22+(m*6));
  2044. }
  2045. return 0;
  2046. }
  2047. static stbtt_int32 stbtt__GetCoverageIndex(stbtt_uint8 *coverageTable, int glyph)
  2048. {
  2049. stbtt_uint16 coverageFormat = ttUSHORT(coverageTable);
  2050. switch(coverageFormat) {
  2051. case 1: {
  2052. stbtt_uint16 glyphCount = ttUSHORT(coverageTable + 2);
  2053. // Binary search.
  2054. stbtt_int32 l=0, r=glyphCount-1, m;
  2055. int straw, needle=glyph;
  2056. while (l <= r) {
  2057. stbtt_uint8 *glyphArray = coverageTable + 4;
  2058. stbtt_uint16 glyphID;
  2059. m = (l + r) >> 1;
  2060. glyphID = ttUSHORT(glyphArray + 2 * m);
  2061. straw = glyphID;
  2062. if (needle < straw)
  2063. r = m - 1;
  2064. else if (needle > straw)
  2065. l = m + 1;
  2066. else {
  2067. return m;
  2068. }
  2069. }
  2070. } break;
  2071. case 2: {
  2072. stbtt_uint16 rangeCount = ttUSHORT(coverageTable + 2);
  2073. stbtt_uint8 *rangeArray = coverageTable + 4;
  2074. // Binary search.
  2075. stbtt_int32 l=0, r=rangeCount-1, m;
  2076. int strawStart, strawEnd, needle=glyph;
  2077. while (l <= r) {
  2078. stbtt_uint8 *rangeRecord;
  2079. m = (l + r) >> 1;
  2080. rangeRecord = rangeArray + 6 * m;
  2081. strawStart = ttUSHORT(rangeRecord);
  2082. strawEnd = ttUSHORT(rangeRecord + 2);
  2083. if (needle < strawStart)
  2084. r = m - 1;
  2085. else if (needle > strawEnd)
  2086. l = m + 1;
  2087. else {
  2088. stbtt_uint16 startCoverageIndex = ttUSHORT(rangeRecord + 4);
  2089. return startCoverageIndex + glyph - strawStart;
  2090. }
  2091. }
  2092. } break;
  2093. default: {
  2094. // There are no other cases.
  2095. STBTT_assert(0);
  2096. } break;
  2097. }
  2098. return -1;
  2099. }
  2100. static stbtt_int32 stbtt__GetGlyphClass(stbtt_uint8 *classDefTable, int glyph)
  2101. {
  2102. stbtt_uint16 classDefFormat = ttUSHORT(classDefTable);
  2103. switch(classDefFormat)
  2104. {
  2105. case 1: {
  2106. stbtt_uint16 startGlyphID = ttUSHORT(classDefTable + 2);
  2107. stbtt_uint16 glyphCount = ttUSHORT(classDefTable + 4);
  2108. stbtt_uint8 *classDef1ValueArray = classDefTable + 6;
  2109. if (glyph >= startGlyphID && glyph < startGlyphID + glyphCount)
  2110. return (stbtt_int32)ttUSHORT(classDef1ValueArray + 2 * (glyph - startGlyphID));
  2111. // [ImGui: commented to fix static analyzer warning]
  2112. //classDefTable = classDef1ValueArray + 2 * glyphCount;
  2113. } break;
  2114. case 2: {
  2115. stbtt_uint16 classRangeCount = ttUSHORT(classDefTable + 2);
  2116. stbtt_uint8 *classRangeRecords = classDefTable + 4;
  2117. // Binary search.
  2118. stbtt_int32 l=0, r=classRangeCount-1, m;
  2119. int strawStart, strawEnd, needle=glyph;
  2120. while (l <= r) {
  2121. stbtt_uint8 *classRangeRecord;
  2122. m = (l + r) >> 1;
  2123. classRangeRecord = classRangeRecords + 6 * m;
  2124. strawStart = ttUSHORT(classRangeRecord);
  2125. strawEnd = ttUSHORT(classRangeRecord + 2);
  2126. if (needle < strawStart)
  2127. r = m - 1;
  2128. else if (needle > strawEnd)
  2129. l = m + 1;
  2130. else
  2131. return (stbtt_int32)ttUSHORT(classRangeRecord + 4);
  2132. }
  2133. // [ImGui: commented to fix static analyzer warning]
  2134. //classDefTable = classRangeRecords + 6 * classRangeCount;
  2135. } break;
  2136. default: {
  2137. // There are no other cases.
  2138. STBTT_assert(0);
  2139. } break;
  2140. }
  2141. return -1;
  2142. }
  2143. // Define to STBTT_assert(x) if you want to break on unimplemented formats.
  2144. #define STBTT_GPOS_TODO_assert(x)
  2145. static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)
  2146. {
  2147. stbtt_uint16 lookupListOffset;
  2148. stbtt_uint8 *lookupList;
  2149. stbtt_uint16 lookupCount;
  2150. stbtt_uint8 *data;
  2151. stbtt_int32 i;
  2152. if (!info->gpos) return 0;
  2153. data = info->data + info->gpos;
  2154. if (ttUSHORT(data+0) != 1) return 0; // Major version 1
  2155. if (ttUSHORT(data+2) != 0) return 0; // Minor version 0
  2156. lookupListOffset = ttUSHORT(data+8);
  2157. lookupList = data + lookupListOffset;
  2158. lookupCount = ttUSHORT(lookupList);
  2159. for (i=0; i<lookupCount; ++i) {
  2160. stbtt_uint16 lookupOffset = ttUSHORT(lookupList + 2 + 2 * i);
  2161. stbtt_uint8 *lookupTable = lookupList + lookupOffset;
  2162. stbtt_uint16 lookupType = ttUSHORT(lookupTable);
  2163. stbtt_uint16 subTableCount = ttUSHORT(lookupTable + 4);
  2164. stbtt_uint8 *subTableOffsets = lookupTable + 6;
  2165. switch(lookupType) {
  2166. case 2: { // Pair Adjustment Positioning Subtable
  2167. stbtt_int32 sti;
  2168. for (sti=0; sti<subTableCount; sti++) {
  2169. stbtt_uint16 subtableOffset = ttUSHORT(subTableOffsets + 2 * sti);
  2170. stbtt_uint8 *table = lookupTable + subtableOffset;
  2171. stbtt_uint16 posFormat = ttUSHORT(table);
  2172. stbtt_uint16 coverageOffset = ttUSHORT(table + 2);
  2173. stbtt_int32 coverageIndex = stbtt__GetCoverageIndex(table + coverageOffset, glyph1);
  2174. if (coverageIndex == -1) continue;
  2175. switch (posFormat) {
  2176. case 1: {
  2177. stbtt_int32 l, r, m;
  2178. int straw, needle;
  2179. stbtt_uint16 valueFormat1 = ttUSHORT(table + 4);
  2180. stbtt_uint16 valueFormat2 = ttUSHORT(table + 6);
  2181. stbtt_int32 valueRecordPairSizeInBytes = 2;
  2182. stbtt_uint16 pairSetCount = ttUSHORT(table + 8);
  2183. stbtt_uint16 pairPosOffset = ttUSHORT(table + 10 + 2 * coverageIndex);
  2184. stbtt_uint8 *pairValueTable = table + pairPosOffset;
  2185. stbtt_uint16 pairValueCount = ttUSHORT(pairValueTable);
  2186. stbtt_uint8 *pairValueArray = pairValueTable + 2;
  2187. // TODO: Support more formats.
  2188. STBTT_GPOS_TODO_assert(valueFormat1 == 4);
  2189. if (valueFormat1 != 4) return 0;
  2190. STBTT_GPOS_TODO_assert(valueFormat2 == 0);
  2191. if (valueFormat2 != 0) return 0;
  2192. STBTT_assert(coverageIndex < pairSetCount);
  2193. STBTT__NOTUSED(pairSetCount);
  2194. needle=glyph2;
  2195. r=pairValueCount-1;
  2196. l=0;
  2197. // Binary search.
  2198. while (l <= r) {
  2199. stbtt_uint16 secondGlyph;
  2200. stbtt_uint8 *pairValue;
  2201. m = (l + r) >> 1;
  2202. pairValue = pairValueArray + (2 + valueRecordPairSizeInBytes) * m;
  2203. secondGlyph = ttUSHORT(pairValue);
  2204. straw = secondGlyph;
  2205. if (needle < straw)
  2206. r = m - 1;
  2207. else if (needle > straw)
  2208. l = m + 1;
  2209. else {
  2210. stbtt_int16 xAdvance = ttSHORT(pairValue + 2);
  2211. return xAdvance;
  2212. }
  2213. }
  2214. } break;
  2215. case 2: {
  2216. stbtt_uint16 valueFormat1 = ttUSHORT(table + 4);
  2217. stbtt_uint16 valueFormat2 = ttUSHORT(table + 6);
  2218. stbtt_uint16 classDef1Offset = ttUSHORT(table + 8);
  2219. stbtt_uint16 classDef2Offset = ttUSHORT(table + 10);
  2220. int glyph1class = stbtt__GetGlyphClass(table + classDef1Offset, glyph1);
  2221. int glyph2class = stbtt__GetGlyphClass(table + classDef2Offset, glyph2);
  2222. stbtt_uint16 class1Count = ttUSHORT(table + 12);
  2223. stbtt_uint16 class2Count = ttUSHORT(table + 14);
  2224. STBTT_assert(glyph1class < class1Count);
  2225. STBTT_assert(glyph2class < class2Count);
  2226. // TODO: Support more formats.
  2227. STBTT_GPOS_TODO_assert(valueFormat1 == 4);
  2228. if (valueFormat1 != 4) return 0;
  2229. STBTT_GPOS_TODO_assert(valueFormat2 == 0);
  2230. if (valueFormat2 != 0) return 0;
  2231. if (glyph1class >= 0 && glyph1class < class1Count && glyph2class >= 0 && glyph2class < class2Count) {
  2232. stbtt_uint8 *class1Records = table + 16;
  2233. stbtt_uint8 *class2Records = class1Records + 2 * (glyph1class * class2Count);
  2234. stbtt_int16 xAdvance = ttSHORT(class2Records + 2 * glyph2class);
  2235. return xAdvance;
  2236. }
  2237. } break;
  2238. default: {
  2239. // There are no other cases.
  2240. STBTT_assert(0);
  2241. break;
  2242. };
  2243. }
  2244. }
  2245. break;
  2246. };
  2247. default:
  2248. // TODO: Implement other stuff.
  2249. break;
  2250. }
  2251. }
  2252. return 0;
  2253. }
  2254. STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int g1, int g2)
  2255. {
  2256. int xAdvance = 0;
  2257. if (info->gpos)
  2258. xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2);
  2259. if (info->kern)
  2260. xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2);
  2261. return xAdvance;
  2262. }
  2263. STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2)
  2264. {
  2265. if (!info->kern && !info->gpos) // if no kerning table, don't waste time looking up both codepoint->glyphs
  2266. return 0;
  2267. return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2));
  2268. }
  2269. STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing)
  2270. {
  2271. stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing);
  2272. }
  2273. STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap)
  2274. {
  2275. if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4);
  2276. if (descent) *descent = ttSHORT(info->data+info->hhea + 6);
  2277. if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8);
  2278. }
  2279. STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap)
  2280. {
  2281. int tab = stbtt__find_table(info->data, info->fontstart, "OS/2");
  2282. if (!tab)
  2283. return 0;
  2284. if (typoAscent ) *typoAscent = ttSHORT(info->data+tab + 68);
  2285. if (typoDescent) *typoDescent = ttSHORT(info->data+tab + 70);
  2286. if (typoLineGap) *typoLineGap = ttSHORT(info->data+tab + 72);
  2287. return 1;
  2288. }
  2289. STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1)
  2290. {
  2291. *x0 = ttSHORT(info->data + info->head + 36);
  2292. *y0 = ttSHORT(info->data + info->head + 38);
  2293. *x1 = ttSHORT(info->data + info->head + 40);
  2294. *y1 = ttSHORT(info->data + info->head + 42);
  2295. }
  2296. STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height)
  2297. {
  2298. int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6);
  2299. return (float) height / fheight;
  2300. }
  2301. STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels)
  2302. {
  2303. int unitsPerEm = ttUSHORT(info->data + info->head + 18);
  2304. return pixels / unitsPerEm;
  2305. }
  2306. STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v)
  2307. {
  2308. STBTT_free(v, info->userdata);
  2309. }
  2310. //////////////////////////////////////////////////////////////////////////////
  2311. //
  2312. // antialiasing software rasterizer
  2313. //
  2314. 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)
  2315. {
  2316. int x0=0,y0=0,x1,y1; // =0 suppresses compiler warning
  2317. if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) {
  2318. // e.g. space character
  2319. if (ix0) *ix0 = 0;
  2320. if (iy0) *iy0 = 0;
  2321. if (ix1) *ix1 = 0;
  2322. if (iy1) *iy1 = 0;
  2323. } else {
  2324. // move to integral bboxes (treating pixels as little squares, what pixels get touched)?
  2325. if (ix0) *ix0 = STBTT_ifloor( x0 * scale_x + shift_x);
  2326. if (iy0) *iy0 = STBTT_ifloor(-y1 * scale_y + shift_y);
  2327. if (ix1) *ix1 = STBTT_iceil ( x1 * scale_x + shift_x);
  2328. if (iy1) *iy1 = STBTT_iceil (-y0 * scale_y + shift_y);
  2329. }
  2330. }
  2331. 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)
  2332. {
  2333. stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1);
  2334. }
  2335. 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)
  2336. {
  2337. stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1);
  2338. }
  2339. 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)
  2340. {
  2341. stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1);
  2342. }
  2343. //////////////////////////////////////////////////////////////////////////////
  2344. //
  2345. // Rasterizer
  2346. typedef struct stbtt__hheap_chunk
  2347. {
  2348. struct stbtt__hheap_chunk *next;
  2349. } stbtt__hheap_chunk;
  2350. typedef struct stbtt__hheap
  2351. {
  2352. struct stbtt__hheap_chunk *head;
  2353. void *first_free;
  2354. int num_remaining_in_head_chunk;
  2355. } stbtt__hheap;
  2356. static void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata)
  2357. {
  2358. if (hh->first_free) {
  2359. void *p = hh->first_free;
  2360. hh->first_free = * (void **) p;
  2361. return p;
  2362. } else {
  2363. if (hh->num_remaining_in_head_chunk == 0) {
  2364. int count = (size < 32 ? 2000 : size < 128 ? 800 : 100);
  2365. stbtt__hheap_chunk *c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata);
  2366. if (c == NULL)
  2367. return NULL;
  2368. c->next = hh->head;
  2369. hh->head = c;
  2370. hh->num_remaining_in_head_chunk = count;
  2371. }
  2372. --hh->num_remaining_in_head_chunk;
  2373. return (char *) (hh->head) + sizeof(stbtt__hheap_chunk) + size * hh->num_remaining_in_head_chunk;
  2374. }
  2375. }
  2376. static void stbtt__hheap_free(stbtt__hheap *hh, void *p)
  2377. {
  2378. *(void **) p = hh->first_free;
  2379. hh->first_free = p;
  2380. }
  2381. static void stbtt__hheap_cleanup(stbtt__hheap *hh, void *userdata)
  2382. {
  2383. stbtt__hheap_chunk *c = hh->head;
  2384. while (c) {
  2385. stbtt__hheap_chunk *n = c->next;
  2386. STBTT_free(c, userdata);
  2387. c = n;
  2388. }
  2389. }
  2390. typedef struct stbtt__edge {
  2391. float x0,y0, x1,y1;
  2392. int invert;
  2393. } stbtt__edge;
  2394. typedef struct stbtt__active_edge
  2395. {
  2396. struct stbtt__active_edge *next;
  2397. #if STBTT_RASTERIZER_VERSION==1
  2398. int x,dx;
  2399. float ey;
  2400. int direction;
  2401. #elif STBTT_RASTERIZER_VERSION==2
  2402. float fx,fdx,fdy;
  2403. float direction;
  2404. float sy;
  2405. float ey;
  2406. #else
  2407. #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
  2408. #endif
  2409. } stbtt__active_edge;
  2410. #if STBTT_RASTERIZER_VERSION == 1
  2411. #define STBTT_FIXSHIFT 10
  2412. #define STBTT_FIX (1 << STBTT_FIXSHIFT)
  2413. #define STBTT_FIXMASK (STBTT_FIX-1)
  2414. static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata)
  2415. {
  2416. stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata);
  2417. float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);
  2418. STBTT_assert(z != NULL);
  2419. if (!z) return z;
  2420. // round dx down to avoid overshooting
  2421. if (dxdy < 0)
  2422. z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy);
  2423. else
  2424. z->dx = STBTT_ifloor(STBTT_FIX * dxdy);
  2425. 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
  2426. z->x -= off_x * STBTT_FIX;
  2427. z->ey = e->y1;
  2428. z->next = 0;
  2429. z->direction = e->invert ? 1 : -1;
  2430. return z;
  2431. }
  2432. #elif STBTT_RASTERIZER_VERSION == 2
  2433. static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata)
  2434. {
  2435. stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata);
  2436. float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);
  2437. STBTT_assert(z != NULL);
  2438. //STBTT_assert(e->y0 <= start_point);
  2439. if (!z) return z;
  2440. z->fdx = dxdy;
  2441. z->fdy = dxdy != 0.0f ? (1.0f/dxdy) : 0.0f;
  2442. z->fx = e->x0 + dxdy * (start_point - e->y0);
  2443. z->fx -= off_x;
  2444. z->direction = e->invert ? 1.0f : -1.0f;
  2445. z->sy = e->y0;
  2446. z->ey = e->y1;
  2447. z->next = 0;
  2448. return z;
  2449. }
  2450. #else
  2451. #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
  2452. #endif
  2453. #if STBTT_RASTERIZER_VERSION == 1
  2454. // note: this routine clips fills that extend off the edges... ideally this
  2455. // wouldn't happen, but it could happen if the truetype glyph bounding boxes
  2456. // are wrong, or if the user supplies a too-small bitmap
  2457. static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight)
  2458. {
  2459. // non-zero winding fill
  2460. int x0=0, w=0;
  2461. while (e) {
  2462. if (w == 0) {
  2463. // if we're currently at zero, we need to record the edge start point
  2464. x0 = e->x; w += e->direction;
  2465. } else {
  2466. int x1 = e->x; w += e->direction;
  2467. // if we went to zero, we need to draw
  2468. if (w == 0) {
  2469. int i = x0 >> STBTT_FIXSHIFT;
  2470. int j = x1 >> STBTT_FIXSHIFT;
  2471. if (i < len && j >= 0) {
  2472. if (i == j) {
  2473. // x0,x1 are the same pixel, so compute combined coverage
  2474. scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> STBTT_FIXSHIFT);
  2475. } else {
  2476. if (i >= 0) // add antialiasing for x0
  2477. scanline[i] = scanline[i] + (stbtt_uint8) (((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT);
  2478. else
  2479. i = -1; // clip
  2480. if (j < len) // add antialiasing for x1
  2481. scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT);
  2482. else
  2483. j = len; // clip
  2484. for (++i; i < j; ++i) // fill pixels between x0 and x1
  2485. scanline[i] = scanline[i] + (stbtt_uint8) max_weight;
  2486. }
  2487. }
  2488. }
  2489. }
  2490. e = e->next;
  2491. }
  2492. }
  2493. static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)
  2494. {
  2495. stbtt__hheap hh = { 0, 0, 0 };
  2496. stbtt__active_edge *active = NULL;
  2497. int y,j=0;
  2498. int max_weight = (255 / vsubsample); // weight per vertical scanline
  2499. int s; // vertical subsample index
  2500. unsigned char scanline_data[512], *scanline;
  2501. if (result->w > 512)
  2502. scanline = (unsigned char *) STBTT_malloc(result->w, userdata);
  2503. else
  2504. scanline = scanline_data;
  2505. y = off_y * vsubsample;
  2506. e[n].y0 = (off_y + result->h) * (float) vsubsample + 1;
  2507. while (j < result->h) {
  2508. STBTT_memset(scanline, 0, result->w);
  2509. for (s=0; s < vsubsample; ++s) {
  2510. // find center of pixel for this scanline
  2511. float scan_y = y + 0.5f;
  2512. stbtt__active_edge **step = &active;
  2513. // update all active edges;
  2514. // remove all active edges that terminate before the center of this scanline
  2515. while (*step) {
  2516. stbtt__active_edge * z = *step;
  2517. if (z->ey <= scan_y) {
  2518. *step = z->next; // delete from list
  2519. STBTT_assert(z->direction);
  2520. z->direction = 0;
  2521. stbtt__hheap_free(&hh, z);
  2522. } else {
  2523. z->x += z->dx; // advance to position for current scanline
  2524. step = &((*step)->next); // advance through list
  2525. }
  2526. }
  2527. // resort the list if needed
  2528. for(;;) {
  2529. int changed=0;
  2530. step = &active;
  2531. while (*step && (*step)->next) {
  2532. if ((*step)->x > (*step)->next->x) {
  2533. stbtt__active_edge *t = *step;
  2534. stbtt__active_edge *q = t->next;
  2535. t->next = q->next;
  2536. q->next = t;
  2537. *step = q;
  2538. changed = 1;
  2539. }
  2540. step = &(*step)->next;
  2541. }
  2542. if (!changed) break;
  2543. }
  2544. // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline
  2545. while (e->y0 <= scan_y) {
  2546. if (e->y1 > scan_y) {
  2547. stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y, userdata);
  2548. if (z != NULL) {
  2549. // find insertion point
  2550. if (active == NULL)
  2551. active = z;
  2552. else if (z->x < active->x) {
  2553. // insert at front
  2554. z->next = active;
  2555. active = z;
  2556. } else {
  2557. // find thing to insert AFTER
  2558. stbtt__active_edge *p = active;
  2559. while (p->next && p->next->x < z->x)
  2560. p = p->next;
  2561. // at this point, p->next->x is NOT < z->x
  2562. z->next = p->next;
  2563. p->next = z;
  2564. }
  2565. }
  2566. }
  2567. ++e;
  2568. }
  2569. // now process all active edges in XOR fashion
  2570. if (active)
  2571. stbtt__fill_active_edges(scanline, result->w, active, max_weight);
  2572. ++y;
  2573. }
  2574. STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w);
  2575. ++j;
  2576. }
  2577. stbtt__hheap_cleanup(&hh, userdata);
  2578. if (scanline != scanline_data)
  2579. STBTT_free(scanline, userdata);
  2580. }
  2581. #elif STBTT_RASTERIZER_VERSION == 2
  2582. // the edge passed in here does not cross the vertical line at x or the vertical line at x+1
  2583. // (i.e. it has already been clipped to those)
  2584. static void stbtt__handle_clipped_edge(float *scanline, int x, stbtt__active_edge *e, float x0, float y0, float x1, float y1)
  2585. {
  2586. if (y0 == y1) return;
  2587. STBTT_assert(y0 < y1);
  2588. STBTT_assert(e->sy <= e->ey);
  2589. if (y0 > e->ey) return;
  2590. if (y1 < e->sy) return;
  2591. if (y0 < e->sy) {
  2592. x0 += (x1-x0) * (e->sy - y0) / (y1-y0);
  2593. y0 = e->sy;
  2594. }
  2595. if (y1 > e->ey) {
  2596. x1 += (x1-x0) * (e->ey - y1) / (y1-y0);
  2597. y1 = e->ey;
  2598. }
  2599. if (x0 == x)
  2600. STBTT_assert(x1 <= x+1);
  2601. else if (x0 == x+1)
  2602. STBTT_assert(x1 >= x);
  2603. else if (x0 <= x)
  2604. STBTT_assert(x1 <= x);
  2605. else if (x0 >= x+1)
  2606. STBTT_assert(x1 >= x+1);
  2607. else
  2608. STBTT_assert(x1 >= x && x1 <= x+1);
  2609. if (x0 <= x && x1 <= x)
  2610. scanline[x] += e->direction * (y1-y0);
  2611. else if (x0 >= x+1 && x1 >= x+1)
  2612. ;
  2613. else {
  2614. STBTT_assert(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1);
  2615. scanline[x] += e->direction * (y1-y0) * (1-((x0-x)+(x1-x))/2); // coverage = 1 - average x position
  2616. }
  2617. }
  2618. static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, stbtt__active_edge *e, float y_top)
  2619. {
  2620. float y_bottom = y_top+1;
  2621. while (e) {
  2622. // brute force every pixel
  2623. // compute intersection points with top & bottom
  2624. STBTT_assert(e->ey >= y_top);
  2625. if (e->fdx == 0) {
  2626. float x0 = e->fx;
  2627. if (x0 < len) {
  2628. if (x0 >= 0) {
  2629. stbtt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom);
  2630. stbtt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom);
  2631. } else {
  2632. stbtt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom);
  2633. }
  2634. }
  2635. } else {
  2636. float x0 = e->fx;
  2637. float dx = e->fdx;
  2638. float xb = x0 + dx;
  2639. float x_top, x_bottom;
  2640. float sy0,sy1;
  2641. float dy = e->fdy;
  2642. STBTT_assert(e->sy <= y_bottom && e->ey >= y_top);
  2643. // compute endpoints of line segment clipped to this scanline (if the
  2644. // line segment starts on this scanline. x0 is the intersection of the
  2645. // line with y_top, but that may be off the line segment.
  2646. if (e->sy > y_top) {
  2647. x_top = x0 + dx * (e->sy - y_top);
  2648. sy0 = e->sy;
  2649. } else {
  2650. x_top = x0;
  2651. sy0 = y_top;
  2652. }
  2653. if (e->ey < y_bottom) {
  2654. x_bottom = x0 + dx * (e->ey - y_top);
  2655. sy1 = e->ey;
  2656. } else {
  2657. x_bottom = xb;
  2658. sy1 = y_bottom;
  2659. }
  2660. if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) {
  2661. // from here on, we don't have to range check x values
  2662. if ((int) x_top == (int) x_bottom) {
  2663. float height;
  2664. // simple case, only spans one pixel
  2665. int x = (int) x_top;
  2666. height = sy1 - sy0;
  2667. STBTT_assert(x >= 0 && x < len);
  2668. scanline[x] += e->direction * (1-((x_top - x) + (x_bottom-x))/2) * height;
  2669. scanline_fill[x] += e->direction * height; // everything right of this pixel is filled
  2670. } else {
  2671. int x,x1,x2;
  2672. float y_crossing, step, sign, area;
  2673. // covers 2+ pixels
  2674. if (x_top > x_bottom) {
  2675. // flip scanline vertically; signed area is the same
  2676. float t;
  2677. sy0 = y_bottom - (sy0 - y_top);
  2678. sy1 = y_bottom - (sy1 - y_top);
  2679. t = sy0, sy0 = sy1, sy1 = t;
  2680. t = x_bottom, x_bottom = x_top, x_top = t;
  2681. dx = -dx;
  2682. dy = -dy;
  2683. t = x0, x0 = xb, xb = t;
  2684. (void)dx; // [ImGui: fix static analyzer warning]
  2685. }
  2686. x1 = (int) x_top;
  2687. x2 = (int) x_bottom;
  2688. // compute intersection with y axis at x1+1
  2689. y_crossing = (x1+1 - x0) * dy + y_top;
  2690. sign = e->direction;
  2691. // area of the rectangle covered from y0..y_crossing
  2692. area = sign * (y_crossing-sy0);
  2693. // area of the triangle (x_top,y0), (x+1,y0), (x+1,y_crossing)
  2694. scanline[x1] += area * (1-((x_top - x1)+(x1+1-x1))/2);
  2695. step = sign * dy;
  2696. for (x = x1+1; x < x2; ++x) {
  2697. scanline[x] += area + step/2;
  2698. area += step;
  2699. }
  2700. y_crossing += dy * (x2 - (x1+1));
  2701. STBTT_assert(STBTT_fabs(area) <= 1.01f);
  2702. scanline[x2] += area + sign * (1-((x2-x2)+(x_bottom-x2))/2) * (sy1-y_crossing);
  2703. scanline_fill[x2] += sign * (sy1-sy0);
  2704. }
  2705. } else {
  2706. // if edge goes outside of box we're drawing, we require
  2707. // clipping logic. since this does not match the intended use
  2708. // of this library, we use a different, very slow brute
  2709. // force implementation
  2710. int x;
  2711. for (x=0; x < len; ++x) {
  2712. // cases:
  2713. //
  2714. // there can be up to two intersections with the pixel. any intersection
  2715. // with left or right edges can be handled by splitting into two (or three)
  2716. // regions. intersections with top & bottom do not necessitate case-wise logic.
  2717. //
  2718. // the old way of doing this found the intersections with the left & right edges,
  2719. // then used some simple logic to produce up to three segments in sorted order
  2720. // from top-to-bottom. however, this had a problem: if an x edge was epsilon
  2721. // across the x border, then the corresponding y position might not be distinct
  2722. // from the other y segment, and it might ignored as an empty segment. to avoid
  2723. // that, we need to explicitly produce segments based on x positions.
  2724. // rename variables to clearly-defined pairs
  2725. float y0 = y_top;
  2726. float x1 = (float) (x);
  2727. float x2 = (float) (x+1);
  2728. float x3 = xb;
  2729. float y3 = y_bottom;
  2730. // x = e->x + e->dx * (y-y_top)
  2731. // (y-y_top) = (x - e->x) / e->dx
  2732. // y = (x - e->x) / e->dx + y_top
  2733. float y1 = (x - x0) / dx + y_top;
  2734. float y2 = (x+1 - x0) / dx + y_top;
  2735. if (x0 < x1 && x3 > x2) { // three segments descending down-right
  2736. stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);
  2737. stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x2,y2);
  2738. stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);
  2739. } else if (x3 < x1 && x0 > x2) { // three segments descending down-left
  2740. stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);
  2741. stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x1,y1);
  2742. stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);
  2743. } else if (x0 < x1 && x3 > x1) { // two segments across x, down-right
  2744. stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);
  2745. stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);
  2746. } else if (x3 < x1 && x0 > x1) { // two segments across x, down-left
  2747. stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);
  2748. stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);
  2749. } else if (x0 < x2 && x3 > x2) { // two segments across x+1, down-right
  2750. stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);
  2751. stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);
  2752. } else if (x3 < x2 && x0 > x2) { // two segments across x+1, down-left
  2753. stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);
  2754. stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);
  2755. } else { // one segment
  2756. stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x3,y3);
  2757. }
  2758. }
  2759. }
  2760. }
  2761. e = e->next;
  2762. }
  2763. }
  2764. // directly AA rasterize edges w/o supersampling
  2765. static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)
  2766. {
  2767. stbtt__hheap hh = { 0, 0, 0 };
  2768. stbtt__active_edge *active = NULL;
  2769. int y,j=0, i;
  2770. float scanline_data[129], *scanline, *scanline2;
  2771. STBTT__NOTUSED(vsubsample);
  2772. if (result->w > 64)
  2773. scanline = (float *) STBTT_malloc((result->w*2+1) * sizeof(float), userdata);
  2774. else
  2775. scanline = scanline_data;
  2776. scanline2 = scanline + result->w;
  2777. y = off_y;
  2778. e[n].y0 = (float) (off_y + result->h) + 1;
  2779. while (j < result->h) {
  2780. // find center of pixel for this scanline
  2781. float scan_y_top = y + 0.0f;
  2782. float scan_y_bottom = y + 1.0f;
  2783. stbtt__active_edge **step = &active;
  2784. STBTT_memset(scanline , 0, result->w*sizeof(scanline[0]));
  2785. STBTT_memset(scanline2, 0, (result->w+1)*sizeof(scanline[0]));
  2786. // update all active edges;
  2787. // remove all active edges that terminate before the top of this scanline
  2788. while (*step) {
  2789. stbtt__active_edge * z = *step;
  2790. if (z->ey <= scan_y_top) {
  2791. *step = z->next; // delete from list
  2792. STBTT_assert(z->direction);
  2793. z->direction = 0;
  2794. stbtt__hheap_free(&hh, z);
  2795. } else {
  2796. step = &((*step)->next); // advance through list
  2797. }
  2798. }
  2799. // insert all edges that start before the bottom of this scanline
  2800. while (e->y0 <= scan_y_bottom) {
  2801. if (e->y0 != e->y1) {
  2802. stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata);
  2803. if (z != NULL) {
  2804. STBTT_assert(z->ey >= scan_y_top);
  2805. // insert at front
  2806. z->next = active;
  2807. active = z;
  2808. }
  2809. }
  2810. ++e;
  2811. }
  2812. // now process all active edges
  2813. if (active)
  2814. stbtt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top);
  2815. {
  2816. float sum = 0;
  2817. for (i=0; i < result->w; ++i) {
  2818. float k;
  2819. int m;
  2820. sum += scanline2[i];
  2821. k = scanline[i] + sum;
  2822. k = (float) STBTT_fabs(k)*255 + 0.5f;
  2823. m = (int) k;
  2824. if (m > 255) m = 255;
  2825. result->pixels[j*result->stride + i] = (unsigned char) m;
  2826. }
  2827. }
  2828. // advance all the edges
  2829. step = &active;
  2830. while (*step) {
  2831. stbtt__active_edge *z = *step;
  2832. z->fx += z->fdx; // advance to position for current scanline
  2833. step = &((*step)->next); // advance through list
  2834. }
  2835. ++y;
  2836. ++j;
  2837. }
  2838. stbtt__hheap_cleanup(&hh, userdata);
  2839. if (scanline != scanline_data)
  2840. STBTT_free(scanline, userdata);
  2841. }
  2842. #else
  2843. #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
  2844. #endif
  2845. #define STBTT__COMPARE(a,b) ((a)->y0 < (b)->y0)
  2846. static void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n)
  2847. {
  2848. int i,j;
  2849. for (i=1; i < n; ++i) {
  2850. stbtt__edge t = p[i], *a = &t;
  2851. j = i;
  2852. while (j > 0) {
  2853. stbtt__edge *b = &p[j-1];
  2854. int c = STBTT__COMPARE(a,b);
  2855. if (!c) break;
  2856. p[j] = p[j-1];
  2857. --j;
  2858. }
  2859. if (i != j)
  2860. p[j] = t;
  2861. }
  2862. }
  2863. static void stbtt__sort_edges_quicksort(stbtt__edge *p, int n)
  2864. {
  2865. /* threshhold for transitioning to insertion sort */
  2866. while (n > 12) {
  2867. stbtt__edge t;
  2868. int c01,c12,c,m,i,j;
  2869. /* compute median of three */
  2870. m = n >> 1;
  2871. c01 = STBTT__COMPARE(&p[0],&p[m]);
  2872. c12 = STBTT__COMPARE(&p[m],&p[n-1]);
  2873. /* if 0 >= mid >= end, or 0 < mid < end, then use mid */
  2874. if (c01 != c12) {
  2875. /* otherwise, we'll need to swap something else to middle */
  2876. int z;
  2877. c = STBTT__COMPARE(&p[0],&p[n-1]);
  2878. /* 0>mid && mid<n: 0>n => n; 0<n => 0 */
  2879. /* 0<mid && mid>n: 0>n => 0; 0<n => n */
  2880. z = (c == c12) ? 0 : n-1;
  2881. t = p[z];
  2882. p[z] = p[m];
  2883. p[m] = t;
  2884. }
  2885. /* now p[m] is the median-of-three */
  2886. /* swap it to the beginning so it won't move around */
  2887. t = p[0];
  2888. p[0] = p[m];
  2889. p[m] = t;
  2890. /* partition loop */
  2891. i=1;
  2892. j=n-1;
  2893. for(;;) {
  2894. /* handling of equality is crucial here */
  2895. /* for sentinels & efficiency with duplicates */
  2896. for (;;++i) {
  2897. if (!STBTT__COMPARE(&p[i], &p[0])) break;
  2898. }
  2899. for (;;--j) {
  2900. if (!STBTT__COMPARE(&p[0], &p[j])) break;
  2901. }
  2902. /* make sure we haven't crossed */
  2903. if (i >= j) break;
  2904. t = p[i];
  2905. p[i] = p[j];
  2906. p[j] = t;
  2907. ++i;
  2908. --j;
  2909. }
  2910. /* recurse on smaller side, iterate on larger */
  2911. if (j < (n-i)) {
  2912. stbtt__sort_edges_quicksort(p,j);
  2913. p = p+i;
  2914. n = n-i;
  2915. } else {
  2916. stbtt__sort_edges_quicksort(p+i, n-i);
  2917. n = j;
  2918. }
  2919. }
  2920. }
  2921. static void stbtt__sort_edges(stbtt__edge *p, int n)
  2922. {
  2923. stbtt__sort_edges_quicksort(p, n);
  2924. stbtt__sort_edges_ins_sort(p, n);
  2925. }
  2926. typedef struct
  2927. {
  2928. float x,y;
  2929. } stbtt__point;
  2930. 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)
  2931. {
  2932. float y_scale_inv = invert ? -scale_y : scale_y;
  2933. stbtt__edge *e;
  2934. int n,i,j,k,m;
  2935. #if STBTT_RASTERIZER_VERSION == 1
  2936. int vsubsample = result->h < 8 ? 15 : 5;
  2937. #elif STBTT_RASTERIZER_VERSION == 2
  2938. int vsubsample = 1;
  2939. #else
  2940. #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
  2941. #endif
  2942. // vsubsample should divide 255 evenly; otherwise we won't reach full opacity
  2943. // now we have to blow out the windings into explicit edge lists
  2944. n = 0;
  2945. for (i=0; i < windings; ++i)
  2946. n += wcount[i];
  2947. e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel
  2948. if (e == 0) return;
  2949. n = 0;
  2950. m=0;
  2951. for (i=0; i < windings; ++i) {
  2952. stbtt__point *p = pts + m;
  2953. m += wcount[i];
  2954. j = wcount[i]-1;
  2955. for (k=0; k < wcount[i]; j=k++) {
  2956. int a=k,b=j;
  2957. // skip the edge if horizontal
  2958. if (p[j].y == p[k].y)
  2959. continue;
  2960. // add edge from j to k to the list
  2961. e[n].invert = 0;
  2962. if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) {
  2963. e[n].invert = 1;
  2964. a=j,b=k;
  2965. }
  2966. e[n].x0 = p[a].x * scale_x + shift_x;
  2967. e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample;
  2968. e[n].x1 = p[b].x * scale_x + shift_x;
  2969. e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample;
  2970. ++n;
  2971. }
  2972. }
  2973. // now sort the edges by their highest point (should snap to integer, and then by x)
  2974. //STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare);
  2975. stbtt__sort_edges(e, n);
  2976. // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule
  2977. stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata);
  2978. STBTT_free(e, userdata);
  2979. }
  2980. static void stbtt__add_point(stbtt__point *points, int n, float x, float y)
  2981. {
  2982. if (!points) return; // during first pass, it's unallocated
  2983. points[n].x = x;
  2984. points[n].y = y;
  2985. }
  2986. // tesselate until threshhold p is happy... @TODO warped to compensate for non-linear stretching
  2987. 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)
  2988. {
  2989. // midpoint
  2990. float mx = (x0 + 2*x1 + x2)/4;
  2991. float my = (y0 + 2*y1 + y2)/4;
  2992. // versus directly drawn line
  2993. float dx = (x0+x2)/2 - mx;
  2994. float dy = (y0+y2)/2 - my;
  2995. if (n > 16) // 65536 segments on one curve better be enough!
  2996. return 1;
  2997. if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA
  2998. stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1);
  2999. stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1);
  3000. } else {
  3001. stbtt__add_point(points, *num_points,x2,y2);
  3002. *num_points = *num_points+1;
  3003. }
  3004. return 1;
  3005. }
  3006. static void stbtt__tesselate_cubic(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float objspace_flatness_squared, int n)
  3007. {
  3008. // @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough
  3009. float dx0 = x1-x0;
  3010. float dy0 = y1-y0;
  3011. float dx1 = x2-x1;
  3012. float dy1 = y2-y1;
  3013. float dx2 = x3-x2;
  3014. float dy2 = y3-y2;
  3015. float dx = x3-x0;
  3016. float dy = y3-y0;
  3017. float longlen = (float) (STBTT_sqrt(dx0*dx0+dy0*dy0)+STBTT_sqrt(dx1*dx1+dy1*dy1)+STBTT_sqrt(dx2*dx2+dy2*dy2));
  3018. float shortlen = (float) STBTT_sqrt(dx*dx+dy*dy);
  3019. float flatness_squared = longlen*longlen-shortlen*shortlen;
  3020. if (n > 16) // 65536 segments on one curve better be enough!
  3021. return;
  3022. if (flatness_squared > objspace_flatness_squared) {
  3023. float x01 = (x0+x1)/2;
  3024. float y01 = (y0+y1)/2;
  3025. float x12 = (x1+x2)/2;
  3026. float y12 = (y1+y2)/2;
  3027. float x23 = (x2+x3)/2;
  3028. float y23 = (y2+y3)/2;
  3029. float xa = (x01+x12)/2;
  3030. float ya = (y01+y12)/2;
  3031. float xb = (x12+x23)/2;
  3032. float yb = (y12+y23)/2;
  3033. float mx = (xa+xb)/2;
  3034. float my = (ya+yb)/2;
  3035. stbtt__tesselate_cubic(points, num_points, x0,y0, x01,y01, xa,ya, mx,my, objspace_flatness_squared,n+1);
  3036. stbtt__tesselate_cubic(points, num_points, mx,my, xb,yb, x23,y23, x3,y3, objspace_flatness_squared,n+1);
  3037. } else {
  3038. stbtt__add_point(points, *num_points,x3,y3);
  3039. *num_points = *num_points+1;
  3040. }
  3041. }
  3042. // returns number of contours
  3043. static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata)
  3044. {
  3045. stbtt__point *points=0;
  3046. int num_points=0;
  3047. float objspace_flatness_squared = objspace_flatness * objspace_flatness;
  3048. int i,n=0,start=0, pass;
  3049. // count how many "moves" there are to get the contour count
  3050. for (i=0; i < num_verts; ++i)
  3051. if (vertices[i].type == STBTT_vmove)
  3052. ++n;
  3053. *num_contours = n;
  3054. if (n == 0) return 0;
  3055. *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata);
  3056. if (*contour_lengths == 0) {
  3057. *num_contours = 0;
  3058. return 0;
  3059. }
  3060. // make two passes through the points so we don't need to realloc
  3061. for (pass=0; pass < 2; ++pass) {
  3062. float x=0,y=0;
  3063. if (pass == 1) {
  3064. points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata);
  3065. if (points == NULL) goto error;
  3066. }
  3067. num_points = 0;
  3068. n= -1;
  3069. for (i=0; i < num_verts; ++i) {
  3070. switch (vertices[i].type) {
  3071. case STBTT_vmove:
  3072. // start the next contour
  3073. if (n >= 0)
  3074. (*contour_lengths)[n] = num_points - start;
  3075. ++n;
  3076. start = num_points;
  3077. x = vertices[i].x, y = vertices[i].y;
  3078. stbtt__add_point(points, num_points++, x,y);
  3079. break;
  3080. case STBTT_vline:
  3081. x = vertices[i].x, y = vertices[i].y;
  3082. stbtt__add_point(points, num_points++, x, y);
  3083. break;
  3084. case STBTT_vcurve:
  3085. stbtt__tesselate_curve(points, &num_points, x,y,
  3086. vertices[i].cx, vertices[i].cy,
  3087. vertices[i].x, vertices[i].y,
  3088. objspace_flatness_squared, 0);
  3089. x = vertices[i].x, y = vertices[i].y;
  3090. break;
  3091. case STBTT_vcubic:
  3092. stbtt__tesselate_cubic(points, &num_points, x,y,
  3093. vertices[i].cx, vertices[i].cy,
  3094. vertices[i].cx1, vertices[i].cy1,
  3095. vertices[i].x, vertices[i].y,
  3096. objspace_flatness_squared, 0);
  3097. x = vertices[i].x, y = vertices[i].y;
  3098. break;
  3099. }
  3100. }
  3101. (*contour_lengths)[n] = num_points - start;
  3102. }
  3103. return points;
  3104. error:
  3105. STBTT_free(points, userdata);
  3106. STBTT_free(*contour_lengths, userdata);
  3107. *contour_lengths = 0;
  3108. *num_contours = 0;
  3109. return NULL;
  3110. }
  3111. 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)
  3112. {
  3113. float scale = scale_x > scale_y ? scale_y : scale_x;
  3114. int winding_count = 0;
  3115. int *winding_lengths = NULL;
  3116. stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata);
  3117. if (windings) {
  3118. stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata);
  3119. STBTT_free(winding_lengths, userdata);
  3120. STBTT_free(windings, userdata);
  3121. }
  3122. }
  3123. STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata)
  3124. {
  3125. STBTT_free(bitmap, userdata);
  3126. }
  3127. 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)
  3128. {
  3129. int ix0,iy0,ix1,iy1;
  3130. stbtt__bitmap gbm;
  3131. stbtt_vertex *vertices;
  3132. int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
  3133. if (scale_x == 0) scale_x = scale_y;
  3134. if (scale_y == 0) {
  3135. if (scale_x == 0) {
  3136. STBTT_free(vertices, info->userdata);
  3137. return NULL;
  3138. }
  3139. scale_y = scale_x;
  3140. }
  3141. stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1);
  3142. // now we get the size
  3143. gbm.w = (ix1 - ix0);
  3144. gbm.h = (iy1 - iy0);
  3145. gbm.pixels = NULL; // in case we error
  3146. if (width ) *width = gbm.w;
  3147. if (height) *height = gbm.h;
  3148. if (xoff ) *xoff = ix0;
  3149. if (yoff ) *yoff = iy0;
  3150. if (gbm.w && gbm.h) {
  3151. gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata);
  3152. if (gbm.pixels) {
  3153. gbm.stride = gbm.w;
  3154. stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata);
  3155. }
  3156. }
  3157. STBTT_free(vertices, info->userdata);
  3158. return gbm.pixels;
  3159. }
  3160. 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)
  3161. {
  3162. return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff);
  3163. }
  3164. 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)
  3165. {
  3166. int ix0,iy0;
  3167. stbtt_vertex *vertices;
  3168. int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
  3169. stbtt__bitmap gbm;
  3170. stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0);
  3171. gbm.pixels = output;
  3172. gbm.w = out_w;
  3173. gbm.h = out_h;
  3174. gbm.stride = out_stride;
  3175. if (gbm.w && gbm.h)
  3176. stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata);
  3177. STBTT_free(vertices, info->userdata);
  3178. }
  3179. 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)
  3180. {
  3181. stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph);
  3182. }
  3183. 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)
  3184. {
  3185. return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff);
  3186. }
  3187. STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint)
  3188. {
  3189. stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, oversample_x, oversample_y, sub_x, sub_y, stbtt_FindGlyphIndex(info,codepoint));
  3190. }
  3191. 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)
  3192. {
  3193. stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint));
  3194. }
  3195. 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)
  3196. {
  3197. return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff);
  3198. }
  3199. 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)
  3200. {
  3201. stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint);
  3202. }
  3203. //////////////////////////////////////////////////////////////////////////////
  3204. //
  3205. // bitmap baking
  3206. //
  3207. // This is SUPER-CRAPPY packing to keep source code small
  3208. static int stbtt_BakeFontBitmap_internal(unsigned char *data, int offset, // font location (use offset=0 for plain .ttf)
  3209. float pixel_height, // height of font in pixels
  3210. unsigned char *pixels, int pw, int ph, // bitmap to be filled in
  3211. int first_char, int num_chars, // characters to bake
  3212. stbtt_bakedchar *chardata)
  3213. {
  3214. float scale;
  3215. int x,y,bottom_y, i;
  3216. stbtt_fontinfo f;
  3217. f.userdata = NULL;
  3218. if (!stbtt_InitFont(&f, data, offset))
  3219. return -1;
  3220. STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels
  3221. x=y=1;
  3222. bottom_y = 1;
  3223. scale = stbtt_ScaleForPixelHeight(&f, pixel_height);
  3224. for (i=0; i < num_chars; ++i) {
  3225. int advance, lsb, x0,y0,x1,y1,gw,gh;
  3226. int g = stbtt_FindGlyphIndex(&f, first_char + i);
  3227. stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb);
  3228. stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1);
  3229. gw = x1-x0;
  3230. gh = y1-y0;
  3231. if (x + gw + 1 >= pw)
  3232. y = bottom_y, x = 1; // advance to next row
  3233. if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row
  3234. return -i;
  3235. STBTT_assert(x+gw < pw);
  3236. STBTT_assert(y+gh < ph);
  3237. stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g);
  3238. chardata[i].x0 = (stbtt_int16) x;
  3239. chardata[i].y0 = (stbtt_int16) y;
  3240. chardata[i].x1 = (stbtt_int16) (x + gw);
  3241. chardata[i].y1 = (stbtt_int16) (y + gh);
  3242. chardata[i].xadvance = scale * advance;
  3243. chardata[i].xoff = (float) x0;
  3244. chardata[i].yoff = (float) y0;
  3245. x = x + gw + 1;
  3246. if (y+gh+1 > bottom_y)
  3247. bottom_y = y+gh+1;
  3248. }
  3249. return bottom_y;
  3250. }
  3251. STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule)
  3252. {
  3253. float d3d_bias = opengl_fillrule ? 0 : -0.5f;
  3254. float ipw = 1.0f / pw, iph = 1.0f / ph;
  3255. const stbtt_bakedchar *b = chardata + char_index;
  3256. int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f);
  3257. int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f);
  3258. q->x0 = round_x + d3d_bias;
  3259. q->y0 = round_y + d3d_bias;
  3260. q->x1 = round_x + b->x1 - b->x0 + d3d_bias;
  3261. q->y1 = round_y + b->y1 - b->y0 + d3d_bias;
  3262. q->s0 = b->x0 * ipw;
  3263. q->t0 = b->y0 * iph;
  3264. q->s1 = b->x1 * ipw;
  3265. q->t1 = b->y1 * iph;
  3266. *xpos += b->xadvance;
  3267. }
  3268. //////////////////////////////////////////////////////////////////////////////
  3269. //
  3270. // rectangle packing replacement routines if you don't have stb_rect_pack.h
  3271. //
  3272. #ifndef STB_RECT_PACK_VERSION
  3273. typedef int stbrp_coord;
  3274. ////////////////////////////////////////////////////////////////////////////////////
  3275. // //
  3276. // //
  3277. // COMPILER WARNING ?!?!? //
  3278. // //
  3279. // //
  3280. // if you get a compile warning due to these symbols being defined more than //
  3281. // once, move #include "stb_rect_pack.h" before #include "stb_truetype.h" //
  3282. // //
  3283. ////////////////////////////////////////////////////////////////////////////////////
  3284. typedef struct
  3285. {
  3286. int width,height;
  3287. int x,y,bottom_y;
  3288. } stbrp_context;
  3289. typedef struct
  3290. {
  3291. unsigned char x;
  3292. } stbrp_node;
  3293. struct stbrp_rect
  3294. {
  3295. stbrp_coord x,y;
  3296. int id,w,h,was_packed;
  3297. };
  3298. static void stbrp_init_target(stbrp_context *con, int pw, int ph, stbrp_node *nodes, int num_nodes)
  3299. {
  3300. con->width = pw;
  3301. con->height = ph;
  3302. con->x = 0;
  3303. con->y = 0;
  3304. con->bottom_y = 0;
  3305. STBTT__NOTUSED(nodes);
  3306. STBTT__NOTUSED(num_nodes);
  3307. }
  3308. static void stbrp_pack_rects(stbrp_context *con, stbrp_rect *rects, int num_rects)
  3309. {
  3310. int i;
  3311. for (i=0; i < num_rects; ++i) {
  3312. if (con->x + rects[i].w > con->width) {
  3313. con->x = 0;
  3314. con->y = con->bottom_y;
  3315. }
  3316. if (con->y + rects[i].h > con->height)
  3317. break;
  3318. rects[i].x = con->x;
  3319. rects[i].y = con->y;
  3320. rects[i].was_packed = 1;
  3321. con->x += rects[i].w;
  3322. if (con->y + rects[i].h > con->bottom_y)
  3323. con->bottom_y = con->y + rects[i].h;
  3324. }
  3325. for ( ; i < num_rects; ++i)
  3326. rects[i].was_packed = 0;
  3327. }
  3328. #endif
  3329. //////////////////////////////////////////////////////////////////////////////
  3330. //
  3331. // bitmap baking
  3332. //
  3333. // This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If
  3334. // stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy.
  3335. 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)
  3336. {
  3337. stbrp_context *context = (stbrp_context *) STBTT_malloc(sizeof(*context) ,alloc_context);
  3338. int num_nodes = pw - padding;
  3339. stbrp_node *nodes = (stbrp_node *) STBTT_malloc(sizeof(*nodes ) * num_nodes,alloc_context);
  3340. if (context == NULL || nodes == NULL) {
  3341. if (context != NULL) STBTT_free(context, alloc_context);
  3342. if (nodes != NULL) STBTT_free(nodes , alloc_context);
  3343. return 0;
  3344. }
  3345. spc->user_allocator_context = alloc_context;
  3346. spc->width = pw;
  3347. spc->height = ph;
  3348. spc->pixels = pixels;
  3349. spc->pack_info = context;
  3350. spc->nodes = nodes;
  3351. spc->padding = padding;
  3352. spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw;
  3353. spc->h_oversample = 1;
  3354. spc->v_oversample = 1;
  3355. stbrp_init_target(context, pw-padding, ph-padding, nodes, num_nodes);
  3356. if (pixels)
  3357. STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels
  3358. return 1;
  3359. }
  3360. STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc)
  3361. {
  3362. STBTT_free(spc->nodes , spc->user_allocator_context);
  3363. STBTT_free(spc->pack_info, spc->user_allocator_context);
  3364. }
  3365. STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample)
  3366. {
  3367. STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE);
  3368. STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE);
  3369. if (h_oversample <= STBTT_MAX_OVERSAMPLE)
  3370. spc->h_oversample = h_oversample;
  3371. if (v_oversample <= STBTT_MAX_OVERSAMPLE)
  3372. spc->v_oversample = v_oversample;
  3373. }
  3374. #define STBTT__OVER_MASK (STBTT_MAX_OVERSAMPLE-1)
  3375. static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)
  3376. {
  3377. unsigned char buffer[STBTT_MAX_OVERSAMPLE];
  3378. int safe_w = w - kernel_width;
  3379. int j;
  3380. STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze
  3381. for (j=0; j < h; ++j) {
  3382. int i;
  3383. unsigned int total;
  3384. STBTT_memset(buffer, 0, kernel_width);
  3385. total = 0;
  3386. // make kernel_width a constant in common cases so compiler can optimize out the divide
  3387. switch (kernel_width) {
  3388. case 2:
  3389. for (i=0; i <= safe_w; ++i) {
  3390. total += pixels[i] - buffer[i & STBTT__OVER_MASK];
  3391. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
  3392. pixels[i] = (unsigned char) (total / 2);
  3393. }
  3394. break;
  3395. case 3:
  3396. for (i=0; i <= safe_w; ++i) {
  3397. total += pixels[i] - buffer[i & STBTT__OVER_MASK];
  3398. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
  3399. pixels[i] = (unsigned char) (total / 3);
  3400. }
  3401. break;
  3402. case 4:
  3403. for (i=0; i <= safe_w; ++i) {
  3404. total += pixels[i] - buffer[i & STBTT__OVER_MASK];
  3405. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
  3406. pixels[i] = (unsigned char) (total / 4);
  3407. }
  3408. break;
  3409. case 5:
  3410. for (i=0; i <= safe_w; ++i) {
  3411. total += pixels[i] - buffer[i & STBTT__OVER_MASK];
  3412. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
  3413. pixels[i] = (unsigned char) (total / 5);
  3414. }
  3415. break;
  3416. default:
  3417. for (i=0; i <= safe_w; ++i) {
  3418. total += pixels[i] - buffer[i & STBTT__OVER_MASK];
  3419. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
  3420. pixels[i] = (unsigned char) (total / kernel_width);
  3421. }
  3422. break;
  3423. }
  3424. for (; i < w; ++i) {
  3425. STBTT_assert(pixels[i] == 0);
  3426. total -= buffer[i & STBTT__OVER_MASK];
  3427. pixels[i] = (unsigned char) (total / kernel_width);
  3428. }
  3429. pixels += stride_in_bytes;
  3430. }
  3431. }
  3432. static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)
  3433. {
  3434. unsigned char buffer[STBTT_MAX_OVERSAMPLE];
  3435. int safe_h = h - kernel_width;
  3436. int j;
  3437. STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze
  3438. for (j=0; j < w; ++j) {
  3439. int i;
  3440. unsigned int total;
  3441. STBTT_memset(buffer, 0, kernel_width);
  3442. total = 0;
  3443. // make kernel_width a constant in common cases so compiler can optimize out the divide
  3444. switch (kernel_width) {
  3445. case 2:
  3446. for (i=0; i <= safe_h; ++i) {
  3447. total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
  3448. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
  3449. pixels[i*stride_in_bytes] = (unsigned char) (total / 2);
  3450. }
  3451. break;
  3452. case 3:
  3453. for (i=0; i <= safe_h; ++i) {
  3454. total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
  3455. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
  3456. pixels[i*stride_in_bytes] = (unsigned char) (total / 3);
  3457. }
  3458. break;
  3459. case 4:
  3460. for (i=0; i <= safe_h; ++i) {
  3461. total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
  3462. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
  3463. pixels[i*stride_in_bytes] = (unsigned char) (total / 4);
  3464. }
  3465. break;
  3466. case 5:
  3467. for (i=0; i <= safe_h; ++i) {
  3468. total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
  3469. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
  3470. pixels[i*stride_in_bytes] = (unsigned char) (total / 5);
  3471. }
  3472. break;
  3473. default:
  3474. for (i=0; i <= safe_h; ++i) {
  3475. total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
  3476. buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
  3477. pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width);
  3478. }
  3479. break;
  3480. }
  3481. for (; i < h; ++i) {
  3482. STBTT_assert(pixels[i*stride_in_bytes] == 0);
  3483. total -= buffer[i & STBTT__OVER_MASK];
  3484. pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width);
  3485. }
  3486. pixels += 1;
  3487. }
  3488. }
  3489. static float stbtt__oversample_shift(int oversample)
  3490. {
  3491. if (!oversample)
  3492. return 0.0f;
  3493. // The prefilter is a box filter of width "oversample",
  3494. // which shifts phase by (oversample - 1)/2 pixels in
  3495. // oversampled space. We want to shift in the opposite
  3496. // direction to counter this.
  3497. return (float)-(oversample - 1) / (2.0f * (float)oversample);
  3498. }
  3499. // rects array must be big enough to accommodate all characters in the given ranges
  3500. STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects)
  3501. {
  3502. int i,j,k;
  3503. k=0;
  3504. for (i=0; i < num_ranges; ++i) {
  3505. float fh = ranges[i].font_size;
  3506. float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh);
  3507. ranges[i].h_oversample = (unsigned char) spc->h_oversample;
  3508. ranges[i].v_oversample = (unsigned char) spc->v_oversample;
  3509. for (j=0; j < ranges[i].num_chars; ++j) {
  3510. int x0,y0,x1,y1;
  3511. int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j];
  3512. int glyph = stbtt_FindGlyphIndex(info, codepoint);
  3513. stbtt_GetGlyphBitmapBoxSubpixel(info,glyph,
  3514. scale * spc->h_oversample,
  3515. scale * spc->v_oversample,
  3516. 0,0,
  3517. &x0,&y0,&x1,&y1);
  3518. rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1);
  3519. rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1);
  3520. ++k;
  3521. }
  3522. }
  3523. return k;
  3524. }
  3525. STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int prefilter_x, int prefilter_y, float *sub_x, float *sub_y, int glyph)
  3526. {
  3527. stbtt_MakeGlyphBitmapSubpixel(info,
  3528. output,
  3529. out_w - (prefilter_x - 1),
  3530. out_h - (prefilter_y - 1),
  3531. out_stride,
  3532. scale_x,
  3533. scale_y,
  3534. shift_x,
  3535. shift_y,
  3536. glyph);
  3537. if (prefilter_x > 1)
  3538. stbtt__h_prefilter(output, out_w, out_h, out_stride, prefilter_x);
  3539. if (prefilter_y > 1)
  3540. stbtt__v_prefilter(output, out_w, out_h, out_stride, prefilter_y);
  3541. *sub_x = stbtt__oversample_shift(prefilter_x);
  3542. *sub_y = stbtt__oversample_shift(prefilter_y);
  3543. }
  3544. // rects array must be big enough to accommodate all characters in the given ranges
  3545. STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects)
  3546. {
  3547. int i,j,k, return_value = 1;
  3548. // save current values
  3549. int old_h_over = spc->h_oversample;
  3550. int old_v_over = spc->v_oversample;
  3551. k = 0;
  3552. for (i=0; i < num_ranges; ++i) {
  3553. float fh = ranges[i].font_size;
  3554. float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh);
  3555. float recip_h,recip_v,sub_x,sub_y;
  3556. spc->h_oversample = ranges[i].h_oversample;
  3557. spc->v_oversample = ranges[i].v_oversample;
  3558. recip_h = 1.0f / spc->h_oversample;
  3559. recip_v = 1.0f / spc->v_oversample;
  3560. sub_x = stbtt__oversample_shift(spc->h_oversample);
  3561. sub_y = stbtt__oversample_shift(spc->v_oversample);
  3562. for (j=0; j < ranges[i].num_chars; ++j) {
  3563. stbrp_rect *r = &rects[k];
  3564. if (r->was_packed) {
  3565. stbtt_packedchar *bc = &ranges[i].chardata_for_range[j];
  3566. int advance, lsb, x0,y0,x1,y1;
  3567. int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j];
  3568. int glyph = stbtt_FindGlyphIndex(info, codepoint);
  3569. stbrp_coord pad = (stbrp_coord) spc->padding;
  3570. // pad on left and top
  3571. r->x += pad;
  3572. r->y += pad;
  3573. r->w -= pad;
  3574. r->h -= pad;
  3575. stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb);
  3576. stbtt_GetGlyphBitmapBox(info, glyph,
  3577. scale * spc->h_oversample,
  3578. scale * spc->v_oversample,
  3579. &x0,&y0,&x1,&y1);
  3580. stbtt_MakeGlyphBitmapSubpixel(info,
  3581. spc->pixels + r->x + r->y*spc->stride_in_bytes,
  3582. r->w - spc->h_oversample+1,
  3583. r->h - spc->v_oversample+1,
  3584. spc->stride_in_bytes,
  3585. scale * spc->h_oversample,
  3586. scale * spc->v_oversample,
  3587. 0,0,
  3588. glyph);
  3589. if (spc->h_oversample > 1)
  3590. stbtt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes,
  3591. r->w, r->h, spc->stride_in_bytes,
  3592. spc->h_oversample);
  3593. if (spc->v_oversample > 1)
  3594. stbtt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes,
  3595. r->w, r->h, spc->stride_in_bytes,
  3596. spc->v_oversample);
  3597. bc->x0 = (stbtt_int16) r->x;
  3598. bc->y0 = (stbtt_int16) r->y;
  3599. bc->x1 = (stbtt_int16) (r->x + r->w);
  3600. bc->y1 = (stbtt_int16) (r->y + r->h);
  3601. bc->xadvance = scale * advance;
  3602. bc->xoff = (float) x0 * recip_h + sub_x;
  3603. bc->yoff = (float) y0 * recip_v + sub_y;
  3604. bc->xoff2 = (x0 + r->w) * recip_h + sub_x;
  3605. bc->yoff2 = (y0 + r->h) * recip_v + sub_y;
  3606. } else {
  3607. return_value = 0; // if any fail, report failure
  3608. }
  3609. ++k;
  3610. }
  3611. }
  3612. // restore original values
  3613. spc->h_oversample = old_h_over;
  3614. spc->v_oversample = old_v_over;
  3615. return return_value;
  3616. }
  3617. STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects)
  3618. {
  3619. stbrp_pack_rects((stbrp_context *) spc->pack_info, rects, num_rects);
  3620. }
  3621. STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges)
  3622. {
  3623. stbtt_fontinfo info;
  3624. int i,j,n, return_value = 1;
  3625. //stbrp_context *context = (stbrp_context *) spc->pack_info;
  3626. stbrp_rect *rects;
  3627. // flag all characters as NOT packed
  3628. for (i=0; i < num_ranges; ++i)
  3629. for (j=0; j < ranges[i].num_chars; ++j)
  3630. ranges[i].chardata_for_range[j].x0 =
  3631. ranges[i].chardata_for_range[j].y0 =
  3632. ranges[i].chardata_for_range[j].x1 =
  3633. ranges[i].chardata_for_range[j].y1 = 0;
  3634. n = 0;
  3635. for (i=0; i < num_ranges; ++i)
  3636. n += ranges[i].num_chars;
  3637. rects = (stbrp_rect *) STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context);
  3638. if (rects == NULL)
  3639. return 0;
  3640. info.userdata = spc->user_allocator_context;
  3641. stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index));
  3642. n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects);
  3643. stbtt_PackFontRangesPackRects(spc, rects, n);
  3644. return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects);
  3645. STBTT_free(rects, spc->user_allocator_context);
  3646. return return_value;
  3647. }
  3648. STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size,
  3649. int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range)
  3650. {
  3651. stbtt_pack_range range;
  3652. range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range;
  3653. range.array_of_unicode_codepoints = NULL;
  3654. range.num_chars = num_chars_in_range;
  3655. range.chardata_for_range = chardata_for_range;
  3656. range.font_size = font_size;
  3657. return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1);
  3658. }
  3659. STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int align_to_integer)
  3660. {
  3661. float ipw = 1.0f / pw, iph = 1.0f / ph;
  3662. const stbtt_packedchar *b = chardata + char_index;
  3663. if (align_to_integer) {
  3664. float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f);
  3665. float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f);
  3666. q->x0 = x;
  3667. q->y0 = y;
  3668. q->x1 = x + b->xoff2 - b->xoff;
  3669. q->y1 = y + b->yoff2 - b->yoff;
  3670. } else {
  3671. q->x0 = *xpos + b->xoff;
  3672. q->y0 = *ypos + b->yoff;
  3673. q->x1 = *xpos + b->xoff2;
  3674. q->y1 = *ypos + b->yoff2;
  3675. }
  3676. q->s0 = b->x0 * ipw;
  3677. q->t0 = b->y0 * iph;
  3678. q->s1 = b->x1 * ipw;
  3679. q->t1 = b->y1 * iph;
  3680. *xpos += b->xadvance;
  3681. }
  3682. //////////////////////////////////////////////////////////////////////////////
  3683. //
  3684. // sdf computation
  3685. //
  3686. #define STBTT_min(a,b) ((a) < (b) ? (a) : (b))
  3687. #define STBTT_max(a,b) ((a) < (b) ? (b) : (a))
  3688. static int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], float q1[2], float q2[2], float hits[2][2])
  3689. {
  3690. float q0perp = q0[1]*ray[0] - q0[0]*ray[1];
  3691. float q1perp = q1[1]*ray[0] - q1[0]*ray[1];
  3692. float q2perp = q2[1]*ray[0] - q2[0]*ray[1];
  3693. float roperp = orig[1]*ray[0] - orig[0]*ray[1];
  3694. float a = q0perp - 2*q1perp + q2perp;
  3695. float b = q1perp - q0perp;
  3696. float c = q0perp - roperp;
  3697. float s0 = 0., s1 = 0.;
  3698. int num_s = 0;
  3699. if (a != 0.0) {
  3700. float discr = b*b - a*c;
  3701. if (discr > 0.0) {
  3702. float rcpna = -1 / a;
  3703. float d = (float) STBTT_sqrt(discr);
  3704. s0 = (b+d) * rcpna;
  3705. s1 = (b-d) * rcpna;
  3706. if (s0 >= 0.0 && s0 <= 1.0)
  3707. num_s = 1;
  3708. if (d > 0.0 && s1 >= 0.0 && s1 <= 1.0) {
  3709. if (num_s == 0) s0 = s1;
  3710. ++num_s;
  3711. }
  3712. }
  3713. } else {
  3714. // 2*b*s + c = 0
  3715. // s = -c / (2*b)
  3716. s0 = c / (-2 * b);
  3717. if (s0 >= 0.0 && s0 <= 1.0)
  3718. num_s = 1;
  3719. }
  3720. if (num_s == 0)
  3721. return 0;
  3722. else {
  3723. float rcp_len2 = 1 / (ray[0]*ray[0] + ray[1]*ray[1]);
  3724. float rayn_x = ray[0] * rcp_len2, rayn_y = ray[1] * rcp_len2;
  3725. float q0d = q0[0]*rayn_x + q0[1]*rayn_y;
  3726. float q1d = q1[0]*rayn_x + q1[1]*rayn_y;
  3727. float q2d = q2[0]*rayn_x + q2[1]*rayn_y;
  3728. float rod = orig[0]*rayn_x + orig[1]*rayn_y;
  3729. float q10d = q1d - q0d;
  3730. float q20d = q2d - q0d;
  3731. float q0rd = q0d - rod;
  3732. hits[0][0] = q0rd + s0*(2.0f - 2.0f*s0)*q10d + s0*s0*q20d;
  3733. hits[0][1] = a*s0+b;
  3734. if (num_s > 1) {
  3735. hits[1][0] = q0rd + s1*(2.0f - 2.0f*s1)*q10d + s1*s1*q20d;
  3736. hits[1][1] = a*s1+b;
  3737. return 2;
  3738. } else {
  3739. return 1;
  3740. }
  3741. }
  3742. }
  3743. static int equal(float *a, float *b)
  3744. {
  3745. return (a[0] == b[0] && a[1] == b[1]);
  3746. }
  3747. static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex *verts)
  3748. {
  3749. int i;
  3750. float orig[2], ray[2] = { 1, 0 };
  3751. float y_frac;
  3752. int winding = 0;
  3753. orig[0] = x;
  3754. //orig[1] = y; // [ImGui] commmented double assignment without reading
  3755. // make sure y never passes through a vertex of the shape
  3756. y_frac = (float) STBTT_fmod(y, 1.0f);
  3757. if (y_frac < 0.01f)
  3758. y += 0.01f;
  3759. else if (y_frac > 0.99f)
  3760. y -= 0.01f;
  3761. orig[1] = y;
  3762. // test a ray from (-infinity,y) to (x,y)
  3763. for (i=0; i < nverts; ++i) {
  3764. if (verts[i].type == STBTT_vline) {
  3765. int x0 = (int) verts[i-1].x, y0 = (int) verts[i-1].y;
  3766. int x1 = (int) verts[i ].x, y1 = (int) verts[i ].y;
  3767. if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) {
  3768. float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0;
  3769. if (x_inter < x)
  3770. winding += (y0 < y1) ? 1 : -1;
  3771. }
  3772. }
  3773. if (verts[i].type == STBTT_vcurve) {
  3774. int x0 = (int) verts[i-1].x , y0 = (int) verts[i-1].y ;
  3775. int x1 = (int) verts[i ].cx, y1 = (int) verts[i ].cy;
  3776. int x2 = (int) verts[i ].x , y2 = (int) verts[i ].y ;
  3777. int ax = STBTT_min(x0,STBTT_min(x1,x2)), ay = STBTT_min(y0,STBTT_min(y1,y2));
  3778. int by = STBTT_max(y0,STBTT_max(y1,y2));
  3779. if (y > ay && y < by && x > ax) {
  3780. float q0[2],q1[2],q2[2];
  3781. float hits[2][2];
  3782. q0[0] = (float)x0;
  3783. q0[1] = (float)y0;
  3784. q1[0] = (float)x1;
  3785. q1[1] = (float)y1;
  3786. q2[0] = (float)x2;
  3787. q2[1] = (float)y2;
  3788. if (equal(q0,q1) || equal(q1,q2)) {
  3789. x0 = (int)verts[i-1].x;
  3790. y0 = (int)verts[i-1].y;
  3791. x1 = (int)verts[i ].x;
  3792. y1 = (int)verts[i ].y;
  3793. if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) {
  3794. float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0;
  3795. if (x_inter < x)
  3796. winding += (y0 < y1) ? 1 : -1;
  3797. }
  3798. } else {
  3799. int num_hits = stbtt__ray_intersect_bezier(orig, ray, q0, q1, q2, hits);
  3800. if (num_hits >= 1)
  3801. if (hits[0][0] < 0)
  3802. winding += (hits[0][1] < 0 ? -1 : 1);
  3803. if (num_hits >= 2)
  3804. if (hits[1][0] < 0)
  3805. winding += (hits[1][1] < 0 ? -1 : 1);
  3806. }
  3807. }
  3808. }
  3809. }
  3810. return winding;
  3811. }
  3812. static float stbtt__cuberoot( float x )
  3813. {
  3814. if (x<0)
  3815. return -(float) STBTT_pow(-x,1.0f/3.0f);
  3816. else
  3817. return (float) STBTT_pow( x,1.0f/3.0f);
  3818. }
  3819. // x^3 + c*x^2 + b*x + a = 0
  3820. static int stbtt__solve_cubic(float a, float b, float c, float* r)
  3821. {
  3822. float s = -a / 3;
  3823. float p = b - a*a / 3;
  3824. float q = a * (2*a*a - 9*b) / 27 + c;
  3825. float p3 = p*p*p;
  3826. float d = q*q + 4*p3 / 27;
  3827. if (d >= 0) {
  3828. float z = (float) STBTT_sqrt(d);
  3829. float u = (-q + z) / 2;
  3830. float v = (-q - z) / 2;
  3831. u = stbtt__cuberoot(u);
  3832. v = stbtt__cuberoot(v);
  3833. r[0] = s + u + v;
  3834. return 1;
  3835. } else {
  3836. float u = (float) STBTT_sqrt(-p/3);
  3837. float v = (float) STBTT_acos(-STBTT_sqrt(-27/p3) * q / 2) / 3; // p3 must be negative, since d is negative
  3838. float m = (float) STBTT_cos(v);
  3839. float n = (float) STBTT_cos(v-3.141592/2)*1.732050808f;
  3840. r[0] = s + u * 2 * m;
  3841. r[1] = s - u * (m + n);
  3842. r[2] = s - u * (m - n);
  3843. //STBTT_assert( STBTT_fabs(((r[0]+a)*r[0]+b)*r[0]+c) < 0.05f); // these asserts may not be safe at all scales, though they're in bezier t parameter units so maybe?
  3844. //STBTT_assert( STBTT_fabs(((r[1]+a)*r[1]+b)*r[1]+c) < 0.05f);
  3845. //STBTT_assert( STBTT_fabs(((r[2]+a)*r[2]+b)*r[2]+c) < 0.05f);
  3846. return 3;
  3847. }
  3848. }
  3849. STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff)
  3850. {
  3851. float scale_x = scale, scale_y = scale;
  3852. int ix0,iy0,ix1,iy1;
  3853. int w,h;
  3854. unsigned char *data;
  3855. // if one scale is 0, use same scale for both
  3856. if (scale_x == 0) scale_x = scale_y;
  3857. if (scale_y == 0) {
  3858. if (scale_x == 0) return NULL; // if both scales are 0, return NULL
  3859. scale_y = scale_x;
  3860. }
  3861. stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f,0.0f, &ix0,&iy0,&ix1,&iy1);
  3862. // if empty, return NULL
  3863. if (ix0 == ix1 || iy0 == iy1)
  3864. return NULL;
  3865. ix0 -= padding;
  3866. iy0 -= padding;
  3867. ix1 += padding;
  3868. iy1 += padding;
  3869. w = (ix1 - ix0);
  3870. h = (iy1 - iy0);
  3871. if (width ) *width = w;
  3872. if (height) *height = h;
  3873. if (xoff ) *xoff = ix0;
  3874. if (yoff ) *yoff = iy0;
  3875. // invert for y-downwards bitmaps
  3876. scale_y = -scale_y;
  3877. {
  3878. int x,y,i,j;
  3879. float *precompute;
  3880. stbtt_vertex *verts;
  3881. int num_verts = stbtt_GetGlyphShape(info, glyph, &verts);
  3882. data = (unsigned char *) STBTT_malloc(w * h, info->userdata);
  3883. precompute = (float *) STBTT_malloc(num_verts * sizeof(float), info->userdata);
  3884. for (i=0,j=num_verts-1; i < num_verts; j=i++) {
  3885. if (verts[i].type == STBTT_vline) {
  3886. float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y;
  3887. float x1 = verts[j].x*scale_x, y1 = verts[j].y*scale_y;
  3888. float dist = (float) STBTT_sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0));
  3889. precompute[i] = (dist == 0) ? 0.0f : 1.0f / dist;
  3890. } else if (verts[i].type == STBTT_vcurve) {
  3891. float x2 = verts[j].x *scale_x, y2 = verts[j].y *scale_y;
  3892. float x1 = verts[i].cx*scale_x, y1 = verts[i].cy*scale_y;
  3893. float x0 = verts[i].x *scale_x, y0 = verts[i].y *scale_y;
  3894. float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2;
  3895. float len2 = bx*bx + by*by;
  3896. if (len2 != 0.0f)
  3897. precompute[i] = 1.0f / (bx*bx + by*by);
  3898. else
  3899. precompute[i] = 0.0f;
  3900. } else
  3901. precompute[i] = 0.0f;
  3902. }
  3903. for (y=iy0; y < iy1; ++y) {
  3904. for (x=ix0; x < ix1; ++x) {
  3905. float val;
  3906. float min_dist = 999999.0f;
  3907. float sx = (float) x + 0.5f;
  3908. float sy = (float) y + 0.5f;
  3909. float x_gspace = (sx / scale_x);
  3910. float y_gspace = (sy / scale_y);
  3911. int winding = stbtt__compute_crossings_x(x_gspace, y_gspace, num_verts, verts); // @OPTIMIZE: this could just be a rasterization, but needs to be line vs. non-tesselated curves so a new path
  3912. for (i=0; i < num_verts; ++i) {
  3913. float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y;
  3914. // check against every point here rather than inside line/curve primitives -- @TODO: wrong if multiple 'moves' in a row produce a garbage point, and given culling, probably more efficient to do within line/curve
  3915. float dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy);
  3916. if (dist2 < min_dist*min_dist)
  3917. min_dist = (float) STBTT_sqrt(dist2);
  3918. if (verts[i].type == STBTT_vline) {
  3919. float x1 = verts[i-1].x*scale_x, y1 = verts[i-1].y*scale_y;
  3920. // coarse culling against bbox
  3921. //if (sx > STBTT_min(x0,x1)-min_dist && sx < STBTT_max(x0,x1)+min_dist &&
  3922. // sy > STBTT_min(y0,y1)-min_dist && sy < STBTT_max(y0,y1)+min_dist)
  3923. float dist = (float) STBTT_fabs((x1-x0)*(y0-sy) - (y1-y0)*(x0-sx)) * precompute[i];
  3924. STBTT_assert(i != 0);
  3925. if (dist < min_dist) {
  3926. // check position along line
  3927. // x' = x0 + t*(x1-x0), y' = y0 + t*(y1-y0)
  3928. // minimize (x'-sx)*(x'-sx)+(y'-sy)*(y'-sy)
  3929. float dx = x1-x0, dy = y1-y0;
  3930. float px = x0-sx, py = y0-sy;
  3931. // minimize (px+t*dx)^2 + (py+t*dy)^2 = px*px + 2*px*dx*t + t^2*dx*dx + py*py + 2*py*dy*t + t^2*dy*dy
  3932. // derivative: 2*px*dx + 2*py*dy + (2*dx*dx+2*dy*dy)*t, set to 0 and solve
  3933. float t = -(px*dx + py*dy) / (dx*dx + dy*dy);
  3934. if (t >= 0.0f && t <= 1.0f)
  3935. min_dist = dist;
  3936. }
  3937. } else if (verts[i].type == STBTT_vcurve) {
  3938. float x2 = verts[i-1].x *scale_x, y2 = verts[i-1].y *scale_y;
  3939. float x1 = verts[i ].cx*scale_x, y1 = verts[i ].cy*scale_y;
  3940. float box_x0 = STBTT_min(STBTT_min(x0,x1),x2);
  3941. float box_y0 = STBTT_min(STBTT_min(y0,y1),y2);
  3942. float box_x1 = STBTT_max(STBTT_max(x0,x1),x2);
  3943. float box_y1 = STBTT_max(STBTT_max(y0,y1),y2);
  3944. // coarse culling against bbox to avoid computing cubic unnecessarily
  3945. if (sx > box_x0-min_dist && sx < box_x1+min_dist && sy > box_y0-min_dist && sy < box_y1+min_dist) {
  3946. int num=0;
  3947. float ax = x1-x0, ay = y1-y0;
  3948. float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2;
  3949. float mx = x0 - sx, my = y0 - sy;
  3950. float res[3],px,py,t,it;
  3951. float a_inv = precompute[i];
  3952. if (a_inv == 0.0) { // if a_inv is 0, it's 2nd degree so use quadratic formula
  3953. float a = 3*(ax*bx + ay*by);
  3954. float b = 2*(ax*ax + ay*ay) + (mx*bx+my*by);
  3955. float c = mx*ax+my*ay;
  3956. if (a == 0.0) { // if a is 0, it's linear
  3957. if (b != 0.0) {
  3958. res[num++] = -c/b;
  3959. }
  3960. } else {
  3961. float discriminant = b*b - 4*a*c;
  3962. if (discriminant < 0)
  3963. num = 0;
  3964. else {
  3965. float root = (float) STBTT_sqrt(discriminant);
  3966. res[0] = (-b - root)/(2*a);
  3967. res[1] = (-b + root)/(2*a);
  3968. num = 2; // don't bother distinguishing 1-solution case, as code below will still work
  3969. }
  3970. }
  3971. } else {
  3972. float b = 3*(ax*bx + ay*by) * a_inv; // could precompute this as it doesn't depend on sample point
  3973. float c = (2*(ax*ax + ay*ay) + (mx*bx+my*by)) * a_inv;
  3974. float d = (mx*ax+my*ay) * a_inv;
  3975. num = stbtt__solve_cubic(b, c, d, res);
  3976. }
  3977. if (num >= 1 && res[0] >= 0.0f && res[0] <= 1.0f) {
  3978. t = res[0], it = 1.0f - t;
  3979. px = it*it*x0 + 2*t*it*x1 + t*t*x2;
  3980. py = it*it*y0 + 2*t*it*y1 + t*t*y2;
  3981. dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);
  3982. if (dist2 < min_dist * min_dist)
  3983. min_dist = (float) STBTT_sqrt(dist2);
  3984. }
  3985. if (num >= 2 && res[1] >= 0.0f && res[1] <= 1.0f) {
  3986. t = res[1], it = 1.0f - t;
  3987. px = it*it*x0 + 2*t*it*x1 + t*t*x2;
  3988. py = it*it*y0 + 2*t*it*y1 + t*t*y2;
  3989. dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);
  3990. if (dist2 < min_dist * min_dist)
  3991. min_dist = (float) STBTT_sqrt(dist2);
  3992. }
  3993. if (num >= 3 && res[2] >= 0.0f && res[2] <= 1.0f) {
  3994. t = res[2], it = 1.0f - t;
  3995. px = it*it*x0 + 2*t*it*x1 + t*t*x2;
  3996. py = it*it*y0 + 2*t*it*y1 + t*t*y2;
  3997. dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);
  3998. if (dist2 < min_dist * min_dist)
  3999. min_dist = (float) STBTT_sqrt(dist2);
  4000. }
  4001. }
  4002. }
  4003. }
  4004. if (winding == 0)
  4005. min_dist = -min_dist; // if outside the shape, value is negative
  4006. val = onedge_value + pixel_dist_scale * min_dist;
  4007. if (val < 0)
  4008. val = 0;
  4009. else if (val > 255)
  4010. val = 255;
  4011. data[(y-iy0)*w+(x-ix0)] = (unsigned char) val;
  4012. }
  4013. }
  4014. STBTT_free(precompute, info->userdata);
  4015. STBTT_free(verts, info->userdata);
  4016. }
  4017. return data;
  4018. }
  4019. STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff)
  4020. {
  4021. return stbtt_GetGlyphSDF(info, scale, stbtt_FindGlyphIndex(info, codepoint), padding, onedge_value, pixel_dist_scale, width, height, xoff, yoff);
  4022. }
  4023. STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata)
  4024. {
  4025. STBTT_free(bitmap, userdata);
  4026. }
  4027. //////////////////////////////////////////////////////////////////////////////
  4028. //
  4029. // font name matching -- recommended not to use this
  4030. //
  4031. // check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string
  4032. static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 *s1, stbtt_int32 len1, stbtt_uint8 *s2, stbtt_int32 len2)
  4033. {
  4034. stbtt_int32 i=0;
  4035. // convert utf16 to utf8 and compare the results while converting
  4036. while (len2) {
  4037. stbtt_uint16 ch = s2[0]*256 + s2[1];
  4038. if (ch < 0x80) {
  4039. if (i >= len1) return -1;
  4040. if (s1[i++] != ch) return -1;
  4041. } else if (ch < 0x800) {
  4042. if (i+1 >= len1) return -1;
  4043. if (s1[i++] != 0xc0 + (ch >> 6)) return -1;
  4044. if (s1[i++] != 0x80 + (ch & 0x3f)) return -1;
  4045. } else if (ch >= 0xd800 && ch < 0xdc00) {
  4046. stbtt_uint32 c;
  4047. stbtt_uint16 ch2 = s2[2]*256 + s2[3];
  4048. if (i+3 >= len1) return -1;
  4049. c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000;
  4050. if (s1[i++] != 0xf0 + (c >> 18)) return -1;
  4051. if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1;
  4052. if (s1[i++] != 0x80 + ((c >> 6) & 0x3f)) return -1;
  4053. if (s1[i++] != 0x80 + ((c ) & 0x3f)) return -1;
  4054. s2 += 2; // plus another 2 below
  4055. len2 -= 2;
  4056. } else if (ch >= 0xdc00 && ch < 0xe000) {
  4057. return -1;
  4058. } else {
  4059. if (i+2 >= len1) return -1;
  4060. if (s1[i++] != 0xe0 + (ch >> 12)) return -1;
  4061. if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1;
  4062. if (s1[i++] != 0x80 + ((ch ) & 0x3f)) return -1;
  4063. }
  4064. s2 += 2;
  4065. len2 -= 2;
  4066. }
  4067. return i;
  4068. }
  4069. static int stbtt_CompareUTF8toUTF16_bigendian_internal(char *s1, int len1, char *s2, int len2)
  4070. {
  4071. return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8*) s1, len1, (stbtt_uint8*) s2, len2);
  4072. }
  4073. // returns results in whatever encoding you request... but note that 2-byte encodings
  4074. // will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare
  4075. STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID)
  4076. {
  4077. stbtt_int32 i,count,stringOffset;
  4078. stbtt_uint8 *fc = font->data;
  4079. stbtt_uint32 offset = font->fontstart;
  4080. stbtt_uint32 nm = stbtt__find_table(fc, offset, "name");
  4081. if (!nm) return NULL;
  4082. count = ttUSHORT(fc+nm+2);
  4083. stringOffset = nm + ttUSHORT(fc+nm+4);
  4084. for (i=0; i < count; ++i) {
  4085. stbtt_uint32 loc = nm + 6 + 12 * i;
  4086. if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2)
  4087. && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) {
  4088. *length = ttUSHORT(fc+loc+8);
  4089. return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10));
  4090. }
  4091. }
  4092. return NULL;
  4093. }
  4094. static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id)
  4095. {
  4096. stbtt_int32 i;
  4097. stbtt_int32 count = ttUSHORT(fc+nm+2);
  4098. stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4);
  4099. for (i=0; i < count; ++i) {
  4100. stbtt_uint32 loc = nm + 6 + 12 * i;
  4101. stbtt_int32 id = ttUSHORT(fc+loc+6);
  4102. if (id == target_id) {
  4103. // find the encoding
  4104. stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4);
  4105. // is this a Unicode encoding?
  4106. if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) {
  4107. stbtt_int32 slen = ttUSHORT(fc+loc+8);
  4108. stbtt_int32 off = ttUSHORT(fc+loc+10);
  4109. // check if there's a prefix match
  4110. stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen);
  4111. if (matchlen >= 0) {
  4112. // check for target_id+1 immediately following, with same encoding & language
  4113. 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) {
  4114. slen = ttUSHORT(fc+loc+12+8);
  4115. off = ttUSHORT(fc+loc+12+10);
  4116. if (slen == 0) {
  4117. if (matchlen == nlen)
  4118. return 1;
  4119. } else if (matchlen < nlen && name[matchlen] == ' ') {
  4120. ++matchlen;
  4121. if (stbtt_CompareUTF8toUTF16_bigendian_internal((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen))
  4122. return 1;
  4123. }
  4124. } else {
  4125. // if nothing immediately following
  4126. if (matchlen == nlen)
  4127. return 1;
  4128. }
  4129. }
  4130. }
  4131. // @TODO handle other encodings
  4132. }
  4133. }
  4134. return 0;
  4135. }
  4136. static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags)
  4137. {
  4138. stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name);
  4139. stbtt_uint32 nm,hd;
  4140. if (!stbtt__isfont(fc+offset)) return 0;
  4141. // check italics/bold/underline flags in macStyle...
  4142. if (flags) {
  4143. hd = stbtt__find_table(fc, offset, "head");
  4144. if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0;
  4145. }
  4146. nm = stbtt__find_table(fc, offset, "name");
  4147. if (!nm) return 0;
  4148. if (flags) {
  4149. // if we checked the macStyle flags, then just check the family and ignore the subfamily
  4150. if (stbtt__matchpair(fc, nm, name, nlen, 16, -1)) return 1;
  4151. if (stbtt__matchpair(fc, nm, name, nlen, 1, -1)) return 1;
  4152. if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1;
  4153. } else {
  4154. if (stbtt__matchpair(fc, nm, name, nlen, 16, 17)) return 1;
  4155. if (stbtt__matchpair(fc, nm, name, nlen, 1, 2)) return 1;
  4156. if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1;
  4157. }
  4158. return 0;
  4159. }
  4160. static int stbtt_FindMatchingFont_internal(unsigned char *font_collection, char *name_utf8, stbtt_int32 flags)
  4161. {
  4162. stbtt_int32 i;
  4163. for (i=0;;++i) {
  4164. stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i);
  4165. if (off < 0) return off;
  4166. if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags))
  4167. return off;
  4168. }
  4169. }
  4170. #if defined(__GNUC__) || defined(__clang__)
  4171. #pragma GCC diagnostic push
  4172. #pragma GCC diagnostic ignored "-Wcast-qual"
  4173. #endif
  4174. STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset,
  4175. float pixel_height, unsigned char *pixels, int pw, int ph,
  4176. int first_char, int num_chars, stbtt_bakedchar *chardata)
  4177. {
  4178. return stbtt_BakeFontBitmap_internal((unsigned char *) data, offset, pixel_height, pixels, pw, ph, first_char, num_chars, chardata);
  4179. }
  4180. STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index)
  4181. {
  4182. return stbtt_GetFontOffsetForIndex_internal((unsigned char *) data, index);
  4183. }
  4184. STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data)
  4185. {
  4186. return stbtt_GetNumberOfFonts_internal((unsigned char *) data);
  4187. }
  4188. STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset)
  4189. {
  4190. return stbtt_InitFont_internal(info, (unsigned char *) data, offset);
  4191. }
  4192. STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags)
  4193. {
  4194. return stbtt_FindMatchingFont_internal((unsigned char *) fontdata, (char *) name, flags);
  4195. }
  4196. STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2)
  4197. {
  4198. return stbtt_CompareUTF8toUTF16_bigendian_internal((char *) s1, len1, (char *) s2, len2);
  4199. }
  4200. #if defined(__GNUC__) || defined(__clang__)
  4201. #pragma GCC diagnostic pop
  4202. #endif
  4203. #endif // STB_TRUETYPE_IMPLEMENTATION
  4204. // FULL VERSION HISTORY
  4205. //
  4206. // 1.19 (2018-02-11) OpenType GPOS kerning (horizontal only), STBTT_fmod
  4207. // 1.18 (2018-01-29) add missing function
  4208. // 1.17 (2017-07-23) make more arguments const; doc fix
  4209. // 1.16 (2017-07-12) SDF support
  4210. // 1.15 (2017-03-03) make more arguments const
  4211. // 1.14 (2017-01-16) num-fonts-in-TTC function
  4212. // 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts
  4213. // 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual
  4214. // 1.11 (2016-04-02) fix unused-variable warning
  4215. // 1.10 (2016-04-02) allow user-defined fabs() replacement
  4216. // fix memory leak if fontsize=0.0
  4217. // fix warning from duplicate typedef
  4218. // 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges
  4219. // 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges
  4220. // 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;
  4221. // allow PackFontRanges to pack and render in separate phases;
  4222. // fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);
  4223. // fixed an assert() bug in the new rasterizer
  4224. // replace assert() with STBTT_assert() in new rasterizer
  4225. // 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine)
  4226. // also more precise AA rasterizer, except if shapes overlap
  4227. // remove need for STBTT_sort
  4228. // 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC
  4229. // 1.04 (2015-04-15) typo in example
  4230. // 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes
  4231. // 1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++
  4232. // 1.01 (2014-12-08) fix subpixel position when oversampling to exactly match
  4233. // non-oversampled; STBTT_POINT_SIZE for packed case only
  4234. // 1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling
  4235. // 0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg)
  4236. // 0.9 (2014-08-07) support certain mac/iOS fonts without an MS platformID
  4237. // 0.8b (2014-07-07) fix a warning
  4238. // 0.8 (2014-05-25) fix a few more warnings
  4239. // 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back
  4240. // 0.6c (2012-07-24) improve documentation
  4241. // 0.6b (2012-07-20) fix a few more warnings
  4242. // 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels,
  4243. // stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty
  4244. // 0.5 (2011-12-09) bugfixes:
  4245. // subpixel glyph renderer computed wrong bounding box
  4246. // first vertex of shape can be off-curve (FreeSans)
  4247. // 0.4b (2011-12-03) fixed an error in the font baking example
  4248. // 0.4 (2011-12-01) kerning, subpixel rendering (tor)
  4249. // bugfixes for:
  4250. // codepoint-to-glyph conversion using table fmt=12
  4251. // codepoint-to-glyph conversion using table fmt=4
  4252. // stbtt_GetBakedQuad with non-square texture (Zer)
  4253. // updated Hello World! sample to use kerning and subpixel
  4254. // fixed some warnings
  4255. // 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM)
  4256. // userdata, malloc-from-userdata, non-zero fill (stb)
  4257. // 0.2 (2009-03-11) Fix unsigned/signed char warnings
  4258. // 0.1 (2009-03-09) First public release
  4259. //
  4260. /*
  4261. ------------------------------------------------------------------------------
  4262. This software is available under 2 licenses -- choose whichever you prefer.
  4263. ------------------------------------------------------------------------------
  4264. ALTERNATIVE A - MIT License
  4265. Copyright (c) 2017 Sean Barrett
  4266. Permission is hereby granted, free of charge, to any person obtaining a copy of
  4267. this software and associated documentation files (the "Software"), to deal in
  4268. the Software without restriction, including without limitation the rights to
  4269. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  4270. of the Software, and to permit persons to whom the Software is furnished to do
  4271. so, subject to the following conditions:
  4272. The above copyright notice and this permission notice shall be included in all
  4273. copies or substantial portions of the Software.
  4274. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  4275. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  4276. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  4277. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  4278. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  4279. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  4280. SOFTWARE.
  4281. ------------------------------------------------------------------------------
  4282. ALTERNATIVE B - Public Domain (www.unlicense.org)
  4283. This is free and unencumbered software released into the public domain.
  4284. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
  4285. software, either in source code form or as a compiled binary, for any purpose,
  4286. commercial or non-commercial, and by any means.
  4287. In jurisdictions that recognize copyright laws, the author or authors of this
  4288. software dedicate any and all copyright interest in the software to the public
  4289. domain. We make this dedication for the benefit of the public at large and to
  4290. the detriment of our heirs and successors. We intend this dedication to be an
  4291. overt act of relinquishment in perpetuity of all present and future rights to
  4292. this software under copyright law.
  4293. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  4294. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  4295. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  4296. AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  4297. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  4298. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  4299. ------------------------------------------------------------------------------
  4300. */