CreateMeshTests.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Numerics;
  4. using System.Text;
  5. using NUnit.Framework;
  6. namespace SharpGLTF.Geometry
  7. {
  8. using Memory;
  9. [TestFixture]
  10. public class CreateMeshTests
  11. {
  12. [Test]
  13. public void CreateTriangleScene()
  14. {
  15. // define the data of a triangle:
  16. var positions = new[]
  17. {
  18. new Vector3(10,-10,0),
  19. new Vector3(0,10,0),
  20. new Vector3(-10,-10,0)
  21. };
  22. var normals = new[]
  23. {
  24. Vector3.UnitZ,
  25. Vector3.UnitZ,
  26. Vector3.UnitZ
  27. };
  28. var indices = new UInt32[] { 0, 1, 2 };
  29. // create a new mesh:
  30. var srcMesh = new Mesh();
  31. // setup a mesh primitive
  32. var srcPrimitive = srcMesh.CreatePrimitive();
  33. srcPrimitive.AllocateVertices(positions.Length, "POSITION", "NORMAL"); // (#1)
  34. srcPrimitive.AllocateIndices(indices.Length, Schema2.PrimitiveType.TRIANGLES); // (#2)
  35. // assign vertices and indices
  36. srcPrimitive.Vertices[0].SetValues(0, positions);
  37. srcPrimitive.Vertices[1].SetValues(0, normals);
  38. srcPrimitive.Indices.SetValues(0, indices);
  39. srcPrimitive.MaterialLogicalIndex = 0; // using material with index 0, which will be created later
  40. // check the values we've set match the input data
  41. CollectionAssert.AreEqual(positions, srcPrimitive.Vertices[0].AsVector3Array());
  42. CollectionAssert.AreEqual(normals, srcPrimitive.Vertices[1].AsVector3Array());
  43. CollectionAssert.AreEqual(indices, srcPrimitive.Indices.AsIntegerArray());
  44. // Notice that until now, we've been working with objects in the .Geometry namespace.
  45. // Now we switch to the .Schema2 namespace and we create a new scene:
  46. var root = Schema2.ModelRoot.CreateNew();
  47. var scene = root.UseScene("default");
  48. var node = scene.AddVisualNode("main scene");
  49. var material = root.AddLogicalMaterial(typeof(Schema2.MaterialPBRMetallicRoughness));
  50. material.DoubleSided = true;
  51. material.GetChannel("BaseColor")
  52. .SetFactor(new Vector4(1, 0, 0, 1));
  53. node.Mesh = root.CreateMesh();
  54. // this assigns the mesh we've created before to this schema mesh.
  55. // Notice that the schema buffers being created will be using the
  56. // memory allocated by (#1) and (#2)
  57. srcMesh.AssignToSchema(node.Mesh);
  58. root.MergeBuffers();
  59. root.AttachToCurrentTest("Triangle.gltf");
  60. root.AttachToCurrentTest("Triangle.glb");
  61. TestContext.CurrentContext.AttachShowDirLink();
  62. }
  63. }
  64. }