TMP_SubMesh.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. using UnityEngine;
  2. using System;
  3. using System.Collections;
  4. using Object = UnityEngine.Object;
  5. #pragma warning disable 0109 // Disable warning due to conflict between Unity Editor DLL and Runtime DLL related to .renderer property being available in one but not the other.
  6. namespace TMPro
  7. {
  8. [RequireComponent(typeof(MeshRenderer))]
  9. [ExecuteAlways]
  10. public class TMP_SubMesh : MonoBehaviour
  11. {
  12. /// <summary>
  13. /// The TMP Font Asset assigned to this sub text object.
  14. /// </summary>
  15. public TMP_FontAsset fontAsset
  16. {
  17. get { return m_fontAsset; }
  18. set { m_fontAsset = value; }
  19. }
  20. [SerializeField]
  21. private TMP_FontAsset m_fontAsset;
  22. /// <summary>
  23. /// The TMP Sprite Asset assigned to this sub text object.
  24. /// </summary>
  25. public TMP_SpriteAsset spriteAsset
  26. {
  27. get { return m_spriteAsset; }
  28. set { m_spriteAsset = value; }
  29. }
  30. [SerializeField]
  31. private TMP_SpriteAsset m_spriteAsset;
  32. /// <summary>
  33. /// The material to be assigned to this object. Returns an instance of the material.
  34. /// </summary>
  35. public Material material
  36. {
  37. // Return a new Instance of the Material if none exists. Otherwise return the current Material Instance.
  38. get { return GetMaterial(m_sharedMaterial); }
  39. // Assign new font material
  40. set
  41. {
  42. if (m_sharedMaterial.GetInstanceID() == value.GetInstanceID())
  43. return;
  44. m_sharedMaterial = m_material = value;
  45. m_padding = GetPaddingForMaterial();
  46. SetVerticesDirty();
  47. SetMaterialDirty();
  48. }
  49. }
  50. [SerializeField]
  51. private Material m_material;
  52. /// <summary>
  53. /// The material to be assigned to this text object.
  54. /// </summary>
  55. public Material sharedMaterial
  56. {
  57. get { return m_sharedMaterial; }
  58. set { SetSharedMaterial(value); }
  59. }
  60. [SerializeField]
  61. private Material m_sharedMaterial;
  62. /// <summary>
  63. /// The fallback material created from the properties of the fallback source material.
  64. /// </summary>
  65. public Material fallbackMaterial
  66. {
  67. get { return m_fallbackMaterial; }
  68. set
  69. {
  70. if (m_fallbackMaterial == value) return;
  71. if (m_fallbackMaterial != null && m_fallbackMaterial != value)
  72. TMP_MaterialManager.ReleaseFallbackMaterial(m_fallbackMaterial);
  73. m_fallbackMaterial = value;
  74. TMP_MaterialManager.AddFallbackMaterialReference(m_fallbackMaterial);
  75. SetSharedMaterial(m_fallbackMaterial);
  76. }
  77. }
  78. private Material m_fallbackMaterial;
  79. /// <summary>
  80. /// The source material used by the fallback font
  81. /// </summary>
  82. public Material fallbackSourceMaterial
  83. {
  84. get { return m_fallbackSourceMaterial; }
  85. set { m_fallbackSourceMaterial = value; }
  86. }
  87. private Material m_fallbackSourceMaterial;
  88. /// <summary>
  89. /// Is the text object using the default font asset material.
  90. /// </summary>
  91. public bool isDefaultMaterial
  92. {
  93. get { return m_isDefaultMaterial; }
  94. set { m_isDefaultMaterial = value; }
  95. }
  96. [SerializeField]
  97. private bool m_isDefaultMaterial;
  98. /// <summary>
  99. /// Padding value resulting for the property settings on the material.
  100. /// </summary>
  101. public float padding
  102. {
  103. get { return m_padding; }
  104. set { m_padding = value; }
  105. }
  106. [SerializeField]
  107. private float m_padding;
  108. /// <summary>
  109. /// The Mesh Renderer of this text sub object.
  110. /// </summary>
  111. public new Renderer renderer
  112. {
  113. get { if (m_renderer == null) m_renderer = GetComponent<Renderer>();
  114. return m_renderer;
  115. }
  116. }
  117. [SerializeField]
  118. private Renderer m_renderer;
  119. /// <summary>
  120. /// The MeshFilter of this text sub object.
  121. /// </summary>
  122. public MeshFilter meshFilter
  123. {
  124. get
  125. {
  126. if (m_meshFilter == null)
  127. {
  128. m_meshFilter = GetComponent<MeshFilter>();
  129. if (m_meshFilter == null)
  130. {
  131. m_meshFilter = gameObject.AddComponent<MeshFilter>();
  132. m_meshFilter.hideFlags = HideFlags.HideInInspector | HideFlags.HideAndDontSave;
  133. }
  134. }
  135. return m_meshFilter;
  136. }
  137. }
  138. private MeshFilter m_meshFilter;
  139. /// <summary>
  140. /// The Mesh of this text sub object.
  141. /// </summary>
  142. public Mesh mesh
  143. {
  144. get
  145. {
  146. if (m_mesh == null)
  147. {
  148. m_mesh = new Mesh();
  149. m_mesh.hideFlags = HideFlags.HideAndDontSave;
  150. }
  151. return m_mesh;
  152. }
  153. set { m_mesh = value; }
  154. }
  155. private Mesh m_mesh;
  156. /// <summary>
  157. ///
  158. /// </summary>
  159. //public BoxCollider boxCollider
  160. //{
  161. // get
  162. // {
  163. // if (m_boxCollider == null)
  164. // {
  165. // //
  166. // m_boxCollider = GetComponent<BoxCollider>();
  167. // if (m_boxCollider == null)
  168. // {
  169. // m_boxCollider = gameObject.AddComponent<BoxCollider>();
  170. // gameObject.AddComponent<Rigidbody>();
  171. // }
  172. // }
  173. // return m_boxCollider;
  174. // }
  175. //}
  176. //[SerializeField]
  177. //private BoxCollider m_boxCollider;
  178. /// <summary>
  179. /// Reference to the parent Text Component.
  180. /// </summary>
  181. public TMP_Text textComponent
  182. {
  183. get
  184. {
  185. if (m_TextComponent == null)
  186. m_TextComponent = GetComponentInParent<TextMeshPro>();
  187. return m_TextComponent;
  188. }
  189. }
  190. [SerializeField]
  191. private TextMeshPro m_TextComponent;
  192. [NonSerialized]
  193. private bool m_isRegisteredForEvents;
  194. public static TMP_SubMesh AddSubTextObject(TextMeshPro textComponent, MaterialReference materialReference)
  195. {
  196. GameObject go = new GameObject("TMP SubMesh [" + materialReference.material.name + "]", typeof(TMP_SubMesh));
  197. go.hideFlags = HideFlags.DontSave;
  198. TMP_SubMesh subMesh = go.GetComponent<TMP_SubMesh>();
  199. go.transform.SetParent(textComponent.transform, false);
  200. go.transform.localPosition = Vector3.zero;
  201. go.transform.localRotation = Quaternion.identity;
  202. go.transform.localScale = Vector3.one;
  203. go.layer = textComponent.gameObject.layer;
  204. subMesh.m_TextComponent = textComponent;
  205. subMesh.m_fontAsset = materialReference.fontAsset;
  206. subMesh.m_spriteAsset = materialReference.spriteAsset;
  207. subMesh.m_isDefaultMaterial = materialReference.isDefaultMaterial;
  208. subMesh.SetSharedMaterial(materialReference.material);
  209. subMesh.renderer.sortingLayerID = textComponent.renderer.sortingLayerID;
  210. subMesh.renderer.sortingOrder = textComponent.renderer.sortingOrder;
  211. return subMesh;
  212. }
  213. void OnEnable()
  214. {
  215. //Debug.Log("***** OnEnable() called on object ID " + GetInstanceID() + "]. Parent Text Object ID [" + (textComponent == null ? "" : textComponent.GetInstanceID().ToString()) + "] *****");
  216. // Register Callbacks for various events.
  217. if (!m_isRegisteredForEvents)
  218. {
  219. #if UNITY_EDITOR
  220. TMPro_EventManager.MATERIAL_PROPERTY_EVENT.Add(ON_MATERIAL_PROPERTY_CHANGED);
  221. TMPro_EventManager.FONT_PROPERTY_EVENT.Add(ON_FONT_PROPERTY_CHANGED);
  222. //TMPro_EventManager.TEXTMESHPRO_PROPERTY_EVENT.Add(ON_TEXTMESHPRO_PROPERTY_CHANGED);
  223. TMPro_EventManager.DRAG_AND_DROP_MATERIAL_EVENT.Add(ON_DRAG_AND_DROP_MATERIAL);
  224. //TMPro_EventManager.TEXT_STYLE_PROPERTY_EVENT.Add(ON_TEXT_STYLE_CHANGED);
  225. TMPro_EventManager.SPRITE_ASSET_PROPERTY_EVENT.Add(ON_SPRITE_ASSET_PROPERTY_CHANGED);
  226. //TMPro_EventManager.TMP_SETTINGS_PROPERTY_EVENT.Add(ON_TMP_SETTINGS_CHANGED);
  227. #endif
  228. m_isRegisteredForEvents = true;
  229. }
  230. // Update HideFlags on previously created sub text objects.
  231. if (hideFlags != HideFlags.DontSave)
  232. hideFlags = HideFlags.DontSave;
  233. // Make the geometry visible when the object is enabled.
  234. meshFilter.sharedMesh = mesh;
  235. // Update _ClipRect values
  236. if (m_sharedMaterial != null)
  237. m_sharedMaterial.SetVector(ShaderUtilities.ID_ClipRect, new Vector4(-32767, -32767, 32767, 32767));
  238. }
  239. void OnDisable()
  240. {
  241. //Debug.Log("***** OnDisable() called on Sub Object ID [" + GetInstanceID() + "]. Parent Text Object ID [" + textComponent.GetInstanceID() + "] *****");
  242. // Hide the geometry when the object is disabled.
  243. m_meshFilter.sharedMesh = null;
  244. if (m_fallbackMaterial != null)
  245. {
  246. TMP_MaterialManager.ReleaseFallbackMaterial(m_fallbackMaterial);
  247. m_fallbackMaterial = null;
  248. }
  249. }
  250. void OnDestroy()
  251. {
  252. //Debug.Log("***** OnDestroy() called on Sub Object ID [" + GetInstanceID() + "]. Parent Text Object ID [" + textComponent.GetInstanceID() + "] *****");
  253. // Destroy Mesh
  254. if (m_mesh != null) DestroyImmediate(m_mesh);
  255. if (m_fallbackMaterial != null)
  256. {
  257. TMP_MaterialManager.ReleaseFallbackMaterial(m_fallbackMaterial);
  258. m_fallbackMaterial = null;
  259. }
  260. #if UNITY_EDITOR
  261. // Unregister the event this object was listening to
  262. TMPro_EventManager.MATERIAL_PROPERTY_EVENT.Remove(ON_MATERIAL_PROPERTY_CHANGED);
  263. TMPro_EventManager.FONT_PROPERTY_EVENT.Remove(ON_FONT_PROPERTY_CHANGED);
  264. //TMPro_EventManager.TEXTMESHPRO_PROPERTY_EVENT.Remove(ON_TEXTMESHPRO_PROPERTY_CHANGED);
  265. TMPro_EventManager.DRAG_AND_DROP_MATERIAL_EVENT.Remove(ON_DRAG_AND_DROP_MATERIAL);
  266. //TMPro_EventManager.TEXT_STYLE_PROPERTY_EVENT.Remove(ON_TEXT_STYLE_CHANGED);
  267. TMPro_EventManager.SPRITE_ASSET_PROPERTY_EVENT.Remove(ON_SPRITE_ASSET_PROPERTY_CHANGED);
  268. //TMPro_EventManager.TMP_SETTINGS_PROPERTY_EVENT.Remove(ON_TMP_SETTINGS_CHANGED);
  269. #endif
  270. m_isRegisteredForEvents = false;
  271. // Notify parent text object
  272. m_TextComponent.havePropertiesChanged = true;
  273. m_TextComponent.SetAllDirty();
  274. }
  275. #if UNITY_EDITOR
  276. // Event received when custom material editor properties are changed.
  277. void ON_MATERIAL_PROPERTY_CHANGED(bool isChanged, Material mat)
  278. {
  279. //Debug.Log("*** ON_MATERIAL_PROPERTY_CHANGED ***");
  280. if (m_sharedMaterial == null)
  281. return;
  282. int targetMaterialID = mat.GetInstanceID();
  283. int sharedMaterialID = m_sharedMaterial.GetInstanceID();
  284. int fallbackSourceMaterialID = m_fallbackSourceMaterial == null ? 0 : m_fallbackSourceMaterial.GetInstanceID();
  285. // Sync culling with parent text object
  286. bool hasCullModeProperty = m_sharedMaterial.HasProperty(ShaderUtilities.ShaderTag_CullMode);
  287. float cullMode = 0;
  288. if (hasCullModeProperty)
  289. {
  290. cullMode = textComponent.fontSharedMaterial.GetFloat(ShaderUtilities.ShaderTag_CullMode);
  291. m_sharedMaterial.SetFloat(ShaderUtilities.ShaderTag_CullMode, cullMode);
  292. }
  293. // Filter events and return if the affected material is not this object's material.
  294. if (targetMaterialID != sharedMaterialID)
  295. {
  296. // Check if event applies to the source fallback material
  297. if (m_fallbackMaterial != null && fallbackSourceMaterialID == targetMaterialID && TMP_Settings.matchMaterialPreset)
  298. {
  299. TMP_MaterialManager.CopyMaterialPresetProperties(mat, m_fallbackMaterial);
  300. // Re-sync culling with parent text object
  301. if (hasCullModeProperty)
  302. m_fallbackMaterial.SetFloat(ShaderUtilities.ShaderTag_CullMode, cullMode);
  303. }
  304. else
  305. return;
  306. }
  307. m_padding = GetPaddingForMaterial();
  308. m_TextComponent.havePropertiesChanged = true;
  309. m_TextComponent.SetVerticesDirty();
  310. }
  311. // Event to Track Material Changed resulting from Drag-n-drop.
  312. void ON_DRAG_AND_DROP_MATERIAL(GameObject obj, Material currentMaterial, Material newMaterial)
  313. {
  314. // Check if event applies to this current object
  315. #if UNITY_2018_2_OR_NEWER
  316. if (obj == gameObject || UnityEditor.PrefabUtility.GetCorrespondingObjectFromSource(gameObject) == obj)
  317. #else
  318. if (obj == gameObject || UnityEditor.PrefabUtility.GetPrefabParent(gameObject) == obj)
  319. #endif
  320. {
  321. if (!m_isDefaultMaterial) return;
  322. // Make sure we have a valid reference to the renderer.
  323. if (m_renderer == null) m_renderer = GetComponent<Renderer>();
  324. UnityEditor.Undo.RecordObject(this, "Material Assignment");
  325. UnityEditor.Undo.RecordObject(m_renderer, "Material Assignment");
  326. SetSharedMaterial(newMaterial);
  327. m_TextComponent.havePropertiesChanged = true;
  328. }
  329. }
  330. // Event received when font asset properties are changed in Font Inspector
  331. void ON_SPRITE_ASSET_PROPERTY_CHANGED(bool isChanged, UnityEngine.Object obj)
  332. {
  333. //if (spriteSheet != null && (obj as TMP_SpriteAsset == m_spriteAsset || obj as Texture2D == m_spriteAsset.spriteSheet))
  334. //{
  335. if (m_TextComponent != null)
  336. {
  337. m_TextComponent.havePropertiesChanged = true;
  338. //m_TextComponent.SetVerticesDirty();
  339. }
  340. //}
  341. }
  342. // Event received when font asset properties are changed in Font Inspector
  343. void ON_FONT_PROPERTY_CHANGED(bool isChanged, Object fontAsset)
  344. {
  345. if (m_fontAsset != null && fontAsset.GetInstanceID() == m_fontAsset.GetInstanceID())
  346. {
  347. // Copy Normal and Bold Weight
  348. if (m_fallbackMaterial != null)
  349. {
  350. if (TMP_Settings.matchMaterialPreset)
  351. {
  352. TMP_MaterialManager.ReleaseFallbackMaterial(m_fallbackMaterial);
  353. TMP_MaterialManager.CleanupFallbackMaterials();
  354. }
  355. }
  356. }
  357. }
  358. /// <summary>
  359. /// Event received when the TMP Settings are changed.
  360. /// </summary>
  361. void ON_TMP_SETTINGS_CHANGED()
  362. {
  363. // //Debug.Log("TMP Setting have changed.");
  364. // //SetVerticesDirty();
  365. // SetMaterialDirty();
  366. }
  367. #endif
  368. public void DestroySelf()
  369. {
  370. Destroy(this.gameObject, 1f);
  371. }
  372. // Function called internally when a new material is assigned via the fontMaterial property.
  373. Material GetMaterial(Material mat)
  374. {
  375. // Check in case Object is disabled. If so, we don't have a valid reference to the Renderer.
  376. // This can occur when the Duplicate Material Context menu is used on an inactive object.
  377. if (m_renderer == null)
  378. m_renderer = GetComponent<Renderer>();
  379. // Create Instance Material only if the new material is not the same instance previously used.
  380. if (m_material == null || m_material.GetInstanceID() != mat.GetInstanceID())
  381. m_material = CreateMaterialInstance(mat);
  382. m_sharedMaterial = m_material;
  383. // Compute and Set new padding values for this new material.
  384. m_padding = GetPaddingForMaterial();
  385. SetVerticesDirty();
  386. SetMaterialDirty();
  387. return m_sharedMaterial;
  388. }
  389. /// <summary>
  390. /// Method used to create an instance of the material
  391. /// </summary>
  392. /// <param name="source"></param>
  393. /// <returns></returns>
  394. Material CreateMaterialInstance(Material source)
  395. {
  396. Material mat = new Material(source);
  397. mat.shaderKeywords = source.shaderKeywords;
  398. mat.name += " (Instance)";
  399. return mat;
  400. }
  401. /// <summary>
  402. /// Method returning the shared material assigned to the text object.
  403. /// </summary>
  404. /// <returns></returns>
  405. Material GetSharedMaterial()
  406. {
  407. if (m_renderer == null)
  408. m_renderer = GetComponent<Renderer>();
  409. return m_renderer.sharedMaterial;
  410. }
  411. /// <summary>
  412. /// Method to set the shared material.
  413. /// </summary>
  414. /// <param name="mat"></param>
  415. void SetSharedMaterial(Material mat)
  416. {
  417. //Debug.Log("*** SetSharedMaterial() *** FRAME (" + Time.frameCount + ")");
  418. // Assign new material.
  419. m_sharedMaterial = mat;
  420. // Compute and Set new padding values for this new material.
  421. m_padding = GetPaddingForMaterial();
  422. SetMaterialDirty();
  423. #if UNITY_EDITOR
  424. if (m_sharedMaterial != null)
  425. gameObject.name = "TMP SubMesh [" + m_sharedMaterial.name + "]";
  426. #endif
  427. }
  428. /// <summary>
  429. /// Function called when the padding value for the material needs to be re-calculated.
  430. /// </summary>
  431. /// <returns></returns>
  432. public float GetPaddingForMaterial()
  433. {
  434. float padding = ShaderUtilities.GetPadding(m_sharedMaterial, m_TextComponent.extraPadding, m_TextComponent.isUsingBold);
  435. return padding;
  436. }
  437. /// <summary>
  438. /// Function to update the padding values of the object.
  439. /// </summary>
  440. /// <param name="isExtraPadding"></param>
  441. /// <param name="isBold"></param>
  442. public void UpdateMeshPadding(bool isExtraPadding, bool isUsingBold)
  443. {
  444. m_padding = ShaderUtilities.GetPadding(m_sharedMaterial, isExtraPadding, isUsingBold);
  445. }
  446. /// <summary>
  447. ///
  448. /// </summary>
  449. public void SetVerticesDirty()
  450. {
  451. if (!this.enabled)
  452. return;
  453. // This is called on the parent TextMeshPro component.
  454. if (m_TextComponent != null)
  455. {
  456. m_TextComponent.havePropertiesChanged = true;
  457. m_TextComponent.SetVerticesDirty();
  458. }
  459. }
  460. /// <summary>
  461. ///
  462. /// </summary>
  463. public void SetMaterialDirty()
  464. {
  465. //if (!this.enabled)
  466. // return;
  467. UpdateMaterial();
  468. //m_materialDirty = true;
  469. //TMP_UpdateRegistry.RegisterCanvasElementForGraphicRebuild((ICanvasElement)this);
  470. }
  471. /// <summary>
  472. ///
  473. /// </summary>
  474. protected void UpdateMaterial()
  475. {
  476. //Debug.Log("*** STO - UpdateMaterial() *** FRAME (" + Time.frameCount + ")");
  477. if (renderer == null || m_sharedMaterial == null) return;
  478. m_renderer.sharedMaterial = m_sharedMaterial;
  479. // Special handling to keep the Culling of the material in sync with parent text object
  480. if (m_sharedMaterial.HasProperty(ShaderUtilities.ShaderTag_CullMode))
  481. {
  482. float cullMode = textComponent.fontSharedMaterial.GetFloat(ShaderUtilities.ShaderTag_CullMode);
  483. m_sharedMaterial.SetFloat(ShaderUtilities.ShaderTag_CullMode, cullMode);
  484. }
  485. #if UNITY_EDITOR
  486. if (m_sharedMaterial != null && gameObject.name != "TMP SubMesh [" + m_sharedMaterial.name + "]")
  487. gameObject.name = "TMP SubMesh [" + m_sharedMaterial.name + "]";
  488. #endif
  489. }
  490. /// <summary>
  491. ///
  492. /// </summary>
  493. //public void UpdateColliders(int vertexCount)
  494. //{
  495. // if (this.boxCollider == null) return;
  496. // Vector2 bl = TMP_Math.MAX_16BIT;
  497. // Vector2 tr = TMP_Math.MIN_16BIT;
  498. // // Compute the bounds of the sub text object mesh (excluding the transform position).
  499. // for (int i = 0; i < vertexCount; i++)
  500. // {
  501. // bl.x = Mathf.Min(bl.x, m_mesh.vertices[i].x);
  502. // bl.y = Mathf.Min(bl.y, m_mesh.vertices[i].y);
  503. // tr.x = Mathf.Max(tr.x, m_mesh.vertices[i].x);
  504. // tr.y = Mathf.Max(tr.y, m_mesh.vertices[i].y);
  505. // }
  506. // Vector3 center = (bl + tr) / 2;
  507. // Vector3 size = tr - bl;
  508. // size.z = .1f;
  509. // this.boxCollider.center = center;
  510. // this.boxCollider.size = size;
  511. //}
  512. }
  513. }