*/}}

stb_truetype.h 191 KB

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