LoadSampleTests.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using NUnit.Framework;
  6. namespace SharpGLTF.Schema2.LoadAndSave
  7. {
  8. /// <summary>
  9. /// Test cases for models found in <see href="https://github.com/KhronosGroup/glTF-Sample-Models"/> and more....
  10. /// </summary>
  11. [TestFixture]
  12. [Category("Model Load and Save")]
  13. public class LoadSampleTests
  14. {
  15. #region setup
  16. [OneTimeSetUp]
  17. public void Setup()
  18. {
  19. // TestFiles.DownloadReferenceModels();
  20. }
  21. #endregion
  22. #region helpers
  23. private static void _LoadModel(string f, bool tryFix = false)
  24. {
  25. var perf = System.Diagnostics.Stopwatch.StartNew();
  26. ModelRoot model = null;
  27. try
  28. {
  29. var settings = tryFix ? Validation.ValidationMode.TryFix : Validation.ValidationMode.Strict;
  30. model = ModelRoot.Load(f, settings);
  31. Assert.NotNull(model);
  32. }
  33. catch (Exception ex)
  34. {
  35. TestContext.Progress.WriteLine($"Failed {f.ToShortDisplayPath()}");
  36. Assert.Fail(ex.Message);
  37. }
  38. var perf_load = perf.ElapsedMilliseconds;
  39. // do a model clone and compare it
  40. _AssertAreEqual(model, model.DeepClone());
  41. var perf_clone = perf.ElapsedMilliseconds;
  42. var unsupportedExtensions = new[] { "MSFT_lod", "EXT_lights_image_based" };
  43. // check extensions used
  44. if (unsupportedExtensions.All(uex => !model.ExtensionsUsed.Contains(uex)))
  45. {
  46. var detectedExtensions = model.RetrieveUsedExtensions().ToArray();
  47. CollectionAssert.AreEquivalent(model.ExtensionsUsed, detectedExtensions);
  48. }
  49. // Save models
  50. model.AttachToCurrentTest(System.IO.Path.ChangeExtension(System.IO.Path.GetFileName(f), ".obj"));
  51. var perf_wavefront = perf.ElapsedMilliseconds;
  52. model.AttachToCurrentTest(System.IO.Path.ChangeExtension(System.IO.Path.GetFileName(f), ".glb"));
  53. var perf_glb = perf.ElapsedMilliseconds;
  54. TestContext.Progress.WriteLine($"processed {f.ToShortDisplayPath()} - Load:{perf_load}ms Clone:{perf_clone}ms S.obj:{perf_wavefront}ms S.glb:{perf_glb}ms");
  55. }
  56. private static void _AssertAreEqual(ModelRoot a, ModelRoot b)
  57. {
  58. var aa = a.GetLogicalChildrenFlattened().ToList();
  59. var bb = b.GetLogicalChildrenFlattened().ToList();
  60. Assert.AreEqual(aa.Count, bb.Count);
  61. CollectionAssert.AreEqual
  62. (
  63. aa.Select(item => item.GetType()),
  64. bb.Select(item => item.GetType())
  65. );
  66. }
  67. #endregion
  68. [TestCase("\\glTF\\")]
  69. // [TestCase("\\glTF-Draco\\")] // Not supported
  70. [TestCase("\\glTF-IBL\\")]
  71. [TestCase("\\glTF-Binary\\")]
  72. [TestCase("\\glTF-Embedded\\")]
  73. [TestCase("\\glTF-pbrSpecularGlossiness\\")]
  74. public void LoadModelsFromKhronosSamples(string section)
  75. {
  76. TestContext.CurrentContext.AttachShowDirLink();
  77. TestContext.CurrentContext.AttachGltfValidatorLinks();
  78. foreach (var f in TestFiles.GetSampleModelsPaths())
  79. {
  80. if (!f.Contains(section)) continue;
  81. _LoadModel(f);
  82. }
  83. }
  84. [Test]
  85. public void LoadModelsFromBabylonJs()
  86. {
  87. TestContext.CurrentContext.AttachShowDirLink();
  88. TestContext.CurrentContext.AttachGltfValidatorLinks();
  89. foreach (var f in TestFiles.GetBabylonJSValidModelsPaths())
  90. {
  91. TestContext.Progress.WriteLine(f);
  92. _LoadModel(f, true);
  93. }
  94. }
  95. [Test]
  96. public void LoadInvalidModelsFromBabylonJs()
  97. {
  98. TestContext.CurrentContext.AttachShowDirLink();
  99. TestContext.CurrentContext.AttachGltfValidatorLinks();
  100. foreach (var f in TestFiles.GetBabylonJSInvalidModelsPaths())
  101. {
  102. TestContext.Progress.WriteLine(f);
  103. try
  104. {
  105. var model = ModelRoot.Load(f);
  106. Assert.Fail("Should throw");
  107. }
  108. catch(Exception ex)
  109. {
  110. TestContext.WriteLine(ex.Message);
  111. }
  112. }
  113. }
  114. [TestCase("SpecGlossVsMetalRough.gltf")]
  115. [TestCase(@"TextureTransformTest.gltf")]
  116. [TestCase(@"UnlitTest\glTF-Binary\UnlitTest.glb")]
  117. public void LoadModelsWithExtensions(string filePath)
  118. {
  119. TestContext.CurrentContext.AttachShowDirLink();
  120. TestContext.CurrentContext.AttachGltfValidatorLinks();
  121. filePath = TestFiles
  122. .GetSampleModelsPaths()
  123. .FirstOrDefault(item => item.EndsWith(filePath));
  124. var model = ModelRoot.Load(filePath);
  125. Assert.NotNull(model);
  126. // do a model clone and compare it
  127. _AssertAreEqual(model, model.DeepClone());
  128. // evaluate and save all the triangles to a Wavefront Object
  129. filePath = System.IO.Path.GetFileNameWithoutExtension(filePath);
  130. model.AttachToCurrentTest(filePath + "_wf.obj");
  131. model.AttachToCurrentTest(filePath + ".glb");
  132. model.AttachToCurrentTest(filePath + ".gltf");
  133. }
  134. [Test]
  135. public void LoadModelWithUnlitMaterial()
  136. {
  137. var f = TestFiles
  138. .GetSampleModelsPaths()
  139. .FirstOrDefault(item => item.EndsWith(@"UnlitTest\glTF-Binary\UnlitTest.glb"));
  140. var model = ModelRoot.Load(f);
  141. Assert.NotNull(model);
  142. Assert.IsTrue(model.LogicalMaterials[0].Unlit);
  143. // do a model roundtrip
  144. var modelBis = ModelRoot.ParseGLB(model.WriteGLB());
  145. Assert.NotNull(modelBis);
  146. Assert.IsTrue(modelBis.LogicalMaterials[0].Unlit);
  147. }
  148. [Test]
  149. public void LoadModelWithLights()
  150. {
  151. var f = TestFiles
  152. .GetSchemaExtensionsModelsPaths()
  153. .FirstOrDefault(item => item.EndsWith("lights.gltf"));
  154. var model = ModelRoot.Load(f);
  155. Assert.NotNull(model);
  156. Assert.AreEqual(3, model.LogicalPunctualLights.Count);
  157. Assert.AreEqual(1, model.DefaultScene.VisualChildren.ElementAt(0).PunctualLight.LogicalIndex);
  158. Assert.AreEqual(0, model.DefaultScene.VisualChildren.ElementAt(1).PunctualLight.LogicalIndex);
  159. }
  160. [Test]
  161. public void LoadModelWithSparseAccessor()
  162. {
  163. var path = TestFiles
  164. .GetSampleModelsPaths()
  165. .FirstOrDefault(item => item.Contains("SimpleSparseAccessor.gltf"));
  166. var model = ModelRoot.Load(path);
  167. Assert.NotNull(model);
  168. var primitive = model.LogicalMeshes[0].Primitives[0];
  169. var accessor = primitive.GetVertexAccessor("POSITION");
  170. var basePositions = accessor._GetMemoryAccessor().AsVector3Array();
  171. var positions = accessor.AsVector3Array();
  172. }
  173. [Test]
  174. public void LoadModelWithMorphTargets()
  175. {
  176. TestContext.CurrentContext.AttachShowDirLink();
  177. var path = TestFiles
  178. .GetSampleModelsPaths()
  179. .FirstOrDefault(item => item.Contains("MorphPrimitivesTest.glb"));
  180. var model = ModelRoot.Load(path);
  181. Assert.NotNull(model);
  182. var triangles = model.DefaultScene
  183. .EvaluateTriangles<Geometry.VertexTypes.VertexPosition, Geometry.VertexTypes.VertexEmpty>(null, 0)
  184. .ToArray();
  185. model.AttachToCurrentTest(System.IO.Path.ChangeExtension(System.IO.Path.GetFileName(path), ".obj"));
  186. model.AttachToCurrentTest(System.IO.Path.ChangeExtension(System.IO.Path.GetFileName(path), ".glb"));
  187. }
  188. [TestCase("RiggedFigure.glb")]
  189. [TestCase("RiggedSimple.glb")]
  190. [TestCase("BoxAnimated.glb")]
  191. [TestCase("AnimatedMorphCube.glb")]
  192. [TestCase("AnimatedMorphSphere.glb")]
  193. [TestCase("CesiumMan.glb")]
  194. //[TestCase("Monster.glb")] // temporarily removed from khronos repo
  195. [TestCase("BrainStem.glb")]
  196. [TestCase("Fox.glb")]
  197. public void LoadModelsWithAnimations(string path)
  198. {
  199. TestContext.CurrentContext.AttachShowDirLink();
  200. path = TestFiles
  201. .GetSampleModelsPaths()
  202. .FirstOrDefault(item => item.Contains(path));
  203. var model = ModelRoot.Load(path);
  204. Assert.NotNull(model);
  205. path = System.IO.Path.GetFileNameWithoutExtension(path);
  206. model.AttachToCurrentTest(path + ".glb");
  207. var triangles = model.DefaultScene
  208. .EvaluateTriangles<Geometry.VertexTypes.VertexPosition, Geometry.VertexTypes.VertexEmpty>()
  209. .ToArray();
  210. var anim = model.LogicalAnimations[0];
  211. var duration = anim.Duration;
  212. for(int i=0; i < 10; ++i)
  213. {
  214. var t = duration * i / 10;
  215. int tt = (int)(t * 1000.0f);
  216. model.AttachToCurrentTest($"{path} at {tt}.obj",anim, t);
  217. }
  218. }
  219. [Test]
  220. public void LoadAnimatedMorphCube()
  221. {
  222. TestContext.CurrentContext.AttachShowDirLink();
  223. var path = TestFiles
  224. .GetSampleModelsPaths()
  225. .FirstOrDefault(item => item.Contains("AnimatedMorphCube.glb"));
  226. var model = ModelRoot.Load(path);
  227. Assert.NotNull(model);
  228. var anim = model.LogicalAnimations[0];
  229. var node = model.LogicalNodes[0];
  230. var acc_master = node.Mesh.Primitives[0].GetVertexAccessor("POSITION");
  231. var acc_morph0 = node.Mesh.Primitives[0].GetMorphTargetAccessors(0)["POSITION"];
  232. var acc_morph1 = node.Mesh.Primitives[0].GetMorphTargetAccessors(1)["POSITION"];
  233. var pos_master = acc_master.AsVector3Array();
  234. var pos_morph0 = acc_morph0.AsVector3Array();
  235. var pos_morph1 = acc_morph1.AsVector3Array();
  236. // pos_master
  237. var instance = Runtime.SceneTemplate
  238. .Create(model.DefaultScene, false)
  239. .CreateInstance();
  240. var pvrt = node.Mesh.Primitives[0].GetVertexColumns();
  241. for (float t = 0; t < 5; t+=0.25f)
  242. {
  243. instance.SetAnimationFrame(anim.LogicalIndex, t);
  244. var nodexform = instance.GetDrawableInstance(0).Transform;
  245. TestContext.WriteLine($"Animation at {t}");
  246. if (t < anim.Duration)
  247. {
  248. var mw = anim.GetMorphWeights(node, t);
  249. TestContext.WriteLine($" Morph Weights: {mw[0]} {mw[1]}");
  250. }
  251. var msw = anim.GetSparseMorphWeights(node, t);
  252. TestContext.WriteLine($" Morph Sparse : {msw.Weight0} {msw.Weight1}");
  253. var triangles = model.DefaultScene
  254. .EvaluateTriangles<Geometry.VertexTypes.VertexPosition, Geometry.VertexTypes.VertexEmpty>(anim, t)
  255. .ToList();
  256. var vertices = triangles
  257. .SelectMany(item => new[] { item.A.Position, item.B.Position, item.C.Position })
  258. .Distinct()
  259. .ToList();
  260. foreach (var v in vertices) TestContext.WriteLine($"{v}");
  261. TestContext.WriteLine();
  262. }
  263. }
  264. [Test]
  265. public void FindDependencyFiles()
  266. {
  267. TestContext.CurrentContext.AttachShowDirLink();
  268. TestContext.CurrentContext.AttachGltfValidatorLinks();
  269. foreach (var f in TestFiles.GetBabylonJSValidModelsPaths())
  270. {
  271. TestContext.WriteLine(f);
  272. var dependencies = ModelRoot.GetSatellitePaths(f);
  273. foreach(var d in dependencies)
  274. {
  275. TestContext.WriteLine($" {d}");
  276. }
  277. TestContext.WriteLine();
  278. }
  279. }
  280. }
  281. }