暫無描述
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.

TMP_FontAsset.cs 123KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080
  1. using System;
  2. using UnityEngine;
  3. using UnityEngine.Serialization;
  4. using UnityEngine.TextCore;
  5. using UnityEngine.TextCore.LowLevel;
  6. using Unity.Profiling;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. #if UNITY_EDITOR && UNITY_2018_4_OR_NEWER && !UNITY_2018_4_0 && !UNITY_2018_4_1 && !UNITY_2018_4_2 && !UNITY_2018_4_3 && !UNITY_2018_4_4
  10. using UnityEditor.TextCore.LowLevel;
  11. #endif
  12. namespace TMPro
  13. {
  14. public enum AtlasPopulationMode
  15. {
  16. Static = 0x0,
  17. Dynamic = 0x1,
  18. }
  19. [Serializable][ExcludeFromPresetAttribute]
  20. public class TMP_FontAsset : TMP_Asset
  21. {
  22. /// <summary>
  23. /// The version of the font asset class.
  24. /// Version 1.1.0 adds support for the new TextCore.FontEngine and Dynamic SDF system.
  25. /// </summary>
  26. public string version
  27. {
  28. get { return m_Version; }
  29. internal set { m_Version = value; }
  30. }
  31. [SerializeField]
  32. private string m_Version;
  33. /// <summary>
  34. /// This field is set when the font asset is first created.
  35. /// </summary>
  36. [SerializeField]
  37. internal string m_SourceFontFileGUID;
  38. #if UNITY_EDITOR
  39. /// <summary>
  40. /// Persistent reference to the source font file maintained in the editor.
  41. /// </summary>
  42. [SerializeField]
  43. internal Font m_SourceFontFile_EditorRef;
  44. #endif
  45. /// <summary>
  46. /// Source font file when atlas population mode is set to dynamic. Null when the atlas population mode is set to static.
  47. /// </summary>
  48. public Font sourceFontFile
  49. {
  50. get { return m_SourceFontFile; }
  51. internal set { m_SourceFontFile = value; }
  52. }
  53. [SerializeField]
  54. private Font m_SourceFontFile;
  55. public AtlasPopulationMode atlasPopulationMode
  56. {
  57. get { return m_AtlasPopulationMode; }
  58. set
  59. {
  60. m_AtlasPopulationMode = value;
  61. #if UNITY_EDITOR
  62. if (m_AtlasPopulationMode == AtlasPopulationMode.Static)
  63. m_SourceFontFile = null;
  64. else if (m_AtlasPopulationMode == AtlasPopulationMode.Dynamic)
  65. m_SourceFontFile = m_SourceFontFile_EditorRef;
  66. #endif
  67. }
  68. }
  69. [SerializeField]
  70. private AtlasPopulationMode m_AtlasPopulationMode;
  71. /// <summary>
  72. /// Information about the font's face.
  73. /// </summary>
  74. public FaceInfo faceInfo
  75. {
  76. get { return m_FaceInfo; }
  77. set { m_FaceInfo = value; }
  78. }
  79. [SerializeField]
  80. internal FaceInfo m_FaceInfo;
  81. /// <summary>
  82. /// List of glyphs contained in the font asset.
  83. /// </summary>
  84. public List<Glyph> glyphTable
  85. {
  86. get { return m_GlyphTable; }
  87. internal set { m_GlyphTable = value; }
  88. }
  89. [SerializeField]
  90. internal List<Glyph> m_GlyphTable = new List<Glyph>();
  91. /// <summary>
  92. /// Dictionary used to lookup glyphs contained in the font asset by their index.
  93. /// </summary>
  94. public Dictionary<uint, Glyph> glyphLookupTable
  95. {
  96. get
  97. {
  98. if (m_GlyphLookupDictionary == null)
  99. ReadFontAssetDefinition();
  100. return m_GlyphLookupDictionary;
  101. }
  102. }
  103. internal Dictionary<uint, Glyph> m_GlyphLookupDictionary;
  104. /// <summary>
  105. /// List containing the characters of the given font asset.
  106. /// </summary>
  107. public List<TMP_Character> characterTable
  108. {
  109. get { return m_CharacterTable; }
  110. internal set { m_CharacterTable = value; }
  111. }
  112. [SerializeField]
  113. internal List<TMP_Character> m_CharacterTable = new List<TMP_Character>();
  114. /// <summary>
  115. /// Dictionary used to lookup characters contained in the font asset by their unicode values.
  116. /// </summary>
  117. public Dictionary<uint, TMP_Character> characterLookupTable
  118. {
  119. get
  120. {
  121. if (m_CharacterLookupDictionary == null)
  122. ReadFontAssetDefinition();
  123. return m_CharacterLookupDictionary;
  124. }
  125. }
  126. internal Dictionary<uint, TMP_Character> m_CharacterLookupDictionary;
  127. /// <summary>
  128. /// Determines if the font asset is using a shared atlas texture(s)
  129. /// </summary>
  130. //public bool isUsingDynamicTextures
  131. //{
  132. // get { return m_IsUsingDynamicTextures; }
  133. // set { m_IsUsingDynamicTextures = value; }
  134. //}
  135. //[SerializeField]
  136. //private bool m_IsUsingDynamicTextures;
  137. /// <summary>
  138. /// The font atlas used by this font asset.
  139. /// This is always the texture at index [0] of the fontAtlasTextures.
  140. /// </summary>
  141. public Texture2D atlasTexture
  142. {
  143. get
  144. {
  145. if (m_AtlasTexture == null)
  146. {
  147. m_AtlasTexture = atlasTextures[0];
  148. }
  149. return m_AtlasTexture;
  150. }
  151. }
  152. internal Texture2D m_AtlasTexture;
  153. /// <summary>
  154. /// Array of atlas textures that contain the glyphs used by this font asset.
  155. /// </summary>
  156. public Texture2D[] atlasTextures
  157. {
  158. get
  159. {
  160. if (m_AtlasTextures == null)
  161. {
  162. //
  163. }
  164. //if (m_IsUsingDynamicTextures)
  165. // return TMP_DynamicAtlasTextureGroup.managedDynamicTextures;
  166. return m_AtlasTextures;
  167. }
  168. set
  169. {
  170. m_AtlasTextures = value;
  171. }
  172. }
  173. [SerializeField]
  174. internal Texture2D[] m_AtlasTextures;
  175. /// <summary>
  176. /// Index of the font atlas texture that still has available space to add new glyphs.
  177. /// </summary>
  178. [SerializeField]
  179. internal int m_AtlasTextureIndex;
  180. /// <summary>
  181. /// Number of atlas textures used by this font asset.
  182. /// </summary>
  183. public int atlasTextureCount { get { return m_AtlasTextureIndex + 1; } }
  184. /// <summary>
  185. /// Enables the font asset to create additional atlas textures as needed.
  186. /// </summary>
  187. public bool isMultiAtlasTexturesEnabled
  188. {
  189. get { return m_IsMultiAtlasTexturesEnabled; }
  190. set { m_IsMultiAtlasTexturesEnabled = value; }
  191. }
  192. [SerializeField]
  193. private bool m_IsMultiAtlasTexturesEnabled;
  194. /// <summary>
  195. /// Determines if dynamic font asset data should be cleared before builds.
  196. /// </summary>
  197. internal bool clearDynamicDataOnBuild
  198. {
  199. get { return m_ClearDynamicDataOnBuild; }
  200. set { m_ClearDynamicDataOnBuild = value; }
  201. }
  202. [SerializeField]
  203. private bool m_ClearDynamicDataOnBuild;
  204. /// <summary>
  205. /// List of spaces occupied by glyphs in a given texture.
  206. /// </summary>
  207. internal List<GlyphRect> usedGlyphRects
  208. {
  209. get { return m_UsedGlyphRects; }
  210. set { m_UsedGlyphRects = value; }
  211. }
  212. [SerializeField]
  213. private List<GlyphRect> m_UsedGlyphRects;
  214. /// <summary>
  215. /// List of spaces available in a given texture to add new glyphs.
  216. /// </summary>
  217. internal List<GlyphRect> freeGlyphRects
  218. {
  219. get { return m_FreeGlyphRects; }
  220. set { m_FreeGlyphRects = value; }
  221. }
  222. [SerializeField]
  223. private List<GlyphRect> m_FreeGlyphRects;
  224. /// <summary>
  225. /// The general information about the font.
  226. /// This property and FaceInfo_Legacy type are no longer used in version 1.1.0 of the font asset.
  227. /// </summary>
  228. [Obsolete("The fontInfo property and underlying type is now obsolete. Please use the faceInfo property and FaceInfo type instead.")]
  229. public FaceInfo_Legacy fontInfo
  230. {
  231. get { return m_fontInfo; }
  232. }
  233. [SerializeField]
  234. private FaceInfo_Legacy m_fontInfo = null;
  235. /// <summary>
  236. ///
  237. /// </summary>
  238. [SerializeField]
  239. public Texture2D atlas; // Should add a property to make this read-only.
  240. /// <summary>
  241. /// The width of the atlas texture(s) used by this font asset.
  242. /// </summary>
  243. public int atlasWidth
  244. {
  245. get { return m_AtlasWidth; }
  246. internal set { m_AtlasWidth = value; }
  247. }
  248. [SerializeField]
  249. internal int m_AtlasWidth;
  250. /// <summary>
  251. /// The height of the atlas texture(s) used by this font asset.
  252. /// </summary>
  253. public int atlasHeight
  254. {
  255. get { return m_AtlasHeight; }
  256. internal set { m_AtlasHeight = value; }
  257. }
  258. [SerializeField]
  259. internal int m_AtlasHeight;
  260. /// <summary>
  261. /// The padding used between glyphs contained in the atlas texture(s) used by this font asset.
  262. /// </summary>
  263. public int atlasPadding
  264. {
  265. get { return m_AtlasPadding; }
  266. internal set { m_AtlasPadding = value; }
  267. }
  268. [SerializeField]
  269. internal int m_AtlasPadding;
  270. public GlyphRenderMode atlasRenderMode
  271. {
  272. get { return m_AtlasRenderMode; }
  273. internal set { m_AtlasRenderMode = value; }
  274. }
  275. [SerializeField]
  276. internal GlyphRenderMode m_AtlasRenderMode;
  277. // Legacy field that will eventually be removed.
  278. [SerializeField]
  279. internal List<TMP_Glyph> m_glyphInfoList;
  280. [SerializeField]
  281. [FormerlySerializedAs("m_kerningInfo")]
  282. internal KerningTable m_KerningTable = new KerningTable();
  283. /// <summary>
  284. /// Table containing the various font features of this font asset.
  285. /// </summary>
  286. public TMP_FontFeatureTable fontFeatureTable
  287. {
  288. get { return m_FontFeatureTable; }
  289. internal set { m_FontFeatureTable = value; }
  290. }
  291. [SerializeField]
  292. internal TMP_FontFeatureTable m_FontFeatureTable = new TMP_FontFeatureTable();
  293. // Legacy field that will eventually be removed
  294. [SerializeField]
  295. #pragma warning disable 0649
  296. private List<TMP_FontAsset> fallbackFontAssets;
  297. /// <summary>
  298. /// List containing the Fallback font assets for this font.
  299. /// </summary>
  300. public List<TMP_FontAsset> fallbackFontAssetTable
  301. {
  302. get { return m_FallbackFontAssetTable; }
  303. set { m_FallbackFontAssetTable = value; }
  304. }
  305. [SerializeField]
  306. internal List<TMP_FontAsset> m_FallbackFontAssetTable;
  307. /// <summary>
  308. /// The settings used in the Font Asset Creator when this font asset was created or edited.
  309. /// </summary>
  310. public FontAssetCreationSettings creationSettings
  311. {
  312. get { return m_CreationSettings; }
  313. set { m_CreationSettings = value; }
  314. }
  315. [SerializeField]
  316. internal FontAssetCreationSettings m_CreationSettings;
  317. /// <summary>
  318. /// Array containing font assets to be used as alternative typefaces for the various potential font weights of this font asset.
  319. /// </summary>
  320. public TMP_FontWeightPair[] fontWeightTable
  321. {
  322. get { return m_FontWeightTable; }
  323. internal set { m_FontWeightTable = value; }
  324. }
  325. [SerializeField]
  326. private TMP_FontWeightPair[] m_FontWeightTable = new TMP_FontWeightPair[10];
  327. // FONT WEIGHTS
  328. /// <summary>
  329. /// Font weights used by font asset prior to version 1.1.0.
  330. /// This is legacy and will be removed at some point in the future.
  331. /// </summary>
  332. [SerializeField]
  333. private TMP_FontWeightPair[] fontWeights = null;
  334. //private int[] m_characterSet; // Array containing all the characters in this font asset.
  335. /// <summary>
  336. /// Defines the dilation of the text when using regular style.
  337. /// </summary>
  338. public float normalStyle = 0;
  339. /// <summary>
  340. /// The spacing between characters when using regular style.
  341. /// </summary>
  342. public float normalSpacingOffset = 0;
  343. /// <summary>
  344. /// Defines the dilation of the text when using bold style.
  345. /// </summary>
  346. public float boldStyle = 0.75f;
  347. /// <summary>
  348. /// The spacing between characters when using regular style.
  349. /// </summary>
  350. public float boldSpacing = 7f;
  351. /// <summary>
  352. /// Defines the slant of the text when using italic style.
  353. /// </summary>
  354. public byte italicStyle = 35;
  355. public byte tabSize = 10;
  356. internal bool IsFontAssetLookupTablesDirty;
  357. // Profiler Marker declarations
  358. private static ProfilerMarker k_ReadFontAssetDefinitionMarker = new ProfilerMarker("TMP.ReadFontAssetDefinition");
  359. private static ProfilerMarker k_AddSynthesizedCharactersMarker = new ProfilerMarker("TMP.AddSynthesizedCharacters");
  360. private static ProfilerMarker k_TryAddCharacterMarker = new ProfilerMarker("TMP.TryAddCharacter");
  361. private static ProfilerMarker k_TryAddCharactersMarker = new ProfilerMarker("TMP.TryAddCharacters");
  362. private static ProfilerMarker k_UpdateGlyphAdjustmentRecordsMarker = new ProfilerMarker("TMP.UpdateGlyphAdjustmentRecords");
  363. private static ProfilerMarker k_ClearFontAssetDataMarker = new ProfilerMarker("TMP.ClearFontAssetData");
  364. private static ProfilerMarker k_UpdateFontAssetDataMarker = new ProfilerMarker("TMP.UpdateFontAssetData");
  365. /// <summary>
  366. /// Create new instance of a font asset using default settings.
  367. /// </summary>
  368. /// <param name="font"></param>
  369. /// <returns></returns>
  370. public static TMP_FontAsset CreateFontAsset(Font font)
  371. {
  372. return CreateFontAsset(font, 90, 9, GlyphRenderMode.SDFAA, 1024, 1024, AtlasPopulationMode.Dynamic);
  373. }
  374. /// <summary>
  375. /// Create new instance of a font asset.
  376. /// </summary>
  377. /// <param name="font">The source font file.</param>
  378. /// <param name="samplingPointSize">The sampling point size.</param>
  379. /// <param name="atlasPadding">The padding / spread between individual glyphs in the font asset.</param>
  380. /// <param name="renderMode"></param>
  381. /// <param name="atlasWidth">The atlas texture width.</param>
  382. /// <param name="atlasHeight">The atlas texture height.</param>
  383. /// <param name="atlasPopulationMode"></param>
  384. /// <returns></returns>
  385. public static TMP_FontAsset CreateFontAsset(Font font, int samplingPointSize, int atlasPadding, GlyphRenderMode renderMode, int atlasWidth, int atlasHeight, AtlasPopulationMode atlasPopulationMode = AtlasPopulationMode.Dynamic, bool enableMultiAtlasSupport = true)
  386. {
  387. // Initialize FontEngine
  388. FontEngine.InitializeFontEngine();
  389. // Load Font Face
  390. if (FontEngine.LoadFontFace(font, samplingPointSize) != FontEngineError.Success)
  391. {
  392. Debug.LogWarning("Unable to load font face for [" + font.name + "]. Make sure \"Include Font Data\" is enabled in the Font Import Settings.", font);
  393. return null;
  394. }
  395. // Create new font asset
  396. TMP_FontAsset fontAsset = ScriptableObject.CreateInstance<TMP_FontAsset>();
  397. fontAsset.m_Version = "1.1.0";
  398. fontAsset.faceInfo = FontEngine.GetFaceInfo();
  399. // Set font reference and GUID
  400. if (atlasPopulationMode == AtlasPopulationMode.Dynamic)
  401. fontAsset.sourceFontFile = font;
  402. // Set persistent reference to source font file in the Editor only.
  403. #if UNITY_EDITOR
  404. string guid;
  405. long localID;
  406. UnityEditor.AssetDatabase.TryGetGUIDAndLocalFileIdentifier(font, out guid, out localID);
  407. fontAsset.m_SourceFontFileGUID = guid;
  408. fontAsset.m_SourceFontFile_EditorRef = font;
  409. #endif
  410. fontAsset.atlasPopulationMode = atlasPopulationMode;
  411. fontAsset.atlasWidth = atlasWidth;
  412. fontAsset.atlasHeight = atlasHeight;
  413. fontAsset.atlasPadding = atlasPadding;
  414. fontAsset.atlasRenderMode = renderMode;
  415. // Initialize array for the font atlas textures.
  416. fontAsset.atlasTextures = new Texture2D[1];
  417. // Create and add font atlas texture.
  418. Texture2D texture = new Texture2D(0, 0, TextureFormat.Alpha8, false);
  419. fontAsset.atlasTextures[0] = texture;
  420. fontAsset.isMultiAtlasTexturesEnabled = enableMultiAtlasSupport;
  421. // Add free rectangle of the size of the texture.
  422. int packingModifier;
  423. if (((GlyphRasterModes)renderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP)
  424. {
  425. packingModifier = 0;
  426. // Optimize by adding static ref to shader.
  427. Material tmp_material = new Material(ShaderUtilities.ShaderRef_MobileBitmap);
  428. //tmp_material.name = texture.name + " Material";
  429. tmp_material.SetTexture(ShaderUtilities.ID_MainTex, texture);
  430. tmp_material.SetFloat(ShaderUtilities.ID_TextureWidth, atlasWidth);
  431. tmp_material.SetFloat(ShaderUtilities.ID_TextureHeight, atlasHeight);
  432. fontAsset.material = tmp_material;
  433. }
  434. else
  435. {
  436. packingModifier = 1;
  437. // Optimize by adding static ref to shader.
  438. Material tmp_material = new Material(ShaderUtilities.ShaderRef_MobileSDF);
  439. //tmp_material.name = texture.name + " Material";
  440. tmp_material.SetTexture(ShaderUtilities.ID_MainTex, texture);
  441. tmp_material.SetFloat(ShaderUtilities.ID_TextureWidth, atlasWidth);
  442. tmp_material.SetFloat(ShaderUtilities.ID_TextureHeight, atlasHeight);
  443. tmp_material.SetFloat(ShaderUtilities.ID_GradientScale, atlasPadding + packingModifier);
  444. tmp_material.SetFloat(ShaderUtilities.ID_WeightNormal, fontAsset.normalStyle);
  445. tmp_material.SetFloat(ShaderUtilities.ID_WeightBold, fontAsset.boldStyle);
  446. fontAsset.material = tmp_material;
  447. }
  448. fontAsset.freeGlyphRects = new List<GlyphRect>(8) { new GlyphRect(0, 0, atlasWidth - packingModifier, atlasHeight - packingModifier) };
  449. fontAsset.usedGlyphRects = new List<GlyphRect>(8);
  450. // TODO: Consider adding support for extracting glyph positioning data
  451. fontAsset.ReadFontAssetDefinition();
  452. return fontAsset;
  453. }
  454. void Awake()
  455. {
  456. // Check version number of font asset to see if it needs to be upgraded.
  457. if (this.material != null && string.IsNullOrEmpty(m_Version))
  458. UpgradeFontAsset();
  459. }
  460. #if UNITY_EDITOR
  461. private void OnValidate()
  462. {
  463. // Make sure our lookup dictionary have been initialized.
  464. if (m_CharacterLookupDictionary == null || m_GlyphLookupDictionary == null)
  465. ReadFontAssetDefinition();
  466. }
  467. #endif
  468. private static string s_DefaultMaterialSuffix = " Atlas Material";
  469. public void ReadFontAssetDefinition()
  470. {
  471. k_ReadFontAssetDefinitionMarker.Begin();
  472. //Debug.Log("Reading Font Asset Definition for " + this.name + ".");
  473. // Check version number of font asset to see if it needs to be upgraded.
  474. if (this.material != null && string.IsNullOrEmpty(m_Version))
  475. UpgradeFontAsset();
  476. // Initialize lookup tables for characters and glyphs.
  477. InitializeDictionaryLookupTables();
  478. // Add synthesized characters and adjust face metrics
  479. AddSynthesizedCharactersAndFaceMetrics();
  480. // Adjust Font Scale for compatibility reasons
  481. if (m_FaceInfo.scale == 0)
  482. m_FaceInfo.scale = 1.0f;
  483. // Set Strikethrough Offset (if needed)
  484. if (m_FaceInfo.strikethroughOffset == 0)
  485. m_FaceInfo.strikethroughOffset = m_FaceInfo.capLine / 2.5f;
  486. // Set Padding value for legacy font assets.
  487. if (m_AtlasPadding == 0)
  488. {
  489. if (material.HasProperty(ShaderUtilities.ID_GradientScale))
  490. m_AtlasPadding = (int)material.GetFloat(ShaderUtilities.ID_GradientScale) - 1;
  491. }
  492. // Compute Hashcode for the font asset name
  493. hashCode = TMP_TextUtilities.GetSimpleHashCode(this.name);
  494. // Compute Hashcode for the material name
  495. materialHashCode = TMP_TextUtilities.GetSimpleHashCode(this.name + s_DefaultMaterialSuffix);
  496. // Add reference to font asset in TMP Resource Manager
  497. //TMP_ResourceManager.AddFontAsset(this);
  498. IsFontAssetLookupTablesDirty = false;
  499. k_ReadFontAssetDefinitionMarker.End();
  500. }
  501. /// <summary>
  502. /// Read the various data tables of the font asset to populate its different dictionaries to allow for faster lookup of related font asset data.
  503. /// </summary>
  504. internal void InitializeDictionaryLookupTables()
  505. {
  506. // Initialize and populate glyph lookup dictionary
  507. InitializeGlyphLookupDictionary();
  508. // Initialize and populate character lookup dictionary
  509. InitializeCharacterLookupDictionary();
  510. // Initialize and populate character lookup dictionary
  511. InitializeGlyphPaidAdjustmentRecordsLookupDictionary();
  512. }
  513. internal void InitializeGlyphLookupDictionary()
  514. {
  515. // Create new instance of the glyph lookup dictionary or clear the existing one.
  516. if (m_GlyphLookupDictionary == null)
  517. m_GlyphLookupDictionary = new Dictionary<uint, Glyph>();
  518. else
  519. m_GlyphLookupDictionary.Clear();
  520. // Initialize or clear list of glyph indexes.
  521. if (m_GlyphIndexList == null)
  522. m_GlyphIndexList = new List<uint>();
  523. else
  524. m_GlyphIndexList.Clear();
  525. // Initialize or clear list of glyph indexes.
  526. if (m_GlyphIndexListNewlyAdded == null)
  527. m_GlyphIndexListNewlyAdded = new List<uint>();
  528. else
  529. m_GlyphIndexListNewlyAdded.Clear();
  530. //
  531. int glyphCount = m_GlyphTable.Count;
  532. // Add glyphs contained in the glyph table to dictionary for faster lookup.
  533. for (int i = 0; i < glyphCount; i++)
  534. {
  535. Glyph glyph = m_GlyphTable[i];
  536. uint index = glyph.index;
  537. // TODO: Not sure it is necessary to check here.
  538. if (m_GlyphLookupDictionary.ContainsKey(index) == false)
  539. {
  540. m_GlyphLookupDictionary.Add(index, glyph);
  541. m_GlyphIndexList.Add(index);
  542. }
  543. }
  544. }
  545. internal void InitializeCharacterLookupDictionary()
  546. {
  547. // Create new instance of the character lookup dictionary or clear the existing one.
  548. if (m_CharacterLookupDictionary == null)
  549. m_CharacterLookupDictionary = new Dictionary<uint, TMP_Character>();
  550. else
  551. m_CharacterLookupDictionary.Clear();
  552. // Add the characters contained in the character table to the dictionary for faster lookup.
  553. for (int i = 0; i < m_CharacterTable.Count; i++)
  554. {
  555. TMP_Character character = m_CharacterTable[i];
  556. uint unicode = character.unicode;
  557. uint glyphIndex = character.glyphIndex;
  558. // Add character along with reference to text asset and glyph
  559. if (m_CharacterLookupDictionary.ContainsKey(unicode) == false)
  560. {
  561. m_CharacterLookupDictionary.Add(unicode, character);
  562. character.textAsset = this;
  563. character.glyph = m_GlyphLookupDictionary[glyphIndex];
  564. }
  565. }
  566. // Clear internal fallback references
  567. if (FallbackSearchQueryLookup == null)
  568. FallbackSearchQueryLookup = new HashSet<int>();
  569. else
  570. FallbackSearchQueryLookup.Clear();
  571. }
  572. internal void InitializeGlyphPaidAdjustmentRecordsLookupDictionary()
  573. {
  574. // Upgrade Glyph Adjustment Table to the new Font Feature table and Glyph Pair Adjustment Records
  575. if (m_KerningTable != null && m_KerningTable.kerningPairs != null && m_KerningTable.kerningPairs.Count > 0)
  576. UpgradeGlyphAdjustmentTableToFontFeatureTable();
  577. // Read Font Features which will include kerning data.
  578. if (m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookupDictionary == null)
  579. m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookupDictionary = new Dictionary<uint, TMP_GlyphPairAdjustmentRecord>();
  580. else
  581. m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookupDictionary.Clear();
  582. List<TMP_GlyphPairAdjustmentRecord> glyphPairAdjustmentRecords = m_FontFeatureTable.m_GlyphPairAdjustmentRecords;
  583. if (glyphPairAdjustmentRecords != null)
  584. {
  585. for (int i = 0; i < glyphPairAdjustmentRecords.Count; i++)
  586. {
  587. TMP_GlyphPairAdjustmentRecord record = glyphPairAdjustmentRecords[i];
  588. uint key = new GlyphPairKey(record).key;
  589. if (!m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookupDictionary.ContainsKey(key))
  590. m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookupDictionary.Add(key, record);
  591. }
  592. }
  593. }
  594. internal void AddSynthesizedCharactersAndFaceMetrics()
  595. {
  596. k_AddSynthesizedCharactersMarker.Begin();
  597. bool isFontFaceLoaded = false;
  598. if (m_AtlasPopulationMode == AtlasPopulationMode.Dynamic)
  599. isFontFaceLoaded = FontEngine.LoadFontFace(sourceFontFile, m_FaceInfo.pointSize) == FontEngineError.Success;
  600. // Only characters not present in the source font file will be synthesized.
  601. // Non visible and control characters with no metrics
  602. // Add End of Text \u0003
  603. AddSynthesizedCharacter(0x03, isFontFaceLoaded, true);
  604. // Add Tab \u0009
  605. AddSynthesizedCharacter(0x09, isFontFaceLoaded, true);
  606. // Add Line Feed (LF) \u000A
  607. AddSynthesizedCharacter(0x0A, isFontFaceLoaded);
  608. // Add Vertical Tab (VT) \u000B
  609. AddSynthesizedCharacter(0x0B, isFontFaceLoaded);
  610. // Add Carriage Return (CR) \u000D
  611. AddSynthesizedCharacter(0x0D, isFontFaceLoaded);
  612. // Add Arabic Letter Mark \u061C
  613. AddSynthesizedCharacter(0x061C, isFontFaceLoaded);
  614. // Add Zero Width Space <ZWSP> \u2000B
  615. AddSynthesizedCharacter(0x200B, isFontFaceLoaded);
  616. // Add Left-To-Right Mark \u200E
  617. AddSynthesizedCharacter(0x200E, isFontFaceLoaded);
  618. // Add Right-To-Left Mark \u200F
  619. AddSynthesizedCharacter(0x200F, isFontFaceLoaded);
  620. // Add Line Separator \u2028
  621. AddSynthesizedCharacter(0x2028, isFontFaceLoaded);
  622. // Add Paragraph Separator \u2029
  623. AddSynthesizedCharacter(0x2029, isFontFaceLoaded);
  624. // Add Word Joiner <WJ> / Zero Width Non-Breaking Space \u2060
  625. AddSynthesizedCharacter(0x2060, isFontFaceLoaded);
  626. // Set Cap Line using the capital letter 'X'
  627. if (m_FaceInfo.capLine == 0 && m_CharacterLookupDictionary.ContainsKey('X'))
  628. {
  629. uint glyphIndex = m_CharacterLookupDictionary['X'].glyphIndex;
  630. m_FaceInfo.capLine = m_GlyphLookupDictionary[glyphIndex].metrics.horizontalBearingY;
  631. }
  632. // Set Mean Line using the lowercase letter 'x'
  633. if (m_FaceInfo.meanLine == 0 && m_CharacterLookupDictionary.ContainsKey('x'))
  634. {
  635. uint glyphIndex = m_CharacterLookupDictionary['x'].glyphIndex;
  636. m_FaceInfo.meanLine = m_GlyphLookupDictionary[glyphIndex].metrics.horizontalBearingY;
  637. }
  638. k_AddSynthesizedCharactersMarker.End();
  639. }
  640. void AddSynthesizedCharacter(uint unicode, bool isFontFaceLoaded, bool addImmediately = false)
  641. {
  642. // Check if unicode is already present in the font asset
  643. if (m_CharacterLookupDictionary.ContainsKey(unicode))
  644. return;
  645. Glyph glyph;
  646. if (isFontFaceLoaded)
  647. {
  648. // Check if unicode is present in font file
  649. if (FontEngine.GetGlyphIndex(unicode) != 0)
  650. {
  651. if (addImmediately == false)
  652. return;
  653. //Debug.Log("Adding Unicode [" + unicode.ToString("X4") + "].");
  654. GlyphLoadFlags glyphLoadFlags = ((GlyphRasterModes)m_AtlasRenderMode & GlyphRasterModes.RASTER_MODE_NO_HINTING) == GlyphRasterModes.RASTER_MODE_NO_HINTING
  655. ? GlyphLoadFlags.LOAD_NO_BITMAP | GlyphLoadFlags.LOAD_NO_HINTING
  656. : GlyphLoadFlags.LOAD_NO_BITMAP;
  657. if (FontEngine.TryGetGlyphWithUnicodeValue(unicode, glyphLoadFlags, out glyph))
  658. m_CharacterLookupDictionary.Add(unicode, new TMP_Character(unicode, this, glyph));
  659. return;
  660. }
  661. }
  662. //Debug.Log("Synthesizing Unicode [" + unicode.ToString("X4") + "].");
  663. // Synthesize and add missing glyph and character
  664. glyph = new Glyph(0, new GlyphMetrics(0, 0, 0, 0, 0), GlyphRect.zero, 1.0f, 0);
  665. m_CharacterLookupDictionary.Add(unicode, new TMP_Character(unicode, this, glyph));
  666. }
  667. internal HashSet<int> FallbackSearchQueryLookup = new HashSet<int>();
  668. internal void AddCharacterToLookupCache(uint unicode, TMP_Character character)
  669. {
  670. m_CharacterLookupDictionary.Add(unicode, character);
  671. // Add font asset to fallback references.
  672. FallbackSearchQueryLookup.Add(character.textAsset.instanceID);
  673. }
  674. /// <summary>
  675. /// Sort the Character table by Unicode values.
  676. /// </summary>
  677. internal void SortCharacterTable()
  678. {
  679. if (m_CharacterTable != null && m_CharacterTable.Count > 0)
  680. m_CharacterTable = m_CharacterTable.OrderBy(c => c.unicode).ToList();
  681. }
  682. /// <summary>
  683. /// Sort the Glyph table by index values.
  684. /// </summary>
  685. internal void SortGlyphTable()
  686. {
  687. if (m_GlyphTable != null && m_GlyphTable.Count > 0)
  688. m_GlyphTable = m_GlyphTable.OrderBy(c => c.index).ToList();
  689. }
  690. internal void SortFontFeatureTable()
  691. {
  692. m_FontFeatureTable.SortGlyphPairAdjustmentRecords();
  693. }
  694. /// <summary>
  695. /// Sort both glyph and character tables.
  696. /// </summary>
  697. internal void SortAllTables()
  698. {
  699. SortGlyphTable();
  700. SortCharacterTable();
  701. SortFontFeatureTable();
  702. }
  703. /// <summary>
  704. /// HashSet of font asset instance ID used in the process of searching for through fallback font assets for a given character or characters.
  705. /// </summary>
  706. private static HashSet<int> k_SearchedFontAssetLookup;
  707. /// <summary>
  708. /// Function to check if a certain character exists in the font asset.
  709. /// </summary>
  710. /// <param name="character"></param>
  711. /// <returns></returns>
  712. public bool HasCharacter(int character)
  713. {
  714. if (m_CharacterLookupDictionary == null)
  715. return false;
  716. return m_CharacterLookupDictionary.ContainsKey((uint)character);
  717. }
  718. /// <summary>
  719. /// Function to check if a character is contained in the font asset with the option to also check potential local fallbacks.
  720. /// </summary>
  721. /// <param name="character"></param>
  722. /// <param name="searchFallbacks"></param>
  723. /// <param name="tryAddCharacter"></param>
  724. /// <returns></returns>
  725. public bool HasCharacter(char character, bool searchFallbacks = false, bool tryAddCharacter = false)
  726. {
  727. // Read font asset definition if it hasn't already been done.
  728. if (m_CharacterLookupDictionary == null)
  729. {
  730. ReadFontAssetDefinition();
  731. if (m_CharacterLookupDictionary == null)
  732. return false;
  733. }
  734. // Check font asset
  735. if (m_CharacterLookupDictionary.ContainsKey(character))
  736. return true;
  737. // Check if font asset is dynamic and if so try to add the requested character to it.
  738. if (tryAddCharacter && m_AtlasPopulationMode == AtlasPopulationMode.Dynamic)
  739. {
  740. TMP_Character returnedCharacter;
  741. if (TryAddCharacterInternal(character, out returnedCharacter))
  742. return true;
  743. }
  744. if (searchFallbacks)
  745. {
  746. // Initialize or clear font asset lookup
  747. if (k_SearchedFontAssetLookup == null)
  748. k_SearchedFontAssetLookup = new HashSet<int>();
  749. else
  750. k_SearchedFontAssetLookup.Clear();
  751. // Add current font asset to lookup
  752. k_SearchedFontAssetLookup.Add(GetInstanceID());
  753. // Check font asset fallbacks
  754. if (fallbackFontAssetTable != null && fallbackFontAssetTable.Count > 0)
  755. {
  756. for (int i = 0; i < fallbackFontAssetTable.Count && fallbackFontAssetTable[i] != null; i++)
  757. {
  758. TMP_FontAsset fallback = fallbackFontAssetTable[i];
  759. int fallbackID = fallback.GetInstanceID();
  760. // Search fallback if not already contained in lookup
  761. if (k_SearchedFontAssetLookup.Add(fallbackID))
  762. {
  763. if (fallback.HasCharacter_Internal(character, true, tryAddCharacter))
  764. return true;
  765. }
  766. }
  767. }
  768. // Check general fallback font assets.
  769. if (TMP_Settings.fallbackFontAssets != null && TMP_Settings.fallbackFontAssets.Count > 0)
  770. {
  771. for (int i = 0; i < TMP_Settings.fallbackFontAssets.Count && TMP_Settings.fallbackFontAssets[i] != null; i++)
  772. {
  773. TMP_FontAsset fallback = TMP_Settings.fallbackFontAssets[i];
  774. int fallbackID = fallback.GetInstanceID();
  775. // Search fallback if not already contained in lookup
  776. if (k_SearchedFontAssetLookup.Add(fallbackID))
  777. {
  778. if (fallback.HasCharacter_Internal(character, true, tryAddCharacter))
  779. return true;
  780. }
  781. }
  782. }
  783. // Check TMP Settings Default Font Asset
  784. if (TMP_Settings.defaultFontAsset != null)
  785. {
  786. TMP_FontAsset fallback = TMP_Settings.defaultFontAsset;
  787. int fallbackID = fallback.GetInstanceID();
  788. // Search fallback if it has not already been searched
  789. if (k_SearchedFontAssetLookup.Add(fallbackID))
  790. {
  791. if (fallback.HasCharacter_Internal(character, true, tryAddCharacter))
  792. return true;
  793. }
  794. }
  795. }
  796. return false;
  797. }
  798. /// <summary>
  799. /// Function to check if a character is contained in a font asset with the option to also check through fallback font assets.
  800. /// This private implementation does not search the fallback font asset in the TMP Settings file.
  801. /// </summary>
  802. /// <param name="character"></param>
  803. /// <param name="searchFallbacks"></param>
  804. /// <param name="tryAddCharacter"></param>
  805. /// <returns></returns>
  806. bool HasCharacter_Internal(uint character, bool searchFallbacks = false, bool tryAddCharacter = false)
  807. {
  808. // Read font asset definition if it hasn't already been done.
  809. if (m_CharacterLookupDictionary == null)
  810. {
  811. ReadFontAssetDefinition();
  812. if (m_CharacterLookupDictionary == null)
  813. return false;
  814. }
  815. // Check font asset
  816. if (m_CharacterLookupDictionary.ContainsKey(character))
  817. return true;
  818. // Check if fallback is dynamic and if so try to add the requested character to it.
  819. if (tryAddCharacter && atlasPopulationMode == AtlasPopulationMode.Dynamic)
  820. {
  821. TMP_Character returnedCharacter;
  822. if (TryAddCharacterInternal(character, out returnedCharacter))
  823. return true;
  824. }
  825. if (searchFallbacks)
  826. {
  827. // Check Font Asset Fallback fonts.
  828. if (fallbackFontAssetTable == null || fallbackFontAssetTable.Count == 0)
  829. return false;
  830. for (int i = 0; i < fallbackFontAssetTable.Count && fallbackFontAssetTable[i] != null; i++)
  831. {
  832. TMP_FontAsset fallback = fallbackFontAssetTable[i];
  833. int fallbackID = fallback.GetInstanceID();
  834. // Search fallback if it has not already been searched
  835. if (k_SearchedFontAssetLookup.Add(fallbackID))
  836. {
  837. if (fallback.HasCharacter_Internal(character, true, tryAddCharacter))
  838. return true;
  839. }
  840. }
  841. }
  842. return false;
  843. }
  844. /// <summary>
  845. /// Function to check if certain characters exists in the font asset. Function returns a list of missing characters.
  846. /// </summary>
  847. /// <param name="text">String containing the characters to check.</param>
  848. /// <param name="missingCharacters">List of missing characters.</param>
  849. /// <returns></returns>
  850. public bool HasCharacters(string text, out List<char> missingCharacters)
  851. {
  852. if (m_CharacterLookupDictionary == null)
  853. {
  854. missingCharacters = null;
  855. return false;
  856. }
  857. missingCharacters = new List<char>();
  858. for (int i = 0; i < text.Length; i++)
  859. {
  860. if (!m_CharacterLookupDictionary.ContainsKey(text[i]))
  861. missingCharacters.Add(text[i]);
  862. }
  863. if (missingCharacters.Count == 0)
  864. return true;
  865. return false;
  866. }
  867. /// <summary>
  868. /// Function to check if the characters in the given string are contained in the font asset with the option to also check its potential local fallbacks.
  869. /// </summary>
  870. /// <param name="text">String containing the characters to check.</param>
  871. /// <param name="missingCharacters">Array containing the unicode values of the missing characters.</param>
  872. /// <param name="searchFallbacks">Determines if fallback font assets assigned to this font asset should be searched.</param>
  873. /// <param name="tryAddCharacter"></param>
  874. /// <returns></returns>
  875. public bool HasCharacters(string text, out uint[] missingCharacters, bool searchFallbacks = false, bool tryAddCharacter = false)
  876. {
  877. missingCharacters = null;
  878. // Read font asset definition if it hasn't already been done.
  879. if (m_CharacterLookupDictionary == null)
  880. {
  881. ReadFontAssetDefinition();
  882. if (m_CharacterLookupDictionary == null)
  883. return false;
  884. }
  885. // Clear internal list of
  886. s_MissingCharacterList.Clear();
  887. for (int i = 0; i < text.Length; i++)
  888. {
  889. bool isMissingCharacter = true;
  890. uint character = text[i];
  891. if (m_CharacterLookupDictionary.ContainsKey(character))
  892. continue;
  893. // Check if fallback is dynamic and if so try to add the requested character to it.
  894. if (tryAddCharacter && atlasPopulationMode == AtlasPopulationMode.Dynamic)
  895. {
  896. TMP_Character returnedCharacter;
  897. if (TryAddCharacterInternal(character, out returnedCharacter))
  898. continue;
  899. }
  900. if (searchFallbacks)
  901. {
  902. // Initialize or clear font asset lookup
  903. if (k_SearchedFontAssetLookup == null)
  904. k_SearchedFontAssetLookup = new HashSet<int>();
  905. else
  906. k_SearchedFontAssetLookup.Clear();
  907. // Add current font asset to lookup
  908. k_SearchedFontAssetLookup.Add(GetInstanceID());
  909. // Check font asset fallbacks
  910. if (fallbackFontAssetTable != null && fallbackFontAssetTable.Count > 0)
  911. {
  912. for (int j = 0; j < fallbackFontAssetTable.Count && fallbackFontAssetTable[j] != null; j++)
  913. {
  914. TMP_FontAsset fallback = fallbackFontAssetTable[j];
  915. int fallbackID = fallback.GetInstanceID();
  916. // Search fallback if it has not already been searched
  917. if (k_SearchedFontAssetLookup.Add(fallbackID))
  918. {
  919. if (fallback.HasCharacter_Internal(character, true, tryAddCharacter) == false)
  920. continue;
  921. isMissingCharacter = false;
  922. break;
  923. }
  924. }
  925. }
  926. // Check general fallback font assets.
  927. if (isMissingCharacter && TMP_Settings.fallbackFontAssets != null && TMP_Settings.fallbackFontAssets.Count > 0)
  928. {
  929. for (int j = 0; j < TMP_Settings.fallbackFontAssets.Count && TMP_Settings.fallbackFontAssets[j] != null; j++)
  930. {
  931. TMP_FontAsset fallback = TMP_Settings.fallbackFontAssets[j];
  932. int fallbackID = fallback.GetInstanceID();
  933. // Search fallback if it has not already been searched
  934. if (k_SearchedFontAssetLookup.Add(fallbackID))
  935. {
  936. if (fallback.HasCharacter_Internal(character, true, tryAddCharacter) == false)
  937. continue;
  938. isMissingCharacter = false;
  939. break;
  940. }
  941. }
  942. }
  943. // Check TMP Settings Default Font Asset
  944. if (isMissingCharacter && TMP_Settings.defaultFontAsset != null)
  945. {
  946. TMP_FontAsset fallback = TMP_Settings.defaultFontAsset;
  947. int fallbackID = fallback.GetInstanceID();
  948. // Search fallback if it has not already been searched
  949. if (k_SearchedFontAssetLookup.Add(fallbackID))
  950. {
  951. if (fallback.HasCharacter_Internal(character, true, tryAddCharacter))
  952. isMissingCharacter = false;
  953. }
  954. }
  955. }
  956. if (isMissingCharacter)
  957. s_MissingCharacterList.Add(character);
  958. }
  959. if (s_MissingCharacterList.Count > 0)
  960. {
  961. missingCharacters = s_MissingCharacterList.ToArray();
  962. return false;
  963. }
  964. return true;
  965. }
  966. /// <summary>
  967. /// Function to check if certain characters exists in the font asset. Function returns false if any characters are missing.
  968. /// </summary>
  969. /// <param name="text">String containing the characters to check</param>
  970. /// <returns></returns>
  971. public bool HasCharacters(string text)
  972. {
  973. if (m_CharacterLookupDictionary == null)
  974. return false;
  975. for (int i = 0; i < text.Length; i++)
  976. {
  977. if (!m_CharacterLookupDictionary.ContainsKey(text[i]))
  978. return false;
  979. }
  980. return true;
  981. }
  982. /// <summary>
  983. /// Function to extract all the characters from a font asset.
  984. /// </summary>
  985. /// <param name="fontAsset"></param>
  986. /// <returns></returns>
  987. public static string GetCharacters(TMP_FontAsset fontAsset)
  988. {
  989. string characters = string.Empty;
  990. for (int i = 0; i < fontAsset.characterTable.Count; i++)
  991. {
  992. characters += (char)fontAsset.characterTable[i].unicode;
  993. }
  994. return characters;
  995. }
  996. /// <summary>
  997. /// Function which returns an array that contains all the characters from a font asset.
  998. /// </summary>
  999. /// <param name="fontAsset"></param>
  1000. /// <returns></returns>
  1001. public static int[] GetCharactersArray(TMP_FontAsset fontAsset)
  1002. {
  1003. int[] characters = new int[fontAsset.characterTable.Count];
  1004. for (int i = 0; i < fontAsset.characterTable.Count; i++)
  1005. {
  1006. characters[i] = (int)fontAsset.characterTable[i].unicode;
  1007. }
  1008. return characters;
  1009. }
  1010. /// <summary>
  1011. /// Internal function used to get the glyph index for the given Unicode.
  1012. /// </summary>
  1013. /// <param name="unicode"></param>
  1014. /// <returns></returns>
  1015. internal uint GetGlyphIndex(uint unicode)
  1016. {
  1017. // Check if glyph already exists in font asset.
  1018. if (m_CharacterLookupDictionary.ContainsKey(unicode))
  1019. return m_CharacterLookupDictionary[unicode].glyphIndex;
  1020. // Load font face.
  1021. if (FontEngine.LoadFontFace(sourceFontFile, m_FaceInfo.pointSize) != FontEngineError.Success)
  1022. return 0;
  1023. return FontEngine.GetGlyphIndex(unicode);
  1024. }
  1025. // ================================================================================
  1026. // Properties and functions related to character and glyph additions as well as
  1027. // tacking glyphs that need to be added to various font asset atlas textures.
  1028. // ================================================================================
  1029. // List and HashSet used for tracking font assets whose font atlas texture and character data needs updating.
  1030. private static List<TMP_FontAsset> k_FontAssets_FontFeaturesUpdateQueue = new List<TMP_FontAsset>();
  1031. private static HashSet<int> k_FontAssets_FontFeaturesUpdateQueueLookup = new HashSet<int>();
  1032. private static List<TMP_FontAsset> k_FontAssets_AtlasTexturesUpdateQueue = new List<TMP_FontAsset>();
  1033. private static HashSet<int> k_FontAssets_AtlasTexturesUpdateQueueLookup = new HashSet<int>();
  1034. /// <summary>
  1035. ///
  1036. /// </summary>
  1037. /// <param name="fontAsset"></param>
  1038. internal static void RegisterFontAssetForFontFeatureUpdate(TMP_FontAsset fontAsset)
  1039. {
  1040. int instanceID = fontAsset.instanceID;
  1041. if (k_FontAssets_FontFeaturesUpdateQueueLookup.Add(instanceID))
  1042. k_FontAssets_FontFeaturesUpdateQueue.Add(fontAsset);
  1043. }
  1044. /// <summary>
  1045. /// Function called to update the font atlas texture and character data of font assets to which
  1046. /// new characters were added.
  1047. /// </summary>
  1048. internal static void UpdateFontFeaturesForFontAssetsInQueue()
  1049. {
  1050. int count = k_FontAssets_FontFeaturesUpdateQueue.Count;
  1051. for (int i = 0; i < count; i++)
  1052. k_FontAssets_FontFeaturesUpdateQueue[i].UpdateGlyphAdjustmentRecords();
  1053. if (count > 0)
  1054. {
  1055. k_FontAssets_FontFeaturesUpdateQueue.Clear();
  1056. k_FontAssets_FontFeaturesUpdateQueueLookup.Clear();
  1057. }
  1058. }
  1059. /// <summary>
  1060. ///
  1061. /// </summary>
  1062. /// <param name="fontAsset"></param>
  1063. internal static void RegisterFontAssetForAtlasTextureUpdate(TMP_FontAsset fontAsset)
  1064. {
  1065. int instanceID = fontAsset.instanceID;
  1066. if (k_FontAssets_AtlasTexturesUpdateQueueLookup.Add(instanceID))
  1067. k_FontAssets_AtlasTexturesUpdateQueue.Add(fontAsset);
  1068. }
  1069. /// <summary>
  1070. ///
  1071. /// </summary>
  1072. internal static void UpdateAtlasTexturesForFontAssetsInQueue()
  1073. {
  1074. int count = k_FontAssets_AtlasTexturesUpdateQueueLookup.Count;
  1075. for (int i = 0; i < count; i++)
  1076. k_FontAssets_AtlasTexturesUpdateQueue[i].TryAddGlyphsToAtlasTextures();
  1077. if (count > 0)
  1078. {
  1079. k_FontAssets_AtlasTexturesUpdateQueue.Clear();
  1080. k_FontAssets_AtlasTexturesUpdateQueueLookup.Clear();
  1081. }
  1082. }
  1083. /// <summary>
  1084. ///
  1085. /// </summary>
  1086. //private bool m_IsAlreadyRegisteredForUpdate;
  1087. /// <summary>
  1088. /// List of glyphs that need to be rendered and added to an atlas texture.
  1089. /// </summary>
  1090. private List<Glyph> m_GlyphsToRender = new List<Glyph>();
  1091. /// <summary>
  1092. /// List of glyphs that we just rendered and added to an atlas texture.
  1093. /// </summary>
  1094. private List<Glyph> m_GlyphsRendered = new List<Glyph>();
  1095. /// <summary>
  1096. /// List of all the glyph indexes contained in the font asset.
  1097. /// </summary>
  1098. private List<uint> m_GlyphIndexList = new List<uint>();
  1099. /// <summary>
  1100. /// List of glyph indexes newly added to the font asset.
  1101. /// This list is used in the process of retrieving font features.
  1102. /// </summary>
  1103. private List<uint> m_GlyphIndexListNewlyAdded = new List<uint>();
  1104. /// <summary>
  1105. ///
  1106. /// </summary>
  1107. internal List<uint> m_GlyphsToAdd = new List<uint>();
  1108. internal HashSet<uint> m_GlyphsToAddLookup = new HashSet<uint>();
  1109. internal List<TMP_Character> m_CharactersToAdd = new List<TMP_Character>();
  1110. internal HashSet<uint> m_CharactersToAddLookup = new HashSet<uint>();
  1111. /// <summary>
  1112. /// Internal list used to track characters that could not be added to the font asset.
  1113. /// </summary>
  1114. internal List<uint> s_MissingCharacterList = new List<uint>();
  1115. /// <summary>
  1116. /// Hash table used to track characters that are known to be missing from the font file.
  1117. /// </summary>
  1118. internal HashSet<uint> m_MissingUnicodesFromFontFile = new HashSet<uint>();
  1119. /// <summary>
  1120. /// Internal static array used to avoid allocations when using the GetGlyphPairAdjustmentTable().
  1121. /// </summary>
  1122. internal static uint[] k_GlyphIndexArray;
  1123. /// <summary>
  1124. /// Try adding the characters from the provided string to the font asset.
  1125. /// </summary>
  1126. /// <param name="unicodes">Array that contains the characters to add to the font asset.</param>
  1127. /// <param name="includeFontFeatures"></param>
  1128. /// <returns>Returns true if all the characters were successfully added to the font asset. Return false otherwise.</returns>
  1129. public bool TryAddCharacters(uint[] unicodes, bool includeFontFeatures = false)
  1130. {
  1131. uint[] missingUnicodes;
  1132. return TryAddCharacters(unicodes, out missingUnicodes, includeFontFeatures);
  1133. }
  1134. /// <summary>
  1135. /// Try adding the characters from the provided string to the font asset.
  1136. /// </summary>
  1137. /// <param name="unicodes">Array that contains the characters to add to the font asset.</param>
  1138. /// <param name="missingUnicodes">Array containing the characters that could not be added to the font asset.</param>
  1139. /// <param name="includeFontFeatures"></param>
  1140. /// <returns>Returns true if all the characters were successfully added to the font asset. Return false otherwise.</returns>
  1141. public bool TryAddCharacters(uint[] unicodes, out uint[] missingUnicodes, bool includeFontFeatures = false)
  1142. {
  1143. k_TryAddCharactersMarker.Begin();
  1144. // Make sure font asset is set to dynamic and that we have a valid list of characters.
  1145. if (unicodes == null || unicodes.Length == 0 || m_AtlasPopulationMode == AtlasPopulationMode.Static)
  1146. {
  1147. if (m_AtlasPopulationMode == AtlasPopulationMode.Static)
  1148. Debug.LogWarning("Unable to add characters to font asset [" + this.name + "] because its AtlasPopulationMode is set to Static.", this);
  1149. else
  1150. Debug.LogWarning("Unable to add characters to font asset [" + this.name + "] because the provided Unicode list is Null or Empty.", this);
  1151. missingUnicodes = null;
  1152. k_TryAddCharactersMarker.End();
  1153. return false;
  1154. }
  1155. // Load font face.
  1156. if (FontEngine.LoadFontFace(m_SourceFontFile, m_FaceInfo.pointSize) != FontEngineError.Success)
  1157. {
  1158. missingUnicodes = unicodes.ToArray();
  1159. k_TryAddCharactersMarker.End();
  1160. return false;
  1161. }
  1162. // Make sure font asset has been initialized
  1163. if (m_CharacterLookupDictionary == null || m_GlyphLookupDictionary == null)
  1164. ReadFontAssetDefinition();
  1165. // Clear lists used to track which character and glyphs were added or missing.
  1166. m_GlyphsToAdd.Clear();
  1167. m_GlyphsToAddLookup.Clear();
  1168. m_CharactersToAdd.Clear();
  1169. m_CharactersToAddLookup.Clear();
  1170. s_MissingCharacterList.Clear();
  1171. bool isMissingCharacters = false;
  1172. int unicodeCount = unicodes.Length;
  1173. for (int i = 0; i < unicodeCount; i++)
  1174. {
  1175. uint unicode = unicodes[i];
  1176. // Check if character is already contained in the character table.
  1177. if (m_CharacterLookupDictionary.ContainsKey(unicode))
  1178. continue;
  1179. // Get the index of the glyph for this Unicode value.
  1180. uint glyphIndex = FontEngine.GetGlyphIndex(unicode);
  1181. // Skip missing glyphs
  1182. if (glyphIndex == 0)
  1183. {
  1184. // Special handling for characters with potential alternative glyph representations
  1185. switch (unicode)
  1186. {
  1187. case 0xA0: // Non Breaking Space <NBSP>
  1188. // Use Space
  1189. glyphIndex = FontEngine.GetGlyphIndex(0x20);
  1190. break;
  1191. case 0xAD: // Soft Hyphen <SHY>
  1192. case 0x2011: // Non Breaking Hyphen
  1193. // Use Hyphen Minus
  1194. glyphIndex = FontEngine.GetGlyphIndex(0x2D);
  1195. break;
  1196. }
  1197. // Skip to next character if no potential alternative glyph representation is present in font file.
  1198. if (glyphIndex == 0)
  1199. {
  1200. // Add character to list of missing characters.
  1201. s_MissingCharacterList.Add(unicode);
  1202. isMissingCharacters = true;
  1203. continue;
  1204. }
  1205. }
  1206. TMP_Character character = new TMP_Character(unicode, glyphIndex);
  1207. // Check if glyph is already contained in the font asset as the same glyph might be referenced by multiple characters.
  1208. if (m_GlyphLookupDictionary.ContainsKey(glyphIndex))
  1209. {
  1210. // Add a reference to the source text asset and glyph
  1211. character.glyph = m_GlyphLookupDictionary[glyphIndex];
  1212. character.textAsset = this;
  1213. m_CharacterTable.Add(character);
  1214. m_CharacterLookupDictionary.Add(unicode, character);
  1215. continue;
  1216. }
  1217. // Make sure glyph index has not already been added to list of glyphs to add.
  1218. if (m_GlyphsToAddLookup.Add(glyphIndex))
  1219. m_GlyphsToAdd.Add(glyphIndex);
  1220. // Make sure unicode / character has not already been added.
  1221. if (m_CharactersToAddLookup.Add(unicode))
  1222. m_CharactersToAdd.Add(character);
  1223. }
  1224. if (m_GlyphsToAdd.Count == 0)
  1225. {
  1226. //Debug.LogWarning("No characters will be added to font asset [" + this.name + "] either because they are already present in the font asset or missing from the font file.");
  1227. missingUnicodes = unicodes;
  1228. k_TryAddCharactersMarker.End();
  1229. return false;
  1230. }
  1231. // Resize the Atlas Texture to the appropriate size
  1232. if (m_AtlasTextures[m_AtlasTextureIndex].width == 0 || m_AtlasTextures[m_AtlasTextureIndex].height == 0)
  1233. {
  1234. m_AtlasTextures[m_AtlasTextureIndex].Resize(m_AtlasWidth, m_AtlasHeight);
  1235. FontEngine.ResetAtlasTexture(m_AtlasTextures[m_AtlasTextureIndex]);
  1236. }
  1237. Glyph[] glyphs;
  1238. bool allGlyphsAddedToTexture = FontEngine.TryAddGlyphsToTexture(m_GlyphsToAdd, m_AtlasPadding, GlyphPackingMode.BestShortSideFit, m_FreeGlyphRects, m_UsedGlyphRects, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex], out glyphs);
  1239. // Add new glyphs to relevant font asset data structure
  1240. for (int i = 0; i < glyphs.Length && glyphs[i] != null; i++)
  1241. {
  1242. Glyph glyph = glyphs[i];
  1243. uint glyphIndex = glyph.index;
  1244. glyph.atlasIndex = m_AtlasTextureIndex;
  1245. // Add new glyph to glyph table.
  1246. m_GlyphTable.Add(glyph);
  1247. m_GlyphLookupDictionary.Add(glyphIndex, glyph);
  1248. m_GlyphIndexListNewlyAdded.Add(glyphIndex);
  1249. m_GlyphIndexList.Add(glyphIndex);
  1250. }
  1251. // Clear glyph index list to allow
  1252. m_GlyphsToAdd.Clear();
  1253. // Add new characters to relevant data structures as well as track glyphs that could not be added to the current atlas texture.
  1254. for (int i = 0; i < m_CharactersToAdd.Count; i++)
  1255. {
  1256. TMP_Character character = m_CharactersToAdd[i];
  1257. Glyph glyph;
  1258. if (m_GlyphLookupDictionary.TryGetValue(character.glyphIndex, out glyph) == false)
  1259. {
  1260. m_GlyphsToAdd.Add(character.glyphIndex);
  1261. continue;
  1262. }
  1263. // Add a reference to the source text asset and glyph
  1264. character.glyph = glyph;
  1265. character.textAsset = this;
  1266. m_CharacterTable.Add(character);
  1267. m_CharacterLookupDictionary.Add(character.unicode, character);
  1268. // Remove character from list to add
  1269. m_CharactersToAdd.RemoveAt(i);
  1270. i -= 1;
  1271. }
  1272. // Try adding missing glyphs to
  1273. if (m_IsMultiAtlasTexturesEnabled && allGlyphsAddedToTexture == false)
  1274. {
  1275. while (allGlyphsAddedToTexture == false)
  1276. allGlyphsAddedToTexture = TryAddGlyphsToNewAtlasTexture();
  1277. }
  1278. // Get Font Features for the given characters
  1279. if (includeFontFeatures)
  1280. UpdateGlyphAdjustmentRecords();
  1281. #if UNITY_EDITOR
  1282. // Makes the changes to the font asset persistent.
  1283. if (UnityEditor.EditorUtility.IsPersistent(this))
  1284. {
  1285. TMP_EditorResourceManager.RegisterResourceForUpdate(this);
  1286. }
  1287. #endif
  1288. // Populate list of missing characters
  1289. for (int i = 0; i < m_CharactersToAdd.Count; i++)
  1290. {
  1291. TMP_Character character = m_CharactersToAdd[i];
  1292. s_MissingCharacterList.Add(character.unicode);
  1293. }
  1294. missingUnicodes = null;
  1295. if (s_MissingCharacterList.Count > 0)
  1296. missingUnicodes = s_MissingCharacterList.ToArray();
  1297. k_TryAddCharactersMarker.End();
  1298. return allGlyphsAddedToTexture && !isMissingCharacters;
  1299. }
  1300. /// <summary>
  1301. /// Try adding the characters from the provided string to the font asset.
  1302. /// </summary>
  1303. /// <param name="characters">String containing the characters to add to the font asset.</param>
  1304. /// <param name="includeFontFeatures"></param>
  1305. /// <returns>Returns true if all the characters were successfully added to the font asset. Return false otherwise.</returns>
  1306. public bool TryAddCharacters(string characters, bool includeFontFeatures = false)
  1307. {
  1308. string missingCharacters;
  1309. return TryAddCharacters(characters, out missingCharacters, includeFontFeatures);
  1310. }
  1311. /// <summary>
  1312. /// Try adding the characters from the provided string to the font asset.
  1313. /// </summary>
  1314. /// <param name="characters">String containing the characters to add to the font asset.</param>
  1315. /// <param name="missingCharacters">String containing the characters that could not be added to the font asset.</param>
  1316. /// <param name="includeFontFeatures"></param>
  1317. /// <returns>Returns true if all the characters were successfully added to the font asset. Return false otherwise.</returns>
  1318. public bool TryAddCharacters(string characters, out string missingCharacters, bool includeFontFeatures = false)
  1319. {
  1320. k_TryAddCharactersMarker.Begin();
  1321. // Make sure font asset is set to dynamic and that we have a valid list of characters.
  1322. if (string.IsNullOrEmpty(characters) || m_AtlasPopulationMode == AtlasPopulationMode.Static)
  1323. {
  1324. if (m_AtlasPopulationMode == AtlasPopulationMode.Static)
  1325. Debug.LogWarning("Unable to add characters to font asset [" + this.name + "] because its AtlasPopulationMode is set to Static.", this);
  1326. else
  1327. {
  1328. Debug.LogWarning("Unable to add characters to font asset [" + this.name + "] because the provided character list is Null or Empty.", this);
  1329. }
  1330. missingCharacters = characters;
  1331. k_TryAddCharactersMarker.End();
  1332. return false;
  1333. }
  1334. // Load font face.
  1335. if (FontEngine.LoadFontFace(m_SourceFontFile, m_FaceInfo.pointSize) != FontEngineError.Success)
  1336. {
  1337. missingCharacters = characters;
  1338. k_TryAddCharactersMarker.End();
  1339. return false;
  1340. }
  1341. // Make sure font asset has been initialized
  1342. if (m_CharacterLookupDictionary == null || m_GlyphLookupDictionary == null)
  1343. ReadFontAssetDefinition();
  1344. // Clear data structures used to track which glyph needs to be added to atlas texture.
  1345. m_GlyphsToAdd.Clear();
  1346. m_GlyphsToAddLookup.Clear();
  1347. m_CharactersToAdd.Clear();
  1348. m_CharactersToAddLookup.Clear();
  1349. s_MissingCharacterList.Clear();
  1350. bool isMissingCharacters = false;
  1351. int characterCount = characters.Length;
  1352. // Iterate over each of the requested characters.
  1353. for (int i = 0; i < characterCount; i++)
  1354. {
  1355. uint unicode = characters[i];
  1356. // Check if character is already contained in the character table.
  1357. if (m_CharacterLookupDictionary.ContainsKey(unicode))
  1358. continue;
  1359. // Get the index of the glyph for this unicode value.
  1360. uint glyphIndex = FontEngine.GetGlyphIndex(unicode);
  1361. // Skip missing glyphs
  1362. if (glyphIndex == 0)
  1363. {
  1364. // Special handling for characters with potential alternative glyph representations
  1365. switch (unicode)
  1366. {
  1367. case 0xA0: // Non Breaking Space <NBSP>
  1368. // Use Space
  1369. glyphIndex = FontEngine.GetGlyphIndex(0x20);
  1370. break;
  1371. case 0xAD: // Soft Hyphen <SHY>
  1372. case 0x2011: // Non Breaking Hyphen
  1373. // Use Hyphen Minus
  1374. glyphIndex = FontEngine.GetGlyphIndex(0x2D);
  1375. break;
  1376. }
  1377. // Skip to next character if no potential alternative glyph representation is present in font file.
  1378. if (glyphIndex == 0)
  1379. {
  1380. // Add character to list of missing characters.
  1381. s_MissingCharacterList.Add(unicode);
  1382. isMissingCharacters = true;
  1383. continue;
  1384. }
  1385. }
  1386. TMP_Character character = new TMP_Character(unicode, glyphIndex);
  1387. // Check if glyph is already contained in the font asset as the same glyph might be referenced by multiple characters.
  1388. if (m_GlyphLookupDictionary.ContainsKey(glyphIndex))
  1389. {
  1390. // Add a reference to the source text asset and glyph
  1391. character.glyph = m_GlyphLookupDictionary[glyphIndex];
  1392. character.textAsset = this;
  1393. m_CharacterTable.Add(character);
  1394. m_CharacterLookupDictionary.Add(unicode, character);
  1395. continue;
  1396. }
  1397. // Make sure glyph index has not already been added to list of glyphs to add.
  1398. if (m_GlyphsToAddLookup.Add(glyphIndex))
  1399. m_GlyphsToAdd.Add(glyphIndex);
  1400. // Make sure unicode / character has not already been added.
  1401. if (m_CharactersToAddLookup.Add(unicode))
  1402. m_CharactersToAdd.Add(character);
  1403. }
  1404. if (m_GlyphsToAdd.Count == 0)
  1405. {
  1406. missingCharacters = characters;
  1407. k_TryAddCharactersMarker.End();
  1408. return false;
  1409. }
  1410. // Resize the Atlas Texture to the appropriate size
  1411. if (m_AtlasTextures[m_AtlasTextureIndex].width == 0 || m_AtlasTextures[m_AtlasTextureIndex].height == 0)
  1412. {
  1413. //Debug.Log("Setting initial size of atlas texture used by font asset [" + this.name + "].");
  1414. m_AtlasTextures[m_AtlasTextureIndex].Resize(m_AtlasWidth, m_AtlasHeight);
  1415. FontEngine.ResetAtlasTexture(m_AtlasTextures[m_AtlasTextureIndex]);
  1416. }
  1417. Glyph[] glyphs;
  1418. bool allGlyphsAddedToTexture = FontEngine.TryAddGlyphsToTexture(m_GlyphsToAdd, m_AtlasPadding, GlyphPackingMode.BestShortSideFit, m_FreeGlyphRects, m_UsedGlyphRects, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex], out glyphs);
  1419. for (int i = 0; i < glyphs.Length && glyphs[i] != null; i++)
  1420. {
  1421. Glyph glyph = glyphs[i];
  1422. uint glyphIndex = glyph.index;
  1423. glyph.atlasIndex = m_AtlasTextureIndex;
  1424. // Add new glyph to glyph table.
  1425. m_GlyphTable.Add(glyph);
  1426. m_GlyphLookupDictionary.Add(glyphIndex, glyph);
  1427. m_GlyphIndexListNewlyAdded.Add(glyphIndex);
  1428. m_GlyphIndexList.Add(glyphIndex);
  1429. }
  1430. // Clear glyph index list to track glyphs that were not added to the atlas texture
  1431. m_GlyphsToAdd.Clear();
  1432. // Add new characters to relevant data structures.
  1433. for (int i = 0; i < m_CharactersToAdd.Count; i++)
  1434. {
  1435. TMP_Character character = m_CharactersToAdd[i];
  1436. Glyph glyph;
  1437. if (m_GlyphLookupDictionary.TryGetValue(character.glyphIndex, out glyph) == false)
  1438. {
  1439. m_GlyphsToAdd.Add(character.glyphIndex);
  1440. continue;
  1441. }
  1442. // Add a reference to the source text asset and glyph
  1443. character.glyph = glyph;
  1444. character.textAsset = this;
  1445. m_CharacterTable.Add(character);
  1446. m_CharacterLookupDictionary.Add(character.unicode, character);
  1447. // Remove character from list to add
  1448. m_CharactersToAdd.RemoveAt(i);
  1449. i -= 1;
  1450. }
  1451. // Try adding glyphs that didn't fit in the current atlas texture to new atlas texture
  1452. if (m_IsMultiAtlasTexturesEnabled && allGlyphsAddedToTexture == false)
  1453. {
  1454. while (allGlyphsAddedToTexture == false)
  1455. allGlyphsAddedToTexture = TryAddGlyphsToNewAtlasTexture();
  1456. }
  1457. // Get Font Features for the given characters
  1458. if (includeFontFeatures)
  1459. UpdateGlyphAdjustmentRecords();
  1460. #if UNITY_EDITOR
  1461. // Makes the changes to the font asset persistent.
  1462. if (UnityEditor.EditorUtility.IsPersistent(this))
  1463. {
  1464. TMP_EditorResourceManager.RegisterResourceForUpdate(this);
  1465. }
  1466. #endif
  1467. missingCharacters = string.Empty;
  1468. // Populate list of missing characters
  1469. for (int i = 0; i < m_CharactersToAdd.Count; i++)
  1470. {
  1471. TMP_Character character = m_CharactersToAdd[i];
  1472. s_MissingCharacterList.Add(character.unicode);
  1473. }
  1474. if (s_MissingCharacterList.Count > 0)
  1475. missingCharacters = s_MissingCharacterList.UintToString();
  1476. k_TryAddCharactersMarker.End();
  1477. return allGlyphsAddedToTexture && !isMissingCharacters;
  1478. }
  1479. // Functions to remove...
  1480. /*
  1481. /// <summary>
  1482. /// NOT USED CURRENTLY - Try adding character using Unicode value to font asset.
  1483. /// </summary>
  1484. /// <param name="unicode">The Unicode value of the character.</param>
  1485. /// <param name="character">The character data if successfully added to the font asset. Null otherwise.</param>
  1486. /// <returns>Returns true if the character has been added. False otherwise.</returns>
  1487. internal bool TryAddCharacter_Internal(uint unicode)
  1488. {
  1489. TMP_Character character = null;
  1490. // Check if character is already contained in the character table.
  1491. if (m_CharacterLookupDictionary.ContainsKey(unicode))
  1492. return true;
  1493. uint glyphIndex = FontEngine.GetGlyphIndex(unicode);
  1494. if (glyphIndex == 0)
  1495. return false;
  1496. // Check if glyph is already contained in the font asset as the same glyph might be referenced by multiple characters.
  1497. if (m_GlyphLookupDictionary.ContainsKey(glyphIndex))
  1498. {
  1499. character = new TMP_Character(unicode, m_GlyphLookupDictionary[glyphIndex]);
  1500. m_CharacterTable.Add(character);
  1501. m_CharacterLookupDictionary.Add(unicode, character);
  1502. //#if UNITY_EDITOR
  1503. // Makes the changes to the font asset persistent.
  1504. // OPTIMIZATION: This could be handled when exiting Play mode if we added any new characters to the asset.
  1505. // Could also add some update registry to handle this.
  1506. //SortGlyphTable();
  1507. //UnityEditor.EditorUtility.SetDirty(this);
  1508. //#endif
  1509. return true;
  1510. }
  1511. // Resize the Atlas Texture to the appropriate size
  1512. if (m_AtlasTextures[m_AtlasTextureIndex].width == 0 || m_AtlasTextures[m_AtlasTextureIndex].height == 0)
  1513. {
  1514. //Debug.Log("Setting initial size of atlas texture used by font asset [" + this.name + "].");
  1515. m_AtlasTextures[m_AtlasTextureIndex].Resize(m_AtlasWidth, m_AtlasHeight);
  1516. FontEngine.ResetAtlasTexture(m_AtlasTextures[m_AtlasTextureIndex]);
  1517. }
  1518. Glyph glyph;
  1519. if (FontEngine.TryAddGlyphToTexture(glyphIndex, m_AtlasPadding, GlyphPackingMode.BestShortSideFit, m_FreeGlyphRects, m_UsedGlyphRects, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex], out glyph))
  1520. {
  1521. // Add new glyph to glyph table.
  1522. m_GlyphTable.Add(glyph);
  1523. m_GlyphLookupDictionary.Add(glyphIndex, glyph);
  1524. // Add new character
  1525. character = new TMP_Character(unicode, glyph);
  1526. m_CharacterTable.Add(character);
  1527. m_CharacterLookupDictionary.Add(unicode, character);
  1528. //#if UNITY_EDITOR
  1529. // Makes the changes to the font asset persistent.
  1530. // OPTIMIZATION: This could be handled when exiting Play mode if we added any new characters to the asset.
  1531. // Could also add some update registry to handle this.
  1532. //SortGlyphTable();
  1533. //UnityEditor.EditorUtility.SetDirty(this);
  1534. //#endif
  1535. return true;
  1536. }
  1537. return false;
  1538. }
  1539. /// <summary>
  1540. /// To be removed.
  1541. /// </summary>
  1542. /// <param name="unicode"></param>
  1543. /// <param name="glyph"></param>
  1544. internal TMP_Character AddCharacter_Internal(uint unicode, Glyph glyph)
  1545. {
  1546. // Check if character is already contained in the character table.
  1547. if (m_CharacterLookupDictionary.ContainsKey(unicode))
  1548. return m_CharacterLookupDictionary[unicode];
  1549. uint glyphIndex = glyph.index;
  1550. // Resize the Atlas Texture to the appropriate size
  1551. if (m_AtlasTextures[m_AtlasTextureIndex].width == 0 || m_AtlasTextures[m_AtlasTextureIndex].height == 0)
  1552. {
  1553. //Debug.Log("Setting initial size of atlas texture used by font asset [" + this.name + "].");
  1554. m_AtlasTextures[m_AtlasTextureIndex].Resize(m_AtlasWidth, m_AtlasHeight);
  1555. FontEngine.ResetAtlasTexture(m_AtlasTextures[m_AtlasTextureIndex]);
  1556. }
  1557. // Check if glyph is already contained in the glyph table.
  1558. if (m_GlyphLookupDictionary.ContainsKey(glyphIndex) == false)
  1559. {
  1560. if (glyph.glyphRect.width == 0 || glyph.glyphRect.width == 0)
  1561. {
  1562. // Glyphs with zero width and / or height can be automatically added to font asset.
  1563. m_GlyphTable.Add(glyph);
  1564. }
  1565. else
  1566. {
  1567. // Try packing new glyph
  1568. if (FontEngine.TryPackGlyphInAtlas(glyph, m_AtlasPadding, GlyphPackingMode.ContactPointRule, m_AtlasRenderMode, m_AtlasWidth, m_AtlasHeight, m_FreeGlyphRects, m_UsedGlyphRects) == false)
  1569. {
  1570. // TODO: Add handling to create new atlas texture to fit glyph.
  1571. return null;
  1572. }
  1573. //m_GlyphsToRender.Add(glyph);
  1574. }
  1575. }
  1576. // Add character to font asset.
  1577. TMP_Character character = new TMP_Character(unicode, glyph);
  1578. m_CharacterTable.Add(character);
  1579. m_CharacterLookupDictionary.Add(unicode, character);
  1580. //Debug.Log("Adding character [" + (char)unicode + "] with Unicode (" + unicode + ") to [" + this.name + "] font asset.");
  1581. // Schedule glyph to be added to the font atlas texture
  1582. //TM_FontAssetUpdateManager.RegisterFontAssetForUpdate(this);
  1583. //UpdateAtlasTexture(); // Temporary until callback system is revised.
  1584. //#if UNITY_EDITOR
  1585. // Makes the changes to the font asset persistent.
  1586. // OPTIMIZATION: This could be handled when exiting Play mode if we added any new characters to the asset.
  1587. // Could also add some update registry to handle this.
  1588. //SortGlyphTable();
  1589. //UnityEditor.EditorUtility.SetDirty(this);
  1590. //#endif
  1591. return character;
  1592. }
  1593. */
  1594. /// <summary>
  1595. /// Try adding character using Unicode value to font asset.
  1596. /// Function assumes internal user has already checked to make sure the character is not already contained in the font asset.
  1597. /// </summary>
  1598. /// <param name="unicode">The Unicode value of the character.</param>
  1599. /// <param name="character">The character data if successfully added to the font asset. Null otherwise.</param>
  1600. /// <returns>Returns true if the character has been added. False otherwise.</returns>
  1601. internal bool TryAddCharacterInternal(uint unicode, out TMP_Character character)
  1602. {
  1603. k_TryAddCharacterMarker.Begin();
  1604. character = null;
  1605. // Check if the Unicode character is already known to be missing from the source font file.
  1606. if (m_MissingUnicodesFromFontFile.Contains(unicode))
  1607. {
  1608. k_TryAddCharacterMarker.End();
  1609. return false;
  1610. }
  1611. // Load font face.
  1612. if (FontEngine.LoadFontFace(sourceFontFile, m_FaceInfo.pointSize) != FontEngineError.Success)
  1613. {
  1614. k_TryAddCharacterMarker.End();
  1615. return false;
  1616. }
  1617. uint glyphIndex = FontEngine.GetGlyphIndex(unicode);
  1618. if (glyphIndex == 0)
  1619. {
  1620. // Special handling for characters with potential alternative glyph representations
  1621. switch (unicode)
  1622. {
  1623. case 0xA0: // Non Breaking Space <NBSP>
  1624. // Use Space
  1625. glyphIndex = FontEngine.GetGlyphIndex(0x20);
  1626. break;
  1627. case 0xAD: // Soft Hyphen <SHY>
  1628. case 0x2011: // Non Breaking Hyphen
  1629. // Use Hyphen Minus
  1630. glyphIndex = FontEngine.GetGlyphIndex(0x2D);
  1631. break;
  1632. }
  1633. // Return if no potential alternative glyph representation is present in font file.
  1634. if (glyphIndex == 0)
  1635. {
  1636. m_MissingUnicodesFromFontFile.Add(unicode);
  1637. k_TryAddCharacterMarker.End();
  1638. return false;
  1639. }
  1640. }
  1641. // Check if glyph is already contained in the font asset as the same glyph might be referenced by multiple characters.
  1642. if (m_GlyphLookupDictionary.ContainsKey(glyphIndex))
  1643. {
  1644. character = new TMP_Character(unicode, this, m_GlyphLookupDictionary[glyphIndex]);
  1645. m_CharacterTable.Add(character);
  1646. m_CharacterLookupDictionary.Add(unicode, character);
  1647. #if UNITY_EDITOR
  1648. // Makes the changes to the font asset persistent.
  1649. // OPTIMIZATION: This could be handled when exiting Play mode if we added any new characters to the asset.
  1650. // Could also add some update registry to handle this.
  1651. //SortGlyphTable();
  1652. if (UnityEditor.EditorUtility.IsPersistent(this))
  1653. {
  1654. TMP_EditorResourceManager.RegisterResourceForUpdate(this);
  1655. }
  1656. #endif
  1657. k_TryAddCharacterMarker.End();
  1658. return true;
  1659. }
  1660. Glyph glyph = null;
  1661. // TODO: Potential new feature to explore where selected font assets share the same atlas texture(s).
  1662. // Handling if using Dynamic Textures
  1663. //if (m_IsUsingDynamicTextures)
  1664. //{
  1665. // if (TMP_DynamicAtlasTextureGroup.AddGlyphToManagedDynamicTexture(this, glyphIndex, m_AtlasPadding, m_AtlasRenderMode, out glyph))
  1666. // {
  1667. // // Add new glyph to glyph table.
  1668. // m_GlyphTable.Add(glyph);
  1669. // m_GlyphLookupDictionary.Add(glyphIndex, glyph);
  1670. // // Add new character
  1671. // character = new TMP_Character(unicode, glyph);
  1672. // m_CharacterTable.Add(character);
  1673. // m_CharacterLookupDictionary.Add(unicode, character);
  1674. // m_GlyphIndexList.Add(glyphIndex);
  1675. // if (TMP_Settings.getFontFeaturesAtRuntime)
  1676. // {
  1677. // if (k_FontAssetsToUpdateLookup.Add(instanceID))
  1678. // k_FontAssetsToUpdate.Add(this);
  1679. // }
  1680. // return true;
  1681. // }
  1682. //}
  1683. // Make sure atlas texture is readable.
  1684. if (m_AtlasTextures[m_AtlasTextureIndex].isReadable == false)
  1685. {
  1686. Debug.LogWarning("Unable to add the requested character to font asset [" + this.name + "]'s atlas texture. Please make the texture [" + m_AtlasTextures[m_AtlasTextureIndex].name + "] readable.", m_AtlasTextures[m_AtlasTextureIndex]);
  1687. k_TryAddCharacterMarker.End();
  1688. return false;
  1689. }
  1690. // Resize the Atlas Texture to the appropriate size
  1691. if (m_AtlasTextures[m_AtlasTextureIndex].width == 0 || m_AtlasTextures[m_AtlasTextureIndex].height == 0)
  1692. {
  1693. m_AtlasTextures[m_AtlasTextureIndex].Resize(m_AtlasWidth, m_AtlasHeight);
  1694. FontEngine.ResetAtlasTexture(m_AtlasTextures[m_AtlasTextureIndex]);
  1695. }
  1696. // Try adding glyph to local atlas texture
  1697. if (FontEngine.TryAddGlyphToTexture(glyphIndex, m_AtlasPadding, GlyphPackingMode.BestShortSideFit, m_FreeGlyphRects, m_UsedGlyphRects, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex], out glyph))
  1698. {
  1699. // Update glyph atlas index
  1700. glyph.atlasIndex = m_AtlasTextureIndex;
  1701. // Add new glyph to glyph table.
  1702. m_GlyphTable.Add(glyph);
  1703. m_GlyphLookupDictionary.Add(glyphIndex, glyph);
  1704. // Add new character
  1705. character = new TMP_Character(unicode, this, glyph);
  1706. m_CharacterTable.Add(character);
  1707. m_CharacterLookupDictionary.Add(unicode, character);
  1708. m_GlyphIndexList.Add(glyphIndex);
  1709. m_GlyphIndexListNewlyAdded.Add(glyphIndex);
  1710. if (TMP_Settings.getFontFeaturesAtRuntime)
  1711. RegisterFontAssetForFontFeatureUpdate(this);
  1712. #if UNITY_EDITOR
  1713. // Makes the changes to the font asset persistent.
  1714. // OPTIMIZATION: This could be handled when exiting Play mode if we added any new characters to the asset.
  1715. // Could also add some update registry to handle this.
  1716. //SortGlyphTable();
  1717. if (UnityEditor.EditorUtility.IsPersistent(this))
  1718. {
  1719. TMP_EditorResourceManager.RegisterResourceForUpdate(this);
  1720. }
  1721. #endif
  1722. k_TryAddCharacterMarker.End();
  1723. return true;
  1724. }
  1725. // Add glyph which did not fit in current atlas texture to new atlas texture.
  1726. if (m_IsMultiAtlasTexturesEnabled)
  1727. {
  1728. // Create new atlas texture
  1729. SetupNewAtlasTexture();
  1730. // Try adding glyph to newly created atlas texture
  1731. if (FontEngine.TryAddGlyphToTexture(glyphIndex, m_AtlasPadding, GlyphPackingMode.BestShortSideFit, m_FreeGlyphRects, m_UsedGlyphRects, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex], out glyph))
  1732. {
  1733. // Update glyph atlas index
  1734. glyph.atlasIndex = m_AtlasTextureIndex;
  1735. // Add new glyph to glyph table.
  1736. m_GlyphTable.Add(glyph);
  1737. m_GlyphLookupDictionary.Add(glyphIndex, glyph);
  1738. // Add new character
  1739. character = new TMP_Character(unicode, this, glyph);
  1740. m_CharacterTable.Add(character);
  1741. m_CharacterLookupDictionary.Add(unicode, character);
  1742. m_GlyphIndexList.Add(glyphIndex);
  1743. m_GlyphIndexListNewlyAdded.Add(glyphIndex);
  1744. if (TMP_Settings.getFontFeaturesAtRuntime)
  1745. RegisterFontAssetForFontFeatureUpdate(this);
  1746. #if UNITY_EDITOR
  1747. //SortGlyphTable();
  1748. if (UnityEditor.EditorUtility.IsPersistent(this))
  1749. {
  1750. TMP_EditorResourceManager.RegisterResourceForUpdate(this);
  1751. }
  1752. #endif
  1753. k_TryAddCharacterMarker.End();
  1754. return true;
  1755. }
  1756. }
  1757. k_TryAddCharacterMarker.End();
  1758. return false;
  1759. }
  1760. internal bool TryGetCharacter_and_QueueRenderToTexture(uint unicode, out TMP_Character character)
  1761. {
  1762. k_TryAddCharacterMarker.Begin();
  1763. character = null;
  1764. // Check if the Unicode character is already known to be missing from the source font file.
  1765. if (m_MissingUnicodesFromFontFile.Contains(unicode))
  1766. {
  1767. k_TryAddCharacterMarker.End();
  1768. return false;
  1769. }
  1770. // Load font face.
  1771. if (FontEngine.LoadFontFace(sourceFontFile, m_FaceInfo.pointSize) != FontEngineError.Success)
  1772. {
  1773. k_TryAddCharacterMarker.End();
  1774. return false;
  1775. }
  1776. uint glyphIndex = FontEngine.GetGlyphIndex(unicode);
  1777. if (glyphIndex == 0)
  1778. {
  1779. // Special handling for characters with potential alternative glyph representations
  1780. switch (unicode)
  1781. {
  1782. case 0xA0: // Non Breaking Space <NBSP>
  1783. // Use Space
  1784. glyphIndex = FontEngine.GetGlyphIndex(0x20);
  1785. break;
  1786. case 0xAD: // Soft Hyphen <SHY>
  1787. case 0x2011: // Non Breaking Hyphen
  1788. // Use Hyphen Minus
  1789. glyphIndex = FontEngine.GetGlyphIndex(0x2D);
  1790. break;
  1791. }
  1792. // Return if no potential alternative glyph representation is present in font file.
  1793. if (glyphIndex == 0)
  1794. {
  1795. m_MissingUnicodesFromFontFile.Add(unicode);
  1796. k_TryAddCharacterMarker.End();
  1797. return false;
  1798. }
  1799. }
  1800. // Check if glyph is already contained in the font asset as the same glyph might be referenced by multiple characters.
  1801. if (m_GlyphLookupDictionary.ContainsKey(glyphIndex))
  1802. {
  1803. character = new TMP_Character(unicode, this, m_GlyphLookupDictionary[glyphIndex]);
  1804. m_CharacterTable.Add(character);
  1805. m_CharacterLookupDictionary.Add(unicode, character);
  1806. #if UNITY_EDITOR
  1807. // Makes the changes to the font asset persistent.
  1808. // OPTIMIZATION: This could be handled when exiting Play mode if we added any new characters to the asset.
  1809. // Could also add some update registry to handle this.
  1810. //SortGlyphTable();
  1811. if (UnityEditor.EditorUtility.IsPersistent(this))
  1812. {
  1813. TMP_EditorResourceManager.RegisterResourceForUpdate(this);
  1814. }
  1815. #endif
  1816. k_TryAddCharacterMarker.End();
  1817. return true;
  1818. }
  1819. GlyphLoadFlags glyphLoadFlags = (GlyphRasterModes.RASTER_MODE_NO_HINTING & (GlyphRasterModes)m_AtlasRenderMode) == GlyphRasterModes.RASTER_MODE_NO_HINTING
  1820. ? GlyphLoadFlags.LOAD_NO_BITMAP | GlyphLoadFlags.LOAD_NO_HINTING
  1821. : GlyphLoadFlags.LOAD_NO_BITMAP;
  1822. Glyph glyph = null;
  1823. if (FontEngine.TryGetGlyphWithIndexValue(glyphIndex, glyphLoadFlags, out glyph))
  1824. {
  1825. // Add new glyph to glyph table.
  1826. m_GlyphTable.Add(glyph);
  1827. m_GlyphLookupDictionary.Add(glyphIndex, glyph);
  1828. // Add new character
  1829. character = new TMP_Character(unicode, this, glyph);
  1830. m_CharacterTable.Add(character);
  1831. m_CharacterLookupDictionary.Add(unicode, character);
  1832. m_GlyphIndexList.Add(glyphIndex);
  1833. m_GlyphIndexListNewlyAdded.Add(glyphIndex);
  1834. if (TMP_Settings.getFontFeaturesAtRuntime)
  1835. RegisterFontAssetForFontFeatureUpdate(this);
  1836. // Add glyph to list of glyphs to be rendered
  1837. m_GlyphsToRender.Add(glyph);
  1838. // Register font asset to render and add glyphs to atlas textures
  1839. RegisterFontAssetForAtlasTextureUpdate(this);
  1840. #if UNITY_EDITOR
  1841. // Makes the changes to the font asset persistent.
  1842. // OPTIMIZATION: This could be handled when exiting Play mode if we added any new characters to the asset.
  1843. // Could also add some update registry to handle this.
  1844. //SortGlyphTable();
  1845. if (UnityEditor.EditorUtility.IsPersistent(this))
  1846. {
  1847. TMP_EditorResourceManager.RegisterResourceForUpdate(this);
  1848. }
  1849. #endif
  1850. k_TryAddCharacterMarker.End();
  1851. return true;
  1852. }
  1853. k_TryAddCharacterMarker.End();
  1854. return false;
  1855. }
  1856. /// <summary>
  1857. /// This function requires an update to the TextCore:FontEngine
  1858. /// </summary>
  1859. internal void TryAddGlyphsToAtlasTextures()
  1860. {
  1861. /*
  1862. // Return if we don't have any glyphs to add.
  1863. if (m_GlyphsToRender.Count == 0)
  1864. return;
  1865. // Resize the Atlas Texture to the appropriate size
  1866. if (m_AtlasTextures[m_AtlasTextureIndex].width == 0 || m_AtlasTextures[m_AtlasTextureIndex].height == 0)
  1867. {
  1868. //Debug.Log("Setting initial size of atlas texture used by font asset [" + this.name + "].");
  1869. m_AtlasTextures[m_AtlasTextureIndex].Resize(m_AtlasWidth, m_AtlasHeight);
  1870. FontEngine.ResetAtlasTexture(m_AtlasTextures[m_AtlasTextureIndex]);
  1871. }
  1872. bool allGlyphsAddedToTexture = FontEngine.TryAddGlyphsToTexture(m_GlyphsToRender, m_GlyphsRendered, m_AtlasPadding, GlyphPackingMode.BestShortSideFit, m_FreeGlyphRects, m_UsedGlyphRects, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex]);
  1873. // Try adding glyphs that didn't fit in the current atlas texture to new atlas texture
  1874. if (m_IsMultiAtlasTexturesEnabled && allGlyphsAddedToTexture == false)
  1875. {
  1876. while (allGlyphsAddedToTexture == false)
  1877. {
  1878. // Create and prepare new atlas texture
  1879. SetupNewAtlasTexture();
  1880. // Try adding remaining glyphs in the newly created atlas texture
  1881. allGlyphsAddedToTexture = FontEngine.TryAddGlyphsToTexture(m_GlyphsToRender, m_GlyphsRendered, m_AtlasPadding, GlyphPackingMode.BestShortSideFit, m_FreeGlyphRects, m_UsedGlyphRects, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex]);
  1882. }
  1883. }
  1884. if (allGlyphsAddedToTexture == false)
  1885. {
  1886. // TODO: Handle case when we have left over glyph to render that didn't fit in the atlas texture.
  1887. Debug.LogError("Unable to add some glyphs to atlas texture.");
  1888. }
  1889. #if UNITY_EDITOR
  1890. // Makes the changes to the font asset persistent.
  1891. if (UnityEditor.EditorUtility.IsPersistent(this))
  1892. {
  1893. //SortGlyphAndCharacterTables();
  1894. TMP_EditorResourceManager.RegisterResourceForUpdate(this);
  1895. }
  1896. #endif
  1897. */
  1898. }
  1899. /// <summary>
  1900. ///
  1901. /// </summary>
  1902. /// <returns></returns>
  1903. bool TryAddGlyphsToNewAtlasTexture()
  1904. {
  1905. // Create and prepare new atlas texture
  1906. SetupNewAtlasTexture();
  1907. Glyph[] glyphs;
  1908. // Try adding remaining glyphs in the newly created atlas texture
  1909. bool allGlyphsAddedToTexture = FontEngine.TryAddGlyphsToTexture(m_GlyphsToAdd, m_AtlasPadding, GlyphPackingMode.BestShortSideFit, m_FreeGlyphRects, m_UsedGlyphRects, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex], out glyphs);
  1910. // Add new glyphs to relevant data structures.
  1911. for (int i = 0; i < glyphs.Length && glyphs[i] != null; i++)
  1912. {
  1913. Glyph glyph = glyphs[i];
  1914. uint glyphIndex = glyph.index;
  1915. glyph.atlasIndex = m_AtlasTextureIndex;
  1916. // Add new glyph to glyph table.
  1917. m_GlyphTable.Add(glyph);
  1918. m_GlyphLookupDictionary.Add(glyphIndex, glyph);
  1919. m_GlyphIndexListNewlyAdded.Add(glyphIndex);
  1920. m_GlyphIndexList.Add(glyphIndex);
  1921. }
  1922. // Clear glyph index list to allow us to track glyphs
  1923. m_GlyphsToAdd.Clear();
  1924. // Add new characters to relevant data structures as well as track glyphs that could not be added to the current atlas texture.
  1925. for (int i = 0; i < m_CharactersToAdd.Count; i++)
  1926. {
  1927. TMP_Character character = m_CharactersToAdd[i];
  1928. Glyph glyph;
  1929. if (m_GlyphLookupDictionary.TryGetValue(character.glyphIndex, out glyph) == false)
  1930. {
  1931. m_GlyphsToAdd.Add(character.glyphIndex);
  1932. continue;
  1933. }
  1934. // Add a reference to the source text asset and glyph
  1935. character.glyph = glyph;
  1936. character.textAsset = this;
  1937. m_CharacterTable.Add(character);
  1938. m_CharacterLookupDictionary.Add(character.unicode, character);
  1939. // Remove character
  1940. m_CharactersToAdd.RemoveAt(i);
  1941. i -= 1;
  1942. }
  1943. return allGlyphsAddedToTexture;
  1944. }
  1945. /// <summary>
  1946. ///
  1947. /// </summary>
  1948. void SetupNewAtlasTexture()
  1949. {
  1950. m_AtlasTextureIndex += 1;
  1951. // Check size of atlas texture array
  1952. if (m_AtlasTextures.Length == m_AtlasTextureIndex)
  1953. Array.Resize(ref m_AtlasTextures, m_AtlasTextures.Length * 2);
  1954. // Initialize new atlas texture
  1955. m_AtlasTextures[m_AtlasTextureIndex] = new Texture2D(m_AtlasWidth, m_AtlasHeight, TextureFormat.Alpha8, false);
  1956. FontEngine.ResetAtlasTexture(m_AtlasTextures[m_AtlasTextureIndex]);
  1957. // Clear packing GlyphRects
  1958. int packingModifier = ((GlyphRasterModes)m_AtlasRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP ? 0 : 1;
  1959. m_FreeGlyphRects.Clear();
  1960. m_FreeGlyphRects.Add(new GlyphRect(0, 0, m_AtlasWidth - packingModifier, m_AtlasHeight - packingModifier));
  1961. m_UsedGlyphRects.Clear();
  1962. #if UNITY_EDITOR
  1963. // Add new texture as sub asset to font asset
  1964. if (UnityEditor.EditorUtility.IsPersistent(this))
  1965. {
  1966. Texture2D tex = m_AtlasTextures[m_AtlasTextureIndex];
  1967. tex.name = m_AtlasTexture.name + " " + m_AtlasTextureIndex;
  1968. UnityEditor.AssetDatabase.AddObjectToAsset(m_AtlasTextures[m_AtlasTextureIndex], this);
  1969. TMP_EditorResourceManager.RegisterResourceForReimport(this);
  1970. }
  1971. #endif
  1972. }
  1973. /// <summary>
  1974. /// Not used currently
  1975. /// </summary>
  1976. internal void UpdateAtlasTexture()
  1977. {
  1978. // Return if we don't have any glyphs to add to atlas texture.
  1979. if (m_GlyphsToRender.Count == 0)
  1980. return;
  1981. //Debug.Log("Updating [" + this.name + "]'s atlas texture.");
  1982. // Pack glyphs in the given atlas texture size.
  1983. // TODO: Packing and glyph render modes should be defined in the font asset.
  1984. //FontEngine.PackGlyphsInAtlas(m_GlyphsToPack, m_GlyphsPacked, m_AtlasPadding, GlyphPackingMode.ContactPointRule, GlyphRenderMode.SDFAA, m_AtlasWidth, m_AtlasHeight, m_FreeGlyphRects, m_UsedGlyphRects);
  1985. //FontEngine.RenderGlyphsToTexture(m_GlyphsPacked, m_AtlasPadding, GlyphRenderMode.SDFAA, m_AtlasTextures[m_AtlasTextureIndex]);
  1986. // Resize the Atlas Texture to the appropriate size
  1987. if (m_AtlasTextures[m_AtlasTextureIndex].width == 0 || m_AtlasTextures[m_AtlasTextureIndex].height == 0)
  1988. {
  1989. //Debug.Log("Setting initial size of atlas texture used by font asset [" + this.name + "].");
  1990. m_AtlasTextures[m_AtlasTextureIndex].Resize(m_AtlasWidth, m_AtlasHeight);
  1991. FontEngine.ResetAtlasTexture(m_AtlasTextures[m_AtlasTextureIndex]);
  1992. }
  1993. //FontEngine.RenderGlyphsToTexture(m_GlyphsToRender, m_AtlasPadding, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex]);
  1994. // Apply changes to atlas texture
  1995. m_AtlasTextures[m_AtlasTextureIndex].Apply(false, false);
  1996. // Add glyphs that were successfully packed to the glyph table.
  1997. //for (int i = 0; i < m_GlyphsToRender.Count /* m_GlyphsPacked.Count */; i++)
  1998. //{
  1999. // Glyph glyph = m_GlyphsToRender[i]; // m_GlyphsPacked[i];
  2000. // // Update atlas texture index
  2001. // glyph.atlasIndex = m_AtlasTextureIndex;
  2002. // m_GlyphTable.Add(glyph);
  2003. // m_GlyphLookupDictionary.Add(glyph.index, glyph);
  2004. //}
  2005. // Clear list of glyphs
  2006. //m_GlyphsPacked.Clear();
  2007. //m_GlyphsToRender.Clear();
  2008. // Add any remaining glyphs into new atlas texture if multi texture support if enabled.
  2009. //if (m_GlyphsToPack.Count > 0)
  2010. //{
  2011. /*
  2012. // Create new atlas texture
  2013. Texture2D tex = new Texture2D(m_AtlasWidth, m_AtlasHeight, TextureFormat.Alpha8, false, true);
  2014. tex.SetPixels32(new Color32[m_AtlasWidth * m_AtlasHeight]);
  2015. tex.Apply();
  2016. m_AtlasTextureIndex++;
  2017. if (m_AtlasTextures.Length == m_AtlasTextureIndex)
  2018. Array.Resize(ref m_AtlasTextures, Mathf.NextPowerOfTwo(m_AtlasTextureIndex + 1));
  2019. m_AtlasTextures[m_AtlasTextureIndex] = tex;
  2020. */
  2021. //}
  2022. #if UNITY_EDITOR
  2023. // Makes the changes to the font asset persistent.
  2024. //SortAllTables();
  2025. TMP_EditorResourceManager.RegisterResourceForUpdate(this);
  2026. #endif
  2027. }
  2028. /// <summary>
  2029. ///
  2030. /// </summary>
  2031. internal void UpdateGlyphAdjustmentRecords()
  2032. {
  2033. k_UpdateGlyphAdjustmentRecordsMarker.Begin();
  2034. // Get glyph pair adjustment records from font file.
  2035. #if UNITY_2018_3 || UNITY_2019_1 || UNITY_2019_2 || UNITY_2019_3
  2036. CopyListDataToArray(m_GlyphIndexList, ref k_GlyphIndexArray);
  2037. GlyphPairAdjustmentRecord[] pairAdjustmentRecords = FontEngine.GetGlyphPairAdjustmentTable(k_GlyphIndexArray);
  2038. #else
  2039. //GlyphPairAdjustmentRecord[] pairAdjustmentRecords = FontEngine.GetGlyphPairAdjustmentRecords(m_GlyphIndexListNewlyAdded, m_GlyphIndexList);
  2040. GlyphPairAdjustmentRecord[] pairAdjustmentRecords = FontEngine.GetGlyphPairAdjustmentRecords(m_GlyphIndexList, out int recordCount);
  2041. #endif
  2042. // Clear newly added glyph list
  2043. m_GlyphIndexListNewlyAdded.Clear();
  2044. if (pairAdjustmentRecords == null || pairAdjustmentRecords.Length == 0)
  2045. {
  2046. k_UpdateGlyphAdjustmentRecordsMarker.End();
  2047. return;
  2048. }
  2049. if (m_FontFeatureTable == null)
  2050. m_FontFeatureTable = new TMP_FontFeatureTable();
  2051. for (int i = 0; i < pairAdjustmentRecords.Length && pairAdjustmentRecords[i].firstAdjustmentRecord.glyphIndex != 0; i++)
  2052. {
  2053. uint pairKey = pairAdjustmentRecords[i].secondAdjustmentRecord.glyphIndex << 16 | pairAdjustmentRecords[i].firstAdjustmentRecord.glyphIndex;
  2054. // Check if table already contains a pair adjustment record for this key.
  2055. if (m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookupDictionary.ContainsKey(pairKey))
  2056. continue;
  2057. TMP_GlyphPairAdjustmentRecord record = new TMP_GlyphPairAdjustmentRecord(pairAdjustmentRecords[i]);
  2058. m_FontFeatureTable.m_GlyphPairAdjustmentRecords.Add(record);
  2059. m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookupDictionary.Add(pairKey, record);
  2060. }
  2061. k_UpdateGlyphAdjustmentRecordsMarker.End();
  2062. }
  2063. /// <summary>
  2064. /// Function used for debugging and performance testing.
  2065. /// </summary>
  2066. /// <param name="glyphIndexes"></param>
  2067. internal void UpdateGlyphAdjustmentRecords(uint[] glyphIndexes)
  2068. {
  2069. k_UpdateGlyphAdjustmentRecordsMarker.Begin();
  2070. // Get glyph pair adjustment records from font file.
  2071. GlyphPairAdjustmentRecord[] pairAdjustmentRecords = FontEngine.GetGlyphPairAdjustmentTable(glyphIndexes);
  2072. // Clear newly added glyph list
  2073. //m_GlyphIndexListNewlyAdded.Clear();
  2074. if (pairAdjustmentRecords == null || pairAdjustmentRecords.Length == 0)
  2075. {
  2076. k_UpdateGlyphAdjustmentRecordsMarker.End();
  2077. return;
  2078. }
  2079. if (m_FontFeatureTable == null)
  2080. m_FontFeatureTable = new TMP_FontFeatureTable();
  2081. for (int i = 0; i < pairAdjustmentRecords.Length && pairAdjustmentRecords[i].firstAdjustmentRecord.glyphIndex != 0; i++)
  2082. {
  2083. uint pairKey = pairAdjustmentRecords[i].secondAdjustmentRecord.glyphIndex << 16 | pairAdjustmentRecords[i].firstAdjustmentRecord.glyphIndex;
  2084. // Check if table already contains a pair adjustment record for this key.
  2085. if (m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookupDictionary.ContainsKey(pairKey))
  2086. continue;
  2087. TMP_GlyphPairAdjustmentRecord record = new TMP_GlyphPairAdjustmentRecord(pairAdjustmentRecords[i]);
  2088. m_FontFeatureTable.m_GlyphPairAdjustmentRecords.Add(record);
  2089. m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookupDictionary.Add(pairKey, record);
  2090. }
  2091. k_UpdateGlyphAdjustmentRecordsMarker.End();
  2092. }
  2093. /// <summary>
  2094. /// Function requires an update to the TextCore:FontEngine
  2095. /// </summary>
  2096. /// <param name="glyphIndexes"></param>
  2097. internal void UpdateGlyphAdjustmentRecords(List<uint> glyphIndexes)
  2098. {
  2099. /*
  2100. k_UpdateGlyphAdjustmentRecordsMarker.Begin();
  2101. // Get glyph pair adjustment records from font file.
  2102. int recordCount;
  2103. GlyphPairAdjustmentRecord[] pairAdjustmentRecords = FontEngine.GetGlyphPairAdjustmentRecords(glyphIndexes, out recordCount);
  2104. // Clear newly added glyph list
  2105. m_GlyphIndexListNewlyAdded.Clear();
  2106. if (pairAdjustmentRecords == null || pairAdjustmentRecords.Length == 0)
  2107. {
  2108. k_UpdateGlyphAdjustmentRecordsMarker.End();
  2109. return;
  2110. }
  2111. if (m_FontFeatureTable == null)
  2112. m_FontFeatureTable = new TMP_FontFeatureTable();
  2113. for (int i = 0; i < pairAdjustmentRecords.Length && pairAdjustmentRecords[i].firstAdjustmentRecord.glyphIndex != 0; i++)
  2114. {
  2115. uint pairKey = pairAdjustmentRecords[i].secondAdjustmentRecord.glyphIndex << 16 | pairAdjustmentRecords[i].firstAdjustmentRecord.glyphIndex;
  2116. // Check if table already contains a pair adjustment record for this key.
  2117. if (m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookupDictionary.ContainsKey(pairKey))
  2118. continue;
  2119. TMP_GlyphPairAdjustmentRecord record = new TMP_GlyphPairAdjustmentRecord(pairAdjustmentRecords[i]);
  2120. m_FontFeatureTable.m_GlyphPairAdjustmentRecords.Add(record);
  2121. m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookupDictionary.Add(pairKey, record);
  2122. }
  2123. k_UpdateGlyphAdjustmentRecordsMarker.End();
  2124. #if UNITY_EDITOR
  2125. m_FontFeatureTable.SortGlyphPairAdjustmentRecords();
  2126. #endif
  2127. */
  2128. }
  2129. /// <summary>
  2130. /// Function requires an update to the TextCore:FontEngine
  2131. /// </summary>
  2132. /// <param name="newGlyphIndexes"></param>
  2133. /// <param name="allGlyphIndexes"></param>
  2134. internal void UpdateGlyphAdjustmentRecords(List<uint> newGlyphIndexes, List<uint> allGlyphIndexes)
  2135. {
  2136. /*
  2137. // Get glyph pair adjustment records from font file.
  2138. GlyphPairAdjustmentRecord[] pairAdjustmentRecords = FontEngine.GetGlyphPairAdjustmentRecords(newGlyphIndexes, allGlyphIndexes);
  2139. // Clear newly added glyph list
  2140. m_GlyphIndexListNewlyAdded.Clear();
  2141. if (pairAdjustmentRecords == null || pairAdjustmentRecords.Length == 0)
  2142. {
  2143. return;
  2144. }
  2145. if (m_FontFeatureTable == null)
  2146. m_FontFeatureTable = new TMP_FontFeatureTable();
  2147. for (int i = 0; i < pairAdjustmentRecords.Length && pairAdjustmentRecords[i].firstAdjustmentRecord.glyphIndex != 0; i++)
  2148. {
  2149. uint pairKey = pairAdjustmentRecords[i].secondAdjustmentRecord.glyphIndex << 16 | pairAdjustmentRecords[i].firstAdjustmentRecord.glyphIndex;
  2150. // Check if table already contains a pair adjustment record for this key.
  2151. if (m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookupDictionary.ContainsKey(pairKey))
  2152. continue;
  2153. TMP_GlyphPairAdjustmentRecord record = new TMP_GlyphPairAdjustmentRecord(pairAdjustmentRecords[i]);
  2154. m_FontFeatureTable.m_GlyphPairAdjustmentRecords.Add(record);
  2155. m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookupDictionary.Add(pairKey, record);
  2156. }
  2157. #if UNITY_EDITOR
  2158. m_FontFeatureTable.SortGlyphPairAdjustmentRecords();
  2159. #endif
  2160. */
  2161. }
  2162. /// <summary>
  2163. /// Internal method to copy generic list data to generic array of the same type.
  2164. /// </summary>
  2165. /// <param name="srcList">Source</param>
  2166. /// <param name="dstArray">Destination</param>
  2167. /// <typeparam name="T">Element type</typeparam>
  2168. void CopyListDataToArray<T>(List<T> srcList, ref T[] dstArray)
  2169. {
  2170. int size = srcList.Count;
  2171. // Make sure destination array is appropriately sized.
  2172. if (dstArray == null)
  2173. dstArray = new T[size];
  2174. else
  2175. Array.Resize(ref dstArray, size);
  2176. for (int i = 0; i < size; i++)
  2177. dstArray[i] = srcList[i];
  2178. }
  2179. /// <summary>
  2180. /// Clears font asset data including the glyph and character tables and textures.
  2181. /// Function might be changed to Internal and only used in tests.
  2182. /// </summary>
  2183. /// <param name="setAtlasSizeToZero">Will set the atlas texture size to zero width and height if true.</param>
  2184. public void ClearFontAssetData(bool setAtlasSizeToZero = false)
  2185. {
  2186. k_ClearFontAssetDataMarker.Begin();
  2187. #if UNITY_EDITOR
  2188. // Record full object undo in the Editor.
  2189. //UnityEditor.Undo.RecordObjects(new UnityEngine.Object[] { this, this.atlasTexture }, "Resetting Font Asset");
  2190. #endif
  2191. // Clear glyph, character and font feature tables
  2192. ClearFontAssetTables();
  2193. // Clear atlas textures
  2194. ClearAtlasTextures(setAtlasSizeToZero);
  2195. ReadFontAssetDefinition();
  2196. //TMP_ResourceManager.RebuildFontAssetCache(instanceID);
  2197. #if UNITY_EDITOR
  2198. // Makes the changes to the font asset persistent.
  2199. TMP_EditorResourceManager.RegisterResourceForUpdate(this);
  2200. #endif
  2201. k_ClearFontAssetDataMarker.End();
  2202. }
  2203. internal void ClearFontAssetDataInternal()
  2204. {
  2205. // Clear glyph, character and font feature tables
  2206. ClearFontAssetTables();
  2207. // Clear atlas textures
  2208. ClearAtlasTextures(true);
  2209. #if UNITY_EDITOR
  2210. // Makes the changes to the font asset persistent.
  2211. TMP_EditorResourceManager.RegisterResourceForUpdate(this);
  2212. #endif
  2213. }
  2214. /// <summary>
  2215. ///
  2216. /// </summary>
  2217. internal void UpdateFontAssetData()
  2218. {
  2219. k_UpdateFontAssetDataMarker.Begin();
  2220. // Get list of all characters currently contained in the font asset.
  2221. uint[] unicodeCharacters = new uint[m_CharacterTable.Count];
  2222. for (int i = 0; i < m_CharacterTable.Count; i++)
  2223. unicodeCharacters[i] = m_CharacterTable[i].unicode;
  2224. // Clear glyph, character and font feature tables
  2225. ClearFontAssetTables();
  2226. // Clear atlas textures
  2227. ClearAtlasTextures(true);
  2228. ReadFontAssetDefinition();
  2229. //TMP_ResourceManager.RebuildFontAssetCache(instanceID);
  2230. // Add existing glyphs and characters back in the font asset (if any)
  2231. if (unicodeCharacters.Length > 0)
  2232. TryAddCharacters(unicodeCharacters, true);
  2233. k_UpdateFontAssetDataMarker.End();
  2234. }
  2235. /// <summary>
  2236. ///
  2237. /// </summary>
  2238. internal void ClearFontAssetTables()
  2239. {
  2240. // Clear glyph and character tables
  2241. if (m_GlyphTable != null)
  2242. m_GlyphTable.Clear();
  2243. if (m_CharacterTable != null)
  2244. m_CharacterTable.Clear();
  2245. // Clear glyph rectangles
  2246. if (m_UsedGlyphRects != null)
  2247. m_UsedGlyphRects.Clear();
  2248. if (m_FreeGlyphRects != null)
  2249. {
  2250. int packingModifier = ((GlyphRasterModes)m_AtlasRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP ? 0 : 1;
  2251. m_FreeGlyphRects.Clear();
  2252. m_FreeGlyphRects.Add(new GlyphRect(0, 0, m_AtlasWidth - packingModifier, m_AtlasHeight - packingModifier));
  2253. }
  2254. if (m_GlyphsToRender != null)
  2255. m_GlyphsToRender.Clear();
  2256. if (m_GlyphsRendered != null)
  2257. m_GlyphsRendered.Clear();
  2258. // Clear Glyph Adjustment Table
  2259. if (m_FontFeatureTable != null && m_FontFeatureTable.m_GlyphPairAdjustmentRecords != null)
  2260. m_FontFeatureTable.glyphPairAdjustmentRecords.Clear();
  2261. }
  2262. /// <summary>
  2263. /// Internal function to clear all atlas textures.
  2264. /// </summary>
  2265. /// <param name="setAtlasSizeToZero">Set main atlas texture size to zero if true.</param>
  2266. internal void ClearAtlasTextures(bool setAtlasSizeToZero = false)
  2267. {
  2268. m_AtlasTextureIndex = 0;
  2269. // Return if we don't have any atlas textures
  2270. if (m_AtlasTextures == null)
  2271. return;
  2272. Texture2D texture = null;
  2273. // Clear all additional atlas textures
  2274. for (int i = 1; i < m_AtlasTextures.Length; i++)
  2275. {
  2276. texture = m_AtlasTextures[i];
  2277. if (texture == null)
  2278. continue;
  2279. DestroyImmediate(texture, true);
  2280. #if UNITY_EDITOR
  2281. if (UnityEditor.EditorUtility.IsPersistent(this))
  2282. TMP_EditorResourceManager.RegisterResourceForReimport(this);
  2283. #endif
  2284. }
  2285. // Resize atlas texture array down to one texture
  2286. Array.Resize(ref m_AtlasTextures, 1);
  2287. texture = m_AtlasTexture = m_AtlasTextures[0];
  2288. // Clear main atlas texture
  2289. if (texture.isReadable == false)
  2290. {
  2291. #if UNITY_EDITOR && UNITY_2018_4_OR_NEWER && !UNITY_2018_4_0 && !UNITY_2018_4_1 && !UNITY_2018_4_2 && !UNITY_2018_4_3 && !UNITY_2018_4_4
  2292. FontEngineEditorUtilities.SetAtlasTextureIsReadable(texture, true);
  2293. #else
  2294. Debug.LogWarning("Unable to reset font asset [" + this.name + "]'s atlas texture. Please make the texture [" + texture.name + "] readable.", texture);
  2295. return;
  2296. #endif
  2297. }
  2298. if (setAtlasSizeToZero)
  2299. {
  2300. texture.Resize(0, 0, TextureFormat.Alpha8, false);
  2301. }
  2302. else if (texture.width != m_AtlasWidth || texture.height != m_AtlasHeight)
  2303. {
  2304. texture.Resize(m_AtlasWidth, m_AtlasHeight, TextureFormat.Alpha8, false);
  2305. }
  2306. // Clear texture atlas
  2307. FontEngine.ResetAtlasTexture(texture);
  2308. texture.Apply();
  2309. }
  2310. /// <summary>
  2311. /// Internal method used to upgrade font asset to support Dynamic SDF.
  2312. /// </summary>
  2313. internal void UpgradeFontAsset()
  2314. {
  2315. m_Version = "1.1.0";
  2316. Debug.Log("Upgrading font asset [" + this.name + "] to version " + m_Version + ".", this);
  2317. m_FaceInfo.familyName = m_fontInfo.Name;
  2318. m_FaceInfo.styleName = string.Empty;
  2319. m_FaceInfo.pointSize = (int)m_fontInfo.PointSize;
  2320. m_FaceInfo.scale = m_fontInfo.Scale;
  2321. m_FaceInfo.lineHeight = m_fontInfo.LineHeight;
  2322. m_FaceInfo.ascentLine = m_fontInfo.Ascender;
  2323. m_FaceInfo.capLine = m_fontInfo.CapHeight;
  2324. m_FaceInfo.meanLine = m_fontInfo.CenterLine;
  2325. m_FaceInfo.baseline = m_fontInfo.Baseline;
  2326. m_FaceInfo.descentLine = m_fontInfo.Descender;
  2327. m_FaceInfo.superscriptOffset = m_fontInfo.SuperscriptOffset;
  2328. m_FaceInfo.superscriptSize = m_fontInfo.SubSize;
  2329. m_FaceInfo.subscriptOffset = m_fontInfo.SubscriptOffset;
  2330. m_FaceInfo.subscriptSize = m_fontInfo.SubSize;
  2331. m_FaceInfo.underlineOffset = m_fontInfo.Underline;
  2332. m_FaceInfo.underlineThickness = m_fontInfo.UnderlineThickness;
  2333. m_FaceInfo.strikethroughOffset = m_fontInfo.strikethrough;
  2334. m_FaceInfo.strikethroughThickness = m_fontInfo.strikethroughThickness;
  2335. m_FaceInfo.tabWidth = m_fontInfo.TabWidth;
  2336. if (m_AtlasTextures == null || m_AtlasTextures.Length == 0)
  2337. m_AtlasTextures = new Texture2D[1];
  2338. m_AtlasTextures[0] = atlas;
  2339. //atlas = null;
  2340. m_AtlasWidth = (int)m_fontInfo.AtlasWidth;
  2341. m_AtlasHeight = (int)m_fontInfo.AtlasHeight;
  2342. m_AtlasPadding = (int)m_fontInfo.Padding;
  2343. switch(m_CreationSettings.renderMode)
  2344. {
  2345. case 0:
  2346. m_AtlasRenderMode = GlyphRenderMode.SMOOTH_HINTED;
  2347. break;
  2348. case 1:
  2349. m_AtlasRenderMode = GlyphRenderMode.SMOOTH;
  2350. break;
  2351. case 2:
  2352. m_AtlasRenderMode = GlyphRenderMode.RASTER_HINTED;
  2353. break;
  2354. case 3:
  2355. m_AtlasRenderMode = GlyphRenderMode.RASTER;
  2356. break;
  2357. case 6:
  2358. m_AtlasRenderMode = GlyphRenderMode.SDF16;
  2359. break;
  2360. case 7:
  2361. m_AtlasRenderMode = GlyphRenderMode.SDF32;
  2362. break;
  2363. }
  2364. //m_fontInfo = null;
  2365. // Convert font weight table
  2366. if (fontWeights != null && fontWeights.Length > 0)
  2367. {
  2368. m_FontWeightTable[4] = fontWeights[4];
  2369. m_FontWeightTable[7] = fontWeights[7];
  2370. // Clear old fontWeight
  2371. //fontWeights = null;
  2372. }
  2373. // Convert font fallbacks
  2374. if (fallbackFontAssets != null && fallbackFontAssets.Count > 0)
  2375. {
  2376. if (m_FallbackFontAssetTable == null)
  2377. m_FallbackFontAssetTable = new List<TMP_FontAsset>(fallbackFontAssets.Count);
  2378. for (int i = 0; i < fallbackFontAssets.Count; i++)
  2379. m_FallbackFontAssetTable.Add(fallbackFontAssets[i]);
  2380. // Clear old fallbackFontAssets list
  2381. //fallbackFontAssets = null;
  2382. }
  2383. // Check if font asset creation settings contains a reference to the source font file GUID
  2384. if (m_CreationSettings.sourceFontFileGUID != null || m_CreationSettings.sourceFontFileGUID != string.Empty)
  2385. {
  2386. m_SourceFontFileGUID = m_CreationSettings.sourceFontFileGUID;
  2387. }
  2388. else
  2389. {
  2390. Debug.LogWarning("Font asset [" + this.name + "] doesn't have a reference to its source font file. Please assign the appropriate source font file for this asset in the Font Atlas & Material section of font asset inspector.", this);
  2391. }
  2392. // Convert legacy glyph and character tables to new format
  2393. m_GlyphTable.Clear();
  2394. m_CharacterTable.Clear();
  2395. //#if UNITY_EDITOR
  2396. // TODO: This is causing a crash in Unity and related to AssetDatabase.LoadAssetAtPath and Resources.Load()
  2397. // Load font to allow us to get the glyph index.
  2398. //string path = UnityEditor.AssetDatabase.GUIDToAssetPath(m_SourceFontFileGUID);
  2399. //if (path != string.Empty)
  2400. //{
  2401. //m_SourceFontFile_EditorRef = UnityEditor.AssetDatabase.LoadAssetAtPath<Font>(path);
  2402. //FontEngine.LoadFontFace(m_SourceFontFile_EditorRef);
  2403. //}
  2404. //#endif
  2405. bool isSpaceCharacterPresent = false;
  2406. for (int i = 0; i < m_glyphInfoList.Count; i++)
  2407. {
  2408. TMP_Glyph oldGlyph = m_glyphInfoList[i];
  2409. Glyph glyph = new Glyph();
  2410. uint glyphIndex = (uint)i + 1;
  2411. //#if UNITY_EDITOR
  2412. //if (m_SourceFontFile_EditorRef != null)
  2413. // glyphIndex = FontEngine.GetGlyphIndex((uint)oldGlyph.id);
  2414. //#endif
  2415. glyph.index = glyphIndex;
  2416. glyph.glyphRect = new GlyphRect((int)oldGlyph.x, m_AtlasHeight - (int)(oldGlyph.y + oldGlyph.height + 0.5f), (int)(oldGlyph.width + 0.5f), (int)(oldGlyph.height + 0.5f));
  2417. glyph.metrics = new GlyphMetrics(oldGlyph.width, oldGlyph.height, oldGlyph.xOffset, oldGlyph.yOffset, oldGlyph.xAdvance);
  2418. glyph.scale = oldGlyph.scale;
  2419. glyph.atlasIndex = 0;
  2420. m_GlyphTable.Add(glyph);
  2421. TMP_Character character = new TMP_Character((uint)oldGlyph.id, this, glyph);
  2422. if (oldGlyph.id == 32)
  2423. isSpaceCharacterPresent = true;
  2424. m_CharacterTable.Add(character);
  2425. }
  2426. // Special handling for the synthesized space character
  2427. if (!isSpaceCharacterPresent)
  2428. {
  2429. Debug.Log("Synthesizing Space for [" + this.name + "]");
  2430. Glyph glyph = new Glyph(0, new GlyphMetrics(0, 0, 0, 0, m_FaceInfo.ascentLine / 5), GlyphRect.zero, 1.0f, 0);
  2431. m_GlyphTable.Add(glyph);
  2432. m_CharacterTable.Add(new TMP_Character(32, this, glyph));
  2433. }
  2434. // Clear legacy glyph info list.
  2435. //m_glyphInfoList.Clear();
  2436. ReadFontAssetDefinition();
  2437. // Convert atlas textures data to new format
  2438. // TODO
  2439. #if UNITY_EDITOR
  2440. if (UnityEditor.EditorUtility.IsPersistent(this))
  2441. {
  2442. TMP_EditorResourceManager.RegisterResourceForUpdate(this);
  2443. }
  2444. #endif
  2445. }
  2446. /// <summary>
  2447. ///
  2448. /// </summary>
  2449. void UpgradeGlyphAdjustmentTableToFontFeatureTable()
  2450. {
  2451. Debug.Log("Upgrading font asset [" + this.name + "] Glyph Adjustment Table.", this);
  2452. if (m_FontFeatureTable == null)
  2453. m_FontFeatureTable = new TMP_FontFeatureTable();
  2454. int pairCount = m_KerningTable.kerningPairs.Count;
  2455. m_FontFeatureTable.m_GlyphPairAdjustmentRecords = new List<TMP_GlyphPairAdjustmentRecord>(pairCount);
  2456. for (int i = 0; i < pairCount; i++)
  2457. {
  2458. KerningPair pair = m_KerningTable.kerningPairs[i];
  2459. uint firstGlyphIndex = 0;
  2460. TMP_Character firstCharacter;
  2461. if (m_CharacterLookupDictionary.TryGetValue(pair.firstGlyph, out firstCharacter))
  2462. firstGlyphIndex = firstCharacter.glyphIndex;
  2463. uint secondGlyphIndex = 0;
  2464. TMP_Character secondCharacter;
  2465. if (m_CharacterLookupDictionary.TryGetValue(pair.secondGlyph, out secondCharacter))
  2466. secondGlyphIndex = secondCharacter.glyphIndex;
  2467. TMP_GlyphAdjustmentRecord firstAdjustmentRecord = new TMP_GlyphAdjustmentRecord(firstGlyphIndex, new TMP_GlyphValueRecord(pair.firstGlyphAdjustments.xPlacement, pair.firstGlyphAdjustments.yPlacement, pair.firstGlyphAdjustments.xAdvance, pair.firstGlyphAdjustments.yAdvance));
  2468. TMP_GlyphAdjustmentRecord secondAdjustmentRecord = new TMP_GlyphAdjustmentRecord(secondGlyphIndex, new TMP_GlyphValueRecord(pair.secondGlyphAdjustments.xPlacement, pair.secondGlyphAdjustments.yPlacement, pair.secondGlyphAdjustments.xAdvance, pair.secondGlyphAdjustments.yAdvance));
  2469. TMP_GlyphPairAdjustmentRecord record = new TMP_GlyphPairAdjustmentRecord(firstAdjustmentRecord, secondAdjustmentRecord);
  2470. m_FontFeatureTable.m_GlyphPairAdjustmentRecords.Add(record);
  2471. }
  2472. // TODO: Should clear legacy kerning table.
  2473. m_KerningTable.kerningPairs = null;
  2474. m_KerningTable = null;
  2475. #if UNITY_EDITOR
  2476. if (UnityEditor.EditorUtility.IsPersistent(this))
  2477. {
  2478. TMP_EditorResourceManager.RegisterResourceForUpdate(this);
  2479. }
  2480. #endif
  2481. }
  2482. }
  2483. }