-
Notifications
You must be signed in to change notification settings - Fork 319
Expand file tree
/
Copy pathTextMeshProUGUI.cs
More file actions
5630 lines (4555 loc) · 279 KB
/
TextMeshProUGUI.cs
File metadata and controls
5630 lines (4555 loc) · 279 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
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UI;
using System.Collections.Generic;
using Unity.Profiling;
using UnityEngine.TextCore;
using UnityEngine.TextCore.LowLevel;
using Object = UnityEngine.Object;
#pragma warning disable 0414 // Disabled a few warnings related to serialized variables not used in this script but used in the editor.
#pragma warning disable 0618 // Disabled warning due to SetVertices being deprecated until new release with SetMesh() is available.
namespace TMPro
{
[DisallowMultipleComponent]
[RequireComponent(typeof(RectTransform))]
[RequireComponent(typeof(CanvasRenderer))]
[AddComponentMenu("UI/TextMeshPro - Text (UI)", 11)]
[ExecuteAlways]
#if UNITY_2023_2_OR_NEWER
[HelpURL("https://docs.unity3d.com/Packages/com.unity.ugui@2.0/manual/TextMeshPro/index.html")]
#else
[HelpURL("https://docs.unity3d.com/Packages/com.unity.textmeshpro@3.2")]
#endif
public class TextMeshProUGUI : TMP_Text, ILayoutElement
{
/// <summary>
/// Get the material that will be used for rendering.
/// </summary>
public override Material materialForRendering
{
get { return TMP_MaterialManager.GetMaterialForRendering(this, m_sharedMaterial); }
}
/// <summary>
/// Determines if the size of the text container will be adjusted to fit the text object when it is first created.
/// </summary>
public override bool autoSizeTextContainer
{
get { return m_autoSizeTextContainer; }
set { if (m_autoSizeTextContainer == value) return; m_autoSizeTextContainer = value; if (m_autoSizeTextContainer) { CanvasUpdateRegistry.RegisterCanvasElementForLayoutRebuild(this); SetLayoutDirty(); } }
}
/// <summary>
/// Reference to the Mesh used by the text object.
/// </summary>
public override Mesh mesh
{
get { return m_mesh; }
}
/// <summary>
/// Reference to the CanvasRenderer used by the text object.
/// </summary>
public new CanvasRenderer canvasRenderer
{
get
{
if (m_canvasRenderer == null) m_canvasRenderer = GetComponent<CanvasRenderer>();
return m_canvasRenderer;
}
}
/// <summary>
/// Anchor dampening prevents the anchor position from being adjusted unless the positional change exceeds about 40% of the width of the underline character. This essentially stabilizes the anchor position.
/// </summary>
//public bool anchorDampening
//{
// get { return m_anchorDampening; }
// set { if (m_anchorDampening != value) { havePropertiesChanged = true; m_anchorDampening = value; /* ScheduleUpdate(); */ } }
//}
#if !UNITY_2019_3_OR_NEWER
[SerializeField]
private bool m_Maskable = true;
#endif
private bool m_isRebuildingLayout = false;
private Coroutine m_DelayedGraphicRebuild;
private Coroutine m_DelayedMaterialRebuild;
/// <summary>
/// Function called by Unity when the horizontal layout needs to be recalculated.
/// </summary>
public void CalculateLayoutInputHorizontal()
{
//Debug.Log("*** CalculateLayoutHorizontal() on Object ID: " + GetInstanceID() + " at frame: " + Time.frameCount + "***");
}
/// <summary>
/// Function called by Unity when the vertical layout needs to be recalculated.
/// </summary>
public void CalculateLayoutInputVertical()
{
//Debug.Log("*** CalculateLayoutInputVertical() on Object ID: " + GetInstanceID() + " at frame: " + Time.frameCount + "***");
}
public override void SetVerticesDirty()
{
if (this == null || !this.IsActive())
return;
if (CanvasUpdateRegistry.IsRebuildingGraphics())
return;
CanvasUpdateRegistry.RegisterCanvasElementForGraphicRebuild(this);
if (m_OnDirtyVertsCallback != null)
m_OnDirtyVertsCallback();
}
/// <summary>
///
/// </summary>
public override void SetLayoutDirty()
{
m_isPreferredWidthDirty = true;
m_isPreferredHeightDirty = true;
if (this == null || !this.IsActive())
return;
LayoutRebuilder.MarkLayoutForRebuild(this.rectTransform);
m_isLayoutDirty = true;
if (m_OnDirtyLayoutCallback != null)
m_OnDirtyLayoutCallback();
}
/// <summary>
///
/// </summary>
public override void SetMaterialDirty()
{
if (this == null || !this.IsActive())
return;
if (CanvasUpdateRegistry.IsRebuildingGraphics())
return;
m_isMaterialDirty = true;
CanvasUpdateRegistry.RegisterCanvasElementForGraphicRebuild(this);
if (m_OnDirtyMaterialCallback != null)
m_OnDirtyMaterialCallback();
}
/// <summary>
///
/// </summary>
public override void SetAllDirty()
{
SetLayoutDirty();
SetVerticesDirty();
SetMaterialDirty();
}
/// <summary>
/// Delay registration of text object for graphic rebuild by one frame.
/// </summary>
/// <returns></returns>
IEnumerator DelayedGraphicRebuild()
{
yield return null;
CanvasUpdateRegistry.RegisterCanvasElementForGraphicRebuild(this);
if (m_OnDirtyVertsCallback != null)
m_OnDirtyVertsCallback();
m_DelayedGraphicRebuild = null;
}
/// <summary>
/// Delay registration of text object for graphic rebuild by one frame.
/// </summary>
/// <returns></returns>
IEnumerator DelayedMaterialRebuild()
{
yield return null;
m_isMaterialDirty = true;
CanvasUpdateRegistry.RegisterCanvasElementForGraphicRebuild(this);
if (m_OnDirtyMaterialCallback != null)
m_OnDirtyMaterialCallback();
m_DelayedMaterialRebuild = null;
}
/// <summary>
///
/// </summary>
/// <param name="update"></param>
public override void Rebuild(CanvasUpdate update)
{
if (this == null) return;
if (update == CanvasUpdate.Prelayout)
{
if (m_autoSizeTextContainer)
{
m_rectTransform.sizeDelta = GetPreferredValues(Mathf.Infinity, Mathf.Infinity);
}
}
else if (update == CanvasUpdate.PreRender)
{
OnPreRenderCanvas();
if (!m_isMaterialDirty) return;
UpdateMaterial();
m_isMaterialDirty = false;
}
}
/// <summary>
/// Method to keep the pivot of the sub text objects in sync with the parent pivot.
/// </summary>
private void UpdateSubObjectPivot()
{
if (m_textInfo == null) return;
for (int i = 1; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
{
m_subTextObjects[i].SetPivotDirty();
}
//m_isPivotDirty = false;
}
/// <summary>
///
/// </summary>
/// <param name="baseMaterial"></param>
/// <returns></returns>
public override Material GetModifiedMaterial(Material baseMaterial)
{
Material mat = baseMaterial;
if (m_ShouldRecalculateStencil)
{
var rootCanvas = MaskUtilities.FindRootSortOverrideCanvas(transform);
m_StencilValue = maskable ? MaskUtilities.GetStencilDepth(transform, rootCanvas) : 0;
m_ShouldRecalculateStencil = false;
}
if (m_StencilValue > 0)
{
var maskMat = StencilMaterial.Add(mat, (1 << m_StencilValue) - 1, StencilOp.Keep, CompareFunction.Equal, ColorWriteMask.All, (1 << m_StencilValue) - 1, 0);
StencilMaterial.Remove(m_MaskMaterial);
m_MaskMaterial = maskMat;
mat = m_MaskMaterial;
}
return mat;
}
/// <summary>
///
/// </summary>
protected override void UpdateMaterial()
{
//Debug.Log("*** UpdateMaterial() ***");
//if (!this.IsActive())
// return;
if (m_sharedMaterial == null || canvasRenderer == null) return;
m_canvasRenderer.materialCount = 1;
m_canvasRenderer.SetMaterial(materialForRendering, 0);
//m_canvasRenderer.SetTexture(materialForRendering.mainTexture);
}
//public override void OnRebuildRequested()
//{
// //Debug.Log("OnRebuildRequested");
// base.OnRebuildRequested();
//}
//public override bool Raycast(Vector2 sp, Camera eventCamera)
//{
// //Debug.Log("Raycast Event. ScreenPoint: " + sp);
// return base.Raycast(sp, eventCamera);
//}
// MASKING RELATED PROPERTIES
/// <summary>
/// Sets the masking offset from the bounds of the object
/// </summary>
public Vector4 maskOffset
{
get { return m_maskOffset; }
set { m_maskOffset = value; UpdateMask(); m_havePropertiesChanged = true; }
}
//public override Material defaultMaterial
//{
// get { Debug.Log("Default Material called."); return m_sharedMaterial; }
//}
//protected override void OnCanvasHierarchyChanged()
//{
// //Debug.Log("OnCanvasHierarchyChanged...");
//}
// IClippable implementation
/// <summary>
/// Method called when the state of a parent changes.
/// </summary>
public override void RecalculateClipping()
{
//Debug.Log("***** RecalculateClipping() *****");
base.RecalculateClipping();
}
// IMaskable Implementation
/// <summary>
/// Method called when Stencil Mask needs to be updated on this element and parents.
/// </summary>
// public override void RecalculateMasking()
// {
// //Debug.Log("***** RecalculateMasking() *****");
//
// this.m_ShouldRecalculateStencil = true;
// SetMaterialDirty();
// }
//public override void SetClipRect(Rect clipRect, bool validRect)
//{
// //Debug.Log("***** SetClipRect (" + clipRect + ", " + validRect + ") *****");
// base.SetClipRect(clipRect, validRect);
//}
/// <summary>
/// Override of the Cull function to provide for the ability to override the culling of the text object.
/// </summary>
/// <param name="clipRect"></param>
/// <param name="validRect"></param>
public override void Cull(Rect clipRect, bool validRect)
{
m_ShouldUpdateCulling = false;
// Delay culling check in the event the text layout is dirty and geometry has to be updated.
if (m_isLayoutDirty)
{
m_ShouldUpdateCulling = true;
m_ClipRect = clipRect;
m_ValidRect = validRect;
return;
}
// Get compound rect for the text object and sub text objects in local canvas space.
Rect rect = GetCanvasSpaceClippingRect();
// No point culling if geometry bounds have no width or height.
//if (rect.width == 0 || rect.height == 0)
// return;
var cull = !validRect || !clipRect.Overlaps(rect, true);
if (m_canvasRenderer.cull != cull)
{
m_canvasRenderer.cull = cull;
onCullStateChanged.Invoke(cull);
OnCullingChanged();
// Update any potential sub mesh objects
for (int i = 1; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
{
m_subTextObjects[i].canvasRenderer.cull = cull;
}
}
}
private bool m_ShouldUpdateCulling;
private Rect m_ClipRect;
private bool m_ValidRect;
/// <summary>
/// Internal function to allow delay of culling until the text geometry has been updated.
/// </summary>
internal override void UpdateCulling()
{
// Get compound rect for the text object and sub text objects in local canvas space.
Rect rect = GetCanvasSpaceClippingRect();
// No point culling if geometry bounds have no width or height.
//if (rect.width == 0 || rect.height == 0)
// return;
var cull = !m_ValidRect || !m_ClipRect.Overlaps(rect, true);
if (m_canvasRenderer.cull != cull)
{
m_canvasRenderer.cull = cull;
onCullStateChanged.Invoke(cull);
OnCullingChanged();
// Update any potential sub mesh objects
for (int i = 1; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
{
m_subTextObjects[i].canvasRenderer.cull = cull;
}
}
m_ShouldUpdateCulling = false;
}
/*
/// <summary>
/// Sets the mask type
/// </summary>
public MaskingTypes mask
{
get { return m_mask; }
set { m_mask = value; havePropertiesChanged = true; isMaskUpdateRequired = true; }
}
/// <summary>
/// Set the masking offset mode (as percentage or pixels)
/// </summary>
public MaskingOffsetMode maskOffsetMode
{
get { return m_maskOffsetMode; }
set { m_maskOffsetMode = value; havePropertiesChanged = true; isMaskUpdateRequired = true; }
}
*/
/*
/// <summary>
/// Sets the softness of the mask
/// </summary>
public Vector2 maskSoftness
{
get { return m_maskSoftness; }
set { m_maskSoftness = value; havePropertiesChanged = true; isMaskUpdateRequired = true; }
}
/// <summary>
/// Allows to move / offset the mesh vertices by a set amount
/// </summary>
public Vector2 vertexOffset
{
get { return m_vertexOffset; }
set { m_vertexOffset = value; havePropertiesChanged = true; isMaskUpdateRequired = true; }
}
*/
/// <summary>
/// Function to be used to force recomputing of character padding when Shader / Material properties have been changed via script.
/// </summary>
public override void UpdateMeshPadding()
{
m_padding = ShaderUtilities.GetPadding(m_sharedMaterial, m_enableExtraPadding, m_isUsingBold);
m_isMaskingEnabled = ShaderUtilities.IsMaskingEnabled(m_sharedMaterial);
m_havePropertiesChanged = true;
checkPaddingRequired = false;
// Return if text object is not awake yet.
if (m_textInfo == null) return;
// Update sub text objects
for (int i = 1; i < m_textInfo.materialCount; i++)
m_subTextObjects[i].UpdateMeshPadding(m_enableExtraPadding, m_isUsingBold);
}
/// <summary>
/// Tweens the CanvasRenderer color associated with this Graphic.
/// </summary>
/// <param name="targetColor">Target color.</param>
/// <param name="duration">Tween duration.</param>
/// <param name="ignoreTimeScale">Should ignore Time.scale?</param>
/// <param name="useAlpha">Should also Tween the alpha channel?</param>
protected override void InternalCrossFadeColor(Color targetColor, float duration, bool ignoreTimeScale, bool useAlpha)
{
if (m_textInfo == null)
return;
int materialCount = m_textInfo.materialCount;
for (int i = 1; i < materialCount; i++)
{
m_subTextObjects[i].CrossFadeColor(targetColor, duration, ignoreTimeScale, useAlpha);
}
}
/// <summary>
/// Tweens the alpha of the CanvasRenderer color associated with this Graphic.
/// </summary>
/// <param name="alpha">Target alpha.</param>
/// <param name="duration">Duration of the tween in seconds.</param>
/// <param name="ignoreTimeScale">Should ignore Time.scale?</param>
protected override void InternalCrossFadeAlpha(float alpha, float duration, bool ignoreTimeScale)
{
if (m_textInfo == null)
return;
int materialCount = m_textInfo.materialCount;
for (int i = 1; i < materialCount; i++)
{
m_subTextObjects[i].CrossFadeAlpha(alpha, duration, ignoreTimeScale);
}
}
/// <summary>
/// Function to force regeneration of the text object before its normal process time. This is useful when changes to the text object properties need to be applied immediately.
/// </summary>
/// <param name="ignoreActiveState">Ignore Active State of text objects. Inactive objects are ignored by default.</param>
/// <param name="forceTextReparsing">Force re-parsing of the text.</param>
public override void ForceMeshUpdate(bool ignoreActiveState = false, bool forceTextReparsing = false)
{
m_havePropertiesChanged = true;
m_ignoreActiveState = ignoreActiveState;
// Special handling in the event the Canvas is only disabled
if (m_canvas == null)
m_canvas = GetComponentInParent<Canvas>();
OnPreRenderCanvas();
}
/// <summary>
/// Function used to evaluate the length of a text string.
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public override TMP_TextInfo GetTextInfo(string text)
{
SetText(text);
SetArraySizes(m_TextProcessingArray);
m_renderMode = TextRenderFlags.DontRender;
ComputeMarginSize();
// Need to make sure we have a valid reference to a Canvas.
if (m_canvas == null) m_canvas = this.canvas;
GenerateTextMesh();
m_renderMode = TextRenderFlags.Render;
return this.textInfo;
}
/// <summary>
/// Function to clear the geometry of the Primary and Sub Text objects.
/// </summary>
public override void ClearMesh()
{
m_canvasRenderer.SetMesh(null);
for (int i = 1; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
m_subTextObjects[i].canvasRenderer.SetMesh(null);
}
/// <summary>
/// Event to allow users to modify the content of the text info before the text is rendered.
/// </summary>
public override event Action<TMP_TextInfo> OnPreRenderText;
/// <summary>
/// Function to update the geometry of the main and sub text objects.
/// </summary>
/// <param name="mesh"></param>
/// <param name="index"></param>
public override void UpdateGeometry(Mesh mesh, int index)
{
mesh.RecalculateBounds();
if (index == 0)
{
m_canvasRenderer.SetMesh(mesh);
}
else
{
m_subTextObjects[index].canvasRenderer.SetMesh(mesh);
}
}
/// <summary>
/// Function to upload the updated vertex data and renderer.
/// </summary>
public override void UpdateVertexData(TMP_VertexDataUpdateFlags flags)
{
int materialCount = m_textInfo.materialCount;
for (int i = 0; i < materialCount; i++)
{
Mesh mesh;
if (i == 0)
mesh = m_mesh;
else
{
// Clear unused vertices
// TODO: Causes issues when sorting geometry as last vertex data attribute get wiped out.
//m_textInfo.meshInfo[i].ClearUnusedVertices();
mesh = m_subTextObjects[i].mesh;
}
if ((flags & TMP_VertexDataUpdateFlags.Vertices) == TMP_VertexDataUpdateFlags.Vertices)
mesh.vertices = m_textInfo.meshInfo[i].vertices;
if ((flags & TMP_VertexDataUpdateFlags.Uv0) == TMP_VertexDataUpdateFlags.Uv0)
mesh.SetUVs(0, m_textInfo.meshInfo[i].uvs0);
if ((flags & TMP_VertexDataUpdateFlags.Uv2) == TMP_VertexDataUpdateFlags.Uv2)
mesh.uv2 = m_textInfo.meshInfo[i].uvs2;
//if ((flags & TMP_VertexDataUpdateFlags.Uv4) == TMP_VertexDataUpdateFlags.Uv4)
// mesh.uv4 = m_textInfo.meshInfo[i].uvs4;
if ((flags & TMP_VertexDataUpdateFlags.Colors32) == TMP_VertexDataUpdateFlags.Colors32)
mesh.colors32 = m_textInfo.meshInfo[i].colors32;
mesh.RecalculateBounds();
if (i == 0)
m_canvasRenderer.SetMesh(mesh);
else
m_subTextObjects[i].canvasRenderer.SetMesh(mesh);
}
}
/// <summary>
/// Function to upload the updated vertex data and renderer.
/// </summary>
public override void UpdateVertexData()
{
int materialCount = m_textInfo.materialCount;
for (int i = 0; i < materialCount; i++)
{
Mesh mesh;
if (i == 0)
mesh = m_mesh;
else
{
// Clear unused vertices
m_textInfo.meshInfo[i].ClearUnusedVertices();
mesh = m_subTextObjects[i].mesh;
}
//mesh.MarkDynamic();
mesh.vertices = m_textInfo.meshInfo[i].vertices;
mesh.SetUVs(0, m_textInfo.meshInfo[i].uvs0);
mesh.uv2 = m_textInfo.meshInfo[i].uvs2;
//mesh.uv4 = m_textInfo.meshInfo[i].uvs4;
mesh.colors32 = m_textInfo.meshInfo[i].colors32;
mesh.RecalculateBounds();
if (i == 0)
m_canvasRenderer.SetMesh(mesh);
else
m_subTextObjects[i].canvasRenderer.SetMesh(mesh);
}
}
public void UpdateFontAsset()
{
LoadFontAsset();
}
#region TMPro_UGUI_Private
[SerializeField]
private bool m_hasFontAssetChanged = false; // Used to track when font properties have changed.
protected TMP_SubMeshUI[] m_subTextObjects = new TMP_SubMeshUI[8];
private float m_previousLossyScaleY = -1; // Used for Tracking lossy scale changes in the transform;
private Vector3[] m_RectTransformCorners = new Vector3[4];
private CanvasRenderer m_canvasRenderer;
private Canvas m_canvas;
private float m_CanvasScaleFactor;
private bool m_isFirstAllocation; // Flag to determine if this is the first allocation of the buffers.
private int m_max_characters = 8; // Determines the initial allocation and size of the character array / buffer.
//private int m_max_numberOfLines = 4; // Determines the initial allocation and maximum number of lines of text.
// MASKING RELATED PROPERTIES
// This property is now obsolete and used for compatibility with previous releases (prior to release 0.1.54).
[SerializeField]
private Material m_baseMaterial;
private bool m_isScrollRegionSet;
//private Mask m_mask;
[SerializeField]
private Vector4 m_maskOffset;
// Matrix used to animated Env Map
private Matrix4x4 m_EnvMapMatrix = new Matrix4x4();
//private bool m_isEnabled;
[NonSerialized]
private bool m_isRegisteredForEvents;
// Profiler Marker declarations
private static ProfilerMarker k_GenerateTextMarker = new ProfilerMarker("TMP.GenerateText");
private static ProfilerMarker k_SetArraySizesMarker = new ProfilerMarker("TMP.SetArraySizes");
private static ProfilerMarker k_GenerateTextPhaseIMarker = new ProfilerMarker("TMP GenerateText - Phase I");
private static ProfilerMarker k_ParseMarkupTextMarker = new ProfilerMarker("TMP Parse Markup Text");
private static ProfilerMarker k_CharacterLookupMarker = new ProfilerMarker("TMP Lookup Character & Glyph Data");
private static ProfilerMarker k_HandleGPOSFeaturesMarker = new ProfilerMarker("TMP Handle GPOS Features");
private static ProfilerMarker k_CalculateVerticesPositionMarker = new ProfilerMarker("TMP Calculate Vertices Position");
private static ProfilerMarker k_ComputeTextMetricsMarker = new ProfilerMarker("TMP Compute Text Metrics");
private static ProfilerMarker k_HandleVisibleCharacterMarker = new ProfilerMarker("TMP Handle Visible Character");
private static ProfilerMarker k_HandleWhiteSpacesMarker = new ProfilerMarker("TMP Handle White Space & Control Character");
private static ProfilerMarker k_HandleHorizontalLineBreakingMarker = new ProfilerMarker("TMP Handle Horizontal Line Breaking");
private static ProfilerMarker k_HandleVerticalLineBreakingMarker = new ProfilerMarker("TMP Handle Vertical Line Breaking");
private static ProfilerMarker k_SaveGlyphVertexDataMarker = new ProfilerMarker("TMP Save Glyph Vertex Data");
private static ProfilerMarker k_ComputeCharacterAdvanceMarker = new ProfilerMarker("TMP Compute Character Advance");
private static ProfilerMarker k_HandleCarriageReturnMarker = new ProfilerMarker("TMP Handle Carriage Return");
private static ProfilerMarker k_HandleLineTerminationMarker = new ProfilerMarker("TMP Handle Line Termination");
private static ProfilerMarker k_SavePageInfoMarker = new ProfilerMarker("TMP Save Page Info");
private static ProfilerMarker k_SaveTextExtentMarker = new ProfilerMarker("TMP Save Text Extent");
private static ProfilerMarker k_SaveProcessingStatesMarker = new ProfilerMarker("TMP Save Processing States");
private static ProfilerMarker k_GenerateTextPhaseIIMarker = new ProfilerMarker("TMP GenerateText - Phase II");
private static ProfilerMarker k_GenerateTextPhaseIIIMarker = new ProfilerMarker("TMP GenerateText - Phase III");
protected override void Awake()
{
//Debug.Log("***** Awake() called on object ID " + GetInstanceID() + ". *****");
#if UNITY_EDITOR
// Special handling for TMP Settings and importing Essential Resources
if (TMP_Settings.instance == null)
{
if (m_isWaitingOnResourceLoad == false)
TMPro_EventManager.RESOURCE_LOAD_EVENT.Add(ON_RESOURCES_LOADED);
m_isWaitingOnResourceLoad = true;
return;
}
#endif
// Cache Reference to the Canvas
m_canvas = this.canvas;
m_isOrthographic = true;
// Cache Reference to RectTransform.
m_rectTransform = gameObject.GetComponent<RectTransform>();
if (m_rectTransform == null)
m_rectTransform = gameObject.AddComponent<RectTransform>();
// Cache a reference to the CanvasRenderer.
m_canvasRenderer = GetComponent<CanvasRenderer>();
if (m_canvasRenderer == null)
m_canvasRenderer = gameObject.AddComponent<CanvasRenderer> ();
if (m_mesh == null)
{
m_mesh = new Mesh();
m_mesh.hideFlags = HideFlags.HideAndDontSave;
#if DEVELOPMENT_BUILD || UNITY_EDITOR
m_mesh.name = "TextMeshPro UI Mesh";
#endif
// Create new TextInfo for the text object.
m_textInfo = new TMP_TextInfo(this);
}
// Load TMP Settings for new text object instances.
LoadDefaultSettings();
#if UNITY_EDITOR
// We don't want to call LoadFontAsset when building the game since it causes some characters to be added to the atlas, making the build bigger.
if (!UnityEditor.BuildPipeline.isBuildingPlayer)
#endif
// Load the font asset and assign material to renderer.
LoadFontAsset();
// Allocate our initial buffers.
if (m_TextProcessingArray == null)
m_TextProcessingArray = new TextProcessingElement[m_max_characters];
m_cached_TextElement = new TMP_Character();
m_isFirstAllocation = true;
// Set flags to ensure our text is parsed and redrawn.
m_havePropertiesChanged = true;
m_isAwake = true;
}
protected override void OnEnable()
{
//Debug.Log("***** OnEnable() called on object ID " + GetInstanceID() + ". *****");
// Return if Awake() has not been called on the text object.
if (m_isAwake == false)
return;
if (!m_isRegisteredForEvents)
{
//Debug.Log("Registering for Events.");
#if UNITY_EDITOR
// Register Callbacks for various events.
TMPro_EventManager.MATERIAL_PROPERTY_EVENT.Add(ON_MATERIAL_PROPERTY_CHANGED);
TMPro_EventManager.FONT_PROPERTY_EVENT.Add(ON_FONT_PROPERTY_CHANGED);
TMPro_EventManager.TEXTMESHPRO_UGUI_PROPERTY_EVENT.Add(ON_TEXTMESHPRO_UGUI_PROPERTY_CHANGED);
TMPro_EventManager.DRAG_AND_DROP_MATERIAL_EVENT.Add(ON_DRAG_AND_DROP_MATERIAL);
TMPro_EventManager.TEXT_STYLE_PROPERTY_EVENT.Add(ON_TEXT_STYLE_CHANGED);
TMPro_EventManager.COLOR_GRADIENT_PROPERTY_EVENT.Add(ON_COLOR_GRADIENT_CHANGED);
TMPro_EventManager.TMP_SETTINGS_PROPERTY_EVENT.Add(ON_TMP_SETTINGS_CHANGED);
UnityEditor.PrefabUtility.prefabInstanceUpdated += OnPrefabInstanceUpdate;
#endif
m_isRegisteredForEvents = true;
}
// Cache Reference to the Canvas
m_canvas = GetCanvas();
SetActiveSubMeshes(true);
// Register Graphic Component to receive event triggers
GraphicRegistry.RegisterGraphicForCanvas(m_canvas, this);
// Register text object for internal updates
if (m_IsTextObjectScaleStatic == false)
TMP_UpdateManager.RegisterTextObjectForUpdate(this);
ComputeMarginSize();
SetAllDirty();
RecalculateClipping();
RecalculateMasking();
}
protected override void OnDisable()
{
//Debug.Log("***** OnDisable() called on object ID " + GetInstanceID() + ". *****");
// Return if Awake() has not been called on the text object.
if (m_isAwake == false)
return;
//if (m_MaskMaterial != null)
//{
// TMP_MaterialManager.ReleaseStencilMaterial(m_MaskMaterial);
// m_MaskMaterial = null;
//}
// UnRegister Graphic Component
GraphicRegistry.UnregisterGraphicForCanvas(m_canvas, this);
CanvasUpdateRegistry.UnRegisterCanvasElementForRebuild((ICanvasElement)this);
TMP_UpdateManager.UnRegisterTextObjectForUpdate(this);
if (m_canvasRenderer != null)
m_canvasRenderer.Clear();
SetActiveSubMeshes(false);
LayoutRebuilder.MarkLayoutForRebuild(m_rectTransform);
RecalculateClipping();
RecalculateMasking();
}
protected override void OnDestroy()
{
//Debug.Log("***** OnDestroy() called on object ID " + GetInstanceID() + ". *****");
// UnRegister Graphic Component
GraphicRegistry.UnregisterGraphicForCanvas(m_canvas, this);
TMP_UpdateManager.UnRegisterTextObjectForUpdate(this);
// Clean up remaining mesh
if (m_mesh != null)
DestroyImmediate(m_mesh);
// Clean up mask material
if (m_MaskMaterial != null)
{
TMP_MaterialManager.ReleaseStencilMaterial(m_MaskMaterial);
m_MaskMaterial = null;
}
#if UNITY_EDITOR
// Unregister the event this object was listening to
TMPro_EventManager.MATERIAL_PROPERTY_EVENT.Remove(ON_MATERIAL_PROPERTY_CHANGED);
TMPro_EventManager.FONT_PROPERTY_EVENT.Remove(ON_FONT_PROPERTY_CHANGED);
TMPro_EventManager.TEXTMESHPRO_UGUI_PROPERTY_EVENT.Remove(ON_TEXTMESHPRO_UGUI_PROPERTY_CHANGED);
TMPro_EventManager.DRAG_AND_DROP_MATERIAL_EVENT.Remove(ON_DRAG_AND_DROP_MATERIAL);
TMPro_EventManager.TEXT_STYLE_PROPERTY_EVENT.Remove(ON_TEXT_STYLE_CHANGED);
TMPro_EventManager.COLOR_GRADIENT_PROPERTY_EVENT.Remove(ON_COLOR_GRADIENT_CHANGED);
TMPro_EventManager.TMP_SETTINGS_PROPERTY_EVENT.Remove(ON_TMP_SETTINGS_CHANGED);
TMPro_EventManager.RESOURCE_LOAD_EVENT.Remove(ON_RESOURCES_LOADED);
UnityEditor.PrefabUtility.prefabInstanceUpdated -= OnPrefabInstanceUpdate;
#endif
m_isRegisteredForEvents = false;
}
#if UNITY_EDITOR
protected override void Reset()
{
//Debug.Log("***** Reset() *****"); //has been called.");
// Return if Awake() has not been called on the text object.
if (m_isAwake == false)
return;
LoadDefaultSettings();
LoadFontAsset();
m_havePropertiesChanged = true;
}
protected override void OnValidate()
{
//Debug.Log("***** OnValidate() ***** Frame:" + Time.frameCount); // ID " + GetInstanceID()); // New Material [" + m_sharedMaterial.name + "] with ID " + m_sharedMaterial.GetInstanceID() + ". Base Material is [" + m_baseMaterial.name + "] with ID " + m_baseMaterial.GetInstanceID() + ". Previous Base Material is [" + (m_lastBaseMaterial == null ? "Null" : m_lastBaseMaterial.name) + "].");
if (m_isAwake == false)
return;
// Handle Font Asset changes in the inspector.
if (m_fontAsset == null || m_hasFontAssetChanged)
{
LoadFontAsset();
m_hasFontAssetChanged = false;
}
if (m_canvasRenderer == null || m_canvasRenderer.GetMaterial() == null || m_canvasRenderer.GetMaterial().GetTexture(ShaderUtilities.ID_MainTex) == null || m_fontAsset == null || m_fontAsset.atlasTexture.GetInstanceID() != m_canvasRenderer.GetMaterial().GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID())
{
LoadFontAsset();
m_hasFontAssetChanged = false;
}
m_padding = GetPaddingForMaterial();
ComputeMarginSize();