stb_truetype.h 173 KB

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