TMP_MaterialManager.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. //#define TMP_DEBUG_MODE
  2. using UnityEngine;
  3. using System.Collections.Generic;
  4. using UnityEngine.UI;
  5. namespace TMPro
  6. {
  7. public static class TMP_MaterialManager
  8. {
  9. private static List<MaskingMaterial> m_materialList = new List<MaskingMaterial>();
  10. private static Dictionary<long, FallbackMaterial> m_fallbackMaterials = new Dictionary<long, FallbackMaterial>();
  11. private static Dictionary<int, long> m_fallbackMaterialLookup = new Dictionary<int, long>();
  12. private static List<FallbackMaterial> m_fallbackCleanupList = new List<FallbackMaterial>();
  13. private static bool isFallbackListDirty;
  14. static TMP_MaterialManager()
  15. {
  16. Camera.onPreRender += new Camera.CameraCallback(OnPreRender);
  17. Canvas.willRenderCanvases += new Canvas.WillRenderCanvases(OnPreRenderCanvas);
  18. }
  19. static void OnPreRender(Camera cam)
  20. {
  21. if (isFallbackListDirty)
  22. {
  23. //Debug.Log("1 - Cleaning up Fallback Materials.");
  24. CleanupFallbackMaterials();
  25. isFallbackListDirty = false;
  26. }
  27. }
  28. static void OnPreRenderCanvas()
  29. {
  30. if (isFallbackListDirty)
  31. {
  32. //Debug.Log("2 - Cleaning up Fallback Materials.");
  33. CleanupFallbackMaterials();
  34. isFallbackListDirty = false;
  35. }
  36. }
  37. /// <summary>
  38. /// Create a Masking Material Instance for the given ID
  39. /// </summary>
  40. /// <param name="baseMaterial"></param>
  41. /// <param name="stencilID"></param>
  42. /// <returns></returns>
  43. public static Material GetStencilMaterial(Material baseMaterial, int stencilID)
  44. {
  45. // Check if Material supports masking
  46. if (!baseMaterial.HasProperty(ShaderUtilities.ID_StencilID))
  47. {
  48. Debug.LogWarning("Selected Shader does not support Stencil Masking. Please select the Distance Field or Mobile Distance Field Shader.");
  49. return baseMaterial;
  50. }
  51. int baseMaterialID = baseMaterial.GetInstanceID();
  52. // If baseMaterial already has a corresponding masking material, return it.
  53. for (int i = 0; i < m_materialList.Count; i++)
  54. {
  55. if (m_materialList[i].baseMaterial.GetInstanceID() == baseMaterialID && m_materialList[i].stencilID == stencilID)
  56. {
  57. m_materialList[i].count += 1;
  58. #if TMP_DEBUG_MODE
  59. ListMaterials();
  60. #endif
  61. return m_materialList[i].stencilMaterial;
  62. }
  63. }
  64. // No matching masking material found. Create and return a new one.
  65. Material stencilMaterial;
  66. //Create new Masking Material Instance for this Base Material
  67. stencilMaterial = new Material(baseMaterial);
  68. stencilMaterial.hideFlags = HideFlags.HideAndDontSave;
  69. #if UNITY_EDITOR
  70. stencilMaterial.name += " Masking ID:" + stencilID;
  71. #endif
  72. stencilMaterial.shaderKeywords = baseMaterial.shaderKeywords;
  73. // Set Stencil Properties
  74. ShaderUtilities.GetShaderPropertyIDs();
  75. stencilMaterial.SetFloat(ShaderUtilities.ID_StencilID, stencilID);
  76. //stencilMaterial.SetFloat(ShaderUtilities.ID_StencilOp, 0);
  77. stencilMaterial.SetFloat(ShaderUtilities.ID_StencilComp, 4);
  78. //stencilMaterial.SetFloat(ShaderUtilities.ID_StencilReadMask, stencilID);
  79. //stencilMaterial.SetFloat(ShaderUtilities.ID_StencilWriteMask, 0);
  80. MaskingMaterial temp = new MaskingMaterial();
  81. temp.baseMaterial = baseMaterial;
  82. temp.stencilMaterial = stencilMaterial;
  83. temp.stencilID = stencilID;
  84. temp.count = 1;
  85. m_materialList.Add(temp);
  86. #if TMP_DEBUG_MODE
  87. ListMaterials();
  88. #endif
  89. return stencilMaterial;
  90. }
  91. /// <summary>
  92. /// Function to release the stencil material.
  93. /// </summary>
  94. /// <param name="stencilMaterial"></param>
  95. public static void ReleaseStencilMaterial(Material stencilMaterial)
  96. {
  97. int stencilMaterialID = stencilMaterial.GetInstanceID();
  98. for (int i = 0; i < m_materialList.Count; i++)
  99. {
  100. if (m_materialList[i].stencilMaterial.GetInstanceID() == stencilMaterialID)
  101. {
  102. if (m_materialList[i].count > 1)
  103. m_materialList[i].count -= 1;
  104. else
  105. {
  106. Object.DestroyImmediate(m_materialList[i].stencilMaterial);
  107. m_materialList.RemoveAt(i);
  108. stencilMaterial = null;
  109. }
  110. break;
  111. }
  112. }
  113. #if TMP_DEBUG_MODE
  114. ListMaterials();
  115. #endif
  116. }
  117. // Function which returns the base material associated with a Masking Material
  118. public static Material GetBaseMaterial(Material stencilMaterial)
  119. {
  120. // Check if maskingMaterial already has a base material associated with it.
  121. int index = m_materialList.FindIndex(item => item.stencilMaterial == stencilMaterial);
  122. if (index == -1)
  123. return null;
  124. else
  125. return m_materialList[index].baseMaterial;
  126. }
  127. /// <summary>
  128. /// Function to set the Material Stencil ID
  129. /// </summary>
  130. /// <param name="material"></param>
  131. /// <param name="stencilID"></param>
  132. /// <returns></returns>
  133. public static Material SetStencil(Material material, int stencilID)
  134. {
  135. material.SetFloat(ShaderUtilities.ID_StencilID, stencilID);
  136. if (stencilID == 0)
  137. material.SetFloat(ShaderUtilities.ID_StencilComp, 8);
  138. else
  139. material.SetFloat(ShaderUtilities.ID_StencilComp, 4);
  140. return material;
  141. }
  142. public static void AddMaskingMaterial(Material baseMaterial, Material stencilMaterial, int stencilID)
  143. {
  144. // Check if maskingMaterial already has a base material associated with it.
  145. int index = m_materialList.FindIndex(item => item.stencilMaterial == stencilMaterial);
  146. if (index == -1)
  147. {
  148. MaskingMaterial temp = new MaskingMaterial();
  149. temp.baseMaterial = baseMaterial;
  150. temp.stencilMaterial = stencilMaterial;
  151. temp.stencilID = stencilID;
  152. temp.count = 1;
  153. m_materialList.Add(temp);
  154. }
  155. else
  156. {
  157. stencilMaterial = m_materialList[index].stencilMaterial;
  158. m_materialList[index].count += 1;
  159. }
  160. }
  161. public static void RemoveStencilMaterial(Material stencilMaterial)
  162. {
  163. // Check if maskingMaterial is already on the list.
  164. int index = m_materialList.FindIndex(item => item.stencilMaterial == stencilMaterial);
  165. if (index != -1)
  166. {
  167. m_materialList.RemoveAt(index);
  168. }
  169. #if TMP_DEBUG_MODE
  170. ListMaterials();
  171. #endif
  172. }
  173. public static void ReleaseBaseMaterial(Material baseMaterial)
  174. {
  175. // Check if baseMaterial already has a masking material associated with it.
  176. int index = m_materialList.FindIndex(item => item.baseMaterial == baseMaterial);
  177. if (index == -1)
  178. {
  179. Debug.Log("No Masking Material exists for " + baseMaterial.name);
  180. }
  181. else
  182. {
  183. if (m_materialList[index].count > 1)
  184. {
  185. m_materialList[index].count -= 1;
  186. Debug.Log("Removed (1) reference to " + m_materialList[index].stencilMaterial.name + ". There are " + m_materialList[index].count + " references left.");
  187. }
  188. else
  189. {
  190. Debug.Log("Removed last reference to " + m_materialList[index].stencilMaterial.name + " with ID " + m_materialList[index].stencilMaterial.GetInstanceID());
  191. Object.DestroyImmediate(m_materialList[index].stencilMaterial);
  192. m_materialList.RemoveAt(index);
  193. }
  194. }
  195. #if TMP_DEBUG_MODE
  196. ListMaterials();
  197. #endif
  198. }
  199. public static void ClearMaterials()
  200. {
  201. if (m_materialList.Count == 0)
  202. {
  203. Debug.Log("Material List has already been cleared.");
  204. return;
  205. }
  206. for (int i = 0; i < m_materialList.Count; i++)
  207. {
  208. //Material baseMaterial = m_materialList[i].baseMaterial;
  209. Material stencilMaterial = m_materialList[i].stencilMaterial;
  210. Object.DestroyImmediate(stencilMaterial);
  211. m_materialList.RemoveAt(i);
  212. }
  213. }
  214. /// <summary>
  215. /// Function to get the Stencil ID
  216. /// </summary>
  217. /// <param name="obj"></param>
  218. /// <returns></returns>
  219. public static int GetStencilID(GameObject obj)
  220. {
  221. // Implementation is almost copied from Unity UI
  222. var count = 0;
  223. var transform = obj.transform;
  224. var stopAfter = FindRootSortOverrideCanvas(transform);
  225. if (transform == stopAfter)
  226. return count;
  227. var t = transform.parent;
  228. var components = TMP_ListPool<Mask>.Get();
  229. while (t != null)
  230. {
  231. t.GetComponents<Mask>(components);
  232. for (var i = 0; i < components.Count; ++i)
  233. {
  234. var mask = components[i];
  235. if (mask != null && mask.MaskEnabled() && mask.graphic.IsActive())
  236. {
  237. ++count;
  238. break;
  239. }
  240. }
  241. if (t == stopAfter)
  242. break;
  243. t = t.parent;
  244. }
  245. TMP_ListPool<Mask>.Release(components);
  246. return Mathf.Min((1 << count) - 1, 255);
  247. }
  248. public static Material GetMaterialForRendering(MaskableGraphic graphic, Material baseMaterial)
  249. {
  250. if (baseMaterial == null)
  251. return null;
  252. var modifiers = TMP_ListPool<IMaterialModifier>.Get();
  253. graphic.GetComponents(modifiers);
  254. var result = baseMaterial;
  255. for (int i = 0; i < modifiers.Count; i++)
  256. result = modifiers[i].GetModifiedMaterial(result);
  257. TMP_ListPool<IMaterialModifier>.Release(modifiers);
  258. return result;
  259. }
  260. private static Transform FindRootSortOverrideCanvas(Transform start)
  261. {
  262. // Implementation is copied from Unity UI
  263. var canvasList = TMP_ListPool<Canvas>.Get();
  264. start.GetComponentsInParent(false, canvasList);
  265. Canvas canvas = null;
  266. for (int i = 0; i < canvasList.Count; ++i)
  267. {
  268. canvas = canvasList[i];
  269. // We found the canvas we want to use break
  270. if (canvas.overrideSorting)
  271. break;
  272. }
  273. TMP_ListPool<Canvas>.Release(canvasList);
  274. return canvas != null ? canvas.transform : null;
  275. }
  276. /// <summary>
  277. /// This function returns a material instance using the material properties of a previous material but using the font atlas texture of the new font asset.
  278. /// </summary>
  279. /// <param name="sourceMaterial">The material containing the source material properties to be copied to the new material.</param>
  280. /// <param name="targetMaterial">The font atlas texture that should be assigned to the new material.</param>
  281. /// <returns></returns>
  282. public static Material GetFallbackMaterial (Material sourceMaterial, Material targetMaterial)
  283. {
  284. int sourceID = sourceMaterial.GetInstanceID();
  285. Texture tex = targetMaterial.GetTexture(ShaderUtilities.ID_MainTex);
  286. int texID = tex.GetInstanceID();
  287. long key = (long)sourceID << 32 | (long)(uint)texID;
  288. if (m_fallbackMaterials.TryGetValue(key, out FallbackMaterial fallback))
  289. {
  290. //Debug.Log("Material [" + fallback.fallbackMaterial.name + "] already exists.");
  291. return fallback.fallbackMaterial;
  292. }
  293. // Create new material from the source material and copy properties if using distance field shaders.
  294. Material fallbackMaterial = null;
  295. if (sourceMaterial.HasProperty(ShaderUtilities.ID_GradientScale) && targetMaterial.HasProperty(ShaderUtilities.ID_GradientScale))
  296. {
  297. fallbackMaterial = new Material(sourceMaterial);
  298. fallbackMaterial.hideFlags = HideFlags.HideAndDontSave;
  299. #if UNITY_EDITOR
  300. fallbackMaterial.name += " + " + tex.name;
  301. //Debug.Log("Creating new fallback material for " + fallbackMaterial.name);
  302. #endif
  303. fallbackMaterial.SetTexture(ShaderUtilities.ID_MainTex, tex);
  304. // Retain material properties unique to target material.
  305. fallbackMaterial.SetFloat(ShaderUtilities.ID_GradientScale, targetMaterial.GetFloat(ShaderUtilities.ID_GradientScale));
  306. fallbackMaterial.SetFloat(ShaderUtilities.ID_TextureWidth, targetMaterial.GetFloat(ShaderUtilities.ID_TextureWidth));
  307. fallbackMaterial.SetFloat(ShaderUtilities.ID_TextureHeight, targetMaterial.GetFloat(ShaderUtilities.ID_TextureHeight));
  308. fallbackMaterial.SetFloat(ShaderUtilities.ID_WeightNormal, targetMaterial.GetFloat(ShaderUtilities.ID_WeightNormal));
  309. fallbackMaterial.SetFloat(ShaderUtilities.ID_WeightBold, targetMaterial.GetFloat(ShaderUtilities.ID_WeightBold));
  310. }
  311. else
  312. {
  313. fallbackMaterial = new Material(targetMaterial);
  314. }
  315. fallback = new FallbackMaterial();
  316. fallback.baseID = sourceID;
  317. fallback.baseMaterial = sourceMaterial;
  318. fallback.fallbackID = key;
  319. fallback.fallbackMaterial = fallbackMaterial;
  320. fallback.count = 0;
  321. m_fallbackMaterials.Add(key, fallback);
  322. m_fallbackMaterialLookup.Add(fallbackMaterial.GetInstanceID(), key);
  323. #if TMP_DEBUG_MODE
  324. ListFallbackMaterials();
  325. #endif
  326. return fallbackMaterial;
  327. }
  328. /// <summary>
  329. ///
  330. /// </summary>
  331. /// <param name="targetMaterial"></param>
  332. public static void AddFallbackMaterialReference(Material targetMaterial)
  333. {
  334. if (targetMaterial == null) return;
  335. int sourceID = targetMaterial.GetInstanceID();
  336. // Lookup key to retrieve
  337. if (m_fallbackMaterialLookup.TryGetValue(sourceID, out long key))
  338. {
  339. if (m_fallbackMaterials.TryGetValue(key, out FallbackMaterial fallback))
  340. {
  341. //Debug.Log("Adding Fallback material " + fallback.fallbackMaterial.name + " with reference count of " + (fallback.count + 1));
  342. fallback.count += 1;
  343. }
  344. }
  345. }
  346. /// <summary>
  347. ///
  348. /// </summary>
  349. /// <param name="targetMaterial"></param>
  350. public static void RemoveFallbackMaterialReference(Material targetMaterial)
  351. {
  352. if (targetMaterial == null) return;
  353. int sourceID = targetMaterial.GetInstanceID();
  354. // Lookup key to retrieve
  355. if (m_fallbackMaterialLookup.TryGetValue(sourceID, out long key))
  356. {
  357. if (m_fallbackMaterials.TryGetValue(key, out FallbackMaterial fallback))
  358. {
  359. fallback.count -= 1;
  360. if (fallback.count < 1)
  361. m_fallbackCleanupList.Add(fallback);
  362. }
  363. }
  364. }
  365. /// <summary>
  366. ///
  367. /// </summary>
  368. public static void CleanupFallbackMaterials()
  369. {
  370. // Return if the list is empty.
  371. if (m_fallbackCleanupList.Count == 0) return;
  372. for (int i = 0; i < m_fallbackCleanupList.Count; i++)
  373. {
  374. FallbackMaterial fallback = m_fallbackCleanupList[i];
  375. if (fallback.count < 1)
  376. {
  377. //Debug.Log("Cleaning up " + fallback.fallbackMaterial.name);
  378. Material mat = fallback.fallbackMaterial;
  379. m_fallbackMaterials.Remove(fallback.fallbackID);
  380. m_fallbackMaterialLookup.Remove(mat.GetInstanceID());
  381. Object.DestroyImmediate(mat);
  382. mat = null;
  383. }
  384. }
  385. m_fallbackCleanupList.Clear();
  386. }
  387. /// <summary>
  388. /// Function to release the fallback material.
  389. /// </summary>
  390. /// <param name="fallackMaterial"></param>
  391. public static void ReleaseFallbackMaterial(Material fallackMaterial)
  392. {
  393. if (fallackMaterial == null) return;
  394. int materialID = fallackMaterial.GetInstanceID();
  395. if (m_fallbackMaterialLookup.TryGetValue(materialID, out long key))
  396. {
  397. if (m_fallbackMaterials.TryGetValue(key, out FallbackMaterial fallback))
  398. {
  399. //Debug.Log("Releasing Fallback material " + fallback.fallbackMaterial.name + " with remaining reference count of " + (fallback.count - 1));
  400. fallback.count -= 1;
  401. if (fallback.count < 1)
  402. m_fallbackCleanupList.Add(fallback);
  403. }
  404. }
  405. isFallbackListDirty = true;
  406. #if TMP_DEBUG_MODE
  407. ListFallbackMaterials();
  408. #endif
  409. }
  410. private class FallbackMaterial
  411. {
  412. public int baseID;
  413. public Material baseMaterial;
  414. public long fallbackID;
  415. public Material fallbackMaterial;
  416. public int count;
  417. }
  418. private class MaskingMaterial
  419. {
  420. public Material baseMaterial;
  421. public Material stencilMaterial;
  422. public int count;
  423. public int stencilID;
  424. }
  425. /// <summary>
  426. /// Function to copy the properties of a source material preset to another while preserving the unique font asset properties of the destination material.
  427. /// </summary>
  428. /// <param name="source"></param>
  429. /// <param name="destination"></param>
  430. public static void CopyMaterialPresetProperties(Material source, Material destination)
  431. {
  432. if (!source.HasProperty(ShaderUtilities.ID_GradientScale) || !destination.HasProperty(ShaderUtilities.ID_GradientScale))
  433. return;
  434. // Save unique material properties
  435. Texture dst_texture = destination.GetTexture(ShaderUtilities.ID_MainTex);
  436. float dst_gradientScale = destination.GetFloat(ShaderUtilities.ID_GradientScale);
  437. float dst_texWidth = destination.GetFloat(ShaderUtilities.ID_TextureWidth);
  438. float dst_texHeight = destination.GetFloat(ShaderUtilities.ID_TextureHeight);
  439. float dst_weightNormal = destination.GetFloat(ShaderUtilities.ID_WeightNormal);
  440. float dst_weightBold = destination.GetFloat(ShaderUtilities.ID_WeightBold);
  441. // Copy all material properties
  442. destination.CopyPropertiesFromMaterial(source);
  443. // Copy shader keywords
  444. destination.shaderKeywords = source.shaderKeywords;
  445. // Restore unique material properties
  446. destination.SetTexture(ShaderUtilities.ID_MainTex, dst_texture);
  447. destination.SetFloat(ShaderUtilities.ID_GradientScale, dst_gradientScale);
  448. destination.SetFloat(ShaderUtilities.ID_TextureWidth, dst_texWidth);
  449. destination.SetFloat(ShaderUtilities.ID_TextureHeight, dst_texHeight);
  450. destination.SetFloat(ShaderUtilities.ID_WeightNormal, dst_weightNormal);
  451. destination.SetFloat(ShaderUtilities.ID_WeightBold, dst_weightBold);
  452. }
  453. #if TMP_DEBUG_MODE
  454. /// <summary>
  455. ///
  456. /// </summary>
  457. public static void ListMaterials()
  458. {
  459. if (m_materialList.Count() == 0)
  460. {
  461. Debug.Log("Material List is empty.");
  462. return;
  463. }
  464. //Debug.Log("List contains " + m_materialList.Count() + " items.");
  465. for (int i = 0; i < m_materialList.Count(); i++)
  466. {
  467. Material baseMaterial = m_materialList[i].baseMaterial;
  468. Material stencilMaterial = m_materialList[i].stencilMaterial;
  469. Debug.Log("Item #" + (i + 1) + " - Base Material is [" + baseMaterial.name + "] with ID " + baseMaterial.GetInstanceID() + " is associated with [" + (stencilMaterial != null ? stencilMaterial.name : "Null") + "] Stencil ID " + m_materialList[i].stencilID + " with ID " + (stencilMaterial != null ? stencilMaterial.GetInstanceID() : 0) + " and is referenced " + m_materialList[i].count + " time(s).");
  470. }
  471. }
  472. /// <summary>
  473. ///
  474. /// </summary>
  475. public static void ListFallbackMaterials()
  476. {
  477. if (m_fallbackMaterialList.Count() == 0)
  478. {
  479. Debug.Log("Material List is empty.");
  480. return;
  481. }
  482. Debug.Log("List contains " + m_fallbackMaterialList.Count() + " items.");
  483. for (int i = 0; i < m_fallbackMaterialList.Count(); i++)
  484. {
  485. Material baseMaterial = m_fallbackMaterialList[i].baseMaterial;
  486. Material fallbackMaterial = m_fallbackMaterialList[i].fallbackMaterial;
  487. Debug.Log("Item #" + (i + 1) + " - Base Material is [" + baseMaterial.name + "] with ID " + baseMaterial.GetInstanceID() + " is associated with [" + (fallbackMaterial != null ? fallbackMaterial.name : "Null") + "] with ID " + (fallbackMaterial != null ? fallbackMaterial.GetInstanceID() : 0) + " and is referenced " + m_fallbackMaterialList[i].count + " time(s).");
  488. }
  489. }
  490. #endif
  491. }
  492. }