You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

633 lines
23 KiB

  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. FallbackMaterial fallback;
  289. if (m_fallbackMaterials.TryGetValue(key, out fallback))
  290. {
  291. //Debug.Log("Material [" + fallback.fallbackMaterial.name + "] already exists.");
  292. return fallback.fallbackMaterial;
  293. }
  294. // Create new material from the source material and copy properties if using distance field shaders.
  295. Material fallbackMaterial = null;
  296. if (sourceMaterial.HasProperty(ShaderUtilities.ID_GradientScale) && targetMaterial.HasProperty(ShaderUtilities.ID_GradientScale))
  297. {
  298. fallbackMaterial = new Material(sourceMaterial);
  299. fallbackMaterial.hideFlags = HideFlags.HideAndDontSave;
  300. #if UNITY_EDITOR
  301. fallbackMaterial.name += " + " + tex.name;
  302. //Debug.Log("Creating new fallback material for " + fallbackMaterial.name);
  303. #endif
  304. fallbackMaterial.SetTexture(ShaderUtilities.ID_MainTex, tex);
  305. // Retain material properties unique to target material.
  306. fallbackMaterial.SetFloat(ShaderUtilities.ID_GradientScale, targetMaterial.GetFloat(ShaderUtilities.ID_GradientScale));
  307. fallbackMaterial.SetFloat(ShaderUtilities.ID_TextureWidth, targetMaterial.GetFloat(ShaderUtilities.ID_TextureWidth));
  308. fallbackMaterial.SetFloat(ShaderUtilities.ID_TextureHeight, targetMaterial.GetFloat(ShaderUtilities.ID_TextureHeight));
  309. fallbackMaterial.SetFloat(ShaderUtilities.ID_WeightNormal, targetMaterial.GetFloat(ShaderUtilities.ID_WeightNormal));
  310. fallbackMaterial.SetFloat(ShaderUtilities.ID_WeightBold, targetMaterial.GetFloat(ShaderUtilities.ID_WeightBold));
  311. }
  312. else
  313. {
  314. fallbackMaterial = new Material(targetMaterial);
  315. }
  316. fallback = new FallbackMaterial();
  317. fallback.baseID = sourceID;
  318. fallback.baseMaterial = sourceMaterial;
  319. fallback.fallbackID = key;
  320. fallback.fallbackMaterial = fallbackMaterial;
  321. fallback.count = 0;
  322. m_fallbackMaterials.Add(key, fallback);
  323. m_fallbackMaterialLookup.Add(fallbackMaterial.GetInstanceID(), key);
  324. #if TMP_DEBUG_MODE
  325. ListFallbackMaterials();
  326. #endif
  327. return fallbackMaterial;
  328. }
  329. /// <summary>
  330. ///
  331. /// </summary>
  332. /// <param name="targetMaterial"></param>
  333. public static void AddFallbackMaterialReference(Material targetMaterial)
  334. {
  335. if (targetMaterial == null) return;
  336. int sourceID = targetMaterial.GetInstanceID();
  337. long key;
  338. // Lookup key to retrieve
  339. if (m_fallbackMaterialLookup.TryGetValue(sourceID, out key))
  340. {
  341. FallbackMaterial fallback;
  342. if (m_fallbackMaterials.TryGetValue(key, out fallback))
  343. {
  344. //Debug.Log("Adding Fallback material " + fallback.fallbackMaterial.name + " with reference count of " + (fallback.count + 1));
  345. fallback.count += 1;
  346. }
  347. }
  348. }
  349. /// <summary>
  350. ///
  351. /// </summary>
  352. /// <param name="targetMaterial"></param>
  353. public static void RemoveFallbackMaterialReference(Material targetMaterial)
  354. {
  355. if (targetMaterial == null) return;
  356. int sourceID = targetMaterial.GetInstanceID();
  357. long key;
  358. // Lookup key to retrieve
  359. if (m_fallbackMaterialLookup.TryGetValue(sourceID, out key))
  360. {
  361. FallbackMaterial fallback;
  362. if (m_fallbackMaterials.TryGetValue(key, out fallback))
  363. {
  364. fallback.count -= 1;
  365. if (fallback.count < 1)
  366. m_fallbackCleanupList.Add(fallback);
  367. }
  368. }
  369. }
  370. /// <summary>
  371. ///
  372. /// </summary>
  373. public static void CleanupFallbackMaterials()
  374. {
  375. // Return if the list is empty.
  376. if (m_fallbackCleanupList.Count == 0) return;
  377. for (int i = 0; i < m_fallbackCleanupList.Count; i++)
  378. {
  379. FallbackMaterial fallback = m_fallbackCleanupList[i];
  380. if (fallback.count < 1)
  381. {
  382. //Debug.Log("Cleaning up " + fallback.fallbackMaterial.name);
  383. Material mat = fallback.fallbackMaterial;
  384. m_fallbackMaterials.Remove(fallback.fallbackID);
  385. m_fallbackMaterialLookup.Remove(mat.GetInstanceID());
  386. Object.DestroyImmediate(mat);
  387. mat = null;
  388. }
  389. }
  390. m_fallbackCleanupList.Clear();
  391. }
  392. /// <summary>
  393. /// Function to release the fallback material.
  394. /// </summary>
  395. /// <param name="fallackMaterial"></param>
  396. public static void ReleaseFallbackMaterial(Material fallackMaterial)
  397. {
  398. if (fallackMaterial == null) return;
  399. int materialID = fallackMaterial.GetInstanceID();
  400. long key;
  401. if (m_fallbackMaterialLookup.TryGetValue(materialID, out key))
  402. {
  403. FallbackMaterial fallback;
  404. if (m_fallbackMaterials.TryGetValue(key, out fallback))
  405. {
  406. //Debug.Log("Releasing Fallback material " + fallback.fallbackMaterial.name + " with remaining reference count of " + (fallback.count - 1));
  407. fallback.count -= 1;
  408. if (fallback.count < 1)
  409. m_fallbackCleanupList.Add(fallback);
  410. }
  411. }
  412. isFallbackListDirty = true;
  413. #if TMP_DEBUG_MODE
  414. ListFallbackMaterials();
  415. #endif
  416. }
  417. private class FallbackMaterial
  418. {
  419. public int baseID;
  420. public Material baseMaterial;
  421. public long fallbackID;
  422. public Material fallbackMaterial;
  423. public int count;
  424. }
  425. private class MaskingMaterial
  426. {
  427. public Material baseMaterial;
  428. public Material stencilMaterial;
  429. public int count;
  430. public int stencilID;
  431. }
  432. /// <summary>
  433. /// Function to copy the properties of a source material preset to another while preserving the unique font asset properties of the destination material.
  434. /// </summary>
  435. /// <param name="source"></param>
  436. /// <param name="destination"></param>
  437. public static void CopyMaterialPresetProperties(Material source, Material destination)
  438. {
  439. if (!source.HasProperty(ShaderUtilities.ID_GradientScale) || !destination.HasProperty(ShaderUtilities.ID_GradientScale))
  440. return;
  441. // Save unique material properties
  442. Texture dst_texture = destination.GetTexture(ShaderUtilities.ID_MainTex);
  443. float dst_gradientScale = destination.GetFloat(ShaderUtilities.ID_GradientScale);
  444. float dst_texWidth = destination.GetFloat(ShaderUtilities.ID_TextureWidth);
  445. float dst_texHeight = destination.GetFloat(ShaderUtilities.ID_TextureHeight);
  446. float dst_weightNormal = destination.GetFloat(ShaderUtilities.ID_WeightNormal);
  447. float dst_weightBold = destination.GetFloat(ShaderUtilities.ID_WeightBold);
  448. // Copy all material properties
  449. destination.CopyPropertiesFromMaterial(source);
  450. // Copy shader keywords
  451. destination.shaderKeywords = source.shaderKeywords;
  452. // Restore unique material properties
  453. destination.SetTexture(ShaderUtilities.ID_MainTex, dst_texture);
  454. destination.SetFloat(ShaderUtilities.ID_GradientScale, dst_gradientScale);
  455. destination.SetFloat(ShaderUtilities.ID_TextureWidth, dst_texWidth);
  456. destination.SetFloat(ShaderUtilities.ID_TextureHeight, dst_texHeight);
  457. destination.SetFloat(ShaderUtilities.ID_WeightNormal, dst_weightNormal);
  458. destination.SetFloat(ShaderUtilities.ID_WeightBold, dst_weightBold);
  459. }
  460. #if TMP_DEBUG_MODE
  461. /// <summary>
  462. ///
  463. /// </summary>
  464. public static void ListMaterials()
  465. {
  466. if (m_materialList.Count() == 0)
  467. {
  468. Debug.Log("Material List is empty.");
  469. return;
  470. }
  471. //Debug.Log("List contains " + m_materialList.Count() + " items.");
  472. for (int i = 0; i < m_materialList.Count(); i++)
  473. {
  474. Material baseMaterial = m_materialList[i].baseMaterial;
  475. Material stencilMaterial = m_materialList[i].stencilMaterial;
  476. 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).");
  477. }
  478. }
  479. /// <summary>
  480. ///
  481. /// </summary>
  482. public static void ListFallbackMaterials()
  483. {
  484. if (m_fallbackMaterialList.Count() == 0)
  485. {
  486. Debug.Log("Material List is empty.");
  487. return;
  488. }
  489. Debug.Log("List contains " + m_fallbackMaterialList.Count() + " items.");
  490. for (int i = 0; i < m_fallbackMaterialList.Count(); i++)
  491. {
  492. Material baseMaterial = m_fallbackMaterialList[i].baseMaterial;
  493. Material fallbackMaterial = m_fallbackMaterialList[i].fallbackMaterial;
  494. 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).");
  495. }
  496. }
  497. #endif
  498. }
  499. }