text_server_adv.cpp 217 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039
  1. /*************************************************************************/
  2. /* text_server_adv.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "text_server_adv.h"
  31. #include "core/object/worker_thread_pool.h"
  32. #ifdef GDEXTENSION
  33. // Headers for building as GDExtension plug-in.
  34. #include <godot_cpp/classes/file.hpp>
  35. #include <godot_cpp/classes/rendering_server.hpp>
  36. #include <godot_cpp/classes/translation_server.hpp>
  37. #include <godot_cpp/core/error_macros.hpp>
  38. using namespace godot;
  39. #else
  40. // Headers for building as built-in module.
  41. #include "core/core_bind.h"
  42. #include "core/error/error_macros.h"
  43. #include "core/string/print_string.h"
  44. #include "core/string/translation.h"
  45. #include "modules/modules_enabled.gen.h" // For freetype, msdfgen.
  46. using namespace core_bind;
  47. #endif
  48. // Built-in ICU data.
  49. #ifdef ICU_STATIC_DATA
  50. #include "icudata.gen.h"
  51. #endif
  52. // Thirdparty headers.
  53. #ifdef MODULE_MSDFGEN_ENABLED
  54. #include "core/ShapeDistanceFinder.h"
  55. #include "core/contour-combiners.h"
  56. #include "core/edge-selectors.h"
  57. #include "msdfgen.h"
  58. #endif
  59. /*************************************************************************/
  60. /* bmp_font_t HarfBuzz Bitmap font interface */
  61. /*************************************************************************/
  62. hb_font_funcs_t *TextServerAdvanced::funcs = nullptr;
  63. TextServerAdvanced::bmp_font_t *TextServerAdvanced::_bmp_font_create(TextServerAdvanced::FontForSizeAdvanced *p_face, bool p_unref) {
  64. bmp_font_t *bm_font = memnew(bmp_font_t);
  65. if (!bm_font) {
  66. return nullptr;
  67. }
  68. bm_font->face = p_face;
  69. bm_font->unref = p_unref;
  70. return bm_font;
  71. }
  72. void TextServerAdvanced::_bmp_font_destroy(void *p_data) {
  73. bmp_font_t *bm_font = static_cast<bmp_font_t *>(p_data);
  74. memdelete(bm_font);
  75. }
  76. hb_bool_t TextServerAdvanced::_bmp_get_nominal_glyph(hb_font_t *p_font, void *p_font_data, hb_codepoint_t p_unicode, hb_codepoint_t *r_glyph, void *p_user_data) {
  77. const bmp_font_t *bm_font = static_cast<const bmp_font_t *>(p_font_data);
  78. if (!bm_font->face) {
  79. return false;
  80. }
  81. if (!bm_font->face->glyph_map.has(p_unicode)) {
  82. if (bm_font->face->glyph_map.has(0xf000u + p_unicode)) {
  83. *r_glyph = 0xf000u + p_unicode;
  84. return true;
  85. } else {
  86. return false;
  87. }
  88. }
  89. *r_glyph = p_unicode;
  90. return true;
  91. }
  92. hb_position_t TextServerAdvanced::_bmp_get_glyph_h_advance(hb_font_t *p_font, void *p_font_data, hb_codepoint_t p_glyph, void *p_user_data) {
  93. const bmp_font_t *bm_font = static_cast<const bmp_font_t *>(p_font_data);
  94. if (!bm_font->face) {
  95. return 0;
  96. }
  97. if (!bm_font->face->glyph_map.has(p_glyph)) {
  98. return 0;
  99. }
  100. return bm_font->face->glyph_map[p_glyph].advance.x * 64;
  101. }
  102. hb_position_t TextServerAdvanced::_bmp_get_glyph_v_advance(hb_font_t *p_font, void *p_font_data, hb_codepoint_t p_glyph, void *p_user_data) {
  103. const bmp_font_t *bm_font = static_cast<const bmp_font_t *>(p_font_data);
  104. if (!bm_font->face) {
  105. return 0;
  106. }
  107. if (!bm_font->face->glyph_map.has(p_glyph)) {
  108. return 0;
  109. }
  110. return -bm_font->face->glyph_map[p_glyph].advance.y * 64;
  111. }
  112. hb_position_t TextServerAdvanced::_bmp_get_glyph_h_kerning(hb_font_t *p_font, void *p_font_data, hb_codepoint_t p_left_glyph, hb_codepoint_t p_right_glyph, void *p_user_data) {
  113. const bmp_font_t *bm_font = static_cast<const bmp_font_t *>(p_font_data);
  114. if (!bm_font->face) {
  115. return 0;
  116. }
  117. if (!bm_font->face->kerning_map.has(Vector2i(p_left_glyph, p_right_glyph))) {
  118. return 0;
  119. }
  120. return bm_font->face->kerning_map[Vector2i(p_left_glyph, p_right_glyph)].x * 64;
  121. }
  122. hb_bool_t TextServerAdvanced::_bmp_get_glyph_v_origin(hb_font_t *p_font, void *p_font_data, hb_codepoint_t p_glyph, hb_position_t *r_x, hb_position_t *r_y, void *p_user_data) {
  123. const bmp_font_t *bm_font = static_cast<const bmp_font_t *>(p_font_data);
  124. if (!bm_font->face) {
  125. return false;
  126. }
  127. if (!bm_font->face->glyph_map.has(p_glyph)) {
  128. return false;
  129. }
  130. *r_x = bm_font->face->glyph_map[p_glyph].advance.x * 32;
  131. *r_y = -bm_font->face->ascent * 64;
  132. return true;
  133. }
  134. hb_bool_t TextServerAdvanced::_bmp_get_glyph_extents(hb_font_t *p_font, void *p_font_data, hb_codepoint_t p_glyph, hb_glyph_extents_t *r_extents, void *p_user_data) {
  135. const bmp_font_t *bm_font = static_cast<const bmp_font_t *>(p_font_data);
  136. if (!bm_font->face) {
  137. return false;
  138. }
  139. if (!bm_font->face->glyph_map.has(p_glyph)) {
  140. return false;
  141. }
  142. r_extents->x_bearing = 0;
  143. r_extents->y_bearing = 0;
  144. r_extents->width = bm_font->face->glyph_map[p_glyph].rect.size.x * 64;
  145. r_extents->height = bm_font->face->glyph_map[p_glyph].rect.size.y * 64;
  146. return true;
  147. }
  148. hb_bool_t TextServerAdvanced::_bmp_get_font_h_extents(hb_font_t *p_font, void *p_font_data, hb_font_extents_t *r_metrics, void *p_user_data) {
  149. const bmp_font_t *bm_font = static_cast<const bmp_font_t *>(p_font_data);
  150. if (!bm_font->face) {
  151. return false;
  152. }
  153. r_metrics->ascender = bm_font->face->ascent;
  154. r_metrics->descender = bm_font->face->descent;
  155. r_metrics->line_gap = 0;
  156. return true;
  157. }
  158. void TextServerAdvanced::_bmp_create_font_funcs() {
  159. if (funcs == nullptr) {
  160. funcs = hb_font_funcs_create();
  161. hb_font_funcs_set_font_h_extents_func(funcs, _bmp_get_font_h_extents, nullptr, nullptr);
  162. hb_font_funcs_set_nominal_glyph_func(funcs, _bmp_get_nominal_glyph, nullptr, nullptr);
  163. hb_font_funcs_set_glyph_h_advance_func(funcs, _bmp_get_glyph_h_advance, nullptr, nullptr);
  164. hb_font_funcs_set_glyph_v_advance_func(funcs, _bmp_get_glyph_v_advance, nullptr, nullptr);
  165. hb_font_funcs_set_glyph_v_origin_func(funcs, _bmp_get_glyph_v_origin, nullptr, nullptr);
  166. hb_font_funcs_set_glyph_h_kerning_func(funcs, _bmp_get_glyph_h_kerning, nullptr, nullptr);
  167. hb_font_funcs_set_glyph_extents_func(funcs, _bmp_get_glyph_extents, nullptr, nullptr);
  168. hb_font_funcs_make_immutable(funcs);
  169. }
  170. }
  171. void TextServerAdvanced::_bmp_free_font_funcs() {
  172. if (funcs != nullptr) {
  173. hb_font_funcs_destroy(funcs);
  174. funcs = nullptr;
  175. }
  176. }
  177. void TextServerAdvanced::_bmp_font_set_funcs(hb_font_t *p_font, TextServerAdvanced::FontForSizeAdvanced *p_face, bool p_unref) {
  178. hb_font_set_funcs(p_font, funcs, _bmp_font_create(p_face, p_unref), _bmp_font_destroy);
  179. }
  180. hb_font_t *TextServerAdvanced::_bmp_font_create(TextServerAdvanced::FontForSizeAdvanced *p_face, hb_destroy_func_t p_destroy) {
  181. hb_font_t *font;
  182. hb_face_t *face = hb_face_create(nullptr, 0);
  183. font = hb_font_create(face);
  184. hb_face_destroy(face);
  185. _bmp_font_set_funcs(font, p_face, false);
  186. return font;
  187. }
  188. /*************************************************************************/
  189. /* Character properties. */
  190. /*************************************************************************/
  191. _FORCE_INLINE_ bool is_ain(char32_t p_chr) {
  192. return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_AIN;
  193. }
  194. _FORCE_INLINE_ bool is_alef(char32_t p_chr) {
  195. return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_ALEF;
  196. }
  197. _FORCE_INLINE_ bool is_beh(char32_t p_chr) {
  198. int32_t prop = u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP);
  199. return (prop == U_JG_BEH) || (prop == U_JG_NOON) || (prop == U_JG_AFRICAN_NOON) || (prop == U_JG_NYA) || (prop == U_JG_YEH) || (prop == U_JG_FARSI_YEH);
  200. }
  201. _FORCE_INLINE_ bool is_dal(char32_t p_chr) {
  202. return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_DAL;
  203. }
  204. _FORCE_INLINE_ bool is_feh(char32_t p_chr) {
  205. return (u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_FEH) || (u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_AFRICAN_FEH);
  206. }
  207. _FORCE_INLINE_ bool is_gaf(char32_t p_chr) {
  208. return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_GAF;
  209. }
  210. _FORCE_INLINE_ bool is_heh(char32_t p_chr) {
  211. return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_HEH;
  212. }
  213. _FORCE_INLINE_ bool is_kaf(char32_t p_chr) {
  214. return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_KAF;
  215. }
  216. _FORCE_INLINE_ bool is_lam(char32_t p_chr) {
  217. return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_LAM;
  218. }
  219. _FORCE_INLINE_ bool is_qaf(char32_t p_chr) {
  220. return (u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_QAF) || (u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_AFRICAN_QAF);
  221. }
  222. _FORCE_INLINE_ bool is_reh(char32_t p_chr) {
  223. return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_REH;
  224. }
  225. _FORCE_INLINE_ bool is_seen_sad(char32_t p_chr) {
  226. return (u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_SAD) || (u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_SEEN);
  227. }
  228. _FORCE_INLINE_ bool is_tah(char32_t p_chr) {
  229. return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_TAH;
  230. }
  231. _FORCE_INLINE_ bool is_teh_marbuta(char32_t p_chr) {
  232. return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_TEH_MARBUTA;
  233. }
  234. _FORCE_INLINE_ bool is_yeh(char32_t p_chr) {
  235. int32_t prop = u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP);
  236. return (prop == U_JG_YEH) || (prop == U_JG_FARSI_YEH) || (prop == U_JG_YEH_BARREE) || (prop == U_JG_BURUSHASKI_YEH_BARREE) || (prop == U_JG_YEH_WITH_TAIL);
  237. }
  238. _FORCE_INLINE_ bool is_waw(char32_t p_chr) {
  239. return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_WAW;
  240. }
  241. _FORCE_INLINE_ bool is_transparent(char32_t p_chr) {
  242. return u_getIntPropertyValue(p_chr, UCHAR_JOINING_TYPE) == U_JT_TRANSPARENT;
  243. }
  244. _FORCE_INLINE_ bool is_ligature(char32_t p_chr, char32_t p_nchr) {
  245. return (is_lam(p_chr) && is_alef(p_nchr));
  246. }
  247. _FORCE_INLINE_ bool is_connected_to_prev(char32_t p_chr, char32_t p_pchr) {
  248. int32_t prop = u_getIntPropertyValue(p_pchr, UCHAR_JOINING_TYPE);
  249. return (prop != U_JT_RIGHT_JOINING) && (prop != U_JT_NON_JOINING) ? !is_ligature(p_pchr, p_chr) : false;
  250. }
  251. /*************************************************************************/
  252. bool TextServerAdvanced::has_feature(Feature p_feature) const {
  253. switch (p_feature) {
  254. case FEATURE_SIMPLE_LAYOUT:
  255. case FEATURE_BIDI_LAYOUT:
  256. case FEATURE_VERTICAL_LAYOUT:
  257. case FEATURE_SHAPING:
  258. case FEATURE_KASHIDA_JUSTIFICATION:
  259. case FEATURE_BREAK_ITERATORS:
  260. case FEATURE_FONT_BITMAP:
  261. #ifdef MODULE_FREETYPE_ENABLED
  262. case FEATURE_FONT_DYNAMIC:
  263. #endif
  264. #ifdef MODULE_MSDFGEN_ENABLED
  265. case FEATURE_FONT_MSDF:
  266. #endif
  267. case FEATURE_FONT_VARIABLE:
  268. case FEATURE_CONTEXT_SENSITIVE_CASE_CONVERSION:
  269. case FEATURE_USE_SUPPORT_DATA:
  270. case FEATURE_UNICODE_IDENTIFIERS:
  271. case FEATURE_UNICODE_SECURITY:
  272. return true;
  273. default: {
  274. }
  275. }
  276. return false;
  277. }
  278. String TextServerAdvanced::get_name() const {
  279. #ifdef GDEXTENSION
  280. return "ICU / HarfBuzz / Graphite (GDExtension)";
  281. #else
  282. return "ICU / HarfBuzz / Graphite (Built-in)";
  283. #endif
  284. }
  285. int64_t TextServerAdvanced::get_features() const {
  286. int64_t interface_features = FEATURE_SIMPLE_LAYOUT | FEATURE_BIDI_LAYOUT | FEATURE_VERTICAL_LAYOUT | FEATURE_SHAPING | FEATURE_KASHIDA_JUSTIFICATION | FEATURE_BREAK_ITERATORS | FEATURE_FONT_BITMAP | FEATURE_FONT_VARIABLE | FEATURE_CONTEXT_SENSITIVE_CASE_CONVERSION | FEATURE_USE_SUPPORT_DATA;
  287. #ifdef MODULE_FREETYPE_ENABLED
  288. interface_features |= FEATURE_FONT_DYNAMIC;
  289. #endif
  290. #ifdef MODULE_MSDFGEN_ENABLED
  291. interface_features |= FEATURE_FONT_MSDF;
  292. #endif
  293. return interface_features;
  294. }
  295. void TextServerAdvanced::free_rid(const RID &p_rid) {
  296. _THREAD_SAFE_METHOD_
  297. if (font_owner.owns(p_rid)) {
  298. FontAdvanced *fd = font_owner.get_or_null(p_rid);
  299. font_owner.free(p_rid);
  300. memdelete(fd);
  301. } else if (shaped_owner.owns(p_rid)) {
  302. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_rid);
  303. shaped_owner.free(p_rid);
  304. memdelete(sd);
  305. }
  306. }
  307. bool TextServerAdvanced::has(const RID &p_rid) {
  308. _THREAD_SAFE_METHOD_
  309. return font_owner.owns(p_rid) || shaped_owner.owns(p_rid);
  310. }
  311. bool TextServerAdvanced::load_support_data(const String &p_filename) {
  312. _THREAD_SAFE_METHOD_
  313. #ifdef ICU_STATIC_DATA
  314. if (!icu_data_loaded) {
  315. UErrorCode err = U_ZERO_ERROR;
  316. u_init(&err); // Do not check for errors, since we only load part of the data.
  317. icu_data_loaded = true;
  318. }
  319. #else
  320. if (!icu_data_loaded) {
  321. String filename = (p_filename.is_empty()) ? String("res://") + _MKSTR(ICU_DATA_NAME) : p_filename;
  322. Ref<File> f;
  323. f.instantiate();
  324. if (f->open(filename, File::READ) != OK) {
  325. return false;
  326. }
  327. uint64_t len = f->get_length();
  328. PackedByteArray icu_data = f->get_buffer(len);
  329. UErrorCode err = U_ZERO_ERROR;
  330. udata_setCommonData(icu_data.ptr(), &err);
  331. if (U_FAILURE(err)) {
  332. ERR_FAIL_V_MSG(false, u_errorName(err));
  333. }
  334. err = U_ZERO_ERROR;
  335. u_init(&err);
  336. if (U_FAILURE(err)) {
  337. ERR_FAIL_V_MSG(false, u_errorName(err));
  338. }
  339. icu_data_loaded = true;
  340. }
  341. #endif
  342. return true;
  343. }
  344. String TextServerAdvanced::get_support_data_filename() const {
  345. #ifdef ICU_STATIC_DATA
  346. return _MKSTR(ICU_DATA_NAME);
  347. #else
  348. return String();
  349. #endif
  350. }
  351. String TextServerAdvanced::get_support_data_info() const {
  352. #ifdef ICU_STATIC_DATA
  353. return String("ICU break iteration data (") + _MKSTR(ICU_DATA_NAME) + String(").");
  354. #else
  355. return String();
  356. #endif
  357. }
  358. bool TextServerAdvanced::save_support_data(const String &p_filename) const {
  359. _THREAD_SAFE_METHOD_
  360. #ifdef ICU_STATIC_DATA
  361. // Store data to the res file if it's available.
  362. Ref<File> f;
  363. f.instantiate();
  364. if (f->open(p_filename, File::WRITE) != OK) {
  365. return false;
  366. }
  367. PackedByteArray icu_data;
  368. icu_data.resize(U_ICUDATA_SIZE);
  369. memcpy(icu_data.ptrw(), U_ICUDATA_ENTRY_POINT, U_ICUDATA_SIZE);
  370. f->store_buffer(icu_data);
  371. return true;
  372. #else
  373. return false;
  374. #endif
  375. }
  376. bool TextServerAdvanced::is_locale_right_to_left(const String &p_locale) const {
  377. String l = p_locale.get_slicec('_', 0);
  378. if ((l == "ar") || (l == "dv") || (l == "he") || (l == "fa") || (l == "ff") || (l == "ku") || (l == "ur")) {
  379. return true;
  380. } else {
  381. return false;
  382. }
  383. }
  384. _FORCE_INLINE_ void TextServerAdvanced::_insert_feature(const StringName &p_name, int32_t p_tag, Variant::Type p_vtype, bool p_hidden) {
  385. FeatureInfo fi;
  386. fi.name = p_name;
  387. fi.vtype = p_vtype;
  388. fi.hidden = p_hidden;
  389. feature_sets.insert(p_name, p_tag);
  390. feature_sets_inv.insert(p_tag, fi);
  391. }
  392. void TextServerAdvanced::_insert_feature_sets() {
  393. // Registered OpenType feature tags.
  394. // Name, Tag, Data Type, Hidden
  395. _insert_feature("access_all_alternates", HB_TAG('a', 'a', 'l', 't'), Variant::Type::INT, false);
  396. _insert_feature("above_base_forms", HB_TAG('a', 'b', 'v', 'f'), Variant::Type::INT, true);
  397. _insert_feature("above_base_mark_positioning", HB_TAG('a', 'b', 'v', 'm'), Variant::Type::INT, true);
  398. _insert_feature("above_base_substitutions", HB_TAG('a', 'b', 'v', 's'), Variant::Type::INT, true);
  399. _insert_feature("alternative_fractions", HB_TAG('a', 'f', 'r', 'c'), Variant::Type::INT, false);
  400. _insert_feature("akhands", HB_TAG('a', 'k', 'h', 'n'), Variant::Type::INT, true);
  401. _insert_feature("below_base_forms", HB_TAG('b', 'l', 'w', 'f'), Variant::Type::INT, true);
  402. _insert_feature("below_base_mark_positioning", HB_TAG('b', 'l', 'w', 'm'), Variant::Type::INT, true);
  403. _insert_feature("below_base_substitutions", HB_TAG('b', 'l', 'w', 's'), Variant::Type::INT, true);
  404. _insert_feature("contextual_alternates", HB_TAG('c', 'a', 'l', 't'), Variant::Type::BOOL, false);
  405. _insert_feature("case_sensitive_forms", HB_TAG('c', 'a', 's', 'e'), Variant::Type::BOOL, false);
  406. _insert_feature("glyph_composition", HB_TAG('c', 'c', 'm', 'p'), Variant::Type::INT, true);
  407. _insert_feature("conjunct_form_after_ro", HB_TAG('c', 'f', 'a', 'r'), Variant::Type::INT, true);
  408. _insert_feature("contextual_half_width_spacing", HB_TAG('c', 'h', 'w', 's'), Variant::Type::INT, true);
  409. _insert_feature("conjunct_forms", HB_TAG('c', 'j', 'c', 't'), Variant::Type::INT, true);
  410. _insert_feature("contextual_ligatures", HB_TAG('c', 'l', 'i', 'g'), Variant::Type::BOOL, false);
  411. _insert_feature("centered_cjk_punctuation", HB_TAG('c', 'p', 'c', 't'), Variant::Type::BOOL, false);
  412. _insert_feature("capital_spacing", HB_TAG('c', 'p', 's', 'p'), Variant::Type::BOOL, false);
  413. _insert_feature("contextual_swash", HB_TAG('c', 's', 'w', 'h'), Variant::Type::INT, false);
  414. _insert_feature("cursive_positioning", HB_TAG('c', 'u', 'r', 's'), Variant::Type::INT, true);
  415. _insert_feature("character_variant_01", HB_TAG('c', 'v', '0', '1'), Variant::Type::BOOL, false);
  416. _insert_feature("character_variant_02", HB_TAG('c', 'v', '0', '2'), Variant::Type::BOOL, false);
  417. _insert_feature("character_variant_03", HB_TAG('c', 'v', '0', '3'), Variant::Type::BOOL, false);
  418. _insert_feature("character_variant_04", HB_TAG('c', 'v', '0', '4'), Variant::Type::BOOL, false);
  419. _insert_feature("character_variant_05", HB_TAG('c', 'v', '0', '5'), Variant::Type::BOOL, false);
  420. _insert_feature("character_variant_06", HB_TAG('c', 'v', '0', '6'), Variant::Type::BOOL, false);
  421. _insert_feature("character_variant_07", HB_TAG('c', 'v', '0', '7'), Variant::Type::BOOL, false);
  422. _insert_feature("character_variant_08", HB_TAG('c', 'v', '0', '8'), Variant::Type::BOOL, false);
  423. _insert_feature("character_variant_09", HB_TAG('c', 'v', '0', '9'), Variant::Type::BOOL, false);
  424. _insert_feature("character_variant_10", HB_TAG('c', 'v', '1', '0'), Variant::Type::BOOL, false);
  425. _insert_feature("character_variant_11", HB_TAG('c', 'v', '1', '1'), Variant::Type::BOOL, false);
  426. _insert_feature("character_variant_12", HB_TAG('c', 'v', '1', '2'), Variant::Type::BOOL, false);
  427. _insert_feature("character_variant_13", HB_TAG('c', 'v', '1', '3'), Variant::Type::BOOL, false);
  428. _insert_feature("character_variant_14", HB_TAG('c', 'v', '1', '4'), Variant::Type::BOOL, false);
  429. _insert_feature("character_variant_15", HB_TAG('c', 'v', '1', '5'), Variant::Type::BOOL, false);
  430. _insert_feature("character_variant_16", HB_TAG('c', 'v', '1', '6'), Variant::Type::BOOL, false);
  431. _insert_feature("character_variant_17", HB_TAG('c', 'v', '1', '7'), Variant::Type::BOOL, false);
  432. _insert_feature("character_variant_18", HB_TAG('c', 'v', '1', '8'), Variant::Type::BOOL, false);
  433. _insert_feature("character_variant_19", HB_TAG('c', 'v', '1', '9'), Variant::Type::BOOL, false);
  434. _insert_feature("character_variant_20", HB_TAG('c', 'v', '2', '0'), Variant::Type::BOOL, false);
  435. _insert_feature("character_variant_21", HB_TAG('c', 'v', '2', '1'), Variant::Type::BOOL, false);
  436. _insert_feature("character_variant_22", HB_TAG('c', 'v', '2', '2'), Variant::Type::BOOL, false);
  437. _insert_feature("character_variant_23", HB_TAG('c', 'v', '2', '3'), Variant::Type::BOOL, false);
  438. _insert_feature("character_variant_24", HB_TAG('c', 'v', '2', '4'), Variant::Type::BOOL, false);
  439. _insert_feature("character_variant_25", HB_TAG('c', 'v', '2', '5'), Variant::Type::BOOL, false);
  440. _insert_feature("character_variant_26", HB_TAG('c', 'v', '2', '6'), Variant::Type::BOOL, false);
  441. _insert_feature("character_variant_27", HB_TAG('c', 'v', '2', '7'), Variant::Type::BOOL, false);
  442. _insert_feature("character_variant_28", HB_TAG('c', 'v', '2', '8'), Variant::Type::BOOL, false);
  443. _insert_feature("character_variant_29", HB_TAG('c', 'v', '2', '9'), Variant::Type::BOOL, false);
  444. _insert_feature("character_variant_30", HB_TAG('c', 'v', '3', '0'), Variant::Type::BOOL, false);
  445. _insert_feature("character_variant_31", HB_TAG('c', 'v', '3', '1'), Variant::Type::BOOL, false);
  446. _insert_feature("character_variant_32", HB_TAG('c', 'v', '3', '2'), Variant::Type::BOOL, false);
  447. _insert_feature("character_variant_33", HB_TAG('c', 'v', '3', '3'), Variant::Type::BOOL, false);
  448. _insert_feature("character_variant_34", HB_TAG('c', 'v', '3', '4'), Variant::Type::BOOL, false);
  449. _insert_feature("character_variant_35", HB_TAG('c', 'v', '3', '5'), Variant::Type::BOOL, false);
  450. _insert_feature("character_variant_36", HB_TAG('c', 'v', '3', '6'), Variant::Type::BOOL, false);
  451. _insert_feature("character_variant_37", HB_TAG('c', 'v', '3', '7'), Variant::Type::BOOL, false);
  452. _insert_feature("character_variant_38", HB_TAG('c', 'v', '3', '8'), Variant::Type::BOOL, false);
  453. _insert_feature("character_variant_39", HB_TAG('c', 'v', '3', '9'), Variant::Type::BOOL, false);
  454. _insert_feature("character_variant_40", HB_TAG('c', 'v', '4', '0'), Variant::Type::BOOL, false);
  455. _insert_feature("character_variant_41", HB_TAG('c', 'v', '4', '1'), Variant::Type::BOOL, false);
  456. _insert_feature("character_variant_42", HB_TAG('c', 'v', '4', '2'), Variant::Type::BOOL, false);
  457. _insert_feature("character_variant_43", HB_TAG('c', 'v', '4', '3'), Variant::Type::BOOL, false);
  458. _insert_feature("character_variant_44", HB_TAG('c', 'v', '4', '4'), Variant::Type::BOOL, false);
  459. _insert_feature("character_variant_45", HB_TAG('c', 'v', '4', '5'), Variant::Type::BOOL, false);
  460. _insert_feature("character_variant_46", HB_TAG('c', 'v', '4', '6'), Variant::Type::BOOL, false);
  461. _insert_feature("character_variant_47", HB_TAG('c', 'v', '4', '7'), Variant::Type::BOOL, false);
  462. _insert_feature("character_variant_48", HB_TAG('c', 'v', '4', '8'), Variant::Type::BOOL, false);
  463. _insert_feature("character_variant_49", HB_TAG('c', 'v', '4', '9'), Variant::Type::BOOL, false);
  464. _insert_feature("character_variant_50", HB_TAG('c', 'v', '5', '0'), Variant::Type::BOOL, false);
  465. _insert_feature("character_variant_51", HB_TAG('c', 'v', '5', '1'), Variant::Type::BOOL, false);
  466. _insert_feature("character_variant_52", HB_TAG('c', 'v', '5', '2'), Variant::Type::BOOL, false);
  467. _insert_feature("character_variant_53", HB_TAG('c', 'v', '5', '3'), Variant::Type::BOOL, false);
  468. _insert_feature("character_variant_54", HB_TAG('c', 'v', '5', '4'), Variant::Type::BOOL, false);
  469. _insert_feature("character_variant_55", HB_TAG('c', 'v', '5', '5'), Variant::Type::BOOL, false);
  470. _insert_feature("character_variant_56", HB_TAG('c', 'v', '5', '6'), Variant::Type::BOOL, false);
  471. _insert_feature("character_variant_57", HB_TAG('c', 'v', '5', '7'), Variant::Type::BOOL, false);
  472. _insert_feature("character_variant_58", HB_TAG('c', 'v', '5', '8'), Variant::Type::BOOL, false);
  473. _insert_feature("character_variant_59", HB_TAG('c', 'v', '5', '9'), Variant::Type::BOOL, false);
  474. _insert_feature("character_variant_60", HB_TAG('c', 'v', '6', '0'), Variant::Type::BOOL, false);
  475. _insert_feature("character_variant_61", HB_TAG('c', 'v', '6', '1'), Variant::Type::BOOL, false);
  476. _insert_feature("character_variant_62", HB_TAG('c', 'v', '6', '2'), Variant::Type::BOOL, false);
  477. _insert_feature("character_variant_63", HB_TAG('c', 'v', '6', '3'), Variant::Type::BOOL, false);
  478. _insert_feature("character_variant_64", HB_TAG('c', 'v', '6', '4'), Variant::Type::BOOL, false);
  479. _insert_feature("character_variant_65", HB_TAG('c', 'v', '6', '5'), Variant::Type::BOOL, false);
  480. _insert_feature("character_variant_66", HB_TAG('c', 'v', '6', '6'), Variant::Type::BOOL, false);
  481. _insert_feature("character_variant_67", HB_TAG('c', 'v', '6', '7'), Variant::Type::BOOL, false);
  482. _insert_feature("character_variant_68", HB_TAG('c', 'v', '6', '8'), Variant::Type::BOOL, false);
  483. _insert_feature("character_variant_69", HB_TAG('c', 'v', '6', '9'), Variant::Type::BOOL, false);
  484. _insert_feature("character_variant_70", HB_TAG('c', 'v', '7', '0'), Variant::Type::BOOL, false);
  485. _insert_feature("character_variant_71", HB_TAG('c', 'v', '7', '1'), Variant::Type::BOOL, false);
  486. _insert_feature("character_variant_72", HB_TAG('c', 'v', '7', '2'), Variant::Type::BOOL, false);
  487. _insert_feature("character_variant_73", HB_TAG('c', 'v', '7', '3'), Variant::Type::BOOL, false);
  488. _insert_feature("character_variant_74", HB_TAG('c', 'v', '7', '4'), Variant::Type::BOOL, false);
  489. _insert_feature("character_variant_75", HB_TAG('c', 'v', '7', '5'), Variant::Type::BOOL, false);
  490. _insert_feature("character_variant_76", HB_TAG('c', 'v', '7', '6'), Variant::Type::BOOL, false);
  491. _insert_feature("character_variant_77", HB_TAG('c', 'v', '7', '7'), Variant::Type::BOOL, false);
  492. _insert_feature("character_variant_78", HB_TAG('c', 'v', '7', '8'), Variant::Type::BOOL, false);
  493. _insert_feature("character_variant_79", HB_TAG('c', 'v', '7', '9'), Variant::Type::BOOL, false);
  494. _insert_feature("character_variant_80", HB_TAG('c', 'v', '8', '0'), Variant::Type::BOOL, false);
  495. _insert_feature("character_variant_81", HB_TAG('c', 'v', '8', '1'), Variant::Type::BOOL, false);
  496. _insert_feature("character_variant_82", HB_TAG('c', 'v', '8', '2'), Variant::Type::BOOL, false);
  497. _insert_feature("character_variant_83", HB_TAG('c', 'v', '8', '3'), Variant::Type::BOOL, false);
  498. _insert_feature("character_variant_84", HB_TAG('c', 'v', '8', '4'), Variant::Type::BOOL, false);
  499. _insert_feature("character_variant_85", HB_TAG('c', 'v', '8', '5'), Variant::Type::BOOL, false);
  500. _insert_feature("character_variant_86", HB_TAG('c', 'v', '8', '6'), Variant::Type::BOOL, false);
  501. _insert_feature("character_variant_87", HB_TAG('c', 'v', '8', '7'), Variant::Type::BOOL, false);
  502. _insert_feature("character_variant_88", HB_TAG('c', 'v', '8', '8'), Variant::Type::BOOL, false);
  503. _insert_feature("character_variant_89", HB_TAG('c', 'v', '8', '9'), Variant::Type::BOOL, false);
  504. _insert_feature("character_variant_90", HB_TAG('c', 'v', '9', '0'), Variant::Type::BOOL, false);
  505. _insert_feature("character_variant_91", HB_TAG('c', 'v', '9', '1'), Variant::Type::BOOL, false);
  506. _insert_feature("character_variant_92", HB_TAG('c', 'v', '9', '2'), Variant::Type::BOOL, false);
  507. _insert_feature("character_variant_93", HB_TAG('c', 'v', '9', '3'), Variant::Type::BOOL, false);
  508. _insert_feature("character_variant_94", HB_TAG('c', 'v', '9', '4'), Variant::Type::BOOL, false);
  509. _insert_feature("character_variant_95", HB_TAG('c', 'v', '9', '5'), Variant::Type::BOOL, false);
  510. _insert_feature("character_variant_96", HB_TAG('c', 'v', '9', '6'), Variant::Type::BOOL, false);
  511. _insert_feature("character_variant_97", HB_TAG('c', 'v', '9', '7'), Variant::Type::BOOL, false);
  512. _insert_feature("character_variant_98", HB_TAG('c', 'v', '9', '8'), Variant::Type::BOOL, false);
  513. _insert_feature("character_variant_99", HB_TAG('c', 'v', '9', '9'), Variant::Type::BOOL, false);
  514. _insert_feature("petite_capitals_from_capitals", HB_TAG('c', '2', 'p', 'c'), Variant::Type::BOOL, false);
  515. _insert_feature("small_capitals_from_capitals", HB_TAG('c', '2', 's', 'c'), Variant::Type::BOOL, false);
  516. _insert_feature("distances", HB_TAG('d', 'i', 's', 't'), Variant::Type::INT, true);
  517. _insert_feature("discretionary_ligatures", HB_TAG('d', 'l', 'i', 'g'), Variant::Type::BOOL, false);
  518. _insert_feature("denominators", HB_TAG('d', 'n', 'o', 'm'), Variant::Type::BOOL, false);
  519. _insert_feature("dotless_forms", HB_TAG('d', 't', 'l', 's'), Variant::Type::INT, true);
  520. _insert_feature("expert_forms", HB_TAG('e', 'x', 'p', 't'), Variant::Type::BOOL, true);
  521. _insert_feature("final_glyph_on_line_alternates", HB_TAG('f', 'a', 'l', 't'), Variant::Type::INT, false);
  522. _insert_feature("terminal_forms_2", HB_TAG('f', 'i', 'n', '2'), Variant::Type::INT, true);
  523. _insert_feature("terminal_forms_3", HB_TAG('f', 'i', 'n', '3'), Variant::Type::INT, true);
  524. _insert_feature("terminal_forms", HB_TAG('f', 'i', 'n', 'a'), Variant::Type::INT, true);
  525. _insert_feature("flattened_accent_forms", HB_TAG('f', 'l', 'a', 'c'), Variant::Type::INT, true);
  526. _insert_feature("fractions", HB_TAG('f', 'r', 'a', 'c'), Variant::Type::BOOL, false);
  527. _insert_feature("full_widths", HB_TAG('f', 'w', 'i', 'd'), Variant::Type::BOOL, false);
  528. _insert_feature("half_forms", HB_TAG('h', 'a', 'l', 'f'), Variant::Type::INT, true);
  529. _insert_feature("halant_forms", HB_TAG('h', 'a', 'l', 'n'), Variant::Type::INT, true);
  530. _insert_feature("alternate_half_widths", HB_TAG('h', 'a', 'l', 't'), Variant::Type::BOOL, false);
  531. _insert_feature("historical_forms", HB_TAG('h', 'i', 's', 't'), Variant::Type::INT, false);
  532. _insert_feature("horizontal_kana_alternates", HB_TAG('h', 'k', 'n', 'a'), Variant::Type::BOOL, false);
  533. _insert_feature("historical_ligatures", HB_TAG('h', 'l', 'i', 'g'), Variant::Type::BOOL, false);
  534. _insert_feature("hangul", HB_TAG('h', 'n', 'g', 'l'), Variant::Type::INT, false);
  535. _insert_feature("hojo_kanji_forms", HB_TAG('h', 'o', 'j', 'o'), Variant::Type::INT, false);
  536. _insert_feature("half_widths", HB_TAG('h', 'w', 'i', 'd'), Variant::Type::BOOL, false);
  537. _insert_feature("initial_forms", HB_TAG('i', 'n', 'i', 't'), Variant::Type::INT, true);
  538. _insert_feature("isolated_forms", HB_TAG('i', 's', 'o', 'l'), Variant::Type::INT, true);
  539. _insert_feature("italics", HB_TAG('i', 't', 'a', 'l'), Variant::Type::INT, false);
  540. _insert_feature("justification_alternates", HB_TAG('j', 'a', 'l', 't'), Variant::Type::INT, false);
  541. _insert_feature("jis78_forms", HB_TAG('j', 'p', '7', '8'), Variant::Type::INT, false);
  542. _insert_feature("jis83_forms", HB_TAG('j', 'p', '8', '3'), Variant::Type::INT, false);
  543. _insert_feature("jis90_forms", HB_TAG('j', 'p', '9', '0'), Variant::Type::INT, false);
  544. _insert_feature("jis2004_forms", HB_TAG('j', 'p', '0', '4'), Variant::Type::INT, false);
  545. _insert_feature("kerning", HB_TAG('k', 'e', 'r', 'n'), Variant::Type::BOOL, false);
  546. _insert_feature("left_bounds", HB_TAG('l', 'f', 'b', 'd'), Variant::Type::INT, false);
  547. _insert_feature("standard_ligatures", HB_TAG('l', 'i', 'g', 'a'), Variant::Type::BOOL, false);
  548. _insert_feature("leading_jamo_forms", HB_TAG('l', 'j', 'm', 'o'), Variant::Type::INT, true);
  549. _insert_feature("lining_figures", HB_TAG('l', 'n', 'u', 'm'), Variant::Type::INT, false);
  550. _insert_feature("localized_forms", HB_TAG('l', 'o', 'c', 'l'), Variant::Type::INT, true);
  551. _insert_feature("left_to_right_alternates", HB_TAG('l', 't', 'r', 'a'), Variant::Type::INT, true);
  552. _insert_feature("left_to_right_mirrored_forms", HB_TAG('l', 't', 'r', 'm'), Variant::Type::INT, true);
  553. _insert_feature("mark_positioning", HB_TAG('m', 'a', 'r', 'k'), Variant::Type::INT, true);
  554. _insert_feature("medial_forms_2", HB_TAG('m', 'e', 'd', '2'), Variant::Type::INT, true);
  555. _insert_feature("medial_forms", HB_TAG('m', 'e', 'd', 'i'), Variant::Type::INT, true);
  556. _insert_feature("mathematical_greek", HB_TAG('m', 'g', 'r', 'k'), Variant::Type::BOOL, false);
  557. _insert_feature("mark_to_mark_positioning", HB_TAG('m', 'k', 'm', 'k'), Variant::Type::INT, true);
  558. _insert_feature("mark_positioning_via_substitution", HB_TAG('m', 's', 'e', 't'), Variant::Type::INT, true);
  559. _insert_feature("alternate_annotation_forms", HB_TAG('n', 'a', 'l', 't'), Variant::Type::INT, false);
  560. _insert_feature("nlc_kanji_forms", HB_TAG('n', 'l', 'c', 'k'), Variant::Type::INT, false);
  561. _insert_feature("nukta_forms", HB_TAG('n', 'u', 'k', 't'), Variant::Type::INT, true);
  562. _insert_feature("numerators", HB_TAG('n', 'u', 'm', 'r'), Variant::Type::BOOL, false);
  563. _insert_feature("oldstyle_figures", HB_TAG('o', 'n', 'u', 'm'), Variant::Type::INT, false);
  564. _insert_feature("optical_bounds", HB_TAG('o', 'p', 'b', 'd'), Variant::Type::INT, true);
  565. _insert_feature("ordinals", HB_TAG('o', 'r', 'd', 'n'), Variant::Type::BOOL, false);
  566. _insert_feature("ornaments", HB_TAG('o', 'r', 'n', 'm'), Variant::Type::INT, false);
  567. _insert_feature("proportional_alternate_widths", HB_TAG('p', 'a', 'l', 't'), Variant::Type::BOOL, false);
  568. _insert_feature("petite_capitals", HB_TAG('p', 'c', 'a', 'p'), Variant::Type::BOOL, false);
  569. _insert_feature("proportional_kana", HB_TAG('p', 'k', 'n', 'a'), Variant::Type::BOOL, false);
  570. _insert_feature("proportional_figures", HB_TAG('p', 'n', 'u', 'm'), Variant::Type::BOOL, false);
  571. _insert_feature("pre_base_forms", HB_TAG('p', 'r', 'e', 'f'), Variant::Type::INT, true);
  572. _insert_feature("pre_base_substitutions", HB_TAG('p', 'r', 'e', 's'), Variant::Type::INT, true);
  573. _insert_feature("post_base_forms", HB_TAG('p', 's', 't', 'f'), Variant::Type::INT, true);
  574. _insert_feature("post_base_substitutions", HB_TAG('p', 's', 't', 's'), Variant::Type::INT, true);
  575. _insert_feature("proportional_widths", HB_TAG('p', 'w', 'i', 'd'), Variant::Type::BOOL, false);
  576. _insert_feature("quarter_widths", HB_TAG('q', 'w', 'i', 'd'), Variant::Type::BOOL, false);
  577. _insert_feature("randomize", HB_TAG('r', 'a', 'n', 'd'), Variant::Type::INT, false);
  578. _insert_feature("required_contextual_alternates", HB_TAG('r', 'c', 'l', 't'), Variant::Type::BOOL, true);
  579. _insert_feature("rakar_forms", HB_TAG('r', 'k', 'r', 'f'), Variant::Type::INT, true);
  580. _insert_feature("required_ligatures", HB_TAG('r', 'l', 'i', 'g'), Variant::Type::BOOL, true);
  581. _insert_feature("reph_forms", HB_TAG('r', 'p', 'h', 'f'), Variant::Type::INT, true);
  582. _insert_feature("right_bounds", HB_TAG('r', 't', 'b', 'd'), Variant::Type::INT, false);
  583. _insert_feature("right_to_left_alternates", HB_TAG('r', 't', 'l', 'a'), Variant::Type::INT, true);
  584. _insert_feature("right_to_left_mirrored_forms", HB_TAG('r', 't', 'l', 'm'), Variant::Type::INT, true);
  585. _insert_feature("ruby_notation_forms", HB_TAG('r', 'u', 'b', 'y'), Variant::Type::INT, false);
  586. _insert_feature("required_variation_alternates", HB_TAG('r', 'v', 'r', 'n'), Variant::Type::INT, true);
  587. _insert_feature("stylistic_alternates", HB_TAG('s', 'a', 'l', 't'), Variant::Type::INT, false);
  588. _insert_feature("scientific_inferiors", HB_TAG('s', 'i', 'n', 'f'), Variant::Type::BOOL, false);
  589. _insert_feature("optical_size", HB_TAG('s', 'i', 'z', 'e'), Variant::Type::INT, false);
  590. _insert_feature("small_capitals", HB_TAG('s', 'm', 'c', 'p'), Variant::Type::BOOL, false);
  591. _insert_feature("simplified_forms", HB_TAG('s', 'm', 'p', 'l'), Variant::Type::INT, false);
  592. _insert_feature("stylistic_set_01", HB_TAG('s', 's', '0', '1'), Variant::Type::BOOL, false);
  593. _insert_feature("stylistic_set_02", HB_TAG('s', 's', '0', '2'), Variant::Type::BOOL, false);
  594. _insert_feature("stylistic_set_03", HB_TAG('s', 's', '0', '3'), Variant::Type::BOOL, false);
  595. _insert_feature("stylistic_set_04", HB_TAG('s', 's', '0', '4'), Variant::Type::BOOL, false);
  596. _insert_feature("stylistic_set_05", HB_TAG('s', 's', '0', '5'), Variant::Type::BOOL, false);
  597. _insert_feature("stylistic_set_06", HB_TAG('s', 's', '0', '6'), Variant::Type::BOOL, false);
  598. _insert_feature("stylistic_set_07", HB_TAG('s', 's', '0', '7'), Variant::Type::BOOL, false);
  599. _insert_feature("stylistic_set_08", HB_TAG('s', 's', '0', '8'), Variant::Type::BOOL, false);
  600. _insert_feature("stylistic_set_09", HB_TAG('s', 's', '0', '9'), Variant::Type::BOOL, false);
  601. _insert_feature("stylistic_set_10", HB_TAG('s', 's', '1', '0'), Variant::Type::BOOL, false);
  602. _insert_feature("stylistic_set_11", HB_TAG('s', 's', '1', '1'), Variant::Type::BOOL, false);
  603. _insert_feature("stylistic_set_12", HB_TAG('s', 's', '1', '2'), Variant::Type::BOOL, false);
  604. _insert_feature("stylistic_set_13", HB_TAG('s', 's', '1', '3'), Variant::Type::BOOL, false);
  605. _insert_feature("stylistic_set_14", HB_TAG('s', 's', '1', '4'), Variant::Type::BOOL, false);
  606. _insert_feature("stylistic_set_15", HB_TAG('s', 's', '1', '5'), Variant::Type::BOOL, false);
  607. _insert_feature("stylistic_set_16", HB_TAG('s', 's', '1', '6'), Variant::Type::BOOL, false);
  608. _insert_feature("stylistic_set_17", HB_TAG('s', 's', '1', '7'), Variant::Type::BOOL, false);
  609. _insert_feature("stylistic_set_18", HB_TAG('s', 's', '1', '8'), Variant::Type::BOOL, false);
  610. _insert_feature("stylistic_set_19", HB_TAG('s', 's', '1', '9'), Variant::Type::BOOL, false);
  611. _insert_feature("stylistic_set_20", HB_TAG('s', 's', '2', '0'), Variant::Type::BOOL, false);
  612. _insert_feature("math_script_style_alternates", HB_TAG('s', 's', 't', 'y'), Variant::Type::INT, true);
  613. _insert_feature("stretching_glyph_decomposition", HB_TAG('s', 't', 'c', 'h'), Variant::Type::INT, true);
  614. _insert_feature("subscript", HB_TAG('s', 'u', 'b', 's'), Variant::Type::BOOL, false);
  615. _insert_feature("superscript", HB_TAG('s', 'u', 'p', 's'), Variant::Type::BOOL, false);
  616. _insert_feature("swash", HB_TAG('s', 'w', 's', 'h'), Variant::Type::INT, false);
  617. _insert_feature("titling", HB_TAG('t', 'i', 't', 'l'), Variant::Type::BOOL, false);
  618. _insert_feature("trailing_jamo_forms", HB_TAG('t', 'j', 'm', 'o'), Variant::Type::INT, true);
  619. _insert_feature("traditional_name_forms", HB_TAG('t', 'n', 'a', 'm'), Variant::Type::INT, false);
  620. _insert_feature("tabular_figures", HB_TAG('t', 'n', 'u', 'm'), Variant::Type::BOOL, false);
  621. _insert_feature("traditional_forms", HB_TAG('t', 'r', 'a', 'd'), Variant::Type::INT, false);
  622. _insert_feature("third_widths", HB_TAG('t', 'w', 'i', 'd'), Variant::Type::BOOL, false);
  623. _insert_feature("unicase", HB_TAG('u', 'n', 'i', 'c'), Variant::Type::BOOL, false);
  624. _insert_feature("alternate_vertical_metrics", HB_TAG('v', 'a', 'l', 't'), Variant::Type::INT, false);
  625. _insert_feature("vattu_variants", HB_TAG('v', 'a', 't', 'u'), Variant::Type::INT, true);
  626. _insert_feature("vertical_contextual_half_width_spacing", HB_TAG('v', 'c', 'h', 'w'), Variant::Type::BOOL, false);
  627. _insert_feature("vertical_alternates", HB_TAG('v', 'e', 'r', 't'), Variant::Type::INT, false);
  628. _insert_feature("alternate_vertical_half_metrics", HB_TAG('v', 'h', 'a', 'l'), Variant::Type::BOOL, false);
  629. _insert_feature("vowel_jamo_forms", HB_TAG('v', 'j', 'm', 'o'), Variant::Type::INT, true);
  630. _insert_feature("vertical_kana_alternates", HB_TAG('v', 'k', 'n', 'a'), Variant::Type::INT, false);
  631. _insert_feature("vertical_kerning", HB_TAG('v', 'k', 'r', 'n'), Variant::Type::BOOL, false);
  632. _insert_feature("proportional_alternate_vertical_metrics", HB_TAG('v', 'p', 'a', 'l'), Variant::Type::BOOL, false);
  633. _insert_feature("vertical_alternates_and_rotation", HB_TAG('v', 'r', 't', '2'), Variant::Type::INT, false);
  634. _insert_feature("vertical_alternates_for_rotation", HB_TAG('v', 'r', 't', 'r'), Variant::Type::INT, false);
  635. _insert_feature("slashed_zero", HB_TAG('z', 'e', 'r', 'o'), Variant::Type::BOOL, false);
  636. // Registered OpenType variation tag.
  637. _insert_feature("italic", HB_TAG('i', 't', 'a', 'l'), Variant::Type::INT, false);
  638. _insert_feature("optical_size", HB_TAG('o', 'p', 's', 'z'), Variant::Type::INT, false);
  639. _insert_feature("slant", HB_TAG('s', 'l', 'n', 't'), Variant::Type::INT, false);
  640. _insert_feature("width", HB_TAG('w', 'd', 't', 'h'), Variant::Type::INT, false);
  641. _insert_feature("weight", HB_TAG('w', 'g', 'h', 't'), Variant::Type::INT, false);
  642. }
  643. int64_t TextServerAdvanced::name_to_tag(const String &p_name) const {
  644. if (feature_sets.has(p_name)) {
  645. return feature_sets[p_name];
  646. }
  647. // No readable name, use tag string.
  648. return hb_tag_from_string(p_name.replace("custom_", "").ascii().get_data(), -1);
  649. }
  650. Variant::Type TextServerAdvanced::_get_tag_type(int64_t p_tag) const {
  651. if (feature_sets_inv.has(p_tag)) {
  652. return feature_sets_inv[p_tag].vtype;
  653. }
  654. return Variant::Type::INT;
  655. }
  656. bool TextServerAdvanced::_get_tag_hidden(int64_t p_tag) const {
  657. if (feature_sets_inv.has(p_tag)) {
  658. return feature_sets_inv[p_tag].hidden;
  659. }
  660. return false;
  661. }
  662. String TextServerAdvanced::tag_to_name(int64_t p_tag) const {
  663. if (feature_sets_inv.has(p_tag)) {
  664. return feature_sets_inv[p_tag].name;
  665. }
  666. // No readable name, use tag string.
  667. char name[5];
  668. memset(name, 0, 5);
  669. hb_tag_to_string(p_tag, name);
  670. return String("custom_") + String(name);
  671. }
  672. /*************************************************************************/
  673. /* Font Glyph Rendering */
  674. /*************************************************************************/
  675. _FORCE_INLINE_ TextServerAdvanced::FontTexturePosition TextServerAdvanced::find_texture_pos_for_glyph(FontForSizeAdvanced *p_data, int p_color_size, Image::Format p_image_format, int p_width, int p_height, bool p_msdf) const {
  676. FontTexturePosition ret;
  677. ret.index = -1;
  678. int mw = p_width;
  679. int mh = p_height;
  680. for (int i = 0; i < p_data->textures.size(); i++) {
  681. const FontTexture &ct = p_data->textures[i];
  682. if (mw > ct.texture_w || mh > ct.texture_h) { // Too big for this texture.
  683. continue;
  684. }
  685. if (ct.offsets.size() < ct.texture_w) {
  686. continue;
  687. }
  688. ret.y = 0x7fffffff;
  689. ret.x = 0;
  690. for (int j = 0; j < ct.texture_w - mw; j++) {
  691. int max_y = 0;
  692. for (int k = j; k < j + mw; k++) {
  693. int y = ct.offsets[k];
  694. if (y > max_y) {
  695. max_y = y;
  696. }
  697. }
  698. if (max_y < ret.y) {
  699. ret.y = max_y;
  700. ret.x = j;
  701. }
  702. }
  703. if (ret.y == 0x7fffffff || ret.y + mh > ct.texture_h) {
  704. continue; // Fail, could not fit it here.
  705. }
  706. ret.index = i;
  707. break;
  708. }
  709. if (ret.index == -1) {
  710. // Could not find texture to fit, create one.
  711. ret.x = 0;
  712. ret.y = 0;
  713. int texsize = MAX(p_data->size.x * p_data->oversampling * 8, 256);
  714. #ifdef GDEXTENSION
  715. texsize = Math::next_power_of_2(texsize);
  716. #else
  717. texsize = next_power_of_2(texsize);
  718. #endif
  719. if (p_msdf) {
  720. texsize = MIN(texsize, 2048);
  721. } else {
  722. texsize = MIN(texsize, 1024);
  723. }
  724. if (mw > texsize) { // Special case, adapt to it?
  725. #ifdef GDEXTENSION
  726. texsize = Math::next_power_of_2(mw);
  727. #else
  728. texsize = next_power_of_2(mw);
  729. #endif
  730. }
  731. if (mh > texsize) { // Special case, adapt to it?
  732. #ifdef GDEXTENSION
  733. texsize = Math::next_power_of_2(mh);
  734. #else
  735. texsize = next_power_of_2(mh);
  736. #endif
  737. }
  738. FontTexture tex;
  739. tex.texture_w = texsize;
  740. tex.texture_h = texsize;
  741. tex.format = p_image_format;
  742. tex.imgdata.resize(texsize * texsize * p_color_size);
  743. {
  744. // Zero texture.
  745. uint8_t *w = tex.imgdata.ptrw();
  746. ERR_FAIL_COND_V(texsize * texsize * p_color_size > tex.imgdata.size(), ret);
  747. // Initialize the texture to all-white pixels to prevent artifacts when the
  748. // font is displayed at a non-default scale with filtering enabled.
  749. if (p_color_size == 2) {
  750. for (int i = 0; i < texsize * texsize * p_color_size; i += 2) { // FORMAT_LA8, BW font.
  751. w[i + 0] = 255;
  752. w[i + 1] = 0;
  753. }
  754. } else if (p_color_size == 4) {
  755. for (int i = 0; i < texsize * texsize * p_color_size; i += 4) { // FORMAT_RGBA8, Color font, Multichannel(+True) SDF.
  756. w[i + 0] = 255;
  757. w[i + 1] = 255;
  758. w[i + 2] = 255;
  759. w[i + 3] = 0;
  760. }
  761. } else {
  762. ERR_FAIL_V(ret);
  763. }
  764. }
  765. tex.offsets.resize(texsize);
  766. int32_t *offw = tex.offsets.ptrw();
  767. for (int i = 0; i < texsize; i++) { // Zero offsets.
  768. offw[i] = 0;
  769. }
  770. p_data->textures.push_back(tex);
  771. ret.index = p_data->textures.size() - 1;
  772. }
  773. return ret;
  774. }
  775. #ifdef MODULE_MSDFGEN_ENABLED
  776. struct MSContext {
  777. msdfgen::Point2 position;
  778. msdfgen::Shape *shape = nullptr;
  779. msdfgen::Contour *contour = nullptr;
  780. };
  781. class DistancePixelConversion {
  782. double invRange;
  783. public:
  784. _FORCE_INLINE_ explicit DistancePixelConversion(double range) :
  785. invRange(1 / range) {}
  786. _FORCE_INLINE_ void operator()(float *pixels, const msdfgen::MultiAndTrueDistance &distance) const {
  787. pixels[0] = float(invRange * distance.r + .5);
  788. pixels[1] = float(invRange * distance.g + .5);
  789. pixels[2] = float(invRange * distance.b + .5);
  790. pixels[3] = float(invRange * distance.a + .5);
  791. }
  792. };
  793. struct MSDFThreadData {
  794. msdfgen::Bitmap<float, 4> *output;
  795. msdfgen::Shape *shape;
  796. msdfgen::Projection *projection;
  797. DistancePixelConversion *distancePixelConversion;
  798. };
  799. static msdfgen::Point2 ft_point2(const FT_Vector &vector) {
  800. return msdfgen::Point2(vector.x / 60.0f, vector.y / 60.0f);
  801. }
  802. static int ft_move_to(const FT_Vector *to, void *user) {
  803. MSContext *context = static_cast<MSContext *>(user);
  804. if (!(context->contour && context->contour->edges.empty())) {
  805. context->contour = &context->shape->addContour();
  806. }
  807. context->position = ft_point2(*to);
  808. return 0;
  809. }
  810. static int ft_line_to(const FT_Vector *to, void *user) {
  811. MSContext *context = static_cast<MSContext *>(user);
  812. msdfgen::Point2 endpoint = ft_point2(*to);
  813. if (endpoint != context->position) {
  814. context->contour->addEdge(new msdfgen::LinearSegment(context->position, endpoint));
  815. context->position = endpoint;
  816. }
  817. return 0;
  818. }
  819. static int ft_conic_to(const FT_Vector *control, const FT_Vector *to, void *user) {
  820. MSContext *context = static_cast<MSContext *>(user);
  821. context->contour->addEdge(new msdfgen::QuadraticSegment(context->position, ft_point2(*control), ft_point2(*to)));
  822. context->position = ft_point2(*to);
  823. return 0;
  824. }
  825. static int ft_cubic_to(const FT_Vector *control1, const FT_Vector *control2, const FT_Vector *to, void *user) {
  826. MSContext *context = static_cast<MSContext *>(user);
  827. context->contour->addEdge(new msdfgen::CubicSegment(context->position, ft_point2(*control1), ft_point2(*control2), ft_point2(*to)));
  828. context->position = ft_point2(*to);
  829. return 0;
  830. }
  831. void TextServerAdvanced::_generateMTSDF_threaded(uint32_t y, void *p_td) const {
  832. MSDFThreadData *td = static_cast<MSDFThreadData *>(p_td);
  833. msdfgen::ShapeDistanceFinder<msdfgen::OverlappingContourCombiner<msdfgen::MultiAndTrueDistanceSelector>> distanceFinder(*td->shape);
  834. int row = td->shape->inverseYAxis ? td->output->height() - y - 1 : y;
  835. for (int col = 0; col < td->output->width(); ++col) {
  836. int x = (y % 2) ? td->output->width() - col - 1 : col;
  837. msdfgen::Point2 p = td->projection->unproject(msdfgen::Point2(x + .5, y + .5));
  838. msdfgen::MultiAndTrueDistance distance = distanceFinder.distance(p);
  839. td->distancePixelConversion->operator()(td->output->operator()(x, row), distance);
  840. }
  841. }
  842. _FORCE_INLINE_ TextServerAdvanced::FontGlyph TextServerAdvanced::rasterize_msdf(FontAdvanced *p_font_data, FontForSizeAdvanced *p_data, int p_pixel_range, int p_rect_margin, FT_Outline *outline, const Vector2 &advance) const {
  843. msdfgen::Shape shape;
  844. shape.contours.clear();
  845. shape.inverseYAxis = false;
  846. MSContext context = {};
  847. context.shape = &shape;
  848. FT_Outline_Funcs ft_functions;
  849. ft_functions.move_to = &ft_move_to;
  850. ft_functions.line_to = &ft_line_to;
  851. ft_functions.conic_to = &ft_conic_to;
  852. ft_functions.cubic_to = &ft_cubic_to;
  853. ft_functions.shift = 0;
  854. ft_functions.delta = 0;
  855. int error = FT_Outline_Decompose(outline, &ft_functions, &context);
  856. ERR_FAIL_COND_V_MSG(error, FontGlyph(), "FreeType: Outline decomposition error: '" + String(FT_Error_String(error)) + "'.");
  857. if (!shape.contours.empty() && shape.contours.back().edges.empty()) {
  858. shape.contours.pop_back();
  859. }
  860. if (FT_Outline_Get_Orientation(outline) == 1) {
  861. for (int i = 0; i < (int)shape.contours.size(); ++i) {
  862. shape.contours[i].reverse();
  863. }
  864. }
  865. shape.inverseYAxis = true;
  866. shape.normalize();
  867. msdfgen::Shape::Bounds bounds = shape.getBounds(p_pixel_range);
  868. FontGlyph chr;
  869. chr.found = true;
  870. chr.advance = advance;
  871. if (shape.validate() && shape.contours.size() > 0) {
  872. int w = (bounds.r - bounds.l);
  873. int h = (bounds.t - bounds.b);
  874. int mw = w + p_rect_margin * 4;
  875. int mh = h + p_rect_margin * 4;
  876. ERR_FAIL_COND_V(mw > 4096, FontGlyph());
  877. ERR_FAIL_COND_V(mh > 4096, FontGlyph());
  878. FontTexturePosition tex_pos = find_texture_pos_for_glyph(p_data, 4, Image::FORMAT_RGBA8, mw, mh, true);
  879. ERR_FAIL_COND_V(tex_pos.index < 0, FontGlyph());
  880. FontTexture &tex = p_data->textures.write[tex_pos.index];
  881. edgeColoringSimple(shape, 3.0); // Max. angle.
  882. msdfgen::Bitmap<float, 4> image(w, h); // Texture size.
  883. DistancePixelConversion distancePixelConversion(p_pixel_range);
  884. msdfgen::Projection projection(msdfgen::Vector2(1.0, 1.0), msdfgen::Vector2(-bounds.l, -bounds.b));
  885. msdfgen::MSDFGeneratorConfig config(true, msdfgen::ErrorCorrectionConfig());
  886. MSDFThreadData td;
  887. td.output = &image;
  888. td.shape = &shape;
  889. td.projection = &projection;
  890. td.distancePixelConversion = &distancePixelConversion;
  891. WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_template_group_task(this, &TextServerAdvanced::_generateMTSDF_threaded, &td, h, -1, true, SNAME("FontServerRasterizeMSDF"));
  892. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
  893. msdfgen::msdfErrorCorrection(image, shape, projection, p_pixel_range, config);
  894. {
  895. uint8_t *wr = tex.imgdata.ptrw();
  896. for (int i = 0; i < h; i++) {
  897. for (int j = 0; j < w; j++) {
  898. int ofs = ((i + tex_pos.y + p_rect_margin * 2) * tex.texture_w + j + tex_pos.x + p_rect_margin * 2) * 4;
  899. ERR_FAIL_COND_V(ofs >= tex.imgdata.size(), FontGlyph());
  900. wr[ofs + 0] = (uint8_t)(CLAMP(image(j, i)[0] * 256.f, 0.f, 255.f));
  901. wr[ofs + 1] = (uint8_t)(CLAMP(image(j, i)[1] * 256.f, 0.f, 255.f));
  902. wr[ofs + 2] = (uint8_t)(CLAMP(image(j, i)[2] * 256.f, 0.f, 255.f));
  903. wr[ofs + 3] = (uint8_t)(CLAMP(image(j, i)[3] * 256.f, 0.f, 255.f));
  904. }
  905. }
  906. }
  907. tex.dirty = true;
  908. // Update height array.
  909. int32_t *offw = tex.offsets.ptrw();
  910. for (int k = tex_pos.x; k < tex_pos.x + mw; k++) {
  911. offw[k] = tex_pos.y + mh;
  912. }
  913. chr.texture_idx = tex_pos.index;
  914. chr.uv_rect = Rect2(tex_pos.x + p_rect_margin, tex_pos.y + p_rect_margin, w + p_rect_margin * 2, h + p_rect_margin * 2);
  915. chr.rect.position = Vector2(bounds.l - p_rect_margin, -bounds.t - p_rect_margin);
  916. chr.rect.size = chr.uv_rect.size;
  917. }
  918. return chr;
  919. }
  920. #endif
  921. #ifdef MODULE_FREETYPE_ENABLED
  922. _FORCE_INLINE_ TextServerAdvanced::FontGlyph TextServerAdvanced::rasterize_bitmap(FontForSizeAdvanced *p_data, int p_rect_margin, FT_Bitmap bitmap, int yofs, int xofs, const Vector2 &advance) const {
  923. int w = bitmap.width;
  924. int h = bitmap.rows;
  925. int mw = w + p_rect_margin * 4;
  926. int mh = h + p_rect_margin * 4;
  927. ERR_FAIL_COND_V(mw > 4096, FontGlyph());
  928. ERR_FAIL_COND_V(mh > 4096, FontGlyph());
  929. int color_size = bitmap.pixel_mode == FT_PIXEL_MODE_BGRA ? 4 : 2;
  930. Image::Format require_format = color_size == 4 ? Image::FORMAT_RGBA8 : Image::FORMAT_LA8;
  931. FontTexturePosition tex_pos = find_texture_pos_for_glyph(p_data, color_size, require_format, mw, mh, false);
  932. ERR_FAIL_COND_V(tex_pos.index < 0, FontGlyph());
  933. // Fit character in char texture.
  934. FontTexture &tex = p_data->textures.write[tex_pos.index];
  935. {
  936. uint8_t *wr = tex.imgdata.ptrw();
  937. for (int i = 0; i < h; i++) {
  938. for (int j = 0; j < w; j++) {
  939. int ofs = ((i + tex_pos.y + p_rect_margin * 2) * tex.texture_w + j + tex_pos.x + p_rect_margin * 2) * color_size;
  940. ERR_FAIL_COND_V(ofs >= tex.imgdata.size(), FontGlyph());
  941. switch (bitmap.pixel_mode) {
  942. case FT_PIXEL_MODE_MONO: {
  943. int byte = i * bitmap.pitch + (j >> 3);
  944. int bit = 1 << (7 - (j % 8));
  945. wr[ofs + 0] = 255; // grayscale as 1
  946. wr[ofs + 1] = (bitmap.buffer[byte] & bit) ? 255 : 0;
  947. } break;
  948. case FT_PIXEL_MODE_GRAY:
  949. wr[ofs + 0] = 255; // grayscale as 1
  950. wr[ofs + 1] = bitmap.buffer[i * bitmap.pitch + j];
  951. break;
  952. case FT_PIXEL_MODE_BGRA: {
  953. int ofs_color = i * bitmap.pitch + (j << 2);
  954. wr[ofs + 2] = bitmap.buffer[ofs_color + 0];
  955. wr[ofs + 1] = bitmap.buffer[ofs_color + 1];
  956. wr[ofs + 0] = bitmap.buffer[ofs_color + 2];
  957. wr[ofs + 3] = bitmap.buffer[ofs_color + 3];
  958. } break;
  959. default:
  960. ERR_FAIL_V_MSG(FontGlyph(), "Font uses unsupported pixel format: " + String::num_int64(bitmap.pixel_mode) + ".");
  961. break;
  962. }
  963. }
  964. }
  965. }
  966. tex.dirty = true;
  967. // Update height array.
  968. int32_t *offw = tex.offsets.ptrw();
  969. for (int k = tex_pos.x; k < tex_pos.x + mw; k++) {
  970. offw[k] = tex_pos.y + mh;
  971. }
  972. FontGlyph chr;
  973. chr.advance = advance * p_data->scale / p_data->oversampling;
  974. chr.texture_idx = tex_pos.index;
  975. chr.found = true;
  976. chr.uv_rect = Rect2(tex_pos.x + p_rect_margin, tex_pos.y + p_rect_margin, w + p_rect_margin * 2, h + p_rect_margin * 2);
  977. chr.rect.position = Vector2(xofs - p_rect_margin, -yofs - p_rect_margin) * p_data->scale / p_data->oversampling;
  978. chr.rect.size = chr.uv_rect.size * p_data->scale / p_data->oversampling;
  979. return chr;
  980. }
  981. #endif
  982. /*************************************************************************/
  983. /* Font Cache */
  984. /*************************************************************************/
  985. _FORCE_INLINE_ bool TextServerAdvanced::_ensure_glyph(FontAdvanced *p_font_data, const Vector2i &p_size, int32_t p_glyph) const {
  986. ERR_FAIL_COND_V(!_ensure_cache_for_size(p_font_data, p_size), false);
  987. int32_t glyph_index = p_glyph & 0xffffff; // Remove subpixel shifts.
  988. FontForSizeAdvanced *fd = p_font_data->cache[p_size];
  989. if (fd->glyph_map.has(p_glyph)) {
  990. return fd->glyph_map[p_glyph].found;
  991. }
  992. if (glyph_index == 0) { // Non graphical or invalid glyph, do not render.
  993. fd->glyph_map[p_glyph] = FontGlyph();
  994. return true;
  995. }
  996. #ifdef MODULE_FREETYPE_ENABLED
  997. FontGlyph gl;
  998. if (fd->face) {
  999. FT_Int32 flags = FT_LOAD_DEFAULT;
  1000. bool outline = p_size.y > 0;
  1001. switch (p_font_data->hinting) {
  1002. case TextServer::HINTING_NONE:
  1003. flags |= FT_LOAD_NO_HINTING;
  1004. break;
  1005. case TextServer::HINTING_LIGHT:
  1006. flags |= FT_LOAD_TARGET_LIGHT;
  1007. break;
  1008. default:
  1009. flags |= FT_LOAD_TARGET_NORMAL;
  1010. break;
  1011. }
  1012. if (p_font_data->force_autohinter) {
  1013. flags |= FT_LOAD_FORCE_AUTOHINT;
  1014. }
  1015. if (outline) {
  1016. flags |= FT_LOAD_NO_BITMAP;
  1017. } else if (FT_HAS_COLOR(fd->face)) {
  1018. flags |= FT_LOAD_COLOR;
  1019. }
  1020. FT_Fixed v, h;
  1021. FT_Get_Advance(fd->face, glyph_index, flags, &h);
  1022. FT_Get_Advance(fd->face, glyph_index, flags | FT_LOAD_VERTICAL_LAYOUT, &v);
  1023. int error = FT_Load_Glyph(fd->face, glyph_index, flags);
  1024. if (error) {
  1025. fd->glyph_map[p_glyph] = FontGlyph();
  1026. return false;
  1027. }
  1028. if (!p_font_data->msdf) {
  1029. if ((p_font_data->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (p_font_data->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && p_size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE)) {
  1030. FT_Pos xshift = (int)((p_glyph >> 27) & 3) << 4;
  1031. FT_Outline_Translate(&fd->face->glyph->outline, xshift, 0);
  1032. } else if ((p_font_data->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (p_font_data->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && p_size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) {
  1033. FT_Pos xshift = (int)((p_glyph >> 27) & 3) << 5;
  1034. FT_Outline_Translate(&fd->face->glyph->outline, xshift, 0);
  1035. }
  1036. }
  1037. if (p_font_data->embolden != 0.f) {
  1038. FT_Pos strength = p_font_data->embolden * p_size.x * 4; // 26.6 fractional units (1 / 64).
  1039. FT_Outline_Embolden(&fd->face->glyph->outline, strength);
  1040. }
  1041. if (p_font_data->transform != Transform2D()) {
  1042. FT_Matrix mat = { FT_Fixed(p_font_data->transform[0][0] * 65536), FT_Fixed(p_font_data->transform[0][1] * 65536), FT_Fixed(p_font_data->transform[1][0] * 65536), FT_Fixed(p_font_data->transform[1][1] * 65536) }; // 16.16 fractional units (1 / 65536).
  1043. FT_Outline_Transform(&fd->face->glyph->outline, &mat);
  1044. }
  1045. if (!outline) {
  1046. if (!p_font_data->msdf) {
  1047. error = FT_Render_Glyph(fd->face->glyph, p_font_data->antialiased ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO);
  1048. }
  1049. FT_GlyphSlot slot = fd->face->glyph;
  1050. if (!error) {
  1051. if (p_font_data->msdf) {
  1052. #ifdef MODULE_MSDFGEN_ENABLED
  1053. gl = rasterize_msdf(p_font_data, fd, p_font_data->msdf_range, rect_range, &slot->outline, Vector2((h + (1 << 9)) >> 10, (v + (1 << 9)) >> 10) / 64.0);
  1054. #else
  1055. fd->glyph_map[p_glyph] = FontGlyph();
  1056. ERR_FAIL_V_MSG(false, "Compiled without MSDFGEN support!");
  1057. #endif
  1058. } else {
  1059. gl = rasterize_bitmap(fd, rect_range, slot->bitmap, slot->bitmap_top, slot->bitmap_left, Vector2((h + (1 << 9)) >> 10, (v + (1 << 9)) >> 10) / 64.0);
  1060. }
  1061. }
  1062. } else {
  1063. FT_Stroker stroker;
  1064. if (FT_Stroker_New(ft_library, &stroker) != 0) {
  1065. fd->glyph_map[p_glyph] = FontGlyph();
  1066. ERR_FAIL_V_MSG(false, "FreeType: Failed to load glyph stroker.");
  1067. }
  1068. FT_Stroker_Set(stroker, (int)(fd->size.y * fd->oversampling * 16.0), FT_STROKER_LINECAP_BUTT, FT_STROKER_LINEJOIN_ROUND, 0);
  1069. FT_Glyph glyph;
  1070. FT_BitmapGlyph glyph_bitmap;
  1071. if (FT_Get_Glyph(fd->face->glyph, &glyph) != 0) {
  1072. goto cleanup_stroker;
  1073. }
  1074. if (FT_Glyph_Stroke(&glyph, stroker, 1) != 0) {
  1075. goto cleanup_glyph;
  1076. }
  1077. if (FT_Glyph_To_Bitmap(&glyph, p_font_data->antialiased ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO, nullptr, 1) != 0) {
  1078. goto cleanup_glyph;
  1079. }
  1080. glyph_bitmap = (FT_BitmapGlyph)glyph;
  1081. gl = rasterize_bitmap(fd, rect_range, glyph_bitmap->bitmap, glyph_bitmap->top, glyph_bitmap->left, Vector2());
  1082. cleanup_glyph:
  1083. FT_Done_Glyph(glyph);
  1084. cleanup_stroker:
  1085. FT_Stroker_Done(stroker);
  1086. }
  1087. fd->glyph_map[p_glyph] = gl;
  1088. return gl.found;
  1089. }
  1090. #endif
  1091. fd->glyph_map[p_glyph] = FontGlyph();
  1092. return false;
  1093. }
  1094. _FORCE_INLINE_ bool TextServerAdvanced::_ensure_cache_for_size(FontAdvanced *p_font_data, const Vector2i &p_size) const {
  1095. ERR_FAIL_COND_V(p_size.x <= 0, false);
  1096. if (p_font_data->cache.has(p_size)) {
  1097. return true;
  1098. }
  1099. FontForSizeAdvanced *fd = memnew(FontForSizeAdvanced);
  1100. fd->size = p_size;
  1101. if (p_font_data->data_ptr && (p_font_data->data_size > 0)) {
  1102. // Init dynamic font.
  1103. #ifdef MODULE_FREETYPE_ENABLED
  1104. int error = 0;
  1105. if (!ft_library) {
  1106. error = FT_Init_FreeType(&ft_library);
  1107. ERR_FAIL_COND_V_MSG(error != 0, false, "FreeType: Error initializing library: '" + String(FT_Error_String(error)) + "'.");
  1108. }
  1109. memset(&fd->stream, 0, sizeof(FT_StreamRec));
  1110. fd->stream.base = (unsigned char *)p_font_data->data_ptr;
  1111. fd->stream.size = p_font_data->data_size;
  1112. fd->stream.pos = 0;
  1113. FT_Open_Args fargs;
  1114. memset(&fargs, 0, sizeof(FT_Open_Args));
  1115. fargs.memory_base = (unsigned char *)p_font_data->data_ptr;
  1116. fargs.memory_size = p_font_data->data_size;
  1117. fargs.flags = FT_OPEN_MEMORY;
  1118. fargs.stream = &fd->stream;
  1119. int max_index = 0;
  1120. FT_Face tmp_face;
  1121. error = FT_Open_Face(ft_library, &fargs, -1, &tmp_face);
  1122. if (error == 0) {
  1123. max_index = tmp_face->num_faces - 1;
  1124. }
  1125. FT_Done_Face(tmp_face);
  1126. error = FT_Open_Face(ft_library, &fargs, CLAMP(p_font_data->face_index, 0, max_index), &fd->face);
  1127. if (error) {
  1128. FT_Done_Face(fd->face);
  1129. fd->face = nullptr;
  1130. ERR_FAIL_V_MSG(false, "FreeType: Error loading font: '" + String(FT_Error_String(error)) + "'.");
  1131. }
  1132. if (p_font_data->msdf) {
  1133. fd->oversampling = 1.0;
  1134. fd->size.x = p_font_data->msdf_source_size;
  1135. } else if (p_font_data->oversampling <= 0.0) {
  1136. fd->oversampling = font_get_global_oversampling();
  1137. } else {
  1138. fd->oversampling = p_font_data->oversampling;
  1139. }
  1140. if (FT_HAS_COLOR(fd->face) && fd->face->num_fixed_sizes > 0) {
  1141. int best_match = 0;
  1142. int diff = ABS(fd->size.x - ((int64_t)fd->face->available_sizes[0].width));
  1143. fd->scale = double(fd->size.x * fd->oversampling) / fd->face->available_sizes[0].width;
  1144. for (int i = 1; i < fd->face->num_fixed_sizes; i++) {
  1145. int ndiff = ABS(fd->size.x - ((int64_t)fd->face->available_sizes[i].width));
  1146. if (ndiff < diff) {
  1147. best_match = i;
  1148. diff = ndiff;
  1149. fd->scale = double(fd->size.x * fd->oversampling) / fd->face->available_sizes[i].width;
  1150. }
  1151. }
  1152. FT_Select_Size(fd->face, best_match);
  1153. } else {
  1154. FT_Set_Pixel_Sizes(fd->face, 0, double(fd->size.x * fd->oversampling));
  1155. fd->scale = ((double)fd->size.x * fd->oversampling) / (double)fd->face->size->metrics.y_ppem;
  1156. }
  1157. fd->hb_handle = hb_ft_font_create(fd->face, nullptr);
  1158. fd->ascent = (fd->face->size->metrics.ascender / 64.0) / fd->oversampling * fd->scale;
  1159. fd->descent = (-fd->face->size->metrics.descender / 64.0) / fd->oversampling * fd->scale;
  1160. fd->underline_position = (-FT_MulFix(fd->face->underline_position, fd->face->size->metrics.y_scale) / 64.0) / fd->oversampling * fd->scale;
  1161. fd->underline_thickness = (FT_MulFix(fd->face->underline_thickness, fd->face->size->metrics.y_scale) / 64.0) / fd->oversampling * fd->scale;
  1162. #if HB_VERSION_ATLEAST(3, 3, 0)
  1163. hb_font_set_synthetic_slant(fd->hb_handle, p_font_data->transform[0][1]);
  1164. #else
  1165. #ifndef _MSC_VER
  1166. #warning Building with HarfBuzz < 3.3.0, synthetic slant offset correction disabled.
  1167. #endif
  1168. #endif
  1169. if (!p_font_data->face_init) {
  1170. // Get style flags and name.
  1171. if (fd->face->family_name != nullptr) {
  1172. p_font_data->font_name = String::utf8((const char *)fd->face->family_name);
  1173. }
  1174. if (fd->face->style_name != nullptr) {
  1175. p_font_data->style_name = String::utf8((const char *)fd->face->style_name);
  1176. }
  1177. p_font_data->style_flags = 0;
  1178. if (fd->face->style_flags & FT_STYLE_FLAG_BOLD) {
  1179. p_font_data->style_flags.set_flag(FONT_BOLD);
  1180. }
  1181. if (fd->face->style_flags & FT_STYLE_FLAG_ITALIC) {
  1182. p_font_data->style_flags.set_flag(FONT_ITALIC);
  1183. }
  1184. if (fd->face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) {
  1185. p_font_data->style_flags.set_flag(FONT_FIXED_WIDTH);
  1186. }
  1187. hb_face_t *hb_face = hb_font_get_face(fd->hb_handle);
  1188. // Get supported scripts from OpenType font data.
  1189. p_font_data->supported_scripts.clear();
  1190. unsigned int count = hb_ot_layout_table_get_script_tags(hb_face, HB_OT_TAG_GSUB, 0, nullptr, nullptr);
  1191. if (count != 0) {
  1192. hb_tag_t *script_tags = (hb_tag_t *)memalloc(count * sizeof(hb_tag_t));
  1193. hb_ot_layout_table_get_script_tags(hb_face, HB_OT_TAG_GSUB, 0, &count, script_tags);
  1194. for (unsigned int i = 0; i < count; i++) {
  1195. p_font_data->supported_scripts.insert(script_tags[i]);
  1196. }
  1197. memfree(script_tags);
  1198. }
  1199. count = hb_ot_layout_table_get_script_tags(hb_face, HB_OT_TAG_GPOS, 0, nullptr, nullptr);
  1200. if (count != 0) {
  1201. hb_tag_t *script_tags = (hb_tag_t *)memalloc(count * sizeof(hb_tag_t));
  1202. hb_ot_layout_table_get_script_tags(hb_face, HB_OT_TAG_GPOS, 0, &count, script_tags);
  1203. for (unsigned int i = 0; i < count; i++) {
  1204. p_font_data->supported_scripts.insert(script_tags[i]);
  1205. }
  1206. memfree(script_tags);
  1207. }
  1208. // Get supported scripts from OS2 table.
  1209. TT_OS2 *os2 = (TT_OS2 *)FT_Get_Sfnt_Table(fd->face, FT_SFNT_OS2);
  1210. if (os2) {
  1211. if ((os2->ulUnicodeRange1 & 1L << 4) || (os2->ulUnicodeRange1 & 1L << 5) || (os2->ulUnicodeRange1 & 1L << 6) || (os2->ulUnicodeRange1 & 1L << 31) || (os2->ulUnicodeRange2 & 1L << 0) || (os2->ulUnicodeRange2 & 1L << 1) || (os2->ulUnicodeRange2 & 1L << 2) || (os2->ulUnicodeRange2 & 1L << 3) || (os2->ulUnicodeRange2 & 1L << 4) || (os2->ulUnicodeRange2 & 1L << 5) || (os2->ulUnicodeRange2 & 1L << 6) || (os2->ulUnicodeRange2 & 1L << 7) || (os2->ulUnicodeRange2 & 1L << 8) || (os2->ulUnicodeRange2 & 1L << 9) || (os2->ulUnicodeRange2 & 1L << 10) || (os2->ulUnicodeRange2 & 1L << 11) || (os2->ulUnicodeRange2 & 1L << 12) || (os2->ulUnicodeRange2 & 1L << 13) || (os2->ulUnicodeRange2 & 1L << 14) || (os2->ulUnicodeRange2 & 1L << 15) || (os2->ulUnicodeRange2 & 1L << 30) || (os2->ulUnicodeRange3 & 1L << 0) || (os2->ulUnicodeRange3 & 1L << 1) || (os2->ulUnicodeRange3 & 1L << 2) || (os2->ulUnicodeRange3 & 1L << 4) || (os2->ulUnicodeRange3 & 1L << 5) || (os2->ulUnicodeRange3 & 1L << 18) || (os2->ulUnicodeRange3 & 1L << 24) || (os2->ulUnicodeRange3 & 1L << 25) || (os2->ulUnicodeRange3 & 1L << 26) || (os2->ulUnicodeRange3 & 1L << 27) || (os2->ulUnicodeRange3 & 1L << 28) || (os2->ulUnicodeRange4 & 1L << 3) || (os2->ulUnicodeRange4 & 1L << 6) || (os2->ulUnicodeRange4 & 1L << 15) || (os2->ulUnicodeRange4 & 1L << 23) || (os2->ulUnicodeRange4 & 1L << 24) || (os2->ulUnicodeRange4 & 1L << 26)) {
  1212. p_font_data->supported_scripts.insert(HB_SCRIPT_COMMON);
  1213. }
  1214. if ((os2->ulUnicodeRange1 & 1L << 0) || (os2->ulUnicodeRange1 & 1L << 1) || (os2->ulUnicodeRange1 & 1L << 2) || (os2->ulUnicodeRange1 & 1L << 3) || (os2->ulUnicodeRange1 & 1L << 29)) {
  1215. p_font_data->supported_scripts.insert(HB_SCRIPT_LATIN);
  1216. }
  1217. if ((os2->ulUnicodeRange1 & 1L << 7) || (os2->ulUnicodeRange1 & 1L << 30)) {
  1218. p_font_data->supported_scripts.insert(HB_SCRIPT_GREEK);
  1219. }
  1220. if (os2->ulUnicodeRange1 & 1L << 8) {
  1221. p_font_data->supported_scripts.insert(HB_SCRIPT_COPTIC);
  1222. }
  1223. if (os2->ulUnicodeRange1 & 1L << 9) {
  1224. p_font_data->supported_scripts.insert(HB_SCRIPT_CYRILLIC);
  1225. }
  1226. if (os2->ulUnicodeRange1 & 1L << 10) {
  1227. p_font_data->supported_scripts.insert(HB_SCRIPT_ARMENIAN);
  1228. }
  1229. if (os2->ulUnicodeRange1 & 1L << 11) {
  1230. p_font_data->supported_scripts.insert(HB_SCRIPT_HEBREW);
  1231. }
  1232. if (os2->ulUnicodeRange1 & 1L << 12) {
  1233. p_font_data->supported_scripts.insert(HB_SCRIPT_VAI);
  1234. }
  1235. if ((os2->ulUnicodeRange1 & 1L << 13) || (os2->ulUnicodeRange2 & 1L << 31) || (os2->ulUnicodeRange3 & 1L << 3)) {
  1236. p_font_data->supported_scripts.insert(HB_SCRIPT_ARABIC);
  1237. }
  1238. if (os2->ulUnicodeRange1 & 1L << 14) {
  1239. p_font_data->supported_scripts.insert(HB_SCRIPT_NKO);
  1240. }
  1241. if (os2->ulUnicodeRange1 & 1L << 15) {
  1242. p_font_data->supported_scripts.insert(HB_SCRIPT_DEVANAGARI);
  1243. }
  1244. if (os2->ulUnicodeRange1 & 1L << 16) {
  1245. p_font_data->supported_scripts.insert(HB_SCRIPT_BENGALI);
  1246. }
  1247. if (os2->ulUnicodeRange1 & 1L << 17) {
  1248. p_font_data->supported_scripts.insert(HB_SCRIPT_GURMUKHI);
  1249. }
  1250. if (os2->ulUnicodeRange1 & 1L << 18) {
  1251. p_font_data->supported_scripts.insert(HB_SCRIPT_GUJARATI);
  1252. }
  1253. if (os2->ulUnicodeRange1 & 1L << 19) {
  1254. p_font_data->supported_scripts.insert(HB_SCRIPT_ORIYA);
  1255. }
  1256. if (os2->ulUnicodeRange1 & 1L << 20) {
  1257. p_font_data->supported_scripts.insert(HB_SCRIPT_TAMIL);
  1258. }
  1259. if (os2->ulUnicodeRange1 & 1L << 21) {
  1260. p_font_data->supported_scripts.insert(HB_SCRIPT_TELUGU);
  1261. }
  1262. if (os2->ulUnicodeRange1 & 1L << 22) {
  1263. p_font_data->supported_scripts.insert(HB_SCRIPT_KANNADA);
  1264. }
  1265. if (os2->ulUnicodeRange1 & 1L << 23) {
  1266. p_font_data->supported_scripts.insert(HB_SCRIPT_MALAYALAM);
  1267. }
  1268. if (os2->ulUnicodeRange1 & 1L << 24) {
  1269. p_font_data->supported_scripts.insert(HB_SCRIPT_THAI);
  1270. }
  1271. if (os2->ulUnicodeRange1 & 1L << 25) {
  1272. p_font_data->supported_scripts.insert(HB_SCRIPT_LAO);
  1273. }
  1274. if (os2->ulUnicodeRange1 & 1L << 26) {
  1275. p_font_data->supported_scripts.insert(HB_SCRIPT_GEORGIAN);
  1276. }
  1277. if (os2->ulUnicodeRange1 & 1L << 27) {
  1278. p_font_data->supported_scripts.insert(HB_SCRIPT_BALINESE);
  1279. }
  1280. if ((os2->ulUnicodeRange1 & 1L << 28) || (os2->ulUnicodeRange2 & 1L << 20) || (os2->ulUnicodeRange2 & 1L << 24)) {
  1281. p_font_data->supported_scripts.insert(HB_SCRIPT_HANGUL);
  1282. }
  1283. if ((os2->ulUnicodeRange2 & 1L << 21) || (os2->ulUnicodeRange2 & 1L << 22) || (os2->ulUnicodeRange2 & 1L << 23) || (os2->ulUnicodeRange2 & 1L << 26) || (os2->ulUnicodeRange2 & 1L << 27) || (os2->ulUnicodeRange2 & 1L << 29)) {
  1284. p_font_data->supported_scripts.insert(HB_SCRIPT_HAN);
  1285. }
  1286. if (os2->ulUnicodeRange2 & 1L << 17) {
  1287. p_font_data->supported_scripts.insert(HB_SCRIPT_HIRAGANA);
  1288. }
  1289. if (os2->ulUnicodeRange2 & 1L << 18) {
  1290. p_font_data->supported_scripts.insert(HB_SCRIPT_KATAKANA);
  1291. }
  1292. if (os2->ulUnicodeRange2 & 1L << 19) {
  1293. p_font_data->supported_scripts.insert(HB_SCRIPT_BOPOMOFO);
  1294. }
  1295. if (os2->ulUnicodeRange3 & 1L << 6) {
  1296. p_font_data->supported_scripts.insert(HB_SCRIPT_TIBETAN);
  1297. }
  1298. if (os2->ulUnicodeRange3 & 1L << 7) {
  1299. p_font_data->supported_scripts.insert(HB_SCRIPT_SYRIAC);
  1300. }
  1301. if (os2->ulUnicodeRange3 & 1L << 8) {
  1302. p_font_data->supported_scripts.insert(HB_SCRIPT_THAANA);
  1303. }
  1304. if (os2->ulUnicodeRange3 & 1L << 9) {
  1305. p_font_data->supported_scripts.insert(HB_SCRIPT_SINHALA);
  1306. }
  1307. if (os2->ulUnicodeRange3 & 1L << 10) {
  1308. p_font_data->supported_scripts.insert(HB_SCRIPT_MYANMAR);
  1309. }
  1310. if (os2->ulUnicodeRange3 & 1L << 11) {
  1311. p_font_data->supported_scripts.insert(HB_SCRIPT_ETHIOPIC);
  1312. }
  1313. if (os2->ulUnicodeRange3 & 1L << 12) {
  1314. p_font_data->supported_scripts.insert(HB_SCRIPT_CHEROKEE);
  1315. }
  1316. if (os2->ulUnicodeRange3 & 1L << 13) {
  1317. p_font_data->supported_scripts.insert(HB_SCRIPT_CANADIAN_SYLLABICS);
  1318. }
  1319. if (os2->ulUnicodeRange3 & 1L << 14) {
  1320. p_font_data->supported_scripts.insert(HB_SCRIPT_OGHAM);
  1321. }
  1322. if (os2->ulUnicodeRange3 & 1L << 15) {
  1323. p_font_data->supported_scripts.insert(HB_SCRIPT_RUNIC);
  1324. }
  1325. if (os2->ulUnicodeRange3 & 1L << 16) {
  1326. p_font_data->supported_scripts.insert(HB_SCRIPT_KHMER);
  1327. }
  1328. if (os2->ulUnicodeRange3 & 1L << 17) {
  1329. p_font_data->supported_scripts.insert(HB_SCRIPT_MONGOLIAN);
  1330. }
  1331. if (os2->ulUnicodeRange3 & 1L << 19) {
  1332. p_font_data->supported_scripts.insert(HB_SCRIPT_YI);
  1333. }
  1334. if (os2->ulUnicodeRange3 & 1L << 20) {
  1335. p_font_data->supported_scripts.insert(HB_SCRIPT_HANUNOO);
  1336. p_font_data->supported_scripts.insert(HB_SCRIPT_TAGBANWA);
  1337. p_font_data->supported_scripts.insert(HB_SCRIPT_BUHID);
  1338. p_font_data->supported_scripts.insert(HB_SCRIPT_TAGALOG);
  1339. }
  1340. if (os2->ulUnicodeRange3 & 1L << 21) {
  1341. p_font_data->supported_scripts.insert(HB_SCRIPT_OLD_ITALIC);
  1342. }
  1343. if (os2->ulUnicodeRange3 & 1L << 22) {
  1344. p_font_data->supported_scripts.insert(HB_SCRIPT_GOTHIC);
  1345. }
  1346. if (os2->ulUnicodeRange3 & 1L << 23) {
  1347. p_font_data->supported_scripts.insert(HB_SCRIPT_DESERET);
  1348. }
  1349. if (os2->ulUnicodeRange3 & 1L << 29) {
  1350. p_font_data->supported_scripts.insert(HB_SCRIPT_LIMBU);
  1351. }
  1352. if (os2->ulUnicodeRange3 & 1L << 30) {
  1353. p_font_data->supported_scripts.insert(HB_SCRIPT_TAI_LE);
  1354. }
  1355. if (os2->ulUnicodeRange3 & 1L << 31) {
  1356. p_font_data->supported_scripts.insert(HB_SCRIPT_NEW_TAI_LUE);
  1357. }
  1358. if (os2->ulUnicodeRange4 & 1L << 0) {
  1359. p_font_data->supported_scripts.insert(HB_SCRIPT_BUGINESE);
  1360. }
  1361. if (os2->ulUnicodeRange4 & 1L << 1) {
  1362. p_font_data->supported_scripts.insert(HB_SCRIPT_GLAGOLITIC);
  1363. }
  1364. if (os2->ulUnicodeRange4 & 1L << 2) {
  1365. p_font_data->supported_scripts.insert(HB_SCRIPT_TIFINAGH);
  1366. }
  1367. if (os2->ulUnicodeRange4 & 1L << 4) {
  1368. p_font_data->supported_scripts.insert(HB_SCRIPT_SYLOTI_NAGRI);
  1369. }
  1370. if (os2->ulUnicodeRange4 & 1L << 5) {
  1371. p_font_data->supported_scripts.insert(HB_SCRIPT_LINEAR_B);
  1372. }
  1373. if (os2->ulUnicodeRange4 & 1L << 7) {
  1374. p_font_data->supported_scripts.insert(HB_SCRIPT_UGARITIC);
  1375. }
  1376. if (os2->ulUnicodeRange4 & 1L << 8) {
  1377. p_font_data->supported_scripts.insert(HB_SCRIPT_OLD_PERSIAN);
  1378. }
  1379. if (os2->ulUnicodeRange4 & 1L << 9) {
  1380. p_font_data->supported_scripts.insert(HB_SCRIPT_SHAVIAN);
  1381. }
  1382. if (os2->ulUnicodeRange4 & 1L << 10) {
  1383. p_font_data->supported_scripts.insert(HB_SCRIPT_OSMANYA);
  1384. }
  1385. if (os2->ulUnicodeRange4 & 1L << 11) {
  1386. p_font_data->supported_scripts.insert(HB_SCRIPT_CYPRIOT);
  1387. }
  1388. if (os2->ulUnicodeRange4 & 1L << 12) {
  1389. p_font_data->supported_scripts.insert(HB_SCRIPT_KHAROSHTHI);
  1390. }
  1391. if (os2->ulUnicodeRange4 & 1L << 13) {
  1392. p_font_data->supported_scripts.insert(HB_SCRIPT_TAI_VIET);
  1393. }
  1394. if (os2->ulUnicodeRange4 & 1L << 14) {
  1395. p_font_data->supported_scripts.insert(HB_SCRIPT_CUNEIFORM);
  1396. }
  1397. if (os2->ulUnicodeRange4 & 1L << 16) {
  1398. p_font_data->supported_scripts.insert(HB_SCRIPT_SUNDANESE);
  1399. }
  1400. if (os2->ulUnicodeRange4 & 1L << 17) {
  1401. p_font_data->supported_scripts.insert(HB_SCRIPT_LEPCHA);
  1402. }
  1403. if (os2->ulUnicodeRange4 & 1L << 18) {
  1404. p_font_data->supported_scripts.insert(HB_SCRIPT_OL_CHIKI);
  1405. }
  1406. if (os2->ulUnicodeRange4 & 1L << 19) {
  1407. p_font_data->supported_scripts.insert(HB_SCRIPT_SAURASHTRA);
  1408. }
  1409. if (os2->ulUnicodeRange4 & 1L << 20) {
  1410. p_font_data->supported_scripts.insert(HB_SCRIPT_KAYAH_LI);
  1411. }
  1412. if (os2->ulUnicodeRange4 & 1L << 21) {
  1413. p_font_data->supported_scripts.insert(HB_SCRIPT_REJANG);
  1414. }
  1415. if (os2->ulUnicodeRange4 & 1L << 22) {
  1416. p_font_data->supported_scripts.insert(HB_SCRIPT_CHAM);
  1417. }
  1418. if (os2->ulUnicodeRange4 & 1L << 25) {
  1419. p_font_data->supported_scripts.insert(HB_SCRIPT_ANATOLIAN_HIEROGLYPHS);
  1420. }
  1421. }
  1422. // Read OpenType feature tags.
  1423. p_font_data->supported_features.clear();
  1424. count = hb_ot_layout_table_get_feature_tags(hb_face, HB_OT_TAG_GSUB, 0, nullptr, nullptr);
  1425. if (count != 0) {
  1426. hb_tag_t *feature_tags = (hb_tag_t *)memalloc(count * sizeof(hb_tag_t));
  1427. hb_ot_layout_table_get_feature_tags(hb_face, HB_OT_TAG_GSUB, 0, &count, feature_tags);
  1428. for (unsigned int i = 0; i < count; i++) {
  1429. Dictionary ftr;
  1430. #if HB_VERSION_ATLEAST(2, 1, 0)
  1431. hb_ot_name_id_t lbl_id;
  1432. if (hb_ot_layout_feature_get_name_ids(hb_face, HB_OT_TAG_GSUB, i, &lbl_id, nullptr, nullptr, nullptr, nullptr)) {
  1433. PackedInt32Array lbl;
  1434. unsigned int text_size = hb_ot_name_get_utf32(hb_face, lbl_id, hb_language_from_string(TranslationServer::get_singleton()->get_tool_locale().ascii().get_data(), -1), nullptr, nullptr) + 1;
  1435. lbl.resize(text_size);
  1436. memset((uint32_t *)lbl.ptrw(), 0, sizeof(uint32_t) * text_size);
  1437. hb_ot_name_get_utf32(hb_face, lbl_id, hb_language_from_string(TranslationServer::get_singleton()->get_tool_locale().ascii().get_data(), -1), &text_size, (uint32_t *)lbl.ptrw());
  1438. ftr["label"] = String((const char32_t *)lbl.ptr());
  1439. }
  1440. #else
  1441. #ifndef _MSC_VER
  1442. #warning Building with HarfBuzz < 2.1.0, readable OpenType feature names disabled.
  1443. #endif
  1444. #endif
  1445. ftr["type"] = _get_tag_type(feature_tags[i]);
  1446. ftr["hidden"] = _get_tag_hidden(feature_tags[i]);
  1447. p_font_data->supported_features[feature_tags[i]] = ftr;
  1448. }
  1449. memfree(feature_tags);
  1450. }
  1451. count = hb_ot_layout_table_get_feature_tags(hb_face, HB_OT_TAG_GPOS, 0, nullptr, nullptr);
  1452. if (count != 0) {
  1453. hb_tag_t *feature_tags = (hb_tag_t *)memalloc(count * sizeof(hb_tag_t));
  1454. hb_ot_layout_table_get_feature_tags(hb_face, HB_OT_TAG_GPOS, 0, &count, feature_tags);
  1455. for (unsigned int i = 0; i < count; i++) {
  1456. Dictionary ftr;
  1457. #if HB_VERSION_ATLEAST(2, 1, 0)
  1458. hb_ot_name_id_t lbl_id;
  1459. if (hb_ot_layout_feature_get_name_ids(hb_face, HB_OT_TAG_GPOS, i, &lbl_id, nullptr, nullptr, nullptr, nullptr)) {
  1460. PackedInt32Array lbl;
  1461. unsigned int text_size = hb_ot_name_get_utf32(hb_face, lbl_id, hb_language_from_string(TranslationServer::get_singleton()->get_tool_locale().ascii().get_data(), -1), nullptr, nullptr) + 1;
  1462. lbl.resize(text_size);
  1463. memset((uint32_t *)lbl.ptrw(), 0, sizeof(uint32_t) * text_size);
  1464. hb_ot_name_get_utf32(hb_face, lbl_id, hb_language_from_string(TranslationServer::get_singleton()->get_tool_locale().ascii().get_data(), -1), &text_size, (uint32_t *)lbl.ptrw());
  1465. ftr["label"] = String((const char32_t *)lbl.ptr());
  1466. }
  1467. #else
  1468. #ifndef _MSC_VER
  1469. #warning Building with HarfBuzz < 2.1.0, readable OpenType feature names disabled.
  1470. #endif
  1471. #endif
  1472. ftr["type"] = _get_tag_type(feature_tags[i]);
  1473. ftr["hidden"] = _get_tag_hidden(feature_tags[i]);
  1474. p_font_data->supported_features[feature_tags[i]] = ftr;
  1475. }
  1476. memfree(feature_tags);
  1477. }
  1478. // Read OpenType variations.
  1479. p_font_data->supported_varaitions.clear();
  1480. if (fd->face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
  1481. FT_MM_Var *amaster;
  1482. FT_Get_MM_Var(fd->face, &amaster);
  1483. for (FT_UInt i = 0; i < amaster->num_axis; i++) {
  1484. p_font_data->supported_varaitions[(int32_t)amaster->axis[i].tag] = Vector3i(amaster->axis[i].minimum / 65536, amaster->axis[i].maximum / 65536, amaster->axis[i].def / 65536);
  1485. }
  1486. FT_Done_MM_Var(ft_library, amaster);
  1487. }
  1488. p_font_data->face_init = true;
  1489. }
  1490. // Write variations.
  1491. if (fd->face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
  1492. FT_MM_Var *amaster;
  1493. FT_Get_MM_Var(fd->face, &amaster);
  1494. Vector<hb_variation_t> hb_vars;
  1495. Vector<FT_Fixed> coords;
  1496. coords.resize(amaster->num_axis);
  1497. FT_Get_Var_Design_Coordinates(fd->face, coords.size(), coords.ptrw());
  1498. for (FT_UInt i = 0; i < amaster->num_axis; i++) {
  1499. hb_variation_t var;
  1500. // Reset to default.
  1501. var.tag = amaster->axis[i].tag;
  1502. var.value = (double)amaster->axis[i].def / 65536.0;
  1503. coords.write[i] = amaster->axis[i].def;
  1504. if (p_font_data->variation_coordinates.has(var.tag)) {
  1505. var.value = p_font_data->variation_coordinates[var.tag];
  1506. coords.write[i] = CLAMP(var.value * 65536.0, amaster->axis[i].minimum, amaster->axis[i].maximum);
  1507. }
  1508. if (p_font_data->variation_coordinates.has(tag_to_name(var.tag))) {
  1509. var.value = p_font_data->variation_coordinates[tag_to_name(var.tag)];
  1510. coords.write[i] = CLAMP(var.value * 65536.0, amaster->axis[i].minimum, amaster->axis[i].maximum);
  1511. }
  1512. hb_vars.push_back(var);
  1513. }
  1514. FT_Set_Var_Design_Coordinates(fd->face, coords.size(), coords.ptrw());
  1515. hb_font_set_variations(fd->hb_handle, hb_vars.is_empty() ? nullptr : &hb_vars[0], hb_vars.size());
  1516. FT_Done_MM_Var(ft_library, amaster);
  1517. }
  1518. #else
  1519. ERR_FAIL_V_MSG(false, "FreeType: Can't load dynamic font, engine is compiled without FreeType support!");
  1520. #endif
  1521. } else {
  1522. // Init bitmap font.
  1523. fd->hb_handle = _bmp_font_create(fd, nullptr);
  1524. }
  1525. p_font_data->cache[p_size] = fd;
  1526. return true;
  1527. }
  1528. _FORCE_INLINE_ void TextServerAdvanced::_font_clear_cache(FontAdvanced *p_font_data) {
  1529. for (const KeyValue<Vector2i, FontForSizeAdvanced *> &E : p_font_data->cache) {
  1530. memdelete(E.value);
  1531. }
  1532. p_font_data->cache.clear();
  1533. p_font_data->face_init = false;
  1534. p_font_data->supported_features.clear();
  1535. p_font_data->supported_varaitions.clear();
  1536. p_font_data->supported_scripts.clear();
  1537. }
  1538. hb_font_t *TextServerAdvanced::_font_get_hb_handle(const RID &p_font_rid, int64_t p_size) const {
  1539. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1540. ERR_FAIL_COND_V(!fd, nullptr);
  1541. MutexLock lock(fd->mutex);
  1542. Vector2i size = _get_size(fd, p_size);
  1543. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), nullptr);
  1544. return fd->cache[size]->hb_handle;
  1545. }
  1546. RID TextServerAdvanced::create_font() {
  1547. _THREAD_SAFE_METHOD_
  1548. FontAdvanced *fd = memnew(FontAdvanced);
  1549. return font_owner.make_rid(fd);
  1550. }
  1551. void TextServerAdvanced::font_set_data(const RID &p_font_rid, const PackedByteArray &p_data) {
  1552. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1553. ERR_FAIL_COND(!fd);
  1554. MutexLock lock(fd->mutex);
  1555. _font_clear_cache(fd);
  1556. fd->data = p_data;
  1557. fd->data_ptr = fd->data.ptr();
  1558. fd->data_size = fd->data.size();
  1559. }
  1560. void TextServerAdvanced::font_set_data_ptr(const RID &p_font_rid, const uint8_t *p_data_ptr, int64_t p_data_size) {
  1561. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1562. ERR_FAIL_COND(!fd);
  1563. MutexLock lock(fd->mutex);
  1564. _font_clear_cache(fd);
  1565. fd->data.resize(0);
  1566. fd->data_ptr = p_data_ptr;
  1567. fd->data_size = p_data_size;
  1568. }
  1569. void TextServerAdvanced::font_set_face_index(const RID &p_font_rid, int64_t p_face_index) {
  1570. ERR_FAIL_COND(p_face_index < 0);
  1571. ERR_FAIL_COND(p_face_index >= 0x7FFF);
  1572. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1573. ERR_FAIL_COND(!fd);
  1574. MutexLock lock(fd->mutex);
  1575. if (fd->face_index != p_face_index) {
  1576. fd->face_index = p_face_index;
  1577. _font_clear_cache(fd);
  1578. }
  1579. }
  1580. int64_t TextServerAdvanced::font_get_face_index(const RID &p_font_rid) const {
  1581. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1582. ERR_FAIL_COND_V(!fd, 0);
  1583. MutexLock lock(fd->mutex);
  1584. return fd->face_index;
  1585. }
  1586. int64_t TextServerAdvanced::font_get_face_count(const RID &p_font_rid) const {
  1587. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1588. ERR_FAIL_COND_V(!fd, 0);
  1589. MutexLock lock(fd->mutex);
  1590. int face_count = 0;
  1591. if (fd->data_ptr && (fd->data_size > 0)) {
  1592. // Init dynamic font.
  1593. #ifdef MODULE_FREETYPE_ENABLED
  1594. int error = 0;
  1595. if (!ft_library) {
  1596. error = FT_Init_FreeType(&ft_library);
  1597. ERR_FAIL_COND_V_MSG(error != 0, false, "FreeType: Error initializing library: '" + String(FT_Error_String(error)) + "'.");
  1598. }
  1599. FT_StreamRec stream;
  1600. memset(&stream, 0, sizeof(FT_StreamRec));
  1601. stream.base = (unsigned char *)fd->data_ptr;
  1602. stream.size = fd->data_size;
  1603. stream.pos = 0;
  1604. FT_Open_Args fargs;
  1605. memset(&fargs, 0, sizeof(FT_Open_Args));
  1606. fargs.memory_base = (unsigned char *)fd->data_ptr;
  1607. fargs.memory_size = fd->data_size;
  1608. fargs.flags = FT_OPEN_MEMORY;
  1609. fargs.stream = &stream;
  1610. FT_Face tmp_face;
  1611. error = FT_Open_Face(ft_library, &fargs, -1, &tmp_face);
  1612. if (error == 0) {
  1613. face_count = tmp_face->num_faces;
  1614. }
  1615. FT_Done_Face(tmp_face);
  1616. #endif
  1617. }
  1618. return face_count;
  1619. }
  1620. void TextServerAdvanced::font_set_style(const RID &p_font_rid, BitField<FontStyle> p_style) {
  1621. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1622. ERR_FAIL_COND(!fd);
  1623. MutexLock lock(fd->mutex);
  1624. Vector2i size = _get_size(fd, 16);
  1625. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  1626. fd->style_flags = p_style;
  1627. }
  1628. BitField<TextServer::FontStyle> TextServerAdvanced::font_get_style(const RID &p_font_rid) const {
  1629. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1630. ERR_FAIL_COND_V(!fd, 0);
  1631. MutexLock lock(fd->mutex);
  1632. Vector2i size = _get_size(fd, 16);
  1633. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), 0);
  1634. return fd->style_flags;
  1635. }
  1636. void TextServerAdvanced::font_set_style_name(const RID &p_font_rid, const String &p_name) {
  1637. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1638. ERR_FAIL_COND(!fd);
  1639. MutexLock lock(fd->mutex);
  1640. Vector2i size = _get_size(fd, 16);
  1641. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  1642. fd->style_name = p_name;
  1643. }
  1644. String TextServerAdvanced::font_get_style_name(const RID &p_font_rid) const {
  1645. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1646. ERR_FAIL_COND_V(!fd, String());
  1647. MutexLock lock(fd->mutex);
  1648. Vector2i size = _get_size(fd, 16);
  1649. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), String());
  1650. return fd->style_name;
  1651. }
  1652. void TextServerAdvanced::font_set_name(const RID &p_font_rid, const String &p_name) {
  1653. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1654. ERR_FAIL_COND(!fd);
  1655. MutexLock lock(fd->mutex);
  1656. Vector2i size = _get_size(fd, 16);
  1657. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  1658. fd->font_name = p_name;
  1659. }
  1660. String TextServerAdvanced::font_get_name(const RID &p_font_rid) const {
  1661. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1662. ERR_FAIL_COND_V(!fd, String());
  1663. MutexLock lock(fd->mutex);
  1664. Vector2i size = _get_size(fd, 16);
  1665. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), String());
  1666. return fd->font_name;
  1667. }
  1668. void TextServerAdvanced::font_set_antialiased(const RID &p_font_rid, bool p_antialiased) {
  1669. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1670. ERR_FAIL_COND(!fd);
  1671. MutexLock lock(fd->mutex);
  1672. if (fd->antialiased != p_antialiased) {
  1673. _font_clear_cache(fd);
  1674. fd->antialiased = p_antialiased;
  1675. }
  1676. }
  1677. bool TextServerAdvanced::font_is_antialiased(const RID &p_font_rid) const {
  1678. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1679. ERR_FAIL_COND_V(!fd, false);
  1680. MutexLock lock(fd->mutex);
  1681. return fd->antialiased;
  1682. }
  1683. void TextServerAdvanced::font_set_generate_mipmaps(const RID &p_font_rid, bool p_generate_mipmaps) {
  1684. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1685. ERR_FAIL_COND(!fd);
  1686. MutexLock lock(fd->mutex);
  1687. if (fd->mipmaps != p_generate_mipmaps) {
  1688. for (KeyValue<Vector2i, FontForSizeAdvanced *> &E : fd->cache) {
  1689. for (int i = 0; i < E.value->textures.size(); i++) {
  1690. E.value->textures.write[i].dirty = true;
  1691. }
  1692. }
  1693. fd->mipmaps = p_generate_mipmaps;
  1694. }
  1695. }
  1696. bool TextServerAdvanced::font_get_generate_mipmaps(const RID &p_font_rid) const {
  1697. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1698. ERR_FAIL_COND_V(!fd, false);
  1699. MutexLock lock(fd->mutex);
  1700. return fd->mipmaps;
  1701. }
  1702. void TextServerAdvanced::font_set_multichannel_signed_distance_field(const RID &p_font_rid, bool p_msdf) {
  1703. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1704. ERR_FAIL_COND(!fd);
  1705. MutexLock lock(fd->mutex);
  1706. if (fd->msdf != p_msdf) {
  1707. _font_clear_cache(fd);
  1708. fd->msdf = p_msdf;
  1709. }
  1710. }
  1711. bool TextServerAdvanced::font_is_multichannel_signed_distance_field(const RID &p_font_rid) const {
  1712. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1713. ERR_FAIL_COND_V(!fd, false);
  1714. MutexLock lock(fd->mutex);
  1715. return fd->msdf;
  1716. }
  1717. void TextServerAdvanced::font_set_msdf_pixel_range(const RID &p_font_rid, int64_t p_msdf_pixel_range) {
  1718. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1719. ERR_FAIL_COND(!fd);
  1720. MutexLock lock(fd->mutex);
  1721. if (fd->msdf_range != p_msdf_pixel_range) {
  1722. _font_clear_cache(fd);
  1723. fd->msdf_range = p_msdf_pixel_range;
  1724. }
  1725. }
  1726. int64_t TextServerAdvanced::font_get_msdf_pixel_range(const RID &p_font_rid) const {
  1727. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1728. ERR_FAIL_COND_V(!fd, false);
  1729. MutexLock lock(fd->mutex);
  1730. return fd->msdf_range;
  1731. }
  1732. void TextServerAdvanced::font_set_msdf_size(const RID &p_font_rid, int64_t p_msdf_size) {
  1733. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1734. ERR_FAIL_COND(!fd);
  1735. MutexLock lock(fd->mutex);
  1736. if (fd->msdf_source_size != p_msdf_size) {
  1737. _font_clear_cache(fd);
  1738. fd->msdf_source_size = p_msdf_size;
  1739. }
  1740. }
  1741. int64_t TextServerAdvanced::font_get_msdf_size(const RID &p_font_rid) const {
  1742. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1743. ERR_FAIL_COND_V(!fd, false);
  1744. MutexLock lock(fd->mutex);
  1745. return fd->msdf_source_size;
  1746. }
  1747. void TextServerAdvanced::font_set_fixed_size(const RID &p_font_rid, int64_t p_fixed_size) {
  1748. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1749. ERR_FAIL_COND(!fd);
  1750. MutexLock lock(fd->mutex);
  1751. fd->fixed_size = p_fixed_size;
  1752. }
  1753. int64_t TextServerAdvanced::font_get_fixed_size(const RID &p_font_rid) const {
  1754. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1755. ERR_FAIL_COND_V(!fd, false);
  1756. MutexLock lock(fd->mutex);
  1757. return fd->fixed_size;
  1758. }
  1759. void TextServerAdvanced::font_set_force_autohinter(const RID &p_font_rid, bool p_force_autohinter) {
  1760. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1761. ERR_FAIL_COND(!fd);
  1762. MutexLock lock(fd->mutex);
  1763. if (fd->force_autohinter != p_force_autohinter) {
  1764. _font_clear_cache(fd);
  1765. fd->force_autohinter = p_force_autohinter;
  1766. }
  1767. }
  1768. bool TextServerAdvanced::font_is_force_autohinter(const RID &p_font_rid) const {
  1769. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1770. ERR_FAIL_COND_V(!fd, false);
  1771. MutexLock lock(fd->mutex);
  1772. return fd->force_autohinter;
  1773. }
  1774. void TextServerAdvanced::font_set_hinting(const RID &p_font_rid, TextServer::Hinting p_hinting) {
  1775. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1776. ERR_FAIL_COND(!fd);
  1777. MutexLock lock(fd->mutex);
  1778. if (fd->hinting != p_hinting) {
  1779. _font_clear_cache(fd);
  1780. fd->hinting = p_hinting;
  1781. }
  1782. }
  1783. TextServer::Hinting TextServerAdvanced::font_get_hinting(const RID &p_font_rid) const {
  1784. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1785. ERR_FAIL_COND_V(!fd, HINTING_NONE);
  1786. MutexLock lock(fd->mutex);
  1787. return fd->hinting;
  1788. }
  1789. void TextServerAdvanced::font_set_subpixel_positioning(const RID &p_font_rid, TextServer::SubpixelPositioning p_subpixel) {
  1790. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1791. ERR_FAIL_COND(!fd);
  1792. MutexLock lock(fd->mutex);
  1793. fd->subpixel_positioning = p_subpixel;
  1794. }
  1795. TextServer::SubpixelPositioning TextServerAdvanced::font_get_subpixel_positioning(const RID &p_font_rid) const {
  1796. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1797. ERR_FAIL_COND_V(!fd, SUBPIXEL_POSITIONING_DISABLED);
  1798. MutexLock lock(fd->mutex);
  1799. return fd->subpixel_positioning;
  1800. }
  1801. void TextServerAdvanced::font_set_embolden(const RID &p_font_rid, double p_strength) {
  1802. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1803. ERR_FAIL_COND(!fd);
  1804. MutexLock lock(fd->mutex);
  1805. if (fd->embolden != p_strength) {
  1806. _font_clear_cache(fd);
  1807. fd->embolden = p_strength;
  1808. }
  1809. }
  1810. double TextServerAdvanced::font_get_embolden(const RID &p_font_rid) const {
  1811. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1812. ERR_FAIL_COND_V(!fd, 0.0);
  1813. MutexLock lock(fd->mutex);
  1814. return fd->embolden;
  1815. }
  1816. void TextServerAdvanced::font_set_transform(const RID &p_font_rid, const Transform2D &p_transform) {
  1817. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1818. ERR_FAIL_COND(!fd);
  1819. MutexLock lock(fd->mutex);
  1820. if (fd->transform != p_transform) {
  1821. _font_clear_cache(fd);
  1822. fd->transform = p_transform;
  1823. }
  1824. }
  1825. Transform2D TextServerAdvanced::font_get_transform(const RID &p_font_rid) const {
  1826. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1827. ERR_FAIL_COND_V(!fd, Transform2D());
  1828. MutexLock lock(fd->mutex);
  1829. return fd->transform;
  1830. }
  1831. void TextServerAdvanced::font_set_variation_coordinates(const RID &p_font_rid, const Dictionary &p_variation_coordinates) {
  1832. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1833. ERR_FAIL_COND(!fd);
  1834. MutexLock lock(fd->mutex);
  1835. if (fd->variation_coordinates != p_variation_coordinates) {
  1836. _font_clear_cache(fd);
  1837. fd->variation_coordinates = p_variation_coordinates;
  1838. }
  1839. }
  1840. Dictionary TextServerAdvanced::font_get_variation_coordinates(const RID &p_font_rid) const {
  1841. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1842. ERR_FAIL_COND_V(!fd, Dictionary());
  1843. MutexLock lock(fd->mutex);
  1844. return fd->variation_coordinates;
  1845. }
  1846. void TextServerAdvanced::font_set_oversampling(const RID &p_font_rid, double p_oversampling) {
  1847. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1848. ERR_FAIL_COND(!fd);
  1849. MutexLock lock(fd->mutex);
  1850. if (fd->oversampling != p_oversampling) {
  1851. _font_clear_cache(fd);
  1852. fd->oversampling = p_oversampling;
  1853. }
  1854. }
  1855. double TextServerAdvanced::font_get_oversampling(const RID &p_font_rid) const {
  1856. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1857. ERR_FAIL_COND_V(!fd, 0.0);
  1858. MutexLock lock(fd->mutex);
  1859. return fd->oversampling;
  1860. }
  1861. Array TextServerAdvanced::font_get_size_cache_list(const RID &p_font_rid) const {
  1862. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1863. ERR_FAIL_COND_V(!fd, Array());
  1864. MutexLock lock(fd->mutex);
  1865. Array ret;
  1866. for (const KeyValue<Vector2i, FontForSizeAdvanced *> &E : fd->cache) {
  1867. ret.push_back(E.key);
  1868. }
  1869. return ret;
  1870. }
  1871. void TextServerAdvanced::font_clear_size_cache(const RID &p_font_rid) {
  1872. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1873. ERR_FAIL_COND(!fd);
  1874. MutexLock lock(fd->mutex);
  1875. for (const KeyValue<Vector2i, FontForSizeAdvanced *> &E : fd->cache) {
  1876. memdelete(E.value);
  1877. }
  1878. fd->cache.clear();
  1879. }
  1880. void TextServerAdvanced::font_remove_size_cache(const RID &p_font_rid, const Vector2i &p_size) {
  1881. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1882. ERR_FAIL_COND(!fd);
  1883. MutexLock lock(fd->mutex);
  1884. if (fd->cache.has(p_size)) {
  1885. memdelete(fd->cache[p_size]);
  1886. fd->cache.erase(p_size);
  1887. }
  1888. }
  1889. void TextServerAdvanced::font_set_ascent(const RID &p_font_rid, int64_t p_size, double p_ascent) {
  1890. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1891. ERR_FAIL_COND(!fd);
  1892. MutexLock lock(fd->mutex);
  1893. Vector2i size = _get_size(fd, p_size);
  1894. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  1895. fd->cache[size]->ascent = p_ascent;
  1896. }
  1897. double TextServerAdvanced::font_get_ascent(const RID &p_font_rid, int64_t p_size) const {
  1898. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1899. ERR_FAIL_COND_V(!fd, 0.0);
  1900. MutexLock lock(fd->mutex);
  1901. Vector2i size = _get_size(fd, p_size);
  1902. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), 0.0);
  1903. if (fd->msdf) {
  1904. return fd->cache[size]->ascent * (double)p_size / (double)fd->msdf_source_size;
  1905. } else {
  1906. return fd->cache[size]->ascent;
  1907. }
  1908. }
  1909. void TextServerAdvanced::font_set_descent(const RID &p_font_rid, int64_t p_size, double p_descent) {
  1910. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1911. ERR_FAIL_COND(!fd);
  1912. Vector2i size = _get_size(fd, p_size);
  1913. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  1914. fd->cache[size]->descent = p_descent;
  1915. }
  1916. double TextServerAdvanced::font_get_descent(const RID &p_font_rid, int64_t p_size) const {
  1917. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1918. ERR_FAIL_COND_V(!fd, 0.0);
  1919. MutexLock lock(fd->mutex);
  1920. Vector2i size = _get_size(fd, p_size);
  1921. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), 0.0);
  1922. if (fd->msdf) {
  1923. return fd->cache[size]->descent * (double)p_size / (double)fd->msdf_source_size;
  1924. } else {
  1925. return fd->cache[size]->descent;
  1926. }
  1927. }
  1928. void TextServerAdvanced::font_set_underline_position(const RID &p_font_rid, int64_t p_size, double p_underline_position) {
  1929. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1930. ERR_FAIL_COND(!fd);
  1931. MutexLock lock(fd->mutex);
  1932. Vector2i size = _get_size(fd, p_size);
  1933. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  1934. fd->cache[size]->underline_position = p_underline_position;
  1935. }
  1936. double TextServerAdvanced::font_get_underline_position(const RID &p_font_rid, int64_t p_size) const {
  1937. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1938. ERR_FAIL_COND_V(!fd, 0.0);
  1939. MutexLock lock(fd->mutex);
  1940. Vector2i size = _get_size(fd, p_size);
  1941. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), 0.0);
  1942. if (fd->msdf) {
  1943. return fd->cache[size]->underline_position * (double)p_size / (double)fd->msdf_source_size;
  1944. } else {
  1945. return fd->cache[size]->underline_position;
  1946. }
  1947. }
  1948. void TextServerAdvanced::font_set_underline_thickness(const RID &p_font_rid, int64_t p_size, double p_underline_thickness) {
  1949. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1950. ERR_FAIL_COND(!fd);
  1951. MutexLock lock(fd->mutex);
  1952. Vector2i size = _get_size(fd, p_size);
  1953. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  1954. fd->cache[size]->underline_thickness = p_underline_thickness;
  1955. }
  1956. double TextServerAdvanced::font_get_underline_thickness(const RID &p_font_rid, int64_t p_size) const {
  1957. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1958. ERR_FAIL_COND_V(!fd, 0.0);
  1959. MutexLock lock(fd->mutex);
  1960. Vector2i size = _get_size(fd, p_size);
  1961. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), 0.0);
  1962. if (fd->msdf) {
  1963. return fd->cache[size]->underline_thickness * (double)p_size / (double)fd->msdf_source_size;
  1964. } else {
  1965. return fd->cache[size]->underline_thickness;
  1966. }
  1967. }
  1968. void TextServerAdvanced::font_set_scale(const RID &p_font_rid, int64_t p_size, double p_scale) {
  1969. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1970. ERR_FAIL_COND(!fd);
  1971. MutexLock lock(fd->mutex);
  1972. Vector2i size = _get_size(fd, p_size);
  1973. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  1974. #ifdef MODULE_FREETYPE_ENABLED
  1975. if (fd->cache[size]->face) {
  1976. return; // Do not override scale for dynamic fonts, it's calculated automatically.
  1977. }
  1978. #endif
  1979. fd->cache[size]->scale = p_scale;
  1980. }
  1981. double TextServerAdvanced::font_get_scale(const RID &p_font_rid, int64_t p_size) const {
  1982. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1983. ERR_FAIL_COND_V(!fd, 0.0);
  1984. MutexLock lock(fd->mutex);
  1985. Vector2i size = _get_size(fd, p_size);
  1986. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), 0.0);
  1987. if (fd->msdf) {
  1988. return fd->cache[size]->scale * (double)p_size / (double)fd->msdf_source_size;
  1989. } else {
  1990. return fd->cache[size]->scale / fd->cache[size]->oversampling;
  1991. }
  1992. }
  1993. int64_t TextServerAdvanced::font_get_texture_count(const RID &p_font_rid, const Vector2i &p_size) const {
  1994. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  1995. ERR_FAIL_COND_V(!fd, 0);
  1996. MutexLock lock(fd->mutex);
  1997. Vector2i size = _get_size_outline(fd, p_size);
  1998. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), 0);
  1999. return fd->cache[size]->textures.size();
  2000. }
  2001. void TextServerAdvanced::font_clear_textures(const RID &p_font_rid, const Vector2i &p_size) {
  2002. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2003. ERR_FAIL_COND(!fd);
  2004. MutexLock lock(fd->mutex);
  2005. Vector2i size = _get_size_outline(fd, p_size);
  2006. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  2007. fd->cache[size]->textures.clear();
  2008. }
  2009. void TextServerAdvanced::font_remove_texture(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) {
  2010. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2011. ERR_FAIL_COND(!fd);
  2012. MutexLock lock(fd->mutex);
  2013. Vector2i size = _get_size_outline(fd, p_size);
  2014. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  2015. ERR_FAIL_INDEX(p_texture_index, fd->cache[size]->textures.size());
  2016. fd->cache[size]->textures.remove_at(p_texture_index);
  2017. }
  2018. void TextServerAdvanced::font_set_texture_image(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index, const Ref<Image> &p_image) {
  2019. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2020. ERR_FAIL_COND(!fd);
  2021. ERR_FAIL_COND(p_image.is_null());
  2022. MutexLock lock(fd->mutex);
  2023. Vector2i size = _get_size_outline(fd, p_size);
  2024. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  2025. ERR_FAIL_COND(p_texture_index < 0);
  2026. if (p_texture_index >= fd->cache[size]->textures.size()) {
  2027. fd->cache[size]->textures.resize(p_texture_index + 1);
  2028. }
  2029. FontTexture &tex = fd->cache[size]->textures.write[p_texture_index];
  2030. tex.imgdata = p_image->get_data();
  2031. tex.texture_w = p_image->get_width();
  2032. tex.texture_h = p_image->get_height();
  2033. tex.format = p_image->get_format();
  2034. Ref<Image> img;
  2035. img.instantiate();
  2036. img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
  2037. if (fd->mipmaps) {
  2038. img->generate_mipmaps();
  2039. }
  2040. tex.texture = ImageTexture::create_from_image(img);
  2041. tex.dirty = false;
  2042. }
  2043. Ref<Image> TextServerAdvanced::font_get_texture_image(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) const {
  2044. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2045. ERR_FAIL_COND_V(!fd, Ref<Image>());
  2046. MutexLock lock(fd->mutex);
  2047. Vector2i size = _get_size_outline(fd, p_size);
  2048. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), Ref<Image>());
  2049. ERR_FAIL_INDEX_V(p_texture_index, fd->cache[size]->textures.size(), Ref<Image>());
  2050. const FontTexture &tex = fd->cache[size]->textures[p_texture_index];
  2051. Ref<Image> img;
  2052. img.instantiate();
  2053. img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
  2054. return img;
  2055. }
  2056. void TextServerAdvanced::font_set_texture_offsets(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index, const PackedInt32Array &p_offset) {
  2057. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2058. ERR_FAIL_COND(!fd);
  2059. MutexLock lock(fd->mutex);
  2060. Vector2i size = _get_size_outline(fd, p_size);
  2061. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  2062. ERR_FAIL_COND(p_texture_index < 0);
  2063. if (p_texture_index >= fd->cache[size]->textures.size()) {
  2064. fd->cache[size]->textures.resize(p_texture_index + 1);
  2065. }
  2066. FontTexture &tex = fd->cache[size]->textures.write[p_texture_index];
  2067. tex.offsets = p_offset;
  2068. }
  2069. PackedInt32Array TextServerAdvanced::font_get_texture_offsets(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) const {
  2070. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2071. ERR_FAIL_COND_V(!fd, PackedInt32Array());
  2072. MutexLock lock(fd->mutex);
  2073. Vector2i size = _get_size_outline(fd, p_size);
  2074. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), PackedInt32Array());
  2075. ERR_FAIL_INDEX_V(p_texture_index, fd->cache[size]->textures.size(), PackedInt32Array());
  2076. const FontTexture &tex = fd->cache[size]->textures[p_texture_index];
  2077. return tex.offsets;
  2078. }
  2079. Array TextServerAdvanced::font_get_glyph_list(const RID &p_font_rid, const Vector2i &p_size) const {
  2080. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2081. ERR_FAIL_COND_V(!fd, Array());
  2082. MutexLock lock(fd->mutex);
  2083. Vector2i size = _get_size_outline(fd, p_size);
  2084. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), Array());
  2085. Array ret;
  2086. const HashMap<int32_t, FontGlyph> &gl = fd->cache[size]->glyph_map;
  2087. for (const KeyValue<int32_t, FontGlyph> &E : gl) {
  2088. ret.push_back(E.key);
  2089. }
  2090. return ret;
  2091. }
  2092. void TextServerAdvanced::font_clear_glyphs(const RID &p_font_rid, const Vector2i &p_size) {
  2093. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2094. ERR_FAIL_COND(!fd);
  2095. MutexLock lock(fd->mutex);
  2096. Vector2i size = _get_size_outline(fd, p_size);
  2097. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  2098. fd->cache[size]->glyph_map.clear();
  2099. }
  2100. void TextServerAdvanced::font_remove_glyph(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) {
  2101. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2102. ERR_FAIL_COND(!fd);
  2103. MutexLock lock(fd->mutex);
  2104. Vector2i size = _get_size_outline(fd, p_size);
  2105. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  2106. fd->cache[size]->glyph_map.erase(p_glyph);
  2107. }
  2108. double TextServerAdvanced::_get_extra_advance(RID p_font_rid, int p_font_size) const {
  2109. const FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2110. ERR_FAIL_COND_V(!fd, 0.0);
  2111. MutexLock lock(fd->mutex);
  2112. Vector2i size = _get_size(fd, p_font_size);
  2113. if (fd->embolden != 0.0) {
  2114. return fd->embolden * double(size.x) / 64.0;
  2115. } else {
  2116. return 0.0;
  2117. }
  2118. }
  2119. Vector2 TextServerAdvanced::font_get_glyph_advance(const RID &p_font_rid, int64_t p_size, int64_t p_glyph) const {
  2120. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2121. ERR_FAIL_COND_V(!fd, Vector2());
  2122. MutexLock lock(fd->mutex);
  2123. Vector2i size = _get_size(fd, p_size);
  2124. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), Vector2());
  2125. if (!_ensure_glyph(fd, size, p_glyph)) {
  2126. return Vector2(); // Invalid or non graphicl glyph, do not display errors.
  2127. }
  2128. const HashMap<int32_t, FontGlyph> &gl = fd->cache[size]->glyph_map;
  2129. Vector2 ea;
  2130. if (fd->embolden != 0.0) {
  2131. ea.x = fd->embolden * double(size.x) / 64.0;
  2132. }
  2133. if (fd->msdf) {
  2134. return (gl[p_glyph].advance + ea) * (double)p_size / (double)fd->msdf_source_size;
  2135. } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_DISABLED) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x > SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) {
  2136. return (gl[p_glyph].advance + ea).round();
  2137. } else {
  2138. return gl[p_glyph].advance + ea;
  2139. }
  2140. }
  2141. void TextServerAdvanced::font_set_glyph_advance(const RID &p_font_rid, int64_t p_size, int64_t p_glyph, const Vector2 &p_advance) {
  2142. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2143. ERR_FAIL_COND(!fd);
  2144. MutexLock lock(fd->mutex);
  2145. Vector2i size = _get_size(fd, p_size);
  2146. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  2147. HashMap<int32_t, FontGlyph> &gl = fd->cache[size]->glyph_map;
  2148. gl[p_glyph].advance = p_advance;
  2149. gl[p_glyph].found = true;
  2150. }
  2151. Vector2 TextServerAdvanced::font_get_glyph_offset(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const {
  2152. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2153. ERR_FAIL_COND_V(!fd, Vector2());
  2154. MutexLock lock(fd->mutex);
  2155. Vector2i size = _get_size_outline(fd, p_size);
  2156. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), Vector2());
  2157. if (!_ensure_glyph(fd, size, p_glyph)) {
  2158. return Vector2(); // Invalid or non graphicl glyph, do not display errors.
  2159. }
  2160. const HashMap<int32_t, FontGlyph> &gl = fd->cache[size]->glyph_map;
  2161. if (fd->msdf) {
  2162. return gl[p_glyph].rect.position * (double)p_size.x / (double)fd->msdf_source_size;
  2163. } else {
  2164. return gl[p_glyph].rect.position;
  2165. }
  2166. }
  2167. void TextServerAdvanced::font_set_glyph_offset(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, const Vector2 &p_offset) {
  2168. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2169. ERR_FAIL_COND(!fd);
  2170. MutexLock lock(fd->mutex);
  2171. Vector2i size = _get_size_outline(fd, p_size);
  2172. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  2173. HashMap<int32_t, FontGlyph> &gl = fd->cache[size]->glyph_map;
  2174. gl[p_glyph].rect.position = p_offset;
  2175. gl[p_glyph].found = true;
  2176. }
  2177. Vector2 TextServerAdvanced::font_get_glyph_size(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const {
  2178. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2179. ERR_FAIL_COND_V(!fd, Vector2());
  2180. MutexLock lock(fd->mutex);
  2181. Vector2i size = _get_size_outline(fd, p_size);
  2182. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), Vector2());
  2183. if (!_ensure_glyph(fd, size, p_glyph)) {
  2184. return Vector2(); // Invalid or non graphicl glyph, do not display errors.
  2185. }
  2186. const HashMap<int32_t, FontGlyph> &gl = fd->cache[size]->glyph_map;
  2187. if (fd->msdf) {
  2188. return gl[p_glyph].rect.size * (double)p_size.x / (double)fd->msdf_source_size;
  2189. } else {
  2190. return gl[p_glyph].rect.size;
  2191. }
  2192. }
  2193. void TextServerAdvanced::font_set_glyph_size(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, const Vector2 &p_gl_size) {
  2194. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2195. ERR_FAIL_COND(!fd);
  2196. MutexLock lock(fd->mutex);
  2197. Vector2i size = _get_size_outline(fd, p_size);
  2198. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  2199. HashMap<int32_t, FontGlyph> &gl = fd->cache[size]->glyph_map;
  2200. gl[p_glyph].rect.size = p_gl_size;
  2201. gl[p_glyph].found = true;
  2202. }
  2203. Rect2 TextServerAdvanced::font_get_glyph_uv_rect(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const {
  2204. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2205. ERR_FAIL_COND_V(!fd, Rect2());
  2206. MutexLock lock(fd->mutex);
  2207. Vector2i size = _get_size_outline(fd, p_size);
  2208. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), Rect2());
  2209. if (!_ensure_glyph(fd, size, p_glyph)) {
  2210. return Rect2(); // Invalid or non graphicl glyph, do not display errors.
  2211. }
  2212. const HashMap<int32_t, FontGlyph> &gl = fd->cache[size]->glyph_map;
  2213. return gl[p_glyph].uv_rect;
  2214. }
  2215. void TextServerAdvanced::font_set_glyph_uv_rect(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, const Rect2 &p_uv_rect) {
  2216. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2217. ERR_FAIL_COND(!fd);
  2218. MutexLock lock(fd->mutex);
  2219. Vector2i size = _get_size_outline(fd, p_size);
  2220. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  2221. HashMap<int32_t, FontGlyph> &gl = fd->cache[size]->glyph_map;
  2222. gl[p_glyph].uv_rect = p_uv_rect;
  2223. gl[p_glyph].found = true;
  2224. }
  2225. int64_t TextServerAdvanced::font_get_glyph_texture_idx(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const {
  2226. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2227. ERR_FAIL_COND_V(!fd, -1);
  2228. MutexLock lock(fd->mutex);
  2229. Vector2i size = _get_size_outline(fd, p_size);
  2230. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), -1);
  2231. if (!_ensure_glyph(fd, size, p_glyph)) {
  2232. return -1; // Invalid or non graphicl glyph, do not display errors.
  2233. }
  2234. const HashMap<int32_t, FontGlyph> &gl = fd->cache[size]->glyph_map;
  2235. return gl[p_glyph].texture_idx;
  2236. }
  2237. void TextServerAdvanced::font_set_glyph_texture_idx(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, int64_t p_texture_idx) {
  2238. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2239. ERR_FAIL_COND(!fd);
  2240. MutexLock lock(fd->mutex);
  2241. Vector2i size = _get_size_outline(fd, p_size);
  2242. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  2243. HashMap<int32_t, FontGlyph> &gl = fd->cache[size]->glyph_map;
  2244. gl[p_glyph].texture_idx = p_texture_idx;
  2245. gl[p_glyph].found = true;
  2246. }
  2247. RID TextServerAdvanced::font_get_glyph_texture_rid(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const {
  2248. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2249. ERR_FAIL_COND_V(!fd, RID());
  2250. MutexLock lock(fd->mutex);
  2251. Vector2i size = _get_size_outline(fd, p_size);
  2252. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), RID());
  2253. if (!_ensure_glyph(fd, size, p_glyph)) {
  2254. return RID(); // Invalid or non graphicl glyph, do not display errors.
  2255. }
  2256. const HashMap<int32_t, FontGlyph> &gl = fd->cache[size]->glyph_map;
  2257. ERR_FAIL_COND_V(gl[p_glyph].texture_idx < -1 || gl[p_glyph].texture_idx >= fd->cache[size]->textures.size(), RID());
  2258. if (RenderingServer::get_singleton() != nullptr) {
  2259. if (gl[p_glyph].texture_idx != -1) {
  2260. if (fd->cache[size]->textures[gl[p_glyph].texture_idx].dirty) {
  2261. FontTexture &tex = fd->cache[size]->textures.write[gl[p_glyph].texture_idx];
  2262. Ref<Image> img;
  2263. img.instantiate();
  2264. img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
  2265. if (fd->mipmaps) {
  2266. img->generate_mipmaps();
  2267. }
  2268. if (tex.texture.is_null()) {
  2269. tex.texture = ImageTexture::create_from_image(img);
  2270. } else {
  2271. tex.texture->update(img);
  2272. }
  2273. tex.dirty = false;
  2274. }
  2275. return fd->cache[size]->textures[gl[p_glyph].texture_idx].texture->get_rid();
  2276. }
  2277. }
  2278. return RID();
  2279. }
  2280. Size2 TextServerAdvanced::font_get_glyph_texture_size(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const {
  2281. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2282. ERR_FAIL_COND_V(!fd, Size2());
  2283. MutexLock lock(fd->mutex);
  2284. Vector2i size = _get_size_outline(fd, p_size);
  2285. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), Size2());
  2286. if (!_ensure_glyph(fd, size, p_glyph)) {
  2287. return Size2(); // Invalid or non graphicl glyph, do not display errors.
  2288. }
  2289. const HashMap<int32_t, FontGlyph> &gl = fd->cache[size]->glyph_map;
  2290. ERR_FAIL_COND_V(gl[p_glyph].texture_idx < -1 || gl[p_glyph].texture_idx >= fd->cache[size]->textures.size(), Size2());
  2291. if (RenderingServer::get_singleton() != nullptr) {
  2292. if (gl[p_glyph].texture_idx != -1) {
  2293. if (fd->cache[size]->textures[gl[p_glyph].texture_idx].dirty) {
  2294. FontTexture &tex = fd->cache[size]->textures.write[gl[p_glyph].texture_idx];
  2295. Ref<Image> img;
  2296. img.instantiate();
  2297. img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
  2298. if (fd->mipmaps) {
  2299. img->generate_mipmaps();
  2300. }
  2301. if (tex.texture.is_null()) {
  2302. tex.texture = ImageTexture::create_from_image(img);
  2303. } else {
  2304. tex.texture->update(img);
  2305. }
  2306. tex.dirty = false;
  2307. }
  2308. return fd->cache[size]->textures[gl[p_glyph].texture_idx].texture->get_size();
  2309. }
  2310. }
  2311. return Size2();
  2312. }
  2313. Dictionary TextServerAdvanced::font_get_glyph_contours(const RID &p_font_rid, int64_t p_size, int64_t p_index) const {
  2314. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2315. ERR_FAIL_COND_V(!fd, Dictionary());
  2316. MutexLock lock(fd->mutex);
  2317. Vector2i size = _get_size(fd, p_size);
  2318. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), Dictionary());
  2319. #ifdef MODULE_FREETYPE_ENABLED
  2320. PackedVector3Array points;
  2321. PackedInt32Array contours;
  2322. int32_t index = p_index & 0xffffff; // Remove subpixel shifts.
  2323. int error = FT_Load_Glyph(fd->cache[size]->face, index, FT_LOAD_NO_BITMAP | (fd->force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0));
  2324. ERR_FAIL_COND_V(error, Dictionary());
  2325. if (fd->embolden != 0.f) {
  2326. FT_Pos strength = fd->embolden * p_size * 4; // 26.6 fractional units (1 / 64).
  2327. FT_Outline_Embolden(&fd->cache[size]->face->glyph->outline, strength);
  2328. }
  2329. if (fd->transform != Transform2D()) {
  2330. FT_Matrix mat = { FT_Fixed(fd->transform[0][0] * 65536), FT_Fixed(fd->transform[0][1] * 65536), FT_Fixed(fd->transform[1][0] * 65536), FT_Fixed(fd->transform[1][1] * 65536) }; // 16.16 fractional units (1 / 65536).
  2331. FT_Outline_Transform(&fd->cache[size]->face->glyph->outline, &mat);
  2332. }
  2333. double scale = (1.0 / 64.0) / fd->cache[size]->oversampling * fd->cache[size]->scale;
  2334. if (fd->msdf) {
  2335. scale = scale * (double)p_size / (double)fd->msdf_source_size;
  2336. }
  2337. for (short i = 0; i < fd->cache[size]->face->glyph->outline.n_points; i++) {
  2338. points.push_back(Vector3(fd->cache[size]->face->glyph->outline.points[i].x * scale, -fd->cache[size]->face->glyph->outline.points[i].y * scale, FT_CURVE_TAG(fd->cache[size]->face->glyph->outline.tags[i])));
  2339. }
  2340. for (short i = 0; i < fd->cache[size]->face->glyph->outline.n_contours; i++) {
  2341. contours.push_back(fd->cache[size]->face->glyph->outline.contours[i]);
  2342. }
  2343. bool orientation = (FT_Outline_Get_Orientation(&fd->cache[size]->face->glyph->outline) == FT_ORIENTATION_FILL_RIGHT);
  2344. Dictionary out;
  2345. out["points"] = points;
  2346. out["contours"] = contours;
  2347. out["orientation"] = orientation;
  2348. return out;
  2349. #else
  2350. return Dictionary();
  2351. #endif
  2352. }
  2353. Array TextServerAdvanced::font_get_kerning_list(const RID &p_font_rid, int64_t p_size) const {
  2354. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2355. ERR_FAIL_COND_V(!fd, Array());
  2356. MutexLock lock(fd->mutex);
  2357. Vector2i size = _get_size(fd, p_size);
  2358. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), Array());
  2359. Array ret;
  2360. for (const KeyValue<Vector2i, FontForSizeAdvanced *> &E : fd->cache) {
  2361. ret.push_back(E.key);
  2362. }
  2363. return ret;
  2364. }
  2365. void TextServerAdvanced::font_clear_kerning_map(const RID &p_font_rid, int64_t p_size) {
  2366. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2367. ERR_FAIL_COND(!fd);
  2368. MutexLock lock(fd->mutex);
  2369. Vector2i size = _get_size(fd, p_size);
  2370. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  2371. fd->cache[size]->kerning_map.clear();
  2372. }
  2373. void TextServerAdvanced::font_remove_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair) {
  2374. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2375. ERR_FAIL_COND(!fd);
  2376. MutexLock lock(fd->mutex);
  2377. Vector2i size = _get_size(fd, p_size);
  2378. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  2379. fd->cache[size]->kerning_map.erase(p_glyph_pair);
  2380. }
  2381. void TextServerAdvanced::font_set_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair, const Vector2 &p_kerning) {
  2382. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2383. ERR_FAIL_COND(!fd);
  2384. MutexLock lock(fd->mutex);
  2385. Vector2i size = _get_size(fd, p_size);
  2386. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  2387. fd->cache[size]->kerning_map[p_glyph_pair] = p_kerning;
  2388. }
  2389. Vector2 TextServerAdvanced::font_get_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair) const {
  2390. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2391. ERR_FAIL_COND_V(!fd, Vector2());
  2392. MutexLock lock(fd->mutex);
  2393. Vector2i size = _get_size(fd, p_size);
  2394. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), Vector2());
  2395. const HashMap<Vector2i, Vector2> &kern = fd->cache[size]->kerning_map;
  2396. if (kern.has(p_glyph_pair)) {
  2397. if (fd->msdf) {
  2398. return kern[p_glyph_pair] * (double)p_size / (double)fd->msdf_source_size;
  2399. } else {
  2400. return kern[p_glyph_pair];
  2401. }
  2402. } else {
  2403. #ifdef MODULE_FREETYPE_ENABLED
  2404. if (fd->cache[size]->face) {
  2405. FT_Vector delta;
  2406. FT_Get_Kerning(fd->cache[size]->face, p_glyph_pair.x, p_glyph_pair.y, FT_KERNING_DEFAULT, &delta);
  2407. if (fd->msdf) {
  2408. return Vector2(delta.x, delta.y) * (double)p_size / (double)fd->msdf_source_size;
  2409. } else {
  2410. return Vector2(delta.x, delta.y);
  2411. }
  2412. }
  2413. #endif
  2414. }
  2415. return Vector2();
  2416. }
  2417. int64_t TextServerAdvanced::font_get_glyph_index(const RID &p_font_rid, int64_t p_size, int64_t p_char, int64_t p_variation_selector) const {
  2418. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2419. ERR_FAIL_COND_V(!fd, 0);
  2420. ERR_FAIL_COND_V_MSG((p_char >= 0xd800 && p_char <= 0xdfff) || (p_char > 0x10ffff), 0, "Unicode parsing error: Invalid unicode codepoint " + String::num_int64(p_char, 16) + ".");
  2421. ERR_FAIL_COND_V_MSG((p_variation_selector >= 0xd800 && p_variation_selector <= 0xdfff) || (p_variation_selector > 0x10ffff), 0, "Unicode parsing error: Invalid unicode codepoint " + String::num_int64(p_variation_selector, 16) + ".");
  2422. MutexLock lock(fd->mutex);
  2423. Vector2i size = _get_size(fd, p_size);
  2424. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), 0);
  2425. #ifdef MODULE_FREETYPE_ENABLED
  2426. if (fd->cache[size]->face) {
  2427. if (p_variation_selector) {
  2428. return FT_Face_GetCharVariantIndex(fd->cache[size]->face, p_char, p_variation_selector);
  2429. } else {
  2430. return FT_Get_Char_Index(fd->cache[size]->face, p_char);
  2431. }
  2432. } else {
  2433. return (int64_t)p_char;
  2434. }
  2435. #else
  2436. return (int64_t)p_char;
  2437. #endif
  2438. }
  2439. bool TextServerAdvanced::font_has_char(const RID &p_font_rid, int64_t p_char) const {
  2440. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2441. ERR_FAIL_COND_V(!fd, false);
  2442. ERR_FAIL_COND_V_MSG((p_char >= 0xd800 && p_char <= 0xdfff) || (p_char > 0x10ffff), false, "Unicode parsing error: Invalid unicode codepoint " + String::num_int64(p_char, 16) + ".");
  2443. MutexLock lock(fd->mutex);
  2444. if (fd->cache.is_empty()) {
  2445. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, fd->msdf ? Vector2i(fd->msdf_source_size, 0) : Vector2i(16, 0)), false);
  2446. }
  2447. FontForSizeAdvanced *at_size = fd->cache.begin()->value;
  2448. #ifdef MODULE_FREETYPE_ENABLED
  2449. if (at_size && at_size->face) {
  2450. return FT_Get_Char_Index(at_size->face, p_char) != 0;
  2451. }
  2452. #endif
  2453. return (at_size) ? at_size->glyph_map.has((int32_t)p_char) : false;
  2454. }
  2455. String TextServerAdvanced::font_get_supported_chars(const RID &p_font_rid) const {
  2456. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2457. ERR_FAIL_COND_V(!fd, String());
  2458. MutexLock lock(fd->mutex);
  2459. if (fd->cache.is_empty()) {
  2460. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, fd->msdf ? Vector2i(fd->msdf_source_size, 0) : Vector2i(16, 0)), String());
  2461. }
  2462. FontForSizeAdvanced *at_size = fd->cache.begin()->value;
  2463. String chars;
  2464. #ifdef MODULE_FREETYPE_ENABLED
  2465. if (at_size && at_size->face) {
  2466. FT_UInt gindex;
  2467. FT_ULong charcode = FT_Get_First_Char(at_size->face, &gindex);
  2468. while (gindex != 0) {
  2469. if (charcode != 0) {
  2470. chars = chars + String::chr(charcode);
  2471. }
  2472. charcode = FT_Get_Next_Char(at_size->face, charcode, &gindex);
  2473. }
  2474. return chars;
  2475. }
  2476. #endif
  2477. if (at_size) {
  2478. const HashMap<int32_t, FontGlyph> &gl = at_size->glyph_map;
  2479. for (const KeyValue<int32_t, FontGlyph> &E : gl) {
  2480. chars = chars + String::chr(E.key);
  2481. }
  2482. }
  2483. return chars;
  2484. }
  2485. void TextServerAdvanced::font_render_range(const RID &p_font_rid, const Vector2i &p_size, int64_t p_start, int64_t p_end) {
  2486. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2487. ERR_FAIL_COND(!fd);
  2488. ERR_FAIL_COND_MSG((p_start >= 0xd800 && p_start <= 0xdfff) || (p_start > 0x10ffff), "Unicode parsing error: Invalid unicode codepoint " + String::num_int64(p_start, 16) + ".");
  2489. ERR_FAIL_COND_MSG((p_end >= 0xd800 && p_end <= 0xdfff) || (p_end > 0x10ffff), "Unicode parsing error: Invalid unicode codepoint " + String::num_int64(p_end, 16) + ".");
  2490. MutexLock lock(fd->mutex);
  2491. Vector2i size = _get_size_outline(fd, p_size);
  2492. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  2493. for (int64_t i = p_start; i <= p_end; i++) {
  2494. #ifdef MODULE_FREETYPE_ENABLED
  2495. int32_t idx = FT_Get_Char_Index(fd->cache[size]->face, i);
  2496. if (fd->cache[size]->face) {
  2497. if (fd->msdf) {
  2498. _ensure_glyph(fd, size, (int32_t)idx);
  2499. } else {
  2500. if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE)) {
  2501. _ensure_glyph(fd, size, (int32_t)idx | (0 << 27));
  2502. _ensure_glyph(fd, size, (int32_t)idx | (1 << 27));
  2503. _ensure_glyph(fd, size, (int32_t)idx | (2 << 27));
  2504. _ensure_glyph(fd, size, (int32_t)idx | (3 << 27));
  2505. } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) {
  2506. _ensure_glyph(fd, size, (int32_t)idx | (1 << 27));
  2507. _ensure_glyph(fd, size, (int32_t)idx | (0 << 27));
  2508. } else {
  2509. _ensure_glyph(fd, size, (int32_t)idx);
  2510. }
  2511. }
  2512. }
  2513. #endif
  2514. }
  2515. }
  2516. void TextServerAdvanced::font_render_glyph(const RID &p_font_rid, const Vector2i &p_size, int64_t p_index) {
  2517. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2518. ERR_FAIL_COND(!fd);
  2519. MutexLock lock(fd->mutex);
  2520. Vector2i size = _get_size_outline(fd, p_size);
  2521. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  2522. #ifdef MODULE_FREETYPE_ENABLED
  2523. int32_t idx = p_index & 0xffffff; // Remove subpixel shifts.
  2524. if (fd->cache[size]->face) {
  2525. if (fd->msdf) {
  2526. _ensure_glyph(fd, size, (int32_t)idx);
  2527. } else {
  2528. if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE)) {
  2529. _ensure_glyph(fd, size, (int32_t)idx | (0 << 27));
  2530. _ensure_glyph(fd, size, (int32_t)idx | (1 << 27));
  2531. _ensure_glyph(fd, size, (int32_t)idx | (2 << 27));
  2532. _ensure_glyph(fd, size, (int32_t)idx | (3 << 27));
  2533. } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) {
  2534. _ensure_glyph(fd, size, (int32_t)idx | (1 << 27));
  2535. _ensure_glyph(fd, size, (int32_t)idx | (0 << 27));
  2536. } else {
  2537. _ensure_glyph(fd, size, (int32_t)idx);
  2538. }
  2539. }
  2540. }
  2541. #endif
  2542. }
  2543. void TextServerAdvanced::font_draw_glyph(const RID &p_font_rid, const RID &p_canvas, int64_t p_size, const Vector2 &p_pos, int64_t p_index, const Color &p_color) const {
  2544. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2545. ERR_FAIL_COND(!fd);
  2546. MutexLock lock(fd->mutex);
  2547. Vector2i size = _get_size(fd, p_size);
  2548. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  2549. int32_t index = p_index & 0xffffff; // Remove subpixel shifts.
  2550. #ifdef MODULE_FREETYPE_ENABLED
  2551. if (!fd->msdf && fd->cache[size]->face) {
  2552. if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE)) {
  2553. int xshift = (int)(Math::floor(4 * (p_pos.x + 0.125)) - 4 * Math::floor(p_pos.x + 0.125));
  2554. index = index | (xshift << 27);
  2555. } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) {
  2556. int xshift = (int)(Math::floor(2 * (p_pos.x + 0.25)) - 2 * Math::floor(p_pos.x + 0.25));
  2557. index = index | (xshift << 27);
  2558. }
  2559. }
  2560. #endif
  2561. if (!_ensure_glyph(fd, size, index)) {
  2562. return; // Invalid or non-graphical glyph, do not display errors, nothing to draw.
  2563. }
  2564. const FontGlyph &gl = fd->cache[size]->glyph_map[index];
  2565. if (gl.found) {
  2566. ERR_FAIL_COND(gl.texture_idx < -1 || gl.texture_idx >= fd->cache[size]->textures.size());
  2567. if (gl.texture_idx != -1) {
  2568. Color modulate = p_color;
  2569. #ifdef MODULE_FREETYPE_ENABLED
  2570. if (fd->cache[size]->face && FT_HAS_COLOR(fd->cache[size]->face)) {
  2571. modulate.r = modulate.g = modulate.b = 1.0;
  2572. }
  2573. #endif
  2574. if (RenderingServer::get_singleton() != nullptr) {
  2575. if (fd->cache[size]->textures[gl.texture_idx].dirty) {
  2576. FontTexture &tex = fd->cache[size]->textures.write[gl.texture_idx];
  2577. Ref<Image> img;
  2578. img.instantiate();
  2579. img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
  2580. if (fd->mipmaps) {
  2581. img->generate_mipmaps();
  2582. }
  2583. if (tex.texture.is_null()) {
  2584. tex.texture = ImageTexture::create_from_image(img);
  2585. } else {
  2586. tex.texture->update(img);
  2587. }
  2588. tex.dirty = false;
  2589. }
  2590. RID texture = fd->cache[size]->textures[gl.texture_idx].texture->get_rid();
  2591. if (fd->msdf) {
  2592. Point2 cpos = p_pos;
  2593. cpos += gl.rect.position * (double)p_size / (double)fd->msdf_source_size;
  2594. Size2 csize = gl.rect.size * (double)p_size / (double)fd->msdf_source_size;
  2595. RenderingServer::get_singleton()->canvas_item_add_msdf_texture_rect_region(p_canvas, Rect2(cpos, csize), texture, gl.uv_rect, modulate, 0, fd->msdf_range);
  2596. } else {
  2597. Point2 cpos = p_pos;
  2598. cpos.y = Math::floor(cpos.y);
  2599. if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE)) {
  2600. cpos.x = ((int)Math::floor(cpos.x + 0.125));
  2601. } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) {
  2602. cpos.x = ((int)Math::floor(cpos.x + 0.25));
  2603. } else {
  2604. cpos.x = Math::floor(cpos.x);
  2605. }
  2606. cpos += gl.rect.position;
  2607. Size2 csize = gl.rect.size;
  2608. RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, Rect2(cpos, csize), texture, gl.uv_rect, modulate, false, false);
  2609. }
  2610. }
  2611. }
  2612. }
  2613. }
  2614. void TextServerAdvanced::font_draw_glyph_outline(const RID &p_font_rid, const RID &p_canvas, int64_t p_size, int64_t p_outline_size, const Vector2 &p_pos, int64_t p_index, const Color &p_color) const {
  2615. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2616. ERR_FAIL_COND(!fd);
  2617. MutexLock lock(fd->mutex);
  2618. Vector2i size = _get_size_outline(fd, Vector2i(p_size, p_outline_size));
  2619. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  2620. int32_t index = p_index & 0xffffff; // Remove subpixel shifts.
  2621. #ifdef MODULE_FREETYPE_ENABLED
  2622. if (!fd->msdf && fd->cache[size]->face) {
  2623. if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE)) {
  2624. int xshift = (int)(Math::floor(4 * (p_pos.x + 0.125)) - 4 * Math::floor(p_pos.x + 0.125));
  2625. index = index | (xshift << 27);
  2626. } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) {
  2627. int xshift = (int)(Math::floor(2 * (p_pos.x + 0.25)) - 2 * Math::floor(p_pos.x + 0.25));
  2628. index = index | (xshift << 27);
  2629. }
  2630. }
  2631. #endif
  2632. if (!_ensure_glyph(fd, size, index)) {
  2633. return; // Invalid or non-graphical glyph, do not display errors, nothing to draw.
  2634. }
  2635. const FontGlyph &gl = fd->cache[size]->glyph_map[index];
  2636. if (gl.found) {
  2637. ERR_FAIL_COND(gl.texture_idx < -1 || gl.texture_idx >= fd->cache[size]->textures.size());
  2638. if (gl.texture_idx != -1) {
  2639. Color modulate = p_color;
  2640. #ifdef MODULE_FREETYPE_ENABLED
  2641. if (fd->cache[size]->face && FT_HAS_COLOR(fd->cache[size]->face)) {
  2642. modulate.r = modulate.g = modulate.b = 1.0;
  2643. }
  2644. #endif
  2645. if (RenderingServer::get_singleton() != nullptr) {
  2646. if (fd->cache[size]->textures[gl.texture_idx].dirty) {
  2647. FontTexture &tex = fd->cache[size]->textures.write[gl.texture_idx];
  2648. Ref<Image> img;
  2649. img.instantiate();
  2650. img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata);
  2651. if (fd->mipmaps) {
  2652. img->generate_mipmaps();
  2653. }
  2654. if (tex.texture.is_null()) {
  2655. tex.texture = ImageTexture::create_from_image(img);
  2656. } else {
  2657. tex.texture->update(img);
  2658. }
  2659. tex.dirty = false;
  2660. }
  2661. RID texture = fd->cache[size]->textures[gl.texture_idx].texture->get_rid();
  2662. if (fd->msdf) {
  2663. Point2 cpos = p_pos;
  2664. cpos += gl.rect.position * (double)p_size / (double)fd->msdf_source_size;
  2665. Size2 csize = gl.rect.size * (double)p_size / (double)fd->msdf_source_size;
  2666. RenderingServer::get_singleton()->canvas_item_add_msdf_texture_rect_region(p_canvas, Rect2(cpos, csize), texture, gl.uv_rect, modulate, p_outline_size * 2, fd->msdf_range);
  2667. } else {
  2668. Point2 cpos = p_pos;
  2669. cpos.y = Math::floor(cpos.y);
  2670. if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE)) {
  2671. cpos.x = ((int)Math::floor(cpos.x + 0.125));
  2672. } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE)) {
  2673. cpos.x = ((int)Math::floor(cpos.x + 0.25));
  2674. } else {
  2675. cpos.x = Math::floor(cpos.x);
  2676. }
  2677. cpos += gl.rect.position;
  2678. Size2 csize = gl.rect.size;
  2679. RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, Rect2(cpos, csize), texture, gl.uv_rect, modulate, false, false);
  2680. }
  2681. }
  2682. }
  2683. }
  2684. }
  2685. bool TextServerAdvanced::font_is_language_supported(const RID &p_font_rid, const String &p_language) const {
  2686. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2687. ERR_FAIL_COND_V(!fd, false);
  2688. MutexLock lock(fd->mutex);
  2689. if (fd->language_support_overrides.has(p_language)) {
  2690. return fd->language_support_overrides[p_language];
  2691. } else {
  2692. return true;
  2693. }
  2694. }
  2695. void TextServerAdvanced::font_set_language_support_override(const RID &p_font_rid, const String &p_language, bool p_supported) {
  2696. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2697. ERR_FAIL_COND(!fd);
  2698. MutexLock lock(fd->mutex);
  2699. fd->language_support_overrides[p_language] = p_supported;
  2700. }
  2701. bool TextServerAdvanced::font_get_language_support_override(const RID &p_font_rid, const String &p_language) {
  2702. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2703. ERR_FAIL_COND_V(!fd, false);
  2704. MutexLock lock(fd->mutex);
  2705. return fd->language_support_overrides[p_language];
  2706. }
  2707. void TextServerAdvanced::font_remove_language_support_override(const RID &p_font_rid, const String &p_language) {
  2708. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2709. ERR_FAIL_COND(!fd);
  2710. MutexLock lock(fd->mutex);
  2711. fd->language_support_overrides.erase(p_language);
  2712. }
  2713. PackedStringArray TextServerAdvanced::font_get_language_support_overrides(const RID &p_font_rid) {
  2714. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2715. ERR_FAIL_COND_V(!fd, PackedStringArray());
  2716. MutexLock lock(fd->mutex);
  2717. PackedStringArray out;
  2718. for (const KeyValue<String, bool> &E : fd->language_support_overrides) {
  2719. out.push_back(E.key);
  2720. }
  2721. return out;
  2722. }
  2723. bool TextServerAdvanced::font_is_script_supported(const RID &p_font_rid, const String &p_script) const {
  2724. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2725. ERR_FAIL_COND_V(!fd, false);
  2726. MutexLock lock(fd->mutex);
  2727. if (fd->script_support_overrides.has(p_script)) {
  2728. return fd->script_support_overrides[p_script];
  2729. } else {
  2730. Vector2i size = _get_size(fd, 16);
  2731. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), false);
  2732. return fd->supported_scripts.has(hb_tag_from_string(p_script.ascii().get_data(), -1));
  2733. }
  2734. }
  2735. void TextServerAdvanced::font_set_script_support_override(const RID &p_font_rid, const String &p_script, bool p_supported) {
  2736. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2737. ERR_FAIL_COND(!fd);
  2738. MutexLock lock(fd->mutex);
  2739. fd->script_support_overrides[p_script] = p_supported;
  2740. }
  2741. bool TextServerAdvanced::font_get_script_support_override(const RID &p_font_rid, const String &p_script) {
  2742. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2743. ERR_FAIL_COND_V(!fd, false);
  2744. MutexLock lock(fd->mutex);
  2745. return fd->script_support_overrides[p_script];
  2746. }
  2747. void TextServerAdvanced::font_remove_script_support_override(const RID &p_font_rid, const String &p_script) {
  2748. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2749. ERR_FAIL_COND(!fd);
  2750. MutexLock lock(fd->mutex);
  2751. fd->script_support_overrides.erase(p_script);
  2752. }
  2753. PackedStringArray TextServerAdvanced::font_get_script_support_overrides(const RID &p_font_rid) {
  2754. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2755. ERR_FAIL_COND_V(!fd, PackedStringArray());
  2756. MutexLock lock(fd->mutex);
  2757. PackedStringArray out;
  2758. for (const KeyValue<String, bool> &E : fd->script_support_overrides) {
  2759. out.push_back(E.key);
  2760. }
  2761. return out;
  2762. }
  2763. void TextServerAdvanced::font_set_opentype_feature_overrides(const RID &p_font_rid, const Dictionary &p_overrides) {
  2764. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2765. ERR_FAIL_COND(!fd);
  2766. MutexLock lock(fd->mutex);
  2767. Vector2i size = _get_size(fd, 16);
  2768. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size));
  2769. fd->feature_overrides = p_overrides;
  2770. }
  2771. Dictionary TextServerAdvanced::font_get_opentype_feature_overrides(const RID &p_font_rid) const {
  2772. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2773. ERR_FAIL_COND_V(!fd, Dictionary());
  2774. MutexLock lock(fd->mutex);
  2775. return fd->feature_overrides;
  2776. }
  2777. Dictionary TextServerAdvanced::font_supported_feature_list(const RID &p_font_rid) const {
  2778. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2779. ERR_FAIL_COND_V(!fd, Dictionary());
  2780. MutexLock lock(fd->mutex);
  2781. Vector2i size = _get_size(fd, 16);
  2782. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), Dictionary());
  2783. return fd->supported_features;
  2784. }
  2785. Dictionary TextServerAdvanced::font_supported_variation_list(const RID &p_font_rid) const {
  2786. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2787. ERR_FAIL_COND_V(!fd, Dictionary());
  2788. MutexLock lock(fd->mutex);
  2789. Vector2i size = _get_size(fd, 16);
  2790. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), Dictionary());
  2791. return fd->supported_varaitions;
  2792. }
  2793. double TextServerAdvanced::font_get_global_oversampling() const {
  2794. return oversampling;
  2795. }
  2796. void TextServerAdvanced::font_set_global_oversampling(double p_oversampling) {
  2797. _THREAD_SAFE_METHOD_
  2798. if (oversampling != p_oversampling) {
  2799. oversampling = p_oversampling;
  2800. List<RID> fonts;
  2801. font_owner.get_owned_list(&fonts);
  2802. bool font_cleared = false;
  2803. for (const RID &E : fonts) {
  2804. if (!font_is_multichannel_signed_distance_field(E) && font_get_oversampling(E) <= 0) {
  2805. font_clear_size_cache(E);
  2806. font_cleared = true;
  2807. }
  2808. }
  2809. if (font_cleared) {
  2810. List<RID> text_bufs;
  2811. shaped_owner.get_owned_list(&text_bufs);
  2812. for (const RID &E : text_bufs) {
  2813. invalidate(shaped_owner.get_or_null(E), false);
  2814. }
  2815. }
  2816. }
  2817. }
  2818. /*************************************************************************/
  2819. /* Shaped text buffer interface */
  2820. /*************************************************************************/
  2821. int64_t TextServerAdvanced::_convert_pos(const String &p_utf32, const Char16String &p_utf16, int64_t p_pos) const {
  2822. int64_t limit = p_pos;
  2823. if (p_utf32.length() != p_utf16.length()) {
  2824. const UChar *data = p_utf16.get_data();
  2825. for (int i = 0; i < p_pos; i++) {
  2826. if (U16_IS_LEAD(data[i])) {
  2827. limit--;
  2828. }
  2829. }
  2830. }
  2831. return limit;
  2832. }
  2833. int64_t TextServerAdvanced::_convert_pos(const ShapedTextDataAdvanced *p_sd, int64_t p_pos) const {
  2834. int64_t limit = p_pos;
  2835. if (p_sd->text.length() != p_sd->utf16.length()) {
  2836. const UChar *data = p_sd->utf16.get_data();
  2837. for (int i = 0; i < p_pos; i++) {
  2838. if (U16_IS_LEAD(data[i])) {
  2839. limit--;
  2840. }
  2841. }
  2842. }
  2843. return limit;
  2844. }
  2845. int64_t TextServerAdvanced::_convert_pos_inv(const ShapedTextDataAdvanced *p_sd, int64_t p_pos) const {
  2846. int64_t limit = p_pos;
  2847. if (p_sd->text.length() != p_sd->utf16.length()) {
  2848. for (int i = 0; i < p_pos; i++) {
  2849. if (p_sd->text[i] > 0xffff) {
  2850. limit++;
  2851. }
  2852. }
  2853. }
  2854. return limit;
  2855. }
  2856. void TextServerAdvanced::invalidate(TextServerAdvanced::ShapedTextDataAdvanced *p_shaped, bool p_text) {
  2857. p_shaped->valid = false;
  2858. p_shaped->sort_valid = false;
  2859. p_shaped->line_breaks_valid = false;
  2860. p_shaped->justification_ops_valid = false;
  2861. p_shaped->text_trimmed = false;
  2862. p_shaped->ascent = 0.0;
  2863. p_shaped->descent = 0.0;
  2864. p_shaped->width = 0.0;
  2865. p_shaped->upos = 0.0;
  2866. p_shaped->uthk = 0.0;
  2867. p_shaped->glyphs.clear();
  2868. p_shaped->glyphs_logical.clear();
  2869. p_shaped->overrun_trim_data = TrimData();
  2870. p_shaped->utf16 = Char16String();
  2871. for (int i = 0; i < p_shaped->bidi_iter.size(); i++) {
  2872. ubidi_close(p_shaped->bidi_iter[i]);
  2873. }
  2874. p_shaped->bidi_iter.clear();
  2875. if (p_text) {
  2876. if (p_shaped->script_iter != nullptr) {
  2877. memdelete(p_shaped->script_iter);
  2878. p_shaped->script_iter = nullptr;
  2879. }
  2880. p_shaped->break_ops_valid = false;
  2881. p_shaped->js_ops_valid = false;
  2882. }
  2883. }
  2884. void TextServerAdvanced::full_copy(ShapedTextDataAdvanced *p_shaped) {
  2885. ShapedTextDataAdvanced *parent = shaped_owner.get_or_null(p_shaped->parent);
  2886. for (const KeyValue<Variant, ShapedTextDataAdvanced::EmbeddedObject> &E : parent->objects) {
  2887. if (E.value.pos >= p_shaped->start && E.value.pos < p_shaped->end) {
  2888. p_shaped->objects[E.key] = E.value;
  2889. }
  2890. }
  2891. for (int i = 0; i < parent->spans.size(); i++) {
  2892. ShapedTextDataAdvanced::Span span = parent->spans[i];
  2893. if (span.start >= p_shaped->end || span.end <= p_shaped->start) {
  2894. continue;
  2895. }
  2896. span.start = MAX(p_shaped->start, span.start);
  2897. span.end = MIN(p_shaped->end, span.end);
  2898. p_shaped->spans.push_back(span);
  2899. }
  2900. p_shaped->parent = RID();
  2901. }
  2902. RID TextServerAdvanced::create_shaped_text(TextServer::Direction p_direction, TextServer::Orientation p_orientation) {
  2903. _THREAD_SAFE_METHOD_
  2904. ShapedTextDataAdvanced *sd = memnew(ShapedTextDataAdvanced);
  2905. sd->hb_buffer = hb_buffer_create();
  2906. sd->direction = p_direction;
  2907. sd->orientation = p_orientation;
  2908. return shaped_owner.make_rid(sd);
  2909. }
  2910. void TextServerAdvanced::shaped_text_clear(const RID &p_shaped) {
  2911. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  2912. ERR_FAIL_COND(!sd);
  2913. MutexLock lock(sd->mutex);
  2914. sd->parent = RID();
  2915. sd->start = 0;
  2916. sd->end = 0;
  2917. sd->text = String();
  2918. sd->spans.clear();
  2919. sd->objects.clear();
  2920. sd->bidi_override.clear();
  2921. invalidate(sd, true);
  2922. }
  2923. void TextServerAdvanced::shaped_text_set_direction(const RID &p_shaped, TextServer::Direction p_direction) {
  2924. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  2925. ERR_FAIL_COND(!sd);
  2926. MutexLock lock(sd->mutex);
  2927. if (sd->direction != p_direction) {
  2928. if (sd->parent != RID()) {
  2929. full_copy(sd);
  2930. }
  2931. sd->direction = p_direction;
  2932. invalidate(sd, false);
  2933. }
  2934. }
  2935. TextServer::Direction TextServerAdvanced::shaped_text_get_direction(const RID &p_shaped) const {
  2936. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  2937. ERR_FAIL_COND_V(!sd, TextServer::DIRECTION_LTR);
  2938. MutexLock lock(sd->mutex);
  2939. return sd->direction;
  2940. }
  2941. TextServer::Direction TextServerAdvanced::shaped_text_get_inferred_direction(const RID &p_shaped) const {
  2942. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  2943. ERR_FAIL_COND_V(!sd, TextServer::DIRECTION_LTR);
  2944. MutexLock lock(sd->mutex);
  2945. return sd->para_direction;
  2946. }
  2947. void TextServerAdvanced::shaped_text_set_custom_punctuation(const RID &p_shaped, const String &p_punct) {
  2948. _THREAD_SAFE_METHOD_
  2949. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  2950. ERR_FAIL_COND(!sd);
  2951. if (sd->custom_punct != p_punct) {
  2952. if (sd->parent != RID()) {
  2953. full_copy(sd);
  2954. }
  2955. sd->custom_punct = p_punct;
  2956. invalidate(sd, false);
  2957. }
  2958. }
  2959. String TextServerAdvanced::shaped_text_get_custom_punctuation(const RID &p_shaped) const {
  2960. _THREAD_SAFE_METHOD_
  2961. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  2962. ERR_FAIL_COND_V(!sd, String());
  2963. return sd->custom_punct;
  2964. }
  2965. void TextServerAdvanced::shaped_text_set_bidi_override(const RID &p_shaped, const Array &p_override) {
  2966. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  2967. ERR_FAIL_COND(!sd);
  2968. MutexLock lock(sd->mutex);
  2969. if (sd->parent != RID()) {
  2970. full_copy(sd);
  2971. }
  2972. sd->bidi_override.clear();
  2973. for (int i = 0; i < p_override.size(); i++) {
  2974. if (p_override[i].get_type() == Variant::VECTOR2I) {
  2975. sd->bidi_override.push_back(p_override[i]);
  2976. }
  2977. }
  2978. invalidate(sd, false);
  2979. }
  2980. void TextServerAdvanced::shaped_text_set_orientation(const RID &p_shaped, TextServer::Orientation p_orientation) {
  2981. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  2982. ERR_FAIL_COND(!sd);
  2983. MutexLock lock(sd->mutex);
  2984. if (sd->orientation != p_orientation) {
  2985. if (sd->parent != RID()) {
  2986. full_copy(sd);
  2987. }
  2988. sd->orientation = p_orientation;
  2989. invalidate(sd, false);
  2990. }
  2991. }
  2992. void TextServerAdvanced::shaped_text_set_preserve_invalid(const RID &p_shaped, bool p_enabled) {
  2993. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  2994. ERR_FAIL_COND(!sd);
  2995. MutexLock lock(sd->mutex);
  2996. ERR_FAIL_COND(sd->parent != RID());
  2997. if (sd->preserve_invalid != p_enabled) {
  2998. sd->preserve_invalid = p_enabled;
  2999. invalidate(sd, false);
  3000. }
  3001. }
  3002. bool TextServerAdvanced::shaped_text_get_preserve_invalid(const RID &p_shaped) const {
  3003. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3004. ERR_FAIL_COND_V(!sd, false);
  3005. MutexLock lock(sd->mutex);
  3006. return sd->preserve_invalid;
  3007. }
  3008. void TextServerAdvanced::shaped_text_set_preserve_control(const RID &p_shaped, bool p_enabled) {
  3009. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3010. ERR_FAIL_COND(!sd);
  3011. MutexLock lock(sd->mutex);
  3012. if (sd->preserve_control != p_enabled) {
  3013. if (sd->parent != RID()) {
  3014. full_copy(sd);
  3015. }
  3016. sd->preserve_control = p_enabled;
  3017. invalidate(sd, false);
  3018. }
  3019. }
  3020. bool TextServerAdvanced::shaped_text_get_preserve_control(const RID &p_shaped) const {
  3021. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3022. ERR_FAIL_COND_V(!sd, false);
  3023. MutexLock lock(sd->mutex);
  3024. return sd->preserve_control;
  3025. }
  3026. void TextServerAdvanced::shaped_text_set_spacing(const RID &p_shaped, SpacingType p_spacing, int64_t p_value) {
  3027. ERR_FAIL_INDEX((int)p_spacing, 4);
  3028. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3029. ERR_FAIL_COND(!sd);
  3030. MutexLock lock(sd->mutex);
  3031. if (sd->extra_spacing[p_spacing] != p_value) {
  3032. if (sd->parent != RID()) {
  3033. full_copy(sd);
  3034. }
  3035. sd->extra_spacing[p_spacing] = p_value;
  3036. invalidate(sd, false);
  3037. }
  3038. }
  3039. int64_t TextServerAdvanced::shaped_text_get_spacing(const RID &p_shaped, SpacingType p_spacing) const {
  3040. ERR_FAIL_INDEX_V((int)p_spacing, 4, 0);
  3041. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3042. ERR_FAIL_COND_V(!sd, 0);
  3043. MutexLock lock(sd->mutex);
  3044. return sd->extra_spacing[p_spacing];
  3045. }
  3046. TextServer::Orientation TextServerAdvanced::shaped_text_get_orientation(const RID &p_shaped) const {
  3047. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3048. ERR_FAIL_COND_V(!sd, TextServer::ORIENTATION_HORIZONTAL);
  3049. MutexLock lock(sd->mutex);
  3050. return sd->orientation;
  3051. }
  3052. int64_t TextServerAdvanced::shaped_get_span_count(const RID &p_shaped) const {
  3053. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3054. ERR_FAIL_COND_V(!sd, 0);
  3055. return sd->spans.size();
  3056. }
  3057. Variant TextServerAdvanced::shaped_get_span_meta(const RID &p_shaped, int64_t p_index) const {
  3058. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3059. ERR_FAIL_COND_V(!sd, Variant());
  3060. ERR_FAIL_INDEX_V(p_index, sd->spans.size(), Variant());
  3061. return sd->spans[p_index].meta;
  3062. }
  3063. void TextServerAdvanced::shaped_set_span_update_font(const RID &p_shaped, int64_t p_index, const Array &p_fonts, int64_t p_size, const Dictionary &p_opentype_features) {
  3064. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3065. ERR_FAIL_COND(!sd);
  3066. ERR_FAIL_INDEX(p_index, sd->spans.size());
  3067. ShapedTextDataAdvanced::Span &span = sd->spans.ptrw()[p_index];
  3068. bool changed = (span.font_size != p_size) || (span.features != p_opentype_features) || (p_fonts.size() != span.fonts.size());
  3069. if (!changed) {
  3070. for (int i = 0; i < p_fonts.size(); i++) {
  3071. changed = changed || (span.fonts[i] != p_fonts[i]);
  3072. }
  3073. }
  3074. if (changed) {
  3075. span.fonts = p_fonts;
  3076. span.font_size = p_size;
  3077. span.features = p_opentype_features;
  3078. invalidate(sd, false);
  3079. }
  3080. }
  3081. bool TextServerAdvanced::shaped_text_add_string(const RID &p_shaped, const String &p_text, const Array &p_fonts, int64_t p_size, const Dictionary &p_opentype_features, const String &p_language, const Variant &p_meta) {
  3082. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3083. ERR_FAIL_COND_V(!sd, false);
  3084. ERR_FAIL_COND_V(p_size <= 0, false);
  3085. MutexLock lock(sd->mutex);
  3086. for (int i = 0; i < p_fonts.size(); i++) {
  3087. ERR_FAIL_COND_V(!font_owner.get_or_null(p_fonts[i]), false);
  3088. }
  3089. if (p_text.is_empty()) {
  3090. return true;
  3091. }
  3092. if (sd->parent != RID()) {
  3093. full_copy(sd);
  3094. }
  3095. ShapedTextDataAdvanced::Span span;
  3096. span.start = sd->text.length();
  3097. span.end = span.start + p_text.length();
  3098. span.fonts = p_fonts; // Do not pre-sort, spans will be divided to subruns later.
  3099. span.font_size = p_size;
  3100. span.language = p_language;
  3101. span.features = p_opentype_features;
  3102. span.meta = p_meta;
  3103. sd->spans.push_back(span);
  3104. sd->text = sd->text + p_text;
  3105. sd->end += p_text.length();
  3106. invalidate(sd, true);
  3107. return true;
  3108. }
  3109. bool TextServerAdvanced::shaped_text_add_object(const RID &p_shaped, const Variant &p_key, const Size2 &p_size, InlineAlignment p_inline_align, int64_t p_length) {
  3110. _THREAD_SAFE_METHOD_
  3111. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3112. ERR_FAIL_COND_V(!sd, false);
  3113. ERR_FAIL_COND_V(p_key == Variant(), false);
  3114. ERR_FAIL_COND_V(sd->objects.has(p_key), false);
  3115. if (sd->parent != RID()) {
  3116. full_copy(sd);
  3117. }
  3118. ShapedTextDataAdvanced::Span span;
  3119. span.start = sd->start + sd->text.length();
  3120. span.end = span.start + p_length;
  3121. span.embedded_key = p_key;
  3122. ShapedTextDataAdvanced::EmbeddedObject obj;
  3123. obj.inline_align = p_inline_align;
  3124. obj.rect.size = p_size;
  3125. obj.pos = span.start;
  3126. sd->spans.push_back(span);
  3127. sd->text = sd->text + String::chr(0xfffc).repeat(p_length);
  3128. sd->end += p_length;
  3129. sd->objects[p_key] = obj;
  3130. invalidate(sd, true);
  3131. return true;
  3132. }
  3133. bool TextServerAdvanced::shaped_text_resize_object(const RID &p_shaped, const Variant &p_key, const Size2 &p_size, InlineAlignment p_inline_align) {
  3134. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3135. ERR_FAIL_COND_V(!sd, false);
  3136. MutexLock lock(sd->mutex);
  3137. ERR_FAIL_COND_V(!sd->objects.has(p_key), false);
  3138. sd->objects[p_key].rect.size = p_size;
  3139. sd->objects[p_key].inline_align = p_inline_align;
  3140. if (sd->valid) {
  3141. // Recalc string metrics.
  3142. sd->ascent = 0;
  3143. sd->descent = 0;
  3144. sd->width = 0;
  3145. sd->upos = 0;
  3146. sd->uthk = 0;
  3147. int sd_size = sd->glyphs.size();
  3148. for (int i = 0; i < sd_size; i++) {
  3149. Glyph gl = sd->glyphs[i];
  3150. Variant key;
  3151. if (gl.count == 1) {
  3152. for (const KeyValue<Variant, ShapedTextDataAdvanced::EmbeddedObject> &E : sd->objects) {
  3153. if (E.value.pos == gl.start) {
  3154. key = E.key;
  3155. break;
  3156. }
  3157. }
  3158. }
  3159. if (key != Variant()) {
  3160. if (sd->orientation == ORIENTATION_HORIZONTAL) {
  3161. sd->objects[key].rect.position.x = sd->width;
  3162. sd->width += sd->objects[key].rect.size.x;
  3163. sd->glyphs.write[i].advance = sd->objects[key].rect.size.x;
  3164. } else {
  3165. sd->objects[key].rect.position.y = sd->width;
  3166. sd->width += sd->objects[key].rect.size.y;
  3167. sd->glyphs.write[i].advance = sd->objects[key].rect.size.y;
  3168. }
  3169. } else {
  3170. if (gl.font_rid.is_valid()) {
  3171. if (sd->orientation == ORIENTATION_HORIZONTAL) {
  3172. sd->ascent = MAX(sd->ascent, MAX(font_get_ascent(gl.font_rid, gl.font_size), -gl.y_off));
  3173. sd->descent = MAX(sd->descent, MAX(font_get_descent(gl.font_rid, gl.font_size), gl.y_off));
  3174. } else {
  3175. sd->ascent = MAX(sd->ascent, Math::round(font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5));
  3176. sd->descent = MAX(sd->descent, Math::round(font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5));
  3177. }
  3178. sd->upos = MAX(sd->upos, font_get_underline_position(gl.font_rid, gl.font_size));
  3179. sd->uthk = MAX(sd->uthk, font_get_underline_thickness(gl.font_rid, gl.font_size));
  3180. } else if (sd->preserve_invalid || (sd->preserve_control && is_control(gl.index))) {
  3181. // Glyph not found, replace with hex code box.
  3182. if (sd->orientation == ORIENTATION_HORIZONTAL) {
  3183. sd->ascent = MAX(sd->ascent, get_hex_code_box_size(gl.font_size, gl.index).y);
  3184. } else {
  3185. sd->ascent = MAX(sd->ascent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).x * 0.5));
  3186. sd->descent = MAX(sd->descent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).x * 0.5));
  3187. }
  3188. }
  3189. sd->width += gl.advance * gl.repeat;
  3190. }
  3191. }
  3192. _realign(sd);
  3193. }
  3194. return true;
  3195. }
  3196. void TextServerAdvanced::_realign(ShapedTextDataAdvanced *p_sd) const {
  3197. // Align embedded objects to baseline.
  3198. double full_ascent = p_sd->ascent;
  3199. double full_descent = p_sd->descent;
  3200. for (KeyValue<Variant, ShapedTextDataAdvanced::EmbeddedObject> &E : p_sd->objects) {
  3201. if ((E.value.pos >= p_sd->start) && (E.value.pos < p_sd->end)) {
  3202. if (p_sd->orientation == ORIENTATION_HORIZONTAL) {
  3203. switch (E.value.inline_align & INLINE_ALIGNMENT_TEXT_MASK) {
  3204. case INLINE_ALIGNMENT_TO_TOP: {
  3205. E.value.rect.position.y = -p_sd->ascent;
  3206. } break;
  3207. case INLINE_ALIGNMENT_TO_CENTER: {
  3208. E.value.rect.position.y = (-p_sd->ascent + p_sd->descent) / 2;
  3209. } break;
  3210. case INLINE_ALIGNMENT_TO_BASELINE: {
  3211. E.value.rect.position.y = 0;
  3212. } break;
  3213. case INLINE_ALIGNMENT_TO_BOTTOM: {
  3214. E.value.rect.position.y = p_sd->descent;
  3215. } break;
  3216. }
  3217. switch (E.value.inline_align & INLINE_ALIGNMENT_IMAGE_MASK) {
  3218. case INLINE_ALIGNMENT_BOTTOM_TO: {
  3219. E.value.rect.position.y -= E.value.rect.size.y;
  3220. } break;
  3221. case INLINE_ALIGNMENT_CENTER_TO: {
  3222. E.value.rect.position.y -= E.value.rect.size.y / 2;
  3223. } break;
  3224. case INLINE_ALIGNMENT_TOP_TO: {
  3225. // NOP
  3226. } break;
  3227. }
  3228. full_ascent = MAX(full_ascent, -E.value.rect.position.y);
  3229. full_descent = MAX(full_descent, E.value.rect.position.y + E.value.rect.size.y);
  3230. } else {
  3231. switch (E.value.inline_align & INLINE_ALIGNMENT_TEXT_MASK) {
  3232. case INLINE_ALIGNMENT_TO_TOP: {
  3233. E.value.rect.position.x = -p_sd->ascent;
  3234. } break;
  3235. case INLINE_ALIGNMENT_TO_CENTER: {
  3236. E.value.rect.position.x = (-p_sd->ascent + p_sd->descent) / 2;
  3237. } break;
  3238. case INLINE_ALIGNMENT_TO_BASELINE: {
  3239. E.value.rect.position.x = 0;
  3240. } break;
  3241. case INLINE_ALIGNMENT_TO_BOTTOM: {
  3242. E.value.rect.position.x = p_sd->descent;
  3243. } break;
  3244. }
  3245. switch (E.value.inline_align & INLINE_ALIGNMENT_IMAGE_MASK) {
  3246. case INLINE_ALIGNMENT_BOTTOM_TO: {
  3247. E.value.rect.position.x -= E.value.rect.size.x;
  3248. } break;
  3249. case INLINE_ALIGNMENT_CENTER_TO: {
  3250. E.value.rect.position.x -= E.value.rect.size.x / 2;
  3251. } break;
  3252. case INLINE_ALIGNMENT_TOP_TO: {
  3253. // NOP
  3254. } break;
  3255. }
  3256. full_ascent = MAX(full_ascent, -E.value.rect.position.x);
  3257. full_descent = MAX(full_descent, E.value.rect.position.x + E.value.rect.size.x);
  3258. }
  3259. }
  3260. }
  3261. p_sd->ascent = full_ascent;
  3262. p_sd->descent = full_descent;
  3263. }
  3264. RID TextServerAdvanced::shaped_text_substr(const RID &p_shaped, int64_t p_start, int64_t p_length) const {
  3265. _THREAD_SAFE_METHOD_
  3266. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3267. ERR_FAIL_COND_V(!sd, RID());
  3268. MutexLock lock(sd->mutex);
  3269. if (sd->parent != RID()) {
  3270. return shaped_text_substr(sd->parent, p_start, p_length);
  3271. }
  3272. if (!sd->valid) {
  3273. const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped);
  3274. }
  3275. ERR_FAIL_COND_V(p_start < 0 || p_length < 0, RID());
  3276. ERR_FAIL_COND_V(sd->start > p_start || sd->end < p_start, RID());
  3277. ERR_FAIL_COND_V(sd->end < p_start + p_length, RID());
  3278. ShapedTextDataAdvanced *new_sd = memnew(ShapedTextDataAdvanced);
  3279. new_sd->parent = p_shaped;
  3280. new_sd->start = p_start;
  3281. new_sd->end = p_start + p_length;
  3282. new_sd->orientation = sd->orientation;
  3283. new_sd->direction = sd->direction;
  3284. new_sd->custom_punct = sd->custom_punct;
  3285. new_sd->para_direction = sd->para_direction;
  3286. for (int i = 0; i < TextServer::SPACING_MAX; i++) {
  3287. new_sd->extra_spacing[i] = sd->extra_spacing[i];
  3288. }
  3289. if (!_shape_substr(new_sd, sd, p_start, p_length)) {
  3290. memdelete(new_sd);
  3291. return RID();
  3292. }
  3293. return shaped_owner.make_rid(new_sd);
  3294. }
  3295. bool TextServerAdvanced::_shape_substr(ShapedTextDataAdvanced *p_new_sd, const ShapedTextDataAdvanced *p_sd, int64_t p_start, int64_t p_length) const {
  3296. if (p_new_sd->valid) {
  3297. return true;
  3298. }
  3299. p_new_sd->hb_buffer = hb_buffer_create();
  3300. p_new_sd->line_breaks_valid = p_sd->line_breaks_valid;
  3301. p_new_sd->justification_ops_valid = p_sd->justification_ops_valid;
  3302. p_new_sd->sort_valid = false;
  3303. p_new_sd->upos = p_sd->upos;
  3304. p_new_sd->uthk = p_sd->uthk;
  3305. if (p_length > 0) {
  3306. p_new_sd->text = p_sd->text.substr(p_start - p_sd->start, p_length);
  3307. p_new_sd->utf16 = p_new_sd->text.utf16();
  3308. p_new_sd->script_iter = memnew(ScriptIterator(p_new_sd->text, 0, p_new_sd->text.length()));
  3309. int sd_size = p_sd->glyphs.size();
  3310. const Glyph *sd_glyphs = p_sd->glyphs.ptr();
  3311. for (int ov = 0; ov < p_sd->bidi_override.size(); ov++) {
  3312. UErrorCode err = U_ZERO_ERROR;
  3313. if (p_sd->bidi_override[ov].x >= p_start + p_length || p_sd->bidi_override[ov].y <= p_start) {
  3314. continue;
  3315. }
  3316. int start = _convert_pos_inv(p_sd, MAX(0, p_start - p_sd->bidi_override[ov].x));
  3317. int end = _convert_pos_inv(p_sd, MIN(p_start + p_length, p_sd->bidi_override[ov].y) - p_sd->bidi_override[ov].x);
  3318. ERR_FAIL_COND_V_MSG((start < 0 || end - start > p_new_sd->utf16.length()), false, "Invalid BiDi override range.");
  3319. // Create temporary line bidi & shape.
  3320. UBiDi *bidi_iter = ubidi_openSized(end - start, 0, &err);
  3321. ERR_FAIL_COND_V_MSG(U_FAILURE(err), false, u_errorName(err));
  3322. ubidi_setLine(p_sd->bidi_iter[ov], start, end, bidi_iter, &err);
  3323. if (U_FAILURE(err)) {
  3324. ubidi_close(bidi_iter);
  3325. ERR_FAIL_V_MSG(false, u_errorName(err));
  3326. }
  3327. p_new_sd->bidi_iter.push_back(bidi_iter);
  3328. err = U_ZERO_ERROR;
  3329. int bidi_run_count = ubidi_countRuns(bidi_iter, &err);
  3330. ERR_FAIL_COND_V_MSG(U_FAILURE(err), false, u_errorName(err));
  3331. for (int i = 0; i < bidi_run_count; i++) {
  3332. int32_t _bidi_run_start = 0;
  3333. int32_t _bidi_run_length = 0;
  3334. ubidi_getVisualRun(bidi_iter, i, &_bidi_run_start, &_bidi_run_length);
  3335. int32_t bidi_run_start = _convert_pos(p_sd, p_sd->bidi_override[ov].x + start + _bidi_run_start);
  3336. int32_t bidi_run_end = _convert_pos(p_sd, p_sd->bidi_override[ov].x + start + _bidi_run_start + _bidi_run_length);
  3337. for (int j = 0; j < sd_size; j++) {
  3338. if ((sd_glyphs[j].start >= bidi_run_start) && (sd_glyphs[j].end <= bidi_run_end)) {
  3339. // Copy glyphs.
  3340. Glyph gl = sd_glyphs[j];
  3341. Variant key;
  3342. bool find_embedded = false;
  3343. if (gl.count == 1) {
  3344. for (const KeyValue<Variant, ShapedTextDataAdvanced::EmbeddedObject> &E : p_sd->objects) {
  3345. if (E.value.pos == gl.start) {
  3346. find_embedded = true;
  3347. key = E.key;
  3348. p_new_sd->objects[key] = E.value;
  3349. break;
  3350. }
  3351. }
  3352. }
  3353. if (find_embedded) {
  3354. if (p_new_sd->orientation == ORIENTATION_HORIZONTAL) {
  3355. p_new_sd->objects[key].rect.position.x = p_new_sd->width;
  3356. p_new_sd->width += p_new_sd->objects[key].rect.size.x;
  3357. } else {
  3358. p_new_sd->objects[key].rect.position.y = p_new_sd->width;
  3359. p_new_sd->width += p_new_sd->objects[key].rect.size.y;
  3360. }
  3361. } else {
  3362. if (gl.font_rid.is_valid()) {
  3363. if (p_new_sd->orientation == ORIENTATION_HORIZONTAL) {
  3364. p_new_sd->ascent = MAX(p_new_sd->ascent, MAX(font_get_ascent(gl.font_rid, gl.font_size), -gl.y_off));
  3365. p_new_sd->descent = MAX(p_new_sd->descent, MAX(font_get_descent(gl.font_rid, gl.font_size), gl.y_off));
  3366. } else {
  3367. p_new_sd->ascent = MAX(p_new_sd->ascent, Math::round(font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5));
  3368. p_new_sd->descent = MAX(p_new_sd->descent, Math::round(font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5));
  3369. }
  3370. } else if (p_new_sd->preserve_invalid || (p_new_sd->preserve_control && is_control(gl.index))) {
  3371. // Glyph not found, replace with hex code box.
  3372. if (p_new_sd->orientation == ORIENTATION_HORIZONTAL) {
  3373. p_new_sd->ascent = MAX(p_new_sd->ascent, get_hex_code_box_size(gl.font_size, gl.index).y);
  3374. } else {
  3375. p_new_sd->ascent = MAX(p_new_sd->ascent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).x * 0.5));
  3376. p_new_sd->descent = MAX(p_new_sd->descent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).x * 0.5));
  3377. }
  3378. }
  3379. p_new_sd->width += gl.advance * gl.repeat;
  3380. }
  3381. p_new_sd->glyphs.push_back(gl);
  3382. }
  3383. }
  3384. }
  3385. }
  3386. _realign(p_new_sd);
  3387. }
  3388. p_new_sd->valid = true;
  3389. return true;
  3390. }
  3391. RID TextServerAdvanced::shaped_text_get_parent(const RID &p_shaped) const {
  3392. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3393. ERR_FAIL_COND_V(!sd, RID());
  3394. MutexLock lock(sd->mutex);
  3395. return sd->parent;
  3396. }
  3397. double TextServerAdvanced::shaped_text_fit_to_width(const RID &p_shaped, double p_width, BitField<TextServer::JustificationFlag> p_jst_flags) {
  3398. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3399. ERR_FAIL_COND_V(!sd, 0.0);
  3400. MutexLock lock(sd->mutex);
  3401. if (!sd->valid) {
  3402. const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped);
  3403. }
  3404. if (!sd->justification_ops_valid) {
  3405. const_cast<TextServerAdvanced *>(this)->shaped_text_update_justification_ops(p_shaped);
  3406. }
  3407. sd->fit_width_minimum_reached = false;
  3408. int start_pos = 0;
  3409. int end_pos = sd->glyphs.size() - 1;
  3410. if (p_jst_flags.has_flag(JUSTIFICATION_AFTER_LAST_TAB)) {
  3411. int start, end, delta;
  3412. if (sd->para_direction == DIRECTION_LTR) {
  3413. start = sd->glyphs.size() - 1;
  3414. end = -1;
  3415. delta = -1;
  3416. } else {
  3417. start = 0;
  3418. end = sd->glyphs.size();
  3419. delta = +1;
  3420. }
  3421. for (int i = start; i != end; i += delta) {
  3422. if ((sd->glyphs[i].flags & GRAPHEME_IS_TAB) == GRAPHEME_IS_TAB) {
  3423. if (sd->para_direction == DIRECTION_LTR) {
  3424. start_pos = i;
  3425. break;
  3426. } else {
  3427. end_pos = i;
  3428. break;
  3429. }
  3430. }
  3431. }
  3432. }
  3433. double justification_width;
  3434. if (p_jst_flags.has_flag(JUSTIFICATION_CONSTRAIN_ELLIPSIS)) {
  3435. if (sd->overrun_trim_data.trim_pos >= 0) {
  3436. if (sd->para_direction == DIRECTION_RTL) {
  3437. start_pos = sd->overrun_trim_data.trim_pos;
  3438. } else {
  3439. end_pos = sd->overrun_trim_data.trim_pos;
  3440. }
  3441. justification_width = sd->width_trimmed;
  3442. } else {
  3443. return Math::ceil(sd->width);
  3444. }
  3445. } else {
  3446. justification_width = sd->width;
  3447. }
  3448. if (p_jst_flags.has_flag(JUSTIFICATION_TRIM_EDGE_SPACES)) {
  3449. // Trim spaces.
  3450. while ((start_pos < end_pos) && ((sd->glyphs[start_pos].flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE || (sd->glyphs[start_pos].flags & GRAPHEME_IS_BREAK_HARD) == GRAPHEME_IS_BREAK_HARD || (sd->glyphs[start_pos].flags & GRAPHEME_IS_BREAK_SOFT) == GRAPHEME_IS_BREAK_SOFT)) {
  3451. justification_width -= sd->glyphs[start_pos].advance * sd->glyphs[start_pos].repeat;
  3452. sd->glyphs.write[start_pos].advance = 0;
  3453. start_pos += sd->glyphs[start_pos].count;
  3454. }
  3455. while ((start_pos < end_pos) && ((sd->glyphs[end_pos].flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE || (sd->glyphs[end_pos].flags & GRAPHEME_IS_BREAK_HARD) == GRAPHEME_IS_BREAK_HARD || (sd->glyphs[end_pos].flags & GRAPHEME_IS_BREAK_SOFT) == GRAPHEME_IS_BREAK_SOFT)) {
  3456. justification_width -= sd->glyphs[end_pos].advance * sd->glyphs[end_pos].repeat;
  3457. sd->glyphs.write[end_pos].advance = 0;
  3458. end_pos -= sd->glyphs[end_pos].count;
  3459. }
  3460. } else {
  3461. // Skip breaks, but do not reset size.
  3462. while ((start_pos < end_pos) && ((sd->glyphs[start_pos].flags & GRAPHEME_IS_BREAK_HARD) == GRAPHEME_IS_BREAK_HARD || (sd->glyphs[start_pos].flags & GRAPHEME_IS_BREAK_SOFT) == GRAPHEME_IS_BREAK_SOFT)) {
  3463. start_pos += sd->glyphs[start_pos].count;
  3464. }
  3465. while ((start_pos < end_pos) && ((sd->glyphs[end_pos].flags & GRAPHEME_IS_BREAK_HARD) == GRAPHEME_IS_BREAK_HARD || (sd->glyphs[end_pos].flags & GRAPHEME_IS_BREAK_SOFT) == GRAPHEME_IS_BREAK_SOFT)) {
  3466. end_pos -= sd->glyphs[end_pos].count;
  3467. }
  3468. }
  3469. int space_count = 0;
  3470. int elongation_count = 0;
  3471. for (int i = start_pos; i <= end_pos; i++) {
  3472. const Glyph &gl = sd->glyphs[i];
  3473. if (gl.count > 0) {
  3474. if ((gl.flags & GRAPHEME_IS_ELONGATION) == GRAPHEME_IS_ELONGATION) {
  3475. if ((i > 0) && ((sd->glyphs[i - 1].flags & GRAPHEME_IS_ELONGATION) != GRAPHEME_IS_ELONGATION)) {
  3476. // Expand once per elongation sequence.
  3477. elongation_count++;
  3478. }
  3479. }
  3480. if ((gl.flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE) {
  3481. space_count++;
  3482. }
  3483. }
  3484. }
  3485. if ((elongation_count > 0) && p_jst_flags.has_flag(JUSTIFICATION_KASHIDA)) {
  3486. double delta_width_per_kashida = (p_width - justification_width) / elongation_count;
  3487. for (int i = start_pos; i <= end_pos; i++) {
  3488. Glyph &gl = sd->glyphs.write[i];
  3489. if (gl.count > 0) {
  3490. if (((gl.flags & GRAPHEME_IS_ELONGATION) == GRAPHEME_IS_ELONGATION) && (gl.advance > 0)) {
  3491. if ((i > 0) && ((sd->glyphs[i - 1].flags & GRAPHEME_IS_ELONGATION) != GRAPHEME_IS_ELONGATION)) {
  3492. // Expand once per elongation sequence.
  3493. int count = delta_width_per_kashida / gl.advance;
  3494. int prev_count = gl.repeat;
  3495. if ((gl.flags & GRAPHEME_IS_VIRTUAL) == GRAPHEME_IS_VIRTUAL) {
  3496. gl.repeat = MAX(count, 0);
  3497. } else {
  3498. gl.repeat = MAX(count + 1, 1);
  3499. }
  3500. justification_width += (gl.repeat - prev_count) * gl.advance;
  3501. }
  3502. }
  3503. }
  3504. }
  3505. }
  3506. if ((space_count > 0) && p_jst_flags.has_flag(JUSTIFICATION_WORD_BOUND)) {
  3507. double delta_width_per_space = (p_width - justification_width) / space_count;
  3508. double adv_remain = 0;
  3509. for (int i = start_pos; i <= end_pos; i++) {
  3510. Glyph &gl = sd->glyphs.write[i];
  3511. if (gl.count > 0) {
  3512. if ((gl.flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE) {
  3513. double old_adv = gl.advance;
  3514. double new_advance;
  3515. if ((gl.flags & GRAPHEME_IS_VIRTUAL) == GRAPHEME_IS_VIRTUAL) {
  3516. new_advance = MAX(gl.advance + delta_width_per_space, 0.0);
  3517. } else {
  3518. new_advance = MAX(gl.advance + delta_width_per_space, 0.1 * gl.font_size);
  3519. }
  3520. gl.advance = new_advance;
  3521. adv_remain += (new_advance - gl.advance);
  3522. if (adv_remain >= 1.0) {
  3523. gl.advance++;
  3524. adv_remain -= 1.0;
  3525. } else if (adv_remain <= -1.0) {
  3526. gl.advance = MAX(gl.advance - 1, 0);
  3527. adv_remain -= 1.0;
  3528. }
  3529. justification_width += (gl.advance - old_adv);
  3530. }
  3531. }
  3532. }
  3533. }
  3534. if (Math::floor(p_width) < Math::floor(justification_width)) {
  3535. sd->fit_width_minimum_reached = true;
  3536. }
  3537. if (!p_jst_flags.has_flag(JUSTIFICATION_CONSTRAIN_ELLIPSIS)) {
  3538. sd->width = justification_width;
  3539. }
  3540. return Math::ceil(justification_width);
  3541. }
  3542. double TextServerAdvanced::shaped_text_tab_align(const RID &p_shaped, const PackedFloat32Array &p_tab_stops) {
  3543. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3544. ERR_FAIL_COND_V(!sd, 0.0);
  3545. MutexLock lock(sd->mutex);
  3546. if (!sd->valid) {
  3547. const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped);
  3548. }
  3549. if (!sd->line_breaks_valid) {
  3550. const_cast<TextServerAdvanced *>(this)->shaped_text_update_breaks(p_shaped);
  3551. }
  3552. for (int i = 0; i < p_tab_stops.size(); i++) {
  3553. if (p_tab_stops[i] <= 0) {
  3554. return 0.0;
  3555. }
  3556. }
  3557. int tab_index = 0;
  3558. double off = 0.0;
  3559. int start, end, delta;
  3560. if (sd->para_direction == DIRECTION_LTR) {
  3561. start = 0;
  3562. end = sd->glyphs.size();
  3563. delta = +1;
  3564. } else {
  3565. start = sd->glyphs.size() - 1;
  3566. end = -1;
  3567. delta = -1;
  3568. }
  3569. Glyph *gl = sd->glyphs.ptrw();
  3570. for (int i = start; i != end; i += delta) {
  3571. if ((gl[i].flags & GRAPHEME_IS_TAB) == GRAPHEME_IS_TAB) {
  3572. double tab_off = 0.0;
  3573. while (tab_off <= off) {
  3574. tab_off += p_tab_stops[tab_index];
  3575. tab_index++;
  3576. if (tab_index >= p_tab_stops.size()) {
  3577. tab_index = 0;
  3578. }
  3579. }
  3580. double old_adv = gl[i].advance;
  3581. gl[i].advance = tab_off - off;
  3582. sd->width += gl[i].advance - old_adv;
  3583. off = 0;
  3584. continue;
  3585. }
  3586. off += gl[i].advance * gl[i].repeat;
  3587. }
  3588. return 0.0;
  3589. }
  3590. void TextServerAdvanced::shaped_text_overrun_trim_to_width(const RID &p_shaped_line, double p_width, BitField<TextServer::TextOverrunFlag> p_trim_flags) {
  3591. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped_line);
  3592. ERR_FAIL_COND_MSG(!sd, "ShapedTextDataAdvanced invalid.");
  3593. MutexLock lock(sd->mutex);
  3594. if (!sd->valid) {
  3595. shaped_text_shape(p_shaped_line);
  3596. }
  3597. sd->text_trimmed = false;
  3598. sd->overrun_trim_data.ellipsis_glyph_buf.clear();
  3599. bool add_ellipsis = p_trim_flags.has_flag(OVERRUN_ADD_ELLIPSIS);
  3600. bool cut_per_word = p_trim_flags.has_flag(OVERRUN_TRIM_WORD_ONLY);
  3601. bool enforce_ellipsis = p_trim_flags.has_flag(OVERRUN_ENFORCE_ELLIPSIS);
  3602. bool justification_aware = p_trim_flags.has_flag(OVERRUN_JUSTIFICATION_AWARE);
  3603. Glyph *sd_glyphs = sd->glyphs.ptrw();
  3604. if ((p_trim_flags & OVERRUN_TRIM) == OVERRUN_NO_TRIM || sd_glyphs == nullptr || p_width <= 0 || !(sd->width > p_width || enforce_ellipsis)) {
  3605. sd->overrun_trim_data.trim_pos = -1;
  3606. sd->overrun_trim_data.ellipsis_pos = -1;
  3607. return;
  3608. }
  3609. if (justification_aware && !sd->fit_width_minimum_reached) {
  3610. return;
  3611. }
  3612. Vector<ShapedTextDataAdvanced::Span> &spans = sd->spans;
  3613. if (sd->parent != RID()) {
  3614. ShapedTextDataAdvanced *parent_sd = shaped_owner.get_or_null(sd->parent);
  3615. ERR_FAIL_COND(!parent_sd->valid);
  3616. spans = parent_sd->spans;
  3617. }
  3618. if (spans.size() == 0) {
  3619. return;
  3620. }
  3621. int sd_size = sd->glyphs.size();
  3622. int last_gl_font_size = sd_glyphs[sd_size - 1].font_size;
  3623. // Find usable fonts, if fonts from the last glyph do not have required chars.
  3624. RID dot_gl_font_rid = sd_glyphs[sd_size - 1].font_rid;
  3625. if (!font_has_char(dot_gl_font_rid, '.')) {
  3626. const Array &fonts = spans[spans.size() - 1].fonts;
  3627. for (int i = 0; i < fonts.size(); i++) {
  3628. if (font_has_char(fonts[i], '.')) {
  3629. dot_gl_font_rid = fonts[i];
  3630. break;
  3631. }
  3632. }
  3633. }
  3634. RID whitespace_gl_font_rid = sd_glyphs[sd_size - 1].font_rid;
  3635. if (!font_has_char(whitespace_gl_font_rid, '.')) {
  3636. const Array &fonts = spans[spans.size() - 1].fonts;
  3637. for (int i = 0; i < fonts.size(); i++) {
  3638. if (font_has_char(fonts[i], ' ')) {
  3639. whitespace_gl_font_rid = fonts[i];
  3640. break;
  3641. }
  3642. }
  3643. }
  3644. int32_t dot_gl_idx = dot_gl_font_rid.is_valid() ? font_get_glyph_index(dot_gl_font_rid, last_gl_font_size, '.') : -10;
  3645. Vector2 dot_adv = dot_gl_font_rid.is_valid() ? font_get_glyph_advance(dot_gl_font_rid, last_gl_font_size, dot_gl_idx) : Vector2();
  3646. int32_t whitespace_gl_idx = whitespace_gl_font_rid.is_valid() ? font_get_glyph_index(whitespace_gl_font_rid, last_gl_font_size, ' ') : -10;
  3647. Vector2 whitespace_adv = whitespace_gl_font_rid.is_valid() ? font_get_glyph_advance(whitespace_gl_font_rid, last_gl_font_size, whitespace_gl_idx) : Vector2();
  3648. int ellipsis_width = 0;
  3649. if (add_ellipsis && whitespace_gl_font_rid.is_valid()) {
  3650. ellipsis_width = 3 * dot_adv.x + sd->extra_spacing[SPACING_GLYPH] + (cut_per_word ? whitespace_adv.x : 0);
  3651. }
  3652. int ell_min_characters = 6;
  3653. double width = sd->width;
  3654. bool is_rtl = sd->para_direction == DIRECTION_RTL;
  3655. int trim_pos = (is_rtl) ? sd_size : 0;
  3656. int ellipsis_pos = (enforce_ellipsis) ? 0 : -1;
  3657. int last_valid_cut = 0;
  3658. bool found = false;
  3659. int glyphs_from = (is_rtl) ? 0 : sd_size - 1;
  3660. int glyphs_to = (is_rtl) ? sd_size - 1 : -1;
  3661. int glyphs_delta = (is_rtl) ? +1 : -1;
  3662. for (int i = glyphs_from; i != glyphs_to; i += glyphs_delta) {
  3663. if (!is_rtl) {
  3664. width -= sd_glyphs[i].advance * sd_glyphs[i].repeat;
  3665. }
  3666. if (sd_glyphs[i].count > 0) {
  3667. bool above_min_char_threshold = ((is_rtl) ? sd_size - 1 - i : i) >= ell_min_characters;
  3668. if (width + (((above_min_char_threshold && add_ellipsis) || enforce_ellipsis) ? ellipsis_width : 0) <= p_width) {
  3669. if (cut_per_word && above_min_char_threshold) {
  3670. if ((sd_glyphs[i].flags & GRAPHEME_IS_BREAK_SOFT) == GRAPHEME_IS_BREAK_SOFT) {
  3671. last_valid_cut = i;
  3672. found = true;
  3673. }
  3674. } else {
  3675. last_valid_cut = i;
  3676. found = true;
  3677. }
  3678. if (found) {
  3679. trim_pos = last_valid_cut;
  3680. if (add_ellipsis && (above_min_char_threshold || enforce_ellipsis) && width - ellipsis_width <= p_width) {
  3681. ellipsis_pos = trim_pos;
  3682. }
  3683. break;
  3684. }
  3685. }
  3686. }
  3687. if (is_rtl) {
  3688. width -= sd_glyphs[i].advance * sd_glyphs[i].repeat;
  3689. }
  3690. }
  3691. sd->overrun_trim_data.trim_pos = trim_pos;
  3692. sd->overrun_trim_data.ellipsis_pos = ellipsis_pos;
  3693. if (trim_pos == 0 && enforce_ellipsis && add_ellipsis) {
  3694. sd->overrun_trim_data.ellipsis_pos = 0;
  3695. }
  3696. if ((trim_pos >= 0 && sd->width > p_width) || enforce_ellipsis) {
  3697. if (add_ellipsis && (ellipsis_pos > 0 || enforce_ellipsis)) {
  3698. // Insert an additional space when cutting word bound for aesthetics.
  3699. if (cut_per_word && (ellipsis_pos > 0)) {
  3700. Glyph gl;
  3701. gl.count = 1;
  3702. gl.advance = whitespace_adv.x;
  3703. gl.index = whitespace_gl_idx;
  3704. gl.font_rid = whitespace_gl_font_rid;
  3705. gl.font_size = last_gl_font_size;
  3706. gl.flags = GRAPHEME_IS_SPACE | GRAPHEME_IS_BREAK_SOFT | GRAPHEME_IS_VIRTUAL | (is_rtl ? GRAPHEME_IS_RTL : 0);
  3707. sd->overrun_trim_data.ellipsis_glyph_buf.append(gl);
  3708. }
  3709. // Add ellipsis dots.
  3710. if (dot_gl_idx != 0) {
  3711. Glyph gl;
  3712. gl.count = 1;
  3713. gl.repeat = 3;
  3714. gl.advance = dot_adv.x;
  3715. gl.index = dot_gl_idx;
  3716. gl.font_rid = dot_gl_font_rid;
  3717. gl.font_size = last_gl_font_size;
  3718. gl.flags = GRAPHEME_IS_PUNCTUATION | GRAPHEME_IS_VIRTUAL | (is_rtl ? GRAPHEME_IS_RTL : 0);
  3719. sd->overrun_trim_data.ellipsis_glyph_buf.append(gl);
  3720. }
  3721. }
  3722. sd->text_trimmed = true;
  3723. sd->width_trimmed = width + ((ellipsis_pos != -1) ? ellipsis_width : 0);
  3724. }
  3725. }
  3726. int64_t TextServerAdvanced::shaped_text_get_trim_pos(const RID &p_shaped) const {
  3727. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3728. ERR_FAIL_COND_V_MSG(!sd, -1, "ShapedTextDataAdvanced invalid.");
  3729. MutexLock lock(sd->mutex);
  3730. return sd->overrun_trim_data.trim_pos;
  3731. }
  3732. int64_t TextServerAdvanced::shaped_text_get_ellipsis_pos(const RID &p_shaped) const {
  3733. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3734. ERR_FAIL_COND_V_MSG(!sd, -1, "ShapedTextDataAdvanced invalid.");
  3735. MutexLock lock(sd->mutex);
  3736. return sd->overrun_trim_data.ellipsis_pos;
  3737. }
  3738. const Glyph *TextServerAdvanced::shaped_text_get_ellipsis_glyphs(const RID &p_shaped) const {
  3739. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3740. ERR_FAIL_COND_V_MSG(!sd, nullptr, "ShapedTextDataAdvanced invalid.");
  3741. MutexLock lock(sd->mutex);
  3742. return sd->overrun_trim_data.ellipsis_glyph_buf.ptr();
  3743. }
  3744. int64_t TextServerAdvanced::shaped_text_get_ellipsis_glyph_count(const RID &p_shaped) const {
  3745. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3746. ERR_FAIL_COND_V_MSG(!sd, 0, "ShapedTextDataAdvanced invalid.");
  3747. MutexLock lock(sd->mutex);
  3748. return sd->overrun_trim_data.ellipsis_glyph_buf.size();
  3749. }
  3750. bool TextServerAdvanced::shaped_text_update_breaks(const RID &p_shaped) {
  3751. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3752. ERR_FAIL_COND_V(!sd, false);
  3753. MutexLock lock(sd->mutex);
  3754. if (!sd->valid) {
  3755. shaped_text_shape(p_shaped);
  3756. }
  3757. if (sd->line_breaks_valid) {
  3758. return true; // Nothing to do.
  3759. }
  3760. const UChar *data = sd->utf16.get_data();
  3761. if (!sd->break_ops_valid) {
  3762. sd->breaks.clear();
  3763. UErrorCode err = U_ZERO_ERROR;
  3764. int i = 0;
  3765. while (i < sd->spans.size()) {
  3766. String language = sd->spans[i].language;
  3767. int r_start = sd->spans[i].start;
  3768. while (i + 1 < sd->spans.size() && language == sd->spans[i + 1].language) {
  3769. i++;
  3770. }
  3771. int r_end = sd->spans[i].end;
  3772. UBreakIterator *bi = ubrk_open(UBRK_LINE, (language.is_empty()) ? TranslationServer::get_singleton()->get_tool_locale().ascii().get_data() : language.ascii().get_data(), data + _convert_pos_inv(sd, r_start), _convert_pos_inv(sd, r_end - r_start), &err);
  3773. if (U_FAILURE(err)) {
  3774. // No data loaded - use fallback.
  3775. for (int j = r_start; j < r_end; j++) {
  3776. char32_t c = sd->text[j - sd->start];
  3777. if (is_whitespace(c)) {
  3778. sd->breaks[j + 1] = false;
  3779. }
  3780. if (is_linebreak(c)) {
  3781. sd->breaks[j + 1] = true;
  3782. }
  3783. }
  3784. } else {
  3785. while (ubrk_next(bi) != UBRK_DONE) {
  3786. int pos = _convert_pos(sd, ubrk_current(bi)) + r_start;
  3787. if ((ubrk_getRuleStatus(bi) >= UBRK_LINE_HARD) && (ubrk_getRuleStatus(bi) < UBRK_LINE_HARD_LIMIT)) {
  3788. sd->breaks[pos] = true;
  3789. } else if ((ubrk_getRuleStatus(bi) >= UBRK_LINE_SOFT) && (ubrk_getRuleStatus(bi) < UBRK_LINE_SOFT_LIMIT)) {
  3790. sd->breaks[pos] = false;
  3791. }
  3792. }
  3793. }
  3794. ubrk_close(bi);
  3795. i++;
  3796. }
  3797. sd->break_ops_valid = true;
  3798. }
  3799. sd->sort_valid = false;
  3800. sd->glyphs_logical.clear();
  3801. int sd_size = sd->glyphs.size();
  3802. const char32_t *ch = sd->text.ptr();
  3803. Glyph *sd_glyphs = sd->glyphs.ptrw();
  3804. int c_punct_size = sd->custom_punct.length();
  3805. const char32_t *c_punct = sd->custom_punct.ptr();
  3806. for (int i = 0; i < sd_size; i++) {
  3807. if (sd_glyphs[i].count > 0) {
  3808. char32_t c = ch[sd_glyphs[i].start - sd->start];
  3809. if (c == 0xfffc) {
  3810. continue;
  3811. }
  3812. if (c == 0x0009 || c == 0x000b) {
  3813. sd_glyphs[i].flags |= GRAPHEME_IS_TAB;
  3814. }
  3815. if (is_whitespace(c)) {
  3816. sd_glyphs[i].flags |= GRAPHEME_IS_SPACE;
  3817. }
  3818. if (c_punct_size == 0) {
  3819. if (u_ispunct(c) && c != 0x005f) {
  3820. sd_glyphs[i].flags |= GRAPHEME_IS_PUNCTUATION;
  3821. }
  3822. } else {
  3823. for (int j = 0; j < c_punct_size; j++) {
  3824. if (c_punct[j] == c) {
  3825. sd_glyphs[i].flags |= GRAPHEME_IS_PUNCTUATION;
  3826. break;
  3827. }
  3828. }
  3829. }
  3830. if (is_underscore(c)) {
  3831. sd_glyphs[i].flags |= GRAPHEME_IS_UNDERSCORE;
  3832. }
  3833. if (sd->breaks.has(sd_glyphs[i].end)) {
  3834. if (sd->breaks[sd_glyphs[i].end] && (is_linebreak(c))) {
  3835. sd_glyphs[i].flags |= GRAPHEME_IS_BREAK_HARD;
  3836. } else if (is_whitespace(c)) {
  3837. sd_glyphs[i].flags |= GRAPHEME_IS_BREAK_SOFT;
  3838. } else {
  3839. int count = sd_glyphs[i].count;
  3840. // Do not add extra space at the end of the line.
  3841. if (sd_glyphs[i].end == sd->end) {
  3842. continue;
  3843. }
  3844. // Do not add extra space after existing space.
  3845. if (sd_glyphs[i].flags & GRAPHEME_IS_RTL) {
  3846. if ((i + count < sd_size - 1) && ((sd_glyphs[i + count].flags & (GRAPHEME_IS_SPACE | GRAPHEME_IS_BREAK_SOFT)) == (GRAPHEME_IS_SPACE | GRAPHEME_IS_BREAK_SOFT))) {
  3847. continue;
  3848. }
  3849. } else {
  3850. if ((i > 0) && ((sd_glyphs[i - 1].flags & (GRAPHEME_IS_SPACE | GRAPHEME_IS_BREAK_SOFT)) == (GRAPHEME_IS_SPACE | GRAPHEME_IS_BREAK_SOFT))) {
  3851. continue;
  3852. }
  3853. }
  3854. Glyph gl;
  3855. gl.start = sd_glyphs[i].start;
  3856. gl.end = sd_glyphs[i].end;
  3857. gl.count = 1;
  3858. gl.font_rid = sd_glyphs[i].font_rid;
  3859. gl.font_size = sd_glyphs[i].font_size;
  3860. gl.flags = GRAPHEME_IS_BREAK_SOFT | GRAPHEME_IS_VIRTUAL | GRAPHEME_IS_SPACE;
  3861. if (sd_glyphs[i].flags & GRAPHEME_IS_RTL) {
  3862. gl.flags |= GRAPHEME_IS_RTL;
  3863. sd->glyphs.insert(i, gl); // Insert before.
  3864. } else {
  3865. sd->glyphs.insert(i + count, gl); // Insert after.
  3866. }
  3867. i += count;
  3868. // Update write pointer and size.
  3869. sd_size = sd->glyphs.size();
  3870. sd_glyphs = sd->glyphs.ptrw();
  3871. continue;
  3872. }
  3873. }
  3874. i += (sd_glyphs[i].count - 1);
  3875. }
  3876. }
  3877. sd->line_breaks_valid = true;
  3878. return sd->line_breaks_valid;
  3879. }
  3880. _FORCE_INLINE_ int64_t _generate_kashida_justification_opportunies(const String &p_data, int64_t p_start, int64_t p_end) {
  3881. int64_t kashida_pos = -1;
  3882. int8_t priority = 100;
  3883. int64_t i = p_start;
  3884. char32_t pc = 0;
  3885. while ((p_end > p_start) && is_transparent(p_data[p_end - 1])) {
  3886. p_end--;
  3887. }
  3888. while (i < p_end) {
  3889. uint32_t c = p_data[i];
  3890. if (c == 0x0640) {
  3891. kashida_pos = i;
  3892. priority = 0;
  3893. }
  3894. if (priority >= 1 && i < p_end - 1) {
  3895. if (is_seen_sad(c) && (p_data[i + 1] != 0x200c)) {
  3896. kashida_pos = i;
  3897. priority = 1;
  3898. }
  3899. }
  3900. if (priority >= 2 && i > p_start) {
  3901. if (is_teh_marbuta(c) || is_dal(c) || (is_heh(c) && i == p_end - 1)) {
  3902. if (is_connected_to_prev(c, pc)) {
  3903. kashida_pos = i - 1;
  3904. priority = 2;
  3905. }
  3906. }
  3907. }
  3908. if (priority >= 3 && i > p_start) {
  3909. if (is_alef(c) || ((is_lam(c) || is_tah(c) || is_kaf(c) || is_gaf(c)) && i == p_end - 1)) {
  3910. if (is_connected_to_prev(c, pc)) {
  3911. kashida_pos = i - 1;
  3912. priority = 3;
  3913. }
  3914. }
  3915. }
  3916. if (priority >= 4 && i > p_start && i < p_end - 1) {
  3917. if (is_beh(c)) {
  3918. if (is_reh(p_data[i + 1]) || is_yeh(p_data[i + 1])) {
  3919. if (is_connected_to_prev(c, pc)) {
  3920. kashida_pos = i - 1;
  3921. priority = 4;
  3922. }
  3923. }
  3924. }
  3925. }
  3926. if (priority >= 5 && i > p_start) {
  3927. if (is_waw(c) || ((is_ain(c) || is_qaf(c) || is_feh(c)) && i == p_end - 1)) {
  3928. if (is_connected_to_prev(c, pc)) {
  3929. kashida_pos = i - 1;
  3930. priority = 5;
  3931. }
  3932. }
  3933. }
  3934. if (priority >= 6 && i > p_start) {
  3935. if (is_reh(c)) {
  3936. if (is_connected_to_prev(c, pc)) {
  3937. kashida_pos = i - 1;
  3938. priority = 6;
  3939. }
  3940. }
  3941. }
  3942. if (!is_transparent(c)) {
  3943. pc = c;
  3944. }
  3945. i++;
  3946. }
  3947. return kashida_pos;
  3948. }
  3949. bool TextServerAdvanced::shaped_text_update_justification_ops(const RID &p_shaped) {
  3950. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3951. ERR_FAIL_COND_V(!sd, false);
  3952. MutexLock lock(sd->mutex);
  3953. if (!sd->valid) {
  3954. shaped_text_shape(p_shaped);
  3955. }
  3956. if (!sd->line_breaks_valid) {
  3957. shaped_text_update_breaks(p_shaped);
  3958. }
  3959. if (sd->justification_ops_valid) {
  3960. return true; // Nothing to do.
  3961. }
  3962. const UChar *data = sd->utf16.get_data();
  3963. int data_size = sd->utf16.length();
  3964. if (!sd->js_ops_valid) {
  3965. sd->jstops.clear();
  3966. // Use ICU word iterator and custom kashida detection.
  3967. UErrorCode err = U_ZERO_ERROR;
  3968. UBreakIterator *bi = ubrk_open(UBRK_WORD, "", data, data_size, &err);
  3969. if (U_FAILURE(err)) {
  3970. // No data - use fallback.
  3971. int limit = 0;
  3972. for (int i = 0; i < sd->text.length(); i++) {
  3973. if (is_whitespace(data[i])) {
  3974. int ks = _generate_kashida_justification_opportunies(sd->text, limit, i) + sd->start;
  3975. if (ks != -1) {
  3976. sd->jstops[ks] = true;
  3977. }
  3978. limit = i + 1;
  3979. }
  3980. }
  3981. int ks = _generate_kashida_justification_opportunies(sd->text, limit, sd->text.length()) + sd->start;
  3982. if (ks != -1) {
  3983. sd->jstops[ks] = true;
  3984. }
  3985. } else {
  3986. int limit = 0;
  3987. while (ubrk_next(bi) != UBRK_DONE) {
  3988. if (ubrk_getRuleStatus(bi) != UBRK_WORD_NONE) {
  3989. int i = _convert_pos(sd, ubrk_current(bi));
  3990. sd->jstops[i + sd->start] = false;
  3991. int ks = _generate_kashida_justification_opportunies(sd->text, limit, i);
  3992. if (ks != -1) {
  3993. sd->jstops[ks + sd->start] = true;
  3994. }
  3995. limit = i;
  3996. }
  3997. }
  3998. ubrk_close(bi);
  3999. }
  4000. sd->js_ops_valid = true;
  4001. }
  4002. sd->sort_valid = false;
  4003. sd->glyphs_logical.clear();
  4004. Glyph *sd_glyphs = sd->glyphs.ptrw();
  4005. int sd_size = sd->glyphs.size();
  4006. if (!sd->jstops.is_empty()) {
  4007. for (int i = 0; i < sd_size; i++) {
  4008. if (sd_glyphs[i].count > 0) {
  4009. char32_t c = sd->text[sd_glyphs[i].start - sd->start];
  4010. if (c == 0x0640 && sd_glyphs[i].start == sd_glyphs[i].end - 1) {
  4011. sd_glyphs[i].flags |= GRAPHEME_IS_ELONGATION;
  4012. }
  4013. if (sd->jstops.has(sd_glyphs[i].start)) {
  4014. if (c == 0xfffc) {
  4015. continue;
  4016. }
  4017. if (sd->jstops[sd_glyphs[i].start]) {
  4018. if (c != 0x0640) {
  4019. if (sd_glyphs[i].font_rid != RID()) {
  4020. Glyph gl = _shape_single_glyph(sd, 0x0640, HB_SCRIPT_ARABIC, HB_DIRECTION_RTL, sd->glyphs[i].font_rid, sd->glyphs[i].font_size);
  4021. if ((sd_glyphs[i].flags & GRAPHEME_IS_VALID) == GRAPHEME_IS_VALID) {
  4022. #if HB_VERSION_ATLEAST(5, 1, 0)
  4023. if ((i > 0) && ((sd_glyphs[i - 1].flags & GRAPHEME_IS_SAFE_TO_INSERT_TATWEEL) != GRAPHEME_IS_SAFE_TO_INSERT_TATWEEL)) {
  4024. continue;
  4025. }
  4026. #endif
  4027. gl.start = sd_glyphs[i].start;
  4028. gl.end = sd_glyphs[i].end;
  4029. gl.repeat = 0;
  4030. gl.count = 1;
  4031. if (sd->orientation == ORIENTATION_HORIZONTAL) {
  4032. gl.y_off = sd_glyphs[i].y_off;
  4033. } else {
  4034. gl.x_off = sd_glyphs[i].x_off;
  4035. }
  4036. gl.flags |= GRAPHEME_IS_ELONGATION | GRAPHEME_IS_VIRTUAL;
  4037. sd->glyphs.insert(i, gl);
  4038. i++;
  4039. // Update write pointer and size.
  4040. sd_size = sd->glyphs.size();
  4041. sd_glyphs = sd->glyphs.ptrw();
  4042. continue;
  4043. }
  4044. }
  4045. }
  4046. } else if ((sd_glyphs[i].flags & GRAPHEME_IS_SPACE) != GRAPHEME_IS_SPACE) {
  4047. int count = sd_glyphs[i].count;
  4048. // Do not add extra spaces at the end of the line.
  4049. if (sd_glyphs[i].end == sd->end) {
  4050. continue;
  4051. }
  4052. // Do not add extra space after existing space.
  4053. if (sd_glyphs[i].flags & GRAPHEME_IS_RTL) {
  4054. if ((i + count < sd_size - 1) && ((sd_glyphs[i + count].flags & (GRAPHEME_IS_SPACE | GRAPHEME_IS_BREAK_SOFT)) == (GRAPHEME_IS_SPACE | GRAPHEME_IS_BREAK_SOFT))) {
  4055. continue;
  4056. }
  4057. } else {
  4058. if ((i > 0) && ((sd_glyphs[i - 1].flags & (GRAPHEME_IS_SPACE | GRAPHEME_IS_BREAK_SOFT)) == (GRAPHEME_IS_SPACE | GRAPHEME_IS_BREAK_SOFT))) {
  4059. continue;
  4060. }
  4061. }
  4062. // Inject virtual space for alignment.
  4063. Glyph gl;
  4064. gl.start = sd_glyphs[i].start;
  4065. gl.end = sd_glyphs[i].end;
  4066. gl.count = 1;
  4067. gl.font_rid = sd_glyphs[i].font_rid;
  4068. gl.font_size = sd_glyphs[i].font_size;
  4069. gl.flags = GRAPHEME_IS_SPACE | GRAPHEME_IS_VIRTUAL;
  4070. if (sd_glyphs[i].flags & GRAPHEME_IS_RTL) {
  4071. gl.flags |= GRAPHEME_IS_RTL;
  4072. sd->glyphs.insert(i, gl); // Insert before.
  4073. } else {
  4074. sd->glyphs.insert(i + count, gl); // Insert after.
  4075. }
  4076. i += count;
  4077. // Update write pointer and size.
  4078. sd_size = sd->glyphs.size();
  4079. sd_glyphs = sd->glyphs.ptrw();
  4080. continue;
  4081. }
  4082. }
  4083. }
  4084. }
  4085. }
  4086. sd->justification_ops_valid = true;
  4087. return sd->justification_ops_valid;
  4088. }
  4089. Glyph TextServerAdvanced::_shape_single_glyph(ShapedTextDataAdvanced *p_sd, char32_t p_char, hb_script_t p_script, hb_direction_t p_direction, const RID &p_font, int64_t p_font_size) {
  4090. hb_font_t *hb_font = _font_get_hb_handle(p_font, p_font_size);
  4091. bool subpos = (font_get_subpixel_positioning(p_font) == SUBPIXEL_POSITIONING_ONE_HALF) || (font_get_subpixel_positioning(p_font) == SUBPIXEL_POSITIONING_ONE_QUARTER) || (font_get_subpixel_positioning(p_font) == SUBPIXEL_POSITIONING_AUTO && p_font_size <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE);
  4092. ERR_FAIL_COND_V(hb_font == nullptr, Glyph());
  4093. hb_buffer_clear_contents(p_sd->hb_buffer);
  4094. hb_buffer_set_direction(p_sd->hb_buffer, p_direction);
  4095. hb_buffer_set_flags(p_sd->hb_buffer, (hb_buffer_flags_t)(HB_BUFFER_FLAG_DEFAULT));
  4096. hb_buffer_set_script(p_sd->hb_buffer, p_script);
  4097. hb_buffer_add_utf32(p_sd->hb_buffer, (const uint32_t *)&p_char, 1, 0, 1);
  4098. hb_shape(hb_font, p_sd->hb_buffer, nullptr, 0);
  4099. unsigned int glyph_count = 0;
  4100. hb_glyph_info_t *glyph_info = hb_buffer_get_glyph_infos(p_sd->hb_buffer, &glyph_count);
  4101. hb_glyph_position_t *glyph_pos = hb_buffer_get_glyph_positions(p_sd->hb_buffer, &glyph_count);
  4102. // Process glyphs.
  4103. Glyph gl;
  4104. if (p_direction == HB_DIRECTION_RTL || p_direction == HB_DIRECTION_BTT) {
  4105. gl.flags |= TextServer::GRAPHEME_IS_RTL;
  4106. }
  4107. gl.font_rid = p_font;
  4108. gl.font_size = p_font_size;
  4109. if (glyph_count > 0) {
  4110. double scale = font_get_scale(p_font, p_font_size);
  4111. if (p_sd->orientation == ORIENTATION_HORIZONTAL) {
  4112. if (subpos) {
  4113. gl.advance = glyph_pos[0].x_advance / (64.0 / scale) + _get_extra_advance(p_font, p_font_size);
  4114. } else {
  4115. gl.advance = Math::round(glyph_pos[0].x_advance / (64.0 / scale) + _get_extra_advance(p_font, p_font_size));
  4116. }
  4117. } else {
  4118. gl.advance = -Math::round(glyph_pos[0].y_advance / (64.0 / scale));
  4119. }
  4120. gl.count = 1;
  4121. gl.index = glyph_info[0].codepoint;
  4122. if (subpos) {
  4123. gl.x_off = glyph_pos[0].x_offset / (64.0 / scale);
  4124. } else {
  4125. gl.x_off = Math::round(glyph_pos[0].x_offset / (64.0 / scale));
  4126. }
  4127. gl.y_off = -Math::round(glyph_pos[0].y_offset / (64.0 / scale));
  4128. if ((glyph_info[0].codepoint != 0) || !u_isgraph(p_char)) {
  4129. gl.flags |= GRAPHEME_IS_VALID;
  4130. }
  4131. }
  4132. return gl;
  4133. }
  4134. _FORCE_INLINE_ void TextServerAdvanced::_add_featuers(const Dictionary &p_source, Vector<hb_feature_t> &r_ftrs) {
  4135. Array keys = p_source.keys();
  4136. Array values = p_source.values();
  4137. for (int i = 0; i < keys.size(); i++) {
  4138. int32_t value = values[i];
  4139. if (value >= 0) {
  4140. hb_feature_t feature;
  4141. if (keys[i].get_type() == Variant::STRING) {
  4142. feature.tag = name_to_tag(keys[i]);
  4143. } else {
  4144. feature.tag = keys[i];
  4145. }
  4146. feature.value = value;
  4147. feature.start = 0;
  4148. feature.end = -1;
  4149. r_ftrs.push_back(feature);
  4150. }
  4151. }
  4152. }
  4153. void TextServerAdvanced::_shape_run(ShapedTextDataAdvanced *p_sd, int64_t p_start, int64_t p_end, hb_script_t p_script, hb_direction_t p_direction, Array p_fonts, int64_t p_span, int64_t p_fb_index) {
  4154. int fs = p_sd->spans[p_span].font_size;
  4155. if (p_fb_index >= p_fonts.size()) {
  4156. // Add fallback glyphs.
  4157. for (int i = p_start; i < p_end; i++) {
  4158. if (p_sd->preserve_invalid || (p_sd->preserve_control && is_control(p_sd->text[i]))) {
  4159. Glyph gl;
  4160. gl.start = i + p_sd->start;
  4161. gl.end = i + 1 + p_sd->start;
  4162. gl.count = 1;
  4163. gl.index = p_sd->text[i];
  4164. gl.font_size = fs;
  4165. gl.font_rid = RID();
  4166. if (p_direction == HB_DIRECTION_RTL || p_direction == HB_DIRECTION_BTT) {
  4167. gl.flags |= TextServer::GRAPHEME_IS_RTL;
  4168. }
  4169. if (p_sd->orientation == ORIENTATION_HORIZONTAL) {
  4170. gl.advance = get_hex_code_box_size(fs, gl.index).x;
  4171. p_sd->ascent = MAX(p_sd->ascent, get_hex_code_box_size(fs, gl.index).y);
  4172. } else {
  4173. gl.advance = get_hex_code_box_size(fs, gl.index).y;
  4174. p_sd->ascent = MAX(p_sd->ascent, Math::round(get_hex_code_box_size(fs, gl.index).x * 0.5));
  4175. p_sd->descent = MAX(p_sd->descent, Math::round(get_hex_code_box_size(fs, gl.index).x * 0.5));
  4176. }
  4177. p_sd->width += gl.advance;
  4178. p_sd->glyphs.push_back(gl);
  4179. }
  4180. }
  4181. return;
  4182. }
  4183. RID f = p_fonts[p_fb_index];
  4184. FontAdvanced *fd = font_owner.get_or_null(f);
  4185. ERR_FAIL_COND(!fd);
  4186. MutexLock lock(fd->mutex);
  4187. Vector2i fss = _get_size(fd, fs);
  4188. hb_font_t *hb_font = _font_get_hb_handle(f, fs);
  4189. double scale = font_get_scale(f, fs);
  4190. double sp_sp = p_sd->extra_spacing[SPACING_SPACE];
  4191. double sp_gl = p_sd->extra_spacing[SPACING_GLYPH];
  4192. bool last_run = (p_sd->end == p_end);
  4193. double ea = _get_extra_advance(f, fs);
  4194. bool subpos = (font_get_subpixel_positioning(f) == SUBPIXEL_POSITIONING_ONE_HALF) || (font_get_subpixel_positioning(f) == SUBPIXEL_POSITIONING_ONE_QUARTER) || (font_get_subpixel_positioning(f) == SUBPIXEL_POSITIONING_AUTO && fs <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE);
  4195. ERR_FAIL_COND(hb_font == nullptr);
  4196. hb_buffer_clear_contents(p_sd->hb_buffer);
  4197. hb_buffer_set_direction(p_sd->hb_buffer, p_direction);
  4198. int flags = (p_start == 0 ? HB_BUFFER_FLAG_BOT : 0) | (p_end == p_sd->text.length() ? HB_BUFFER_FLAG_EOT : 0);
  4199. if (p_sd->preserve_control) {
  4200. flags |= HB_BUFFER_FLAG_PRESERVE_DEFAULT_IGNORABLES;
  4201. } else {
  4202. flags |= HB_BUFFER_FLAG_DEFAULT;
  4203. }
  4204. #if HB_VERSION_ATLEAST(5, 1, 0)
  4205. flags |= HB_BUFFER_FLAG_PRODUCE_SAFE_TO_INSERT_TATWEEL;
  4206. #endif
  4207. hb_buffer_set_flags(p_sd->hb_buffer, (hb_buffer_flags_t)flags);
  4208. hb_buffer_set_script(p_sd->hb_buffer, p_script);
  4209. if (p_sd->spans[p_span].language.is_empty()) {
  4210. hb_language_t lang = hb_language_from_string(TranslationServer::get_singleton()->get_tool_locale().ascii().get_data(), -1);
  4211. hb_buffer_set_language(p_sd->hb_buffer, lang);
  4212. } else {
  4213. hb_language_t lang = hb_language_from_string(p_sd->spans[p_span].language.ascii().get_data(), -1);
  4214. hb_buffer_set_language(p_sd->hb_buffer, lang);
  4215. }
  4216. hb_buffer_add_utf32(p_sd->hb_buffer, (const uint32_t *)p_sd->text.ptr(), p_sd->text.length(), p_start, p_end - p_start);
  4217. Vector<hb_feature_t> ftrs;
  4218. _add_featuers(font_get_opentype_feature_overrides(f), ftrs);
  4219. _add_featuers(p_sd->spans[p_span].features, ftrs);
  4220. hb_shape(hb_font, p_sd->hb_buffer, ftrs.is_empty() ? nullptr : &ftrs[0], ftrs.size());
  4221. unsigned int glyph_count = 0;
  4222. hb_glyph_info_t *glyph_info = hb_buffer_get_glyph_infos(p_sd->hb_buffer, &glyph_count);
  4223. hb_glyph_position_t *glyph_pos = hb_buffer_get_glyph_positions(p_sd->hb_buffer, &glyph_count);
  4224. // Process glyphs.
  4225. if (glyph_count > 0) {
  4226. Glyph *w = (Glyph *)memalloc(glyph_count * sizeof(Glyph));
  4227. int end = (p_direction == HB_DIRECTION_RTL || p_direction == HB_DIRECTION_BTT) ? p_end : 0;
  4228. uint32_t last_cluster_id = UINT32_MAX;
  4229. unsigned int last_cluster_index = 0;
  4230. bool last_cluster_valid = true;
  4231. for (unsigned int i = 0; i < glyph_count; i++) {
  4232. if ((i > 0) && (last_cluster_id != glyph_info[i].cluster)) {
  4233. if (p_direction == HB_DIRECTION_RTL || p_direction == HB_DIRECTION_BTT) {
  4234. end = w[last_cluster_index].start;
  4235. } else {
  4236. for (unsigned int j = last_cluster_index; j < i; j++) {
  4237. w[j].end = glyph_info[i].cluster;
  4238. }
  4239. }
  4240. if (p_direction == HB_DIRECTION_RTL || p_direction == HB_DIRECTION_BTT) {
  4241. w[last_cluster_index].flags |= GRAPHEME_IS_RTL;
  4242. }
  4243. if (last_cluster_valid) {
  4244. w[last_cluster_index].flags |= GRAPHEME_IS_VALID;
  4245. }
  4246. w[last_cluster_index].count = i - last_cluster_index;
  4247. last_cluster_index = i;
  4248. last_cluster_valid = true;
  4249. }
  4250. last_cluster_id = glyph_info[i].cluster;
  4251. Glyph &gl = w[i];
  4252. gl = Glyph();
  4253. gl.start = glyph_info[i].cluster;
  4254. gl.end = end;
  4255. gl.count = 0;
  4256. gl.font_rid = p_fonts[p_fb_index];
  4257. gl.font_size = fs;
  4258. if (glyph_info[i].mask & HB_GLYPH_FLAG_UNSAFE_TO_BREAK) {
  4259. gl.flags |= GRAPHEME_IS_CONNECTED;
  4260. }
  4261. #if HB_VERSION_ATLEAST(5, 1, 0)
  4262. if (glyph_info[i].mask & HB_GLYPH_FLAG_SAFE_TO_INSERT_TATWEEL) {
  4263. gl.flags |= GRAPHEME_IS_SAFE_TO_INSERT_TATWEEL;
  4264. }
  4265. #endif
  4266. gl.index = glyph_info[i].codepoint;
  4267. if (gl.index != 0) {
  4268. _ensure_glyph(fd, fss, gl.index);
  4269. if (p_sd->orientation == ORIENTATION_HORIZONTAL) {
  4270. if (subpos) {
  4271. gl.advance = glyph_pos[i].x_advance / (64.0 / scale) + ea;
  4272. } else {
  4273. gl.advance = Math::round(glyph_pos[i].x_advance / (64.0 / scale) + ea);
  4274. }
  4275. } else {
  4276. gl.advance = -Math::round(glyph_pos[i].y_advance / (64.0 / scale));
  4277. }
  4278. if (subpos) {
  4279. gl.x_off = glyph_pos[i].x_offset / (64.0 / scale);
  4280. } else {
  4281. gl.x_off = Math::round(glyph_pos[i].x_offset / (64.0 / scale));
  4282. }
  4283. gl.y_off = -Math::round(glyph_pos[i].y_offset / (64.0 / scale));
  4284. }
  4285. if (!last_run || i < glyph_count - 1) {
  4286. // Do not add extra spacing to the last glyph of the string.
  4287. if (sp_sp && is_whitespace(p_sd->text[glyph_info[i].cluster])) {
  4288. gl.advance += sp_sp;
  4289. } else {
  4290. gl.advance += sp_gl;
  4291. }
  4292. }
  4293. if (p_sd->preserve_control) {
  4294. last_cluster_valid = last_cluster_valid && ((glyph_info[i].codepoint != 0) || (p_sd->text[glyph_info[i].cluster] == 0x0009) || (u_isblank(p_sd->text[glyph_info[i].cluster]) && (gl.advance != 0)) || (!u_isblank(p_sd->text[glyph_info[i].cluster]) && is_linebreak(p_sd->text[glyph_info[i].cluster])));
  4295. } else {
  4296. last_cluster_valid = last_cluster_valid && ((glyph_info[i].codepoint != 0) || (p_sd->text[glyph_info[i].cluster] == 0x0009) || (u_isblank(p_sd->text[glyph_info[i].cluster]) && (gl.advance != 0)) || (!u_isblank(p_sd->text[glyph_info[i].cluster]) && !u_isgraph(p_sd->text[glyph_info[i].cluster])));
  4297. }
  4298. }
  4299. if (p_direction == HB_DIRECTION_LTR || p_direction == HB_DIRECTION_TTB) {
  4300. for (unsigned int j = last_cluster_index; j < glyph_count; j++) {
  4301. w[j].end = p_end;
  4302. }
  4303. }
  4304. w[last_cluster_index].count = glyph_count - last_cluster_index;
  4305. if (p_direction == HB_DIRECTION_RTL || p_direction == HB_DIRECTION_BTT) {
  4306. w[last_cluster_index].flags |= GRAPHEME_IS_RTL;
  4307. }
  4308. if (last_cluster_valid) {
  4309. w[last_cluster_index].flags |= GRAPHEME_IS_VALID;
  4310. }
  4311. // Fallback.
  4312. int failed_subrun_start = p_end + 1;
  4313. int failed_subrun_end = p_start;
  4314. for (unsigned int i = 0; i < glyph_count; i++) {
  4315. if ((w[i].flags & GRAPHEME_IS_VALID) == GRAPHEME_IS_VALID) {
  4316. if (failed_subrun_start != p_end + 1) {
  4317. _shape_run(p_sd, failed_subrun_start, failed_subrun_end, p_script, p_direction, p_fonts, p_span, p_fb_index + 1);
  4318. failed_subrun_start = p_end + 1;
  4319. failed_subrun_end = p_start;
  4320. }
  4321. for (int j = 0; j < w[i].count; j++) {
  4322. if (p_sd->orientation == ORIENTATION_HORIZONTAL) {
  4323. p_sd->ascent = MAX(p_sd->ascent, -w[i + j].y_off);
  4324. p_sd->descent = MAX(p_sd->descent, w[i + j].y_off);
  4325. } else {
  4326. double gla = Math::round(font_get_glyph_advance(f, fs, w[i + j].index).x * 0.5);
  4327. p_sd->ascent = MAX(p_sd->ascent, gla);
  4328. p_sd->descent = MAX(p_sd->descent, gla);
  4329. }
  4330. p_sd->width += w[i + j].advance;
  4331. w[i + j].start += p_sd->start;
  4332. w[i + j].end += p_sd->start;
  4333. p_sd->glyphs.push_back(w[i + j]);
  4334. }
  4335. } else {
  4336. if (failed_subrun_start >= w[i].start) {
  4337. failed_subrun_start = w[i].start;
  4338. }
  4339. if (failed_subrun_end <= w[i].end) {
  4340. failed_subrun_end = w[i].end;
  4341. }
  4342. }
  4343. i += w[i].count - 1;
  4344. }
  4345. memfree(w);
  4346. if (failed_subrun_start != p_end + 1) {
  4347. _shape_run(p_sd, failed_subrun_start, failed_subrun_end, p_script, p_direction, p_fonts, p_span, p_fb_index + 1);
  4348. }
  4349. p_sd->ascent = MAX(p_sd->ascent, font_get_ascent(f, fs));
  4350. p_sd->descent = MAX(p_sd->descent, font_get_descent(f, fs));
  4351. p_sd->upos = MAX(p_sd->upos, font_get_underline_position(f, fs));
  4352. p_sd->uthk = MAX(p_sd->uthk, font_get_underline_thickness(f, fs));
  4353. }
  4354. }
  4355. bool TextServerAdvanced::shaped_text_shape(const RID &p_shaped) {
  4356. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4357. ERR_FAIL_COND_V(!sd, false);
  4358. MutexLock lock(sd->mutex);
  4359. if (sd->valid) {
  4360. return true;
  4361. }
  4362. invalidate(sd, false);
  4363. if (sd->parent != RID()) {
  4364. shaped_text_shape(sd->parent);
  4365. ShapedTextDataAdvanced *parent_sd = shaped_owner.get_or_null(sd->parent);
  4366. ERR_FAIL_COND_V(!parent_sd->valid, false);
  4367. ERR_FAIL_COND_V(!_shape_substr(sd, parent_sd, sd->start, sd->end - sd->start), false);
  4368. return true;
  4369. }
  4370. if (sd->text.length() == 0) {
  4371. sd->valid = true;
  4372. return true;
  4373. }
  4374. sd->utf16 = sd->text.utf16();
  4375. const UChar *data = sd->utf16.get_data();
  4376. // Create script iterator.
  4377. if (sd->script_iter == nullptr) {
  4378. sd->script_iter = memnew(ScriptIterator(sd->text, 0, sd->text.length()));
  4379. }
  4380. if (sd->bidi_override.is_empty()) {
  4381. sd->bidi_override.push_back(Vector2i(sd->start, sd->end));
  4382. }
  4383. for (int ov = 0; ov < sd->bidi_override.size(); ov++) {
  4384. // Create BiDi iterator.
  4385. int start = _convert_pos_inv(sd, sd->bidi_override[ov].x - sd->start);
  4386. int end = _convert_pos_inv(sd, sd->bidi_override[ov].y - sd->start);
  4387. if (start < 0 || end - start > sd->utf16.length()) {
  4388. continue;
  4389. }
  4390. UErrorCode err = U_ZERO_ERROR;
  4391. UBiDi *bidi_iter = ubidi_openSized(end, 0, &err);
  4392. ERR_FAIL_COND_V_MSG(U_FAILURE(err), false, u_errorName(err));
  4393. switch (sd->direction) {
  4394. case DIRECTION_LTR: {
  4395. ubidi_setPara(bidi_iter, data + start, end - start, UBIDI_LTR, nullptr, &err);
  4396. sd->para_direction = DIRECTION_LTR;
  4397. } break;
  4398. case DIRECTION_RTL: {
  4399. ubidi_setPara(bidi_iter, data + start, end - start, UBIDI_RTL, nullptr, &err);
  4400. sd->para_direction = DIRECTION_RTL;
  4401. } break;
  4402. case DIRECTION_AUTO: {
  4403. UBiDiDirection direction = ubidi_getBaseDirection(data + start, end - start);
  4404. if (direction != UBIDI_NEUTRAL) {
  4405. ubidi_setPara(bidi_iter, data + start, end - start, direction, nullptr, &err);
  4406. sd->para_direction = (direction == UBIDI_RTL) ? DIRECTION_RTL : DIRECTION_LTR;
  4407. } else {
  4408. ubidi_setPara(bidi_iter, data + start, end - start, UBIDI_DEFAULT_LTR, nullptr, &err);
  4409. sd->para_direction = DIRECTION_LTR;
  4410. }
  4411. } break;
  4412. }
  4413. ERR_FAIL_COND_V_MSG(U_FAILURE(err), false, u_errorName(err));
  4414. sd->bidi_iter.push_back(bidi_iter);
  4415. err = U_ZERO_ERROR;
  4416. int bidi_run_count = ubidi_countRuns(bidi_iter, &err);
  4417. ERR_FAIL_COND_V_MSG(U_FAILURE(err), false, u_errorName(err));
  4418. for (int i = 0; i < bidi_run_count; i++) {
  4419. int32_t _bidi_run_start = 0;
  4420. int32_t _bidi_run_length = 0;
  4421. hb_direction_t bidi_run_direction = HB_DIRECTION_INVALID;
  4422. bool is_rtl = (ubidi_getVisualRun(bidi_iter, i, &_bidi_run_start, &_bidi_run_length) == UBIDI_LTR);
  4423. switch (sd->orientation) {
  4424. case ORIENTATION_HORIZONTAL: {
  4425. if (is_rtl) {
  4426. bidi_run_direction = HB_DIRECTION_LTR;
  4427. } else {
  4428. bidi_run_direction = HB_DIRECTION_RTL;
  4429. }
  4430. } break;
  4431. case ORIENTATION_VERTICAL: {
  4432. if (is_rtl) {
  4433. bidi_run_direction = HB_DIRECTION_TTB;
  4434. } else {
  4435. bidi_run_direction = HB_DIRECTION_BTT;
  4436. }
  4437. }
  4438. }
  4439. int32_t bidi_run_start = _convert_pos(sd, sd->bidi_override[ov].x - sd->start + _bidi_run_start);
  4440. int32_t bidi_run_end = _convert_pos(sd, sd->bidi_override[ov].x - sd->start + _bidi_run_start + _bidi_run_length);
  4441. // Shape runs.
  4442. int scr_from = (is_rtl) ? 0 : sd->script_iter->script_ranges.size() - 1;
  4443. int scr_to = (is_rtl) ? sd->script_iter->script_ranges.size() : -1;
  4444. int scr_delta = (is_rtl) ? +1 : -1;
  4445. for (int j = scr_from; j != scr_to; j += scr_delta) {
  4446. if ((sd->script_iter->script_ranges[j].start < bidi_run_end) && (sd->script_iter->script_ranges[j].end > bidi_run_start)) {
  4447. int32_t script_run_start = MAX(sd->script_iter->script_ranges[j].start, bidi_run_start);
  4448. int32_t script_run_end = MIN(sd->script_iter->script_ranges[j].end, bidi_run_end);
  4449. char scr_buffer[5] = { 0, 0, 0, 0, 0 };
  4450. hb_tag_to_string(hb_script_to_iso15924_tag(sd->script_iter->script_ranges[j].script), scr_buffer);
  4451. String script = String(scr_buffer);
  4452. int spn_from = (is_rtl) ? 0 : sd->spans.size() - 1;
  4453. int spn_to = (is_rtl) ? sd->spans.size() : -1;
  4454. int spn_delta = (is_rtl) ? +1 : -1;
  4455. for (int k = spn_from; k != spn_to; k += spn_delta) {
  4456. const ShapedTextDataAdvanced::Span &span = sd->spans[k];
  4457. if (span.start - sd->start >= script_run_end || span.end - sd->start <= script_run_start) {
  4458. continue;
  4459. }
  4460. if (span.embedded_key != Variant()) {
  4461. // Embedded object.
  4462. if (sd->orientation == ORIENTATION_HORIZONTAL) {
  4463. sd->objects[span.embedded_key].rect.position.x = sd->width;
  4464. sd->width += sd->objects[span.embedded_key].rect.size.x;
  4465. } else {
  4466. sd->objects[span.embedded_key].rect.position.y = sd->width;
  4467. sd->width += sd->objects[span.embedded_key].rect.size.y;
  4468. }
  4469. Glyph gl;
  4470. gl.start = span.start;
  4471. gl.end = span.end;
  4472. gl.count = 1;
  4473. gl.flags = GRAPHEME_IS_VALID | GRAPHEME_IS_VIRTUAL;
  4474. if (sd->orientation == ORIENTATION_HORIZONTAL) {
  4475. gl.advance = sd->objects[span.embedded_key].rect.size.x;
  4476. } else {
  4477. gl.advance = sd->objects[span.embedded_key].rect.size.y;
  4478. }
  4479. sd->glyphs.push_back(gl);
  4480. } else {
  4481. Array fonts;
  4482. Array fonts_scr_only;
  4483. Array fonts_no_match;
  4484. int font_count = span.fonts.size();
  4485. for (int l = 0; l < font_count; l++) {
  4486. if (font_is_script_supported(span.fonts[l], script)) {
  4487. if (font_is_language_supported(span.fonts[l], span.language)) {
  4488. fonts.push_back(sd->spans[k].fonts[l]);
  4489. } else {
  4490. fonts_scr_only.push_back(sd->spans[k].fonts[l]);
  4491. }
  4492. } else {
  4493. fonts_no_match.push_back(sd->spans[k].fonts[l]);
  4494. }
  4495. }
  4496. fonts.append_array(fonts_scr_only);
  4497. fonts.append_array(fonts_no_match);
  4498. _shape_run(sd, MAX(sd->spans[k].start - sd->start, script_run_start), MIN(sd->spans[k].end - sd->start, script_run_end), sd->script_iter->script_ranges[j].script, bidi_run_direction, fonts, k, 0);
  4499. }
  4500. }
  4501. }
  4502. }
  4503. }
  4504. }
  4505. _realign(sd);
  4506. sd->valid = true;
  4507. return sd->valid;
  4508. }
  4509. bool TextServerAdvanced::shaped_text_is_ready(const RID &p_shaped) const {
  4510. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4511. ERR_FAIL_COND_V(!sd, false);
  4512. MutexLock lock(sd->mutex);
  4513. return sd->valid;
  4514. }
  4515. const Glyph *TextServerAdvanced::shaped_text_get_glyphs(const RID &p_shaped) const {
  4516. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4517. ERR_FAIL_COND_V(!sd, nullptr);
  4518. MutexLock lock(sd->mutex);
  4519. if (!sd->valid) {
  4520. const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped);
  4521. }
  4522. return sd->glyphs.ptr();
  4523. }
  4524. int64_t TextServerAdvanced::shaped_text_get_glyph_count(const RID &p_shaped) const {
  4525. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4526. ERR_FAIL_COND_V(!sd, 0);
  4527. MutexLock lock(sd->mutex);
  4528. if (!sd->valid) {
  4529. const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped);
  4530. }
  4531. return sd->glyphs.size();
  4532. }
  4533. const Glyph *TextServerAdvanced::shaped_text_sort_logical(const RID &p_shaped) {
  4534. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4535. ERR_FAIL_COND_V(!sd, nullptr);
  4536. MutexLock lock(sd->mutex);
  4537. if (!sd->valid) {
  4538. const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped);
  4539. }
  4540. if (!sd->sort_valid) {
  4541. sd->glyphs_logical = sd->glyphs;
  4542. sd->glyphs_logical.sort_custom<GlyphCompare>();
  4543. sd->sort_valid = true;
  4544. }
  4545. return sd->glyphs_logical.ptr();
  4546. }
  4547. Vector2i TextServerAdvanced::shaped_text_get_range(const RID &p_shaped) const {
  4548. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4549. ERR_FAIL_COND_V(!sd, Vector2i());
  4550. MutexLock lock(sd->mutex);
  4551. return Vector2(sd->start, sd->end);
  4552. }
  4553. Array TextServerAdvanced::shaped_text_get_objects(const RID &p_shaped) const {
  4554. Array ret;
  4555. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4556. ERR_FAIL_COND_V(!sd, ret);
  4557. MutexLock lock(sd->mutex);
  4558. for (const KeyValue<Variant, ShapedTextDataAdvanced::EmbeddedObject> &E : sd->objects) {
  4559. ret.push_back(E.key);
  4560. }
  4561. return ret;
  4562. }
  4563. Rect2 TextServerAdvanced::shaped_text_get_object_rect(const RID &p_shaped, const Variant &p_key) const {
  4564. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4565. ERR_FAIL_COND_V(!sd, Rect2());
  4566. MutexLock lock(sd->mutex);
  4567. ERR_FAIL_COND_V(!sd->objects.has(p_key), Rect2());
  4568. if (!sd->valid) {
  4569. const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped);
  4570. }
  4571. return sd->objects[p_key].rect;
  4572. }
  4573. Size2 TextServerAdvanced::shaped_text_get_size(const RID &p_shaped) const {
  4574. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4575. ERR_FAIL_COND_V(!sd, Size2());
  4576. MutexLock lock(sd->mutex);
  4577. if (!sd->valid) {
  4578. const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped);
  4579. }
  4580. if (sd->orientation == TextServer::ORIENTATION_HORIZONTAL) {
  4581. return Size2((sd->text_trimmed ? sd->width_trimmed : sd->width), sd->ascent + sd->descent + sd->extra_spacing[SPACING_TOP] + sd->extra_spacing[SPACING_BOTTOM]).ceil();
  4582. } else {
  4583. return Size2(sd->ascent + sd->descent + sd->extra_spacing[SPACING_TOP] + sd->extra_spacing[SPACING_BOTTOM], (sd->text_trimmed ? sd->width_trimmed : sd->width)).ceil();
  4584. }
  4585. }
  4586. double TextServerAdvanced::shaped_text_get_ascent(const RID &p_shaped) const {
  4587. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4588. ERR_FAIL_COND_V(!sd, 0.0);
  4589. MutexLock lock(sd->mutex);
  4590. if (!sd->valid) {
  4591. const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped);
  4592. }
  4593. return sd->ascent + sd->extra_spacing[SPACING_TOP];
  4594. }
  4595. double TextServerAdvanced::shaped_text_get_descent(const RID &p_shaped) const {
  4596. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4597. ERR_FAIL_COND_V(!sd, 0.0);
  4598. MutexLock lock(sd->mutex);
  4599. if (!sd->valid) {
  4600. const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped);
  4601. }
  4602. return sd->descent + sd->extra_spacing[SPACING_BOTTOM];
  4603. }
  4604. double TextServerAdvanced::shaped_text_get_width(const RID &p_shaped) const {
  4605. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4606. ERR_FAIL_COND_V(!sd, 0.0);
  4607. MutexLock lock(sd->mutex);
  4608. if (!sd->valid) {
  4609. const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped);
  4610. }
  4611. return Math::ceil(sd->text_trimmed ? sd->width_trimmed : sd->width);
  4612. }
  4613. double TextServerAdvanced::shaped_text_get_underline_position(const RID &p_shaped) const {
  4614. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4615. ERR_FAIL_COND_V(!sd, 0.0);
  4616. MutexLock lock(sd->mutex);
  4617. if (!sd->valid) {
  4618. const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped);
  4619. }
  4620. return sd->upos;
  4621. }
  4622. double TextServerAdvanced::shaped_text_get_underline_thickness(const RID &p_shaped) const {
  4623. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4624. ERR_FAIL_COND_V(!sd, 0.0);
  4625. MutexLock lock(sd->mutex);
  4626. if (!sd->valid) {
  4627. const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped);
  4628. }
  4629. return sd->uthk;
  4630. }
  4631. void TextServerAdvanced::_insert_num_systems_lang() {
  4632. // Eastern Arabic numerals.
  4633. {
  4634. NumSystemData ar;
  4635. ar.lang.insert(StringName("ar")); // Arabic
  4636. ar.lang.insert(StringName("ar_AE"));
  4637. ar.lang.insert(StringName("ar_BH"));
  4638. ar.lang.insert(StringName("ar_DJ"));
  4639. ar.lang.insert(StringName("ar_EG"));
  4640. ar.lang.insert(StringName("ar_ER"));
  4641. ar.lang.insert(StringName("ar_IL"));
  4642. ar.lang.insert(StringName("ar_IQ"));
  4643. ar.lang.insert(StringName("ar_JO"));
  4644. ar.lang.insert(StringName("ar_KM"));
  4645. ar.lang.insert(StringName("ar_KW"));
  4646. ar.lang.insert(StringName("ar_LB"));
  4647. ar.lang.insert(StringName("ar_MR"));
  4648. ar.lang.insert(StringName("ar_OM"));
  4649. ar.lang.insert(StringName("ar_PS"));
  4650. ar.lang.insert(StringName("ar_QA"));
  4651. ar.lang.insert(StringName("ar_SA"));
  4652. ar.lang.insert(StringName("ar_SD"));
  4653. ar.lang.insert(StringName("ar_SO"));
  4654. ar.lang.insert(StringName("ar_SS"));
  4655. ar.lang.insert(StringName("ar_SY"));
  4656. ar.lang.insert(StringName("ar_TD"));
  4657. ar.lang.insert(StringName("ar_YE"));
  4658. ar.lang.insert(StringName("ckb")); // Central Kurdish
  4659. ar.lang.insert(StringName("ckb_IQ"));
  4660. ar.lang.insert(StringName("ckb_IR"));
  4661. ar.lang.insert(StringName("sd")); // Sindhi
  4662. ar.lang.insert(StringName("sd_PK"));
  4663. ar.lang.insert(StringName("sd_Arab"));
  4664. ar.lang.insert(StringName("sd_Arab_PK"));
  4665. ar.digits = U"٠١٢٣٤٥٦٧٨٩٫";
  4666. ar.percent_sign = U"٪";
  4667. ar.exp = U"اس";
  4668. num_systems.push_back(ar);
  4669. }
  4670. // Persian and Urdu numerals.
  4671. {
  4672. NumSystemData pr;
  4673. pr.lang.insert(StringName("fa")); // Persian
  4674. pr.lang.insert(StringName("fa_AF"));
  4675. pr.lang.insert(StringName("fa_IR"));
  4676. pr.lang.insert(StringName("ks")); // Kashmiri
  4677. pr.lang.insert(StringName("ks_IN"));
  4678. pr.lang.insert(StringName("ks_Arab"));
  4679. pr.lang.insert(StringName("ks_Arab_IN"));
  4680. pr.lang.insert(StringName("lrc")); // Northern Luri
  4681. pr.lang.insert(StringName("lrc_IQ"));
  4682. pr.lang.insert(StringName("lrc_IR"));
  4683. pr.lang.insert(StringName("mzn")); // Mazanderani
  4684. pr.lang.insert(StringName("mzn_IR"));
  4685. pr.lang.insert(StringName("pa_PK")); // Panjabi
  4686. pr.lang.insert(StringName("pa_Arab"));
  4687. pr.lang.insert(StringName("pa_Arab_PK"));
  4688. pr.lang.insert(StringName("ps")); // Pushto
  4689. pr.lang.insert(StringName("ps_AF"));
  4690. pr.lang.insert(StringName("ps_PK"));
  4691. pr.lang.insert(StringName("ur_IN")); // Urdu
  4692. pr.lang.insert(StringName("uz_AF")); // Uzbek
  4693. pr.lang.insert(StringName("uz_Arab"));
  4694. pr.lang.insert(StringName("uz_Arab_AF"));
  4695. pr.digits = U"۰۱۲۳۴۵۶۷۸۹٫";
  4696. pr.percent_sign = U"٪";
  4697. pr.exp = U"اس";
  4698. num_systems.push_back(pr);
  4699. }
  4700. // Bengali numerals.
  4701. {
  4702. NumSystemData bn;
  4703. bn.lang.insert(StringName("as")); // Assamese
  4704. bn.lang.insert(StringName("as_IN"));
  4705. bn.lang.insert(StringName("bn")); // Bengali
  4706. bn.lang.insert(StringName("bn_BD"));
  4707. bn.lang.insert(StringName("bn_IN"));
  4708. bn.lang.insert(StringName("mni")); // Manipuri
  4709. bn.lang.insert(StringName("mni_IN"));
  4710. bn.lang.insert(StringName("mni_Beng"));
  4711. bn.lang.insert(StringName("mni_Beng_IN"));
  4712. bn.digits = U"০১২৩৪৫৬৭৮৯.";
  4713. bn.percent_sign = U"%";
  4714. bn.exp = U"e";
  4715. num_systems.push_back(bn);
  4716. }
  4717. // Devanagari numerals.
  4718. {
  4719. NumSystemData mr;
  4720. mr.lang.insert(StringName("mr")); // Marathi
  4721. mr.lang.insert(StringName("mr_IN"));
  4722. mr.lang.insert(StringName("ne")); // Nepali
  4723. mr.lang.insert(StringName("ne_IN"));
  4724. mr.lang.insert(StringName("ne_NP"));
  4725. mr.lang.insert(StringName("sa")); // Sanskrit
  4726. mr.lang.insert(StringName("sa_IN"));
  4727. mr.digits = U"०१२३४५६७८९.";
  4728. mr.percent_sign = U"%";
  4729. mr.exp = U"e";
  4730. num_systems.push_back(mr);
  4731. }
  4732. // Dzongkha numerals.
  4733. {
  4734. NumSystemData dz;
  4735. dz.lang.insert(StringName("dz")); // Dzongkha
  4736. dz.lang.insert(StringName("dz_BT"));
  4737. dz.digits = U"༠༡༢༣༤༥༦༧༨༩.";
  4738. dz.percent_sign = U"%";
  4739. dz.exp = U"e";
  4740. num_systems.push_back(dz);
  4741. }
  4742. // Santali numerals.
  4743. {
  4744. NumSystemData sat;
  4745. sat.lang.insert(StringName("sat")); // Santali
  4746. sat.lang.insert(StringName("sat_IN"));
  4747. sat.lang.insert(StringName("sat_Olck"));
  4748. sat.lang.insert(StringName("sat_Olck_IN"));
  4749. sat.digits = U"᱐᱑᱒᱓᱔᱕᱖᱗᱘᱙.";
  4750. sat.percent_sign = U"%";
  4751. sat.exp = U"e";
  4752. num_systems.push_back(sat);
  4753. }
  4754. // Burmese numerals.
  4755. {
  4756. NumSystemData my;
  4757. my.lang.insert(StringName("my")); // Burmese
  4758. my.lang.insert(StringName("my_MM"));
  4759. my.digits = U"၀၁၂၃၄၅၆၇၈၉.";
  4760. my.percent_sign = U"%";
  4761. my.exp = U"e";
  4762. num_systems.push_back(my);
  4763. }
  4764. // Chakma numerals.
  4765. {
  4766. NumSystemData ccp;
  4767. ccp.lang.insert(StringName("ccp")); // Chakma
  4768. ccp.lang.insert(StringName("ccp_BD"));
  4769. ccp.lang.insert(StringName("ccp_IN"));
  4770. ccp.digits = U"𑄶𑄷𑄸𑄹𑄺𑄻𑄼𑄽𑄾𑄿.";
  4771. ccp.percent_sign = U"%";
  4772. ccp.exp = U"e";
  4773. num_systems.push_back(ccp);
  4774. }
  4775. // Adlam numerals.
  4776. {
  4777. NumSystemData ff;
  4778. ff.lang.insert(StringName("ff")); // Fulah
  4779. ff.lang.insert(StringName("ff_Adlm_BF"));
  4780. ff.lang.insert(StringName("ff_Adlm_CM"));
  4781. ff.lang.insert(StringName("ff_Adlm_GH"));
  4782. ff.lang.insert(StringName("ff_Adlm_GM"));
  4783. ff.lang.insert(StringName("ff_Adlm_GN"));
  4784. ff.lang.insert(StringName("ff_Adlm_GW"));
  4785. ff.lang.insert(StringName("ff_Adlm_LR"));
  4786. ff.lang.insert(StringName("ff_Adlm_MR"));
  4787. ff.lang.insert(StringName("ff_Adlm_NE"));
  4788. ff.lang.insert(StringName("ff_Adlm_NG"));
  4789. ff.lang.insert(StringName("ff_Adlm_SL"));
  4790. ff.lang.insert(StringName("ff_Adlm_SN"));
  4791. ff.digits = U"𞥐𞥑𞥒𞥓𞥔𞥕𞥖𞥗𞥘𞥙.";
  4792. ff.percent_sign = U"%";
  4793. ff.exp = U"e";
  4794. num_systems.push_back(ff);
  4795. }
  4796. }
  4797. String TextServerAdvanced::format_number(const String &p_string, const String &p_language) const {
  4798. const StringName lang = (p_language.is_empty()) ? TranslationServer::get_singleton()->get_tool_locale() : p_language;
  4799. String res = p_string;
  4800. for (int i = 0; i < num_systems.size(); i++) {
  4801. if (num_systems[i].lang.has(lang)) {
  4802. if (num_systems[i].digits.is_empty()) {
  4803. return p_string;
  4804. }
  4805. res.replace("e", num_systems[i].exp);
  4806. res.replace("E", num_systems[i].exp);
  4807. char32_t *data = res.ptrw();
  4808. for (int j = 0; j < res.length(); j++) {
  4809. if (data[j] >= 0x30 && data[j] <= 0x39) {
  4810. data[j] = num_systems[i].digits[data[j] - 0x30];
  4811. } else if (data[j] == '.' || data[j] == ',') {
  4812. data[j] = num_systems[i].digits[10];
  4813. }
  4814. }
  4815. break;
  4816. }
  4817. }
  4818. return res;
  4819. }
  4820. String TextServerAdvanced::parse_number(const String &p_string, const String &p_language) const {
  4821. const StringName lang = (p_language.is_empty()) ? TranslationServer::get_singleton()->get_tool_locale() : p_language;
  4822. String res = p_string;
  4823. for (int i = 0; i < num_systems.size(); i++) {
  4824. if (num_systems[i].lang.has(lang)) {
  4825. if (num_systems[i].digits.is_empty()) {
  4826. return p_string;
  4827. }
  4828. res.replace(num_systems[i].exp, "e");
  4829. char32_t *data = res.ptrw();
  4830. for (int j = 0; j < res.length(); j++) {
  4831. if (data[j] == num_systems[i].digits[10]) {
  4832. data[j] = '.';
  4833. } else {
  4834. for (int k = 0; k < 10; k++) {
  4835. if (data[j] == num_systems[i].digits[k]) {
  4836. data[j] = 0x30 + k;
  4837. }
  4838. }
  4839. }
  4840. }
  4841. break;
  4842. }
  4843. }
  4844. return res;
  4845. }
  4846. String TextServerAdvanced::percent_sign(const String &p_language) const {
  4847. const StringName lang = (p_language.is_empty()) ? TranslationServer::get_singleton()->get_tool_locale() : p_language;
  4848. for (int i = 0; i < num_systems.size(); i++) {
  4849. if (num_systems[i].lang.has(lang)) {
  4850. if (num_systems[i].percent_sign.is_empty()) {
  4851. return "%";
  4852. }
  4853. return num_systems[i].percent_sign;
  4854. }
  4855. }
  4856. return "%";
  4857. }
  4858. int TextServerAdvanced::is_confusable(const String &p_string, const PackedStringArray &p_dict) const {
  4859. UErrorCode status = U_ZERO_ERROR;
  4860. int match_index = -1;
  4861. Char16String utf16 = p_string.utf16();
  4862. Vector<UChar *> skeletons;
  4863. skeletons.resize(p_dict.size());
  4864. USpoofChecker *sc = uspoof_open(&status);
  4865. uspoof_setChecks(sc, USPOOF_CONFUSABLE, &status);
  4866. for (int i = 0; i < p_dict.size(); i++) {
  4867. Char16String word = p_dict[i].utf16();
  4868. int32_t len = uspoof_getSkeleton(sc, 0, word.get_data(), -1, NULL, 0, &status);
  4869. skeletons.write[i] = (UChar *)memalloc(++len * sizeof(UChar));
  4870. status = U_ZERO_ERROR;
  4871. uspoof_getSkeleton(sc, 0, word.get_data(), -1, skeletons.write[i], len, &status);
  4872. }
  4873. int32_t len = uspoof_getSkeleton(sc, 0, utf16.get_data(), -1, NULL, 0, &status);
  4874. UChar *skel = (UChar *)memalloc(++len * sizeof(UChar));
  4875. status = U_ZERO_ERROR;
  4876. uspoof_getSkeleton(sc, 0, utf16.get_data(), -1, skel, len, &status);
  4877. for (int i = 0; i < skeletons.size(); i++) {
  4878. if (u_strcmp(skel, skeletons[i]) == 0) {
  4879. match_index = i;
  4880. break;
  4881. }
  4882. }
  4883. memfree(skel);
  4884. for (int i = 0; i < skeletons.size(); i++) {
  4885. memfree(skeletons.write[i]);
  4886. }
  4887. uspoof_close(sc);
  4888. ERR_FAIL_COND_V_MSG(U_FAILURE(status), -1, u_errorName(status));
  4889. return match_index;
  4890. }
  4891. bool TextServerAdvanced::spoof_check(const String &p_string) const {
  4892. UErrorCode status = U_ZERO_ERROR;
  4893. Char16String utf16 = p_string.utf16();
  4894. USet *allowed = uset_openEmpty();
  4895. uset_addAll(allowed, uspoof_getRecommendedSet(&status));
  4896. uset_addAll(allowed, uspoof_getInclusionSet(&status));
  4897. USpoofChecker *sc = uspoof_open(&status);
  4898. uspoof_setAllowedChars(sc, allowed, &status);
  4899. uspoof_setRestrictionLevel(sc, USPOOF_MODERATELY_RESTRICTIVE);
  4900. int32_t bitmask = uspoof_check(sc, utf16.get_data(), -1, NULL, &status);
  4901. uspoof_close(sc);
  4902. uset_close(allowed);
  4903. ERR_FAIL_COND_V_MSG(U_FAILURE(status), false, u_errorName(status));
  4904. return (bitmask != 0);
  4905. }
  4906. String TextServerAdvanced::strip_diacritics(const String &p_string) const {
  4907. UErrorCode err = U_ZERO_ERROR;
  4908. // Get NFKD normalizer singleton.
  4909. const UNormalizer2 *unorm = unorm2_getNFKDInstance(&err);
  4910. ERR_FAIL_COND_V_MSG(U_FAILURE(err), TextServer::strip_diacritics(p_string), u_errorName(err));
  4911. // Convert to UTF-16.
  4912. Char16String utf16 = p_string.utf16();
  4913. // Normalize.
  4914. Vector<char16_t> normalized;
  4915. err = U_ZERO_ERROR;
  4916. int32_t len = unorm2_normalize(unorm, utf16.get_data(), -1, nullptr, 0, &err);
  4917. ERR_FAIL_COND_V_MSG(err != U_BUFFER_OVERFLOW_ERROR, TextServer::strip_diacritics(p_string), u_errorName(err));
  4918. normalized.resize(len);
  4919. err = U_ZERO_ERROR;
  4920. unorm2_normalize(unorm, utf16.get_data(), -1, normalized.ptrw(), len, &err);
  4921. ERR_FAIL_COND_V_MSG(U_FAILURE(err), TextServer::strip_diacritics(p_string), u_errorName(err));
  4922. // Convert back to UTF-32.
  4923. String normalized_string = String::utf16(normalized.ptr(), len);
  4924. // Strip combining characters.
  4925. String result;
  4926. for (int i = 0; i < normalized_string.length(); i++) {
  4927. if (u_getCombiningClass(normalized_string[i]) == 0) {
  4928. result = result + normalized_string[i];
  4929. }
  4930. }
  4931. return result;
  4932. }
  4933. String TextServerAdvanced::string_to_upper(const String &p_string, const String &p_language) const {
  4934. const String lang = (p_language.is_empty()) ? TranslationServer::get_singleton()->get_tool_locale() : p_language;
  4935. // Convert to UTF-16.
  4936. Char16String utf16 = p_string.utf16();
  4937. Vector<char16_t> upper;
  4938. UErrorCode err = U_ZERO_ERROR;
  4939. int32_t len = u_strToUpper(nullptr, 0, utf16.get_data(), -1, lang.ascii().get_data(), &err);
  4940. ERR_FAIL_COND_V_MSG(err != U_BUFFER_OVERFLOW_ERROR, p_string, u_errorName(err));
  4941. upper.resize(len);
  4942. err = U_ZERO_ERROR;
  4943. u_strToUpper(upper.ptrw(), len, utf16.get_data(), -1, lang.ascii().get_data(), &err);
  4944. ERR_FAIL_COND_V_MSG(U_FAILURE(err), p_string, u_errorName(err));
  4945. // Convert back to UTF-32.
  4946. return String::utf16(upper.ptr(), len);
  4947. }
  4948. String TextServerAdvanced::string_to_lower(const String &p_string, const String &p_language) const {
  4949. const String lang = (p_language.is_empty()) ? TranslationServer::get_singleton()->get_tool_locale() : p_language;
  4950. // Convert to UTF-16.
  4951. Char16String utf16 = p_string.utf16();
  4952. Vector<char16_t> lower;
  4953. UErrorCode err = U_ZERO_ERROR;
  4954. int32_t len = u_strToLower(nullptr, 0, utf16.get_data(), -1, lang.ascii().get_data(), &err);
  4955. ERR_FAIL_COND_V_MSG(err != U_BUFFER_OVERFLOW_ERROR, p_string, u_errorName(err));
  4956. lower.resize(len);
  4957. err = U_ZERO_ERROR;
  4958. u_strToLower(lower.ptrw(), len, utf16.get_data(), -1, lang.ascii().get_data(), &err);
  4959. ERR_FAIL_COND_V_MSG(U_FAILURE(err), p_string, u_errorName(err));
  4960. // Convert back to UTF-32.
  4961. return String::utf16(lower.ptr(), len);
  4962. }
  4963. PackedInt32Array TextServerAdvanced::string_get_word_breaks(const String &p_string, const String &p_language) const {
  4964. const String lang = (p_language.is_empty()) ? TranslationServer::get_singleton()->get_tool_locale() : p_language;
  4965. // Convert to UTF-16.
  4966. Char16String utf16 = p_string.utf16();
  4967. HashSet<int> breaks;
  4968. UErrorCode err = U_ZERO_ERROR;
  4969. UBreakIterator *bi = ubrk_open(UBRK_LINE, lang.ascii().get_data(), (const UChar *)utf16.get_data(), utf16.length(), &err);
  4970. if (U_FAILURE(err)) {
  4971. // No data loaded - use fallback.
  4972. for (int i = 0; i < p_string.length(); i++) {
  4973. char32_t c = p_string[i];
  4974. if (is_whitespace(c) || is_linebreak(c)) {
  4975. breaks.insert(i);
  4976. }
  4977. }
  4978. } else {
  4979. while (ubrk_next(bi) != UBRK_DONE) {
  4980. int pos = _convert_pos(p_string, utf16, ubrk_current(bi)) - 1;
  4981. if (pos != p_string.length() - 1) {
  4982. breaks.insert(pos);
  4983. }
  4984. }
  4985. }
  4986. ubrk_close(bi);
  4987. PackedInt32Array ret;
  4988. for (int i = 0; i < p_string.length(); i++) {
  4989. char32_t c = p_string[i];
  4990. if (c == 0xfffc) {
  4991. continue;
  4992. }
  4993. if (u_ispunct(c) && c != 0x005F) {
  4994. ret.push_back(i);
  4995. continue;
  4996. }
  4997. if (is_underscore(c)) {
  4998. ret.push_back(i);
  4999. continue;
  5000. }
  5001. if (breaks.has(i)) {
  5002. ret.push_back(i);
  5003. continue;
  5004. }
  5005. }
  5006. return ret;
  5007. }
  5008. bool TextServerAdvanced::is_valid_identifier(const String &p_string) const {
  5009. enum UAX31SequenceStatus {
  5010. SEQ_NOT_STARTED,
  5011. SEQ_STARTED,
  5012. SEQ_STARTED_VIR,
  5013. SEQ_NEAR_END,
  5014. };
  5015. const char32_t *str = p_string.ptr();
  5016. int len = p_string.length();
  5017. if (len == 0) {
  5018. return false; // Empty string.
  5019. }
  5020. UErrorCode err = U_ZERO_ERROR;
  5021. Char16String utf16 = p_string.utf16();
  5022. const UNormalizer2 *norm_c = unorm2_getNFCInstance(&err);
  5023. if (U_FAILURE(err)) {
  5024. return false; // Failed to load normalizer.
  5025. }
  5026. bool isnurom = unorm2_isNormalized(norm_c, utf16.ptr(), utf16.length(), &err);
  5027. if (U_FAILURE(err) || !isnurom) {
  5028. return false; // Do not conform to Normalization Form C.
  5029. }
  5030. UAX31SequenceStatus A1_sequence_status = SEQ_NOT_STARTED;
  5031. UScriptCode A1_scr = USCRIPT_INHERITED;
  5032. UAX31SequenceStatus A2_sequence_status = SEQ_NOT_STARTED;
  5033. UScriptCode A2_scr = USCRIPT_INHERITED;
  5034. UAX31SequenceStatus B_sequence_status = SEQ_NOT_STARTED;
  5035. UScriptCode B_scr = USCRIPT_INHERITED;
  5036. for (int i = 0; i < len; i++) {
  5037. err = U_ZERO_ERROR;
  5038. UScriptCode scr = uscript_getScript(str[i], &err);
  5039. if (U_FAILURE(err)) {
  5040. return false; // Invalid script.
  5041. }
  5042. if (uscript_getUsage(scr) != USCRIPT_USAGE_RECOMMENDED) {
  5043. return false; // Not a recommended script.
  5044. }
  5045. uint8_t cat = u_charType(str[i]);
  5046. int32_t jt = u_getIntPropertyValue(str[i], UCHAR_JOINING_TYPE);
  5047. // UAX #31 section 2.3 subsections A1, A2 and B, check ZWNJ and ZWJ usage.
  5048. switch (A1_sequence_status) {
  5049. case SEQ_NEAR_END: {
  5050. if ((A1_scr > USCRIPT_INHERITED) && (scr > USCRIPT_INHERITED) && (scr != A1_scr)) {
  5051. return false; // Mixed script.
  5052. }
  5053. if (jt == U_JT_RIGHT_JOINING || jt == U_JT_DUAL_JOINING) {
  5054. A1_sequence_status = SEQ_NOT_STARTED; // Valid end of sequence, reset.
  5055. } else if (jt != U_JT_TRANSPARENT) {
  5056. return false; // Invalid end of sequence.
  5057. }
  5058. } break;
  5059. case SEQ_STARTED: {
  5060. if ((A1_scr > USCRIPT_INHERITED) && (scr > USCRIPT_INHERITED) && (scr != A1_scr)) {
  5061. A1_sequence_status = SEQ_NOT_STARTED; // Reset.
  5062. } else {
  5063. if (jt != U_JT_TRANSPARENT) {
  5064. if (str[i] == 0x200C /*ZWNJ*/) {
  5065. A1_sequence_status = SEQ_NEAR_END;
  5066. continue;
  5067. } else {
  5068. A1_sequence_status = SEQ_NOT_STARTED; // Reset.
  5069. }
  5070. }
  5071. }
  5072. } break;
  5073. default:
  5074. break;
  5075. }
  5076. if (A1_sequence_status == SEQ_NOT_STARTED) {
  5077. if (jt == U_JT_LEFT_JOINING || jt == U_JT_DUAL_JOINING) {
  5078. A1_sequence_status = SEQ_STARTED;
  5079. A1_scr = scr;
  5080. }
  5081. };
  5082. switch (A2_sequence_status) {
  5083. case SEQ_NEAR_END: {
  5084. if ((A2_scr > USCRIPT_INHERITED) && (scr > USCRIPT_INHERITED) && (scr != A2_scr)) {
  5085. return false; // Mixed script.
  5086. }
  5087. if (cat == U_UPPERCASE_LETTER || cat == U_LOWERCASE_LETTER || cat == U_TITLECASE_LETTER || cat == U_MODIFIER_LETTER || cat == U_OTHER_LETTER) {
  5088. A2_sequence_status = SEQ_NOT_STARTED; // Valid end of sequence, reset.
  5089. } else if (cat != U_MODIFIER_LETTER || u_getCombiningClass(str[i]) == 0) {
  5090. return false; // Invalid end of sequence.
  5091. }
  5092. } break;
  5093. case SEQ_STARTED_VIR: {
  5094. if ((A2_scr > USCRIPT_INHERITED) && (scr > USCRIPT_INHERITED) && (scr != A2_scr)) {
  5095. A2_sequence_status = SEQ_NOT_STARTED; // Reset.
  5096. } else {
  5097. if (str[i] == 0x200C /*ZWNJ*/) {
  5098. A2_sequence_status = SEQ_NEAR_END;
  5099. continue;
  5100. } else if (cat != U_MODIFIER_LETTER || u_getCombiningClass(str[i]) == 0) {
  5101. A2_sequence_status = SEQ_NOT_STARTED; // Reset.
  5102. }
  5103. }
  5104. } break;
  5105. case SEQ_STARTED: {
  5106. if ((A2_scr > USCRIPT_INHERITED) && (scr > USCRIPT_INHERITED) && (scr != A2_scr)) {
  5107. A2_sequence_status = SEQ_NOT_STARTED; // Reset.
  5108. } else {
  5109. if (u_getCombiningClass(str[i]) == 9 /*Virama Combining Class*/) {
  5110. A2_sequence_status = SEQ_STARTED_VIR;
  5111. } else if (cat != U_MODIFIER_LETTER) {
  5112. A2_sequence_status = SEQ_NOT_STARTED; // Reset.
  5113. }
  5114. }
  5115. } break;
  5116. default:
  5117. break;
  5118. }
  5119. if (A2_sequence_status == SEQ_NOT_STARTED) {
  5120. if (cat == U_UPPERCASE_LETTER || cat == U_LOWERCASE_LETTER || cat == U_TITLECASE_LETTER || cat == U_MODIFIER_LETTER || cat == U_OTHER_LETTER) {
  5121. A2_sequence_status = SEQ_STARTED;
  5122. A2_scr = scr;
  5123. }
  5124. }
  5125. switch (B_sequence_status) {
  5126. case SEQ_NEAR_END: {
  5127. if ((B_scr > USCRIPT_INHERITED) && (scr > USCRIPT_INHERITED) && (scr != B_scr)) {
  5128. return false; // Mixed script.
  5129. }
  5130. if (u_getIntPropertyValue(str[i], UCHAR_INDIC_SYLLABIC_CATEGORY) != U_INSC_VOWEL_DEPENDENT) {
  5131. B_sequence_status = SEQ_NOT_STARTED; // Valid end of sequence, reset.
  5132. } else {
  5133. return false; // Invalid end of sequence.
  5134. }
  5135. } break;
  5136. case SEQ_STARTED_VIR: {
  5137. if ((B_scr > USCRIPT_INHERITED) && (scr > USCRIPT_INHERITED) && (scr != B_scr)) {
  5138. B_sequence_status = SEQ_NOT_STARTED; // Reset.
  5139. } else {
  5140. if (str[i] == 0x200D /*ZWJ*/) {
  5141. B_sequence_status = SEQ_NEAR_END;
  5142. continue;
  5143. } else if (cat != U_MODIFIER_LETTER || u_getCombiningClass(str[i]) == 0) {
  5144. B_sequence_status = SEQ_NOT_STARTED; // Reset.
  5145. }
  5146. }
  5147. } break;
  5148. case SEQ_STARTED: {
  5149. if ((B_scr > USCRIPT_INHERITED) && (scr > USCRIPT_INHERITED) && (scr != B_scr)) {
  5150. B_sequence_status = SEQ_NOT_STARTED; // Reset.
  5151. } else {
  5152. if (u_getCombiningClass(str[i]) == 9 /*Virama Combining Class*/) {
  5153. B_sequence_status = SEQ_STARTED_VIR;
  5154. } else if (cat != U_MODIFIER_LETTER) {
  5155. B_sequence_status = SEQ_NOT_STARTED; // Reset.
  5156. }
  5157. }
  5158. } break;
  5159. default:
  5160. break;
  5161. }
  5162. if (B_sequence_status == SEQ_NOT_STARTED) {
  5163. if (cat == U_UPPERCASE_LETTER || cat == U_LOWERCASE_LETTER || cat == U_TITLECASE_LETTER || cat == U_MODIFIER_LETTER || cat == U_OTHER_LETTER) {
  5164. B_sequence_status = SEQ_STARTED;
  5165. B_scr = scr;
  5166. }
  5167. }
  5168. if (u_hasBinaryProperty(str[i], UCHAR_PATTERN_SYNTAX) || u_hasBinaryProperty(str[i], UCHAR_PATTERN_WHITE_SPACE) || u_hasBinaryProperty(str[i], UCHAR_NONCHARACTER_CODE_POINT)) {
  5169. return false; // Not a XID_Start or XID_Continue character.
  5170. }
  5171. if (i == 0) {
  5172. if (!(cat == U_LOWERCASE_LETTER || cat == U_UPPERCASE_LETTER || cat == U_TITLECASE_LETTER || cat == U_OTHER_LETTER || cat == U_MODIFIER_LETTER || cat == U_LETTER_NUMBER || str[0] == 0x2118 || str[0] == 0x212E || str[0] == 0x309B || str[0] == 0x309C || str[0] == 0x005F)) {
  5173. return false; // Not a XID_Start character.
  5174. }
  5175. } else {
  5176. if (!(cat == U_LOWERCASE_LETTER || cat == U_UPPERCASE_LETTER || cat == U_TITLECASE_LETTER || cat == U_OTHER_LETTER || cat == U_MODIFIER_LETTER || cat == U_LETTER_NUMBER || cat == U_NON_SPACING_MARK || cat == U_COMBINING_SPACING_MARK || cat == U_DECIMAL_DIGIT_NUMBER || cat == U_CONNECTOR_PUNCTUATION || str[i] == 0x2118 || str[i] == 0x212E || str[i] == 0x309B || str[i] == 0x309C || str[i] == 0x1369 || str[i] == 0x1371 || str[i] == 0x00B7 || str[i] == 0x0387 || str[i] == 0x19DA || str[i] == 0x0E33 || str[i] == 0x0EB3 || str[i] == 0xFF9E || str[i] == 0xFF9F)) {
  5177. return false; // Not a XID_Continue character.
  5178. }
  5179. }
  5180. }
  5181. return true;
  5182. }
  5183. TextServerAdvanced::TextServerAdvanced() {
  5184. _insert_num_systems_lang();
  5185. _insert_feature_sets();
  5186. _bmp_create_font_funcs();
  5187. }
  5188. TextServerAdvanced::~TextServerAdvanced() {
  5189. _bmp_free_font_funcs();
  5190. #ifdef MODULE_FREETYPE_ENABLED
  5191. if (ft_library != nullptr) {
  5192. FT_Done_FreeType(ft_library);
  5193. }
  5194. #endif
  5195. u_cleanup();
  5196. }