-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Expand file tree
/
Copy pathFontAssetCreatorWindow.cs
More file actions
2103 lines (1675 loc) · 94.8 KB
/
Copy pathFontAssetCreatorWindow.cs
File metadata and controls
2103 lines (1675 loc) · 94.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.IO;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.TextCore.Text;
using UnityEngine.TextCore.LowLevel;
using UnityEditor.TextCore.LowLevel;
using Object = UnityEngine.Object;
using TextAsset = UnityEngine.TextAsset;
using FaceInfo = UnityEngine.TextCore.FaceInfo;
using Glyph = UnityEngine.TextCore.Glyph;
using GlyphRect = UnityEngine.TextCore.GlyphRect;
using GlyphMetrics = UnityEngine.TextCore.GlyphMetrics;
using System;
#pragma warning disable CS0618 // Font feature tables and OTL feature tags; TextCoreShaderGUI, TextCoreShaderGUISDF, TextCoreShaderGUIBitmap, TextShaderUtilities are obsolete; handled natively by ATG
namespace UnityEditor.TextCore.Text
{
public class FontAssetCreatorWindow : EditorWindow
{
[MenuItem("Window/Text/Font Asset Creator", false, 2025)]
internal static void ShowFontAtlasCreatorWindow()
{
var window = GetWindow<FontAssetCreatorWindow>();
window.titleContent = new GUIContent("Font Asset Creator");
window.Focus();
// Make sure TMP Essential Resources have been imported.
window.CheckEssentialResources();
}
public static void ShowFontAtlasCreatorWindow(Font font)
{
var window = GetWindow<FontAssetCreatorWindow>();
window.titleContent = new GUIContent("Font Asset Creator");
window.Focus();
window.ClearGeneratedData();
window.m_LegacyFontAsset = null;
window.m_SelectedFontAsset = null;
// Override selected font asset
window.m_SourceFont = font;
// Make sure TMP Essential Resources have been imported.
window.CheckEssentialResources();
}
public static void ShowFontAtlasCreatorWindow(FontAsset fontAsset)
{
var window = GetWindow<FontAssetCreatorWindow>();
window.titleContent = new GUIContent("Font Asset Creator");
window.Focus();
// Clear any previously generated data
window.ClearGeneratedData();
window.m_LegacyFontAsset = null;
// Load font asset creation settings if we have valid settings
if (string.IsNullOrEmpty(fontAsset.fontAssetCreationEditorSettings.sourceFontFileGUID) == false)
{
window.LoadFontCreationSettings(fontAsset.fontAssetCreationEditorSettings);
// Override settings to inject character list from font asset
// window.m_CharacterSetSelectionMode = 6;
// window.m_CharacterSequence = TextCoreEditorUtilities.GetUnicodeCharacterSequence(FontAsset.GetCharactersArray(fontAsset));
window.m_ReferencedFontAsset = fontAsset;
window.m_SavedFontAtlas = fontAsset.atlasTexture;
}
else
{
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.";
window.m_SourceFont = null;
window.m_LegacyFontAsset = fontAsset;
}
// Even if we don't have any saved generation settings, we still want to pre-select the source font file.
window.m_SelectedFontAsset = fontAsset;
// Make sure TMP Essential Resources have been imported.
window.CheckEssentialResources();
}
[System.Serializable]
class FontAssetCreationSettingsContainer
{
public List<FontAssetCreationEditorSettings> fontAssetCreationSettings;
}
FontAssetCreationSettingsContainer m_FontAssetCreationSettingsContainer;
//static readonly string[] m_FontCreationPresets = new string[] { "Recent 1", "Recent 2", "Recent 3", "Recent 4" };
int m_FontAssetCreationSettingsCurrentIndex = 0;
const string k_FontAssetCreationSettingsContainerKey = "TextMeshPro.FontAssetCreator.RecentFontAssetCreationSettings.Container";
const string k_FontAssetCreationSettingsCurrentIndexKey = "TextMeshPro.FontAssetCreator.RecentFontAssetCreationSettings.CurrentIndex";
const float k_TwoColumnControlsWidth = 335f;
// Diagnostics
System.Diagnostics.Stopwatch m_StopWatch;
double m_GlyphPackingGenerationTime;
double m_GlyphRenderingGenerationTime;
string[] m_FontSizingOptions = { "Auto Sizing", "Custom Size" };
int m_PointSizeSamplingMode;
string[] m_FontResolutionLabels = { "8", "16", "32", "64", "128", "256", "512", "1024", "2048", "4096", "8192" };
int[] m_FontAtlasResolutions = { 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192 };
string[] m_FontCharacterSets = { "ASCII", "Extended ASCII", "ASCII Lowercase", "ASCII Uppercase", "Numbers + Symbols", "Custom Range", "Unicode Range (Hex)", "Custom Characters", "Characters from File" };
enum FontPackingModes { Fast = 0, Optimum = 4 };
FontPackingModes m_PackingMode = FontPackingModes.Fast;
int m_CharacterSetSelectionMode;
string m_CharacterSequence = "";
string m_OutputFeedback = "";
string m_WarningMessage;
int m_CharacterCount;
Vector2 m_ScrollPosition;
Vector2 m_OutputScrollPosition;
bool m_IsRepaintNeeded;
float m_AtlasGenerationProgress;
string m_AtlasGenerationProgressLabel = string.Empty;
bool m_IsGlyphPackingDone;
bool m_IsGlyphRenderingDone;
bool m_IsRenderingDone;
bool m_IsProcessing;
bool m_IsGenerationDisabled;
bool m_IsGenerationCancelled;
bool m_IsFontAtlasInvalid;
Font m_SourceFont;
int m_SourceFontFaceIndex;
private string[] m_SourceFontFaces = Array.Empty<string>();
FontAsset m_SelectedFontAsset;
FontAsset m_LegacyFontAsset;
FontAsset m_ReferencedFontAsset;
TextAsset m_CharactersFromFile;
int m_PointSize;
float m_PaddingFieldValue = 10;
int m_Padding;
enum PaddingMode { Undefined = 0, Percentage = 1, Pixel = 2 };
string[] k_PaddingOptionLabels = { "%", "px" };
private PaddingMode m_PaddingMode = PaddingMode.Percentage;
GlyphRenderMode m_GlyphRenderMode = GlyphRenderMode.SDFAA;
int m_AtlasWidth = 512;
int m_AtlasHeight = 512;
byte[] m_AtlasTextureBuffer;
Texture2D m_FontAtlasTexture;
Texture2D m_GlyphRectPreviewTexture;
Texture2D m_SavedFontAtlas;
//
List<Glyph> m_FontGlyphTable = new List<Glyph>();
List<Character> m_FontCharacterTable = new List<Character>();
Dictionary<uint, uint> m_CharacterLookupMap = new Dictionary<uint, uint>();
Dictionary<uint, List<uint>> m_GlyphLookupMap = new Dictionary<uint, List<uint>>();
List<Glyph> m_GlyphsToPack = new List<Glyph>();
List<Glyph> m_GlyphsPacked = new List<Glyph>();
List<GlyphRect> m_FreeGlyphRects = new List<GlyphRect>();
List<GlyphRect> m_UsedGlyphRects = new List<GlyphRect>();
List<Glyph> m_GlyphsToRender = new List<Glyph>();
List<uint> m_AvailableGlyphsToAdd = new List<uint>();
List<uint> m_MissingCharacters = new List<uint>();
List<uint> m_ExcludedCharacters = new List<uint>();
private FaceInfo m_FaceInfo;
bool m_IncludeFontFeatures;
public void OnEnable()
{
// Used for Diagnostics
m_StopWatch = new System.Diagnostics.Stopwatch();
// Set Editor window size.
minSize = new Vector2(315, minSize.y);
// Initialize & Get shader property IDs.
TextShaderUtilities.GetShaderPropertyIDs();
// Load last selected preset if we are not already in the process of regenerating an existing font asset (via the Context menu)
if (EditorPrefs.HasKey(k_FontAssetCreationSettingsContainerKey))
{
if (m_FontAssetCreationSettingsContainer == null)
m_FontAssetCreationSettingsContainer = JsonUtility.FromJson<FontAssetCreationSettingsContainer>(EditorPrefs.GetString(k_FontAssetCreationSettingsContainerKey));
if (m_FontAssetCreationSettingsContainer.fontAssetCreationSettings != null && m_FontAssetCreationSettingsContainer.fontAssetCreationSettings.Count > 0)
{
// Load Font Asset Creation Settings preset.
if (EditorPrefs.HasKey(k_FontAssetCreationSettingsCurrentIndexKey))
m_FontAssetCreationSettingsCurrentIndex = EditorPrefs.GetInt(k_FontAssetCreationSettingsCurrentIndexKey);
LoadFontCreationSettings(m_FontAssetCreationSettingsContainer.fontAssetCreationSettings[m_FontAssetCreationSettingsCurrentIndex]);
}
}
// Get potential font face and styles for the current font.
m_SourceFontFaces = GetFontFaces();
ClearGeneratedData();
}
public void OnDisable()
{
//Debug.Log("TextMeshPro Editor Window has been disabled.");
// Destroy Engine only if it has been initialized already
FontEngine.DestroyFontEngine();
ClearGeneratedData();
// Remove Glyph Report if one was created.
if (File.Exists("Assets/TextMesh Pro/Glyph Report.txt"))
{
File.Delete("Assets/TextMesh Pro/Glyph Report.txt");
File.Delete("Assets/TextMesh Pro/Glyph Report.txt.meta");
AssetDatabase.Refresh();
}
// Save Font Asset Creation Settings Index
SaveCreationSettingsToEditorPrefs(SaveFontCreationSettings());
EditorPrefs.SetInt(k_FontAssetCreationSettingsCurrentIndexKey, m_FontAssetCreationSettingsCurrentIndex);
// Unregister to event
TextEventManager.RESOURCE_LOAD_EVENT.Remove(ON_RESOURCES_LOADED);
Resources.UnloadUnusedAssets();
}
// Event received when TMP resources have been loaded.
void ON_RESOURCES_LOADED()
{
TextEventManager.RESOURCE_LOAD_EVENT.Remove(ON_RESOURCES_LOADED);
m_IsGenerationDisabled = false;
}
// Make sure TMP Essential Resources have been imported.
void CheckEssentialResources()
{
// TODO: Update this
// if (TMP_Settings.instance == null)
// {
// if (m_IsGenerationDisabled == false)
// TMPro_EventManager.RESOURCE_LOAD_EVENT.Add(ON_RESOURCES_LOADED);
//
// m_IsGenerationDisabled = true;
// }
}
public void OnGUI()
{
GUILayout.BeginHorizontal();
DrawControls();
if (position.width > position.height && position.width > k_TwoColumnControlsWidth)
DrawPreview();
GUILayout.EndHorizontal();
}
public void Update()
{
if (m_IsRepaintNeeded)
{
//Debug.Log("Repainting...");
m_IsRepaintNeeded = false;
Repaint();
}
// Update Progress bar is we are Rendering a Font.
if (m_IsProcessing)
{
m_AtlasGenerationProgress = FontEngine.generationProgress;
m_IsRepaintNeeded = true;
}
if (m_IsGlyphPackingDone)
{
UpdateRenderFeedbackWindow();
if (m_IsGenerationCancelled == false)
{
DrawGlyphRectPreviewTexture();
Debug.Log("Glyph packing completed in: " + m_GlyphPackingGenerationTime.ToString("0.000 ms."));
}
m_IsGlyphPackingDone = false;
}
if (m_IsGlyphRenderingDone)
{
Debug.Log("Font Atlas generation completed in: " + m_GlyphRenderingGenerationTime.ToString("0.000 ms."));
m_IsGlyphRenderingDone = false;
}
// Update Feedback Window & Create Font Texture once Rendering is done.
if (m_IsRenderingDone)
{
m_IsProcessing = false;
m_IsRenderingDone = false;
if (m_IsGenerationCancelled == false)
{
m_AtlasGenerationProgress = FontEngine.generationProgress;
m_AtlasGenerationProgressLabel = "Generation completed in: " + (m_GlyphPackingGenerationTime + m_GlyphRenderingGenerationTime).ToString("0.00 ms.");
UpdateRenderFeedbackWindow();
CreateFontAtlasTexture();
// If dynamic make readable ...
m_FontAtlasTexture.Apply(false, false);
}
Repaint();
}
}
/// <summary>
/// Method which returns the character corresponding to a decimal value.
/// </summary>
/// <param name="sequence"></param>
/// <returns></returns>
static uint[] ParseNumberSequence(string sequence)
{
List<uint> unicodeList = new List<uint>();
string[] sequences = sequence.Split(',');
foreach (string seq in sequences)
{
string[] s1 = seq.Split('-');
if (s1.Length == 1)
try
{
unicodeList.Add(uint.Parse(s1[0]));
}
catch
{
Debug.Log("No characters selected or invalid format.");
}
else
{
for (uint j = uint.Parse(s1[0]); j < uint.Parse(s1[1]) + 1; j++)
{
unicodeList.Add(j);
}
}
}
return unicodeList.ToArray();
}
/// <summary>
/// Method which returns the character (decimal value) from a hex sequence.
/// </summary>
/// <param name="sequence"></param>
/// <returns></returns>
static uint[] ParseHexNumberSequence(string sequence)
{
List<uint> unicodeList = new List<uint>();
string[] sequences = sequence.Split(',');
foreach (string seq in sequences)
{
string[] s1 = seq.Split('-');
if (s1.Length == 1)
try
{
unicodeList.Add(uint.Parse(s1[0], NumberStyles.AllowHexSpecifier));
}
catch
{
Debug.Log("No characters selected or invalid format.");
}
else
{
for (uint j = uint.Parse(s1[0], NumberStyles.AllowHexSpecifier); j < uint.Parse(s1[1], NumberStyles.AllowHexSpecifier) + 1; j++)
{
unicodeList.Add(j);
}
}
}
return unicodeList.ToArray();
}
void DrawControls()
{
GUILayout.Space(5f);
if (position.width > position.height && position.width > k_TwoColumnControlsWidth)
{
m_ScrollPosition = EditorGUILayout.BeginScrollView(m_ScrollPosition, GUILayout.Width(315));
}
else
{
m_ScrollPosition = EditorGUILayout.BeginScrollView(m_ScrollPosition);
}
GUILayout.Space(5f);
GUILayout.Label(m_SelectedFontAsset != null ? string.Format("Font Settings [{0}]", m_SelectedFontAsset.name) : "Font Settings", EditorStyles.boldLabel);
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
EditorGUIUtility.labelWidth = 125f;
EditorGUIUtility.fieldWidth = 5f;
// Disable Options if already generating a font atlas texture.
EditorGUI.BeginDisabledGroup(m_IsProcessing);
{
// FONT SELECTION
EditorGUI.BeginChangeCheck();
m_SourceFont = EditorGUILayout.ObjectField("Source Font", m_SourceFont, typeof(Font), false) as Font;
if (EditorGUI.EndChangeCheck())
{
m_SelectedFontAsset = null;
m_IsFontAtlasInvalid = true;
m_SourceFontFaces = GetFontFaces();
m_SourceFontFaceIndex = 0;
}
// FONT FACE AND STYLE SELECTION
EditorGUI.BeginChangeCheck();
GUI.enabled = m_SourceFont != null;
m_SourceFontFaceIndex = EditorGUILayout.Popup("Font Face", m_SourceFontFaceIndex, m_SourceFontFaces);
if (EditorGUI.EndChangeCheck())
{
m_SelectedFontAsset = null;
m_IsFontAtlasInvalid = true;
}
GUI.enabled = true;
// FONT SIZING
EditorGUI.BeginChangeCheck();
if (m_PointSizeSamplingMode == 0)
{
m_PointSizeSamplingMode = EditorGUILayout.Popup("Sampling Point Size", m_PointSizeSamplingMode, m_FontSizingOptions);
}
else
{
GUILayout.BeginHorizontal();
m_PointSizeSamplingMode = EditorGUILayout.Popup("Sampling Point Size", m_PointSizeSamplingMode, m_FontSizingOptions, GUILayout.Width(225));
m_PointSize = EditorGUILayout.IntField(m_PointSize);
GUILayout.EndHorizontal();
}
if (EditorGUI.EndChangeCheck())
{
m_IsFontAtlasInvalid = true;
}
// FONT PADDING
GUILayout.BeginHorizontal();
EditorGUI.BeginChangeCheck();
m_PaddingFieldValue = Mathf.Max(EditorGUILayout.FloatField("Padding", m_PaddingFieldValue), 0);
int selection = m_PaddingMode == PaddingMode.Undefined || m_PaddingMode == PaddingMode.Pixel ? 1 : 0;
selection = GUILayout.SelectionGrid(selection, k_PaddingOptionLabels, 2);
if (m_PaddingMode == PaddingMode.Percentage)
m_PaddingFieldValue = Mathf.Min((int)(m_PaddingFieldValue + 0.5f), float.MaxValue);
if (EditorGUI.EndChangeCheck())
{
m_PaddingMode = (PaddingMode)selection + 1;
m_IsFontAtlasInvalid = true;
}
GUILayout.EndHorizontal();
// FONT PACKING METHOD SELECTION
EditorGUI.BeginChangeCheck();
m_PackingMode = (FontPackingModes)EditorGUILayout.EnumPopup("Packing Method", m_PackingMode);
if (EditorGUI.EndChangeCheck())
{
m_IsFontAtlasInvalid = true;
}
// FONT ATLAS RESOLUTION SELECTION
GUILayout.BeginHorizontal();
GUI.changed = false;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PrefixLabel("Atlas Resolution");
m_AtlasWidth = EditorGUILayout.IntPopup(m_AtlasWidth, m_FontResolutionLabels, m_FontAtlasResolutions);
m_AtlasHeight = EditorGUILayout.IntPopup(m_AtlasHeight, m_FontResolutionLabels, m_FontAtlasResolutions);
if (EditorGUI.EndChangeCheck())
{
m_IsFontAtlasInvalid = true;
}
GUILayout.EndHorizontal();
// FONT CHARACTER SET SELECTION
EditorGUI.BeginChangeCheck();
bool hasSelectionChanged = false;
m_CharacterSetSelectionMode = EditorGUILayout.Popup("Character Set", m_CharacterSetSelectionMode, m_FontCharacterSets);
if (EditorGUI.EndChangeCheck())
{
m_CharacterSequence = "";
hasSelectionChanged = true;
m_IsFontAtlasInvalid = true;
}
switch (m_CharacterSetSelectionMode)
{
case 0: // ASCII
//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";
m_CharacterSequence = "32 - 126, 160, 8203, 8230, 9633";
break;
case 1: // EXTENDED ASCII
m_CharacterSequence = "32 - 126, 160 - 255, 8192 - 8303, 8364, 8482, 9633";
// Could add 9632 for missing glyph
break;
case 2: // Lowercase
m_CharacterSequence = "32 - 64, 91 - 126, 160";
break;
case 3: // Uppercase
m_CharacterSequence = "32 - 96, 123 - 126, 160";
break;
case 4: // Numbers & Symbols
m_CharacterSequence = "32 - 64, 91 - 96, 123 - 126, 160";
break;
case 5: // Custom Range
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
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.", TM_EditorStyles.label);
GUILayout.Space(10f);
EditorGUI.BeginChangeCheck();
m_ReferencedFontAsset = EditorGUILayout.ObjectField("Select Font Asset", m_ReferencedFontAsset, typeof(FontAsset), false) as FontAsset;
if (EditorGUI.EndChangeCheck() || hasSelectionChanged)
{
if (m_ReferencedFontAsset != null)
{
m_CharacterSequence = TextCoreEditorUtilities.GetDecimalCharacterSequence(FontAsset.GetCharactersArray(m_ReferencedFontAsset));
}
m_IsFontAtlasInvalid = true;
}
// Filter out unwanted characters.
char chr = Event.current.character;
if ((chr < '0' || chr > '9') && (chr < ',' || chr > '-'))
{
Event.current.character = '\0';
}
GUILayout.Label("Character Sequence (Decimal)", EditorStyles.boldLabel);
EditorGUI.BeginChangeCheck();
m_CharacterSequence = EditorGUILayout.TextArea(m_CharacterSequence, TM_EditorStyles.textAreaBoxWindow, GUILayout.Height(120), GUILayout.ExpandWidth(true));
if (EditorGUI.EndChangeCheck())
{
m_IsFontAtlasInvalid = true;
}
EditorGUILayout.EndVertical();
break;
case 6: // Unicode HEX Range
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
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.", TM_EditorStyles.label);
GUILayout.Space(10f);
EditorGUI.BeginChangeCheck();
m_ReferencedFontAsset = EditorGUILayout.ObjectField("Select Font Asset", m_ReferencedFontAsset, typeof(FontAsset), false) as FontAsset;
if (EditorGUI.EndChangeCheck() || hasSelectionChanged)
{
if (m_ReferencedFontAsset != null)
{
m_CharacterSequence = TextCoreEditorUtilities.GetUnicodeCharacterSequence(FontAsset.GetCharactersArray(m_ReferencedFontAsset));
}
m_IsFontAtlasInvalid = true;
}
// Filter out unwanted characters.
chr = Event.current.character;
if ((chr < '0' || chr > '9') && (chr < 'a' || chr > 'f') && (chr < 'A' || chr > 'F') && (chr < ',' || chr > '-'))
{
Event.current.character = '\0';
}
GUILayout.Label("Character Sequence (Hex)", EditorStyles.boldLabel);
EditorGUI.BeginChangeCheck();
m_CharacterSequence = EditorGUILayout.TextArea(m_CharacterSequence, TM_EditorStyles.textAreaBoxWindow, GUILayout.Height(120), GUILayout.ExpandWidth(true));
if (EditorGUI.EndChangeCheck())
{
m_IsFontAtlasInvalid = true;
}
EditorGUILayout.EndVertical();
break;
case 7: // Characters from Font Asset
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
GUILayout.Label("Type the characters to be included in the font asset or retrieve them from another font asset.", TM_EditorStyles.label);
GUILayout.Space(10f);
EditorGUI.BeginChangeCheck();
m_ReferencedFontAsset = EditorGUILayout.ObjectField("Select Font Asset", m_ReferencedFontAsset, typeof(FontAsset), false) as FontAsset;
if (EditorGUI.EndChangeCheck() || hasSelectionChanged)
{
if (m_ReferencedFontAsset != null)
{
m_CharacterSequence = FontAsset.GetCharacters(m_ReferencedFontAsset);
}
m_IsFontAtlasInvalid = true;
}
EditorGUI.indentLevel = 0;
GUILayout.Label("Custom Character List", EditorStyles.boldLabel);
EditorGUI.BeginChangeCheck();
m_CharacterSequence = EditorGUILayout.TextArea(m_CharacterSequence, TM_EditorStyles.textAreaBoxWindow, GUILayout.Height(120), GUILayout.ExpandWidth(true));
if (EditorGUI.EndChangeCheck())
{
m_IsFontAtlasInvalid = true;
}
EditorGUILayout.EndVertical();
break;
case 8: // Character List from File
EditorGUI.BeginChangeCheck();
m_CharactersFromFile = EditorGUILayout.ObjectField("Character File", m_CharactersFromFile, typeof(TextAsset), false) as TextAsset;
if (EditorGUI.EndChangeCheck())
{
m_IsFontAtlasInvalid = true;
}
if (m_CharactersFromFile != null)
{
Regex rx = new Regex(@"(?<!\\)(?:\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8})");
m_CharacterSequence = rx.Replace(m_CharactersFromFile.text,
match =>
{
if (match.Value.StartsWith("\\U"))
return char.ConvertFromUtf32(int.Parse(match.Value.Replace("\\U", ""), NumberStyles.HexNumber));
return char.ConvertFromUtf32(int.Parse(match.Value.Replace("\\u", ""), NumberStyles.HexNumber));
});
}
break;
}
// FONT STYLE SELECTION
//GUILayout.BeginHorizontal();
//EditorGUI.BeginChangeCheck();
////m_FontStyle = (FaceStyles)EditorGUILayout.EnumPopup("Font Style", m_FontStyle, GUILayout.Width(225));
////m_FontStyleValue = EditorGUILayout.IntField((int)m_FontStyleValue);
//if (EditorGUI.EndChangeCheck())
//{
// m_IsFontAtlasInvalid = true;
//}
//GUILayout.EndHorizontal();
// Render Mode Selection
GlyphRenderModeUI selectedUIMode = (GlyphRenderModeUI)m_GlyphRenderMode;
EditorGUI.BeginChangeCheck();
selectedUIMode = (GlyphRenderModeUI)EditorGUILayout.EnumPopup("Render Mode", selectedUIMode);
if (EditorGUI.EndChangeCheck())
{
m_GlyphRenderMode = (GlyphRenderMode)selectedUIMode;
}
m_IncludeFontFeatures = EditorGUILayout.Toggle("Get Font Features", m_IncludeFontFeatures);
EditorGUILayout.Space();
}
EditorGUI.EndDisabledGroup();
if (!string.IsNullOrEmpty(m_WarningMessage))
{
EditorGUILayout.HelpBox(m_WarningMessage, MessageType.Warning);
}
GUI.enabled = m_SourceFont != null && !m_IsProcessing && !m_IsGenerationDisabled; // Enable Preview if we are not already rendering a font.
if (GUILayout.Button("Generate Font Atlas") && GUI.enabled)
{
if (!m_IsProcessing && m_SourceFont != null)
{
DestroyImmediate(m_FontAtlasTexture);
DestroyImmediate(m_GlyphRectPreviewTexture);
m_FontAtlasTexture = null;
m_SavedFontAtlas = null;
m_OutputFeedback = string.Empty;
// Initialize font engine
FontEngineError errorCode = FontEngine.InitializeFontEngine();
if (errorCode != FontEngineError.Success)
{
Debug.Log("Font Asset Creator - Error [" + errorCode + "] has occurred while Initializing the FreeType Library.");
}
if (errorCode == FontEngineError.Success)
{
errorCode = FontEngine.LoadFontFace(m_SourceFont, 0, m_SourceFontFaceIndex);
if (errorCode != FontEngineError.Success)
{
Debug.LogWarning("Unable to load font face for [" + m_SourceFont.name + "]. Make sure \"Include Font Data\" is enabled in the Font Import Settings. You may disable it after creating the static Font Asset.", m_SourceFont);
}
}
// Define an array containing the characters we will render.
if (errorCode == FontEngineError.Success)
{
uint[] characterSet = null;
// Get list of characters that need to be packed and rendered to the atlas texture.
if (m_CharacterSetSelectionMode == 7 || m_CharacterSetSelectionMode == 8)
{
// Ensure these characters are always added
List<uint> char_List = new List<uint>()
{
9, // Space
95 // Underline
};
for (int i = 0; i < m_CharacterSequence.Length; i++)
{
uint unicode = m_CharacterSequence[i];
// Handle surrogate pairs
if (i < m_CharacterSequence.Length - 1 && char.IsHighSurrogate((char)unicode) && char.IsLowSurrogate(m_CharacterSequence[i + 1]))
{
unicode = (uint)char.ConvertToUtf32(m_CharacterSequence[i], m_CharacterSequence[i + 1]);
i += 1;
}
// Check to make sure we don't include duplicates
if (char_List.FindIndex(item => item == unicode) == -1)
char_List.Add(unicode);
}
characterSet = char_List.ToArray();
}
else if (m_CharacterSetSelectionMode == 6)
{
characterSet = ParseHexNumberSequence(m_CharacterSequence);
}
else
{
characterSet = ParseNumberSequence(m_CharacterSequence);
}
m_CharacterCount = characterSet.Length;
m_AtlasGenerationProgress = 0;
m_IsProcessing = true;
m_IsGenerationCancelled = false;
GlyphLoadFlags glyphLoadFlags = ((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_HINTED) == GlyphRasterModes.RASTER_MODE_HINTED
? GlyphLoadFlags.LOAD_RENDER
: GlyphLoadFlags.LOAD_RENDER | GlyphLoadFlags.LOAD_NO_HINTING;
glyphLoadFlags = ((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_MONO) == GlyphRasterModes.RASTER_MODE_MONO
? glyphLoadFlags | GlyphLoadFlags.LOAD_MONOCHROME
: glyphLoadFlags;
glyphLoadFlags = ((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_COLOR) == GlyphRasterModes.RASTER_MODE_COLOR
? glyphLoadFlags | GlyphLoadFlags.LOAD_COLOR
: glyphLoadFlags;
//
AutoResetEvent autoEvent = new AutoResetEvent(false);
// Worker thread to pack glyphs in the given texture space.
ThreadPool.QueueUserWorkItem(PackGlyphs =>
{
// Start Stop Watch
m_StopWatch = System.Diagnostics.Stopwatch.StartNew();
// Clear the various lists used in the generation process.
m_AvailableGlyphsToAdd.Clear();
m_MissingCharacters.Clear();
m_ExcludedCharacters.Clear();
m_CharacterLookupMap.Clear();
m_GlyphLookupMap.Clear();
m_GlyphsToPack.Clear();
m_GlyphsPacked.Clear();
// Check if requested characters are available in the source font file.
for (int i = 0; i < characterSet.Length; i++)
{
uint unicode = characterSet[i];
uint glyphIndex;
if (FontEngine.TryGetGlyphIndex(unicode, out glyphIndex))
{
// Skip over potential duplicate characters.
if (m_CharacterLookupMap.ContainsKey(unicode))
continue;
// Add character to character lookup map.
m_CharacterLookupMap.Add(unicode, glyphIndex);
// Skip over potential duplicate glyph references.
if (m_GlyphLookupMap.ContainsKey(glyphIndex))
{
// Add additional glyph reference for this character.
m_GlyphLookupMap[glyphIndex].Add(unicode);
continue;
}
// Add glyph reference to glyph lookup map.
m_GlyphLookupMap.Add(glyphIndex, new List<uint>() { unicode });
// Add glyph index to list of glyphs to add to texture.
m_AvailableGlyphsToAdd.Add(glyphIndex);
}
else
{
// Add Unicode to list of missing characters.
m_MissingCharacters.Add(unicode);
}
}
// Pack available glyphs in the provided texture space.
if (m_AvailableGlyphsToAdd.Count > 0)
{
int packingModifier = ((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP ? 0 : 1;
if (m_PointSizeSamplingMode == 0) // Auto-Sizing Point Size Mode
{
// Estimate min / max range for auto sizing of point size.
int minPointSize = 0;
int maxPointSize = (int)Mathf.Sqrt((m_AtlasWidth * m_AtlasHeight) / m_AvailableGlyphsToAdd.Count) * 3;
m_PointSize = (maxPointSize + minPointSize) / 2;
bool optimumPointSizeFound = false;
for (int iteration = 0; iteration < 15 && optimumPointSizeFound == false && m_PointSize > 0; iteration++)
{
m_AtlasGenerationProgressLabel = "Packing glyphs - Pass (" + iteration + ")";
FontEngine.SetFaceSize(m_PointSize);
m_Padding = (int)(m_PaddingMode == PaddingMode.Percentage ? m_PointSize * m_PaddingFieldValue / 100f : m_PaddingFieldValue);
m_GlyphsToPack.Clear();
m_GlyphsPacked.Clear();
m_FreeGlyphRects.Clear();
m_FreeGlyphRects.Add(new GlyphRect(0, 0, m_AtlasWidth - packingModifier, m_AtlasHeight - packingModifier));
m_UsedGlyphRects.Clear();
for (int i = 0; i < m_AvailableGlyphsToAdd.Count; i++)
{
uint glyphIndex = m_AvailableGlyphsToAdd[i];
Glyph glyph;
if (FontEngine.TryGetGlyphWithIndexValue(glyphIndex, glyphLoadFlags, out glyph))
{
if (glyph.glyphRect.width > 0 && glyph.glyphRect.height > 0)
{
m_GlyphsToPack.Add(glyph);
}
else
{
m_GlyphsPacked.Add(glyph);
}
}
}
FontEngine.TryPackGlyphsInAtlas(m_GlyphsToPack, m_GlyphsPacked, m_Padding, (GlyphPackingMode)m_PackingMode, m_GlyphRenderMode, m_AtlasWidth, m_AtlasHeight, m_FreeGlyphRects, m_UsedGlyphRects);
if (m_IsGenerationCancelled)
{
DestroyImmediate(m_FontAtlasTexture);
m_FontAtlasTexture = null;
return;
}
//Debug.Log("Glyphs remaining to add [" + m_GlyphsToAdd.Count + "]. Glyphs added [" + m_GlyphsAdded.Count + "].");
if (m_GlyphsToPack.Count > 0)
{
if (m_PointSize > minPointSize)
{
maxPointSize = m_PointSize;
m_PointSize = (m_PointSize + minPointSize) / 2;
//Debug.Log("Decreasing point size from [" + maxPointSize + "] to [" + m_PointSize + "].");
}
}
else
{
if (maxPointSize - minPointSize > 1 && m_PointSize < maxPointSize)
{
minPointSize = m_PointSize;
m_PointSize = (m_PointSize + maxPointSize) / 2;
//Debug.Log("Increasing point size from [" + minPointSize + "] to [" + m_PointSize + "].");
}
else
{
//Debug.Log("[" + iteration + "] iterations to find the optimum point size of : [" + m_PointSize + "].");
optimumPointSizeFound = true;
}
}
}
}
else // Custom Point Size Mode
{
m_AtlasGenerationProgressLabel = "Packing glyphs...";
// Set point size
FontEngine.SetFaceSize(m_PointSize);
m_Padding = (int)(m_PaddingMode == PaddingMode.Percentage ? m_PointSize * m_PaddingFieldValue / 100 : m_PaddingFieldValue);
m_GlyphsToPack.Clear();
m_GlyphsPacked.Clear();
m_FreeGlyphRects.Clear();
m_FreeGlyphRects.Add(new GlyphRect(0, 0, m_AtlasWidth - packingModifier, m_AtlasHeight - packingModifier));
m_UsedGlyphRects.Clear();
for (int i = 0; i < m_AvailableGlyphsToAdd.Count; i++)
{
uint glyphIndex = m_AvailableGlyphsToAdd[i];
Glyph glyph;
if (FontEngine.TryGetGlyphWithIndexValue(glyphIndex, glyphLoadFlags, out glyph))
{
if (glyph.glyphRect.width > 0 && glyph.glyphRect.height > 0)
{
m_GlyphsToPack.Add(glyph);
}
else
{
m_GlyphsPacked.Add(glyph);
}
}
}
FontEngine.TryPackGlyphsInAtlas(m_GlyphsToPack, m_GlyphsPacked, m_Padding, (GlyphPackingMode)m_PackingMode, m_GlyphRenderMode, m_AtlasWidth, m_AtlasHeight, m_FreeGlyphRects, m_UsedGlyphRects);
if (m_IsGenerationCancelled)
{
DestroyImmediate(m_FontAtlasTexture);
m_FontAtlasTexture = null;
return;
}
//Debug.Log("Glyphs remaining to add [" + m_GlyphsToAdd.Count + "]. Glyphs added [" + m_GlyphsAdded.Count + "].");
}
}
else
{
int packingModifier = ((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP ? 0 : 1;
FontEngine.SetFaceSize(m_PointSize);
m_Padding = (int)(m_PaddingMode == PaddingMode.Percentage ? m_PointSize * m_PaddingFieldValue / 100 : m_PaddingFieldValue);
m_GlyphsToPack.Clear();
m_GlyphsPacked.Clear();
m_FreeGlyphRects.Clear();
m_FreeGlyphRects.Add(new GlyphRect(0, 0, m_AtlasWidth - packingModifier, m_AtlasHeight - packingModifier));
m_UsedGlyphRects.Clear();
}
//Stop StopWatch
m_StopWatch.Stop();