TMPro_FontAssetCreatorWindow.cs 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736
  1. using System;
  2. using UnityEngine;
  3. using UnityEditor;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.Threading;
  7. using System.IO;
  8. using System.Text.RegularExpressions;
  9. using UnityEngine.TextCore;
  10. using UnityEngine.TextCore.LowLevel;
  11. using Object = UnityEngine.Object;
  12. namespace TMPro.EditorUtilities
  13. {
  14. public class TMPro_FontAssetCreatorWindow : EditorWindow
  15. {
  16. [MenuItem("Window/TextMeshPro/Font Asset Creator", false, 2025)]
  17. public static void ShowFontAtlasCreatorWindow()
  18. {
  19. var window = GetWindow<TMPro_FontAssetCreatorWindow>();
  20. window.titleContent = new GUIContent("Font Asset Creator");
  21. window.Focus();
  22. // Make sure TMP Essential Resources have been imported.
  23. window.CheckEssentialResources();
  24. }
  25. public static void ShowFontAtlasCreatorWindow(Font sourceFontFile)
  26. {
  27. var window = GetWindow<TMPro_FontAssetCreatorWindow>();
  28. window.titleContent = new GUIContent("Font Asset Creator");
  29. window.Focus();
  30. window.ClearGeneratedData();
  31. window.m_LegacyFontAsset = null;
  32. window.m_SelectedFontAsset = null;
  33. // Override selected font asset
  34. window.m_SourceFontFile = sourceFontFile;
  35. // Make sure TMP Essential Resources have been imported.
  36. window.CheckEssentialResources();
  37. }
  38. public static void ShowFontAtlasCreatorWindow(TMP_FontAsset fontAsset)
  39. {
  40. var window = GetWindow<TMPro_FontAssetCreatorWindow>();
  41. window.titleContent = new GUIContent("Font Asset Creator");
  42. window.Focus();
  43. // Clear any previously generated data
  44. window.ClearGeneratedData();
  45. window.m_LegacyFontAsset = null;
  46. // Load font asset creation settings if we have valid settings
  47. if (string.IsNullOrEmpty(fontAsset.creationSettings.sourceFontFileGUID) == false)
  48. {
  49. window.LoadFontCreationSettings(fontAsset.creationSettings);
  50. // Override settings to inject character list from font asset
  51. window.m_CharacterSetSelectionMode = 6;
  52. window.m_CharacterSequence = TMP_EditorUtility.GetUnicodeCharacterSequence(TMP_FontAsset.GetCharactersArray(fontAsset));
  53. window.m_ReferencedFontAsset = fontAsset;
  54. window.m_SavedFontAtlas = fontAsset.atlasTexture;
  55. }
  56. else
  57. {
  58. window.m_WarningMessage = "Font Asset [" + fontAsset.name + "] does not contain any previous \"Font Asset Creation Settings\". This usually means [" + fontAsset.name + "] was created before this new functionality was added.";
  59. window.m_SourceFontFile = null;
  60. window.m_LegacyFontAsset = fontAsset;
  61. }
  62. // Even if we don't have any saved generation settings, we still want to pre-select the source font file.
  63. window.m_SelectedFontAsset = fontAsset;
  64. // Make sure TMP Essential Resources have been imported.
  65. window.CheckEssentialResources();
  66. }
  67. [System.Serializable]
  68. class FontAssetCreationSettingsContainer
  69. {
  70. public List<FontAssetCreationSettings> fontAssetCreationSettings;
  71. }
  72. FontAssetCreationSettingsContainer m_FontAssetCreationSettingsContainer;
  73. //static readonly string[] m_FontCreationPresets = new string[] { "Recent 1", "Recent 2", "Recent 3", "Recent 4" };
  74. int m_FontAssetCreationSettingsCurrentIndex = 0;
  75. const string k_FontAssetCreationSettingsContainerKey = "TextMeshPro.FontAssetCreator.RecentFontAssetCreationSettings.Container";
  76. const string k_FontAssetCreationSettingsCurrentIndexKey = "TextMeshPro.FontAssetCreator.RecentFontAssetCreationSettings.CurrentIndex";
  77. const float k_TwoColumnControlsWidth = 335f;
  78. // Diagnostics
  79. System.Diagnostics.Stopwatch m_StopWatch;
  80. double m_GlyphPackingGenerationTime;
  81. double m_GlyphRenderingGenerationTime;
  82. string[] m_FontSizingOptions = { "Auto Sizing", "Custom Size" };
  83. int m_PointSizeSamplingMode;
  84. string[] m_FontResolutionLabels = { "8", "16","32", "64", "128", "256", "512", "1024", "2048", "4096", "8192" };
  85. int[] m_FontAtlasResolutions = { 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192 };
  86. string[] m_FontCharacterSets = { "ASCII", "Extended ASCII", "ASCII Lowercase", "ASCII Uppercase", "Numbers + Symbols", "Custom Range", "Unicode Range (Hex)", "Custom Characters", "Characters from File" };
  87. enum FontPackingModes { Fast = 0, Optimum = 4 };
  88. FontPackingModes m_PackingMode = FontPackingModes.Fast;
  89. int m_CharacterSetSelectionMode;
  90. string m_CharacterSequence = "";
  91. string m_OutputFeedback = "";
  92. string m_WarningMessage;
  93. int m_CharacterCount;
  94. Vector2 m_ScrollPosition;
  95. Vector2 m_OutputScrollPosition;
  96. bool m_IsRepaintNeeded;
  97. float m_AtlasGenerationProgress;
  98. string m_AtlasGenerationProgressLabel = string.Empty;
  99. float m_RenderingProgress;
  100. bool m_IsRenderingDone;
  101. bool m_IsProcessing;
  102. bool m_IsGenerationDisabled;
  103. bool m_IsGenerationCancelled;
  104. bool m_IsFontAtlasInvalid;
  105. Object m_SourceFontFile;
  106. TMP_FontAsset m_SelectedFontAsset;
  107. TMP_FontAsset m_LegacyFontAsset;
  108. TMP_FontAsset m_ReferencedFontAsset;
  109. TextAsset m_CharactersFromFile;
  110. int m_PointSize;
  111. int m_Padding = 5;
  112. //FaceStyles m_FontStyle = FaceStyles.Normal;
  113. //float m_FontStyleValue = 2;
  114. GlyphRenderMode m_GlyphRenderMode = GlyphRenderMode.SDFAA;
  115. int m_AtlasWidth = 512;
  116. int m_AtlasHeight = 512;
  117. byte[] m_AtlasTextureBuffer;
  118. Texture2D m_FontAtlasTexture;
  119. Texture2D m_SavedFontAtlas;
  120. //
  121. List<Glyph> m_FontGlyphTable = new List<Glyph>();
  122. List<TMP_Character> m_FontCharacterTable = new List<TMP_Character>();
  123. Dictionary<uint, uint> m_CharacterLookupMap = new Dictionary<uint, uint>();
  124. Dictionary<uint, List<uint>> m_GlyphLookupMap = new Dictionary<uint, List<uint>>();
  125. List<Glyph> m_GlyphsToPack = new List<Glyph>();
  126. List<Glyph> m_GlyphsPacked = new List<Glyph>();
  127. List<GlyphRect> m_FreeGlyphRects = new List<GlyphRect>();
  128. List<GlyphRect> m_UsedGlyphRects = new List<GlyphRect>();
  129. List<Glyph> m_GlyphsToRender = new List<Glyph>();
  130. List<uint> m_AvailableGlyphsToAdd = new List<uint>();
  131. List<uint> m_MissingCharacters = new List<uint>();
  132. List<uint> m_ExcludedCharacters = new List<uint>();
  133. private FaceInfo m_FaceInfo;
  134. bool m_IncludeFontFeatures;
  135. public void OnEnable()
  136. {
  137. // Used for Diagnostics
  138. m_StopWatch = new System.Diagnostics.Stopwatch();
  139. // Set Editor window size.
  140. minSize = new Vector2(315, minSize.y);
  141. // Initialize & Get shader property IDs.
  142. ShaderUtilities.GetShaderPropertyIDs();
  143. // Load last selected preset if we are not already in the process of regenerating an existing font asset (via the Context menu)
  144. if (EditorPrefs.HasKey(k_FontAssetCreationSettingsContainerKey))
  145. {
  146. if (m_FontAssetCreationSettingsContainer == null)
  147. m_FontAssetCreationSettingsContainer = JsonUtility.FromJson<FontAssetCreationSettingsContainer>(EditorPrefs.GetString(k_FontAssetCreationSettingsContainerKey));
  148. if (m_FontAssetCreationSettingsContainer.fontAssetCreationSettings != null && m_FontAssetCreationSettingsContainer.fontAssetCreationSettings.Count > 0)
  149. {
  150. // Load Font Asset Creation Settings preset.
  151. if (EditorPrefs.HasKey(k_FontAssetCreationSettingsCurrentIndexKey))
  152. m_FontAssetCreationSettingsCurrentIndex = EditorPrefs.GetInt(k_FontAssetCreationSettingsCurrentIndexKey);
  153. LoadFontCreationSettings(m_FontAssetCreationSettingsContainer.fontAssetCreationSettings[m_FontAssetCreationSettingsCurrentIndex]);
  154. }
  155. }
  156. ClearGeneratedData();
  157. }
  158. public void OnDisable()
  159. {
  160. //Debug.Log("TextMeshPro Editor Window has been disabled.");
  161. // Destroy Engine only if it has been initialized already
  162. FontEngine.DestroyFontEngine();
  163. ClearGeneratedData();
  164. // Remove Glyph Report if one was created.
  165. if (File.Exists("Assets/TextMesh Pro/Glyph Report.txt"))
  166. {
  167. File.Delete("Assets/TextMesh Pro/Glyph Report.txt");
  168. File.Delete("Assets/TextMesh Pro/Glyph Report.txt.meta");
  169. AssetDatabase.Refresh();
  170. }
  171. // Save Font Asset Creation Settings Index
  172. SaveCreationSettingsToEditorPrefs(SaveFontCreationSettings());
  173. EditorPrefs.SetInt(k_FontAssetCreationSettingsCurrentIndexKey, m_FontAssetCreationSettingsCurrentIndex);
  174. // Unregister to event
  175. TMPro_EventManager.RESOURCE_LOAD_EVENT.Remove(ON_RESOURCES_LOADED);
  176. Resources.UnloadUnusedAssets();
  177. }
  178. // Event received when TMP resources have been loaded.
  179. void ON_RESOURCES_LOADED()
  180. {
  181. TMPro_EventManager.RESOURCE_LOAD_EVENT.Remove(ON_RESOURCES_LOADED);
  182. m_IsGenerationDisabled = false;
  183. }
  184. // Make sure TMP Essential Resources have been imported.
  185. void CheckEssentialResources()
  186. {
  187. if (TMP_Settings.instance == null)
  188. {
  189. if (m_IsGenerationDisabled == false)
  190. TMPro_EventManager.RESOURCE_LOAD_EVENT.Add(ON_RESOURCES_LOADED);
  191. m_IsGenerationDisabled = true;
  192. }
  193. }
  194. public void OnGUI()
  195. {
  196. GUILayout.BeginHorizontal();
  197. DrawControls();
  198. if (position.width > position.height && position.width > k_TwoColumnControlsWidth)
  199. {
  200. DrawPreview();
  201. }
  202. GUILayout.EndHorizontal();
  203. }
  204. public void Update()
  205. {
  206. if (m_IsRepaintNeeded)
  207. {
  208. //Debug.Log("Repainting...");
  209. m_IsRepaintNeeded = false;
  210. Repaint();
  211. }
  212. // Update Progress bar is we are Rendering a Font.
  213. if (m_IsProcessing)
  214. {
  215. m_AtlasGenerationProgress = FontEngine.generationProgress;
  216. m_IsRepaintNeeded = true;
  217. }
  218. // Update Feedback Window & Create Font Texture once Rendering is done.
  219. if (m_IsRenderingDone)
  220. {
  221. m_IsProcessing = false;
  222. m_IsRenderingDone = false;
  223. if (m_IsGenerationCancelled == false)
  224. {
  225. m_AtlasGenerationProgressLabel = "Generation completed in: " + (m_GlyphPackingGenerationTime + m_GlyphRenderingGenerationTime).ToString("0.00 ms.");
  226. UpdateRenderFeedbackWindow();
  227. CreateFontAtlasTexture();
  228. // If dynamic make readable ...
  229. m_FontAtlasTexture.Apply(false, false);
  230. }
  231. Repaint();
  232. }
  233. }
  234. /// <summary>
  235. /// Method which returns the character corresponding to a decimal value.
  236. /// </summary>
  237. /// <param name="sequence"></param>
  238. /// <returns></returns>
  239. static uint[] ParseNumberSequence(string sequence)
  240. {
  241. List<uint> unicodeList = new List<uint>();
  242. string[] sequences = sequence.Split(',');
  243. foreach (string seq in sequences)
  244. {
  245. string[] s1 = seq.Split('-');
  246. if (s1.Length == 1)
  247. try
  248. {
  249. unicodeList.Add(uint.Parse(s1[0]));
  250. }
  251. catch
  252. {
  253. Debug.Log("No characters selected or invalid format.");
  254. }
  255. else
  256. {
  257. for (uint j = uint.Parse(s1[0]); j < uint.Parse(s1[1]) + 1; j++)
  258. {
  259. unicodeList.Add(j);
  260. }
  261. }
  262. }
  263. return unicodeList.ToArray();
  264. }
  265. /// <summary>
  266. /// Method which returns the character (decimal value) from a hex sequence.
  267. /// </summary>
  268. /// <param name="sequence"></param>
  269. /// <returns></returns>
  270. static uint[] ParseHexNumberSequence(string sequence)
  271. {
  272. List<uint> unicodeList = new List<uint>();
  273. string[] sequences = sequence.Split(',');
  274. foreach (string seq in sequences)
  275. {
  276. string[] s1 = seq.Split('-');
  277. if (s1.Length == 1)
  278. try
  279. {
  280. unicodeList.Add(uint.Parse(s1[0], NumberStyles.AllowHexSpecifier));
  281. }
  282. catch
  283. {
  284. Debug.Log("No characters selected or invalid format.");
  285. }
  286. else
  287. {
  288. for (uint j = uint.Parse(s1[0], NumberStyles.AllowHexSpecifier); j < uint.Parse(s1[1], NumberStyles.AllowHexSpecifier) + 1; j++)
  289. {
  290. unicodeList.Add(j);
  291. }
  292. }
  293. }
  294. return unicodeList.ToArray();
  295. }
  296. void DrawControls()
  297. {
  298. GUILayout.Space(5f);
  299. if (position.width > position.height && position.width > k_TwoColumnControlsWidth)
  300. {
  301. m_ScrollPosition = EditorGUILayout.BeginScrollView(m_ScrollPosition, GUILayout.Width(315));
  302. }
  303. else
  304. {
  305. m_ScrollPosition = EditorGUILayout.BeginScrollView(m_ScrollPosition);
  306. }
  307. GUILayout.Space(5f);
  308. GUILayout.Label(m_SelectedFontAsset != null ? string.Format("Font Settings [{0}]", m_SelectedFontAsset.name) : "Font Settings", EditorStyles.boldLabel);
  309. EditorGUILayout.BeginVertical(EditorStyles.helpBox);
  310. EditorGUIUtility.labelWidth = 125f;
  311. EditorGUIUtility.fieldWidth = 5f;
  312. // Disable Options if already generating a font atlas texture.
  313. EditorGUI.BeginDisabledGroup(m_IsProcessing);
  314. {
  315. // FONT TTF SELECTION
  316. EditorGUI.BeginChangeCheck();
  317. m_SourceFontFile = EditorGUILayout.ObjectField("Source Font File", m_SourceFontFile, typeof(Font), false) as Font;
  318. if (EditorGUI.EndChangeCheck())
  319. {
  320. m_SelectedFontAsset = null;
  321. m_IsFontAtlasInvalid = true;
  322. }
  323. // FONT SIZING
  324. EditorGUI.BeginChangeCheck();
  325. if (m_PointSizeSamplingMode == 0)
  326. {
  327. m_PointSizeSamplingMode = EditorGUILayout.Popup("Sampling Point Size", m_PointSizeSamplingMode, m_FontSizingOptions);
  328. }
  329. else
  330. {
  331. GUILayout.BeginHorizontal();
  332. m_PointSizeSamplingMode = EditorGUILayout.Popup("Sampling Point Size", m_PointSizeSamplingMode, m_FontSizingOptions, GUILayout.Width(225));
  333. m_PointSize = EditorGUILayout.IntField(m_PointSize);
  334. GUILayout.EndHorizontal();
  335. }
  336. if (EditorGUI.EndChangeCheck())
  337. {
  338. m_IsFontAtlasInvalid = true;
  339. }
  340. // FONT PADDING
  341. EditorGUI.BeginChangeCheck();
  342. m_Padding = EditorGUILayout.IntField("Padding", m_Padding);
  343. m_Padding = (int)Mathf.Clamp(m_Padding, 0f, 64f);
  344. if (EditorGUI.EndChangeCheck())
  345. {
  346. m_IsFontAtlasInvalid = true;
  347. }
  348. // FONT PACKING METHOD SELECTION
  349. EditorGUI.BeginChangeCheck();
  350. m_PackingMode = (FontPackingModes)EditorGUILayout.EnumPopup("Packing Method", m_PackingMode);
  351. if (EditorGUI.EndChangeCheck())
  352. {
  353. m_IsFontAtlasInvalid = true;
  354. }
  355. // FONT ATLAS RESOLUTION SELECTION
  356. GUILayout.BeginHorizontal();
  357. GUI.changed = false;
  358. EditorGUI.BeginChangeCheck();
  359. EditorGUILayout.PrefixLabel("Atlas Resolution");
  360. m_AtlasWidth = EditorGUILayout.IntPopup(m_AtlasWidth, m_FontResolutionLabels, m_FontAtlasResolutions);
  361. m_AtlasHeight = EditorGUILayout.IntPopup(m_AtlasHeight, m_FontResolutionLabels, m_FontAtlasResolutions);
  362. if (EditorGUI.EndChangeCheck())
  363. {
  364. m_IsFontAtlasInvalid = true;
  365. }
  366. GUILayout.EndHorizontal();
  367. // FONT CHARACTER SET SELECTION
  368. EditorGUI.BeginChangeCheck();
  369. bool hasSelectionChanged = false;
  370. m_CharacterSetSelectionMode = EditorGUILayout.Popup("Character Set", m_CharacterSetSelectionMode, m_FontCharacterSets);
  371. if (EditorGUI.EndChangeCheck())
  372. {
  373. m_CharacterSequence = "";
  374. hasSelectionChanged = true;
  375. m_IsFontAtlasInvalid = true;
  376. }
  377. switch (m_CharacterSetSelectionMode)
  378. {
  379. case 0: // ASCII
  380. //characterSequence = "32 - 126, 130, 132 - 135, 139, 145 - 151, 153, 155, 161, 166 - 167, 169 - 174, 176, 181 - 183, 186 - 187, 191, 8210 - 8226, 8230, 8240, 8242 - 8244, 8249 - 8250, 8252 - 8254, 8260, 8286";
  381. m_CharacterSequence = "32 - 126, 160, 8203, 8230, 9633";
  382. break;
  383. case 1: // EXTENDED ASCII
  384. m_CharacterSequence = "32 - 126, 160 - 255, 8192 - 8303, 8364, 8482, 9633";
  385. // Could add 9632 for missing glyph
  386. break;
  387. case 2: // Lowercase
  388. m_CharacterSequence = "32 - 64, 91 - 126, 160";
  389. break;
  390. case 3: // Uppercase
  391. m_CharacterSequence = "32 - 96, 123 - 126, 160";
  392. break;
  393. case 4: // Numbers & Symbols
  394. m_CharacterSequence = "32 - 64, 91 - 96, 123 - 126, 160";
  395. break;
  396. case 5: // Custom Range
  397. EditorGUILayout.BeginVertical(EditorStyles.helpBox);
  398. GUILayout.Label("Enter a sequence of decimal values to define the characters to be included in the font asset or retrieve one from another font asset.", TMP_UIStyleManager.label);
  399. GUILayout.Space(10f);
  400. EditorGUI.BeginChangeCheck();
  401. m_ReferencedFontAsset = EditorGUILayout.ObjectField("Select Font Asset", m_ReferencedFontAsset, typeof(TMP_FontAsset), false) as TMP_FontAsset;
  402. if (EditorGUI.EndChangeCheck() || hasSelectionChanged)
  403. {
  404. if (m_ReferencedFontAsset != null)
  405. m_CharacterSequence = TMP_EditorUtility.GetDecimalCharacterSequence(TMP_FontAsset.GetCharactersArray(m_ReferencedFontAsset));
  406. m_IsFontAtlasInvalid = true;
  407. }
  408. // Filter out unwanted characters.
  409. char chr = Event.current.character;
  410. if ((chr < '0' || chr > '9') && (chr < ',' || chr > '-'))
  411. {
  412. Event.current.character = '\0';
  413. }
  414. GUILayout.Label("Character Sequence (Decimal)", EditorStyles.boldLabel);
  415. EditorGUI.BeginChangeCheck();
  416. m_CharacterSequence = EditorGUILayout.TextArea(m_CharacterSequence, TMP_UIStyleManager.textAreaBoxWindow, GUILayout.Height(120), GUILayout.ExpandWidth(true));
  417. if (EditorGUI.EndChangeCheck())
  418. {
  419. m_IsFontAtlasInvalid = true;
  420. }
  421. EditorGUILayout.EndVertical();
  422. break;
  423. case 6: // Unicode HEX Range
  424. EditorGUILayout.BeginVertical(EditorStyles.helpBox);
  425. GUILayout.Label("Enter a sequence of Unicode (hex) values to define the characters to be included in the font asset or retrieve one from another font asset.", TMP_UIStyleManager.label);
  426. GUILayout.Space(10f);
  427. EditorGUI.BeginChangeCheck();
  428. m_ReferencedFontAsset = EditorGUILayout.ObjectField("Select Font Asset", m_ReferencedFontAsset, typeof(TMP_FontAsset), false) as TMP_FontAsset;
  429. if (EditorGUI.EndChangeCheck() || hasSelectionChanged)
  430. {
  431. if (m_ReferencedFontAsset != null)
  432. m_CharacterSequence = TMP_EditorUtility.GetUnicodeCharacterSequence(TMP_FontAsset.GetCharactersArray(m_ReferencedFontAsset));
  433. m_IsFontAtlasInvalid = true;
  434. }
  435. // Filter out unwanted characters.
  436. chr = Event.current.character;
  437. if ((chr < '0' || chr > '9') && (chr < 'a' || chr > 'f') && (chr < 'A' || chr > 'F') && (chr < ',' || chr > '-'))
  438. {
  439. Event.current.character = '\0';
  440. }
  441. GUILayout.Label("Character Sequence (Hex)", EditorStyles.boldLabel);
  442. EditorGUI.BeginChangeCheck();
  443. m_CharacterSequence = EditorGUILayout.TextArea(m_CharacterSequence, TMP_UIStyleManager.textAreaBoxWindow, GUILayout.Height(120), GUILayout.ExpandWidth(true));
  444. if (EditorGUI.EndChangeCheck())
  445. {
  446. m_IsFontAtlasInvalid = true;
  447. }
  448. EditorGUILayout.EndVertical();
  449. break;
  450. case 7: // Characters from Font Asset
  451. EditorGUILayout.BeginVertical(EditorStyles.helpBox);
  452. GUILayout.Label("Type the characters to be included in the font asset or retrieve them from another font asset.", TMP_UIStyleManager.label);
  453. GUILayout.Space(10f);
  454. EditorGUI.BeginChangeCheck();
  455. m_ReferencedFontAsset = EditorGUILayout.ObjectField("Select Font Asset", m_ReferencedFontAsset, typeof(TMP_FontAsset), false) as TMP_FontAsset;
  456. if (EditorGUI.EndChangeCheck() || hasSelectionChanged)
  457. {
  458. if (m_ReferencedFontAsset != null)
  459. m_CharacterSequence = TMP_FontAsset.GetCharacters(m_ReferencedFontAsset);
  460. m_IsFontAtlasInvalid = true;
  461. }
  462. EditorGUI.indentLevel = 0;
  463. GUILayout.Label("Custom Character List", EditorStyles.boldLabel);
  464. EditorGUI.BeginChangeCheck();
  465. m_CharacterSequence = EditorGUILayout.TextArea(m_CharacterSequence, TMP_UIStyleManager.textAreaBoxWindow, GUILayout.Height(120), GUILayout.ExpandWidth(true));
  466. if (EditorGUI.EndChangeCheck())
  467. {
  468. m_IsFontAtlasInvalid = true;
  469. }
  470. EditorGUILayout.EndVertical();
  471. break;
  472. case 8: // Character List from File
  473. EditorGUI.BeginChangeCheck();
  474. m_CharactersFromFile = EditorGUILayout.ObjectField("Character File", m_CharactersFromFile, typeof(TextAsset), false) as TextAsset;
  475. if (EditorGUI.EndChangeCheck())
  476. {
  477. m_IsFontAtlasInvalid = true;
  478. }
  479. if (m_CharactersFromFile != null)
  480. {
  481. Regex rx = new Regex(@"(?<!\\)(?:\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8})");
  482. m_CharacterSequence = rx.Replace(m_CharactersFromFile.text,
  483. match =>
  484. {
  485. if (match.Value.StartsWith("\\U"))
  486. return char.ConvertFromUtf32(int.Parse(match.Value.Replace("\\U", ""), NumberStyles.HexNumber));
  487. return char.ConvertFromUtf32(int.Parse(match.Value.Replace("\\u", ""), NumberStyles.HexNumber));
  488. });
  489. }
  490. break;
  491. }
  492. // FONT STYLE SELECTION
  493. //GUILayout.BeginHorizontal();
  494. //EditorGUI.BeginChangeCheck();
  495. ////m_FontStyle = (FaceStyles)EditorGUILayout.EnumPopup("Font Style", m_FontStyle, GUILayout.Width(225));
  496. ////m_FontStyleValue = EditorGUILayout.IntField((int)m_FontStyleValue);
  497. //if (EditorGUI.EndChangeCheck())
  498. //{
  499. // m_IsFontAtlasInvalid = true;
  500. //}
  501. //GUILayout.EndHorizontal();
  502. // Render Mode Selection
  503. CheckForLegacyGlyphRenderMode();
  504. EditorGUI.BeginChangeCheck();
  505. m_GlyphRenderMode = (GlyphRenderMode)EditorGUILayout.EnumPopup("Render Mode", m_GlyphRenderMode);
  506. if (EditorGUI.EndChangeCheck())
  507. {
  508. m_IsFontAtlasInvalid = true;
  509. }
  510. m_IncludeFontFeatures = EditorGUILayout.Toggle("Get Kerning Pairs", m_IncludeFontFeatures);
  511. EditorGUILayout.Space();
  512. }
  513. EditorGUI.EndDisabledGroup();
  514. if (!string.IsNullOrEmpty(m_WarningMessage))
  515. {
  516. EditorGUILayout.HelpBox(m_WarningMessage, MessageType.Warning);
  517. }
  518. GUI.enabled = m_SourceFontFile != null && !m_IsProcessing && !m_IsGenerationDisabled; // Enable Preview if we are not already rendering a font.
  519. if (GUILayout.Button("Generate Font Atlas") && GUI.enabled)
  520. {
  521. if (!m_IsProcessing && m_SourceFontFile != null)
  522. {
  523. DestroyImmediate(m_FontAtlasTexture);
  524. m_FontAtlasTexture = null;
  525. m_SavedFontAtlas = null;
  526. // Initialize font engine
  527. FontEngineError errorCode = FontEngine.InitializeFontEngine();
  528. if (errorCode != FontEngineError.Success)
  529. {
  530. Debug.Log("Font Asset Creator - Error [" + errorCode + "] has occurred while Initializing the FreeType Library.");
  531. }
  532. // Get file path of the source font file.
  533. string fontPath = AssetDatabase.GetAssetPath(m_SourceFontFile);
  534. if (errorCode == FontEngineError.Success)
  535. {
  536. errorCode = FontEngine.LoadFontFace(fontPath);
  537. if (errorCode != FontEngineError.Success)
  538. {
  539. Debug.Log("Font Asset Creator - Error Code [" + errorCode + "] has occurred trying to load the [" + m_SourceFontFile.name + "] font file. This typically results from the use of an incompatible or corrupted font file.");
  540. }
  541. }
  542. // Define an array containing the characters we will render.
  543. if (errorCode == FontEngineError.Success)
  544. {
  545. uint[] characterSet = null;
  546. // Get list of characters that need to be packed and rendered to the atlas texture.
  547. if (m_CharacterSetSelectionMode == 7 || m_CharacterSetSelectionMode == 8)
  548. {
  549. List<uint> char_List = new List<uint>();
  550. for (int i = 0; i < m_CharacterSequence.Length; i++)
  551. {
  552. uint unicode = m_CharacterSequence[i];
  553. // Handle surrogate pairs
  554. if (i < m_CharacterSequence.Length - 1 && char.IsHighSurrogate((char)unicode) && char.IsLowSurrogate(m_CharacterSequence[i + 1]))
  555. {
  556. unicode = (uint)char.ConvertToUtf32(m_CharacterSequence[i], m_CharacterSequence[i + 1]);
  557. i += 1;
  558. }
  559. // Check to make sure we don't include duplicates
  560. if (char_List.FindIndex(item => item == unicode) == -1)
  561. char_List.Add(unicode);
  562. }
  563. characterSet = char_List.ToArray();
  564. }
  565. else if (m_CharacterSetSelectionMode == 6)
  566. {
  567. characterSet = ParseHexNumberSequence(m_CharacterSequence);
  568. }
  569. else
  570. {
  571. characterSet = ParseNumberSequence(m_CharacterSequence);
  572. }
  573. m_CharacterCount = characterSet.Length;
  574. m_AtlasGenerationProgress = 0;
  575. m_IsProcessing = true;
  576. m_IsGenerationCancelled = false;
  577. GlyphLoadFlags glyphLoadFlags = ((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_HINTED) == GlyphRasterModes.RASTER_MODE_HINTED ? GlyphLoadFlags.LOAD_RENDER : GlyphLoadFlags.LOAD_RENDER | GlyphLoadFlags.LOAD_NO_HINTING;
  578. //
  579. AutoResetEvent autoEvent = new AutoResetEvent(false);
  580. // Worker thread to pack glyphs in the given texture space.
  581. ThreadPool.QueueUserWorkItem(PackGlyphs =>
  582. {
  583. // Start Stop Watch
  584. m_StopWatch = System.Diagnostics.Stopwatch.StartNew();
  585. // Clear the various lists used in the generation process.
  586. m_AvailableGlyphsToAdd.Clear();
  587. m_MissingCharacters.Clear();
  588. m_ExcludedCharacters.Clear();
  589. m_CharacterLookupMap.Clear();
  590. m_GlyphLookupMap.Clear();
  591. m_GlyphsToPack.Clear();
  592. m_GlyphsPacked.Clear();
  593. // Check if requested characters are available in the source font file.
  594. for (int i = 0; i < characterSet.Length; i++)
  595. {
  596. uint unicode = characterSet[i];
  597. if (FontEngine.TryGetGlyphIndex(unicode, out uint glyphIndex))
  598. {
  599. // Skip over potential duplicate characters.
  600. if (m_CharacterLookupMap.ContainsKey(unicode))
  601. continue;
  602. // Add character to character lookup map.
  603. m_CharacterLookupMap.Add(unicode, glyphIndex);
  604. // Skip over potential duplicate glyph references.
  605. if (m_GlyphLookupMap.ContainsKey(glyphIndex))
  606. {
  607. // Add additional glyph reference for this character.
  608. m_GlyphLookupMap[glyphIndex].Add(unicode);
  609. continue;
  610. }
  611. // Add glyph reference to glyph lookup map.
  612. m_GlyphLookupMap.Add(glyphIndex, new List<uint>() { unicode });
  613. // Add glyph index to list of glyphs to add to texture.
  614. m_AvailableGlyphsToAdd.Add(glyphIndex);
  615. }
  616. else
  617. {
  618. // Add Unicode to list of missing characters.
  619. m_MissingCharacters.Add(unicode);
  620. }
  621. }
  622. // Pack available glyphs in the provided texture space.
  623. if (m_AvailableGlyphsToAdd.Count > 0)
  624. {
  625. int packingModifier = ((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP ? 0 : 1;
  626. if (m_PointSizeSamplingMode == 0) // Auto-Sizing Point Size Mode
  627. {
  628. // Estimate min / max range for auto sizing of point size.
  629. int minPointSize = 0;
  630. int maxPointSize = (int)Mathf.Sqrt((m_AtlasWidth * m_AtlasHeight) / m_AvailableGlyphsToAdd.Count) * 3;
  631. m_PointSize = (maxPointSize + minPointSize) / 2;
  632. bool optimumPointSizeFound = false;
  633. for (int iteration = 0; iteration < 15 && optimumPointSizeFound == false; iteration++)
  634. {
  635. m_AtlasGenerationProgressLabel = "Packing glyphs - Pass (" + iteration + ")";
  636. FontEngine.SetFaceSize(m_PointSize);
  637. m_GlyphsToPack.Clear();
  638. m_GlyphsPacked.Clear();
  639. m_FreeGlyphRects.Clear();
  640. m_FreeGlyphRects.Add(new GlyphRect(0, 0, m_AtlasWidth - packingModifier, m_AtlasHeight - packingModifier));
  641. m_UsedGlyphRects.Clear();
  642. for (int i = 0; i < m_AvailableGlyphsToAdd.Count; i++)
  643. {
  644. uint glyphIndex = m_AvailableGlyphsToAdd[i];
  645. if (FontEngine.TryGetGlyphWithIndexValue(glyphIndex, glyphLoadFlags, out Glyph glyph))
  646. {
  647. if (glyph.glyphRect.width > 0 && glyph.glyphRect.height > 0)
  648. {
  649. m_GlyphsToPack.Add(glyph);
  650. }
  651. else
  652. {
  653. m_GlyphsPacked.Add(glyph);
  654. }
  655. }
  656. }
  657. FontEngine.TryPackGlyphsInAtlas(m_GlyphsToPack, m_GlyphsPacked, m_Padding, (GlyphPackingMode)m_PackingMode, m_GlyphRenderMode, m_AtlasWidth, m_AtlasHeight, m_FreeGlyphRects, m_UsedGlyphRects);
  658. if (m_IsGenerationCancelled)
  659. {
  660. DestroyImmediate(m_FontAtlasTexture);
  661. m_FontAtlasTexture = null;
  662. return;
  663. }
  664. //Debug.Log("Glyphs remaining to add [" + m_GlyphsToAdd.Count + "]. Glyphs added [" + m_GlyphsAdded.Count + "].");
  665. if (m_GlyphsToPack.Count > 0)
  666. {
  667. if (m_PointSize > minPointSize)
  668. {
  669. maxPointSize = m_PointSize;
  670. m_PointSize = (m_PointSize + minPointSize) / 2;
  671. //Debug.Log("Decreasing point size from [" + maxPointSize + "] to [" + m_PointSize + "].");
  672. }
  673. }
  674. else
  675. {
  676. if (maxPointSize - minPointSize > 1 && m_PointSize < maxPointSize)
  677. {
  678. minPointSize = m_PointSize;
  679. m_PointSize = (m_PointSize + maxPointSize) / 2;
  680. //Debug.Log("Increasing point size from [" + minPointSize + "] to [" + m_PointSize + "].");
  681. }
  682. else
  683. {
  684. //Debug.Log("[" + iteration + "] iterations to find the optimum point size of : [" + m_PointSize + "].");
  685. optimumPointSizeFound = true;
  686. }
  687. }
  688. }
  689. }
  690. else // Custom Point Size Mode
  691. {
  692. m_AtlasGenerationProgressLabel = "Packing glyphs...";
  693. // Set point size
  694. FontEngine.SetFaceSize(m_PointSize);
  695. m_GlyphsToPack.Clear();
  696. m_GlyphsPacked.Clear();
  697. m_FreeGlyphRects.Clear();
  698. m_FreeGlyphRects.Add(new GlyphRect(0, 0, m_AtlasWidth - packingModifier, m_AtlasHeight - packingModifier));
  699. m_UsedGlyphRects.Clear();
  700. for (int i = 0; i < m_AvailableGlyphsToAdd.Count; i++)
  701. {
  702. uint glyphIndex = m_AvailableGlyphsToAdd[i];
  703. if (FontEngine.TryGetGlyphWithIndexValue(glyphIndex, glyphLoadFlags, out Glyph glyph))
  704. {
  705. if (glyph.glyphRect.width > 0 && glyph.glyphRect.height > 0)
  706. {
  707. m_GlyphsToPack.Add(glyph);
  708. }
  709. else
  710. {
  711. m_GlyphsPacked.Add(glyph);
  712. }
  713. }
  714. }
  715. FontEngine.TryPackGlyphsInAtlas(m_GlyphsToPack, m_GlyphsPacked, m_Padding, (GlyphPackingMode)m_PackingMode, m_GlyphRenderMode, m_AtlasWidth, m_AtlasHeight, m_FreeGlyphRects, m_UsedGlyphRects);
  716. if (m_IsGenerationCancelled)
  717. {
  718. DestroyImmediate(m_FontAtlasTexture);
  719. m_FontAtlasTexture = null;
  720. return;
  721. }
  722. //Debug.Log("Glyphs remaining to add [" + m_GlyphsToAdd.Count + "]. Glyphs added [" + m_GlyphsAdded.Count + "].");
  723. }
  724. }
  725. else
  726. {
  727. int packingModifier = ((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP ? 0 : 1;
  728. FontEngine.SetFaceSize(m_PointSize);
  729. m_GlyphsToPack.Clear();
  730. m_GlyphsPacked.Clear();
  731. m_FreeGlyphRects.Clear();
  732. m_FreeGlyphRects.Add(new GlyphRect(0, 0, m_AtlasWidth - packingModifier, m_AtlasHeight - packingModifier));
  733. m_UsedGlyphRects.Clear();
  734. }
  735. //Stop StopWatch
  736. m_StopWatch.Stop();
  737. m_GlyphPackingGenerationTime = m_StopWatch.Elapsed.TotalMilliseconds;
  738. Debug.Log("Glyph packing completed in: " + m_GlyphPackingGenerationTime.ToString("0.000 ms."));
  739. m_StopWatch.Reset();
  740. m_FontCharacterTable.Clear();
  741. m_FontGlyphTable.Clear();
  742. m_GlyphsToRender.Clear();
  743. // Add glyphs and characters successfully added to texture to their respective font tables.
  744. foreach (Glyph glyph in m_GlyphsPacked)
  745. {
  746. uint glyphIndex = glyph.index;
  747. m_FontGlyphTable.Add(glyph);
  748. // Add glyphs to list of glyphs that need to be rendered.
  749. if (glyph.glyphRect.width > 0 && glyph.glyphRect.height > 0)
  750. m_GlyphsToRender.Add(glyph);
  751. foreach (uint unicode in m_GlyphLookupMap[glyphIndex])
  752. {
  753. // Create new Character
  754. m_FontCharacterTable.Add(new TMP_Character(unicode, glyph));
  755. }
  756. }
  757. //
  758. foreach (Glyph glyph in m_GlyphsToPack)
  759. {
  760. foreach (uint unicode in m_GlyphLookupMap[glyph.index])
  761. {
  762. m_ExcludedCharacters.Add(unicode);
  763. }
  764. }
  765. // Get the face info for the current sampling point size.
  766. m_FaceInfo = FontEngine.GetFaceInfo();
  767. autoEvent.Set();
  768. });
  769. // Worker thread to render glyphs in texture buffer.
  770. ThreadPool.QueueUserWorkItem(RenderGlyphs =>
  771. {
  772. autoEvent.WaitOne();
  773. // Start Stop Watch
  774. m_StopWatch = System.Diagnostics.Stopwatch.StartNew();
  775. m_IsRenderingDone = false;
  776. // Allocate texture data
  777. m_AtlasTextureBuffer = new byte[m_AtlasWidth * m_AtlasHeight];
  778. m_AtlasGenerationProgressLabel = "Rendering glyphs...";
  779. // Render and add glyphs to the given atlas texture.
  780. if (m_GlyphsToRender.Count > 0)
  781. {
  782. FontEngine.RenderGlyphsToTexture(m_GlyphsToRender, m_Padding, m_GlyphRenderMode, m_AtlasTextureBuffer, m_AtlasWidth, m_AtlasHeight);
  783. }
  784. m_IsRenderingDone = true;
  785. // Stop StopWatch
  786. m_StopWatch.Stop();
  787. m_GlyphRenderingGenerationTime = m_StopWatch.Elapsed.TotalMilliseconds;
  788. Debug.Log("Font Atlas generation completed in: " + m_GlyphRenderingGenerationTime.ToString("0.000 ms."));
  789. m_StopWatch.Reset();
  790. });
  791. }
  792. SaveCreationSettingsToEditorPrefs(SaveFontCreationSettings());
  793. }
  794. }
  795. // FONT RENDERING PROGRESS BAR
  796. GUILayout.Space(1);
  797. Rect progressRect = EditorGUILayout.GetControlRect(false, 20);
  798. GUI.enabled = true;
  799. progressRect.width -= 22;
  800. EditorGUI.ProgressBar(progressRect, Mathf.Max(0.01f, m_AtlasGenerationProgress), m_AtlasGenerationProgressLabel);
  801. progressRect.x = progressRect.x + progressRect.width + 2;
  802. progressRect.y -= 1;
  803. progressRect.width = 20;
  804. progressRect.height = 20;
  805. GUI.enabled = m_IsProcessing;
  806. if (GUI.Button(progressRect, "X"))
  807. {
  808. FontEngine.SendCancellationRequest();
  809. m_AtlasGenerationProgress = 0;
  810. m_IsProcessing = false;
  811. m_IsGenerationCancelled = true;
  812. }
  813. GUILayout.Space(5);
  814. // FONT STATUS & INFORMATION
  815. GUI.enabled = true;
  816. GUILayout.BeginVertical(EditorStyles.helpBox, GUILayout.Height(200));
  817. m_OutputScrollPosition = EditorGUILayout.BeginScrollView(m_OutputScrollPosition);
  818. EditorGUILayout.LabelField(m_OutputFeedback, TMP_UIStyleManager.label);
  819. EditorGUILayout.EndScrollView();
  820. GUILayout.EndVertical();
  821. // SAVE TEXTURE & CREATE and SAVE FONT XML FILE
  822. GUI.enabled = m_FontAtlasTexture != null && !m_IsProcessing; // Enable Save Button if font_Atlas is not Null.
  823. EditorGUILayout.BeginHorizontal();
  824. if (GUILayout.Button("Save") && GUI.enabled)
  825. {
  826. if (m_SelectedFontAsset == null)
  827. {
  828. if (m_LegacyFontAsset != null)
  829. SaveNewFontAssetWithSameName(m_LegacyFontAsset);
  830. else
  831. SaveNewFontAsset(m_SourceFontFile);
  832. }
  833. else
  834. {
  835. // Save over exiting Font Asset
  836. string filePath = Path.GetFullPath(AssetDatabase.GetAssetPath(m_SelectedFontAsset)).Replace('\\', '/');
  837. if (((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP)
  838. Save_Bitmap_FontAsset(filePath);
  839. else
  840. Save_SDF_FontAsset(filePath);
  841. }
  842. }
  843. if (GUILayout.Button("Save as...") && GUI.enabled)
  844. {
  845. if (m_SelectedFontAsset == null)
  846. {
  847. SaveNewFontAsset(m_SourceFontFile);
  848. }
  849. else
  850. {
  851. SaveNewFontAssetWithSameName(m_SelectedFontAsset);
  852. }
  853. }
  854. EditorGUILayout.EndHorizontal();
  855. EditorGUILayout.Space();
  856. EditorGUILayout.EndVertical();
  857. GUI.enabled = true; // Re-enable GUI
  858. if (position.height > position.width || position.width < k_TwoColumnControlsWidth)
  859. {
  860. DrawPreview();
  861. GUILayout.Space(5);
  862. }
  863. EditorGUILayout.EndScrollView();
  864. if (m_IsFontAtlasInvalid)
  865. ClearGeneratedData();
  866. }
  867. /// <summary>
  868. /// Clear the previously generated data.
  869. /// </summary>
  870. void ClearGeneratedData()
  871. {
  872. m_IsFontAtlasInvalid = false;
  873. if (m_FontAtlasTexture != null && !EditorUtility.IsPersistent(m_FontAtlasTexture))
  874. {
  875. DestroyImmediate(m_FontAtlasTexture);
  876. m_FontAtlasTexture = null;
  877. }
  878. m_AtlasGenerationProgressLabel = string.Empty;
  879. m_AtlasGenerationProgress = 0;
  880. m_SavedFontAtlas = null;
  881. m_OutputFeedback = string.Empty;
  882. m_WarningMessage = string.Empty;
  883. }
  884. /// <summary>
  885. /// Function to update the feedback window showing the results of the latest generation.
  886. /// </summary>
  887. void UpdateRenderFeedbackWindow()
  888. {
  889. m_PointSize = m_FaceInfo.pointSize;
  890. string missingGlyphReport = string.Empty;
  891. //string colorTag = m_FontCharacterTable.Count == m_CharacterCount ? "<color=#C0ffff>" : "<color=#ffff00>";
  892. string colorTag2 = "<color=#C0ffff>";
  893. missingGlyphReport = "Font: <b>" + colorTag2 + m_FaceInfo.familyName + "</color></b> Style: <b>" + colorTag2 + m_FaceInfo.styleName + "</color></b>";
  894. missingGlyphReport += "\nPoint Size: <b>" + colorTag2 + m_FaceInfo.pointSize + "</color></b> SP/PD Ratio: <b>" + colorTag2 + ((float)m_Padding / m_FaceInfo.pointSize).ToString("0.0%" + "</color></b>");
  895. missingGlyphReport += "\n\nCharacters included: <color=#ffff00><b>" + m_FontCharacterTable.Count + "/" + m_CharacterCount + "</b></color>";
  896. missingGlyphReport += "\nMissing characters: <color=#ffff00><b>" + m_MissingCharacters.Count + "</b></color>";
  897. missingGlyphReport += "\nExcluded characters: <color=#ffff00><b>" + m_ExcludedCharacters.Count + "</b></color>";
  898. // Report characters missing from font file
  899. missingGlyphReport += "\n\n<b><color=#ffff00>Characters missing from font file:</color></b>";
  900. missingGlyphReport += "\n----------------------------------------";
  901. m_OutputFeedback = missingGlyphReport;
  902. for (int i = 0; i < m_MissingCharacters.Count; i++)
  903. {
  904. missingGlyphReport += "\nID: <color=#C0ffff>" + m_MissingCharacters[i] + "\t</color>Hex: <color=#C0ffff>" + m_MissingCharacters[i].ToString("X") + "\t</color>Char [<color=#C0ffff>" + (char)m_MissingCharacters[i] + "</color>]";
  905. if (missingGlyphReport.Length < 16300)
  906. m_OutputFeedback = missingGlyphReport;
  907. }
  908. // Report characters that did not fit in the atlas texture
  909. missingGlyphReport += "\n\n<b><color=#ffff00>Characters excluded from packing:</color></b>";
  910. missingGlyphReport += "\n----------------------------------------";
  911. for (int i = 0; i < m_ExcludedCharacters.Count; i++)
  912. {
  913. missingGlyphReport += "\nID: <color=#C0ffff>" + m_ExcludedCharacters[i] + "\t</color>Hex: <color=#C0ffff>" + m_ExcludedCharacters[i].ToString("X") + "\t</color>Char [<color=#C0ffff>" + (char)m_ExcludedCharacters[i] + "</color>]";
  914. if (missingGlyphReport.Length < 16300)
  915. m_OutputFeedback = missingGlyphReport;
  916. }
  917. if (missingGlyphReport.Length > 16300)
  918. m_OutputFeedback += "\n\n<color=#ffff00>Report truncated.</color>\n<color=#c0ffff>See</color> \"TextMesh Pro\\Glyph Report.txt\"";
  919. // Save Missing Glyph Report file
  920. if (Directory.Exists("Assets/TextMesh Pro"))
  921. {
  922. missingGlyphReport = System.Text.RegularExpressions.Regex.Replace(missingGlyphReport, @"<[^>]*>", string.Empty);
  923. File.WriteAllText("Assets/TextMesh Pro/Glyph Report.txt", missingGlyphReport);
  924. AssetDatabase.Refresh();
  925. }
  926. }
  927. void CreateFontAtlasTexture()
  928. {
  929. if (m_FontAtlasTexture != null)
  930. DestroyImmediate(m_FontAtlasTexture);
  931. m_FontAtlasTexture = new Texture2D(m_AtlasWidth, m_AtlasHeight, TextureFormat.Alpha8, false, true);
  932. Color32[] colors = new Color32[m_AtlasWidth * m_AtlasHeight];
  933. for (int i = 0; i < colors.Length; i++)
  934. {
  935. byte c = m_AtlasTextureBuffer[i];
  936. colors[i] = new Color32(c, c, c, c);
  937. }
  938. // Clear allocation of
  939. m_AtlasTextureBuffer = null;
  940. if ((m_GlyphRenderMode & GlyphRenderMode.RASTER) == GlyphRenderMode.RASTER || (m_GlyphRenderMode & GlyphRenderMode.RASTER_HINTED) == GlyphRenderMode.RASTER_HINTED)
  941. m_FontAtlasTexture.filterMode = FilterMode.Point;
  942. m_FontAtlasTexture.SetPixels32(colors, 0);
  943. m_FontAtlasTexture.Apply(false, false);
  944. // Saving File for Debug
  945. //var pngData = m_FontAtlasTexture.EncodeToPNG();
  946. //File.WriteAllBytes("Assets/Textures/Debug Font Texture.png", pngData);
  947. }
  948. /// <summary>
  949. /// Open Save Dialog to provide the option save the font asset using the name of the source font file. This also appends SDF to the name if using any of the SDF Font Asset creation modes.
  950. /// </summary>
  951. /// <param name="sourceObject"></param>
  952. void SaveNewFontAsset(Object sourceObject)
  953. {
  954. string filePath;
  955. // Save new Font Asset and open save file requester at Source Font File location.
  956. string saveDirectory = new FileInfo(AssetDatabase.GetAssetPath(sourceObject)).DirectoryName;
  957. if (((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP)
  958. {
  959. filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", saveDirectory, sourceObject.name, "asset");
  960. if (filePath.Length == 0)
  961. return;
  962. Save_Bitmap_FontAsset(filePath);
  963. }
  964. else
  965. {
  966. filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", saveDirectory, sourceObject.name + " SDF", "asset");
  967. if (filePath.Length == 0)
  968. return;
  969. Save_SDF_FontAsset(filePath);
  970. }
  971. }
  972. /// <summary>
  973. /// Open Save Dialog to provide the option to save the font asset under the same name.
  974. /// </summary>
  975. /// <param name="sourceObject"></param>
  976. void SaveNewFontAssetWithSameName(Object sourceObject)
  977. {
  978. string filePath;
  979. // Save new Font Asset and open save file requester at Source Font File location.
  980. string saveDirectory = new FileInfo(AssetDatabase.GetAssetPath(sourceObject)).DirectoryName;
  981. filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", saveDirectory, sourceObject.name, "asset");
  982. if (filePath.Length == 0)
  983. return;
  984. if (((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP)
  985. {
  986. Save_Bitmap_FontAsset(filePath);
  987. }
  988. else
  989. {
  990. Save_SDF_FontAsset(filePath);
  991. }
  992. }
  993. void Save_Bitmap_FontAsset(string filePath)
  994. {
  995. filePath = filePath.Substring(0, filePath.Length - 6); // Trim file extension from filePath.
  996. string dataPath = Application.dataPath;
  997. if (filePath.IndexOf(dataPath, System.StringComparison.InvariantCultureIgnoreCase) == -1)
  998. {
  999. Debug.LogError("You're saving the font asset in a directory outside of this project folder. This is not supported. Please select a directory under \"" + dataPath + "\"");
  1000. return;
  1001. }
  1002. string relativeAssetPath = filePath.Substring(dataPath.Length - 6);
  1003. string tex_DirName = Path.GetDirectoryName(relativeAssetPath);
  1004. string tex_FileName = Path.GetFileNameWithoutExtension(relativeAssetPath);
  1005. string tex_Path_NoExt = tex_DirName + "/" + tex_FileName;
  1006. // Check if TextMeshPro font asset already exists. If not, create a new one. Otherwise update the existing one.
  1007. TMP_FontAsset fontAsset = AssetDatabase.LoadAssetAtPath(tex_Path_NoExt + ".asset", typeof(TMP_FontAsset)) as TMP_FontAsset;
  1008. if (fontAsset == null)
  1009. {
  1010. //Debug.Log("Creating TextMeshPro font asset!");
  1011. fontAsset = ScriptableObject.CreateInstance<TMP_FontAsset>(); // Create new TextMeshPro Font Asset.
  1012. AssetDatabase.CreateAsset(fontAsset, tex_Path_NoExt + ".asset");
  1013. // Set version number of font asset
  1014. fontAsset.version = "1.1.0";
  1015. //Set Font Asset Type
  1016. fontAsset.atlasRenderMode = m_GlyphRenderMode;
  1017. // Reference to the source font file GUID.
  1018. fontAsset.m_SourceFontFileGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(m_SourceFontFile));
  1019. // Add FaceInfo to Font Asset
  1020. fontAsset.faceInfo = m_FaceInfo;
  1021. // Add GlyphInfo[] to Font Asset
  1022. fontAsset.glyphTable = m_FontGlyphTable;
  1023. // Add CharacterTable[] to font asset.
  1024. fontAsset.characterTable = m_FontCharacterTable;
  1025. // Sort glyph and character tables.
  1026. fontAsset.SortGlyphAndCharacterTables();
  1027. // Get and Add Kerning Pairs to Font Asset
  1028. if (m_IncludeFontFeatures)
  1029. fontAsset.fontFeatureTable = GetKerningTable();
  1030. // Add Font Atlas as Sub-Asset
  1031. fontAsset.atlasTextures = new Texture2D[] { m_FontAtlasTexture };
  1032. m_FontAtlasTexture.name = tex_FileName + " Atlas";
  1033. fontAsset.atlasWidth = m_AtlasWidth;
  1034. fontAsset.atlasHeight = m_AtlasHeight;
  1035. fontAsset.atlasPadding = m_Padding;
  1036. AssetDatabase.AddObjectToAsset(m_FontAtlasTexture, fontAsset);
  1037. // Create new Material and Add it as Sub-Asset
  1038. Shader default_Shader = Shader.Find("TextMeshPro/Bitmap"); // m_shaderSelection;
  1039. Material tmp_material = new Material(default_Shader);
  1040. tmp_material.name = tex_FileName + " Material";
  1041. tmp_material.SetTexture(ShaderUtilities.ID_MainTex, m_FontAtlasTexture);
  1042. fontAsset.material = tmp_material;
  1043. AssetDatabase.AddObjectToAsset(tmp_material, fontAsset);
  1044. }
  1045. else
  1046. {
  1047. // Find all Materials referencing this font atlas.
  1048. Material[] material_references = TMP_EditorUtility.FindMaterialReferences(fontAsset);
  1049. // Set version number of font asset
  1050. fontAsset.version = "1.1.0";
  1051. // Special handling to remove legacy font asset data
  1052. if (fontAsset.m_glyphInfoList != null && fontAsset.m_glyphInfoList.Count > 0)
  1053. fontAsset.m_glyphInfoList = null;
  1054. // Destroy Assets that will be replaced.
  1055. if (fontAsset.atlasTextures != null && fontAsset.atlasTextures.Length > 0)
  1056. DestroyImmediate(fontAsset.atlasTextures[0], true);
  1057. //Set Font Asset Type
  1058. fontAsset.atlasRenderMode = m_GlyphRenderMode;
  1059. // Add FaceInfo to Font Asset
  1060. fontAsset.faceInfo = m_FaceInfo;
  1061. // Add GlyphInfo[] to Font Asset
  1062. fontAsset.glyphTable = m_FontGlyphTable;
  1063. // Add CharacterTable[] to font asset.
  1064. fontAsset.characterTable = m_FontCharacterTable;
  1065. // Sort glyph and character tables.
  1066. fontAsset.SortGlyphAndCharacterTables();
  1067. // Get and Add Kerning Pairs to Font Asset
  1068. if (m_IncludeFontFeatures)
  1069. fontAsset.fontFeatureTable = GetKerningTable();
  1070. // Add Font Atlas as Sub-Asset
  1071. fontAsset.atlasTextures = new Texture2D[] { m_FontAtlasTexture };
  1072. m_FontAtlasTexture.name = tex_FileName + " Atlas";
  1073. fontAsset.atlasWidth = m_AtlasWidth;
  1074. fontAsset.atlasHeight = m_AtlasHeight;
  1075. fontAsset.atlasPadding = m_Padding;
  1076. // Special handling due to a bug in earlier versions of Unity.
  1077. m_FontAtlasTexture.hideFlags = HideFlags.None;
  1078. fontAsset.material.hideFlags = HideFlags.None;
  1079. AssetDatabase.AddObjectToAsset(m_FontAtlasTexture, fontAsset);
  1080. // Assign new font atlas texture to the existing material.
  1081. fontAsset.material.SetTexture(ShaderUtilities.ID_MainTex, fontAsset.atlasTextures[0]);
  1082. // Update the Texture reference on the Material
  1083. for (int i = 0; i < material_references.Length; i++)
  1084. {
  1085. material_references[i].SetTexture(ShaderUtilities.ID_MainTex, m_FontAtlasTexture);
  1086. }
  1087. }
  1088. // Add list of GlyphRects to font asset.
  1089. fontAsset.freeGlyphRects = m_FreeGlyphRects;
  1090. fontAsset.usedGlyphRects = m_UsedGlyphRects;
  1091. // Save Font Asset creation settings
  1092. m_SelectedFontAsset = fontAsset;
  1093. m_LegacyFontAsset = null;
  1094. fontAsset.creationSettings = SaveFontCreationSettings();
  1095. AssetDatabase.SaveAssets();
  1096. AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(fontAsset)); // Re-import font asset to get the new updated version.
  1097. //EditorUtility.SetDirty(font_asset);
  1098. fontAsset.ReadFontAssetDefinition();
  1099. AssetDatabase.Refresh();
  1100. m_FontAtlasTexture = null;
  1101. // NEED TO GENERATE AN EVENT TO FORCE A REDRAW OF ANY TEXTMESHPRO INSTANCES THAT MIGHT BE USING THIS FONT ASSET
  1102. TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, fontAsset);
  1103. }
  1104. void Save_SDF_FontAsset(string filePath)
  1105. {
  1106. filePath = filePath.Substring(0, filePath.Length - 6); // Trim file extension from filePath.
  1107. string dataPath = Application.dataPath;
  1108. if (filePath.IndexOf(dataPath, System.StringComparison.InvariantCultureIgnoreCase) == -1)
  1109. {
  1110. Debug.LogError("You're saving the font asset in a directory outside of this project folder. This is not supported. Please select a directory under \"" + dataPath + "\"");
  1111. return;
  1112. }
  1113. string relativeAssetPath = filePath.Substring(dataPath.Length - 6);
  1114. string tex_DirName = Path.GetDirectoryName(relativeAssetPath);
  1115. string tex_FileName = Path.GetFileNameWithoutExtension(relativeAssetPath);
  1116. string tex_Path_NoExt = tex_DirName + "/" + tex_FileName;
  1117. // Check if TextMeshPro font asset already exists. If not, create a new one. Otherwise update the existing one.
  1118. TMP_FontAsset fontAsset = AssetDatabase.LoadAssetAtPath<TMP_FontAsset>(tex_Path_NoExt + ".asset");
  1119. if (fontAsset == null)
  1120. {
  1121. //Debug.Log("Creating TextMeshPro font asset!");
  1122. fontAsset = ScriptableObject.CreateInstance<TMP_FontAsset>(); // Create new TextMeshPro Font Asset.
  1123. AssetDatabase.CreateAsset(fontAsset, tex_Path_NoExt + ".asset");
  1124. // Set version number of font asset
  1125. fontAsset.version = "1.1.0";
  1126. // Reference to source font file GUID.
  1127. fontAsset.m_SourceFontFileGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(m_SourceFontFile));
  1128. //Set Font Asset Type
  1129. fontAsset.atlasRenderMode = m_GlyphRenderMode;
  1130. // Add FaceInfo to Font Asset
  1131. fontAsset.faceInfo = m_FaceInfo;
  1132. // Add GlyphInfo[] to Font Asset
  1133. fontAsset.glyphTable = m_FontGlyphTable;
  1134. // Add CharacterTable[] to font asset.
  1135. fontAsset.characterTable = m_FontCharacterTable;
  1136. // Sort glyph and character tables.
  1137. fontAsset.SortGlyphAndCharacterTables();
  1138. // Get and Add Kerning Pairs to Font Asset
  1139. if (m_IncludeFontFeatures)
  1140. fontAsset.fontFeatureTable = GetKerningTable();
  1141. // Add Font Atlas as Sub-Asset
  1142. fontAsset.atlasTextures = new Texture2D[] { m_FontAtlasTexture };
  1143. m_FontAtlasTexture.name = tex_FileName + " Atlas";
  1144. fontAsset.atlasWidth = m_AtlasWidth;
  1145. fontAsset.atlasHeight = m_AtlasHeight;
  1146. fontAsset.atlasPadding = m_Padding;
  1147. AssetDatabase.AddObjectToAsset(m_FontAtlasTexture, fontAsset);
  1148. // Create new Material and Add it as Sub-Asset
  1149. Shader default_Shader = Shader.Find("TextMeshPro/Distance Field");
  1150. Material tmp_material = new Material(default_Shader);
  1151. tmp_material.name = tex_FileName + " Material";
  1152. tmp_material.SetTexture(ShaderUtilities.ID_MainTex, m_FontAtlasTexture);
  1153. tmp_material.SetFloat(ShaderUtilities.ID_TextureWidth, m_FontAtlasTexture.width);
  1154. tmp_material.SetFloat(ShaderUtilities.ID_TextureHeight, m_FontAtlasTexture.height);
  1155. int spread = m_Padding + 1;
  1156. tmp_material.SetFloat(ShaderUtilities.ID_GradientScale, spread); // Spread = Padding for Brute Force SDF.
  1157. tmp_material.SetFloat(ShaderUtilities.ID_WeightNormal, fontAsset.normalStyle);
  1158. tmp_material.SetFloat(ShaderUtilities.ID_WeightBold, fontAsset.boldStyle);
  1159. fontAsset.material = tmp_material;
  1160. AssetDatabase.AddObjectToAsset(tmp_material, fontAsset);
  1161. }
  1162. else
  1163. {
  1164. // Find all Materials referencing this font atlas.
  1165. Material[] material_references = TMP_EditorUtility.FindMaterialReferences(fontAsset);
  1166. // Destroy Assets that will be replaced.
  1167. if (fontAsset.atlasTextures != null && fontAsset.atlasTextures.Length > 0)
  1168. DestroyImmediate(fontAsset.atlasTextures[0], true);
  1169. // Set version number of font asset
  1170. fontAsset.version = "1.1.0";
  1171. // Special handling to remove legacy font asset data
  1172. if (fontAsset.m_glyphInfoList != null && fontAsset.m_glyphInfoList.Count > 0)
  1173. fontAsset.m_glyphInfoList = null;
  1174. //Set Font Asset Type
  1175. fontAsset.atlasRenderMode = m_GlyphRenderMode;
  1176. // Add FaceInfo to Font Asset
  1177. fontAsset.faceInfo = m_FaceInfo;
  1178. // Add GlyphInfo[] to Font Asset
  1179. fontAsset.glyphTable = m_FontGlyphTable;
  1180. // Add CharacterTable[] to font asset.
  1181. fontAsset.characterTable = m_FontCharacterTable;
  1182. // Sort glyph and character tables.
  1183. fontAsset.SortGlyphAndCharacterTables();
  1184. // Get and Add Kerning Pairs to Font Asset
  1185. // TODO: Check and preserve existing adjustment pairs.
  1186. if (m_IncludeFontFeatures)
  1187. fontAsset.fontFeatureTable = GetKerningTable();
  1188. // Add Font Atlas as Sub-Asset
  1189. fontAsset.atlasTextures = new Texture2D[] { m_FontAtlasTexture };
  1190. m_FontAtlasTexture.name = tex_FileName + " Atlas";
  1191. fontAsset.atlasWidth = m_AtlasWidth;
  1192. fontAsset.atlasHeight = m_AtlasHeight;
  1193. fontAsset.atlasPadding = m_Padding;
  1194. // Special handling due to a bug in earlier versions of Unity.
  1195. m_FontAtlasTexture.hideFlags = HideFlags.None;
  1196. fontAsset.material.hideFlags = HideFlags.None;
  1197. AssetDatabase.AddObjectToAsset(m_FontAtlasTexture, fontAsset);
  1198. // Assign new font atlas texture to the existing material.
  1199. fontAsset.material.SetTexture(ShaderUtilities.ID_MainTex, fontAsset.atlasTextures[0]);
  1200. // Update the Texture reference on the Material
  1201. for (int i = 0; i < material_references.Length; i++)
  1202. {
  1203. material_references[i].SetTexture(ShaderUtilities.ID_MainTex, m_FontAtlasTexture);
  1204. material_references[i].SetFloat(ShaderUtilities.ID_TextureWidth, m_FontAtlasTexture.width);
  1205. material_references[i].SetFloat(ShaderUtilities.ID_TextureHeight, m_FontAtlasTexture.height);
  1206. int spread = m_Padding + 1;
  1207. material_references[i].SetFloat(ShaderUtilities.ID_GradientScale, spread); // Spread = Padding for Brute Force SDF.
  1208. material_references[i].SetFloat(ShaderUtilities.ID_WeightNormal, fontAsset.normalStyle);
  1209. material_references[i].SetFloat(ShaderUtilities.ID_WeightBold, fontAsset.boldStyle);
  1210. }
  1211. }
  1212. // Saving File for Debug
  1213. //var pngData = destination_Atlas.EncodeToPNG();
  1214. //File.WriteAllBytes("Assets/Textures/Debug Distance Field.png", pngData);
  1215. // Add list of GlyphRects to font asset.
  1216. fontAsset.freeGlyphRects = m_FreeGlyphRects;
  1217. fontAsset.usedGlyphRects = m_UsedGlyphRects;
  1218. // Save Font Asset creation settings
  1219. m_SelectedFontAsset = fontAsset;
  1220. m_LegacyFontAsset = null;
  1221. fontAsset.creationSettings = SaveFontCreationSettings();
  1222. AssetDatabase.SaveAssets();
  1223. AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(fontAsset)); // Re-import font asset to get the new updated version.
  1224. fontAsset.ReadFontAssetDefinition();
  1225. AssetDatabase.Refresh();
  1226. m_FontAtlasTexture = null;
  1227. // NEED TO GENERATE AN EVENT TO FORCE A REDRAW OF ANY TEXTMESHPRO INSTANCES THAT MIGHT BE USING THIS FONT ASSET
  1228. TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, fontAsset);
  1229. }
  1230. /// <summary>
  1231. /// Internal method to save the Font Asset Creation Settings
  1232. /// </summary>
  1233. /// <returns></returns>
  1234. FontAssetCreationSettings SaveFontCreationSettings()
  1235. {
  1236. FontAssetCreationSettings settings = new FontAssetCreationSettings();
  1237. //settings.sourceFontFileName = m_SourceFontFile.name;
  1238. settings.sourceFontFileGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(m_SourceFontFile));
  1239. settings.pointSizeSamplingMode = m_PointSizeSamplingMode;
  1240. settings.pointSize = m_PointSize;
  1241. settings.padding = m_Padding;
  1242. settings.packingMode = (int)m_PackingMode;
  1243. settings.atlasWidth = m_AtlasWidth;
  1244. settings.atlasHeight = m_AtlasHeight;
  1245. settings.characterSetSelectionMode = m_CharacterSetSelectionMode;
  1246. settings.characterSequence = m_CharacterSequence;
  1247. settings.referencedFontAssetGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(m_ReferencedFontAsset));
  1248. settings.referencedTextAssetGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(m_CharactersFromFile));
  1249. //settings.fontStyle = (int)m_FontStyle;
  1250. //settings.fontStyleModifier = m_FontStyleValue;
  1251. settings.renderMode = (int)m_GlyphRenderMode;
  1252. settings.includeFontFeatures = m_IncludeFontFeatures;
  1253. return settings;
  1254. }
  1255. /// <summary>
  1256. /// Internal method to load the Font Asset Creation Settings
  1257. /// </summary>
  1258. /// <param name="settings"></param>
  1259. void LoadFontCreationSettings(FontAssetCreationSettings settings)
  1260. {
  1261. m_SourceFontFile = AssetDatabase.LoadAssetAtPath<Font>(AssetDatabase.GUIDToAssetPath(settings.sourceFontFileGUID));
  1262. m_PointSizeSamplingMode = settings.pointSizeSamplingMode;
  1263. m_PointSize = settings.pointSize;
  1264. m_Padding = settings.padding;
  1265. m_PackingMode = (FontPackingModes)settings.packingMode;
  1266. m_AtlasWidth = settings.atlasWidth;
  1267. m_AtlasHeight = settings.atlasHeight;
  1268. m_CharacterSetSelectionMode = settings.characterSetSelectionMode;
  1269. m_CharacterSequence = settings.characterSequence;
  1270. m_ReferencedFontAsset = AssetDatabase.LoadAssetAtPath<TMP_FontAsset>(AssetDatabase.GUIDToAssetPath(settings.referencedFontAssetGUID));
  1271. m_CharactersFromFile = AssetDatabase.LoadAssetAtPath<TextAsset>(AssetDatabase.GUIDToAssetPath(settings.referencedTextAssetGUID));
  1272. //m_FontStyle = (FaceStyles)settings.fontStyle;
  1273. //m_FontStyleValue = settings.fontStyleModifier;
  1274. m_GlyphRenderMode = (GlyphRenderMode)settings.renderMode;
  1275. m_IncludeFontFeatures = settings.includeFontFeatures;
  1276. }
  1277. /// <summary>
  1278. /// Save the latest font asset creation settings to EditorPrefs.
  1279. /// </summary>
  1280. /// <param name="settings"></param>
  1281. void SaveCreationSettingsToEditorPrefs(FontAssetCreationSettings settings)
  1282. {
  1283. // Create new list if one does not already exist
  1284. if (m_FontAssetCreationSettingsContainer == null)
  1285. {
  1286. m_FontAssetCreationSettingsContainer = new FontAssetCreationSettingsContainer();
  1287. m_FontAssetCreationSettingsContainer.fontAssetCreationSettings = new List<FontAssetCreationSettings>();
  1288. }
  1289. // Add new creation settings to the list
  1290. m_FontAssetCreationSettingsContainer.fontAssetCreationSettings.Add(settings);
  1291. // Since list should only contain the most 4 recent settings, we remove the first element if list exceeds 4 elements.
  1292. if (m_FontAssetCreationSettingsContainer.fontAssetCreationSettings.Count > 4)
  1293. m_FontAssetCreationSettingsContainer.fontAssetCreationSettings.RemoveAt(0);
  1294. m_FontAssetCreationSettingsCurrentIndex = m_FontAssetCreationSettingsContainer.fontAssetCreationSettings.Count - 1;
  1295. // Serialize list to JSON
  1296. string serializedSettings = JsonUtility.ToJson(m_FontAssetCreationSettingsContainer, true);
  1297. EditorPrefs.SetString(k_FontAssetCreationSettingsContainerKey, serializedSettings);
  1298. }
  1299. void DrawPreview()
  1300. {
  1301. Rect pixelRect;
  1302. if (position.width > position.height && position.width > k_TwoColumnControlsWidth)
  1303. {
  1304. float minSide = Mathf.Min(position.height - 15f, position.width - k_TwoColumnControlsWidth);
  1305. EditorGUILayout.BeginVertical(EditorStyles.helpBox, GUILayout.MaxWidth(minSide));
  1306. pixelRect = GUILayoutUtility.GetRect(minSide, minSide, GUILayout.ExpandHeight(false), GUILayout.ExpandWidth(false));
  1307. }
  1308. else
  1309. {
  1310. EditorGUILayout.BeginVertical(EditorStyles.helpBox);
  1311. pixelRect = GUILayoutUtility.GetAspectRect(1f);
  1312. }
  1313. if (m_FontAtlasTexture != null)
  1314. {
  1315. EditorGUI.DrawTextureAlpha(pixelRect, m_FontAtlasTexture, ScaleMode.StretchToFill);
  1316. }
  1317. else if (m_SavedFontAtlas != null)
  1318. {
  1319. EditorGUI.DrawTextureAlpha(pixelRect, m_SavedFontAtlas, ScaleMode.StretchToFill);
  1320. }
  1321. EditorGUILayout.EndVertical();
  1322. }
  1323. void CheckForLegacyGlyphRenderMode()
  1324. {
  1325. // Special handling for legacy glyph render mode
  1326. if ((int)m_GlyphRenderMode < 0x100)
  1327. {
  1328. switch ((int)m_GlyphRenderMode)
  1329. {
  1330. case 0:
  1331. m_GlyphRenderMode = GlyphRenderMode.SMOOTH_HINTED;
  1332. break;
  1333. case 1:
  1334. m_GlyphRenderMode = GlyphRenderMode.SMOOTH;
  1335. break;
  1336. case 2:
  1337. m_GlyphRenderMode = GlyphRenderMode.RASTER_HINTED;
  1338. break;
  1339. case 3:
  1340. m_GlyphRenderMode = GlyphRenderMode.RASTER;
  1341. break;
  1342. case 6:
  1343. case 7:
  1344. m_GlyphRenderMode = GlyphRenderMode.SDFAA;
  1345. break;
  1346. }
  1347. }
  1348. }
  1349. // Get Kerning Pairs
  1350. public TMP_FontFeatureTable GetKerningTable()
  1351. {
  1352. GlyphPairAdjustmentRecord[] adjustmentRecords = FontEngine.GetGlyphPairAdjustmentTable(m_AvailableGlyphsToAdd.ToArray());
  1353. if (adjustmentRecords == null)
  1354. return null;
  1355. TMP_FontFeatureTable fontFeatureTable = new TMP_FontFeatureTable();
  1356. for (int i = 0; i < adjustmentRecords.Length; i++)
  1357. {
  1358. fontFeatureTable.glyphPairAdjustmentRecords.Add(new TMP_GlyphPairAdjustmentRecord(adjustmentRecords[i]));
  1359. }
  1360. fontFeatureTable.SortGlyphPairAdjustmentRecords();
  1361. return fontFeatureTable;
  1362. }
  1363. }
  1364. }