using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using SharpGLTF.Geometry; using SharpGLTF.Geometry.VertexTypes; using SharpGLTF.Materials; using SharpGLTF.Schema2; namespace GltfExporter2 { public class GltfExporter2 { public static void ExportGltf(string pathToFile, Object3DGroup object3DGroup) { // create a new gltf model var model = ModelRoot.CreateModel(); var geometryIndex = 0; object3DGroup.ForeachMaterialObject(delegate(MaterialObejct3D materialObject3D, object context) { var diffuse = materialObject3D.Material.Diffuse; var diffuseR = diffuse.R / 255.0f; var diffuseG = diffuse.G / 255.0f; var diffuseB = diffuse.B / 255.0f; var diffuseA = diffuse.A / 255.0f; var gltfMaterial = new MaterialBuilder() .WithDoubleSide(true) .WithMetallicRoughnessShader() .WithChannelParam("BaseColor", new Vector4(diffuseR, diffuseG, diffuseB, diffuseA)); var mesh = new MeshBuilder("mesh"); var primitive = mesh.UsePrimitive(gltfMaterial); var viSoftGeometry = materialObject3D.Geometry; for (var index = 0; index < viSoftGeometry.Indexes.Count; index += 3) { var index1 = viSoftGeometry.Indexes[index]; var index2 = viSoftGeometry.Indexes[index + 1]; var index3 = viSoftGeometry.Indexes[index + 2]; var coordinate1 = viSoftGeometry.Coords[index1]; var coordinate2 = viSoftGeometry.Coords[index2]; var coordinate3 = viSoftGeometry.Coords[index3]; var normal1 = viSoftGeometry.Normals[index1]; var normal2= viSoftGeometry.Normals[index2]; var normal3 = viSoftGeometry.Normals[index3]; //primitive.AddTriangle(new VertexPosition(coordinate1.X, coordinate1.Y, coordinate1.Z), // new VertexPosition(coordinate2.X, coordinate2.Y, coordinate2.Z), // new VertexPosition(coordinate3.X, coordinate3.Y, coordinate3.Z)); var vertexPositionNormal1 = new Vertex { Geometry = { Normal = new Vector3(normal1.X, normal1.Y, normal1.Z), Position = new Vector3(coordinate1.X, coordinate1.Y, coordinate1.Z) } }; var vertexPositionNormal2 = new Vertex { Geometry = { Normal = new Vector3(normal2.X, normal2.Y, normal2.Z), Position = new Vector3(coordinate2.X, coordinate2.Y, coordinate2.Z) } }; var vertexPositionNormal3 = new Vertex { Geometry = { Normal = new Vector3(normal3.X, normal3.Y, normal3.Z), Position = new Vector3(coordinate3.X, coordinate3.Y, coordinate3.Z) } }; primitive.AddTriangle(vertexPositionNormal1, vertexPositionNormal2, vertexPositionNormal3); } // add all meshes (just one in this case) to the model model.CreateMeshes(mesh); // create a scene, a node, and assign the first mesh model.UseScene("Default") .CreateNode() .WithMesh(model.LogicalMeshes[geometryIndex]); geometryIndex++; }, null); // // save the model in different formats model.SaveGLTF(@"d:\test.gltf", Formatting.Indented); } } }