LoadSpecialModelsTest.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Numerics;
  5. using System.Text;
  6. using NUnit.Framework;
  7. namespace SharpGLTF.Schema2.LoadAndSave
  8. {
  9. /// <summary>
  10. /// Test cases for models found in <see href="https://github.com/KhronosGroup/glTF-Blender-Exporter"/>
  11. /// </summary>
  12. [TestFixture]
  13. [AttachmentPathFormat("*/TestResults/LoadAndSave/?")]
  14. [Category("Model Load and Save")]
  15. public class LoadSpecialModelsTest
  16. {
  17. #region setup
  18. [OneTimeSetUp]
  19. public void Setup()
  20. {
  21. // TestFiles.DownloadReferenceModels();
  22. }
  23. #endregion
  24. [Test]
  25. public void LoadEscapedUriModel()
  26. {
  27. TestContext.CurrentContext.AttachShowDirLink();
  28. var path = System.IO.Path.Combine(TestContext.CurrentContext.TestDirectory, "Assets\\white space.gltf");
  29. var model = ModelRoot.Load(path);
  30. Assert.NotNull(model);
  31. model.AttachToCurrentTest("white space.glb");
  32. }
  33. public void LoadWithCustomImageLoader()
  34. {
  35. TestContext.CurrentContext.AttachShowDirLink();
  36. // load Polly model
  37. var model = ModelRoot.Load(TestFiles.GetPollyFileModelPath());
  38. }
  39. [Test(Description = "Example of traversing the visual tree all the way to individual vertices and indices")]
  40. public void LoadPollyModel()
  41. {
  42. TestContext.CurrentContext.AttachShowDirLink();
  43. // load Polly model
  44. var model = ModelRoot.Load(TestFiles.GetPollyFileModelPath(), Validation.ValidationMode.TryFix);
  45. Assert.NotNull(model);
  46. var triangles = model.DefaultScene
  47. .EvaluateTriangles<Geometry.VertexTypes.VertexPosition, Geometry.VertexTypes.VertexTexture1>(null, model.LogicalAnimations[0], 0.5f)
  48. .ToList();
  49. // Save as GLB, and also evaluate all triangles and save as Wavefront OBJ
  50. model.AttachToCurrentTest("polly_out.glb");
  51. model.AttachToCurrentTest("polly_out.obj");
  52. // hierarchically browse some elements of the model:
  53. var scene = model.DefaultScene;
  54. var pollyNode = scene.FindNode(n => n.Name == "Polly_Display");
  55. var pollyPrimitive = pollyNode.Mesh.Primitives[0];
  56. var pollyIndices = pollyPrimitive.GetIndices();
  57. var pollyPositions = pollyPrimitive.GetVertices("POSITION").AsVector3Array();
  58. var pollyNormals = pollyPrimitive.GetVertices("NORMAL").AsVector3Array();
  59. for (int i = 0; i < pollyIndices.Count; i += 3)
  60. {
  61. var a = (int)pollyIndices[i + 0];
  62. var b = (int)pollyIndices[i + 1];
  63. var c = (int)pollyIndices[i + 2];
  64. var ap = pollyPositions[a];
  65. var bp = pollyPositions[b];
  66. var cp = pollyPositions[c];
  67. var an = pollyNormals[a];
  68. var bn = pollyNormals[b];
  69. var cn = pollyNormals[c];
  70. TestContext.WriteLine($"Triangle {ap} {an} {bp} {bn} {cp} {cn}");
  71. }
  72. // create a clone and apply a global axis transform.
  73. var clonedModel = model.DeepClone();
  74. var basisTransform
  75. = Matrix4x4.CreateScale(1, 2, 1)
  76. * Matrix4x4.CreateFromYawPitchRoll(1, 2, 3)
  77. * Matrix4x4.CreateTranslation(10,5,2);
  78. clonedModel.ApplyBasisTransform(basisTransform);
  79. clonedModel.AttachToCurrentTest("polly_out_transformed.glb");
  80. var wsettings = new WriteSettings();
  81. wsettings.ImageWriting = ResourceWriteMode.BufferView;
  82. wsettings.MergeBuffers = true;
  83. wsettings.BuffersMaxSize = 1024 * 1024 * 10;
  84. clonedModel.AttachToCurrentTest("polly_out_merged_10mb.gltf", wsettings);
  85. }
  86. [Test]
  87. public void LoadUniVRM()
  88. {
  89. TestContext.CurrentContext.AttachShowDirLink();
  90. var path = TestFiles.GetUniVRMModelPath();
  91. var model = ModelRoot.Load(path);
  92. Assert.NotNull(model);
  93. var flattenExtensions = model.GatherUsedExtensions().ToArray();
  94. model.AttachToCurrentTest("AliceModel.glb");
  95. }
  96. // [Test]
  97. public void LoadShrekshaoModel()
  98. {
  99. TestContext.CurrentContext.AttachShowDirLink();
  100. var path = "Assets\\SpecialCases\\shrekshao.glb";
  101. var model = ModelRoot.Load(path);
  102. Assert.NotNull(model);
  103. }
  104. [Test]
  105. public void LoadMouseModel()
  106. {
  107. // this model has several nodes with curve animations containing a single animation key,
  108. // which is causing some problems to the interpolator.
  109. TestContext.CurrentContext.AttachShowDirLink();
  110. var path = System.IO.Path.Combine(TestContext.CurrentContext.TestDirectory, "Assets\\SpecialCases\\mouse.glb");
  111. var model = ModelRoot.Load(path);
  112. var boundingSphere = Runtime.MeshDecoder.EvaluateBoundingSphere(model.DefaultScene);
  113. var sampler = model
  114. .LogicalNodes[5]
  115. .GetCurveSamplers(model.LogicalAnimations[1])
  116. .Rotation
  117. .CreateCurveSampler(true);
  118. var node5_R_00 = sampler.GetPoint(0);
  119. var node5_R_01 = sampler.GetPoint(1);
  120. Assert.AreEqual(node5_R_00, node5_R_01);
  121. model.AttachToCurrentTest("mouse_00.obj", model.LogicalAnimations[1], 0f);
  122. model.AttachToCurrentTest("mouse_01.obj", model.LogicalAnimations[1], 1f);
  123. }
  124. [TestCase("SketchfabExport-WhatIsPBR.glb")] // model has exported tangents in the form <0,0,0,1>
  125. public void LoadSketchfabModels(string path)
  126. {
  127. // this model has several nodes with curve animations containing a single animation key,
  128. // which is causing some problems to the interpolator.
  129. TestContext.CurrentContext.AttachShowDirLink();
  130. path = System.IO.Path.Combine(TestContext.CurrentContext.TestDirectory, $"Assets\\SpecialCases\\{path}");
  131. var model = ModelRoot.Load(path, Validation.ValidationMode.TryFix);
  132. model.AttachToCurrentTest("output.glb");
  133. }
  134. // these models show normal mapping but lack tangents, which are expected to be
  135. // generated at runtime; These tests generate the tangents and check them against the baseline.
  136. [TestCase("NormalTangentTest.glb")]
  137. [TestCase("NormalTangentMirrorTest.glb")]
  138. public void LoadGeneratedTangetsTest(string fileName)
  139. {
  140. TestContext.CurrentContext.AttachShowDirLink();
  141. var path = TestFiles.GetSampleModelsPaths().FirstOrDefault(item => item.EndsWith(fileName));
  142. var model = ModelRoot.Load(path);
  143. var mesh = model.DefaultScene
  144. .EvaluateTriangles<Geometry.VertexTypes.VertexPositionNormalTangent, Geometry.VertexTypes.VertexTexture1>()
  145. .ToMeshBuilder();
  146. var editableScene = new Scenes.SceneBuilder();
  147. editableScene.AddRigidMesh(mesh, Matrix4x4.Identity);
  148. model.AttachToCurrentTest("original.glb");
  149. editableScene.ToGltf2().AttachToCurrentTest("WithTangents.glb");
  150. }
  151. [Test]
  152. public void LoadAndSaveToMemory()
  153. {
  154. var path = TestFiles.GetSampleModelsPaths().FirstOrDefault(item => item.EndsWith("Avocado.glb"));
  155. var model = ModelRoot.Load(path);
  156. // model.LogicalImages[0].TransferToSatelliteFile(); // TODO
  157. // we will use this dictionary as our in-memory model container.
  158. var dictionary = new Dictionary<string, ArraySegment<Byte>>();
  159. // write to dictionary
  160. var wcontext = WriteContext.CreateFromDictionary(dictionary);
  161. model.Save("avocado.gltf", wcontext);
  162. Assert.IsTrue(dictionary.ContainsKey("avocado.gltf"));
  163. Assert.IsTrue(dictionary.ContainsKey("avocado.bin"));
  164. // read back from dictionary
  165. var rcontext = ReadContext.CreateFromDictionary(dictionary);
  166. var model2 = ModelRoot.Load("avocado.gltf", rcontext);
  167. // TODO: verify
  168. }
  169. [Test]
  170. public void LoadInvalidModelWithJsonFix()
  171. {
  172. // try to load an invalid gltf with an empty array
  173. var path = System.IO.Path.Combine(TestContext.CurrentContext.TestDirectory, "Assets\\SpecialCases\\Invalid_EmptyArray.gltf");
  174. Assert.Throws<Validation.SchemaException>(() => ModelRoot.Load(path));
  175. // try to load an invalid gltf with an empty array, using a hook to fix the json before running the parser.
  176. var rsettings = new ReadSettings();
  177. rsettings.JsonPreprocessor = _RemoveEmptyArrayJsonProcessor;
  178. var model = ModelRoot.Load(path, rsettings);
  179. Assert.NotNull(model);
  180. // save the model, using a hook to modify the json before writing it to the file.
  181. var wsettings = new WriteSettings();
  182. wsettings.JsonPostprocessor = json =>
  183. {
  184. json = json.Replace("glTF 2.0 Validator test suite", "postprocessed json"); return json;
  185. };
  186. path = model.AttachToCurrentTest("modified.gltf", wsettings);
  187. model = ModelRoot.Load(path);
  188. Assert.AreEqual(model.Asset.Generator, "postprocessed json");
  189. }
  190. private string _RemoveEmptyArrayJsonProcessor(string json)
  191. {
  192. var obj = Newtonsoft.Json.Linq.JObject.Parse(json);
  193. var children = obj.Children().ToArray();
  194. children[1].Remove(); // remove the empty "meshes" array.
  195. json = obj.ToString();
  196. return json;
  197. }
  198. }
  199. }