ResourceManager.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Microsoft.Xna.Framework;
  5. using Microsoft.Xna.Framework.Graphics;
  6. namespace SharpGLTF.Runtime
  7. {
  8. class GraphicsResourceTracker
  9. {
  10. #region data
  11. private readonly List<GraphicsResource> _Disposables = new List<GraphicsResource>();
  12. #endregion
  13. #region properties
  14. public IReadOnlyList<GraphicsResource> Disposables => _Disposables;
  15. #endregion
  16. #region API
  17. public void AddDisposable(GraphicsResource resource)
  18. {
  19. if (resource == null) throw new ArgumentNullException();
  20. if (_Disposables.Contains(resource)) throw new ArgumentException();
  21. _Disposables.Add(resource);
  22. }
  23. #endregion
  24. }
  25. class TextureFactory
  26. {
  27. #region lifecycle
  28. public TextureFactory(GraphicsDevice device, GraphicsResourceTracker disposables)
  29. {
  30. _Device = device;
  31. _Disposables = disposables;
  32. }
  33. #endregion
  34. #region data
  35. private readonly GraphicsDevice _Device;
  36. private readonly GraphicsResourceTracker _Disposables;
  37. private readonly Dictionary<IReadOnlyList<Byte>, Texture2D> _Textures = new Dictionary<IReadOnlyList<byte>, Texture2D>(new ArraySegmentContentComparer());
  38. #endregion
  39. #region API
  40. public Texture2D UseTexture(ArraySegment<Byte> data, string name = null)
  41. {
  42. if (_Device == null) throw new InvalidOperationException();
  43. if (data.Count == 0) return null;
  44. if (_Textures.TryGetValue(data, out Texture2D tex)) return tex;
  45. using (var m = new System.IO.MemoryStream(data.Array, data.Offset, data.Count, false))
  46. {
  47. tex = Texture2D.FromStream(_Device, m);
  48. _Disposables.AddDisposable(tex);
  49. tex.Name = name;
  50. _Textures[data] = tex;
  51. return tex;
  52. }
  53. }
  54. public Texture2D UseWhiteImage()
  55. {
  56. const string solidWhitePNg = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAACXBIWXMAAA7DAAAOwwHHb6hkAAAAFHpUWHRUaXRsZQAACJkrz8gsSQUABoACIippo0oAAAAoelRYdEF1dGhvcgAACJkLy0xOzStJVQhIzUtMSS1WcCzKTc1Lzy8BAG89CQyAoFAQAAAAGklEQVQoz2P8//8/AymAiYFEMKphVMPQ0QAAVW0DHZ8uFaIAAAAASUVORK5CYII=";
  57. var toBytes = Convert.FromBase64String(solidWhitePNg);
  58. return UseTexture(new ArraySegment<byte>(toBytes), "_InternalSolidWhite");
  59. }
  60. #endregion
  61. #region types
  62. private class ArraySegmentContentComparer : IEqualityComparer<IReadOnlyList<Byte>>
  63. {
  64. public bool Equals(IReadOnlyList<byte> x, IReadOnlyList<byte> y)
  65. {
  66. return Enumerable.SequenceEqual(x, y);
  67. }
  68. public int GetHashCode(IReadOnlyList<byte> obj)
  69. {
  70. var h = 0;
  71. for (int i = 0; i < obj.Count; ++i)
  72. {
  73. h ^= obj[i].GetHashCode();
  74. h *= 17;
  75. }
  76. return h;
  77. }
  78. }
  79. #endregion
  80. }
  81. class MaterialFactory
  82. {
  83. #region lifecycle
  84. public MaterialFactory(GraphicsDevice device, GraphicsResourceTracker disposables)
  85. {
  86. _Device = device;
  87. _TexFactory = new TextureFactory(device, disposables);
  88. _Disposables = disposables;
  89. }
  90. #endregion
  91. #region data
  92. private readonly GraphicsDevice _Device;
  93. private readonly TextureFactory _TexFactory;
  94. private readonly GraphicsResourceTracker _Disposables;
  95. private readonly Dictionary<Object, Effect> _StaticEffects = new Dictionary<Object, Effect>();
  96. private readonly Dictionary<Object, SkinnedEffect> _SkinnedEffects = new Dictionary<Object, SkinnedEffect>();
  97. private BasicEffect _DefaultStatic;
  98. private SkinnedEffect _DefaultSkinned;
  99. #endregion
  100. #region API - Schema
  101. // Monogame's BasicEffect uses Phong's shading, while glTF uses PBR shading, so
  102. // given monogame's limitations, we try to guess the most appropiate values
  103. // to have a reasonably good looking renders.
  104. public Effect UseStaticEffect(Schema2.Material srcMaterial)
  105. {
  106. if (_Device == null) throw new InvalidOperationException();
  107. if (srcMaterial == null)
  108. {
  109. if (_DefaultStatic == null)
  110. {
  111. _DefaultStatic = new BasicEffect(_Device);
  112. _Disposables.AddDisposable(_DefaultStatic);
  113. }
  114. return _DefaultStatic;
  115. }
  116. if (_StaticEffects.TryGetValue(srcMaterial, out Effect dstMaterial)) return dstMaterial;
  117. dstMaterial = srcMaterial.Alpha == Schema2.AlphaMode.MASK ? CreateAlphaTestEffect(srcMaterial) : CreateBasicEffect(srcMaterial);
  118. _StaticEffects[srcMaterial] = dstMaterial;
  119. return dstMaterial;
  120. }
  121. private Effect CreateBasicEffect(Schema2.Material srcMaterial)
  122. {
  123. var dstMaterial = new BasicEffect(_Device);
  124. _Disposables.AddDisposable(dstMaterial);
  125. dstMaterial.Name = srcMaterial.Name;
  126. dstMaterial.Alpha = GetAlphaLevel(srcMaterial);
  127. dstMaterial.DiffuseColor = GetDiffuseColor(srcMaterial);
  128. dstMaterial.SpecularColor = GetSpecularColor(srcMaterial);
  129. dstMaterial.SpecularPower = GetSpecularPower(srcMaterial);
  130. dstMaterial.EmissiveColor = GeEmissiveColor(srcMaterial);
  131. dstMaterial.Texture = GetDiffuseTexture(srcMaterial);
  132. if (srcMaterial.Unlit)
  133. {
  134. dstMaterial.EmissiveColor = dstMaterial.DiffuseColor;
  135. dstMaterial.SpecularColor = Vector3.Zero;
  136. dstMaterial.SpecularPower = 16;
  137. }
  138. dstMaterial.PreferPerPixelLighting = true;
  139. dstMaterial.TextureEnabled = dstMaterial.Texture != null;
  140. return dstMaterial;
  141. }
  142. private Effect CreateAlphaTestEffect(Schema2.Material srcMaterial)
  143. {
  144. var dstMaterial = new AlphaTestEffect(_Device);
  145. _Disposables.AddDisposable(dstMaterial);
  146. dstMaterial.Name = srcMaterial.Name;
  147. dstMaterial.Alpha = GetAlphaLevel(srcMaterial);
  148. //dstMaterial.AlphaFunction = CompareFunction.GreaterEqual;
  149. dstMaterial.ReferenceAlpha = (int)(srcMaterial.AlphaCutoff * 255);
  150. dstMaterial.DiffuseColor = GetDiffuseColor(srcMaterial);
  151. dstMaterial.Texture = GetDiffuseTexture(srcMaterial);
  152. return dstMaterial;
  153. }
  154. public Effect UseSkinnedEffect(Schema2.Material srcMaterial)
  155. {
  156. if (_Device == null) throw new InvalidOperationException();
  157. if (srcMaterial == null)
  158. {
  159. if (_DefaultSkinned == null)
  160. {
  161. _DefaultSkinned = new SkinnedEffect(_Device);
  162. _Disposables.AddDisposable(_DefaultStatic);
  163. }
  164. return _DefaultSkinned;
  165. }
  166. if (_SkinnedEffects.TryGetValue(srcMaterial, out SkinnedEffect dstMaterial)) return dstMaterial;
  167. dstMaterial = new SkinnedEffect(_Device);
  168. _SkinnedEffects[srcMaterial] = dstMaterial;
  169. _Disposables.AddDisposable(dstMaterial);
  170. dstMaterial.Name = srcMaterial.Name;
  171. dstMaterial.Alpha = GetAlphaLevel(srcMaterial);
  172. dstMaterial.DiffuseColor = GetDiffuseColor(srcMaterial);
  173. dstMaterial.SpecularColor = GetSpecularColor(srcMaterial);
  174. dstMaterial.SpecularPower = GetSpecularPower(srcMaterial);
  175. dstMaterial.EmissiveColor = GeEmissiveColor(srcMaterial);
  176. dstMaterial.Texture = GetDiffuseTexture(srcMaterial);
  177. dstMaterial.WeightsPerVertex = 4;
  178. dstMaterial.PreferPerPixelLighting = true;
  179. // apparently, SkinnedEffect does not support disabling textures, so we set a white texture here.
  180. if (dstMaterial.Texture == null) dstMaterial.Texture = _TexFactory.UseWhiteImage();
  181. return dstMaterial;
  182. }
  183. private static float GetAlphaLevel(Schema2.Material srcMaterial)
  184. {
  185. if (srcMaterial.Alpha == Schema2.AlphaMode.OPAQUE) return 1;
  186. var baseColor = srcMaterial.FindChannel("BaseColor");
  187. if (baseColor == null) return 1;
  188. return baseColor.Value.Parameter.W;
  189. }
  190. private static Vector3 GetDiffuseColor(Schema2.Material srcMaterial)
  191. {
  192. var diffuse = srcMaterial.FindChannel("BaseColor");
  193. if (diffuse == null) return Vector3.One;
  194. return new Vector3(diffuse.Value.Parameter.X, diffuse.Value.Parameter.Y, diffuse.Value.Parameter.Z);
  195. }
  196. private static Vector3 GetSpecularColor(Schema2.Material srcMaterial)
  197. {
  198. var mr = srcMaterial.FindChannel("MetallicRoughness");
  199. if (mr == null) return Vector3.One; // default value 16
  200. var diffuse = GetDiffuseColor(srcMaterial);
  201. var metallic = mr.Value.Parameter.X;
  202. var roughness = mr.Value.Parameter.Y;
  203. var k = Vector3.Zero;
  204. k += Vector3.Lerp(diffuse, Vector3.Zero, roughness);
  205. k += Vector3.Lerp(diffuse, Vector3.One, metallic);
  206. k *= 0.5f;
  207. return k;
  208. }
  209. private static float GetSpecularPower(Schema2.Material srcMaterial)
  210. {
  211. var mr = srcMaterial.FindChannel("MetallicRoughness");
  212. if (mr == null) return 16; // default value = 16
  213. var metallic = mr.Value.Parameter.X;
  214. var roughness = mr.Value.Parameter.Y;
  215. return 4 + 16 * metallic;
  216. }
  217. private static Vector3 GeEmissiveColor(Schema2.Material srcMaterial)
  218. {
  219. var emissive = srcMaterial.FindChannel("Emissive");
  220. if (emissive == null) return Vector3.Zero;
  221. return new Vector3(emissive.Value.Parameter.X, emissive.Value.Parameter.Y, emissive.Value.Parameter.Z);
  222. }
  223. private Texture2D GetDiffuseTexture(Schema2.Material srcMaterial)
  224. {
  225. var diffuse = srcMaterial.FindChannel("BaseColor");
  226. if (diffuse == null) return null;
  227. var name = srcMaterial.Name;
  228. if (name == null) name = "null";
  229. name += "-Diffuse";
  230. return _TexFactory.UseTexture(diffuse.Value.Texture?.PrimaryImage?.GetImageContent() ?? default, name);
  231. }
  232. #endregion
  233. }
  234. }