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

TextMeshPro.cs 259KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using UnityEngine.TextCore;
  6. using UnityEngine.TextCore.LowLevel;
  7. using Unity.Profiling;
  8. using Object = UnityEngine.Object;
  9. #pragma warning disable 0414 // Disabled a few warnings related to serialized variables not used in this script but used in the editor.
  10. namespace TMPro
  11. {
  12. [DisallowMultipleComponent]
  13. [RequireComponent(typeof(MeshRenderer))]
  14. [AddComponentMenu("Mesh/TextMeshPro - Text")]
  15. [ExecuteAlways]
  16. [HelpURL("https://docs.unity3d.com/Packages/com.unity.textmeshpro@3.2")]
  17. public class TextMeshPro : TMP_Text, ILayoutElement
  18. {
  19. // Public Properties and Serializable Properties
  20. [SerializeField] internal int _SortingLayer;
  21. /// <summary>
  22. /// Sets the Renderer's sorting Layer ID
  23. /// </summary>
  24. public int sortingLayerID
  25. {
  26. get
  27. {
  28. if (renderer == null)
  29. return 0;
  30. return m_renderer.sortingLayerID;
  31. }
  32. set
  33. {
  34. if (renderer == null)
  35. return;
  36. m_renderer.sortingLayerID = value;
  37. _SortingLayerID = value;
  38. // Make sure sorting layer ID change is also reflected on sub text objects.
  39. UpdateSubMeshSortingLayerID(value);
  40. }
  41. }
  42. [SerializeField]
  43. internal int _SortingLayerID;
  44. /// <summary>
  45. /// Sets the Renderer's sorting order within the assigned layer.
  46. /// </summary>
  47. public int sortingOrder
  48. {
  49. get
  50. {
  51. if (renderer == null)
  52. return 0;
  53. return m_renderer.sortingOrder;
  54. }
  55. set
  56. {
  57. if (renderer == null)
  58. return;
  59. m_renderer.sortingOrder = value;
  60. _SortingOrder = value;
  61. // Make sure sorting order change is also reflected on sub text objects.
  62. UpdateSubMeshSortingOrder(value);
  63. }
  64. }
  65. [SerializeField]
  66. internal int _SortingOrder;
  67. /// <summary>
  68. /// Determines if the size of the text container will be adjusted to fit the text object when it is first created.
  69. /// </summary>
  70. public override bool autoSizeTextContainer
  71. {
  72. get { return m_autoSizeTextContainer; }
  73. set { if (m_autoSizeTextContainer == value) return; m_autoSizeTextContainer = value; if (m_autoSizeTextContainer) { TMP_UpdateManager.RegisterTextElementForLayoutRebuild(this); SetLayoutDirty(); } }
  74. }
  75. /// <summary>
  76. /// Returns a reference to the Text Container
  77. /// </summary>
  78. [Obsolete("The TextContainer is now obsolete. Use the RectTransform instead.")]
  79. public TextContainer textContainer
  80. {
  81. get
  82. {
  83. return null;
  84. }
  85. }
  86. /// <summary>
  87. /// Returns a reference to the Transform
  88. /// </summary>
  89. public new Transform transform
  90. {
  91. get
  92. {
  93. if (m_transform == null)
  94. m_transform = GetComponent<Transform>();
  95. return m_transform;
  96. }
  97. }
  98. #pragma warning disable 0108
  99. /// <summary>
  100. /// Returns the rendered assigned to the text object.
  101. /// </summary>
  102. public Renderer renderer
  103. {
  104. get
  105. {
  106. if (m_renderer == null)
  107. m_renderer = GetComponent<Renderer>();
  108. return m_renderer;
  109. }
  110. }
  111. /// <summary>
  112. /// Returns the mesh assigned to the text object.
  113. /// </summary>
  114. public override Mesh mesh
  115. {
  116. get
  117. {
  118. if (m_mesh == null)
  119. {
  120. m_mesh = new Mesh();
  121. m_mesh.hideFlags = HideFlags.HideAndDontSave;
  122. }
  123. return m_mesh;
  124. }
  125. }
  126. /// <summary>
  127. /// Returns the Mesh Filter of the text object.
  128. /// </summary>
  129. public MeshFilter meshFilter
  130. {
  131. get
  132. {
  133. if (m_meshFilter == null)
  134. {
  135. m_meshFilter = GetComponent<MeshFilter>();
  136. if (m_meshFilter == null)
  137. {
  138. m_meshFilter = gameObject.AddComponent<MeshFilter>();
  139. m_meshFilter.hideFlags = HideFlags.HideInInspector | HideFlags.HideAndDontSave;
  140. }
  141. }
  142. return m_meshFilter;
  143. }
  144. }
  145. // MASKING RELATED PROPERTIES
  146. /// <summary>
  147. /// Sets the mask type
  148. /// </summary>
  149. public MaskingTypes maskType
  150. {
  151. get { return m_maskType; }
  152. set { m_maskType = value; SetMask(m_maskType); }
  153. }
  154. /// <summary>
  155. /// Function used to set the mask type and coordinates in World Space
  156. /// </summary>
  157. /// <param name="type"></param>
  158. /// <param name="maskCoords"></param>
  159. public void SetMask(MaskingTypes type, Vector4 maskCoords)
  160. {
  161. SetMask(type);
  162. SetMaskCoordinates(maskCoords);
  163. }
  164. /// <summary>
  165. /// Function used to set the mask type, coordinates and softness
  166. /// </summary>
  167. /// <param name="type"></param>
  168. /// <param name="maskCoords"></param>
  169. /// <param name="softnessX"></param>
  170. /// <param name="softnessY"></param>
  171. public void SetMask(MaskingTypes type, Vector4 maskCoords, float softnessX, float softnessY)
  172. {
  173. SetMask(type);
  174. SetMaskCoordinates(maskCoords, softnessX, softnessY);
  175. }
  176. /// <summary>
  177. /// Schedule rebuilding of the text geometry.
  178. /// </summary>
  179. public override void SetVerticesDirty()
  180. {
  181. //Debug.Log("***** SetVerticesDirty() called on object [" + this.name + "] at frame [" + Time.frameCount + "] *****");
  182. if (this == null || !this.IsActive())
  183. return;
  184. TMP_UpdateManager.RegisterTextElementForGraphicRebuild(this);
  185. }
  186. /// <summary>
  187. ///
  188. /// </summary>
  189. public override void SetLayoutDirty()
  190. {
  191. m_isPreferredWidthDirty = true;
  192. m_isPreferredHeightDirty = true;
  193. if (this == null || !this.IsActive())
  194. return;
  195. LayoutRebuilder.MarkLayoutForRebuild(this.rectTransform);
  196. m_isLayoutDirty = true;
  197. }
  198. /// <summary>
  199. /// Schedule updating of the material used by the text object.
  200. /// </summary>
  201. public override void SetMaterialDirty()
  202. {
  203. //Debug.Log("SetMaterialDirty()");
  204. //if (!this.IsActive())
  205. // return;
  206. //m_isMaterialDirty = true;
  207. UpdateMaterial();
  208. //TMP_UpdateManager.RegisterTextElementForGraphicRebuild(this);
  209. }
  210. /// <summary>
  211. ///
  212. /// </summary>
  213. public override void SetAllDirty()
  214. {
  215. SetLayoutDirty();
  216. SetVerticesDirty();
  217. SetMaterialDirty();
  218. }
  219. /// <summary>
  220. ///
  221. /// </summary>
  222. /// <param name="update"></param>
  223. public override void Rebuild(CanvasUpdate update)
  224. {
  225. if (this == null) return;
  226. if (update == CanvasUpdate.Prelayout)
  227. {
  228. if (m_autoSizeTextContainer)
  229. {
  230. m_rectTransform.sizeDelta = GetPreferredValues(Mathf.Infinity, Mathf.Infinity);
  231. }
  232. }
  233. else if (update == CanvasUpdate.PreRender)
  234. {
  235. this.OnPreRenderObject();
  236. if (!m_isMaterialDirty) return;
  237. UpdateMaterial();
  238. m_isMaterialDirty = false;
  239. }
  240. }
  241. /// <summary>
  242. ///
  243. /// </summary>
  244. protected override void UpdateMaterial()
  245. {
  246. //Debug.Log("***** UpdateMaterial() called on object ID " + GetInstanceID() + ". *****");
  247. //if (!this.IsActive())
  248. // return;
  249. if (renderer == null || m_sharedMaterial == null)
  250. return;
  251. // Only update the material if it has changed.
  252. if (m_renderer.sharedMaterial == null || m_renderer.sharedMaterial.GetInstanceID() != m_sharedMaterial.GetInstanceID())
  253. m_renderer.sharedMaterial = m_sharedMaterial;
  254. }
  255. /// <summary>
  256. /// Function to be used to force recomputing of character padding when Shader / Material properties have been changed via script.
  257. /// </summary>
  258. public override void UpdateMeshPadding()
  259. {
  260. m_padding = ShaderUtilities.GetPadding(m_sharedMaterial, m_enableExtraPadding, m_isUsingBold);
  261. m_isMaskingEnabled = ShaderUtilities.IsMaskingEnabled(m_sharedMaterial);
  262. m_havePropertiesChanged = true;
  263. checkPaddingRequired = false;
  264. // Return if text object is not awake yet.
  265. if (m_textInfo == null) return;
  266. // Update sub text objects
  267. for (int i = 1; i < m_textInfo.materialCount; i++)
  268. m_subTextObjects[i].UpdateMeshPadding(m_enableExtraPadding, m_isUsingBold);
  269. }
  270. /// <summary>
  271. /// Function to force regeneration of the text object before its normal process time. This is useful when changes to the text object properties need to be applied immediately.
  272. /// </summary>
  273. /// <param name="ignoreActiveState">Ignore Active State of text objects. Inactive objects are ignored by default.</param>
  274. /// <param name="forceTextReparsing">Force re-parsing of the text.</param>
  275. public override void ForceMeshUpdate(bool ignoreActiveState = false, bool forceTextReparsing = false)
  276. {
  277. m_havePropertiesChanged = true;
  278. m_ignoreActiveState = ignoreActiveState;
  279. OnPreRenderObject();
  280. }
  281. /// <summary>
  282. /// Function used to evaluate the length of a text string.
  283. /// </summary>
  284. /// <param name="text"></param>
  285. /// <returns></returns>
  286. public override TMP_TextInfo GetTextInfo(string text)
  287. {
  288. SetText(text);
  289. SetArraySizes(m_TextProcessingArray);
  290. m_renderMode = TextRenderFlags.DontRender;
  291. ComputeMarginSize();
  292. GenerateTextMesh();
  293. m_renderMode = TextRenderFlags.Render;
  294. return this.textInfo;
  295. }
  296. /// <summary>
  297. /// Function to clear the geometry of the Primary and Sub Text objects.
  298. /// </summary>
  299. public override void ClearMesh(bool updateMesh)
  300. {
  301. if (m_textInfo.meshInfo[0].mesh == null) m_textInfo.meshInfo[0].mesh = m_mesh;
  302. m_textInfo.ClearMeshInfo(updateMesh);
  303. }
  304. /// <summary>
  305. /// Event to allow users to modify the content of the text info before the text is rendered.
  306. /// </summary>
  307. public override event Action<TMP_TextInfo> OnPreRenderText;
  308. /// <summary>
  309. /// Function to update the geometry of the main and sub text objects.
  310. /// </summary>
  311. /// <param name="mesh"></param>
  312. /// <param name="index"></param>
  313. public override void UpdateGeometry(Mesh mesh, int index)
  314. {
  315. mesh.RecalculateBounds();
  316. }
  317. /// <summary>
  318. /// Function to upload the updated vertex data and renderer.
  319. /// </summary>
  320. public override void UpdateVertexData(TMP_VertexDataUpdateFlags flags)
  321. {
  322. int materialCount = m_textInfo.materialCount;
  323. for (int i = 0; i < materialCount; i++)
  324. {
  325. Mesh mesh;
  326. if (i == 0)
  327. mesh = m_mesh;
  328. else
  329. {
  330. // Clear unused vertices
  331. // TODO: Causes issues when sorting geometry as last vertex data attribute get wiped out.
  332. //m_textInfo.meshInfo[i].ClearUnusedVertices();
  333. mesh = m_subTextObjects[i].mesh;
  334. }
  335. //mesh.MarkDynamic();
  336. if ((flags & TMP_VertexDataUpdateFlags.Vertices) == TMP_VertexDataUpdateFlags.Vertices)
  337. mesh.vertices = m_textInfo.meshInfo[i].vertices;
  338. if ((flags & TMP_VertexDataUpdateFlags.Uv0) == TMP_VertexDataUpdateFlags.Uv0)
  339. mesh.SetUVs(0, m_textInfo.meshInfo[i].uvs0);
  340. if ((flags & TMP_VertexDataUpdateFlags.Uv2) == TMP_VertexDataUpdateFlags.Uv2)
  341. mesh.uv2 = m_textInfo.meshInfo[i].uvs2;
  342. //if ((flags & TMP_VertexDataUpdateFlags.Uv4) == TMP_VertexDataUpdateFlags.Uv4)
  343. // mesh.uv4 = m_textInfo.meshInfo[i].uvs4;
  344. if ((flags & TMP_VertexDataUpdateFlags.Colors32) == TMP_VertexDataUpdateFlags.Colors32)
  345. mesh.colors32 = m_textInfo.meshInfo[i].colors32;
  346. mesh.RecalculateBounds();
  347. }
  348. }
  349. /// <summary>
  350. /// Function to upload the updated vertex data and renderer.
  351. /// </summary>
  352. public override void UpdateVertexData()
  353. {
  354. int materialCount = m_textInfo.materialCount;
  355. for (int i = 0; i < materialCount; i++)
  356. {
  357. Mesh mesh;
  358. if (i == 0)
  359. mesh = m_mesh;
  360. else
  361. {
  362. // Clear unused vertices
  363. m_textInfo.meshInfo[i].ClearUnusedVertices();
  364. mesh = m_subTextObjects[i].mesh;
  365. }
  366. //mesh.MarkDynamic();
  367. mesh.vertices = m_textInfo.meshInfo[i].vertices;
  368. mesh.SetUVs(0, m_textInfo.meshInfo[i].uvs0);
  369. mesh.uv2 = m_textInfo.meshInfo[i].uvs2;
  370. //mesh.uv4 = m_textInfo.meshInfo[i].uvs4;
  371. mesh.colors32 = m_textInfo.meshInfo[i].colors32;
  372. mesh.RecalculateBounds();
  373. }
  374. }
  375. public void UpdateFontAsset()
  376. {
  377. LoadFontAsset();
  378. }
  379. public void CalculateLayoutInputHorizontal() { }
  380. public void CalculateLayoutInputVertical() { }
  381. #region TMPro_Private
  382. [SerializeField]
  383. private bool m_hasFontAssetChanged = false; // Used to track when font properties have changed.
  384. float m_previousLossyScaleY = -1; // Used for Tracking lossy scale changes in the transform;
  385. [SerializeField]
  386. private Renderer m_renderer;
  387. private MeshFilter m_meshFilter;
  388. private bool m_isFirstAllocation; // Flag to determine if this is the first allocation of the buffers.
  389. private int m_max_characters = 8; // Determines the initial allocation and size of the character array / buffer.
  390. private int m_max_numberOfLines = 4; // Determines the initial allocation and maximum number of lines of text.
  391. private TMP_SubMesh[] m_subTextObjects = new TMP_SubMesh[8];
  392. // MASKING RELATED PROPERTIES
  393. [SerializeField]
  394. private MaskingTypes m_maskType;
  395. // Matrix used to animated Env Map
  396. private Matrix4x4 m_EnvMapMatrix = new Matrix4x4();
  397. // Text Container / RectTransform Component
  398. private Vector3[] m_RectTransformCorners = new Vector3[4];
  399. [NonSerialized]
  400. private bool m_isRegisteredForEvents;
  401. // Profiler Marker declarations
  402. private static ProfilerMarker k_GenerateTextMarker = new ProfilerMarker("TMP Layout Text");
  403. private static ProfilerMarker k_SetArraySizesMarker = new ProfilerMarker("TMP.SetArraySizes");
  404. private static ProfilerMarker k_GenerateTextPhaseIMarker = new ProfilerMarker("TMP GenerateText - Phase I");
  405. private static ProfilerMarker k_ParseMarkupTextMarker = new ProfilerMarker("TMP Parse Markup Text");
  406. private static ProfilerMarker k_CharacterLookupMarker = new ProfilerMarker("TMP Lookup Character & Glyph Data");
  407. private static ProfilerMarker k_HandleGPOSFeaturesMarker = new ProfilerMarker("TMP Handle GPOS Features");
  408. private static ProfilerMarker k_CalculateVerticesPositionMarker = new ProfilerMarker("TMP Calculate Vertices Position");
  409. private static ProfilerMarker k_ComputeTextMetricsMarker = new ProfilerMarker("TMP Compute Text Metrics");
  410. private static ProfilerMarker k_HandleVisibleCharacterMarker = new ProfilerMarker("TMP Handle Visible Character");
  411. private static ProfilerMarker k_HandleWhiteSpacesMarker = new ProfilerMarker("TMP Handle White Space & Control Character");
  412. private static ProfilerMarker k_HandleHorizontalLineBreakingMarker = new ProfilerMarker("TMP Handle Horizontal Line Breaking");
  413. private static ProfilerMarker k_HandleVerticalLineBreakingMarker = new ProfilerMarker("TMP Handle Vertical Line Breaking");
  414. private static ProfilerMarker k_SaveGlyphVertexDataMarker = new ProfilerMarker("TMP Save Glyph Vertex Data");
  415. private static ProfilerMarker k_ComputeCharacterAdvanceMarker = new ProfilerMarker("TMP Compute Character Advance");
  416. private static ProfilerMarker k_HandleCarriageReturnMarker = new ProfilerMarker("TMP Handle Carriage Return");
  417. private static ProfilerMarker k_HandleLineTerminationMarker = new ProfilerMarker("TMP Handle Line Termination");
  418. private static ProfilerMarker k_SavePageInfoMarker = new ProfilerMarker("TMP Save Page Info");
  419. private static ProfilerMarker k_SaveTextExtentMarker = new ProfilerMarker("TMP Save Text Extent");
  420. private static ProfilerMarker k_SaveProcessingStatesMarker = new ProfilerMarker("TMP Save Processing States");
  421. private static ProfilerMarker k_GenerateTextPhaseIIMarker = new ProfilerMarker("TMP GenerateText - Phase II");
  422. private static ProfilerMarker k_GenerateTextPhaseIIIMarker = new ProfilerMarker("TMP GenerateText - Phase III");
  423. protected override void Awake()
  424. {
  425. //Debug.Log("***** Awake() called on object ID " + GetInstanceID() + ". *****");
  426. #if UNITY_EDITOR
  427. // Special handling for TMP Settings and importing Essential Resources
  428. if (TMP_Settings.instance == null)
  429. {
  430. if (m_isWaitingOnResourceLoad == false)
  431. TMPro_EventManager.RESOURCE_LOAD_EVENT.Add(ON_RESOURCES_LOADED);
  432. m_isWaitingOnResourceLoad = true;
  433. return;
  434. }
  435. #endif
  436. // Cache Reference to the Mesh Renderer.
  437. m_renderer = GetComponent<Renderer>();
  438. if (m_renderer == null)
  439. m_renderer = gameObject.AddComponent<Renderer>();
  440. // Cache Reference to RectTransform
  441. m_rectTransform = this.rectTransform;
  442. // Cache Reference to the transform;
  443. m_transform = this.transform;
  444. // Cache a reference to the Mesh Filter.
  445. m_meshFilter = GetComponent<MeshFilter>();
  446. if (m_meshFilter == null)
  447. m_meshFilter = gameObject.AddComponent<MeshFilter>();
  448. // Create new Mesh if necessary and cache reference to it.
  449. if (m_mesh == null)
  450. {
  451. m_mesh = new Mesh();
  452. m_mesh.hideFlags = HideFlags.HideAndDontSave;
  453. #if DEVELOPMENT_BUILD || UNITY_EDITOR
  454. m_mesh.name = "TextMeshPro Mesh";
  455. #endif
  456. m_meshFilter.sharedMesh = m_mesh;
  457. // Create new TextInfo for the text object.
  458. m_textInfo = new TMP_TextInfo(this);
  459. }
  460. m_meshFilter.hideFlags = HideFlags.HideInInspector | HideFlags.HideAndDontSave;
  461. #if UNITY_EDITOR
  462. // Special handling for the CanvasRenderer which used to be automatically added by the Graphic class.
  463. CanvasRenderer canvasRendererComponent = GetComponent<CanvasRenderer>();
  464. if (canvasRendererComponent != null)
  465. {
  466. Debug.LogWarning("Please remove the CanvasRenderer component from the [" + this.name + "] GameObject as this component is no longer necessary.", this);
  467. canvasRendererComponent.hideFlags = HideFlags.None;
  468. }
  469. #endif
  470. // Load TMP Settings for new text object instances.
  471. LoadDefaultSettings();
  472. // Load the font asset and assign material to renderer.
  473. LoadFontAsset();
  474. // Allocate our initial buffers.
  475. if (m_TextProcessingArray == null)
  476. m_TextProcessingArray = new TextProcessingElement[m_max_characters];
  477. m_cached_TextElement = new TMP_Character();
  478. m_isFirstAllocation = true;
  479. // Set flags to ensure our text is parsed and redrawn.
  480. m_havePropertiesChanged = true;
  481. m_isAwake = true;
  482. }
  483. protected override void OnEnable()
  484. {
  485. //Debug.Log("***** OnEnable() called on object ID " + GetInstanceID() + ". *****");
  486. // Return if Awake() has not been called on the text object.
  487. if (m_isAwake == false)
  488. return;
  489. // Register Callbacks for various events.
  490. if (!m_isRegisteredForEvents)
  491. {
  492. #if UNITY_EDITOR
  493. TMPro_EventManager.MATERIAL_PROPERTY_EVENT.Add(ON_MATERIAL_PROPERTY_CHANGED);
  494. TMPro_EventManager.FONT_PROPERTY_EVENT.Add(ON_FONT_PROPERTY_CHANGED);
  495. TMPro_EventManager.TEXTMESHPRO_PROPERTY_EVENT.Add(ON_TEXTMESHPRO_PROPERTY_CHANGED);
  496. TMPro_EventManager.DRAG_AND_DROP_MATERIAL_EVENT.Add(ON_DRAG_AND_DROP_MATERIAL);
  497. TMPro_EventManager.TEXT_STYLE_PROPERTY_EVENT.Add(ON_TEXT_STYLE_CHANGED);
  498. TMPro_EventManager.COLOR_GRADIENT_PROPERTY_EVENT.Add(ON_COLOR_GRADIENT_CHANGED);
  499. TMPro_EventManager.TMP_SETTINGS_PROPERTY_EVENT.Add(ON_TMP_SETTINGS_CHANGED);
  500. UnityEditor.PrefabUtility.prefabInstanceUpdated += OnPrefabInstanceUpdate;
  501. #endif
  502. m_isRegisteredForEvents = true;
  503. }
  504. // Register text object for internal updates
  505. if (m_IsTextObjectScaleStatic == false)
  506. TMP_UpdateManager.RegisterTextObjectForUpdate(this);
  507. meshFilter.sharedMesh = mesh;
  508. SetActiveSubMeshes(true);
  509. // Schedule potential text object update (if any of the properties have changed.
  510. ComputeMarginSize();
  511. SetAllDirty();
  512. //m_havePropertiesChanged = true;
  513. }
  514. protected override void OnDisable()
  515. {
  516. //Debug.Log("***** OnDisable() called on object ID " + GetInstanceID() + ". *****");
  517. // Return if Awake() has not been called on the text object.
  518. if (m_isAwake == false)
  519. return;
  520. TMP_UpdateManager.UnRegisterTextElementForRebuild(this);
  521. TMP_UpdateManager.UnRegisterTextObjectForUpdate(this);
  522. meshFilter.sharedMesh = null;
  523. SetActiveSubMeshes(false);
  524. }
  525. protected override void OnDestroy()
  526. {
  527. //Debug.Log("***** OnDestroy() called on object ID " + GetInstanceID() + ". *****");
  528. // Destroy the mesh if we have one.
  529. if (m_mesh != null)
  530. DestroyImmediate(m_mesh);
  531. // Unregister the event this object was listening to
  532. #if UNITY_EDITOR
  533. TMPro_EventManager.MATERIAL_PROPERTY_EVENT.Remove(ON_MATERIAL_PROPERTY_CHANGED);
  534. TMPro_EventManager.FONT_PROPERTY_EVENT.Remove(ON_FONT_PROPERTY_CHANGED);
  535. TMPro_EventManager.TEXTMESHPRO_PROPERTY_EVENT.Remove(ON_TEXTMESHPRO_PROPERTY_CHANGED);
  536. TMPro_EventManager.DRAG_AND_DROP_MATERIAL_EVENT.Remove(ON_DRAG_AND_DROP_MATERIAL);
  537. TMPro_EventManager.TEXT_STYLE_PROPERTY_EVENT.Remove(ON_TEXT_STYLE_CHANGED);
  538. TMPro_EventManager.COLOR_GRADIENT_PROPERTY_EVENT.Remove(ON_COLOR_GRADIENT_CHANGED);
  539. TMPro_EventManager.TMP_SETTINGS_PROPERTY_EVENT.Remove(ON_TMP_SETTINGS_CHANGED);
  540. TMPro_EventManager.RESOURCE_LOAD_EVENT.Remove(ON_RESOURCES_LOADED);
  541. UnityEditor.PrefabUtility.prefabInstanceUpdated -= OnPrefabInstanceUpdate;
  542. #endif
  543. m_isRegisteredForEvents = false;
  544. TMP_UpdateManager.UnRegisterTextElementForRebuild(this);
  545. TMP_UpdateManager.UnRegisterTextObjectForUpdate(this);
  546. }
  547. #if UNITY_EDITOR
  548. protected override void Reset()
  549. {
  550. //Debug.Log("***** Reset() called on object ID " + GetInstanceID() + ". *****");
  551. // Return if Awake() has not been called on the text object.
  552. if (m_isAwake == false)
  553. return;
  554. if (m_mesh != null)
  555. DestroyImmediate(m_mesh);
  556. Awake();
  557. }
  558. protected override void OnValidate()
  559. {
  560. //Debug.Log("***** OnValidate() called on object ID " + GetInstanceID() + ". *****", this);
  561. if (m_isAwake == false)
  562. return;
  563. if (meshFilter != null && m_meshFilter.hideFlags != (HideFlags.HideInInspector | HideFlags.HideAndDontSave))
  564. m_meshFilter.hideFlags = HideFlags.HideInInspector | HideFlags.HideAndDontSave;
  565. // Handle Font Asset changes in the inspector
  566. if (m_fontAsset == null || m_hasFontAssetChanged)
  567. {
  568. LoadFontAsset();
  569. m_hasFontAssetChanged = false;
  570. }
  571. m_padding = GetPaddingForMaterial();
  572. ComputeMarginSize();
  573. m_inputSource = TextInputSources.TextInputBox;
  574. m_havePropertiesChanged = true;
  575. m_isPreferredWidthDirty = true;
  576. m_isPreferredHeightDirty = true;
  577. SetAllDirty();
  578. }
  579. private void OnBecameVisible()
  580. {
  581. // Keep the parent text object's renderer in sync with child sub objects' renderers.
  582. SetActiveSubTextObjectRenderers(true);
  583. }
  584. private void OnBecameInvisible()
  585. {
  586. // Keep the parent text object's renderer in sync with child sub objects' renderers.
  587. SetActiveSubTextObjectRenderers(false);
  588. }
  589. /// <summary>
  590. /// Callback received when Prefabs are updated.
  591. /// </summary>
  592. /// <param name="go">The affected GameObject</param>
  593. void OnPrefabInstanceUpdate(GameObject go)
  594. {
  595. // Remove Callback if this prefab has been deleted.
  596. if (this == null)
  597. {
  598. UnityEditor.PrefabUtility.prefabInstanceUpdated -= OnPrefabInstanceUpdate;
  599. return;
  600. }
  601. if (go == this.gameObject)
  602. {
  603. TMP_SubMesh[] subTextObjects = GetComponentsInChildren<TMP_SubMesh>();
  604. if (subTextObjects.Length > 0)
  605. {
  606. for (int i = 0; i < subTextObjects.Length; i++)
  607. m_subTextObjects[i + 1] = subTextObjects[i];
  608. }
  609. }
  610. }
  611. // Event received when TMP resources have been loaded.
  612. void ON_RESOURCES_LOADED()
  613. {
  614. TMPro_EventManager.RESOURCE_LOAD_EVENT.Remove(ON_RESOURCES_LOADED);
  615. if (this == null)
  616. return;
  617. m_isWaitingOnResourceLoad = false;
  618. Awake();
  619. OnEnable();
  620. }
  621. // Event received when custom material editor properties are changed.
  622. void ON_MATERIAL_PROPERTY_CHANGED(bool isChanged, Material mat)
  623. {
  624. //Debug.Log("ON_MATERIAL_PROPERTY_CHANGED event received. Targeted Material is: " + mat.name + " m_sharedMaterial: " + m_sharedMaterial.name + " m_renderer.sharedMaterial: " + m_renderer.sharedMaterial);
  625. if (m_renderer.sharedMaterial == null)
  626. {
  627. if (m_fontAsset != null)
  628. {
  629. m_renderer.sharedMaterial = m_fontAsset.material;
  630. Debug.LogWarning("No Material was assigned to " + name + ". " + m_fontAsset.material.name + " was assigned.", this);
  631. }
  632. else
  633. {
  634. Debug.LogWarning("No Font Asset assigned to " + name + ". Please assign a Font Asset.", this);
  635. return;
  636. }
  637. }
  638. // if (m_fontAsset.atlasTexture != null && m_fontAsset.atlasTexture.GetInstanceID() != m_renderer.sharedMaterial.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID())
  639. // {
  640. // m_renderer.sharedMaterial = m_sharedMaterial;
  641. // //m_renderer.sharedMaterial = m_fontAsset.material;
  642. // Debug.LogWarning("Font Asset Atlas doesn't match the Atlas in the newly assigned material. Select a matching material or a different font asset.", this);
  643. // }
  644. if (m_renderer.sharedMaterial != m_sharedMaterial)
  645. {
  646. //Debug.Log("ON_MATERIAL_PROPERTY_CHANGED Called on Target ID: " + GetInstanceID() + ". Previous Material:" + m_sharedMaterial + " New Material:" + m_renderer.sharedMaterial); // on Object ID:" + GetInstanceID() + ". m_sharedMaterial: " + m_sharedMaterial.name + " m_renderer.sharedMaterial: " + m_renderer.sharedMaterial.name);
  647. m_sharedMaterial = m_renderer.sharedMaterial;
  648. }
  649. m_padding = GetPaddingForMaterial();
  650. //m_sharedMaterialHashCode = TMP_TextUtilities.GetSimpleHashCode(m_sharedMaterial.name);
  651. UpdateMask();
  652. UpdateEnvMapMatrix();
  653. m_havePropertiesChanged = true;
  654. SetVerticesDirty();
  655. }
  656. // Event received when font asset properties are changed in Font Inspector
  657. void ON_FONT_PROPERTY_CHANGED(bool isChanged, Object fontAsset)
  658. {
  659. //Debug.Log("ON_FONT_PROPERTY_CHANGED event received. Target is [" + font.name + "]");
  660. // TODO: Optimize so we don't update all text objects when font asset properties are changed.
  661. //if (MaterialReference.Contains(m_materialReferences, (TMP_FontAsset)fontAsset))
  662. {
  663. m_havePropertiesChanged = true;
  664. UpdateMeshPadding();
  665. SetAllDirty();
  666. }
  667. }
  668. // Event received when UNDO / REDO Event alters the properties of the object.
  669. void ON_TEXTMESHPRO_PROPERTY_CHANGED(bool isChanged, Object textComponent)
  670. {
  671. if (textComponent == this)
  672. {
  673. //Debug.Log("Undo / Redo Event Received by Object ID:" + GetInstanceID());
  674. m_havePropertiesChanged = true;
  675. m_padding = GetPaddingForMaterial();
  676. ComputeMarginSize(); // Verify this change
  677. SetVerticesDirty();
  678. }
  679. }
  680. // Event to Track Material Changed resulting from Drag-n-drop.
  681. void ON_DRAG_AND_DROP_MATERIAL(GameObject obj, Material currentMaterial, Material newMaterial)
  682. {
  683. //Debug.Log("Drag-n-Drop Event - Receiving Object ID " + GetInstanceID()); // + ". Target Object ID " + obj.GetInstanceID() + ". New Material is " + mat.name + " with ID " + mat.GetInstanceID() + ". Base Material is " + m_baseMaterial.name + " with ID " + m_baseMaterial.GetInstanceID());
  684. // Check if event applies to this current object
  685. if (obj == gameObject || UnityEditor.PrefabUtility.GetCorrespondingObjectFromSource(gameObject) == obj)
  686. {
  687. UnityEditor.Undo.RecordObject(this, "Material Assignment");
  688. UnityEditor.Undo.RecordObject(m_renderer, "Material Assignment");
  689. m_sharedMaterial = newMaterial;
  690. m_padding = GetPaddingForMaterial();
  691. m_havePropertiesChanged = true;
  692. SetVerticesDirty();
  693. SetMaterialDirty();
  694. }
  695. }
  696. // Event received when Text Styles are changed.
  697. void ON_TEXT_STYLE_CHANGED(bool isChanged)
  698. {
  699. m_havePropertiesChanged = true;
  700. SetVerticesDirty();
  701. }
  702. /// <summary>
  703. /// Event received when a Color Gradient Preset is modified.
  704. /// </summary>
  705. /// <param name="textObject"></param>
  706. void ON_COLOR_GRADIENT_CHANGED(Object gradient)
  707. {
  708. m_havePropertiesChanged = true;
  709. SetVerticesDirty();
  710. }
  711. /// <summary>
  712. /// Event received when the TMP Settings are changed.
  713. /// </summary>
  714. void ON_TMP_SETTINGS_CHANGED()
  715. {
  716. m_defaultSpriteAsset = null;
  717. m_havePropertiesChanged = true;
  718. SetAllDirty();
  719. }
  720. #endif
  721. // Function which loads either the default font or a newly assigned font asset. This function also assigned the appropriate material to the renderer.
  722. protected override void LoadFontAsset()
  723. {
  724. //Debug.Log("TextMeshPro LoadFontAsset() has been called."); // Current Font Asset is " + (font != null ? font.name: "Null") );
  725. ShaderUtilities.GetShaderPropertyIDs(); // Initialize & Get shader property IDs.
  726. if (m_fontAsset == null)
  727. {
  728. if (TMP_Settings.defaultFontAsset != null)
  729. m_fontAsset = TMP_Settings.defaultFontAsset;
  730. if (m_fontAsset == null)
  731. {
  732. Debug.LogWarning("The LiberationSans SDF Font Asset was not found. There is no Font Asset assigned to " + gameObject.name + ".", this);
  733. return;
  734. }
  735. if (m_fontAsset.characterLookupTable == null)
  736. {
  737. Debug.Log("Dictionary is Null!");
  738. }
  739. m_sharedMaterial = m_fontAsset.material;
  740. m_sharedMaterial.SetFloat("_CullMode", 0);
  741. m_renderer.receiveShadows = false;
  742. m_renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
  743. }
  744. else
  745. {
  746. if (m_fontAsset.characterLookupTable == null)
  747. m_fontAsset.ReadFontAssetDefinition();
  748. // If font atlas texture doesn't match the assigned material font atlas, switch back to default material specified in the Font Asset.
  749. if (m_sharedMaterial == null || m_sharedMaterial.GetTexture(ShaderUtilities.ID_MainTex) == null || m_fontAsset.atlasTexture.GetInstanceID() != m_sharedMaterial.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID())
  750. {
  751. if (m_fontAsset.material == null)
  752. Debug.LogWarning("The Font Atlas Texture of the Font Asset " + m_fontAsset.name + " assigned to " + gameObject.name + " is missing.", this);
  753. else
  754. m_sharedMaterial = m_fontAsset.material;
  755. }
  756. }
  757. m_padding = GetPaddingForMaterial();
  758. m_isMaskingEnabled = ShaderUtilities.IsMaskingEnabled(m_sharedMaterial);
  759. // Find and cache Underline & Ellipsis characters.
  760. GetSpecialCharacters(m_fontAsset);
  761. SetMaterialDirty();
  762. }
  763. void UpdateEnvMapMatrix()
  764. {
  765. if (!m_sharedMaterial.HasProperty(ShaderUtilities.ID_EnvMap) || m_sharedMaterial.GetTexture(ShaderUtilities.ID_EnvMap) == null)
  766. return;
  767. //Debug.Log("Updating Env Matrix...");
  768. Vector3 rotation = m_sharedMaterial.GetVector(ShaderUtilities.ID_EnvMatrixRotation);
  769. m_EnvMapMatrix = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(rotation), Vector3.one);
  770. m_sharedMaterial.SetMatrix(ShaderUtilities.ID_EnvMatrix, m_EnvMapMatrix);
  771. }
  772. //
  773. void SetMask(MaskingTypes maskType)
  774. {
  775. switch(maskType)
  776. {
  777. case MaskingTypes.MaskOff:
  778. m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_SOFT);
  779. m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_HARD);
  780. m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_TEX);
  781. break;
  782. case MaskingTypes.MaskSoft:
  783. m_sharedMaterial.EnableKeyword(ShaderUtilities.Keyword_MASK_SOFT);
  784. m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_HARD);
  785. m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_TEX);
  786. break;
  787. case MaskingTypes.MaskHard:
  788. m_sharedMaterial.EnableKeyword(ShaderUtilities.Keyword_MASK_HARD);
  789. m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_SOFT);
  790. m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_TEX);
  791. break;
  792. //case MaskingTypes.MaskTex:
  793. // m_sharedMaterial.EnableKeyword(ShaderUtilities.Keyword_MASK_TEX);
  794. // m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_HARD);
  795. // m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_SOFT);
  796. // break;
  797. }
  798. }
  799. // Method used to set the masking coordinates
  800. void SetMaskCoordinates(Vector4 coords)
  801. {
  802. m_sharedMaterial.SetVector(ShaderUtilities.ID_ClipRect, coords);
  803. }
  804. // Method used to set the masking coordinates
  805. void SetMaskCoordinates(Vector4 coords, float softX, float softY)
  806. {
  807. m_sharedMaterial.SetVector(ShaderUtilities.ID_ClipRect, coords);
  808. m_sharedMaterial.SetFloat(ShaderUtilities.ID_MaskSoftnessX, softX);
  809. m_sharedMaterial.SetFloat(ShaderUtilities.ID_MaskSoftnessY, softY);
  810. }
  811. // Enable Masking in the Shader
  812. void EnableMasking()
  813. {
  814. if (m_sharedMaterial.HasProperty(ShaderUtilities.ID_ClipRect))
  815. {
  816. m_sharedMaterial.EnableKeyword(ShaderUtilities.Keyword_MASK_SOFT);
  817. m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_HARD);
  818. m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_TEX);
  819. m_isMaskingEnabled = true;
  820. UpdateMask();
  821. }
  822. }
  823. // Enable Masking in the Shader
  824. void DisableMasking()
  825. {
  826. if (m_sharedMaterial.HasProperty(ShaderUtilities.ID_ClipRect))
  827. {
  828. m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_SOFT);
  829. m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_HARD);
  830. m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_TEX);
  831. m_isMaskingEnabled = false;
  832. UpdateMask();
  833. }
  834. }
  835. void UpdateMask()
  836. {
  837. //Debug.Log("UpdateMask() called.");
  838. if (!m_isMaskingEnabled)
  839. {
  840. // Release Masking Material
  841. // Re-assign Base Material
  842. return;
  843. }
  844. if (m_isMaskingEnabled && m_fontMaterial == null)
  845. {
  846. CreateMaterialInstance();
  847. }
  848. /*
  849. if (!m_isMaskingEnabled)
  850. {
  851. //Debug.Log("Masking is not enabled.");
  852. if (m_maskingPropertyBlock != null)
  853. {
  854. m_renderer.SetPropertyBlock(null);
  855. //havePropertiesChanged = true;
  856. }
  857. return;
  858. }
  859. //else
  860. // Debug.Log("Updating Masking...");
  861. */
  862. // Compute Masking Coordinates & Softness
  863. //float softnessX = Mathf.Min(Mathf.Min(m_textContainer.margins.x, m_textContainer.margins.z), m_sharedMaterial.GetFloat(ShaderUtilities.ID_MaskSoftnessX));
  864. //float softnessY = Mathf.Min(Mathf.Min(m_textContainer.margins.y, m_textContainer.margins.w), m_sharedMaterial.GetFloat(ShaderUtilities.ID_MaskSoftnessY));
  865. //softnessX = softnessX > 0 ? softnessX : 0;
  866. //softnessY = softnessY > 0 ? softnessY : 0;
  867. //float width = (m_textContainer.width - Mathf.Max(m_textContainer.margins.x, 0) - Mathf.Max(m_textContainer.margins.z, 0)) / 2 + softnessX;
  868. //float height = (m_textContainer.height - Mathf.Max(m_textContainer.margins.y, 0) - Mathf.Max(m_textContainer.margins.w, 0)) / 2 + softnessY;
  869. //Vector2 center = new Vector2((0.5f - m_textContainer.pivot.x) * m_textContainer.width + (Mathf.Max(m_textContainer.margins.x, 0) - Mathf.Max(m_textContainer.margins.z, 0)) / 2, (0.5f - m_textContainer.pivot.y) * m_textContainer.height + (- Mathf.Max(m_textContainer.margins.y, 0) + Mathf.Max(m_textContainer.margins.w, 0)) / 2);
  870. //Vector4 mask = new Vector4(center.x, center.y, width, height);
  871. //m_fontMaterial.SetVector(ShaderUtilities.ID_ClipRect, mask);
  872. //m_fontMaterial.SetFloat(ShaderUtilities.ID_MaskSoftnessX, softnessX);
  873. //m_fontMaterial.SetFloat(ShaderUtilities.ID_MaskSoftnessY, softnessY);
  874. /*
  875. if(m_maskingPropertyBlock == null)
  876. {
  877. m_maskingPropertyBlock = new MaterialPropertyBlock();
  878. //m_maskingPropertyBlock.AddFloat(ShaderUtilities.ID_VertexOffsetX, m_sharedMaterial.GetFloat(ShaderUtilities.ID_VertexOffsetX));
  879. //m_maskingPropertyBlock.AddFloat(ShaderUtilities.ID_VertexOffsetY, m_sharedMaterial.GetFloat(ShaderUtilities.ID_VertexOffsetY));
  880. //Debug.Log("Creating new MaterialPropertyBlock.");
  881. }
  882. //Debug.Log("Updating Material Property Block.");
  883. //m_maskingPropertyBlock.Clear();
  884. m_maskingPropertyBlock.AddFloat(ShaderUtilities.ID_MaskID, m_renderer.GetInstanceID());
  885. m_maskingPropertyBlock.AddVector(ShaderUtilities.ID_MaskCoord, mask);
  886. m_maskingPropertyBlock.AddFloat(ShaderUtilities.ID_MaskSoftnessX, softnessX);
  887. m_maskingPropertyBlock.AddFloat(ShaderUtilities.ID_MaskSoftnessY, softnessY);
  888. m_renderer.SetPropertyBlock(m_maskingPropertyBlock);
  889. */
  890. }
  891. // Function called internally when a new material is assigned via the fontMaterial property.
  892. protected override Material GetMaterial(Material mat)
  893. {
  894. // Check in case Object is disabled. If so, we don't have a valid reference to the Renderer.
  895. // This can occur when the Duplicate Material Context menu is used on an inactive object.
  896. //if (m_renderer == null)
  897. // m_renderer = GetComponent<Renderer>();
  898. // Create Instance Material only if the new material is not the same instance previously used.
  899. if (m_fontMaterial == null || m_fontMaterial.GetInstanceID() != mat.GetInstanceID())
  900. m_fontMaterial = CreateMaterialInstance(mat);
  901. m_sharedMaterial = m_fontMaterial;
  902. m_padding = GetPaddingForMaterial();
  903. SetVerticesDirty();
  904. SetMaterialDirty();
  905. return m_sharedMaterial;
  906. }
  907. /// <summary>
  908. /// Method returning instances of the materials used by the text object.
  909. /// </summary>
  910. /// <returns></returns>
  911. protected override Material[] GetMaterials(Material[] mats)
  912. {
  913. int materialCount = m_textInfo.materialCount;
  914. if (m_fontMaterials == null)
  915. m_fontMaterials = new Material[materialCount];
  916. else if (m_fontMaterials.Length != materialCount)
  917. TMP_TextInfo.Resize(ref m_fontMaterials, materialCount, false);
  918. // Get instances of the materials
  919. for (int i = 0; i < materialCount; i++)
  920. {
  921. if (i == 0)
  922. m_fontMaterials[i] = fontMaterial;
  923. else
  924. m_fontMaterials[i] = m_subTextObjects[i].material;
  925. }
  926. m_fontSharedMaterials = m_fontMaterials;
  927. return m_fontMaterials;
  928. }
  929. // Function called internally when a new shared material is assigned via the fontSharedMaterial property.
  930. protected override void SetSharedMaterial(Material mat)
  931. {
  932. // Check in case Object is disabled. If so, we don't have a valid reference to the Renderer.
  933. // This can occur when the Duplicate Material Context menu is used on an inactive object.
  934. //if (m_renderer == null)
  935. // m_renderer = GetComponent<Renderer>();
  936. m_sharedMaterial = mat;
  937. m_padding = GetPaddingForMaterial();
  938. SetMaterialDirty();
  939. }
  940. /// <summary>
  941. /// Method returning an array containing the materials used by the text object.
  942. /// </summary>
  943. /// <returns></returns>
  944. protected override Material[] GetSharedMaterials()
  945. {
  946. int materialCount = m_textInfo.materialCount;
  947. if (m_fontSharedMaterials == null)
  948. m_fontSharedMaterials = new Material[materialCount];
  949. else if (m_fontSharedMaterials.Length != materialCount)
  950. TMP_TextInfo.Resize(ref m_fontSharedMaterials, materialCount, false);
  951. for (int i = 0; i < materialCount; i++)
  952. {
  953. if (i == 0)
  954. m_fontSharedMaterials[i] = m_sharedMaterial;
  955. else
  956. m_fontSharedMaterials[i] = m_subTextObjects[i].sharedMaterial;
  957. }
  958. return m_fontSharedMaterials;
  959. }
  960. /// <summary>
  961. /// Method used to assign new materials to the text and sub text objects.
  962. /// </summary>
  963. protected override void SetSharedMaterials(Material[] materials)
  964. {
  965. int materialCount = m_textInfo.materialCount;
  966. // Check allocation of the fontSharedMaterials array.
  967. if (m_fontSharedMaterials == null)
  968. m_fontSharedMaterials = new Material[materialCount];
  969. else if (m_fontSharedMaterials.Length != materialCount)
  970. TMP_TextInfo.Resize(ref m_fontSharedMaterials, materialCount, false);
  971. // Only assign as many materials as the text object contains.
  972. for (int i = 0; i < materialCount; i++)
  973. {
  974. Texture mat_MainTex = materials[i].GetTexture(ShaderUtilities.ID_MainTex);
  975. if (i == 0)
  976. {
  977. // Only assign new material if the font atlas textures match.
  978. if ( mat_MainTex == null || mat_MainTex.GetInstanceID() != m_sharedMaterial.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID())
  979. continue;
  980. m_sharedMaterial = m_fontSharedMaterials[i] = materials[i];
  981. m_padding = GetPaddingForMaterial(m_sharedMaterial);
  982. }
  983. else
  984. {
  985. // Only assign new material if the font atlas textures match.
  986. if (mat_MainTex == null || mat_MainTex.GetInstanceID() != m_subTextObjects[i].sharedMaterial.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID())
  987. continue;
  988. // Only assign a new material if none were specified in the text input.
  989. if (m_subTextObjects[i].isDefaultMaterial)
  990. m_subTextObjects[i].sharedMaterial = m_fontSharedMaterials[i] = materials[i];
  991. }
  992. }
  993. }
  994. // This function will create an instance of the Font Material.
  995. protected override void SetOutlineThickness(float thickness)
  996. {
  997. thickness = Mathf.Clamp01(thickness);
  998. m_renderer.material.SetFloat(ShaderUtilities.ID_OutlineWidth, thickness);
  999. if (m_fontMaterial == null)
  1000. m_fontMaterial = m_renderer.material;
  1001. m_fontMaterial = m_renderer.material;
  1002. m_sharedMaterial = m_fontMaterial;
  1003. m_padding = GetPaddingForMaterial();
  1004. }
  1005. // This function will create an instance of the Font Material.
  1006. protected override void SetFaceColor(Color32 color)
  1007. {
  1008. m_renderer.material.SetColor(ShaderUtilities.ID_FaceColor, color);
  1009. if (m_fontMaterial == null)
  1010. m_fontMaterial = m_renderer.material;
  1011. m_sharedMaterial = m_fontMaterial;
  1012. }
  1013. // This function will create an instance of the Font Material.
  1014. protected override void SetOutlineColor(Color32 color)
  1015. {
  1016. m_renderer.material.SetColor(ShaderUtilities.ID_OutlineColor, color);
  1017. if (m_fontMaterial == null)
  1018. m_fontMaterial = m_renderer.material;
  1019. //Debug.Log("Material ID:" + m_fontMaterial.GetInstanceID());
  1020. m_sharedMaterial = m_fontMaterial;
  1021. }
  1022. // Function used to create an instance of the material
  1023. void CreateMaterialInstance()
  1024. {
  1025. Material mat = new Material(m_sharedMaterial);
  1026. mat.shaderKeywords = m_sharedMaterial.shaderKeywords;
  1027. //mat.hideFlags = HideFlags.DontSave;
  1028. mat.name += " Instance";
  1029. m_fontMaterial = mat;
  1030. }
  1031. // Sets the Render Queue and Ztest mode
  1032. protected override void SetShaderDepth()
  1033. {
  1034. if (m_isOverlay)
  1035. {
  1036. // Changing these properties results in an instance of the material
  1037. //m_sharedMaterial.SetFloat(ShaderUtilities.ShaderTag_ZTestMode, 0);
  1038. Material mat = m_renderer.material;
  1039. //mat.renderQueue = 4000;
  1040. m_sharedMaterial = mat;
  1041. }
  1042. else
  1043. {
  1044. // Should this use an instanced material?
  1045. //m_sharedMaterial.SetFloat(ShaderUtilities.ShaderTag_ZTestMode, 4);
  1046. Material mat = m_renderer.material;
  1047. //mat.renderQueue = -1;
  1048. m_sharedMaterial = mat;
  1049. }
  1050. }
  1051. // Sets the Culling mode of the material
  1052. protected override void SetCulling()
  1053. {
  1054. if (m_isCullingEnabled)
  1055. {
  1056. m_renderer.material.SetFloat("_CullMode", 2);
  1057. for (int i = 1; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
  1058. {
  1059. Renderer renderer = m_subTextObjects[i].renderer;
  1060. if (renderer != null)
  1061. {
  1062. renderer.material.SetFloat(ShaderUtilities.ShaderTag_CullMode, 2);
  1063. }
  1064. }
  1065. }
  1066. else
  1067. {
  1068. m_renderer.material.SetFloat("_CullMode", 0);
  1069. for (int i = 1; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
  1070. {
  1071. Renderer renderer = m_subTextObjects[i].renderer;
  1072. if (renderer != null)
  1073. {
  1074. renderer.material.SetFloat(ShaderUtilities.ShaderTag_CullMode, 0);
  1075. }
  1076. }
  1077. }
  1078. }
  1079. // Set Perspective Correction Mode based on whether Camera is Orthographic or Perspective
  1080. void SetPerspectiveCorrection()
  1081. {
  1082. if (m_isOrthographic)
  1083. m_sharedMaterial.SetFloat(ShaderUtilities.ID_PerspectiveFilter, 0.0f);
  1084. else
  1085. m_sharedMaterial.SetFloat(ShaderUtilities.ID_PerspectiveFilter, 0.875f);
  1086. }
  1087. // This function parses through the Char[] to determine how many characters will be visible. It then makes sure the arrays are large enough for all those characters.
  1088. internal override int SetArraySizes(TextProcessingElement[] textProcessingArray)
  1089. {
  1090. k_SetArraySizesMarker.Begin();
  1091. int spriteCount = 0;
  1092. m_totalCharacterCount = 0;
  1093. m_isUsingBold = false;
  1094. m_isTextLayoutPhase = false;
  1095. tag_NoParsing = false;
  1096. m_FontStyleInternal = m_fontStyle;
  1097. m_fontStyleStack.Clear();
  1098. m_FontWeightInternal = (m_FontStyleInternal & FontStyles.Bold) == FontStyles.Bold ? FontWeight.Bold : m_fontWeight;
  1099. m_FontWeightStack.SetDefault(m_FontWeightInternal);
  1100. m_currentFontAsset = m_fontAsset;
  1101. m_currentMaterial = m_sharedMaterial;
  1102. m_currentMaterialIndex = 0;
  1103. m_materialReferenceStack.SetDefault(new MaterialReference(m_currentMaterialIndex, m_currentFontAsset, null, m_currentMaterial, m_padding));
  1104. m_materialReferenceIndexLookup.Clear();
  1105. MaterialReference.AddMaterialReference(m_currentMaterial, m_currentFontAsset, ref m_materialReferences, m_materialReferenceIndexLookup);
  1106. // Set allocations for the text object's TextInfo
  1107. if (m_textInfo == null)
  1108. m_textInfo = new TMP_TextInfo(m_InternalTextProcessingArraySize);
  1109. else if (m_textInfo.characterInfo.Length < m_InternalTextProcessingArraySize)
  1110. TMP_TextInfo.Resize(ref m_textInfo.characterInfo, m_InternalTextProcessingArraySize, false);
  1111. m_textElementType = TMP_TextElementType.Character;
  1112. // Handling for Underline special character
  1113. #region Setup Underline Special Character
  1114. /*
  1115. GetUnderlineSpecialCharacter(m_currentFontAsset);
  1116. if (m_Underline.character != null)
  1117. {
  1118. if (m_Underline.fontAsset.GetInstanceID() != m_currentFontAsset.GetInstanceID())
  1119. {
  1120. if (TMP_Settings.matchMaterialPreset && m_currentMaterial.GetInstanceID() != m_Underline.fontAsset.material.GetInstanceID())
  1121. m_Underline.material = TMP_MaterialManager.GetFallbackMaterial(m_currentMaterial, m_Underline.fontAsset.material);
  1122. else
  1123. m_Underline.material = m_Underline.fontAsset.material;
  1124. m_Underline.materialIndex = MaterialReference.AddMaterialReference(m_Underline.material, m_Underline.fontAsset, m_materialReferences, m_materialReferenceIndexLookup);
  1125. m_materialReferences[m_Underline.materialIndex].referenceCount = 0;
  1126. }
  1127. }
  1128. */
  1129. #endregion
  1130. // Handling for Ellipsis special character
  1131. #region Setup Ellipsis Special Character
  1132. if (m_overflowMode == TextOverflowModes.Ellipsis)
  1133. {
  1134. GetEllipsisSpecialCharacter(m_currentFontAsset);
  1135. if (m_Ellipsis.character != null)
  1136. {
  1137. if (m_Ellipsis.fontAsset.GetInstanceID() != m_currentFontAsset.GetInstanceID())
  1138. {
  1139. if (TMP_Settings.matchMaterialPreset && m_currentMaterial.GetInstanceID() != m_Ellipsis.fontAsset.material.GetInstanceID())
  1140. m_Ellipsis.material = TMP_MaterialManager.GetFallbackMaterial(m_currentMaterial, m_Ellipsis.fontAsset.material);
  1141. else
  1142. m_Ellipsis.material = m_Ellipsis.fontAsset.material;
  1143. m_Ellipsis.materialIndex = MaterialReference.AddMaterialReference(m_Ellipsis.material, m_Ellipsis.fontAsset, ref m_materialReferences, m_materialReferenceIndexLookup);
  1144. m_materialReferences[m_Ellipsis.materialIndex].referenceCount = 0;
  1145. }
  1146. }
  1147. else
  1148. {
  1149. m_overflowMode = TextOverflowModes.Truncate;
  1150. if (!TMP_Settings.warningsDisabled)
  1151. Debug.LogWarning("The character used for Ellipsis is not available in font asset [" + m_currentFontAsset.name + "] or any potential fallbacks. Switching Text Overflow mode to Truncate.", this);
  1152. }
  1153. }
  1154. #endregion
  1155. // Check if we should process Ligatures
  1156. bool ligature = m_ActiveFontFeatures.Contains(OTL_FeatureTag.liga);
  1157. // Clear Linked Text object if we have one.
  1158. if (m_overflowMode == TextOverflowModes.Linked && m_linkedTextComponent != null && !m_isCalculatingPreferredValues)
  1159. m_linkedTextComponent.text = string.Empty;
  1160. // Parsing XML tags in the text
  1161. for (int i = 0; i < textProcessingArray.Length && textProcessingArray[i].unicode != 0; i++)
  1162. {
  1163. //Make sure the characterInfo array can hold the next text element.
  1164. if (m_textInfo.characterInfo == null || m_totalCharacterCount >= m_textInfo.characterInfo.Length)
  1165. TMP_TextInfo.Resize(ref m_textInfo.characterInfo, m_totalCharacterCount + 1, true);
  1166. uint unicode = textProcessingArray[i].unicode;
  1167. // PARSE XML TAGS
  1168. #region PARSE XML TAGS
  1169. if (m_isRichText && unicode == 60) // if Char '<'
  1170. {
  1171. int prev_MaterialIndex = m_currentMaterialIndex;
  1172. int endTagIndex;
  1173. // Check if Tag is Valid
  1174. if (ValidateHtmlTag(textProcessingArray, i + 1, out endTagIndex))
  1175. {
  1176. int tagStartIndex = textProcessingArray[i].stringIndex;
  1177. i = endTagIndex;
  1178. if ((m_FontStyleInternal & FontStyles.Bold) == FontStyles.Bold)
  1179. m_isUsingBold = true;
  1180. if (m_textElementType == TMP_TextElementType.Sprite)
  1181. {
  1182. m_materialReferences[m_currentMaterialIndex].referenceCount += 1;
  1183. m_textInfo.characterInfo[m_totalCharacterCount].character = (char)(57344 + m_spriteIndex);
  1184. m_textInfo.characterInfo[m_totalCharacterCount].fontAsset = m_currentFontAsset;
  1185. m_textInfo.characterInfo[m_totalCharacterCount].materialReferenceIndex = m_currentMaterialIndex;
  1186. m_textInfo.characterInfo[m_totalCharacterCount].textElement = m_currentSpriteAsset.spriteCharacterTable[m_spriteIndex];
  1187. m_textInfo.characterInfo[m_totalCharacterCount].elementType = m_textElementType;
  1188. m_textInfo.characterInfo[m_totalCharacterCount].index = tagStartIndex;
  1189. m_textInfo.characterInfo[m_totalCharacterCount].stringLength = textProcessingArray[i].stringIndex - tagStartIndex + 1;
  1190. // Restore element type and material index to previous values.
  1191. m_textElementType = TMP_TextElementType.Character;
  1192. m_currentMaterialIndex = prev_MaterialIndex;
  1193. spriteCount += 1;
  1194. m_totalCharacterCount += 1;
  1195. }
  1196. continue;
  1197. }
  1198. }
  1199. #endregion
  1200. bool isUsingAlternativeTypeface = false;
  1201. bool isUsingFallbackOrAlternativeTypeface = false;
  1202. TMP_FontAsset prev_fontAsset = m_currentFontAsset;
  1203. Material prev_material = m_currentMaterial;
  1204. int prev_materialIndex = m_currentMaterialIndex;
  1205. // Handle Font Styles like LowerCase, UpperCase and SmallCaps.
  1206. #region Handling of LowerCase, UpperCase and SmallCaps Font Styles
  1207. if (m_textElementType == TMP_TextElementType.Character)
  1208. {
  1209. if ((m_FontStyleInternal & FontStyles.UpperCase) == FontStyles.UpperCase)
  1210. {
  1211. // If this character is lowercase, switch to uppercase.
  1212. if (char.IsLower((char)unicode))
  1213. unicode = char.ToUpper((char)unicode);
  1214. }
  1215. else if ((m_FontStyleInternal & FontStyles.LowerCase) == FontStyles.LowerCase)
  1216. {
  1217. // If this character is uppercase, switch to lowercase.
  1218. if (char.IsUpper((char)unicode))
  1219. unicode = char.ToLower((char)unicode);
  1220. }
  1221. else if ((m_FontStyleInternal & FontStyles.SmallCaps) == FontStyles.SmallCaps)
  1222. {
  1223. // Only convert lowercase characters to uppercase.
  1224. if (char.IsLower((char)unicode))
  1225. unicode = char.ToUpper((char)unicode);
  1226. }
  1227. }
  1228. #endregion
  1229. // Lookup the Glyph data for each character and cache it.
  1230. #region LOOKUP GLYPH
  1231. TMP_TextElement character = null;
  1232. uint nextCharacter = i + 1 < textProcessingArray.Length ? textProcessingArray[i + 1].unicode : 0;
  1233. // Check Emoji Fallback first in the event the requested unicode code point is an Emoji
  1234. if (emojiFallbackSupport && ((TMP_TextParsingUtilities.IsEmojiPresentationForm(unicode) && nextCharacter != 0xFE0E) || (TMP_TextParsingUtilities.IsEmoji(unicode) && nextCharacter == 0xFE0F)))
  1235. {
  1236. if (TMP_Settings.emojiFallbackTextAssets != null && TMP_Settings.emojiFallbackTextAssets.Count > 0)
  1237. {
  1238. character = TMP_FontAssetUtilities.GetTextElementFromTextAssets(unicode, m_currentFontAsset, TMP_Settings.emojiFallbackTextAssets, true, fontStyle, fontWeight, out isUsingAlternativeTypeface);
  1239. if (character != null)
  1240. {
  1241. // Add character to font asset lookup cache
  1242. //fontAsset.AddCharacterToLookupCache(unicode, character);
  1243. }
  1244. }
  1245. }
  1246. if (character == null)
  1247. character = GetTextElement(unicode, m_currentFontAsset, m_FontStyleInternal, m_FontWeightInternal, out isUsingAlternativeTypeface);
  1248. // Check if Lowercase or Uppercase variant of the character is available.
  1249. /* Not sure this is necessary anyone as it is very unlikely with recursive search through fallback fonts.
  1250. if (glyph == null)
  1251. {
  1252. if (char.IsLower((char)c))
  1253. {
  1254. if (m_currentFontAsset.characterDictionary.TryGetValue(char.ToUpper((char)c), out glyph))
  1255. c = chars[i] = char.ToUpper((char)c);
  1256. }
  1257. else if (char.IsUpper((char)c))
  1258. {
  1259. if (m_currentFontAsset.characterDictionary.TryGetValue(char.ToLower((char)c), out glyph))
  1260. c = chars[i] = char.ToLower((char)c);
  1261. }
  1262. }*/
  1263. #region MISSING CHARACTER HANDLING
  1264. // Replace missing glyph by the Square (9633) glyph or possibly the Space (32) glyph.
  1265. if (character == null)
  1266. {
  1267. DoMissingGlyphCallback((int)unicode, textProcessingArray[i].stringIndex, m_currentFontAsset);
  1268. // Save the original unicode character
  1269. uint srcGlyph = unicode;
  1270. // Try replacing the missing glyph character by TMP Settings Missing Glyph or Square (9633) character.
  1271. unicode = textProcessingArray[i].unicode = (uint)TMP_Settings.missingGlyphCharacter == 0 ? 9633 : (uint)TMP_Settings.missingGlyphCharacter;
  1272. // Check for the missing glyph character in the currently assigned font asset and its fallbacks
  1273. character = TMP_FontAssetUtilities.GetCharacterFromFontAsset((uint)unicode, m_currentFontAsset, true, m_FontStyleInternal, m_FontWeightInternal, out isUsingAlternativeTypeface);
  1274. if (character == null)
  1275. {
  1276. // Search for the missing glyph character in the TMP Settings Fallback list.
  1277. if (TMP_Settings.fallbackFontAssets != null && TMP_Settings.fallbackFontAssets.Count > 0)
  1278. character = TMP_FontAssetUtilities.GetCharacterFromFontAssets(unicode, m_currentFontAsset, TMP_Settings.fallbackFontAssets, true, m_FontStyleInternal, m_FontWeightInternal, out isUsingAlternativeTypeface);
  1279. }
  1280. if (character == null)
  1281. {
  1282. // Search for the missing glyph in the TMP Settings Default Font Asset.
  1283. if (TMP_Settings.defaultFontAsset != null)
  1284. character = TMP_FontAssetUtilities.GetCharacterFromFontAsset(unicode, TMP_Settings.defaultFontAsset, true, m_FontStyleInternal, m_FontWeightInternal, out isUsingAlternativeTypeface);
  1285. }
  1286. if (character == null)
  1287. {
  1288. // Use Space (32) Glyph from the currently assigned font asset.
  1289. unicode = textProcessingArray[i].unicode = 32;
  1290. character = TMP_FontAssetUtilities.GetCharacterFromFontAsset(unicode, m_currentFontAsset, true, m_FontStyleInternal, m_FontWeightInternal, out isUsingAlternativeTypeface);
  1291. }
  1292. if (character == null)
  1293. {
  1294. // Use End of Text (0x03) Glyph from the currently assigned font asset.
  1295. unicode = textProcessingArray[i].unicode = 0x03;
  1296. character = TMP_FontAssetUtilities.GetCharacterFromFontAsset(unicode, m_currentFontAsset, true, m_FontStyleInternal, m_FontWeightInternal, out isUsingAlternativeTypeface);
  1297. }
  1298. if (!TMP_Settings.warningsDisabled)
  1299. {
  1300. string formattedWarning = srcGlyph > 0xFFFF
  1301. ? string.Format("The character with Unicode value \\U{0:X8} was not found in the [{1}] font asset or any potential fallbacks. It was replaced by Unicode character \\u{2:X4} in text object [{3}].", srcGlyph, m_fontAsset.name, character.unicode, this.name)
  1302. : string.Format("The character with Unicode value \\u{0:X4} was not found in the [{1}] font asset or any potential fallbacks. It was replaced by Unicode character \\u{2:X4} in text object [{3}].", srcGlyph, m_fontAsset.name, character.unicode, this.name);
  1303. Debug.LogWarning(formattedWarning, this);
  1304. }
  1305. }
  1306. #endregion
  1307. m_textInfo.characterInfo[m_totalCharacterCount].alternativeGlyph = null;
  1308. if (character.elementType == TextElementType.Character)
  1309. {
  1310. if (character.textAsset.instanceID != m_currentFontAsset.instanceID)
  1311. {
  1312. isUsingFallbackOrAlternativeTypeface = true;
  1313. m_currentFontAsset = character.textAsset as TMP_FontAsset;
  1314. }
  1315. #region VARIATION SELECTOR
  1316. if (nextCharacter >= 0xFE00 && nextCharacter <= 0xFE0F || nextCharacter >= 0xE0100 && nextCharacter <= 0xE01EF)
  1317. {
  1318. // Get potential variant glyph index
  1319. uint variantGlyphIndex = m_currentFontAsset.GetGlyphVariantIndex((uint)unicode, nextCharacter);
  1320. if (variantGlyphIndex != 0)
  1321. {
  1322. if (m_currentFontAsset.TryAddGlyphInternal(variantGlyphIndex, out Glyph glyph))
  1323. {
  1324. m_textInfo.characterInfo[m_totalCharacterCount].alternativeGlyph = glyph;
  1325. }
  1326. }
  1327. textProcessingArray[i + 1].unicode = 0x1A;
  1328. i += 1;
  1329. }
  1330. #endregion
  1331. #region LIGATURES
  1332. if (ligature && m_currentFontAsset.fontFeatureTable.m_LigatureSubstitutionRecordLookup.TryGetValue(character.glyphIndex, out List<LigatureSubstitutionRecord> records))
  1333. {
  1334. if (records == null)
  1335. break;
  1336. for (int j = 0; j < records.Count; j++)
  1337. {
  1338. LigatureSubstitutionRecord record = records[j];
  1339. int componentCount = record.componentGlyphIDs.Length;
  1340. uint ligatureGlyphID = record.ligatureGlyphID;
  1341. //
  1342. for (int k = 1; k < componentCount; k++)
  1343. {
  1344. uint componentUnicode = (uint)textProcessingArray[i + k].unicode;
  1345. // Special Handling for Zero Width Joiner (ZWJ)
  1346. //if (componentUnicode == 0x200D)
  1347. // continue;
  1348. uint glyphIndex = m_currentFontAsset.GetGlyphIndex(componentUnicode);
  1349. if (glyphIndex == record.componentGlyphIDs[k])
  1350. continue;
  1351. ligatureGlyphID = 0;
  1352. break;
  1353. }
  1354. if (ligatureGlyphID != 0)
  1355. {
  1356. if (m_currentFontAsset.TryAddGlyphInternal(ligatureGlyphID, out Glyph glyph))
  1357. {
  1358. m_textInfo.characterInfo[m_totalCharacterCount].alternativeGlyph = glyph;
  1359. // Update text processing array
  1360. for (int c = 0; c < componentCount; c++)
  1361. {
  1362. if (c == 0)
  1363. {
  1364. textProcessingArray[i + c].length = componentCount;
  1365. continue;
  1366. }
  1367. textProcessingArray[i + c].unicode = 0x1A;
  1368. }
  1369. i += componentCount - 1;
  1370. break;
  1371. }
  1372. }
  1373. }
  1374. }
  1375. #endregion
  1376. }
  1377. #endregion
  1378. // Save text element data
  1379. m_textInfo.characterInfo[m_totalCharacterCount].elementType = TMP_TextElementType.Character;
  1380. m_textInfo.characterInfo[m_totalCharacterCount].textElement = character;
  1381. m_textInfo.characterInfo[m_totalCharacterCount].isUsingAlternateTypeface = isUsingAlternativeTypeface;
  1382. m_textInfo.characterInfo[m_totalCharacterCount].character = (char)unicode;
  1383. m_textInfo.characterInfo[m_totalCharacterCount].index = textProcessingArray[i].stringIndex;
  1384. m_textInfo.characterInfo[m_totalCharacterCount].stringLength = textProcessingArray[i].length;
  1385. m_textInfo.characterInfo[m_totalCharacterCount].fontAsset = m_currentFontAsset;
  1386. // Special handling if the character is a sprite.
  1387. if (character.elementType == TextElementType.Sprite)
  1388. {
  1389. TMP_SpriteAsset spriteAssetRef = character.textAsset as TMP_SpriteAsset;
  1390. m_currentMaterialIndex = MaterialReference.AddMaterialReference(spriteAssetRef.material, spriteAssetRef, ref m_materialReferences, m_materialReferenceIndexLookup);
  1391. m_materialReferences[m_currentMaterialIndex].referenceCount += 1;
  1392. m_textInfo.characterInfo[m_totalCharacterCount].elementType = TMP_TextElementType.Sprite;
  1393. m_textInfo.characterInfo[m_totalCharacterCount].materialReferenceIndex = m_currentMaterialIndex;
  1394. // Restore element type and material index to previous values.
  1395. m_textElementType = TMP_TextElementType.Character;
  1396. m_currentMaterialIndex = prev_materialIndex;
  1397. spriteCount += 1;
  1398. m_totalCharacterCount += 1;
  1399. continue;
  1400. }
  1401. if (isUsingFallbackOrAlternativeTypeface && m_currentFontAsset.instanceID != m_fontAsset.instanceID)
  1402. {
  1403. // Create Fallback material instance matching current material preset if necessary
  1404. if (TMP_Settings.matchMaterialPreset)
  1405. m_currentMaterial = TMP_MaterialManager.GetFallbackMaterial(m_currentMaterial, m_currentFontAsset.material);
  1406. else
  1407. m_currentMaterial = m_currentFontAsset.material;
  1408. m_currentMaterialIndex = MaterialReference.AddMaterialReference(m_currentMaterial, m_currentFontAsset, ref m_materialReferences, m_materialReferenceIndexLookup);
  1409. }
  1410. // Handle Multi Atlas Texture support
  1411. if (character != null && character.glyph.atlasIndex > 0)
  1412. {
  1413. m_currentMaterial = TMP_MaterialManager.GetFallbackMaterial(m_currentFontAsset, m_currentMaterial, character.glyph.atlasIndex);
  1414. m_currentMaterialIndex = MaterialReference.AddMaterialReference(m_currentMaterial, m_currentFontAsset, ref m_materialReferences, m_materialReferenceIndexLookup);
  1415. isUsingFallbackOrAlternativeTypeface = true;
  1416. }
  1417. if (!char.IsWhiteSpace((char)unicode) && unicode != 0x200B)
  1418. {
  1419. // Limit the mesh of the main text object to 65535 vertices and use sub objects for the overflow.
  1420. if (m_materialReferences[m_currentMaterialIndex].referenceCount < 16383)
  1421. m_materialReferences[m_currentMaterialIndex].referenceCount += 1;
  1422. else
  1423. {
  1424. m_currentMaterialIndex = MaterialReference.AddMaterialReference(new Material(m_currentMaterial), m_currentFontAsset, ref m_materialReferences, m_materialReferenceIndexLookup);
  1425. m_materialReferences[m_currentMaterialIndex].referenceCount += 1;
  1426. }
  1427. }
  1428. m_textInfo.characterInfo[m_totalCharacterCount].material = m_currentMaterial;
  1429. m_textInfo.characterInfo[m_totalCharacterCount].materialReferenceIndex = m_currentMaterialIndex;
  1430. m_materialReferences[m_currentMaterialIndex].isFallbackMaterial = isUsingFallbackOrAlternativeTypeface;
  1431. // Restore previous font asset and material if fallback font was used.
  1432. if (isUsingFallbackOrAlternativeTypeface)
  1433. {
  1434. m_materialReferences[m_currentMaterialIndex].fallbackMaterial = prev_material;
  1435. m_currentFontAsset = prev_fontAsset;
  1436. m_currentMaterial = prev_material;
  1437. m_currentMaterialIndex = prev_materialIndex;
  1438. }
  1439. m_totalCharacterCount += 1;
  1440. }
  1441. // Early return if we are calculating the preferred values.
  1442. if (m_isCalculatingPreferredValues)
  1443. {
  1444. m_isCalculatingPreferredValues = false;
  1445. k_SetArraySizesMarker.End();
  1446. return m_totalCharacterCount;
  1447. }
  1448. // Save material and sprite count.
  1449. m_textInfo.spriteCount = spriteCount;
  1450. int materialCount = m_textInfo.materialCount = m_materialReferenceIndexLookup.Count;
  1451. // Check if we need to resize the MeshInfo array for handling different materials.
  1452. if (materialCount > m_textInfo.meshInfo.Length)
  1453. TMP_TextInfo.Resize(ref m_textInfo.meshInfo, materialCount, false);
  1454. // Resize SubTextObject array if necessary
  1455. if (materialCount > m_subTextObjects.Length)
  1456. TMP_TextInfo.Resize(ref m_subTextObjects, Mathf.NextPowerOfTwo(materialCount + 1));
  1457. // Resize CharacterInfo[] if allocations are excessive
  1458. if (m_VertexBufferAutoSizeReduction && m_textInfo.characterInfo.Length - m_totalCharacterCount > 256)
  1459. TMP_TextInfo.Resize(ref m_textInfo.characterInfo, Mathf.Max(m_totalCharacterCount + 1, 256), true);
  1460. // Iterate through the material references to set the mesh buffer allocations
  1461. for (int i = 0; i < materialCount; i++)
  1462. {
  1463. // Add new sub text object for each material reference
  1464. if (i > 0)
  1465. {
  1466. if (m_subTextObjects[i] == null)
  1467. {
  1468. m_subTextObjects[i] = TMP_SubMesh.AddSubTextObject(this, m_materialReferences[i]);
  1469. // Not sure this is necessary
  1470. m_textInfo.meshInfo[i].vertices = null;
  1471. }
  1472. //else if (m_subTextObjects[i].gameObject.activeInHierarchy == false)
  1473. // m_subTextObjects[i].gameObject.SetActive(true);
  1474. // Check if the material has changed.
  1475. if (m_subTextObjects[i].sharedMaterial == null || m_subTextObjects[i].sharedMaterial.GetInstanceID() != m_materialReferences[i].material.GetInstanceID())
  1476. {
  1477. m_subTextObjects[i].sharedMaterial = m_materialReferences[i].material;
  1478. m_subTextObjects[i].fontAsset = m_materialReferences[i].fontAsset;
  1479. m_subTextObjects[i].spriteAsset = m_materialReferences[i].spriteAsset;
  1480. }
  1481. // Check if we need to use a Fallback Material
  1482. if (m_materialReferences[i].isFallbackMaterial)
  1483. {
  1484. m_subTextObjects[i].fallbackMaterial = m_materialReferences[i].material;
  1485. m_subTextObjects[i].fallbackSourceMaterial = m_materialReferences[i].fallbackMaterial;
  1486. }
  1487. }
  1488. int referenceCount = m_materialReferences[i].referenceCount;
  1489. // Check to make sure our buffers allocations can accommodate the required text elements.
  1490. if (m_textInfo.meshInfo[i].vertices == null || m_textInfo.meshInfo[i].vertices.Length < referenceCount * 4)
  1491. {
  1492. if (m_textInfo.meshInfo[i].vertices == null)
  1493. {
  1494. if (i == 0)
  1495. m_textInfo.meshInfo[i] = new TMP_MeshInfo(m_mesh, referenceCount + 1);
  1496. else
  1497. m_textInfo.meshInfo[i] = new TMP_MeshInfo(m_subTextObjects[i].mesh, referenceCount + 1);
  1498. }
  1499. else
  1500. m_textInfo.meshInfo[i].ResizeMeshInfo(referenceCount > 1024 ? referenceCount + 256 : Mathf.NextPowerOfTwo(referenceCount + 1));
  1501. }
  1502. else if (m_VertexBufferAutoSizeReduction && referenceCount > 0 && m_textInfo.meshInfo[i].vertices.Length / 4 - referenceCount > 256)
  1503. {
  1504. // Resize vertex buffers if allocations are excessive.
  1505. //Debug.Log("Reducing the size of the vertex buffers.");
  1506. m_textInfo.meshInfo[i].ResizeMeshInfo(referenceCount > 1024 ? referenceCount + 256 : Mathf.NextPowerOfTwo(referenceCount + 1));
  1507. }
  1508. // Assign material reference
  1509. m_textInfo.meshInfo[i].material = m_materialReferences[i].material;
  1510. }
  1511. //TMP_MaterialManager.CleanupFallbackMaterials();
  1512. // Clean up unused SubMeshes
  1513. for (int i = materialCount; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
  1514. {
  1515. if (i < m_textInfo.meshInfo.Length)
  1516. m_textInfo.meshInfo[i].ClearUnusedVertices(0, true);
  1517. //m_subTextObjects[i].gameObject.SetActive(false);
  1518. }
  1519. k_SetArraySizesMarker.End();
  1520. return m_totalCharacterCount;
  1521. }
  1522. // Added to sort handle the potential issue with OnWillRenderObject() not getting called when objects are not visible by camera.
  1523. //void OnBecameInvisible()
  1524. //{
  1525. // if (m_mesh != null)
  1526. // m_mesh.bounds = new Bounds(transform.position, new Vector3(1000, 1000, 0));
  1527. //}
  1528. /// <summary>
  1529. /// Update the margin width and height
  1530. /// </summary>
  1531. public override void ComputeMarginSize()
  1532. {
  1533. if (this.rectTransform != null)
  1534. {
  1535. //Debug.Log("*** ComputeMarginSize() *** Current RectTransform's Width is " + m_rectTransform.rect.width + " and Height is " + m_rectTransform.rect.height); // + " and size delta is " + m_rectTransform.sizeDelta);
  1536. Rect rect = m_rectTransform.rect;
  1537. m_marginWidth = rect.width - m_margin.x - m_margin.z;
  1538. m_marginHeight = rect.height - m_margin.y - m_margin.w;
  1539. // Cache current RectTransform width and pivot referenced in OnRectTransformDimensionsChange() to get around potential rounding error in the reported width of the RectTransform.
  1540. m_PreviousRectTransformSize = rect.size;
  1541. m_PreviousPivotPosition = m_rectTransform.pivot;
  1542. // Update the corners of the RectTransform
  1543. m_RectTransformCorners = GetTextContainerLocalCorners();
  1544. }
  1545. }
  1546. /// <summary>
  1547. ///
  1548. /// </summary>
  1549. protected override void OnDidApplyAnimationProperties()
  1550. {
  1551. m_havePropertiesChanged = true;
  1552. isMaskUpdateRequired = true;
  1553. SetVerticesDirty();
  1554. }
  1555. protected override void OnTransformParentChanged()
  1556. {
  1557. //Debug.Log("*** OnTransformParentChanged() ***");
  1558. //ComputeMarginSize();
  1559. SetVerticesDirty();
  1560. SetLayoutDirty();
  1561. }
  1562. protected override void OnRectTransformDimensionsChange()
  1563. {
  1564. //Debug.Log("*** OnRectTransformDimensionsChange() ***");
  1565. // Ignore changes to RectTransform SizeDelta that are very small and typically the result of rounding errors when using RectTransform in Anchor Stretch mode.
  1566. if (rectTransform != null &&
  1567. Mathf.Abs(m_rectTransform.rect.width - m_PreviousRectTransformSize.x) < 0.0001f && Mathf.Abs(m_rectTransform.rect.height - m_PreviousRectTransformSize.y) < 0.0001f &&
  1568. Mathf.Abs(m_rectTransform.pivot.x - m_PreviousPivotPosition.x) < 0.0001f && Mathf.Abs(m_rectTransform.pivot.y - m_PreviousPivotPosition.y) < 0.0001f)
  1569. {
  1570. return;
  1571. }
  1572. ComputeMarginSize();
  1573. SetVerticesDirty();
  1574. SetLayoutDirty();
  1575. }
  1576. /// <summary>
  1577. /// Function used as a replacement for LateUpdate to check if the transform or scale of the text object has changed.
  1578. /// </summary>
  1579. internal override void InternalUpdate()
  1580. {
  1581. // We need to update the SDF scale or possibly regenerate the text object if lossy scale has changed.
  1582. if (m_havePropertiesChanged == false)
  1583. {
  1584. float lossyScaleY = m_rectTransform.lossyScale.y;
  1585. if (lossyScaleY != m_previousLossyScaleY && m_TextProcessingArray[0].unicode != 0)
  1586. {
  1587. float scaleDelta = lossyScaleY / m_previousLossyScaleY;
  1588. // Only update SDF Scale when lossy scale has changed by more than 20%
  1589. if (scaleDelta < 0.8f || scaleDelta > 1.25f)
  1590. {
  1591. UpdateSDFScale(scaleDelta);
  1592. m_previousLossyScaleY = lossyScaleY;
  1593. }
  1594. }
  1595. }
  1596. // Added to handle legacy animation mode.
  1597. if (m_isUsingLegacyAnimationComponent)
  1598. {
  1599. m_havePropertiesChanged = true;
  1600. OnPreRenderObject();
  1601. }
  1602. }
  1603. /// <summary>
  1604. /// Function called when the text needs to be updated.
  1605. /// </summary>
  1606. void OnPreRenderObject()
  1607. {
  1608. //Debug.Log("*** OnPreRenderObject() called on object [" + this.name + "] ***");
  1609. // Make sure object is active.
  1610. if (!m_isAwake || (this.IsActive() == false && m_ignoreActiveState == false))
  1611. return;
  1612. // Check if we have a font asset assigned. Return if we don't because no one likes to see purple squares on screen.
  1613. if (m_fontAsset == null)
  1614. {
  1615. Debug.LogWarning("Please assign a Font Asset to this " + transform.name + " gameobject.", this);
  1616. return;
  1617. }
  1618. if (m_havePropertiesChanged || m_isLayoutDirty)
  1619. {
  1620. //Debug.Log("Properties have changed!"); // Assigned Material is:" + m_sharedMaterial); // New Text is: " + m_text + ".");
  1621. if (isMaskUpdateRequired)
  1622. {
  1623. UpdateMask();
  1624. isMaskUpdateRequired = false;
  1625. }
  1626. // Update mesh padding if necessary.
  1627. if (checkPaddingRequired)
  1628. UpdateMeshPadding();
  1629. // Reparse the text as input may have changed or been truncated.
  1630. ParseInputText();
  1631. TMP_FontAsset.UpdateFontAssetsInUpdateQueue();
  1632. // Reset Font min / max used with Auto-sizing
  1633. if (m_enableAutoSizing)
  1634. m_fontSize = Mathf.Clamp(m_fontSizeBase, m_fontSizeMin, m_fontSizeMax);
  1635. m_maxFontSize = m_fontSizeMax;
  1636. m_minFontSize = m_fontSizeMin;
  1637. m_lineSpacingDelta = 0;
  1638. m_charWidthAdjDelta = 0;
  1639. m_isTextTruncated = false;
  1640. m_havePropertiesChanged = false;
  1641. m_isLayoutDirty = false;
  1642. m_ignoreActiveState = false;
  1643. // Reset Text Auto Size iteration tracking.
  1644. m_IsAutoSizePointSizeSet = false;
  1645. m_AutoSizeIterationCount = 0;
  1646. // Make sure state of MeshRenderer is mirrored on potential sub text objects.
  1647. SetActiveSubTextObjectRenderers(m_renderer.enabled);
  1648. // The GenerateTextMesh function is potentially called repeatedly when text auto size is enabled.
  1649. // This is a revised implementation to remove the use of recursion which could potentially result in stack overflow issues.
  1650. while (m_IsAutoSizePointSizeSet == false)
  1651. {
  1652. GenerateTextMesh();
  1653. m_AutoSizeIterationCount += 1;
  1654. }
  1655. }
  1656. }
  1657. /// <summary>
  1658. /// This is the main function that is responsible for creating / displaying the text.
  1659. /// </summary>
  1660. protected virtual void GenerateTextMesh()
  1661. {
  1662. k_GenerateTextMarker.Begin();
  1663. // Early exit if no font asset was assigned. This should not be needed since LiberationSans SDF will be assigned by default.
  1664. if (m_fontAsset == null || m_fontAsset.characterLookupTable == null)
  1665. {
  1666. Debug.LogWarning("Can't Generate Mesh! No Font Asset has been assigned to Object ID: " + this.GetInstanceID());
  1667. m_IsAutoSizePointSizeSet = true;
  1668. k_GenerateTextMarker.End();
  1669. return;
  1670. }
  1671. // Clear TextInfo
  1672. if (m_textInfo != null)
  1673. m_textInfo.Clear();
  1674. // Early exit if we don't have any Text to generate.
  1675. if (m_TextProcessingArray == null || m_TextProcessingArray.Length == 0 || m_TextProcessingArray[0].unicode == 0)
  1676. {
  1677. // Clear mesh and upload changes to the mesh.
  1678. ClearMesh(true);
  1679. m_preferredWidth = 0;
  1680. m_preferredHeight = 0;
  1681. // Event indicating the text has been regenerated.
  1682. TMPro_EventManager.ON_TEXT_CHANGED(this);
  1683. m_IsAutoSizePointSizeSet = true;
  1684. k_GenerateTextMarker.End();
  1685. return;
  1686. }
  1687. m_currentFontAsset = m_fontAsset;
  1688. m_currentMaterial = m_sharedMaterial;
  1689. m_currentMaterialIndex = 0;
  1690. m_materialReferenceStack.SetDefault(new MaterialReference(m_currentMaterialIndex, m_currentFontAsset, null, m_currentMaterial, m_padding));
  1691. m_currentSpriteAsset = m_spriteAsset;
  1692. // Stop all Sprite Animations
  1693. if (m_spriteAnimator != null)
  1694. m_spriteAnimator.StopAllAnimations();
  1695. // Total character count is computed when the text is parsed.
  1696. int totalCharacterCount = m_totalCharacterCount;
  1697. // Calculate the scale of the font based on selected font size and sampling point size.
  1698. // baseScale is calculated using the font asset assigned to the text object.
  1699. float baseScale = (m_fontSize / m_fontAsset.m_FaceInfo.pointSize * m_fontAsset.m_FaceInfo.scale * (m_isOrthographic ? 1 : 0.1f));
  1700. float currentElementScale = baseScale;
  1701. float currentEmScale = m_fontSize * 0.01f * (m_isOrthographic ? 1 : 0.1f);
  1702. m_fontScaleMultiplier = 1;
  1703. m_currentFontSize = m_fontSize;
  1704. m_sizeStack.SetDefault(m_currentFontSize);
  1705. float fontSizeDelta = 0;
  1706. uint charCode = 0; // Holds the character code of the currently being processed character.
  1707. m_FontStyleInternal = m_fontStyle; // Set the default style.
  1708. m_FontWeightInternal = (m_FontStyleInternal & FontStyles.Bold) == FontStyles.Bold ? FontWeight.Bold : m_fontWeight;
  1709. m_FontWeightStack.SetDefault(m_FontWeightInternal);
  1710. m_fontStyleStack.Clear();
  1711. m_lineJustification = m_HorizontalAlignment; // m_textAlignment; // Sets the line justification mode to match editor alignment.
  1712. m_lineJustificationStack.SetDefault(m_lineJustification);
  1713. float padding = 0;
  1714. m_baselineOffset = 0; // Used by subscript characters.
  1715. m_baselineOffsetStack.Clear();
  1716. // Underline
  1717. bool beginUnderline = false;
  1718. Vector3 underline_start = Vector3.zero; // Used to track where underline starts & ends.
  1719. Vector3 underline_end = Vector3.zero;
  1720. // Strike-through
  1721. bool beginStrikethrough = false;
  1722. Vector3 strikethrough_start = Vector3.zero;
  1723. Vector3 strikethrough_end = Vector3.zero;
  1724. // Text Highlight
  1725. bool beginHighlight = false;
  1726. Vector3 highlight_start = Vector3.zero;
  1727. Vector3 highlight_end = Vector3.zero;
  1728. m_fontColor32 = m_fontColor;
  1729. m_htmlColor = m_fontColor32;
  1730. m_underlineColor = m_htmlColor;
  1731. m_strikethroughColor = m_htmlColor;
  1732. m_colorStack.SetDefault(m_htmlColor);
  1733. m_underlineColorStack.SetDefault(m_htmlColor);
  1734. m_strikethroughColorStack.SetDefault(m_htmlColor);
  1735. m_HighlightStateStack.SetDefault(new HighlightState(m_htmlColor, TMP_Offset.zero));
  1736. m_colorGradientPreset = null;
  1737. m_colorGradientStack.SetDefault(null);
  1738. m_ItalicAngle = m_currentFontAsset.italicStyle;
  1739. m_ItalicAngleStack.SetDefault(m_ItalicAngle);
  1740. // Clear the Style stack.
  1741. //m_styleStack.Clear();
  1742. // Clear the Action stack.
  1743. m_actionStack.Clear();
  1744. m_FXScale = Vector3.one;
  1745. m_FXRotation = Quaternion.identity;
  1746. m_lineOffset = 0; // Amount of space between lines (font line spacing + m_linespacing).
  1747. m_lineHeight = TMP_Math.FLOAT_UNSET;
  1748. float lineGap = m_currentFontAsset.m_FaceInfo.lineHeight - (m_currentFontAsset.m_FaceInfo.ascentLine - m_currentFontAsset.m_FaceInfo.descentLine);
  1749. m_cSpacing = 0; // Amount of space added between characters as a result of the use of the <cspace> tag.
  1750. m_monoSpacing = 0;
  1751. m_xAdvance = 0; // Used to track the position of each character.
  1752. tag_LineIndent = 0; // Used for indentation of text.
  1753. tag_Indent = 0;
  1754. m_indentStack.SetDefault(0);
  1755. tag_NoParsing = false;
  1756. //m_isIgnoringAlignment = false;
  1757. m_characterCount = 0; // Total characters in the char[]
  1758. // Tracking of line information
  1759. m_firstCharacterOfLine = m_firstVisibleCharacter;
  1760. m_lastCharacterOfLine = 0;
  1761. m_firstVisibleCharacterOfLine = 0;
  1762. m_lastVisibleCharacterOfLine = 0;
  1763. m_maxLineAscender = k_LargeNegativeFloat;
  1764. m_maxLineDescender = k_LargePositiveFloat;
  1765. m_lineNumber = 0;
  1766. m_startOfLineAscender = 0;
  1767. m_startOfLineDescender = 0;
  1768. m_lineVisibleCharacterCount = 0;
  1769. m_lineVisibleSpaceCount = 0;
  1770. bool isStartOfNewLine = true;
  1771. m_IsDrivenLineSpacing = false;
  1772. m_firstOverflowCharacterIndex = -1;
  1773. m_LastBaseGlyphIndex = int.MinValue;
  1774. bool kerning = m_ActiveFontFeatures.Contains(OTL_FeatureTag.kern);
  1775. bool markToBase = m_ActiveFontFeatures.Contains(OTL_FeatureTag.mark);
  1776. bool markToMark = m_ActiveFontFeatures.Contains(OTL_FeatureTag.mkmk);
  1777. m_pageNumber = 0;
  1778. int pageToDisplay = Mathf.Clamp(m_pageToDisplay - 1, 0, m_textInfo.pageInfo.Length - 1);
  1779. m_textInfo.ClearPageInfo();
  1780. Vector4 margins = m_margin;
  1781. float marginWidth = m_marginWidth > 0 ? m_marginWidth : 0;
  1782. float marginHeight = m_marginHeight > 0 ? m_marginHeight : 0;
  1783. m_marginLeft = 0;
  1784. m_marginRight = 0;
  1785. m_width = -1;
  1786. float widthOfTextArea = marginWidth + 0.0001f - m_marginLeft - m_marginRight;
  1787. // Need to initialize these Extents structures
  1788. m_meshExtents.min = k_LargePositiveVector2;
  1789. m_meshExtents.max = k_LargeNegativeVector2;
  1790. // Initialize lineInfo
  1791. m_textInfo.ClearLineInfo();
  1792. // Tracking of the highest Ascender
  1793. m_maxCapHeight = 0;
  1794. m_maxTextAscender = 0;
  1795. m_ElementDescender = 0;
  1796. m_PageAscender = 0;
  1797. float maxVisibleDescender = 0;
  1798. bool isMaxVisibleDescenderSet = false;
  1799. m_isNewPage = false;
  1800. // Initialize struct to track states of word wrapping
  1801. bool isFirstWordOfLine = true;
  1802. m_isNonBreakingSpace = false;
  1803. bool ignoreNonBreakingSpace = false;
  1804. int lastSoftLineBreak = 0;
  1805. CharacterSubstitution characterToSubstitute = new CharacterSubstitution(-1, 0);
  1806. bool isSoftHyphenIgnored = false;
  1807. // Save character and line state before we begin layout.
  1808. SaveWordWrappingState(ref m_SavedWordWrapState, -1, -1);
  1809. SaveWordWrappingState(ref m_SavedLineState, -1, -1);
  1810. SaveWordWrappingState(ref m_SavedEllipsisState, -1, -1);
  1811. SaveWordWrappingState(ref m_SavedLastValidState, -1, -1);
  1812. SaveWordWrappingState(ref m_SavedSoftLineBreakState, -1, -1);
  1813. m_EllipsisInsertionCandidateStack.Clear();
  1814. // Safety Tracker
  1815. int restoreCount = 0;
  1816. k_GenerateTextPhaseIMarker.Begin();
  1817. // Parse through Character buffer to read HTML tags and begin creating mesh.
  1818. for (int i = 0; i < m_TextProcessingArray.Length && m_TextProcessingArray[i].unicode != 0; i++)
  1819. {
  1820. charCode = m_TextProcessingArray[i].unicode;
  1821. if (restoreCount > 5)
  1822. {
  1823. Debug.LogError("Line breaking recursion max threshold hit... Character [" + charCode + "] index: " + i);
  1824. characterToSubstitute.index = m_characterCount;
  1825. characterToSubstitute.unicode = 0x03;
  1826. }
  1827. // Skip characters that have been substituted.
  1828. if (charCode == 0x1A)
  1829. continue;
  1830. // Parse Rich Text Tag
  1831. #region Parse Rich Text Tag
  1832. if (m_isRichText && charCode == '<')
  1833. {
  1834. k_ParseMarkupTextMarker.Begin();
  1835. m_isTextLayoutPhase = true;
  1836. m_textElementType = TMP_TextElementType.Character;
  1837. int endTagIndex;
  1838. // Check if Tag is valid. If valid, skip to the end of the validated tag.
  1839. if (ValidateHtmlTag(m_TextProcessingArray, i + 1, out endTagIndex))
  1840. {
  1841. i = endTagIndex;
  1842. // Continue to next character or handle the sprite element
  1843. if (m_textElementType == TMP_TextElementType.Character)
  1844. {
  1845. k_ParseMarkupTextMarker.End();
  1846. continue;
  1847. }
  1848. }
  1849. k_ParseMarkupTextMarker.End();
  1850. }
  1851. else
  1852. {
  1853. m_textElementType = m_textInfo.characterInfo[m_characterCount].elementType;
  1854. m_currentMaterialIndex = m_textInfo.characterInfo[m_characterCount].materialReferenceIndex;
  1855. m_currentFontAsset = m_textInfo.characterInfo[m_characterCount].fontAsset;
  1856. }
  1857. #endregion End Parse Rich Text Tag
  1858. int previousMaterialIndex = m_currentMaterialIndex;
  1859. bool isUsingAltTypeface = m_textInfo.characterInfo[m_characterCount].isUsingAlternateTypeface;
  1860. m_isTextLayoutPhase = false;
  1861. // Handle potential character substitutions
  1862. #region Character Substitutions
  1863. bool isInjectedCharacter = false;
  1864. if (characterToSubstitute.index == m_characterCount)
  1865. {
  1866. charCode = characterToSubstitute.unicode;
  1867. m_textElementType = TMP_TextElementType.Character;
  1868. isInjectedCharacter = true;
  1869. switch (charCode)
  1870. {
  1871. case 0x03:
  1872. m_textInfo.characterInfo[m_characterCount].textElement = m_currentFontAsset.characterLookupTable[0x03];
  1873. m_isTextTruncated = true;
  1874. break;
  1875. case 0x2D:
  1876. //
  1877. break;
  1878. case 0x2026:
  1879. m_textInfo.characterInfo[m_characterCount].textElement = m_Ellipsis.character;
  1880. m_textInfo.characterInfo[m_characterCount].elementType = TMP_TextElementType.Character;
  1881. m_textInfo.characterInfo[m_characterCount].fontAsset = m_Ellipsis.fontAsset;
  1882. m_textInfo.characterInfo[m_characterCount].material = m_Ellipsis.material;
  1883. m_textInfo.characterInfo[m_characterCount].materialReferenceIndex = m_Ellipsis.materialIndex;
  1884. // Need to increase reference count in the event the primary mesh has no characters.
  1885. m_materialReferences[m_Underline.materialIndex].referenceCount += 1;
  1886. // Indicates the source parsing data has been modified.
  1887. m_isTextTruncated = true;
  1888. // End Of Text
  1889. characterToSubstitute.index = m_characterCount + 1;
  1890. characterToSubstitute.unicode = 0x03;
  1891. break;
  1892. }
  1893. }
  1894. #endregion
  1895. // When using Linked text, mark character as ignored and skip to next character.
  1896. #region Linked Text
  1897. if (m_characterCount < m_firstVisibleCharacter && charCode != 0x03)
  1898. {
  1899. m_textInfo.characterInfo[m_characterCount].isVisible = false;
  1900. m_textInfo.characterInfo[m_characterCount].character = (char)0x200B;
  1901. m_textInfo.characterInfo[m_characterCount].lineNumber = 0;
  1902. m_characterCount += 1;
  1903. continue;
  1904. }
  1905. #endregion
  1906. // Handle Font Styles like LowerCase, UpperCase and SmallCaps.
  1907. #region Handling of LowerCase, UpperCase and SmallCaps Font Styles
  1908. float smallCapsMultiplier = 1.0f;
  1909. if (m_textElementType == TMP_TextElementType.Character)
  1910. {
  1911. if ((m_FontStyleInternal & FontStyles.UpperCase) == FontStyles.UpperCase)
  1912. {
  1913. // If this character is lowercase, switch to uppercase.
  1914. if (char.IsLower((char)charCode))
  1915. charCode = char.ToUpper((char)charCode);
  1916. }
  1917. else if ((m_FontStyleInternal & FontStyles.LowerCase) == FontStyles.LowerCase)
  1918. {
  1919. // If this character is uppercase, switch to lowercase.
  1920. if (char.IsUpper((char)charCode))
  1921. charCode = char.ToLower((char)charCode);
  1922. }
  1923. else if ((m_FontStyleInternal & FontStyles.SmallCaps) == FontStyles.SmallCaps)
  1924. {
  1925. if (char.IsLower((char)charCode))
  1926. {
  1927. smallCapsMultiplier = 0.8f;
  1928. charCode = char.ToUpper((char)charCode);
  1929. }
  1930. }
  1931. }
  1932. #endregion
  1933. // Look up Character Data from Dictionary and cache it.
  1934. #region Look up Character Data
  1935. k_CharacterLookupMarker.Begin();
  1936. float baselineOffset = 0;
  1937. float elementAscentLine = 0;
  1938. float elementDescentLine = 0;
  1939. if (m_textElementType == TMP_TextElementType.Sprite)
  1940. {
  1941. // If a sprite is used as a fallback then get a reference to it and set the color to white.
  1942. TMP_SpriteCharacter sprite = (TMP_SpriteCharacter)textInfo.characterInfo[m_characterCount].textElement;
  1943. m_currentSpriteAsset = sprite.textAsset as TMP_SpriteAsset;
  1944. m_spriteIndex = (int)sprite.glyphIndex;
  1945. if (sprite == null)
  1946. {
  1947. k_CharacterLookupMarker.End();
  1948. continue;
  1949. }
  1950. // Sprites are assigned in the E000 Private Area + sprite Index
  1951. if (charCode == '<')
  1952. charCode = 57344 + (uint)m_spriteIndex;
  1953. else
  1954. m_spriteColor = s_colorWhite;
  1955. float fontScale = (m_currentFontSize / m_currentFontAsset.faceInfo.pointSize * m_currentFontAsset.faceInfo.scale * (m_isOrthographic ? 1 : 0.1f));
  1956. // The sprite scale calculations are based on the font asset assigned to the text object.
  1957. if (m_currentSpriteAsset.m_FaceInfo.pointSize > 0)
  1958. {
  1959. float spriteScale = m_currentFontSize / m_currentSpriteAsset.m_FaceInfo.pointSize * m_currentSpriteAsset.m_FaceInfo.scale * (m_isOrthographic ? 1 : 0.1f);
  1960. currentElementScale = sprite.m_Scale * sprite.m_Glyph.scale * spriteScale;
  1961. elementAscentLine = m_currentSpriteAsset.m_FaceInfo.ascentLine;
  1962. baselineOffset = m_currentSpriteAsset.m_FaceInfo.baseline * fontScale * m_fontScaleMultiplier * m_currentSpriteAsset.m_FaceInfo.scale;
  1963. elementDescentLine = m_currentSpriteAsset.m_FaceInfo.descentLine;
  1964. }
  1965. else
  1966. {
  1967. float spriteScale = m_currentFontSize / m_currentFontAsset.m_FaceInfo.pointSize * m_currentFontAsset.m_FaceInfo.scale * (m_isOrthographic ? 1 : 0.1f);
  1968. currentElementScale = m_currentFontAsset.m_FaceInfo.ascentLine / sprite.m_Glyph.metrics.height * sprite.m_Scale * sprite.m_Glyph.scale * spriteScale;
  1969. float scaleDelta = spriteScale / currentElementScale;
  1970. elementAscentLine = m_currentFontAsset.m_FaceInfo.ascentLine * scaleDelta;
  1971. baselineOffset = m_currentFontAsset.m_FaceInfo.baseline * fontScale * m_fontScaleMultiplier * m_currentFontAsset.m_FaceInfo.scale;
  1972. elementDescentLine = m_currentFontAsset.m_FaceInfo.descentLine * scaleDelta;
  1973. }
  1974. m_cached_TextElement = sprite;
  1975. m_textInfo.characterInfo[m_characterCount].elementType = TMP_TextElementType.Sprite;
  1976. m_textInfo.characterInfo[m_characterCount].scale = currentElementScale;
  1977. m_textInfo.characterInfo[m_characterCount].fontAsset = m_currentFontAsset;
  1978. m_textInfo.characterInfo[m_characterCount].materialReferenceIndex = m_currentMaterialIndex;
  1979. m_currentMaterialIndex = previousMaterialIndex;
  1980. padding = 0;
  1981. }
  1982. else if (m_textElementType == TMP_TextElementType.Character)
  1983. {
  1984. m_cached_TextElement = m_textInfo.characterInfo[m_characterCount].textElement;
  1985. if (m_cached_TextElement == null)
  1986. {
  1987. k_CharacterLookupMarker.End();
  1988. continue;
  1989. }
  1990. m_currentFontAsset = m_textInfo.characterInfo[m_characterCount].fontAsset;
  1991. m_currentMaterial = m_textInfo.characterInfo[m_characterCount].material;
  1992. m_currentMaterialIndex = m_textInfo.characterInfo[m_characterCount].materialReferenceIndex;
  1993. // Special handling if replaced character was a line feed where in this case we have to use the scale of the previous character.
  1994. float adjustedScale;
  1995. if (isInjectedCharacter && m_TextProcessingArray[i].unicode == 0x0A && m_characterCount != m_firstCharacterOfLine)
  1996. adjustedScale = m_textInfo.characterInfo[m_characterCount - 1].pointSize * smallCapsMultiplier / m_currentFontAsset.m_FaceInfo.pointSize * m_currentFontAsset.m_FaceInfo.scale * (m_isOrthographic ? 1 : 0.1f);
  1997. else
  1998. adjustedScale = m_currentFontSize * smallCapsMultiplier / m_currentFontAsset.m_FaceInfo.pointSize * m_currentFontAsset.m_FaceInfo.scale * (m_isOrthographic ? 1 : 0.1f);
  1999. // Special handling for injected Ellipsis
  2000. if (isInjectedCharacter && charCode == 0x2026)
  2001. {
  2002. elementAscentLine = 0;
  2003. elementDescentLine = 0;
  2004. }
  2005. else
  2006. {
  2007. elementAscentLine = m_currentFontAsset.m_FaceInfo.ascentLine;
  2008. elementDescentLine = m_currentFontAsset.m_FaceInfo.descentLine;
  2009. }
  2010. currentElementScale = adjustedScale * m_fontScaleMultiplier * m_cached_TextElement.m_Scale * m_cached_TextElement.m_Glyph.scale;
  2011. baselineOffset = m_currentFontAsset.m_FaceInfo.baseline * adjustedScale * m_fontScaleMultiplier * m_currentFontAsset.m_FaceInfo.scale;
  2012. m_textInfo.characterInfo[m_characterCount].elementType = TMP_TextElementType.Character;
  2013. m_textInfo.characterInfo[m_characterCount].scale = currentElementScale;
  2014. padding = m_currentMaterialIndex == 0 ? m_padding : m_subTextObjects[m_currentMaterialIndex].padding;
  2015. }
  2016. k_CharacterLookupMarker.End();
  2017. #endregion
  2018. // Handle Soft Hyphen
  2019. #region Handle Soft Hyphen
  2020. float currentElementUnmodifiedScale = currentElementScale;
  2021. if (charCode == 0xAD || charCode == 0x03)
  2022. currentElementScale = 0;
  2023. #endregion
  2024. // Store some of the text object's information
  2025. m_textInfo.characterInfo[m_characterCount].character = (char)charCode;
  2026. m_textInfo.characterInfo[m_characterCount].pointSize = m_currentFontSize;
  2027. m_textInfo.characterInfo[m_characterCount].color = m_htmlColor;
  2028. m_textInfo.characterInfo[m_characterCount].underlineColor = m_underlineColor;
  2029. m_textInfo.characterInfo[m_characterCount].strikethroughColor = m_strikethroughColor;
  2030. m_textInfo.characterInfo[m_characterCount].highlightState = m_HighlightState;
  2031. m_textInfo.characterInfo[m_characterCount].style = m_FontStyleInternal;
  2032. // Cache glyph metrics
  2033. Glyph altGlyph = m_textInfo.characterInfo[m_characterCount].alternativeGlyph;
  2034. GlyphMetrics currentGlyphMetrics = altGlyph == null ? m_cached_TextElement.m_Glyph.metrics : altGlyph.metrics;
  2035. // Optimization to avoid calling this more than once per character.
  2036. bool isWhiteSpace = charCode <= 0xFFFF && char.IsWhiteSpace((char)charCode);
  2037. // Handle Kerning if Enabled.
  2038. #region Handle Kerning
  2039. GlyphValueRecord glyphAdjustments = new GlyphValueRecord();
  2040. float characterSpacingAdjustment = m_characterSpacing;
  2041. if (kerning && m_textElementType == TMP_TextElementType.Character)
  2042. {
  2043. k_HandleGPOSFeaturesMarker.Begin();
  2044. GlyphPairAdjustmentRecord adjustmentPair;
  2045. uint baseGlyphIndex = m_cached_TextElement.m_GlyphIndex;
  2046. if (m_characterCount < totalCharacterCount - 1 && m_textInfo.characterInfo[m_characterCount + 1].elementType == TMP_TextElementType.Character)
  2047. {
  2048. uint nextGlyphIndex = m_textInfo.characterInfo[m_characterCount + 1].textElement.m_GlyphIndex;
  2049. uint key = nextGlyphIndex << 16 | baseGlyphIndex;
  2050. if (m_currentFontAsset.m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookup.TryGetValue(key, out adjustmentPair))
  2051. {
  2052. glyphAdjustments = adjustmentPair.firstAdjustmentRecord.glyphValueRecord;
  2053. characterSpacingAdjustment = (adjustmentPair.featureLookupFlags & UnityEngine.TextCore.LowLevel.FontFeatureLookupFlags.IgnoreSpacingAdjustments) == UnityEngine.TextCore.LowLevel.FontFeatureLookupFlags.IgnoreSpacingAdjustments ? 0 : characterSpacingAdjustment;
  2054. }
  2055. }
  2056. if (m_characterCount >= 1)
  2057. {
  2058. uint previousGlyphIndex = m_textInfo.characterInfo[m_characterCount - 1].textElement.m_GlyphIndex;
  2059. uint key = baseGlyphIndex << 16 | previousGlyphIndex;
  2060. if (textInfo.characterInfo[m_characterCount - 1].elementType == TMP_TextElementType.Character && m_currentFontAsset.m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookup.TryGetValue(key, out adjustmentPair))
  2061. {
  2062. glyphAdjustments += adjustmentPair.secondAdjustmentRecord.glyphValueRecord;
  2063. characterSpacingAdjustment = (adjustmentPair.featureLookupFlags & UnityEngine.TextCore.LowLevel.FontFeatureLookupFlags.IgnoreSpacingAdjustments) == UnityEngine.TextCore.LowLevel.FontFeatureLookupFlags.IgnoreSpacingAdjustments ? 0 : characterSpacingAdjustment;
  2064. }
  2065. }
  2066. k_HandleGPOSFeaturesMarker.End();
  2067. }
  2068. m_textInfo.characterInfo[m_characterCount].adjustedHorizontalAdvance = glyphAdjustments.xAdvance;
  2069. #endregion
  2070. // Handle Diacritical Marks
  2071. #region Handle Diacritical Marks
  2072. bool isBaseGlyph = TMP_TextParsingUtilities.IsBaseGlyph(charCode);
  2073. if (isBaseGlyph)
  2074. m_LastBaseGlyphIndex = m_characterCount;
  2075. if (m_characterCount > 0 && !isBaseGlyph)
  2076. {
  2077. // Check for potential Mark-to-Base lookup if previous glyph was a base glyph
  2078. if (markToBase && m_LastBaseGlyphIndex != int.MinValue && m_LastBaseGlyphIndex == m_characterCount - 1)
  2079. {
  2080. Glyph baseGlyph = m_textInfo.characterInfo[m_LastBaseGlyphIndex].textElement.glyph;
  2081. uint baseGlyphIndex = baseGlyph.index;
  2082. uint markGlyphIndex = m_cached_TextElement.glyphIndex;
  2083. uint key = markGlyphIndex << 16 | baseGlyphIndex;
  2084. if (m_currentFontAsset.fontFeatureTable.m_MarkToBaseAdjustmentRecordLookup.TryGetValue(key, out MarkToBaseAdjustmentRecord glyphAdjustmentRecord))
  2085. {
  2086. float advanceOffset = (m_textInfo.characterInfo[m_LastBaseGlyphIndex].origin - m_xAdvance) / currentElementScale;
  2087. glyphAdjustments.xPlacement = advanceOffset + glyphAdjustmentRecord.baseGlyphAnchorPoint.xCoordinate - glyphAdjustmentRecord.markPositionAdjustment.xPositionAdjustment;
  2088. glyphAdjustments.yPlacement = glyphAdjustmentRecord.baseGlyphAnchorPoint.yCoordinate - glyphAdjustmentRecord.markPositionAdjustment.yPositionAdjustment;
  2089. characterSpacingAdjustment = 0;
  2090. }
  2091. }
  2092. else
  2093. {
  2094. // Iterate from previous glyph to last base glyph checking for any potential Mark-to-Mark lookups to apply. Otherwise check for potential Mark-to-Base lookup between the current glyph and last base glyph
  2095. bool wasLookupApplied = false;
  2096. // Check for any potential Mark-to-Mark lookups
  2097. if (markToMark)
  2098. {
  2099. for (int characterLookupIndex = m_characterCount - 1; characterLookupIndex >= 0 && characterLookupIndex != m_LastBaseGlyphIndex; characterLookupIndex--)
  2100. {
  2101. // Handle any potential Mark-to-Mark lookup
  2102. Glyph baseMarkGlyph = m_textInfo.characterInfo[characterLookupIndex].textElement.glyph;
  2103. uint baseGlyphIndex = baseMarkGlyph.index;
  2104. uint combiningMarkGlyphIndex = m_cached_TextElement.glyphIndex;
  2105. uint key = combiningMarkGlyphIndex << 16 | baseGlyphIndex;
  2106. if (m_currentFontAsset.fontFeatureTable.m_MarkToMarkAdjustmentRecordLookup.TryGetValue(key, out MarkToMarkAdjustmentRecord glyphAdjustmentRecord))
  2107. {
  2108. float baseMarkOrigin = (m_textInfo.characterInfo[characterLookupIndex].origin - m_xAdvance) / currentElementScale;
  2109. float currentBaseline = baselineOffset - m_lineOffset + m_baselineOffset;
  2110. float baseMarkBaseline = (m_textInfo.characterInfo[characterLookupIndex].baseLine - currentBaseline) / currentElementScale;
  2111. glyphAdjustments.xPlacement = baseMarkOrigin + glyphAdjustmentRecord.baseMarkGlyphAnchorPoint.xCoordinate - glyphAdjustmentRecord.combiningMarkPositionAdjustment.xPositionAdjustment;
  2112. glyphAdjustments.yPlacement = baseMarkBaseline + glyphAdjustmentRecord.baseMarkGlyphAnchorPoint.yCoordinate - glyphAdjustmentRecord.combiningMarkPositionAdjustment.yPositionAdjustment;
  2113. characterSpacingAdjustment = 0;
  2114. wasLookupApplied = true;
  2115. break;
  2116. }
  2117. }
  2118. }
  2119. // If no Mark-to-Mark lookups were applied, check for potential Mark-to-Base lookup.
  2120. if (markToBase && m_LastBaseGlyphIndex != int.MinValue && !wasLookupApplied)
  2121. {
  2122. // Handle lookup for Mark-to-Base
  2123. Glyph baseGlyph = m_textInfo.characterInfo[m_LastBaseGlyphIndex].textElement.glyph;
  2124. uint baseGlyphIndex = baseGlyph.index;
  2125. uint markGlyphIndex = m_cached_TextElement.glyphIndex;
  2126. uint key = markGlyphIndex << 16 | baseGlyphIndex;
  2127. if (m_currentFontAsset.fontFeatureTable.m_MarkToBaseAdjustmentRecordLookup.TryGetValue(key, out MarkToBaseAdjustmentRecord glyphAdjustmentRecord))
  2128. {
  2129. float advanceOffset = (m_textInfo.characterInfo[m_LastBaseGlyphIndex].origin - m_xAdvance) / currentElementScale;
  2130. glyphAdjustments.xPlacement = advanceOffset + glyphAdjustmentRecord.baseGlyphAnchorPoint.xCoordinate - glyphAdjustmentRecord.markPositionAdjustment.xPositionAdjustment;
  2131. glyphAdjustments.yPlacement = glyphAdjustmentRecord.baseGlyphAnchorPoint.yCoordinate - glyphAdjustmentRecord.markPositionAdjustment.yPositionAdjustment;
  2132. characterSpacingAdjustment = 0;
  2133. }
  2134. }
  2135. }
  2136. }
  2137. // Adjust relevant text metrics
  2138. elementAscentLine += glyphAdjustments.yPlacement;
  2139. elementDescentLine += glyphAdjustments.yPlacement;
  2140. #endregion
  2141. // Initial Implementation for RTL support.
  2142. #region Handle Right-to-Left
  2143. if (m_isRightToLeft)
  2144. {
  2145. m_xAdvance -= currentGlyphMetrics.horizontalAdvance * (1 - m_charWidthAdjDelta) * currentElementScale;
  2146. if (isWhiteSpace || charCode == 0x200B)
  2147. m_xAdvance -= m_wordSpacing * currentEmScale;
  2148. }
  2149. #endregion
  2150. // Handle Mono Spacing
  2151. #region Handle Mono Spacing
  2152. float monoAdvance = 0;
  2153. if (m_monoSpacing != 0)
  2154. {
  2155. if (m_duoSpace && (charCode == '.' || charCode == ':' || charCode == ','))
  2156. monoAdvance = (m_monoSpacing / 4 - (currentGlyphMetrics.width / 2 + currentGlyphMetrics.horizontalBearingX) * currentElementScale) * (1 - m_charWidthAdjDelta);
  2157. else
  2158. monoAdvance = (m_monoSpacing / 2 - (currentGlyphMetrics.width / 2 + currentGlyphMetrics.horizontalBearingX) * currentElementScale) * (1 - m_charWidthAdjDelta);
  2159. m_xAdvance += monoAdvance;
  2160. }
  2161. #endregion
  2162. // Set Padding based on selected font style
  2163. #region Handle Style Padding
  2164. float boldSpacingAdjustment;
  2165. float style_padding;
  2166. if (m_textElementType == TMP_TextElementType.Character && !isUsingAltTypeface && ((m_FontStyleInternal & FontStyles.Bold) == FontStyles.Bold)) // Checks for any combination of Bold Style.
  2167. {
  2168. if (m_currentMaterial != null && m_currentMaterial.HasProperty(ShaderUtilities.ID_GradientScale))
  2169. {
  2170. float gradientScale = m_currentMaterial.GetFloat(ShaderUtilities.ID_GradientScale);
  2171. style_padding = m_currentFontAsset.boldStyle / 4.0f * gradientScale * m_currentMaterial.GetFloat(ShaderUtilities.ID_ScaleRatio_A);
  2172. // Clamp overall padding to Gradient Scale size.
  2173. if (style_padding + padding > gradientScale)
  2174. padding = gradientScale - style_padding;
  2175. }
  2176. else
  2177. style_padding = 0;
  2178. boldSpacingAdjustment = m_currentFontAsset.boldSpacing;
  2179. }
  2180. else
  2181. {
  2182. if (m_currentMaterial != null && m_currentMaterial.HasProperty(ShaderUtilities.ID_GradientScale) && m_currentMaterial.HasProperty(ShaderUtilities.ID_ScaleRatio_A))
  2183. {
  2184. float gradientScale = m_currentMaterial.GetFloat(ShaderUtilities.ID_GradientScale);
  2185. style_padding = m_currentFontAsset.normalStyle / 4.0f * gradientScale * m_currentMaterial.GetFloat(ShaderUtilities.ID_ScaleRatio_A);
  2186. // Clamp overall padding to Gradient Scale size.
  2187. if (style_padding + padding > gradientScale)
  2188. padding = gradientScale - style_padding;
  2189. }
  2190. else
  2191. style_padding = 0;
  2192. boldSpacingAdjustment = 0;
  2193. }
  2194. #endregion Handle Style Padding
  2195. // Determine the position of the vertices of the Character or Sprite.
  2196. #region Calculate Vertices Position
  2197. k_CalculateVerticesPositionMarker.Begin();
  2198. Vector3 top_left;
  2199. top_left.x = m_xAdvance + ((currentGlyphMetrics.horizontalBearingX * m_FXScale.x - padding - style_padding + glyphAdjustments.xPlacement) * currentElementScale * (1 - m_charWidthAdjDelta));
  2200. top_left.y = baselineOffset + (currentGlyphMetrics.horizontalBearingY + padding + glyphAdjustments.yPlacement) * currentElementScale - m_lineOffset + m_baselineOffset;
  2201. top_left.z = 0;
  2202. Vector3 bottom_left;
  2203. bottom_left.x = top_left.x;
  2204. bottom_left.y = top_left.y - ((currentGlyphMetrics.height + padding * 2) * currentElementScale);
  2205. bottom_left.z = 0;
  2206. Vector3 top_right;
  2207. top_right.x = bottom_left.x + ((currentGlyphMetrics.width * m_FXScale.x + padding * 2 + style_padding * 2) * currentElementScale * (1 - m_charWidthAdjDelta));
  2208. top_right.y = top_left.y;
  2209. top_right.z = 0;
  2210. Vector3 bottom_right;
  2211. bottom_right.x = top_right.x;
  2212. bottom_right.y = bottom_left.y;
  2213. bottom_right.z = 0;
  2214. k_CalculateVerticesPositionMarker.End();
  2215. #endregion
  2216. // Check if we need to Shear the rectangles for Italic styles
  2217. #region Handle Italic & Shearing
  2218. if (m_textElementType == TMP_TextElementType.Character && !isUsingAltTypeface && ((m_FontStyleInternal & FontStyles.Italic) == FontStyles.Italic))
  2219. {
  2220. // Shift Top vertices forward by half (Shear Value * height of character) and Bottom vertices back by same amount.
  2221. float shear_value = m_ItalicAngle * 0.01f;
  2222. float midPoint = ((m_currentFontAsset.m_FaceInfo.capLine - (m_currentFontAsset.m_FaceInfo.baseline + m_baselineOffset)) / 2) * m_fontScaleMultiplier * m_currentFontAsset.m_FaceInfo.scale;
  2223. Vector3 topShear = new Vector3(shear_value * ((currentGlyphMetrics.horizontalBearingY + padding + style_padding - midPoint) * currentElementScale), 0, 0);
  2224. Vector3 bottomShear = new Vector3(shear_value * (((currentGlyphMetrics.horizontalBearingY - currentGlyphMetrics.height - padding - style_padding - midPoint)) * currentElementScale), 0, 0);
  2225. top_left += topShear;
  2226. bottom_left += bottomShear;
  2227. top_right += topShear;
  2228. bottom_right += bottomShear;
  2229. }
  2230. #endregion Handle Italics & Shearing
  2231. // Handle Character FX Rotation
  2232. #region Handle Character FX Rotation
  2233. if (m_FXRotation != Quaternion.identity)
  2234. {
  2235. Matrix4x4 rotationMatrix = Matrix4x4.Rotate(m_FXRotation);
  2236. Vector3 positionOffset = (top_right + bottom_left) / 2;
  2237. top_left = rotationMatrix.MultiplyPoint3x4(top_left - positionOffset) + positionOffset;
  2238. bottom_left = rotationMatrix.MultiplyPoint3x4(bottom_left - positionOffset) + positionOffset;
  2239. top_right = rotationMatrix.MultiplyPoint3x4(top_right - positionOffset) + positionOffset;
  2240. bottom_right = rotationMatrix.MultiplyPoint3x4(bottom_right - positionOffset) + positionOffset;
  2241. }
  2242. #endregion
  2243. // Store vertex information for the character or sprite.
  2244. m_textInfo.characterInfo[m_characterCount].bottomLeft = bottom_left;
  2245. m_textInfo.characterInfo[m_characterCount].topLeft = top_left;
  2246. m_textInfo.characterInfo[m_characterCount].topRight = top_right;
  2247. m_textInfo.characterInfo[m_characterCount].bottomRight = bottom_right;
  2248. m_textInfo.characterInfo[m_characterCount].origin = m_xAdvance + glyphAdjustments.xPlacement * currentElementScale;
  2249. m_textInfo.characterInfo[m_characterCount].baseLine = (baselineOffset - m_lineOffset + m_baselineOffset) + glyphAdjustments.yPlacement * currentElementScale;
  2250. m_textInfo.characterInfo[m_characterCount].aspectRatio = (top_right.x - bottom_left.x) / (top_left.y - bottom_left.y);
  2251. // Compute text metrics
  2252. #region Compute Ascender & Descender values
  2253. k_ComputeTextMetricsMarker.Begin();
  2254. // Element Ascender in line space
  2255. float elementAscender = m_textElementType == TMP_TextElementType.Character
  2256. ? elementAscentLine * currentElementScale / smallCapsMultiplier + m_baselineOffset
  2257. : elementAscentLine * currentElementScale + m_baselineOffset;
  2258. // Element Descender in line space
  2259. float elementDescender = m_textElementType == TMP_TextElementType.Character
  2260. ? elementDescentLine * currentElementScale / smallCapsMultiplier + m_baselineOffset
  2261. : elementDescentLine * currentElementScale + m_baselineOffset;
  2262. float adjustedAscender = elementAscender;
  2263. float adjustedDescender = elementDescender;
  2264. // Max line ascender and descender in line space
  2265. bool isFirstCharacterOfLine = m_characterCount == m_firstCharacterOfLine;
  2266. if (isFirstCharacterOfLine || isWhiteSpace == false)
  2267. {
  2268. // Special handling for Superscript and Subscript where we use the unadjusted line ascender and descender
  2269. if (m_baselineOffset != 0)
  2270. {
  2271. adjustedAscender = Mathf.Max((elementAscender - m_baselineOffset) / m_fontScaleMultiplier, adjustedAscender);
  2272. adjustedDescender = Mathf.Min((elementDescender - m_baselineOffset) / m_fontScaleMultiplier, adjustedDescender);
  2273. }
  2274. m_maxLineAscender = Mathf.Max(adjustedAscender, m_maxLineAscender);
  2275. m_maxLineDescender = Mathf.Min(adjustedDescender, m_maxLineDescender);
  2276. }
  2277. // Element Ascender and Descender in object space
  2278. if (isFirstCharacterOfLine || isWhiteSpace == false)
  2279. {
  2280. m_textInfo.characterInfo[m_characterCount].adjustedAscender = adjustedAscender;
  2281. m_textInfo.characterInfo[m_characterCount].adjustedDescender = adjustedDescender;
  2282. m_ElementAscender = m_textInfo.characterInfo[m_characterCount].ascender = elementAscender - m_lineOffset;
  2283. m_ElementDescender = m_textInfo.characterInfo[m_characterCount].descender = elementDescender - m_lineOffset;
  2284. }
  2285. else
  2286. {
  2287. m_textInfo.characterInfo[m_characterCount].adjustedAscender = m_maxLineAscender;
  2288. m_textInfo.characterInfo[m_characterCount].adjustedDescender = m_maxLineDescender;
  2289. m_ElementAscender = m_textInfo.characterInfo[m_characterCount].ascender = m_maxLineAscender - m_lineOffset;
  2290. m_ElementDescender = m_textInfo.characterInfo[m_characterCount].descender = m_maxLineDescender - m_lineOffset;
  2291. }
  2292. // Max text object ascender and cap height
  2293. if (m_lineNumber == 0 || m_isNewPage)
  2294. {
  2295. if (isFirstCharacterOfLine || isWhiteSpace == false)
  2296. {
  2297. m_maxTextAscender = m_maxLineAscender;
  2298. m_maxCapHeight = Mathf.Max(m_maxCapHeight, m_currentFontAsset.m_FaceInfo.capLine * currentElementScale / smallCapsMultiplier);
  2299. }
  2300. }
  2301. // Page ascender
  2302. if (m_lineOffset == 0)
  2303. {
  2304. if (isFirstCharacterOfLine || isWhiteSpace == false)
  2305. m_PageAscender = m_PageAscender > elementAscender ? m_PageAscender : elementAscender;
  2306. }
  2307. k_ComputeTextMetricsMarker.End();
  2308. #endregion
  2309. // Set Characters to not visible by default.
  2310. m_textInfo.characterInfo[m_characterCount].isVisible = false;
  2311. bool isJustifiedOrFlush = (m_lineJustification & HorizontalAlignmentOptions.Flush) == HorizontalAlignmentOptions.Flush || (m_lineJustification & HorizontalAlignmentOptions.Justified) == HorizontalAlignmentOptions.Justified;
  2312. // Setup Mesh for visible text elements. ie. not a SPACE / LINEFEED / CARRIAGE RETURN.
  2313. #region Handle Visible Characters
  2314. if (charCode == 9 || ((m_TextWrappingMode == TextWrappingModes.PreserveWhitespace || m_TextWrappingMode == TextWrappingModes.PreserveWhitespaceNoWrap) && (isWhiteSpace || charCode == 0x200B)) || (isWhiteSpace == false && charCode != 0x200B && charCode != 0xAD && charCode != 0x03) || (charCode == 0xAD && isSoftHyphenIgnored == false) || m_textElementType == TMP_TextElementType.Sprite)
  2315. {
  2316. k_HandleVisibleCharacterMarker.Begin();
  2317. m_textInfo.characterInfo[m_characterCount].isVisible = true;
  2318. #region Experimental Margin Shaper
  2319. //Vector2 shapedMargins;
  2320. //if (marginShaper)
  2321. //{
  2322. // shapedMargins = m_marginShaper.GetShapedMargins(m_textInfo.characterInfo[m_characterCount].baseLine);
  2323. // if (shapedMargins.x < margins.x)
  2324. // {
  2325. // shapedMargins.x = m_marginLeft;
  2326. // }
  2327. // else
  2328. // {
  2329. // shapedMargins.x += m_marginLeft - margins.x;
  2330. // }
  2331. // if (shapedMargins.y < margins.z)
  2332. // {
  2333. // shapedMargins.y = m_marginRight;
  2334. // }
  2335. // else
  2336. // {
  2337. // shapedMargins.y += m_marginRight - margins.z;
  2338. // }
  2339. //}
  2340. //else
  2341. //{
  2342. // shapedMargins.x = m_marginLeft;
  2343. // shapedMargins.y = m_marginRight;
  2344. //}
  2345. //width = marginWidth + 0.0001f - shapedMargins.x - shapedMargins.y;
  2346. //if (m_width != -1 && m_width < width)
  2347. //{
  2348. // width = m_width;
  2349. //}
  2350. //m_textInfo.lineInfo[m_lineNumber].marginLeft = shapedMargins.x;
  2351. #endregion
  2352. float marginLeft = m_marginLeft;
  2353. float marginRight = m_marginRight;
  2354. // Injected characters do not override margins
  2355. if (isInjectedCharacter)
  2356. {
  2357. marginLeft = m_textInfo.lineInfo[m_lineNumber].marginLeft;
  2358. marginRight = m_textInfo.lineInfo[m_lineNumber].marginRight;
  2359. }
  2360. widthOfTextArea = m_width != -1 ? Mathf.Min(marginWidth + 0.0001f - marginLeft - marginRight, m_width) : marginWidth + 0.0001f - marginLeft - marginRight;
  2361. // Calculate the line breaking width of the text.
  2362. float textWidth = Mathf.Abs(m_xAdvance) + (!m_isRightToLeft ? currentGlyphMetrics.horizontalAdvance : 0) * (1 - m_charWidthAdjDelta) * (charCode == 0xAD ? currentElementUnmodifiedScale : currentElementScale);
  2363. float textHeight = m_maxTextAscender - (m_maxLineDescender - m_lineOffset) + (m_lineOffset > 0 && m_IsDrivenLineSpacing == false ? m_maxLineAscender - m_startOfLineAscender : 0);
  2364. int testedCharacterCount = m_characterCount;
  2365. // Handling of current line Vertical Bounds
  2366. #region Current Line Vertical Bounds Check
  2367. if (textHeight > marginHeight + 0.0001f)
  2368. {
  2369. k_HandleVerticalLineBreakingMarker.Begin();
  2370. // Set isTextOverflowing and firstOverflowCharacterIndex
  2371. if (m_firstOverflowCharacterIndex == -1)
  2372. m_firstOverflowCharacterIndex = m_characterCount;
  2373. // Check if Auto-Size is enabled
  2374. if (m_enableAutoSizing)
  2375. {
  2376. // Handle Line spacing adjustments
  2377. #region Line Spacing Adjustments
  2378. if (m_lineSpacingDelta > m_lineSpacingMax && m_lineOffset > 0 && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount)
  2379. {
  2380. float adjustmentDelta = (marginHeight - textHeight) / m_lineNumber;
  2381. m_lineSpacingDelta = Mathf.Max(m_lineSpacingDelta + adjustmentDelta / baseScale, m_lineSpacingMax);
  2382. //Debug.Log("[" + m_AutoSizeIterationCount + "] Reducing Line Spacing. Delta of [" + m_lineSpacingDelta.ToString("f3") + "].");
  2383. k_HandleVerticalLineBreakingMarker.End();
  2384. k_HandleVisibleCharacterMarker.End();
  2385. k_GenerateTextPhaseIMarker.End();
  2386. k_GenerateTextMarker.End();
  2387. return;
  2388. }
  2389. #endregion
  2390. // Handle Text Auto-sizing resulting from text exceeding vertical bounds.
  2391. #region Text Auto-Sizing (Text greater than vertical bounds)
  2392. if (m_fontSize > m_fontSizeMin && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount)
  2393. {
  2394. m_maxFontSize = m_fontSize;
  2395. float sizeDelta = Mathf.Max((m_fontSize - m_minFontSize) / 2, 0.05f);
  2396. m_fontSize -= sizeDelta;
  2397. m_fontSize = Mathf.Max((int)(m_fontSize * 20 + 0.5f) / 20f, m_fontSizeMin);
  2398. //Debug.Log("[" + m_AutoSizeIterationCount + "] Reducing Point Size from [" + m_maxFontSize.ToString("f3") + "] to [" + m_fontSize.ToString("f3") + "] with delta of [" + sizeDelta.ToString("f3") + "].");
  2399. k_HandleVerticalLineBreakingMarker.End();
  2400. k_HandleVisibleCharacterMarker.End();
  2401. k_GenerateTextPhaseIMarker.End();
  2402. k_GenerateTextMarker.End();
  2403. return;
  2404. }
  2405. #endregion Text Auto-Sizing
  2406. }
  2407. // Handle Vertical Overflow on current line
  2408. switch (m_overflowMode)
  2409. {
  2410. case TextOverflowModes.Overflow:
  2411. case TextOverflowModes.ScrollRect:
  2412. case TextOverflowModes.Masking:
  2413. // Nothing happens as vertical bounds are ignored in this mode.
  2414. break;
  2415. case TextOverflowModes.Truncate:
  2416. i = RestoreWordWrappingState(ref m_SavedLastValidState);
  2417. characterToSubstitute.index = testedCharacterCount;
  2418. characterToSubstitute.unicode = 0x03;
  2419. k_HandleVerticalLineBreakingMarker.End();
  2420. k_HandleVisibleCharacterMarker.End();
  2421. continue;
  2422. case TextOverflowModes.Ellipsis:
  2423. if (m_EllipsisInsertionCandidateStack.Count == 0)
  2424. {
  2425. i = -1;
  2426. m_characterCount = 0;
  2427. characterToSubstitute.index = 0;
  2428. characterToSubstitute.unicode = 0x03;
  2429. m_firstCharacterOfLine = 0;
  2430. k_HandleVerticalLineBreakingMarker.End();
  2431. k_HandleVisibleCharacterMarker.End();
  2432. continue;
  2433. }
  2434. var ellipsisState = m_EllipsisInsertionCandidateStack.Pop();
  2435. i = RestoreWordWrappingState(ref ellipsisState);
  2436. i -= 1;
  2437. m_characterCount -= 1;
  2438. characterToSubstitute.index = m_characterCount;
  2439. characterToSubstitute.unicode = 0x2026;
  2440. restoreCount += 1;
  2441. k_HandleVerticalLineBreakingMarker.End();
  2442. k_HandleVisibleCharacterMarker.End();
  2443. continue;
  2444. case TextOverflowModes.Linked:
  2445. i = RestoreWordWrappingState(ref m_SavedLastValidState);
  2446. if (m_linkedTextComponent != null)
  2447. {
  2448. m_linkedTextComponent.text = text;
  2449. m_linkedTextComponent.m_inputSource = m_inputSource;
  2450. m_linkedTextComponent.firstVisibleCharacter = m_characterCount;
  2451. m_linkedTextComponent.ForceMeshUpdate();
  2452. m_isTextTruncated = true;
  2453. }
  2454. // Truncate remaining text
  2455. characterToSubstitute.index = testedCharacterCount;
  2456. characterToSubstitute.unicode = 0x03;
  2457. k_HandleVerticalLineBreakingMarker.End();
  2458. k_HandleVisibleCharacterMarker.End();
  2459. continue;
  2460. case TextOverflowModes.Page:
  2461. // End layout of text if first character / page doesn't fit.
  2462. if (i < 0 || testedCharacterCount == 0)
  2463. {
  2464. i = -1;
  2465. m_characterCount = 0;
  2466. characterToSubstitute.index = 0;
  2467. characterToSubstitute.unicode = 0x03;
  2468. k_HandleVerticalLineBreakingMarker.End();
  2469. k_HandleVisibleCharacterMarker.End();
  2470. continue;
  2471. }
  2472. else if (m_maxLineAscender - m_maxLineDescender > marginHeight + 0.0001f)
  2473. {
  2474. // Current line exceeds the height of the text container
  2475. // as such we stop on the previous line.
  2476. i = RestoreWordWrappingState(ref m_SavedLineState);
  2477. characterToSubstitute.index = testedCharacterCount;
  2478. characterToSubstitute.unicode = 0x03;
  2479. k_HandleVerticalLineBreakingMarker.End();
  2480. k_HandleVisibleCharacterMarker.End();
  2481. continue;
  2482. }
  2483. // Go back to previous line and re-layout
  2484. i = RestoreWordWrappingState(ref m_SavedLineState);
  2485. m_isNewPage = true;
  2486. m_firstCharacterOfLine = m_characterCount;
  2487. m_maxLineAscender = k_LargeNegativeFloat;
  2488. m_maxLineDescender = k_LargePositiveFloat;
  2489. m_startOfLineAscender = 0;
  2490. m_xAdvance = 0 + tag_Indent;
  2491. m_lineOffset = 0;
  2492. m_maxTextAscender = 0;
  2493. m_PageAscender = 0;
  2494. m_lineNumber += 1;
  2495. m_pageNumber += 1;
  2496. // Should consider saving page data here
  2497. k_HandleVerticalLineBreakingMarker.End();
  2498. k_HandleVisibleCharacterMarker.End();
  2499. continue;
  2500. }
  2501. k_HandleVerticalLineBreakingMarker.End();
  2502. }
  2503. #endregion
  2504. // Handling of Horizontal Bounds
  2505. #region Current Line Horizontal Bounds Check
  2506. if (isBaseGlyph && textWidth > widthOfTextArea * (isJustifiedOrFlush ? 1.05f : 1.0f))
  2507. {
  2508. k_HandleHorizontalLineBreakingMarker.Begin();
  2509. // Handle Line Breaking (if still possible)
  2510. if (m_TextWrappingMode != TextWrappingModes.NoWrap && m_TextWrappingMode != TextWrappingModes.PreserveWhitespaceNoWrap && m_characterCount != m_firstCharacterOfLine)
  2511. {
  2512. // Restore state to previous safe line breaking
  2513. i = RestoreWordWrappingState(ref m_SavedWordWrapState);
  2514. // Compute potential new line offset in the event a line break is needed.
  2515. float lineOffsetDelta = 0;
  2516. if (m_lineHeight == TMP_Math.FLOAT_UNSET)
  2517. {
  2518. float ascender = m_textInfo.characterInfo[m_characterCount].adjustedAscender;
  2519. lineOffsetDelta = (m_lineOffset > 0 && m_IsDrivenLineSpacing == false ? m_maxLineAscender - m_startOfLineAscender : 0) - m_maxLineDescender + ascender + (lineGap + m_lineSpacingDelta) * baseScale + m_lineSpacing * currentEmScale;
  2520. }
  2521. else
  2522. {
  2523. lineOffsetDelta = m_lineHeight + m_lineSpacing * currentEmScale;
  2524. m_IsDrivenLineSpacing = true;
  2525. }
  2526. // Calculate new text height
  2527. float newTextHeight = m_maxTextAscender + lineOffsetDelta + m_lineOffset - m_textInfo.characterInfo[m_characterCount].adjustedDescender;
  2528. // Replace Soft Hyphen by Hyphen Minus 0x2D
  2529. #region Handle Soft Hyphenation
  2530. if (m_textInfo.characterInfo[m_characterCount - 1].character == 0xAD && isSoftHyphenIgnored == false)
  2531. {
  2532. // Only inject Hyphen Minus if new line is possible
  2533. if (m_overflowMode == TextOverflowModes.Overflow || newTextHeight < marginHeight + 0.0001f)
  2534. {
  2535. characterToSubstitute.index = m_characterCount - 1;
  2536. characterToSubstitute.unicode = 0x2D;
  2537. i -= 1;
  2538. m_characterCount -= 1;
  2539. k_HandleHorizontalLineBreakingMarker.End();
  2540. k_HandleVisibleCharacterMarker.End();
  2541. continue;
  2542. }
  2543. }
  2544. isSoftHyphenIgnored = false;
  2545. // Ignore Soft Hyphen to prevent it from wrapping
  2546. if (m_textInfo.characterInfo[m_characterCount].character == 0xAD)
  2547. {
  2548. isSoftHyphenIgnored = true;
  2549. k_HandleHorizontalLineBreakingMarker.End();
  2550. k_HandleVisibleCharacterMarker.End();
  2551. continue;
  2552. }
  2553. #endregion
  2554. // Adjust character spacing before breaking up word if auto size is enabled
  2555. if (m_enableAutoSizing && isFirstWordOfLine)
  2556. {
  2557. // Handle Character Width Adjustments
  2558. #region Character Width Adjustments
  2559. if (m_charWidthAdjDelta < m_charWidthMaxAdj / 100 && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount)
  2560. {
  2561. float adjustedTextWidth = textWidth;
  2562. // Determine full width of the text
  2563. if (m_charWidthAdjDelta > 0)
  2564. adjustedTextWidth /= 1f - m_charWidthAdjDelta;
  2565. float adjustmentDelta = textWidth - (widthOfTextArea - 0.0001f) * (isJustifiedOrFlush ? 1.05f : 1.0f);
  2566. m_charWidthAdjDelta += adjustmentDelta / adjustedTextWidth;
  2567. m_charWidthAdjDelta = Mathf.Min(m_charWidthAdjDelta, m_charWidthMaxAdj / 100);
  2568. //Debug.Log("[" + m_AutoSizeIterationCount + "] Reducing Character Width by " + (m_charWidthAdjDelta * 100) + "%");
  2569. k_HandleHorizontalLineBreakingMarker.End();
  2570. k_HandleVisibleCharacterMarker.End();
  2571. k_GenerateTextPhaseIMarker.End();
  2572. k_GenerateTextMarker.End();
  2573. return;
  2574. }
  2575. #endregion
  2576. // Handle Text Auto-sizing resulting from text exceeding vertical bounds.
  2577. #region Text Auto-Sizing (Text greater than vertical bounds)
  2578. if (m_fontSize > m_fontSizeMin && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount)
  2579. {
  2580. m_maxFontSize = m_fontSize;
  2581. float sizeDelta = Mathf.Max((m_fontSize - m_minFontSize) / 2, 0.05f);
  2582. m_fontSize -= sizeDelta;
  2583. m_fontSize = Mathf.Max((int)(m_fontSize * 20 + 0.5f) / 20f, m_fontSizeMin);
  2584. //Debug.Log("[" + m_AutoSizeIterationCount + "] Reducing Point Size from [" + m_maxFontSize.ToString("f3") + "] to [" + m_fontSize.ToString("f3") + "] with delta of [" + sizeDelta.ToString("f3") + "].");
  2585. k_HandleHorizontalLineBreakingMarker.End();
  2586. k_HandleVisibleCharacterMarker.End();
  2587. k_GenerateTextPhaseIMarker.End();
  2588. k_GenerateTextMarker.End();
  2589. return;
  2590. }
  2591. #endregion Text Auto-Sizing
  2592. }
  2593. // Special handling if first word of line and non breaking space
  2594. int savedSoftLineBreakingSpace = m_SavedSoftLineBreakState.previous_WordBreak;
  2595. if (isFirstWordOfLine && savedSoftLineBreakingSpace != -1)
  2596. {
  2597. if (savedSoftLineBreakingSpace != lastSoftLineBreak)
  2598. {
  2599. i = RestoreWordWrappingState(ref m_SavedSoftLineBreakState);
  2600. lastSoftLineBreak = savedSoftLineBreakingSpace;
  2601. // check if soft hyphen
  2602. if (m_textInfo.characterInfo[m_characterCount - 1].character == 0xAD)
  2603. {
  2604. characterToSubstitute.index = m_characterCount - 1;
  2605. characterToSubstitute.unicode = 0x2D;
  2606. i -= 1;
  2607. m_characterCount -= 1;
  2608. k_HandleHorizontalLineBreakingMarker.End();
  2609. k_HandleVisibleCharacterMarker.End();
  2610. continue;
  2611. }
  2612. }
  2613. }
  2614. // Determine if new line of text would exceed the vertical bounds of text container
  2615. if (newTextHeight > marginHeight + 0.0001f)
  2616. {
  2617. k_HandleVerticalLineBreakingMarker.Begin();
  2618. // Set isTextOverflowing and firstOverflowCharacterIndex
  2619. if (m_firstOverflowCharacterIndex == -1)
  2620. m_firstOverflowCharacterIndex = m_characterCount;
  2621. // Check if Auto-Size is enabled
  2622. if (m_enableAutoSizing)
  2623. {
  2624. // Handle Line spacing adjustments
  2625. #region Line Spacing Adjustments
  2626. if (m_lineSpacingDelta > m_lineSpacingMax && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount)
  2627. {
  2628. float adjustmentDelta = (marginHeight - newTextHeight) / (m_lineNumber + 1);
  2629. m_lineSpacingDelta = Mathf.Max(m_lineSpacingDelta + adjustmentDelta / baseScale, m_lineSpacingMax);
  2630. //Debug.Log("[" + m_AutoSizeIterationCount + "] Reducing Line Spacing. Delta of [" + m_lineSpacingDelta.ToString("f3") + "].");
  2631. k_HandleVerticalLineBreakingMarker.End();
  2632. k_HandleHorizontalLineBreakingMarker.End();
  2633. k_HandleVisibleCharacterMarker.End();
  2634. k_GenerateTextPhaseIMarker.End();
  2635. k_GenerateTextMarker.End();
  2636. return;
  2637. }
  2638. #endregion
  2639. // Handle Character Width Adjustments
  2640. #region Character Width Adjustments
  2641. if (m_charWidthAdjDelta < m_charWidthMaxAdj / 100 && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount)
  2642. {
  2643. float adjustedTextWidth = textWidth;
  2644. // Determine full width of the text
  2645. if (m_charWidthAdjDelta > 0)
  2646. adjustedTextWidth /= 1f - m_charWidthAdjDelta;
  2647. float adjustmentDelta = textWidth - (widthOfTextArea - 0.0001f) * (isJustifiedOrFlush ? 1.05f : 1.0f);
  2648. m_charWidthAdjDelta += adjustmentDelta / adjustedTextWidth;
  2649. m_charWidthAdjDelta = Mathf.Min(m_charWidthAdjDelta, m_charWidthMaxAdj / 100);
  2650. //Debug.Log("[" + m_AutoSizeIterationCount + "] Reducing Character Width by " + (m_charWidthAdjDelta * 100) + "%");
  2651. k_HandleVerticalLineBreakingMarker.End();
  2652. k_HandleHorizontalLineBreakingMarker.End();
  2653. k_HandleVisibleCharacterMarker.End();
  2654. k_GenerateTextPhaseIMarker.End();
  2655. k_GenerateTextMarker.End();
  2656. return;
  2657. }
  2658. #endregion
  2659. // Handle Text Auto-sizing resulting from text exceeding vertical bounds.
  2660. #region Text Auto-Sizing (Text greater than vertical bounds)
  2661. if (m_fontSize > m_fontSizeMin && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount)
  2662. {
  2663. m_maxFontSize = m_fontSize;
  2664. float sizeDelta = Mathf.Max((m_fontSize - m_minFontSize) / 2, 0.05f);
  2665. m_fontSize -= sizeDelta;
  2666. m_fontSize = Mathf.Max((int)(m_fontSize * 20 + 0.5f) / 20f, m_fontSizeMin);
  2667. //Debug.Log("[" + m_AutoSizeIterationCount + "] Reducing Point Size from [" + m_maxFontSize.ToString("f3") + "] to [" + m_fontSize.ToString("f3") + "] with delta of [" + sizeDelta.ToString("f3") + "].");
  2668. k_HandleVerticalLineBreakingMarker.End();
  2669. k_HandleHorizontalLineBreakingMarker.End();
  2670. k_HandleVisibleCharacterMarker.End();
  2671. k_GenerateTextPhaseIMarker.End();
  2672. k_GenerateTextMarker.End();
  2673. return;
  2674. }
  2675. #endregion Text Auto-Sizing
  2676. }
  2677. // Check Text Overflow Modes
  2678. switch (m_overflowMode)
  2679. {
  2680. case TextOverflowModes.Overflow:
  2681. case TextOverflowModes.ScrollRect:
  2682. case TextOverflowModes.Masking:
  2683. InsertNewLine(i, baseScale, currentElementScale, currentEmScale, boldSpacingAdjustment, characterSpacingAdjustment, widthOfTextArea, lineGap, ref isMaxVisibleDescenderSet, ref maxVisibleDescender);
  2684. isStartOfNewLine = true;
  2685. isFirstWordOfLine = true;
  2686. k_HandleVerticalLineBreakingMarker.End();
  2687. k_HandleHorizontalLineBreakingMarker.End();
  2688. k_HandleVisibleCharacterMarker.End();
  2689. continue;
  2690. case TextOverflowModes.Truncate:
  2691. i = RestoreWordWrappingState(ref m_SavedLastValidState);
  2692. characterToSubstitute.index = testedCharacterCount;
  2693. characterToSubstitute.unicode = 0x03;
  2694. k_HandleVerticalLineBreakingMarker.End();
  2695. k_HandleHorizontalLineBreakingMarker.End();
  2696. k_HandleVisibleCharacterMarker.End();
  2697. continue;
  2698. case TextOverflowModes.Ellipsis:
  2699. if (m_EllipsisInsertionCandidateStack.Count == 0)
  2700. {
  2701. i = -1;
  2702. m_characterCount = 0;
  2703. characterToSubstitute.index = 0;
  2704. characterToSubstitute.unicode = 0x03;
  2705. m_firstCharacterOfLine = 0;
  2706. k_HandleVerticalLineBreakingMarker.End();
  2707. k_HandleHorizontalLineBreakingMarker.End();
  2708. k_HandleVisibleCharacterMarker.End();
  2709. continue;
  2710. }
  2711. var ellipsisState = m_EllipsisInsertionCandidateStack.Pop();
  2712. i = RestoreWordWrappingState(ref ellipsisState);
  2713. i -= 1;
  2714. m_characterCount -= 1;
  2715. characterToSubstitute.index = m_characterCount;
  2716. characterToSubstitute.unicode = 0x2026;
  2717. restoreCount += 1;
  2718. k_HandleVerticalLineBreakingMarker.End();
  2719. k_HandleHorizontalLineBreakingMarker.End();
  2720. k_HandleVisibleCharacterMarker.End();
  2721. continue;
  2722. case TextOverflowModes.Linked:
  2723. if (m_linkedTextComponent != null)
  2724. {
  2725. m_linkedTextComponent.text = text;
  2726. m_linkedTextComponent.m_inputSource = m_inputSource;
  2727. m_linkedTextComponent.firstVisibleCharacter = m_characterCount;
  2728. m_linkedTextComponent.ForceMeshUpdate();
  2729. m_isTextTruncated = true;
  2730. }
  2731. // Truncate remaining text
  2732. characterToSubstitute.index = m_characterCount;
  2733. characterToSubstitute.unicode = 0x03;
  2734. k_HandleVerticalLineBreakingMarker.End();
  2735. k_HandleHorizontalLineBreakingMarker.End();
  2736. k_HandleVisibleCharacterMarker.End();
  2737. continue;
  2738. case TextOverflowModes.Page:
  2739. // Add new page
  2740. m_isNewPage = true;
  2741. InsertNewLine(i, baseScale, currentElementScale, currentEmScale, boldSpacingAdjustment, characterSpacingAdjustment, widthOfTextArea, lineGap, ref isMaxVisibleDescenderSet, ref maxVisibleDescender);
  2742. m_startOfLineAscender = 0;
  2743. m_lineOffset = 0;
  2744. m_maxTextAscender = 0;
  2745. m_PageAscender = 0;
  2746. m_pageNumber += 1;
  2747. isStartOfNewLine = true;
  2748. isFirstWordOfLine = true;
  2749. k_HandleVerticalLineBreakingMarker.End();
  2750. k_HandleHorizontalLineBreakingMarker.End();
  2751. k_HandleVisibleCharacterMarker.End();
  2752. continue;
  2753. }
  2754. }
  2755. else
  2756. {
  2757. //if (m_enableAutoSizing && isFirstWordOfLine)
  2758. //{
  2759. // // Handle Character Width Adjustments
  2760. // #region Character Width Adjustments
  2761. // if (m_charWidthAdjDelta < m_charWidthMaxAdj / 100 && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount)
  2762. // {
  2763. // //m_AutoSizeIterationCount = 0;
  2764. // float adjustedTextWidth = textWidth;
  2765. // // Determine full width of the text
  2766. // if (m_charWidthAdjDelta > 0)
  2767. // adjustedTextWidth /= 1f - m_charWidthAdjDelta;
  2768. // float adjustmentDelta = textWidth - (widthOfTextArea - 0.0001f) * (isJustifiedOrFlush ? 1.05f : 1.0f);
  2769. // m_charWidthAdjDelta += adjustmentDelta / adjustedTextWidth;
  2770. // m_charWidthAdjDelta = Mathf.Min(m_charWidthAdjDelta, m_charWidthMaxAdj / 100);
  2771. // //Debug.Log("[" + m_AutoSizeIterationCount + "] Reducing Character Width by " + (m_charWidthAdjDelta * 100) + "%");
  2772. // GenerateTextMesh();
  2773. // return;
  2774. // }
  2775. // #endregion
  2776. //}
  2777. // New line of text does not exceed vertical bounds of text container
  2778. InsertNewLine(i, baseScale, currentElementScale, currentEmScale, boldSpacingAdjustment, characterSpacingAdjustment, widthOfTextArea, lineGap, ref isMaxVisibleDescenderSet, ref maxVisibleDescender);
  2779. isStartOfNewLine = true;
  2780. isFirstWordOfLine = true;
  2781. k_HandleHorizontalLineBreakingMarker.End();
  2782. k_HandleVisibleCharacterMarker.End();
  2783. continue;
  2784. }
  2785. }
  2786. else
  2787. {
  2788. if (m_enableAutoSizing && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount)
  2789. {
  2790. // Handle Character Width Adjustments
  2791. #region Character Width Adjustments
  2792. if (m_charWidthAdjDelta < m_charWidthMaxAdj / 100)
  2793. {
  2794. float adjustedTextWidth = textWidth;
  2795. // Determine full width of the text
  2796. if (m_charWidthAdjDelta > 0)
  2797. adjustedTextWidth /= 1f - m_charWidthAdjDelta;
  2798. float adjustmentDelta = textWidth - (widthOfTextArea - 0.0001f) * (isJustifiedOrFlush ? 1.05f : 1.0f);
  2799. m_charWidthAdjDelta += adjustmentDelta / adjustedTextWidth;
  2800. m_charWidthAdjDelta = Mathf.Min(m_charWidthAdjDelta, m_charWidthMaxAdj / 100);
  2801. //Debug.Log("[" + m_AutoSizeIterationCount + "] Reducing Character Width by " + (m_charWidthAdjDelta * 100) + "%");
  2802. k_HandleHorizontalLineBreakingMarker.End();
  2803. k_HandleVisibleCharacterMarker.End();
  2804. k_GenerateTextPhaseIMarker.End();
  2805. k_GenerateTextMarker.End();
  2806. return;
  2807. }
  2808. #endregion
  2809. // Handle Text Auto-sizing resulting from text exceeding horizontal bounds.
  2810. #region Text Exceeds Horizontal Bounds - Reducing Point Size
  2811. if (m_fontSize > m_fontSizeMin)
  2812. {
  2813. // Reset character width adjustment delta
  2814. //m_charWidthAdjDelta = 0;
  2815. // Adjust Point Size
  2816. m_maxFontSize = m_fontSize;
  2817. float sizeDelta = Mathf.Max((m_fontSize - m_minFontSize) / 2, 0.05f);
  2818. m_fontSize -= sizeDelta;
  2819. m_fontSize = Mathf.Max((int)(m_fontSize * 20 + 0.5f) / 20f, m_fontSizeMin);
  2820. //Debug.Log("[" + m_AutoSizeIterationCount + "] Reducing Point Size from [" + m_maxFontSize.ToString("f3") + "] to [" + m_fontSize.ToString("f3") + "] with delta of [" + sizeDelta.ToString("f3") + "].");
  2821. k_HandleHorizontalLineBreakingMarker.End();
  2822. k_HandleVisibleCharacterMarker.End();
  2823. k_GenerateTextPhaseIMarker.End();
  2824. k_GenerateTextMarker.End();
  2825. return;
  2826. }
  2827. #endregion
  2828. }
  2829. // Check Text Overflow Modes
  2830. switch (m_overflowMode)
  2831. {
  2832. case TextOverflowModes.Overflow:
  2833. case TextOverflowModes.ScrollRect:
  2834. case TextOverflowModes.Masking:
  2835. // Nothing happens as horizontal bounds are ignored in this mode.
  2836. break;
  2837. case TextOverflowModes.Truncate:
  2838. i = RestoreWordWrappingState(ref m_SavedWordWrapState);
  2839. characterToSubstitute.index = testedCharacterCount;
  2840. characterToSubstitute.unicode = 0x03;
  2841. k_HandleHorizontalLineBreakingMarker.End();
  2842. k_HandleVisibleCharacterMarker.End();
  2843. continue;
  2844. case TextOverflowModes.Ellipsis:
  2845. if (m_EllipsisInsertionCandidateStack.Count == 0)
  2846. {
  2847. i = -1;
  2848. m_characterCount = 0;
  2849. characterToSubstitute.index = 0;
  2850. characterToSubstitute.unicode = 0x03;
  2851. m_firstCharacterOfLine = 0;
  2852. k_HandleHorizontalLineBreakingMarker.End();
  2853. k_HandleVisibleCharacterMarker.End();
  2854. continue;
  2855. }
  2856. var ellipsisState = m_EllipsisInsertionCandidateStack.Pop();
  2857. i = RestoreWordWrappingState(ref ellipsisState);
  2858. i -= 1;
  2859. m_characterCount -= 1;
  2860. characterToSubstitute.index = m_characterCount;
  2861. characterToSubstitute.unicode = 0x2026;
  2862. restoreCount += 1;
  2863. k_HandleHorizontalLineBreakingMarker.End();
  2864. k_HandleVisibleCharacterMarker.End();
  2865. continue;
  2866. case TextOverflowModes.Linked:
  2867. i = RestoreWordWrappingState(ref m_SavedWordWrapState);
  2868. if (m_linkedTextComponent != null)
  2869. {
  2870. m_linkedTextComponent.text = text;
  2871. m_linkedTextComponent.m_inputSource = m_inputSource;
  2872. m_linkedTextComponent.firstVisibleCharacter = m_characterCount;
  2873. m_linkedTextComponent.ForceMeshUpdate();
  2874. m_isTextTruncated = true;
  2875. }
  2876. // Truncate text the overflows the vertical bounds
  2877. characterToSubstitute.index = m_characterCount;
  2878. characterToSubstitute.unicode = 0x03;
  2879. k_HandleHorizontalLineBreakingMarker.End();
  2880. k_HandleVisibleCharacterMarker.End();
  2881. continue;
  2882. }
  2883. }
  2884. k_HandleHorizontalLineBreakingMarker.End();
  2885. }
  2886. #endregion
  2887. // Special handling of characters that are not ignored at the end of a line.
  2888. if (isWhiteSpace)
  2889. {
  2890. m_textInfo.characterInfo[m_characterCount].isVisible = false;
  2891. m_lastVisibleCharacterOfLine = m_characterCount;
  2892. m_lineVisibleSpaceCount = m_textInfo.lineInfo[m_lineNumber].spaceCount += 1;
  2893. m_textInfo.lineInfo[m_lineNumber].marginLeft = marginLeft;
  2894. m_textInfo.lineInfo[m_lineNumber].marginRight = marginRight;
  2895. m_textInfo.spaceCount += 1;
  2896. if (charCode == 0xA0)
  2897. m_textInfo.lineInfo[m_lineNumber].controlCharacterCount += 1;
  2898. }
  2899. else if (charCode == 0xAD)
  2900. {
  2901. m_textInfo.characterInfo[m_characterCount].isVisible = false;
  2902. }
  2903. else
  2904. {
  2905. // Determine Vertex Color
  2906. Color32 vertexColor;
  2907. if (m_overrideHtmlColors)
  2908. vertexColor = m_fontColor32;
  2909. else
  2910. vertexColor = m_htmlColor;
  2911. k_SaveGlyphVertexDataMarker.Begin();
  2912. // Store Character & Sprite Vertex Information
  2913. if (m_textElementType == TMP_TextElementType.Character)
  2914. {
  2915. // Save Character Vertex Data
  2916. SaveGlyphVertexInfo(padding, style_padding, vertexColor);
  2917. }
  2918. else if (m_textElementType == TMP_TextElementType.Sprite)
  2919. {
  2920. SaveSpriteVertexInfo(vertexColor);
  2921. }
  2922. k_SaveGlyphVertexDataMarker.End();
  2923. if (isStartOfNewLine)
  2924. {
  2925. isStartOfNewLine = false;
  2926. m_firstVisibleCharacterOfLine = m_characterCount;
  2927. }
  2928. m_lineVisibleCharacterCount += 1;
  2929. m_lastVisibleCharacterOfLine = m_characterCount;
  2930. m_textInfo.lineInfo[m_lineNumber].marginLeft = marginLeft;
  2931. m_textInfo.lineInfo[m_lineNumber].marginRight = marginRight;
  2932. }
  2933. k_HandleVisibleCharacterMarker.End();
  2934. }
  2935. else
  2936. {
  2937. k_HandleWhiteSpacesMarker.Begin();
  2938. // Special handling for text overflow linked mode
  2939. #region Check Vertical Bounds
  2940. if (m_overflowMode == TextOverflowModes.Linked && (charCode == 10 || charCode == 11))
  2941. {
  2942. float textHeight = m_maxTextAscender - (m_maxLineDescender - m_lineOffset) + (m_lineOffset > 0 && m_IsDrivenLineSpacing == false ? m_maxLineAscender - m_startOfLineAscender : 0);
  2943. int testedCharacterCount = m_characterCount;
  2944. if (textHeight > marginHeight + 0.0001f)
  2945. {
  2946. // Set isTextOverflowing and firstOverflowCharacterIndex
  2947. if (m_firstOverflowCharacterIndex == -1)
  2948. m_firstOverflowCharacterIndex = m_characterCount;
  2949. i = RestoreWordWrappingState(ref m_SavedLastValidState);
  2950. if (m_linkedTextComponent != null)
  2951. {
  2952. m_linkedTextComponent.text = text;
  2953. m_linkedTextComponent.m_inputSource = m_inputSource;
  2954. m_linkedTextComponent.firstVisibleCharacter = m_characterCount;
  2955. m_linkedTextComponent.ForceMeshUpdate();
  2956. m_isTextTruncated = true;
  2957. }
  2958. // Truncate remaining text
  2959. characterToSubstitute.index = testedCharacterCount;
  2960. characterToSubstitute.unicode = 0x03;
  2961. k_HandleWhiteSpacesMarker.End();
  2962. continue;
  2963. }
  2964. }
  2965. #endregion
  2966. // Track # of spaces per line which is used for line justification.
  2967. if ((charCode == 10 || charCode == 11 || charCode == 0xA0 || charCode == 0x2007 || charCode == 0x2028 || charCode == 0x2029 || char.IsSeparator((char)charCode)) && charCode != 0xAD && charCode != 0x200B && charCode != 0x2060)
  2968. {
  2969. m_textInfo.lineInfo[m_lineNumber].spaceCount += 1;
  2970. m_textInfo.spaceCount += 1;
  2971. }
  2972. // Special handling for control characters like <NBSP>
  2973. if (charCode == 0xA0)
  2974. m_textInfo.lineInfo[m_lineNumber].controlCharacterCount += 1;
  2975. k_HandleWhiteSpacesMarker.End();
  2976. }
  2977. #endregion Handle Visible Characters
  2978. // Tracking of potential insertion positions for Ellipsis character
  2979. #region Track Potential Insertion Location for Ellipsis
  2980. if (m_overflowMode == TextOverflowModes.Ellipsis && (isInjectedCharacter == false || charCode == 0x2D))
  2981. {
  2982. float fontScale = m_currentFontSize / m_Ellipsis.fontAsset.m_FaceInfo.pointSize * m_Ellipsis.fontAsset.m_FaceInfo.scale * (m_isOrthographic ? 1 : 0.1f);
  2983. float scale = fontScale * m_fontScaleMultiplier * m_Ellipsis.character.m_Scale * m_Ellipsis.character.m_Glyph.scale;
  2984. float marginLeft = m_marginLeft;
  2985. float marginRight = m_marginRight;
  2986. // Use the scale and margins of the previous character if Line Feed (LF) is not the first character of a line.
  2987. if (charCode == 0x0A && m_characterCount != m_firstCharacterOfLine)
  2988. {
  2989. fontScale = m_textInfo.characterInfo[m_characterCount - 1].pointSize / m_Ellipsis.fontAsset.m_FaceInfo.pointSize * m_Ellipsis.fontAsset.m_FaceInfo.scale * (m_isOrthographic ? 1 : 0.1f);
  2990. scale = fontScale * m_fontScaleMultiplier * m_Ellipsis.character.m_Scale * m_Ellipsis.character.m_Glyph.scale;
  2991. marginLeft = m_textInfo.lineInfo[m_lineNumber].marginLeft;
  2992. marginRight = m_textInfo.lineInfo[m_lineNumber].marginRight;
  2993. }
  2994. float textHeight = m_maxTextAscender - (m_maxLineDescender - m_lineOffset) + (m_lineOffset > 0 && m_IsDrivenLineSpacing == false ? m_maxLineAscender - m_startOfLineAscender : 0);
  2995. float textWidth = Mathf.Abs(m_xAdvance) + (!m_isRightToLeft ? m_Ellipsis.character.m_Glyph.metrics.horizontalAdvance : 0) * (1 - m_charWidthAdjDelta) * scale;
  2996. float widthOfTextAreaForEllipsis = m_width != -1 ? Mathf.Min(marginWidth + 0.0001f - marginLeft - marginRight, m_width) : marginWidth + 0.0001f - marginLeft - marginRight;
  2997. if (textWidth < widthOfTextAreaForEllipsis * (isJustifiedOrFlush ? 1.05f : 1.0f) && textHeight < marginHeight + 0.0001f)
  2998. {
  2999. SaveWordWrappingState(ref m_SavedEllipsisState, i, m_characterCount);
  3000. m_EllipsisInsertionCandidateStack.Push(m_SavedEllipsisState);
  3001. }
  3002. }
  3003. #endregion
  3004. // Store Rectangle positions for each Character.
  3005. #region Store Character Data
  3006. m_textInfo.characterInfo[m_characterCount].lineNumber = m_lineNumber;
  3007. m_textInfo.characterInfo[m_characterCount].pageNumber = m_pageNumber;
  3008. if (charCode != 10 && charCode != 11 && charCode != 13 && isInjectedCharacter == false /* && charCode != 8230 */ || m_textInfo.lineInfo[m_lineNumber].characterCount == 1)
  3009. m_textInfo.lineInfo[m_lineNumber].alignment = m_lineJustification;
  3010. #endregion Store Character Data
  3011. // Handle xAdvance & Tabulation Stops. Tab stops at every 25% of Font Size.
  3012. #region XAdvance, Tabulation & Stops
  3013. k_ComputeCharacterAdvanceMarker.Begin();
  3014. if (charCode == 9)
  3015. {
  3016. float tabSize = m_currentFontAsset.m_FaceInfo.tabWidth * m_currentFontAsset.tabSize * currentElementScale;
  3017. float tabs = Mathf.Ceil(m_xAdvance / tabSize) * tabSize;
  3018. m_xAdvance = tabs > m_xAdvance ? tabs : m_xAdvance + tabSize;
  3019. }
  3020. else if (m_monoSpacing != 0)
  3021. {
  3022. float monoAdjustment;
  3023. if (m_duoSpace && (charCode == '.' || charCode == ':' || charCode == ','))
  3024. monoAdjustment = m_monoSpacing / 2 - monoAdvance;
  3025. else
  3026. monoAdjustment = m_monoSpacing - monoAdvance;
  3027. m_xAdvance += (monoAdjustment + ((m_currentFontAsset.normalSpacingOffset + characterSpacingAdjustment) * currentEmScale) + m_cSpacing) * (1 - m_charWidthAdjDelta);
  3028. if (isWhiteSpace || charCode == 0x200B)
  3029. m_xAdvance += m_wordSpacing * currentEmScale;
  3030. }
  3031. else if (m_isRightToLeft)
  3032. {
  3033. m_xAdvance -= ((glyphAdjustments.xAdvance * currentElementScale + (m_currentFontAsset.normalSpacingOffset + characterSpacingAdjustment + boldSpacingAdjustment) * currentEmScale + m_cSpacing) * (1 - m_charWidthAdjDelta));
  3034. if (isWhiteSpace || charCode == 0x200B)
  3035. m_xAdvance -= m_wordSpacing * currentEmScale;
  3036. }
  3037. else
  3038. {
  3039. m_xAdvance += ((currentGlyphMetrics.horizontalAdvance * m_FXScale.x + glyphAdjustments.xAdvance) * currentElementScale + (m_currentFontAsset.normalSpacingOffset + characterSpacingAdjustment + boldSpacingAdjustment) * currentEmScale + m_cSpacing) * (1 - m_charWidthAdjDelta);
  3040. if (isWhiteSpace || charCode == 0x200B)
  3041. m_xAdvance += m_wordSpacing * currentEmScale;
  3042. }
  3043. // Store xAdvance information
  3044. m_textInfo.characterInfo[m_characterCount].xAdvance = m_xAdvance;
  3045. k_ComputeCharacterAdvanceMarker.End();
  3046. #endregion Tabulation & Stops
  3047. // Handle Carriage Return
  3048. #region Carriage Return
  3049. if (charCode == 13)
  3050. {
  3051. k_HandleCarriageReturnMarker.Begin();
  3052. m_xAdvance = 0 + tag_Indent;
  3053. k_HandleCarriageReturnMarker.End();
  3054. }
  3055. #endregion Carriage Return
  3056. // Tracking of text overflow page mode
  3057. #region Save PageInfo
  3058. k_SavePageInfoMarker.Begin();
  3059. if (m_overflowMode == TextOverflowModes.Page && charCode != 10 && charCode != 11 && charCode != 13 && charCode != 0x2028 && charCode != 0x2029)
  3060. {
  3061. // Check if we need to increase allocations for the pageInfo array.
  3062. if (m_pageNumber + 1 > m_textInfo.pageInfo.Length)
  3063. TMP_TextInfo.Resize(ref m_textInfo.pageInfo, m_pageNumber + 1, true);
  3064. m_textInfo.pageInfo[m_pageNumber].ascender = m_PageAscender;
  3065. m_textInfo.pageInfo[m_pageNumber].descender = m_ElementDescender < m_textInfo.pageInfo[m_pageNumber].descender
  3066. ? m_ElementDescender
  3067. : m_textInfo.pageInfo[m_pageNumber].descender;
  3068. if (m_isNewPage)
  3069. {
  3070. m_isNewPage = false;
  3071. m_textInfo.pageInfo[m_pageNumber].firstCharacterIndex = m_characterCount;
  3072. }
  3073. // Last index
  3074. m_textInfo.pageInfo[m_pageNumber].lastCharacterIndex = m_characterCount;
  3075. }
  3076. k_SavePageInfoMarker.End();
  3077. #endregion Save PageInfo
  3078. // Handle Line Spacing Adjustments + Word Wrapping & special case for last line.
  3079. #region Check for Line Feed and Last Character
  3080. if (charCode == 10 || charCode == 11 || charCode == 0x03 || charCode == 0x2028 || charCode == 0x2029 || (charCode == 0x2D && isInjectedCharacter) || m_characterCount == totalCharacterCount - 1)
  3081. {
  3082. k_HandleLineTerminationMarker.Begin();
  3083. // Adjust current line spacing (if necessary) before inserting new line
  3084. float baselineAdjustmentDelta = m_maxLineAscender - m_startOfLineAscender;
  3085. if (m_lineOffset > 0 && Math.Abs(baselineAdjustmentDelta) > 0.01f && m_IsDrivenLineSpacing == false && !m_isNewPage)
  3086. {
  3087. //Debug.Log("Line Feed - Adjusting Line Spacing on line #" + m_lineNumber);
  3088. AdjustLineOffset(m_firstCharacterOfLine, m_characterCount, baselineAdjustmentDelta);
  3089. m_ElementDescender -= baselineAdjustmentDelta;
  3090. m_lineOffset += baselineAdjustmentDelta;
  3091. // Adjust saved ellipsis state only if we are adjusting the same line number
  3092. if (m_SavedEllipsisState.lineNumber == m_lineNumber)
  3093. {
  3094. m_SavedEllipsisState = m_EllipsisInsertionCandidateStack.Pop();
  3095. m_SavedEllipsisState.startOfLineAscender += baselineAdjustmentDelta;
  3096. m_SavedEllipsisState.lineOffset += baselineAdjustmentDelta;
  3097. m_EllipsisInsertionCandidateStack.Push(m_SavedEllipsisState);
  3098. }
  3099. }
  3100. m_isNewPage = false;
  3101. // Calculate lineAscender & make sure if last character is superscript or subscript that we check that as well.
  3102. float lineAscender = m_maxLineAscender - m_lineOffset;
  3103. float lineDescender = m_maxLineDescender - m_lineOffset;
  3104. // Update maxDescender and maxVisibleDescender
  3105. m_ElementDescender = m_ElementDescender < lineDescender ? m_ElementDescender : lineDescender;
  3106. if (!isMaxVisibleDescenderSet)
  3107. maxVisibleDescender = m_ElementDescender;
  3108. if (m_useMaxVisibleDescender && (m_characterCount >= m_maxVisibleCharacters || m_lineNumber >= m_maxVisibleLines))
  3109. isMaxVisibleDescenderSet = true;
  3110. // Save Line Information
  3111. m_textInfo.lineInfo[m_lineNumber].firstCharacterIndex = m_firstCharacterOfLine;
  3112. m_textInfo.lineInfo[m_lineNumber].firstVisibleCharacterIndex = m_firstVisibleCharacterOfLine = m_firstCharacterOfLine > m_firstVisibleCharacterOfLine ? m_firstCharacterOfLine : m_firstVisibleCharacterOfLine;
  3113. m_textInfo.lineInfo[m_lineNumber].lastCharacterIndex = m_lastCharacterOfLine = m_characterCount;
  3114. m_textInfo.lineInfo[m_lineNumber].lastVisibleCharacterIndex = m_lastVisibleCharacterOfLine = m_lastVisibleCharacterOfLine < m_firstVisibleCharacterOfLine ? m_firstVisibleCharacterOfLine : m_lastVisibleCharacterOfLine;
  3115. m_textInfo.lineInfo[m_lineNumber].characterCount = m_textInfo.lineInfo[m_lineNumber].lastCharacterIndex - m_textInfo.lineInfo[m_lineNumber].firstCharacterIndex + 1;
  3116. m_textInfo.lineInfo[m_lineNumber].visibleCharacterCount = m_lineVisibleCharacterCount;
  3117. m_textInfo.lineInfo[m_lineNumber].visibleSpaceCount = (m_textInfo.lineInfo[m_lineNumber].lastVisibleCharacterIndex + 1) - m_lineVisibleCharacterCount;
  3118. m_textInfo.lineInfo[m_lineNumber].lineExtents.min = new Vector2(m_textInfo.characterInfo[m_firstVisibleCharacterOfLine].bottomLeft.x, lineDescender);
  3119. m_textInfo.lineInfo[m_lineNumber].lineExtents.max = new Vector2(m_textInfo.characterInfo[m_lastVisibleCharacterOfLine].topRight.x, lineAscender);
  3120. m_textInfo.lineInfo[m_lineNumber].length = m_textInfo.lineInfo[m_lineNumber].lineExtents.max.x - (padding * currentElementScale);
  3121. m_textInfo.lineInfo[m_lineNumber].width = widthOfTextArea;
  3122. if (m_textInfo.lineInfo[m_lineNumber].characterCount == 1)
  3123. m_textInfo.lineInfo[m_lineNumber].alignment = m_lineJustification;
  3124. float maxAdvanceOffset = ((m_currentFontAsset.normalSpacingOffset + characterSpacingAdjustment + boldSpacingAdjustment) * currentEmScale + m_cSpacing) * (1 - m_charWidthAdjDelta);
  3125. if (m_textInfo.characterInfo[m_lastVisibleCharacterOfLine].isVisible)
  3126. m_textInfo.lineInfo[m_lineNumber].maxAdvance = m_textInfo.characterInfo[m_lastVisibleCharacterOfLine].xAdvance + (m_isRightToLeft ? maxAdvanceOffset : - maxAdvanceOffset);
  3127. else
  3128. m_textInfo.lineInfo[m_lineNumber].maxAdvance = m_textInfo.characterInfo[m_lastCharacterOfLine].xAdvance + (m_isRightToLeft ? maxAdvanceOffset : - maxAdvanceOffset);
  3129. m_textInfo.lineInfo[m_lineNumber].baseline = 0 - m_lineOffset;
  3130. m_textInfo.lineInfo[m_lineNumber].ascender = lineAscender;
  3131. m_textInfo.lineInfo[m_lineNumber].descender = lineDescender;
  3132. m_textInfo.lineInfo[m_lineNumber].lineHeight = lineAscender - lineDescender + lineGap * baseScale;
  3133. // Add new line if not last line or character.
  3134. if (charCode == 10 || charCode == 11 || (charCode == 0x2D && isInjectedCharacter) || charCode == 0x2028 || charCode == 0x2029)
  3135. {
  3136. // Store the state of the line before starting on the new line.
  3137. SaveWordWrappingState(ref m_SavedLineState, i, m_characterCount);
  3138. m_lineNumber += 1;
  3139. isStartOfNewLine = true;
  3140. ignoreNonBreakingSpace = false;
  3141. isFirstWordOfLine = true;
  3142. m_firstCharacterOfLine = m_characterCount + 1;
  3143. m_lineVisibleCharacterCount = 0;
  3144. m_lineVisibleSpaceCount = 0;
  3145. // Check to make sure Array is large enough to hold a new line.
  3146. if (m_lineNumber >= m_textInfo.lineInfo.Length)
  3147. ResizeLineExtents(m_lineNumber);
  3148. float lastVisibleAscender = m_textInfo.characterInfo[m_characterCount].adjustedAscender;
  3149. // Apply Line Spacing with special handling for VT char(11)
  3150. if (m_lineHeight == TMP_Math.FLOAT_UNSET)
  3151. {
  3152. float lineOffsetDelta = 0 - m_maxLineDescender + lastVisibleAscender + (lineGap + m_lineSpacingDelta) * baseScale + (m_lineSpacing + (charCode == 10 || charCode == 0x2029 ? m_paragraphSpacing : 0)) * currentEmScale;
  3153. m_lineOffset += lineOffsetDelta;
  3154. m_IsDrivenLineSpacing = false;
  3155. }
  3156. else
  3157. {
  3158. m_lineOffset += m_lineHeight + (m_lineSpacing + (charCode == 10 || charCode == 0x2029 ? m_paragraphSpacing : 0)) * currentEmScale;
  3159. m_IsDrivenLineSpacing = true;
  3160. }
  3161. m_maxLineAscender = k_LargeNegativeFloat;
  3162. m_maxLineDescender = k_LargePositiveFloat;
  3163. m_startOfLineAscender = lastVisibleAscender;
  3164. m_xAdvance = 0 + tag_LineIndent + tag_Indent;
  3165. SaveWordWrappingState(ref m_SavedWordWrapState, i, m_characterCount);
  3166. SaveWordWrappingState(ref m_SavedLastValidState, i, m_characterCount);
  3167. m_characterCount += 1;
  3168. k_HandleLineTerminationMarker.End();
  3169. continue;
  3170. }
  3171. // If End of Text
  3172. if (charCode == 0x03)
  3173. i = m_TextProcessingArray.Length;
  3174. k_HandleLineTerminationMarker.End();
  3175. }
  3176. #endregion Check for Linefeed or Last Character
  3177. // Track extents of the text
  3178. #region Track Text Extents
  3179. k_SaveTextExtentMarker.Begin();
  3180. // Determine the bounds of the Mesh.
  3181. if (m_textInfo.characterInfo[m_characterCount].isVisible)
  3182. {
  3183. m_meshExtents.min.x = Mathf.Min(m_meshExtents.min.x, m_textInfo.characterInfo[m_characterCount].bottomLeft.x);
  3184. m_meshExtents.min.y = Mathf.Min(m_meshExtents.min.y, m_textInfo.characterInfo[m_characterCount].bottomLeft.y);
  3185. m_meshExtents.max.x = Mathf.Max(m_meshExtents.max.x, m_textInfo.characterInfo[m_characterCount].topRight.x);
  3186. m_meshExtents.max.y = Mathf.Max(m_meshExtents.max.y, m_textInfo.characterInfo[m_characterCount].topRight.y);
  3187. //m_meshExtents.min = new Vector2(Mathf.Min(m_meshExtents.min.x, m_textInfo.characterInfo[m_characterCount].bottomLeft.x), Mathf.Min(m_meshExtents.min.y, m_textInfo.characterInfo[m_characterCount].bottomLeft.y));
  3188. //m_meshExtents.max = new Vector2(Mathf.Max(m_meshExtents.max.x, m_textInfo.characterInfo[m_characterCount].topRight.x), Mathf.Max(m_meshExtents.max.y, m_textInfo.characterInfo[m_characterCount].topRight.y));
  3189. }
  3190. k_SaveTextExtentMarker.End();
  3191. #endregion Track Text Extents
  3192. // Save State of Mesh Creation for handling of Word Wrapping
  3193. #region Save Word Wrapping State
  3194. if ((m_TextWrappingMode != TextWrappingModes.NoWrap && m_TextWrappingMode != TextWrappingModes.PreserveWhitespaceNoWrap) || m_overflowMode == TextOverflowModes.Truncate || m_overflowMode == TextOverflowModes.Ellipsis || m_overflowMode == TextOverflowModes.Linked)
  3195. {
  3196. k_SaveProcessingStatesMarker.Begin();
  3197. bool shouldSaveHardLineBreak = false;
  3198. bool shouldSaveSoftLineBreak = false;
  3199. if ((isWhiteSpace || charCode == 0x200B || charCode == 0x2D || charCode == 0xAD) && (!m_isNonBreakingSpace || ignoreNonBreakingSpace) && charCode != 0xA0 && charCode != 0x2007 && charCode != 0x2011 && charCode != 0x202F && charCode != 0x2060)
  3200. {
  3201. // Ignore Hyphen (0x2D) when preceded by a whitespace
  3202. if ((charCode == 0x2D && m_characterCount > 0 && char.IsWhiteSpace(m_textInfo.characterInfo[m_characterCount - 1].character)) == false)
  3203. {
  3204. isFirstWordOfLine = false;
  3205. shouldSaveHardLineBreak = true;
  3206. // Reset soft line breaking point since we now have a valid hard break point.
  3207. m_SavedSoftLineBreakState.previous_WordBreak = -1;
  3208. }
  3209. }
  3210. // Handling for East Asian scripts
  3211. else if (m_isNonBreakingSpace == false && (TMP_TextParsingUtilities.IsHangul(charCode) && TMP_Settings.useModernHangulLineBreakingRules == false || TMP_TextParsingUtilities.IsCJK(charCode)))
  3212. {
  3213. bool isCurrentLeadingCharacter = TMP_Settings.linebreakingRules.leadingCharacters.Contains(charCode);
  3214. bool isNextFollowingCharacter = m_characterCount < totalCharacterCount - 1 && TMP_Settings.linebreakingRules.followingCharacters.Contains(m_textInfo.characterInfo[m_characterCount + 1].character);
  3215. if (isCurrentLeadingCharacter == false)
  3216. {
  3217. if (isNextFollowingCharacter == false)
  3218. {
  3219. isFirstWordOfLine = false;
  3220. shouldSaveHardLineBreak = true;
  3221. }
  3222. if (isFirstWordOfLine)
  3223. {
  3224. // Special handling for non-breaking space and soft line breaks
  3225. if (isWhiteSpace)
  3226. shouldSaveSoftLineBreak = true;
  3227. shouldSaveHardLineBreak = true;
  3228. }
  3229. }
  3230. else
  3231. {
  3232. if (isFirstWordOfLine && isFirstCharacterOfLine)
  3233. {
  3234. // Special handling for non-breaking space and soft line breaks
  3235. if (isWhiteSpace)
  3236. shouldSaveSoftLineBreak = true;
  3237. shouldSaveHardLineBreak = true;
  3238. }
  3239. }
  3240. }
  3241. // Special handling for Latin characters followed by a CJK character.
  3242. else if (m_isNonBreakingSpace == false && m_characterCount + 1 < totalCharacterCount && TMP_TextParsingUtilities.IsCJK(m_textInfo.characterInfo[m_characterCount + 1].character))
  3243. {
  3244. shouldSaveHardLineBreak = true;
  3245. }
  3246. else if (isFirstWordOfLine)
  3247. {
  3248. // Special handling for non-breaking space and soft line breaks
  3249. if (isWhiteSpace && charCode != 0xA0 || (charCode == 0xAD && isSoftHyphenIgnored == false))
  3250. shouldSaveSoftLineBreak = true;
  3251. shouldSaveHardLineBreak = true;
  3252. }
  3253. // Save potential Hard lines break
  3254. if (shouldSaveHardLineBreak)
  3255. SaveWordWrappingState(ref m_SavedWordWrapState, i, m_characterCount);
  3256. // Save potential Soft line break
  3257. if (shouldSaveSoftLineBreak)
  3258. SaveWordWrappingState(ref m_SavedSoftLineBreakState, i, m_characterCount);
  3259. k_SaveProcessingStatesMarker.End();
  3260. }
  3261. #endregion Save Word Wrapping State
  3262. // Consider only saving state on base glyphs
  3263. SaveWordWrappingState(ref m_SavedLastValidState, i, m_characterCount);
  3264. m_characterCount += 1;
  3265. }
  3266. // Check Auto Sizing and increase font size to fill text container.
  3267. #region Check Auto-Sizing (Upper Font Size Bounds)
  3268. fontSizeDelta = m_maxFontSize - m_minFontSize;
  3269. if (/* !m_isCharacterWrappingEnabled && */ m_enableAutoSizing && fontSizeDelta > 0.051f && m_fontSize < m_fontSizeMax && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount)
  3270. {
  3271. // Reset character width adjustment delta
  3272. if (m_charWidthAdjDelta < m_charWidthMaxAdj / 100)
  3273. m_charWidthAdjDelta = 0;
  3274. m_minFontSize = m_fontSize;
  3275. float sizeDelta = Mathf.Max((m_maxFontSize - m_fontSize) / 2, 0.05f);
  3276. m_fontSize += sizeDelta;
  3277. m_fontSize = Mathf.Min((int)(m_fontSize * 20 + 0.5f) / 20f, m_fontSizeMax);
  3278. //Debug.Log("[" + m_AutoSizeIterationCount + "] Increasing Point Size from [" + m_minFontSize.ToString("f3") + "] to [" + m_fontSize.ToString("f3") + "] with delta of [" + sizeDelta.ToString("f3") + "].");
  3279. k_GenerateTextPhaseIMarker.End();
  3280. k_GenerateTextMarker.End();
  3281. return;
  3282. }
  3283. #endregion End Auto-sizing Check
  3284. m_IsAutoSizePointSizeSet = true;
  3285. if (m_AutoSizeIterationCount >= m_AutoSizeMaxIterationCount)
  3286. Debug.Log("Auto Size Iteration Count: " + m_AutoSizeIterationCount + ". Final Point Size: " + m_fontSize);
  3287. // If there are no visible characters or only character is End of Text (0x03)... no need to continue
  3288. if (m_characterCount == 0 || (m_characterCount == 1 && charCode == 0x03))
  3289. {
  3290. ClearMesh(true);
  3291. // Event indicating the text has been regenerated.
  3292. TMPro_EventManager.ON_TEXT_CHANGED(this);
  3293. k_GenerateTextPhaseIMarker.End();
  3294. k_GenerateTextMarker.End();
  3295. return;
  3296. }
  3297. // End Sampling of Phase I
  3298. k_GenerateTextPhaseIMarker.End();
  3299. // *** PHASE II of Text Generation ***
  3300. k_GenerateTextPhaseIIMarker.Begin();
  3301. int last_vert_index = m_materialReferences[m_Underline.materialIndex].referenceCount * 4;
  3302. // Partial clear of the vertices array to mark unused vertices as degenerate.
  3303. m_textInfo.meshInfo[0].Clear(false);
  3304. // Handle Text Alignment
  3305. #region Text Vertical Alignment
  3306. Vector3 anchorOffset = Vector3.zero;
  3307. Vector3[] corners = m_RectTransformCorners; // GetTextContainerLocalCorners();
  3308. // Handle Vertical Text Alignment
  3309. switch (m_VerticalAlignment)
  3310. {
  3311. // Top Vertically
  3312. case VerticalAlignmentOptions.Top:
  3313. if (m_overflowMode != TextOverflowModes.Page)
  3314. anchorOffset = corners[1] + new Vector3(0 + margins.x, 0 - m_maxTextAscender - margins.y, 0);
  3315. else
  3316. anchorOffset = corners[1] + new Vector3(0 + margins.x, 0 - m_textInfo.pageInfo[pageToDisplay].ascender - margins.y, 0);
  3317. break;
  3318. // Middle Vertically
  3319. case VerticalAlignmentOptions.Middle:
  3320. if (m_overflowMode != TextOverflowModes.Page)
  3321. anchorOffset = (corners[0] + corners[1]) / 2 + new Vector3(0 + margins.x, 0 - (m_maxTextAscender + margins.y + maxVisibleDescender - margins.w) / 2, 0);
  3322. else
  3323. anchorOffset = (corners[0] + corners[1]) / 2 + new Vector3(0 + margins.x, 0 - (m_textInfo.pageInfo[pageToDisplay].ascender + margins.y + m_textInfo.pageInfo[pageToDisplay].descender - margins.w) / 2, 0);
  3324. break;
  3325. // Bottom Vertically
  3326. case VerticalAlignmentOptions.Bottom:
  3327. if (m_overflowMode != TextOverflowModes.Page)
  3328. anchorOffset = corners[0] + new Vector3(0 + margins.x, 0 - maxVisibleDescender + margins.w, 0);
  3329. else
  3330. anchorOffset = corners[0] + new Vector3(0 + margins.x, 0 - m_textInfo.pageInfo[pageToDisplay].descender + margins.w, 0);
  3331. break;
  3332. // Baseline Vertically
  3333. case VerticalAlignmentOptions.Baseline:
  3334. anchorOffset = (corners[0] + corners[1]) / 2 + new Vector3(0 + margins.x, 0, 0);
  3335. break;
  3336. // Midline Vertically
  3337. case VerticalAlignmentOptions.Geometry:
  3338. anchorOffset = (corners[0] + corners[1]) / 2 + new Vector3(0 + margins.x, 0 - (m_meshExtents.max.y + margins.y + m_meshExtents.min.y - margins.w) / 2, 0);
  3339. break;
  3340. // Capline Vertically
  3341. case VerticalAlignmentOptions.Capline:
  3342. anchorOffset = (corners[0] + corners[1]) / 2 + new Vector3(0 + margins.x, 0 - (m_maxCapHeight - margins.y - margins.w) / 2, 0);
  3343. break;
  3344. }
  3345. #endregion
  3346. // Initialization for Second Pass
  3347. Vector3 justificationOffset = Vector3.zero;
  3348. Vector3 offset = Vector3.zero;
  3349. // int vert_index_X4 = 0;
  3350. // int sprite_index_X4 = 0;
  3351. int wordCount = 0;
  3352. int lineCount = 0;
  3353. int lastLine = 0;
  3354. bool isFirstSeperator = false;
  3355. bool isStartOfWord = false;
  3356. int wordFirstChar = 0;
  3357. int wordLastChar = 0;
  3358. // Second Pass : Line Justification, UV Mapping, Character & Line Visibility & more.
  3359. float lossyScale = m_previousLossyScaleY = this.transform.lossyScale.y;
  3360. Color32 underlineColor = Color.white;
  3361. Color32 strikethroughColor = Color.white;
  3362. HighlightState highlightState = new HighlightState(new Color32(255, 255, 0, 64), TMP_Offset.zero);
  3363. float xScale = 0;
  3364. float xScaleMax = 0;
  3365. float underlineStartScale = 0;
  3366. float underlineEndScale = 0;
  3367. float underlineMaxScale = 0;
  3368. float underlineBaseLine = k_LargePositiveFloat;
  3369. int lastPage = 0;
  3370. float strikethroughPointSize = 0;
  3371. float strikethroughScale = 0;
  3372. float strikethroughBaseline = 0;
  3373. TMP_CharacterInfo[] characterInfos = m_textInfo.characterInfo;
  3374. #region Handle Line Justification & UV Mapping & Character Visibility & More
  3375. for (int i = 0; i < m_characterCount; i++)
  3376. {
  3377. TMP_FontAsset currentFontAsset = characterInfos[i].fontAsset;
  3378. char unicode = characterInfos[i].character;
  3379. bool isWhiteSpace = char.IsWhiteSpace(unicode);
  3380. int currentLine = characterInfos[i].lineNumber;
  3381. TMP_LineInfo lineInfo = m_textInfo.lineInfo[currentLine];
  3382. lineCount = currentLine + 1;
  3383. HorizontalAlignmentOptions lineAlignment = lineInfo.alignment;
  3384. // Process Line Justification
  3385. #region Handle Line Justification
  3386. switch (lineAlignment)
  3387. {
  3388. case HorizontalAlignmentOptions.Left:
  3389. if (!m_isRightToLeft)
  3390. justificationOffset = new Vector3(0 + lineInfo.marginLeft, 0, 0);
  3391. else
  3392. justificationOffset = new Vector3(0 - lineInfo.maxAdvance, 0, 0);
  3393. break;
  3394. case HorizontalAlignmentOptions.Center:
  3395. justificationOffset = new Vector3(lineInfo.marginLeft + lineInfo.width / 2 - lineInfo.maxAdvance / 2, 0, 0);
  3396. break;
  3397. case HorizontalAlignmentOptions.Geometry:
  3398. justificationOffset = new Vector3(lineInfo.marginLeft + lineInfo.width / 2 - (lineInfo.lineExtents.min.x + lineInfo.lineExtents.max.x) / 2, 0, 0);
  3399. break;
  3400. case HorizontalAlignmentOptions.Right:
  3401. if (!m_isRightToLeft)
  3402. justificationOffset = new Vector3(lineInfo.marginLeft + lineInfo.width - lineInfo.maxAdvance, 0, 0);
  3403. else
  3404. justificationOffset = new Vector3(lineInfo.marginLeft + lineInfo.width, 0, 0);
  3405. break;
  3406. case HorizontalAlignmentOptions.Justified:
  3407. case HorizontalAlignmentOptions.Flush:
  3408. // Skip Zero Width Characters and spaces outside of the margins.
  3409. if (i > lineInfo.lastVisibleCharacterIndex || unicode == 0x0A || unicode == 0xAD || unicode == 0x200B || unicode == 0x2060 || unicode == 0x03) break;
  3410. char lastCharOfCurrentLine = characterInfos[lineInfo.lastCharacterIndex].character;
  3411. bool isFlush = (lineAlignment & HorizontalAlignmentOptions.Flush) == HorizontalAlignmentOptions.Flush;
  3412. // In Justified mode, all lines are justified except the last one.
  3413. // In Flush mode, all lines are justified.
  3414. if (char.IsControl(lastCharOfCurrentLine) == false && currentLine < m_lineNumber || isFlush || lineInfo.maxAdvance > lineInfo.width)
  3415. {
  3416. // First character of each line.
  3417. if (currentLine != lastLine || i == 0 || i == m_firstVisibleCharacter)
  3418. {
  3419. if (!m_isRightToLeft)
  3420. justificationOffset = new Vector3(lineInfo.marginLeft, 0, 0);
  3421. else
  3422. justificationOffset = new Vector3(lineInfo.marginLeft + lineInfo.width, 0, 0);
  3423. if (char.IsSeparator(unicode))
  3424. isFirstSeperator = true;
  3425. else
  3426. isFirstSeperator = false;
  3427. }
  3428. else
  3429. {
  3430. float gap = !m_isRightToLeft ? lineInfo.width - lineInfo.maxAdvance : lineInfo.width + lineInfo.maxAdvance;
  3431. int visibleCount = lineInfo.visibleCharacterCount - 1 + lineInfo.controlCharacterCount;
  3432. int spaces = lineInfo.spaceCount - lineInfo.controlCharacterCount;
  3433. if (isFirstSeperator) { spaces -= 1; visibleCount += 1; }
  3434. float ratio = spaces > 0 ? m_wordWrappingRatios : 1;
  3435. if (spaces < 1) spaces = 1;
  3436. if (unicode != 0xA0 && (unicode == 9 || char.IsSeparator(unicode)))
  3437. {
  3438. if (!m_isRightToLeft)
  3439. justificationOffset += new Vector3(gap * (1 - ratio) / spaces, 0, 0);
  3440. else
  3441. justificationOffset -= new Vector3(gap * (1 - ratio) / spaces, 0, 0);
  3442. }
  3443. else
  3444. {
  3445. if (!m_isRightToLeft)
  3446. justificationOffset += new Vector3(gap * ratio / visibleCount, 0, 0);
  3447. else
  3448. justificationOffset -= new Vector3(gap * ratio / visibleCount, 0, 0);
  3449. }
  3450. }
  3451. }
  3452. else
  3453. {
  3454. if (!m_isRightToLeft)
  3455. justificationOffset = new Vector3(lineInfo.marginLeft, 0, 0); // Keep last line left justified.
  3456. else
  3457. justificationOffset = new Vector3(lineInfo.marginLeft + lineInfo.width, 0, 0); // Keep last line right justified.
  3458. }
  3459. //Debug.Log("Char [" + (char)charCode + "] Code:" + charCode + " Line # " + currentLine + " Offset:" + justificationOffset + " # Spaces:" + lineInfo.spaceCount + " # Characters:" + lineInfo.characterCount);
  3460. break;
  3461. }
  3462. #endregion End Text Justification
  3463. offset = anchorOffset + justificationOffset;
  3464. // Handle UV2 mapping options and packing of scale information into UV2.
  3465. #region Handling of UV2 mapping & Scale packing
  3466. bool isCharacterVisible = characterInfos[i].isVisible;
  3467. if (isCharacterVisible)
  3468. {
  3469. TMP_TextElementType elementType = characterInfos[i].elementType;
  3470. switch (elementType)
  3471. {
  3472. // CHARACTERS
  3473. case TMP_TextElementType.Character:
  3474. Extents lineExtents = lineInfo.lineExtents;
  3475. float uvOffset = (m_uvLineOffset * currentLine) % 1; // + m_uvOffset.x;
  3476. // Setup UV2 based on Character Mapping Options Selected
  3477. #region Handle UV Mapping Options
  3478. switch (m_horizontalMapping)
  3479. {
  3480. case TextureMappingOptions.Character:
  3481. characterInfos[i].vertex_BL.uv2.x = 0; //+ m_uvOffset.x;
  3482. characterInfos[i].vertex_TL.uv2.x = 0; //+ m_uvOffset.x;
  3483. characterInfos[i].vertex_TR.uv2.x = 1; //+ m_uvOffset.x;
  3484. characterInfos[i].vertex_BR.uv2.x = 1; //+ m_uvOffset.x;
  3485. break;
  3486. case TextureMappingOptions.Line:
  3487. if (m_textAlignment != TextAlignmentOptions.Justified)
  3488. {
  3489. characterInfos[i].vertex_BL.uv2.x = (characterInfos[i].vertex_BL.position.x - lineExtents.min.x) / (lineExtents.max.x - lineExtents.min.x) + uvOffset;
  3490. characterInfos[i].vertex_TL.uv2.x = (characterInfos[i].vertex_TL.position.x - lineExtents.min.x) / (lineExtents.max.x - lineExtents.min.x) + uvOffset;
  3491. characterInfos[i].vertex_TR.uv2.x = (characterInfos[i].vertex_TR.position.x - lineExtents.min.x) / (lineExtents.max.x - lineExtents.min.x) + uvOffset;
  3492. characterInfos[i].vertex_BR.uv2.x = (characterInfos[i].vertex_BR.position.x - lineExtents.min.x) / (lineExtents.max.x - lineExtents.min.x) + uvOffset;
  3493. break;
  3494. }
  3495. else // Special Case if Justified is used in Line Mode.
  3496. {
  3497. characterInfos[i].vertex_BL.uv2.x = (characterInfos[i].vertex_BL.position.x + justificationOffset.x - m_meshExtents.min.x) / (m_meshExtents.max.x - m_meshExtents.min.x) + uvOffset;
  3498. characterInfos[i].vertex_TL.uv2.x = (characterInfos[i].vertex_TL.position.x + justificationOffset.x - m_meshExtents.min.x) / (m_meshExtents.max.x - m_meshExtents.min.x) + uvOffset;
  3499. characterInfos[i].vertex_TR.uv2.x = (characterInfos[i].vertex_TR.position.x + justificationOffset.x - m_meshExtents.min.x) / (m_meshExtents.max.x - m_meshExtents.min.x) + uvOffset;
  3500. characterInfos[i].vertex_BR.uv2.x = (characterInfos[i].vertex_BR.position.x + justificationOffset.x - m_meshExtents.min.x) / (m_meshExtents.max.x - m_meshExtents.min.x) + uvOffset;
  3501. break;
  3502. }
  3503. case TextureMappingOptions.Paragraph:
  3504. characterInfos[i].vertex_BL.uv2.x = (characterInfos[i].vertex_BL.position.x + justificationOffset.x - m_meshExtents.min.x) / (m_meshExtents.max.x - m_meshExtents.min.x) + uvOffset;
  3505. characterInfos[i].vertex_TL.uv2.x = (characterInfos[i].vertex_TL.position.x + justificationOffset.x - m_meshExtents.min.x) / (m_meshExtents.max.x - m_meshExtents.min.x) + uvOffset;
  3506. characterInfos[i].vertex_TR.uv2.x = (characterInfos[i].vertex_TR.position.x + justificationOffset.x - m_meshExtents.min.x) / (m_meshExtents.max.x - m_meshExtents.min.x) + uvOffset;
  3507. characterInfos[i].vertex_BR.uv2.x = (characterInfos[i].vertex_BR.position.x + justificationOffset.x - m_meshExtents.min.x) / (m_meshExtents.max.x - m_meshExtents.min.x) + uvOffset;
  3508. break;
  3509. case TextureMappingOptions.MatchAspect:
  3510. switch (m_verticalMapping)
  3511. {
  3512. case TextureMappingOptions.Character:
  3513. characterInfos[i].vertex_BL.uv2.y = 0; // + m_uvOffset.y;
  3514. characterInfos[i].vertex_TL.uv2.y = 1; // + m_uvOffset.y;
  3515. characterInfos[i].vertex_TR.uv2.y = 0; // + m_uvOffset.y;
  3516. characterInfos[i].vertex_BR.uv2.y = 1; // + m_uvOffset.y;
  3517. break;
  3518. case TextureMappingOptions.Line:
  3519. characterInfos[i].vertex_BL.uv2.y = (characterInfos[i].vertex_BL.position.y - lineExtents.min.y) / (lineExtents.max.y - lineExtents.min.y) + uvOffset;
  3520. characterInfos[i].vertex_TL.uv2.y = (characterInfos[i].vertex_TL.position.y - lineExtents.min.y) / (lineExtents.max.y - lineExtents.min.y) + uvOffset;
  3521. characterInfos[i].vertex_TR.uv2.y = characterInfos[i].vertex_BL.uv2.y;
  3522. characterInfos[i].vertex_BR.uv2.y = characterInfos[i].vertex_TL.uv2.y;
  3523. break;
  3524. case TextureMappingOptions.Paragraph:
  3525. characterInfos[i].vertex_BL.uv2.y = (characterInfos[i].vertex_BL.position.y - m_meshExtents.min.y) / (m_meshExtents.max.y - m_meshExtents.min.y) + uvOffset;
  3526. characterInfos[i].vertex_TL.uv2.y = (characterInfos[i].vertex_TL.position.y - m_meshExtents.min.y) / (m_meshExtents.max.y - m_meshExtents.min.y) + uvOffset;
  3527. characterInfos[i].vertex_TR.uv2.y = characterInfos[i].vertex_BL.uv2.y;
  3528. characterInfos[i].vertex_BR.uv2.y = characterInfos[i].vertex_TL.uv2.y;
  3529. break;
  3530. case TextureMappingOptions.MatchAspect:
  3531. Debug.Log("ERROR: Cannot Match both Vertical & Horizontal.");
  3532. break;
  3533. }
  3534. //float xDelta = 1 - (_uv2s[vert_index + 0].y * textMeshCharacterInfo[i].AspectRatio); // Left aligned
  3535. float xDelta = (1 - ((characterInfos[i].vertex_BL.uv2.y + characterInfos[i].vertex_TL.uv2.y) * characterInfos[i].aspectRatio)) / 2; // Center of Rectangle
  3536. characterInfos[i].vertex_BL.uv2.x = (characterInfos[i].vertex_BL.uv2.y * characterInfos[i].aspectRatio) + xDelta + uvOffset;
  3537. characterInfos[i].vertex_TL.uv2.x = characterInfos[i].vertex_BL.uv2.x;
  3538. characterInfos[i].vertex_TR.uv2.x = (characterInfos[i].vertex_TL.uv2.y * characterInfos[i].aspectRatio) + xDelta + uvOffset;
  3539. characterInfos[i].vertex_BR.uv2.x = characterInfos[i].vertex_TR.uv2.x;
  3540. break;
  3541. }
  3542. switch (m_verticalMapping)
  3543. {
  3544. case TextureMappingOptions.Character:
  3545. characterInfos[i].vertex_BL.uv2.y = 0; // + m_uvOffset.y;
  3546. characterInfos[i].vertex_TL.uv2.y = 1; // + m_uvOffset.y;
  3547. characterInfos[i].vertex_TR.uv2.y = 1; // + m_uvOffset.y;
  3548. characterInfos[i].vertex_BR.uv2.y = 0; // + m_uvOffset.y;
  3549. break;
  3550. case TextureMappingOptions.Line:
  3551. characterInfos[i].vertex_BL.uv2.y = (characterInfos[i].vertex_BL.position.y - lineInfo.descender) / (lineInfo.ascender - lineInfo.descender); // + m_uvOffset.y;
  3552. characterInfos[i].vertex_TL.uv2.y = (characterInfos[i].vertex_TL.position.y - lineInfo.descender) / (lineInfo.ascender - lineInfo.descender); // + m_uvOffset.y;
  3553. characterInfos[i].vertex_TR.uv2.y = characterInfos[i].vertex_TL.uv2.y;
  3554. characterInfos[i].vertex_BR.uv2.y = characterInfos[i].vertex_BL.uv2.y;
  3555. break;
  3556. case TextureMappingOptions.Paragraph:
  3557. characterInfos[i].vertex_BL.uv2.y = (characterInfos[i].vertex_BL.position.y - m_meshExtents.min.y) / (m_meshExtents.max.y - m_meshExtents.min.y); // + m_uvOffset.y;
  3558. characterInfos[i].vertex_TL.uv2.y = (characterInfos[i].vertex_TL.position.y - m_meshExtents.min.y) / (m_meshExtents.max.y - m_meshExtents.min.y); // + m_uvOffset.y;
  3559. characterInfos[i].vertex_TR.uv2.y = characterInfos[i].vertex_TL.uv2.y;
  3560. characterInfos[i].vertex_BR.uv2.y = characterInfos[i].vertex_BL.uv2.y;
  3561. break;
  3562. case TextureMappingOptions.MatchAspect:
  3563. float yDelta = (1 - ((characterInfos[i].vertex_BL.uv2.x + characterInfos[i].vertex_TR.uv2.x) / characterInfos[i].aspectRatio)) / 2; // Center of Rectangle
  3564. characterInfos[i].vertex_BL.uv2.y = yDelta + (characterInfos[i].vertex_BL.uv2.x / characterInfos[i].aspectRatio); // + m_uvOffset.y;
  3565. characterInfos[i].vertex_TL.uv2.y = yDelta + (characterInfos[i].vertex_TR.uv2.x / characterInfos[i].aspectRatio); // + m_uvOffset.y;
  3566. characterInfos[i].vertex_BR.uv2.y = characterInfos[i].vertex_BL.uv2.y;
  3567. characterInfos[i].vertex_TR.uv2.y = characterInfos[i].vertex_TL.uv2.y;
  3568. break;
  3569. }
  3570. #endregion
  3571. // Pack UV's so that we can pass Xscale needed for Shader to maintain 1:1 ratio.
  3572. #region Pack Scale into UV2
  3573. xScale = characterInfos[i].scale * Mathf.Abs(lossyScale) * (1 - m_charWidthAdjDelta);
  3574. if (!characterInfos[i].isUsingAlternateTypeface && (characterInfos[i].style & FontStyles.Bold) == FontStyles.Bold) xScale *= -1;
  3575. // Set SDF Scale
  3576. characterInfos[i].vertex_BL.uv.w = xScale;
  3577. characterInfos[i].vertex_TL.uv.w = xScale;
  3578. characterInfos[i].vertex_TR.uv.w = xScale;
  3579. characterInfos[i].vertex_BR.uv.w = xScale;
  3580. #endregion
  3581. break;
  3582. // SPRITES
  3583. case TMP_TextElementType.Sprite:
  3584. // Nothing right now
  3585. break;
  3586. }
  3587. // Handle maxVisibleCharacters, maxVisibleLines and Overflow Page Mode.
  3588. #region Handle maxVisibleCharacters / maxVisibleLines / Page Mode
  3589. if (i < m_maxVisibleCharacters && wordCount < m_maxVisibleWords && currentLine < m_maxVisibleLines && m_overflowMode != TextOverflowModes.Page)
  3590. {
  3591. characterInfos[i].vertex_BL.position += offset;
  3592. characterInfos[i].vertex_TL.position += offset;
  3593. characterInfos[i].vertex_TR.position += offset;
  3594. characterInfos[i].vertex_BR.position += offset;
  3595. }
  3596. else if (i < m_maxVisibleCharacters && wordCount < m_maxVisibleWords && currentLine < m_maxVisibleLines && m_overflowMode == TextOverflowModes.Page && characterInfos[i].pageNumber == pageToDisplay)
  3597. {
  3598. characterInfos[i].vertex_BL.position += offset;
  3599. characterInfos[i].vertex_TL.position += offset;
  3600. characterInfos[i].vertex_TR.position += offset;
  3601. characterInfos[i].vertex_BR.position += offset;
  3602. }
  3603. else
  3604. {
  3605. characterInfos[i].vertex_BL.position = Vector3.zero;
  3606. characterInfos[i].vertex_TL.position = Vector3.zero;
  3607. characterInfos[i].vertex_TR.position = Vector3.zero;
  3608. characterInfos[i].vertex_BR.position = Vector3.zero;
  3609. characterInfos[i].isVisible = false;
  3610. }
  3611. #endregion
  3612. if (QualitySettings.activeColorSpace == ColorSpace.Linear)
  3613. m_ConvertToLinearSpace = true;
  3614. else
  3615. m_ConvertToLinearSpace = false;
  3616. // Fill Vertex Buffers for the various types of element
  3617. if (elementType == TMP_TextElementType.Character)
  3618. {
  3619. FillCharacterVertexBuffers(i);
  3620. }
  3621. else if (elementType == TMP_TextElementType.Sprite)
  3622. {
  3623. FillSpriteVertexBuffers(i);
  3624. }
  3625. }
  3626. #endregion
  3627. // Apply Alignment and Justification Offset
  3628. m_textInfo.characterInfo[i].bottomLeft += offset;
  3629. m_textInfo.characterInfo[i].topLeft += offset;
  3630. m_textInfo.characterInfo[i].topRight += offset;
  3631. m_textInfo.characterInfo[i].bottomRight += offset;
  3632. m_textInfo.characterInfo[i].origin += offset.x;
  3633. m_textInfo.characterInfo[i].xAdvance += offset.x;
  3634. m_textInfo.characterInfo[i].ascender += offset.y;
  3635. m_textInfo.characterInfo[i].descender += offset.y;
  3636. m_textInfo.characterInfo[i].baseLine += offset.y;
  3637. // Update MeshExtents
  3638. if (isCharacterVisible)
  3639. {
  3640. //m_meshExtents.min = new Vector2(Mathf.Min(m_meshExtents.min.x, m_textInfo.characterInfo[i].bottomLeft.x), Mathf.Min(m_meshExtents.min.y, m_textInfo.characterInfo[i].bottomLeft.y));
  3641. //m_meshExtents.max = new Vector2(Mathf.Max(m_meshExtents.max.x, m_textInfo.characterInfo[i].topRight.x), Mathf.Max(m_meshExtents.max.y, m_textInfo.characterInfo[i].topLeft.y));
  3642. }
  3643. // Need to recompute lineExtent to account for the offset from justification.
  3644. #region Adjust lineExtents resulting from alignment offset
  3645. if (currentLine != lastLine || i == m_characterCount - 1)
  3646. {
  3647. // Update the previous line's extents
  3648. if (currentLine != lastLine)
  3649. {
  3650. m_textInfo.lineInfo[lastLine].baseline += offset.y;
  3651. m_textInfo.lineInfo[lastLine].ascender += offset.y;
  3652. m_textInfo.lineInfo[lastLine].descender += offset.y;
  3653. m_textInfo.lineInfo[lastLine].maxAdvance += offset.x;
  3654. m_textInfo.lineInfo[lastLine].lineExtents.min = new Vector2(m_textInfo.characterInfo[m_textInfo.lineInfo[lastLine].firstCharacterIndex].bottomLeft.x, m_textInfo.lineInfo[lastLine].descender);
  3655. m_textInfo.lineInfo[lastLine].lineExtents.max = new Vector2(m_textInfo.characterInfo[m_textInfo.lineInfo[lastLine].lastVisibleCharacterIndex].topRight.x, m_textInfo.lineInfo[lastLine].ascender);
  3656. }
  3657. // Update the current line's extents
  3658. if (i == m_characterCount - 1)
  3659. {
  3660. m_textInfo.lineInfo[currentLine].baseline += offset.y;
  3661. m_textInfo.lineInfo[currentLine].ascender += offset.y;
  3662. m_textInfo.lineInfo[currentLine].descender += offset.y;
  3663. m_textInfo.lineInfo[currentLine].maxAdvance += offset.x;
  3664. m_textInfo.lineInfo[currentLine].lineExtents.min = new Vector2(m_textInfo.characterInfo[m_textInfo.lineInfo[currentLine].firstCharacterIndex].bottomLeft.x, m_textInfo.lineInfo[currentLine].descender);
  3665. m_textInfo.lineInfo[currentLine].lineExtents.max = new Vector2(m_textInfo.characterInfo[m_textInfo.lineInfo[currentLine].lastVisibleCharacterIndex].topRight.x, m_textInfo.lineInfo[currentLine].ascender);
  3666. }
  3667. }
  3668. #endregion
  3669. // Track Word Count per line and for the object
  3670. #region Track Word Count
  3671. if (char.IsLetterOrDigit(unicode) || unicode == 0x2D || unicode == 0xAD || unicode == 0x2010 || unicode == 0x2011)
  3672. {
  3673. if (isStartOfWord == false)
  3674. {
  3675. isStartOfWord = true;
  3676. wordFirstChar = i;
  3677. }
  3678. // If last character is a word
  3679. if (isStartOfWord && i == m_characterCount - 1)
  3680. {
  3681. int size = m_textInfo.wordInfo.Length;
  3682. int index = m_textInfo.wordCount;
  3683. if (m_textInfo.wordCount + 1 > size)
  3684. TMP_TextInfo.Resize(ref m_textInfo.wordInfo, size + 1);
  3685. wordLastChar = i;
  3686. m_textInfo.wordInfo[index].firstCharacterIndex = wordFirstChar;
  3687. m_textInfo.wordInfo[index].lastCharacterIndex = wordLastChar;
  3688. m_textInfo.wordInfo[index].characterCount = wordLastChar - wordFirstChar + 1;
  3689. m_textInfo.wordInfo[index].textComponent = this;
  3690. wordCount += 1;
  3691. m_textInfo.wordCount += 1;
  3692. m_textInfo.lineInfo[currentLine].wordCount += 1;
  3693. }
  3694. }
  3695. else if (isStartOfWord || i == 0 && (!char.IsPunctuation(unicode) || isWhiteSpace || unicode == 0x200B || i == m_characterCount - 1))
  3696. {
  3697. if (i > 0 && i < characterInfos.Length - 1 && i < m_characterCount && (unicode == 39 || unicode == 8217) && char.IsLetterOrDigit(characterInfos[i - 1].character) && char.IsLetterOrDigit(characterInfos[i + 1].character))
  3698. {
  3699. }
  3700. else
  3701. {
  3702. wordLastChar = i == m_characterCount - 1 && char.IsLetterOrDigit(unicode) ? i : i - 1;
  3703. isStartOfWord = false;
  3704. int size = m_textInfo.wordInfo.Length;
  3705. int index = m_textInfo.wordCount;
  3706. if (m_textInfo.wordCount + 1 > size)
  3707. TMP_TextInfo.Resize(ref m_textInfo.wordInfo, size + 1);
  3708. m_textInfo.wordInfo[index].firstCharacterIndex = wordFirstChar;
  3709. m_textInfo.wordInfo[index].lastCharacterIndex = wordLastChar;
  3710. m_textInfo.wordInfo[index].characterCount = wordLastChar - wordFirstChar + 1;
  3711. m_textInfo.wordInfo[index].textComponent = this;
  3712. wordCount += 1;
  3713. m_textInfo.wordCount += 1;
  3714. m_textInfo.lineInfo[currentLine].wordCount += 1;
  3715. }
  3716. }
  3717. #endregion
  3718. // Setup & Handle Underline
  3719. #region Underline
  3720. // NOTE: Need to figure out how underline will be handled with multiple fonts and which font will be used for the underline.
  3721. bool isUnderline = (m_textInfo.characterInfo[i].style & FontStyles.Underline) == FontStyles.Underline;
  3722. if (isUnderline)
  3723. {
  3724. bool isUnderlineVisible = true;
  3725. int currentPage = m_textInfo.characterInfo[i].pageNumber;
  3726. m_textInfo.characterInfo[i].underlineVertexIndex = last_vert_index;
  3727. if (i > m_maxVisibleCharacters || currentLine > m_maxVisibleLines || (m_overflowMode == TextOverflowModes.Page && currentPage + 1 != m_pageToDisplay))
  3728. isUnderlineVisible = false;
  3729. // We only use the scale of visible characters.
  3730. if (!isWhiteSpace && unicode != 0x200B)
  3731. {
  3732. underlineMaxScale = Mathf.Max(underlineMaxScale, m_textInfo.characterInfo[i].scale);
  3733. xScaleMax = Mathf.Max(xScaleMax, Mathf.Abs(xScale));
  3734. underlineBaseLine = Mathf.Min(currentPage == lastPage ? underlineBaseLine : k_LargePositiveFloat, m_textInfo.characterInfo[i].baseLine + font.m_FaceInfo.underlineOffset * underlineMaxScale);
  3735. lastPage = currentPage; // Need to track pages to ensure we reset baseline for the new pages.
  3736. }
  3737. if (beginUnderline == false && isUnderlineVisible == true && i <= lineInfo.lastVisibleCharacterIndex && unicode != 10 && unicode != 11 && unicode != 13)
  3738. {
  3739. if (i == lineInfo.lastVisibleCharacterIndex && char.IsSeparator(unicode))
  3740. { }
  3741. else
  3742. {
  3743. beginUnderline = true;
  3744. underlineStartScale = m_textInfo.characterInfo[i].scale;
  3745. if (underlineMaxScale == 0)
  3746. {
  3747. underlineMaxScale = underlineStartScale;
  3748. xScaleMax = xScale;
  3749. }
  3750. underline_start = new Vector3(m_textInfo.characterInfo[i].bottomLeft.x, underlineBaseLine, 0);
  3751. underlineColor = m_textInfo.characterInfo[i].underlineColor;
  3752. }
  3753. }
  3754. // End Underline if text only contains one character.
  3755. if (beginUnderline && m_characterCount == 1)
  3756. {
  3757. beginUnderline = false;
  3758. underline_end = new Vector3(m_textInfo.characterInfo[i].topRight.x, underlineBaseLine, 0);
  3759. underlineEndScale = m_textInfo.characterInfo[i].scale;
  3760. DrawUnderlineMesh(underline_start, underline_end, ref last_vert_index, underlineStartScale, underlineEndScale, underlineMaxScale, xScaleMax, underlineColor);
  3761. underlineMaxScale = 0;
  3762. xScaleMax = 0;
  3763. underlineBaseLine = k_LargePositiveFloat;
  3764. }
  3765. else if (beginUnderline && (i == lineInfo.lastCharacterIndex || i >= lineInfo.lastVisibleCharacterIndex))
  3766. {
  3767. // Terminate underline at previous visible character if space or carriage return.
  3768. if (isWhiteSpace || unicode == 0x200B)
  3769. {
  3770. int lastVisibleCharacterIndex = lineInfo.lastVisibleCharacterIndex;
  3771. underline_end = new Vector3(m_textInfo.characterInfo[lastVisibleCharacterIndex].topRight.x, underlineBaseLine, 0);
  3772. underlineEndScale = m_textInfo.characterInfo[lastVisibleCharacterIndex].scale;
  3773. }
  3774. else
  3775. { // End underline if last character of the line.
  3776. underline_end = new Vector3(m_textInfo.characterInfo[i].topRight.x, underlineBaseLine, 0);
  3777. underlineEndScale = m_textInfo.characterInfo[i].scale;
  3778. }
  3779. beginUnderline = false;
  3780. DrawUnderlineMesh(underline_start, underline_end, ref last_vert_index, underlineStartScale, underlineEndScale, underlineMaxScale, xScaleMax, underlineColor);
  3781. underlineMaxScale = 0;
  3782. xScaleMax = 0;
  3783. underlineBaseLine = k_LargePositiveFloat;
  3784. }
  3785. else if (beginUnderline && !isUnderlineVisible)
  3786. {
  3787. beginUnderline = false;
  3788. underline_end = new Vector3(m_textInfo.characterInfo[i - 1].topRight.x, underlineBaseLine, 0);
  3789. underlineEndScale = m_textInfo.characterInfo[i - 1].scale;
  3790. DrawUnderlineMesh(underline_start, underline_end, ref last_vert_index, underlineStartScale, underlineEndScale, underlineMaxScale, xScaleMax, underlineColor);
  3791. underlineMaxScale = 0;
  3792. xScaleMax = 0;
  3793. underlineBaseLine = k_LargePositiveFloat;
  3794. }
  3795. else if (beginUnderline && i < m_characterCount - 1 && !underlineColor.Compare(m_textInfo.characterInfo[i + 1].underlineColor))
  3796. {
  3797. // End underline if underline color has changed.
  3798. beginUnderline = false;
  3799. underline_end = new Vector3(m_textInfo.characterInfo[i].topRight.x, underlineBaseLine, 0);
  3800. underlineEndScale = m_textInfo.characterInfo[i].scale;
  3801. DrawUnderlineMesh(underline_start, underline_end, ref last_vert_index, underlineStartScale, underlineEndScale, underlineMaxScale, xScaleMax, underlineColor);
  3802. underlineMaxScale = 0;
  3803. xScaleMax = 0;
  3804. underlineBaseLine = k_LargePositiveFloat;
  3805. }
  3806. }
  3807. else
  3808. {
  3809. // End Underline
  3810. if (beginUnderline == true)
  3811. {
  3812. beginUnderline = false;
  3813. underline_end = new Vector3(m_textInfo.characterInfo[i - 1].topRight.x, underlineBaseLine, 0);
  3814. underlineEndScale = m_textInfo.characterInfo[i - 1].scale;
  3815. DrawUnderlineMesh(underline_start, underline_end, ref last_vert_index, underlineStartScale, underlineEndScale, underlineMaxScale, xScaleMax, underlineColor);
  3816. underlineMaxScale = 0;
  3817. xScaleMax = 0;
  3818. underlineBaseLine = k_LargePositiveFloat;
  3819. }
  3820. }
  3821. #endregion
  3822. // Setup & Handle Strikethrough
  3823. #region Strikethrough
  3824. // NOTE: Need to figure out how underline will be handled with multiple fonts and which font will be used for the underline.
  3825. bool isStrikethrough = (m_textInfo.characterInfo[i].style & FontStyles.Strikethrough) == FontStyles.Strikethrough;
  3826. float strikethroughOffset = currentFontAsset.m_FaceInfo.strikethroughOffset;
  3827. if (isStrikethrough)
  3828. {
  3829. bool isStrikeThroughVisible = true;
  3830. m_textInfo.characterInfo[i].strikethroughVertexIndex = last_vert_index;
  3831. if (i > m_maxVisibleCharacters || currentLine > m_maxVisibleLines || (m_overflowMode == TextOverflowModes.Page && m_textInfo.characterInfo[i].pageNumber + 1 != m_pageToDisplay))
  3832. isStrikeThroughVisible = false;
  3833. if (beginStrikethrough == false && isStrikeThroughVisible && i <= lineInfo.lastVisibleCharacterIndex && unicode != 10 && unicode != 11 && unicode != 13)
  3834. {
  3835. if (i == lineInfo.lastVisibleCharacterIndex && char.IsSeparator(unicode))
  3836. { }
  3837. else
  3838. {
  3839. beginStrikethrough = true;
  3840. strikethroughPointSize = m_textInfo.characterInfo[i].pointSize;
  3841. strikethroughScale = m_textInfo.characterInfo[i].scale;
  3842. strikethrough_start = new Vector3(m_textInfo.characterInfo[i].bottomLeft.x, m_textInfo.characterInfo[i].baseLine + strikethroughOffset * strikethroughScale, 0);
  3843. strikethroughColor = m_textInfo.characterInfo[i].strikethroughColor;
  3844. strikethroughBaseline = m_textInfo.characterInfo[i].baseLine;
  3845. //Debug.Log("Char [" + currentCharacter + "] Start Strikethrough POS: " + strikethrough_start);
  3846. }
  3847. }
  3848. // End Strikethrough if text only contains one character.
  3849. if (beginStrikethrough && m_characterCount == 1)
  3850. {
  3851. beginStrikethrough = false;
  3852. strikethrough_end = new Vector3(m_textInfo.characterInfo[i].topRight.x, m_textInfo.characterInfo[i].baseLine + strikethroughOffset * strikethroughScale, 0);
  3853. DrawUnderlineMesh(strikethrough_start, strikethrough_end, ref last_vert_index, strikethroughScale, strikethroughScale, strikethroughScale, xScale, strikethroughColor);
  3854. }
  3855. else if (beginStrikethrough && i == lineInfo.lastCharacterIndex)
  3856. {
  3857. // Terminate Strikethrough at previous visible character if space or carriage return.
  3858. if (isWhiteSpace || unicode == 0x200B)
  3859. {
  3860. int lastVisibleCharacterIndex = lineInfo.lastVisibleCharacterIndex;
  3861. strikethrough_end = new Vector3(m_textInfo.characterInfo[lastVisibleCharacterIndex].topRight.x, m_textInfo.characterInfo[lastVisibleCharacterIndex].baseLine + strikethroughOffset * strikethroughScale, 0);
  3862. }
  3863. else
  3864. {
  3865. // Terminate Strikethrough at last character of line.
  3866. strikethrough_end = new Vector3(m_textInfo.characterInfo[i].topRight.x, m_textInfo.characterInfo[i].baseLine + strikethroughOffset * strikethroughScale, 0);
  3867. }
  3868. beginStrikethrough = false;
  3869. DrawUnderlineMesh(strikethrough_start, strikethrough_end, ref last_vert_index, strikethroughScale, strikethroughScale, strikethroughScale, xScale, strikethroughColor);
  3870. }
  3871. else if (beginStrikethrough && i < m_characterCount && (m_textInfo.characterInfo[i + 1].pointSize != strikethroughPointSize || !TMP_Math.Approximately(m_textInfo.characterInfo[i + 1].baseLine + offset.y, strikethroughBaseline)))
  3872. {
  3873. // Terminate Strikethrough if scale changes.
  3874. beginStrikethrough = false;
  3875. int lastVisibleCharacterIndex = lineInfo.lastVisibleCharacterIndex;
  3876. if (i > lastVisibleCharacterIndex)
  3877. strikethrough_end = new Vector3(m_textInfo.characterInfo[lastVisibleCharacterIndex].topRight.x, m_textInfo.characterInfo[lastVisibleCharacterIndex].baseLine + strikethroughOffset * strikethroughScale, 0);
  3878. else
  3879. strikethrough_end = new Vector3(m_textInfo.characterInfo[i].topRight.x, m_textInfo.characterInfo[i].baseLine + strikethroughOffset * strikethroughScale, 0);
  3880. DrawUnderlineMesh(strikethrough_start, strikethrough_end, ref last_vert_index, strikethroughScale, strikethroughScale, strikethroughScale, xScale, strikethroughColor);
  3881. //Debug.Log("Char [" + currentCharacter + "] at Index: " + i + " End Strikethrough POS: " + strikethrough_end + " Baseline: " + m_textInfo.characterInfo[i].baseLine.ToString("f3"));
  3882. }
  3883. else if (beginStrikethrough && i < m_characterCount && currentFontAsset.GetInstanceID() != characterInfos[i + 1].fontAsset.GetInstanceID())
  3884. {
  3885. // Terminate Strikethrough if font asset changes.
  3886. beginStrikethrough = false;
  3887. strikethrough_end = new Vector3(m_textInfo.characterInfo[i].topRight.x, m_textInfo.characterInfo[i].baseLine + strikethroughOffset * strikethroughScale, 0);
  3888. DrawUnderlineMesh(strikethrough_start, strikethrough_end, ref last_vert_index, strikethroughScale, strikethroughScale, strikethroughScale, xScale, strikethroughColor);
  3889. }
  3890. else if (beginStrikethrough && !isStrikeThroughVisible)
  3891. {
  3892. // Terminate Strikethrough if character is not visible.
  3893. beginStrikethrough = false;
  3894. strikethrough_end = new Vector3(m_textInfo.characterInfo[i - 1].topRight.x, m_textInfo.characterInfo[i - 1].baseLine + strikethroughOffset * strikethroughScale, 0);
  3895. DrawUnderlineMesh(strikethrough_start, strikethrough_end, ref last_vert_index, strikethroughScale, strikethroughScale, strikethroughScale, xScale, strikethroughColor);
  3896. }
  3897. }
  3898. else
  3899. {
  3900. // End Strikethrough
  3901. if (beginStrikethrough == true)
  3902. {
  3903. beginStrikethrough = false;
  3904. strikethrough_end = new Vector3(m_textInfo.characterInfo[i - 1].topRight.x, m_textInfo.characterInfo[i - 1].baseLine + strikethroughOffset * strikethroughScale, 0);
  3905. DrawUnderlineMesh(strikethrough_start, strikethrough_end, ref last_vert_index, strikethroughScale, strikethroughScale, strikethroughScale, xScale, strikethroughColor);
  3906. }
  3907. }
  3908. #endregion
  3909. // HANDLE TEXT HIGHLIGHTING
  3910. #region Text Highlighting
  3911. bool isHighlight = (m_textInfo.characterInfo[i].style & FontStyles.Highlight) == FontStyles.Highlight;
  3912. if (isHighlight)
  3913. {
  3914. bool isHighlightVisible = true;
  3915. int currentPage = m_textInfo.characterInfo[i].pageNumber;
  3916. if (i > m_maxVisibleCharacters || currentLine > m_maxVisibleLines || (m_overflowMode == TextOverflowModes.Page && currentPage + 1 != m_pageToDisplay))
  3917. isHighlightVisible = false;
  3918. if (beginHighlight == false && isHighlightVisible == true && i <= lineInfo.lastVisibleCharacterIndex && unicode != 10 && unicode != 11 && unicode != 13)
  3919. {
  3920. if (i == lineInfo.lastVisibleCharacterIndex && char.IsSeparator(unicode))
  3921. { }
  3922. else
  3923. {
  3924. beginHighlight = true;
  3925. highlight_start = k_LargePositiveVector2;
  3926. highlight_end = k_LargeNegativeVector2;
  3927. highlightState = m_textInfo.characterInfo[i].highlightState;
  3928. }
  3929. }
  3930. if (beginHighlight)
  3931. {
  3932. TMP_CharacterInfo currentCharacter = m_textInfo.characterInfo[i];
  3933. HighlightState currentState = currentCharacter.highlightState;
  3934. bool isColorTransition = false;
  3935. // Handle Highlight color changes
  3936. if (highlightState != currentState)
  3937. {
  3938. // Adjust previous highlight section to prevent a gaps between sections.
  3939. if (isWhiteSpace)
  3940. highlight_end.x = (highlight_end.x - highlightState.padding.right + currentCharacter.origin) / 2;
  3941. else
  3942. highlight_end.x = (highlight_end.x - highlightState.padding.right + currentCharacter.bottomLeft.x) / 2;
  3943. highlight_start.y = Mathf.Min(highlight_start.y, currentCharacter.descender);
  3944. highlight_end.y = Mathf.Max(highlight_end.y, currentCharacter.ascender);
  3945. DrawTextHighlight(highlight_start, highlight_end, ref last_vert_index, highlightState.color);
  3946. beginHighlight = true;
  3947. highlight_start = new Vector2(highlight_end.x, currentCharacter.descender - currentState.padding.bottom);
  3948. if (isWhiteSpace)
  3949. highlight_end = new Vector2(currentCharacter.xAdvance + currentState.padding.right, currentCharacter.ascender + currentState.padding.top);
  3950. else
  3951. highlight_end = new Vector2(currentCharacter.topRight.x + currentState.padding.right, currentCharacter.ascender + currentState.padding.top);
  3952. highlightState = currentState;
  3953. isColorTransition = true;
  3954. }
  3955. if (!isColorTransition)
  3956. {
  3957. if (isWhiteSpace)
  3958. {
  3959. // Use the Min / Max of glyph metrics if white space.
  3960. highlight_start.x = Mathf.Min(highlight_start.x, currentCharacter.origin - highlightState.padding.left);
  3961. highlight_end.x = Mathf.Max(highlight_end.x, currentCharacter.xAdvance + highlightState.padding.right);
  3962. }
  3963. else
  3964. {
  3965. // Use the Min / Max of character bounds
  3966. highlight_start.x = Mathf.Min(highlight_start.x, currentCharacter.bottomLeft.x - highlightState.padding.left);
  3967. highlight_end.x = Mathf.Max(highlight_end.x, currentCharacter.topRight.x + highlightState.padding.right);
  3968. }
  3969. highlight_start.y = Mathf.Min(highlight_start.y, currentCharacter.descender - highlightState.padding.bottom);
  3970. highlight_end.y = Mathf.Max(highlight_end.y, currentCharacter.ascender + highlightState.padding.top);
  3971. }
  3972. }
  3973. // End Highlight if text only contains one character.
  3974. if (beginHighlight && m_characterCount == 1)
  3975. {
  3976. beginHighlight = false;
  3977. DrawTextHighlight(highlight_start, highlight_end, ref last_vert_index, highlightState.color);
  3978. }
  3979. else if (beginHighlight && (i == lineInfo.lastCharacterIndex || i >= lineInfo.lastVisibleCharacterIndex))
  3980. {
  3981. beginHighlight = false;
  3982. DrawTextHighlight(highlight_start, highlight_end, ref last_vert_index, highlightState.color);
  3983. }
  3984. else if (beginHighlight && !isHighlightVisible)
  3985. {
  3986. beginHighlight = false;
  3987. DrawTextHighlight(highlight_start, highlight_end, ref last_vert_index, highlightState.color);
  3988. }
  3989. }
  3990. else
  3991. {
  3992. // End Highlight
  3993. if (beginHighlight == true)
  3994. {
  3995. beginHighlight = false;
  3996. DrawTextHighlight(highlight_start, highlight_end, ref last_vert_index, highlightState.color);
  3997. }
  3998. }
  3999. #endregion
  4000. lastLine = currentLine;
  4001. }
  4002. #endregion
  4003. // Set vertex count for Underline geometry
  4004. m_textInfo.meshInfo[m_Underline.materialIndex].vertexCount = last_vert_index;
  4005. // METRICS ABOUT THE TEXT OBJECT
  4006. m_textInfo.characterCount = m_characterCount;
  4007. m_textInfo.spriteCount = m_spriteCount;
  4008. m_textInfo.lineCount = lineCount;
  4009. m_textInfo.wordCount = wordCount != 0 && m_characterCount > 0 ? wordCount : 1;
  4010. m_textInfo.pageCount = m_pageNumber + 1;
  4011. // End Sampling of Phase II
  4012. k_GenerateTextPhaseIIMarker.End();
  4013. // Phase III - Update Mesh Vertex Data
  4014. k_GenerateTextPhaseIIIMarker.Begin();
  4015. if (m_renderMode == TextRenderFlags.Render && IsActive())
  4016. {
  4017. // Event to allow users to modify the content of the text info before the text is rendered.
  4018. OnPreRenderText?.Invoke(m_textInfo);
  4019. // Sort the geometry of the text object if needed.
  4020. if (m_geometrySortingOrder != VertexSortingOrder.Normal)
  4021. m_textInfo.meshInfo[0].SortGeometry(VertexSortingOrder.Reverse);
  4022. // Upload Mesh Data
  4023. m_mesh.MarkDynamic();
  4024. m_mesh.vertices = m_textInfo.meshInfo[0].vertices;
  4025. m_mesh.SetUVs(0, m_textInfo.meshInfo[0].uvs0);
  4026. m_mesh.uv2 = m_textInfo.meshInfo[0].uvs2;
  4027. //m_mesh.uv4 = m_textInfo.meshInfo[0].uvs4;
  4028. m_mesh.colors32 = m_textInfo.meshInfo[0].colors32;
  4029. // Compute Bounds for the mesh. Manual computation is more efficient then using Mesh.RecalculteBounds.
  4030. m_mesh.RecalculateBounds();
  4031. //m_mesh.bounds = new Bounds(new Vector3((m_meshExtents.max.x + m_meshExtents.min.x) / 2, (m_meshExtents.max.y + m_meshExtents.min.y) / 2, 0) + offset, new Vector3(m_meshExtents.max.x - m_meshExtents.min.x, m_meshExtents.max.y - m_meshExtents.min.y, 0));
  4032. for (int i = 1; i < m_textInfo.materialCount; i++)
  4033. {
  4034. // Clear unused vertices
  4035. m_textInfo.meshInfo[i].ClearUnusedVertices();
  4036. if (m_subTextObjects[i] == null) continue;
  4037. // Sort the geometry of the sub-text objects if needed.
  4038. if (m_geometrySortingOrder != VertexSortingOrder.Normal)
  4039. m_textInfo.meshInfo[i].SortGeometry(VertexSortingOrder.Reverse);
  4040. m_subTextObjects[i].mesh.vertices = m_textInfo.meshInfo[i].vertices;
  4041. m_subTextObjects[i].mesh.SetUVs(0, m_textInfo.meshInfo[i].uvs0);
  4042. m_subTextObjects[i].mesh.uv2 = m_textInfo.meshInfo[i].uvs2;
  4043. //m_subTextObjects[i].mesh.uv4 = m_textInfo.meshInfo[i].uvs4;
  4044. m_subTextObjects[i].mesh.colors32 = m_textInfo.meshInfo[i].colors32;
  4045. m_subTextObjects[i].mesh.RecalculateBounds();
  4046. // Update the collider on the sub text object
  4047. //m_subTextObjects[i].UpdateColliders(m_textInfo.meshInfo[i].vertexCount);
  4048. }
  4049. }
  4050. // Event indicating the text has been regenerated.
  4051. TMPro_EventManager.ON_TEXT_CHANGED(this);
  4052. //Debug.Log("***** Done rendering text object ID " + GetInstanceID() + ". *****");
  4053. // Clear allocations no longer necessary given the text object is static
  4054. // if (true)
  4055. // {
  4056. // m_isInputParsingRequired = true;
  4057. // m_textInfo.ClearAllData();
  4058. // }
  4059. // End Sampling
  4060. k_GenerateTextPhaseIIIMarker.End();
  4061. k_GenerateTextMarker.End();
  4062. }
  4063. /// <summary>
  4064. /// Method to return the local corners of the Text Container or RectTransform.
  4065. /// </summary>
  4066. /// <returns></returns>
  4067. protected override Vector3[] GetTextContainerLocalCorners()
  4068. {
  4069. if (m_rectTransform == null) m_rectTransform = this.rectTransform;
  4070. m_rectTransform.GetLocalCorners(m_RectTransformCorners);
  4071. return m_RectTransformCorners;
  4072. }
  4073. /// <summary>
  4074. /// Method to disable the renderers.
  4075. /// </summary>
  4076. void SetMeshFilters(bool state)
  4077. {
  4078. // Parent text object
  4079. if (m_meshFilter != null)
  4080. {
  4081. if (state)
  4082. m_meshFilter.sharedMesh = m_mesh;
  4083. else
  4084. m_meshFilter.sharedMesh = null;
  4085. }
  4086. for (int i = 1; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
  4087. {
  4088. if (m_subTextObjects[i].meshFilter != null)
  4089. {
  4090. if (state)
  4091. m_subTextObjects[i].meshFilter.sharedMesh = m_subTextObjects[i].mesh;
  4092. else
  4093. m_subTextObjects[i].meshFilter.sharedMesh = null;
  4094. }
  4095. }
  4096. }
  4097. /// <summary>
  4098. /// Method to Enable or Disable child SubMesh objects.
  4099. /// </summary>
  4100. /// <param name="state"></param>
  4101. protected override void SetActiveSubMeshes(bool state)
  4102. {
  4103. for (int i = 1; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
  4104. {
  4105. if (m_subTextObjects[i].enabled != state)
  4106. m_subTextObjects[i].enabled = state;
  4107. }
  4108. }
  4109. protected void SetActiveSubTextObjectRenderers(bool state)
  4110. {
  4111. for (int i = 1; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
  4112. {
  4113. Renderer subMeshRenderer = m_subTextObjects[i].renderer;
  4114. if (subMeshRenderer != null && subMeshRenderer.enabled != state)
  4115. subMeshRenderer.enabled = state;
  4116. }
  4117. }
  4118. /// <summary>
  4119. /// Destroy Sub Mesh Objects
  4120. /// </summary>
  4121. protected override void DestroySubMeshObjects()
  4122. {
  4123. for (int i = 1; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
  4124. DestroyImmediate(m_subTextObjects[i]);
  4125. }
  4126. /// <summary>
  4127. ///
  4128. /// </summary>
  4129. internal void UpdateSubMeshSortingLayerID(int id)
  4130. {
  4131. for (int i = 1; i < m_subTextObjects.Length; i++)
  4132. {
  4133. TMP_SubMesh subMesh = m_subTextObjects[i];
  4134. if (subMesh != null && subMesh.renderer != null)
  4135. {
  4136. subMesh.renderer.sortingLayerID = id;
  4137. }
  4138. }
  4139. }
  4140. /// <summary>
  4141. ///
  4142. /// </summary>
  4143. internal void UpdateSubMeshSortingOrder(int order)
  4144. {
  4145. for (int i = 1; i < m_subTextObjects.Length; i++)
  4146. {
  4147. TMP_SubMesh subMesh = m_subTextObjects[i];
  4148. if (subMesh != null && subMesh.renderer != null)
  4149. {
  4150. subMesh.renderer.sortingOrder = order;
  4151. }
  4152. }
  4153. }
  4154. /// <summary>
  4155. /// Method returning the compound bounds of the text object and child sub objects.
  4156. /// </summary>
  4157. /// <returns></returns>
  4158. protected override Bounds GetCompoundBounds()
  4159. {
  4160. Bounds mainBounds = m_mesh.bounds;
  4161. Vector3 min = mainBounds.min;
  4162. Vector3 max = mainBounds.max;
  4163. for (int i = 1; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
  4164. {
  4165. Bounds subBounds = m_subTextObjects[i].mesh.bounds;
  4166. min.x = min.x < subBounds.min.x ? min.x : subBounds.min.x;
  4167. min.y = min.y < subBounds.min.y ? min.y : subBounds.min.y;
  4168. max.x = max.x > subBounds.max.x ? max.x : subBounds.max.x;
  4169. max.y = max.y > subBounds.max.y ? max.y : subBounds.max.y;
  4170. }
  4171. Vector3 center = (min + max) / 2;
  4172. Vector2 size = max - min;
  4173. return new Bounds(center, size);
  4174. }
  4175. /// <summary>
  4176. /// Method to Update Scale in UV2
  4177. /// </summary>
  4178. //void UpdateSDFScale(float lossyScale)
  4179. //{
  4180. // // TODO: Resolve - Underline / Strikethrough segments not getting their SDF Scale adjusted.
  4181. // //Debug.Log("*** UpdateSDFScale() ***");
  4182. // // Iterate through each of the characters.
  4183. // for (int i = 0; i < m_textInfo.characterCount; i++)
  4184. // {
  4185. // // Only update scale for visible characters.
  4186. // if (m_textInfo.characterInfo[i].isVisible && m_textInfo.characterInfo[i].elementType == TMP_TextElementType.Character)
  4187. // {
  4188. // float scale = lossyScale * m_textInfo.characterInfo[i].scale * (1 - m_charWidthAdjDelta);
  4189. // if (!m_textInfo.characterInfo[i].isUsingAlternateTypeface && (m_textInfo.characterInfo[i].style & FontStyles.Bold) == FontStyles.Bold) scale *= -1;
  4190. // int index = m_textInfo.characterInfo[i].materialReferenceIndex;
  4191. // int vertexIndex = m_textInfo.characterInfo[i].vertexIndex;
  4192. // m_textInfo.meshInfo[index].uvs2[vertexIndex + 0].y = scale;
  4193. // m_textInfo.meshInfo[index].uvs2[vertexIndex + 1].y = scale;
  4194. // m_textInfo.meshInfo[index].uvs2[vertexIndex + 2].y = scale;
  4195. // m_textInfo.meshInfo[index].uvs2[vertexIndex + 3].y = scale;
  4196. // }
  4197. // }
  4198. // // Push the updated uv2 scale information to the meshes.
  4199. // for (int i = 0; i < m_textInfo.meshInfo.Length; i++)
  4200. // {
  4201. // if (i == 0)
  4202. // m_mesh.uv2 = m_textInfo.meshInfo[0].uvs2;
  4203. // else
  4204. // m_subTextObjects[i].mesh.uv2 = m_textInfo.meshInfo[i].uvs2;
  4205. // }
  4206. //}
  4207. /// <summary>
  4208. /// Method to update the SDF Scale in UV2.
  4209. /// </summary>
  4210. /// <param name="scaleDelta"></param>
  4211. void UpdateSDFScale(float scaleDelta)
  4212. {
  4213. if (scaleDelta == 0 || scaleDelta == float.PositiveInfinity || scaleDelta == float.NegativeInfinity)
  4214. {
  4215. m_havePropertiesChanged = true;
  4216. OnPreRenderObject();
  4217. return;
  4218. }
  4219. for (int materialIndex = 0; materialIndex < m_textInfo.materialCount; materialIndex++)
  4220. {
  4221. TMP_MeshInfo meshInfo = m_textInfo.meshInfo[materialIndex];
  4222. for (int i = 0; i < meshInfo.uvs0.Length; i++)
  4223. {
  4224. meshInfo.uvs0[i].w *= Mathf.Abs(scaleDelta);
  4225. }
  4226. }
  4227. // Push the updated uv0 scale information to the meshes.
  4228. for (int i = 0; i < m_textInfo.meshInfo.Length; i++)
  4229. {
  4230. if (i == 0)
  4231. m_mesh.SetUVs(0, m_textInfo.meshInfo[0].uvs0);
  4232. else
  4233. m_subTextObjects[i].mesh.SetUVs(0, m_textInfo.meshInfo[i].uvs0);
  4234. }
  4235. }
  4236. #endregion
  4237. }
  4238. }