/// <summary> /// Writes a geometrymesh to a file, given a location. /// </summary> /// <param name="type">The geometry mesh.</param> /// <param name="location">The location of the file.</param> public void WriteFile(GeometryMesh type, string location) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (string.IsNullOrEmpty(location)) { throw new ArgumentNullException(nameof(location)); } IOWriteResult result = StandardMeshWriter.WriteMesh( location, type.Base, Options); if (result.code != IOCode.Ok) { throw new G3WriterException(result); } using (StreamWriter writer = File.AppendText(location)) { IOConventions.WriteIfNormalised(type.IsNormalised, writer); } }
/// <summary> /// Writes a geometrymesh to a file, given a streamwriter. /// </summary> /// <param name="type">The geometry mesh.</param> /// <param name="location">The streamwriter.</param> public void WriteFile(GeometryMesh type, StreamWriter writer) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (writer == null) { throw new ArgumentNullException(nameof(writer)); } g3.OFFWriter offWriter = new g3.OFFWriter(); List <WriteMesh> serialisableMeshes = new List <WriteMesh>() { new WriteMesh(type.Base) }; IOWriteResult result = offWriter.Write(writer, serialisableMeshes, Options); if (result.code != IOCode.Ok) { throw new G3WriterException(result); } IOConventions.WriteIfNormalised(type.IsNormalised, writer); }
void ThreadFunc() { Status = StandardMeshWriter.WriteFile(Filename, Meshes, options); if (CompletionF != null) { CompletionF(Status); } }
protected override void Recompute(DGArguments args) { string path = Inputs[0].Value <string>(args); DMesh3 mesh = Inputs[1].Value <DMesh3>(args); StandardMeshWriter writer = new StandardMeshWriter(); IOWriteResult result = writer.Write(path, new List <WriteMesh>() { new WriteMesh(mesh) }, WriteOptions.Defaults); if (result.code != IOCode.Ok) { // what?? } }
protected override void SolveInstance(IGH_DataAccess DA) { this.Message = "." + type.ToString(); DMesh3_goo goo = null; string path = ""; string file = ""; DA.GetData(0, ref goo); DA.GetData(1, ref path); DA.GetData(2, ref file); DMesh3 mesh = new DMesh3(goo.Value); IOWriteResult result = StandardMeshWriter.WriteFile(Path.Combine(path, file) + "." + type.ToString(), new List <WriteMesh>() { new WriteMesh(mesh) }, WriteOptions.Defaults); DA.SetData(0, Path.Combine(path, file) + "." + type.ToString()); }
public IOWriteResult RunBackgroundWrite() { // transform meshes gParallel.ForEach(Interval1i.Range(ExportMeshes.Length), (i) => { if (MeshFrames[i].Origin != Vector3f.Zero || MeshFrames[i].Rotation != Quaternionf.Identity) { MeshTransforms.FromFrame(ExportMeshes[i], MeshFrames[i]); } MeshTransforms.FlipLeftRightCoordSystems(ExportMeshes[i]); if (ExportYUp == false) { MeshTransforms.ConvertYUpToZUp(ExportMeshes[i]); } }); List <WriteMesh> writeMeshes = new List <WriteMesh>(); for (int i = 0; i < ExportMeshes.Length; ++i) { writeMeshes.Add(new WriteMesh(ExportMeshes[i])); } WriteOptions options = WriteOptions.Defaults; options.bWriteBinary = true; options.ProgressFunc = BackgroundProgressFunc; StandardMeshWriter writer = new StandardMeshWriter(); IOWriteResult result = writer.Write(WritePath, writeMeshes, options); return(result); }
void SaveMesh(PlateConfig config, [CallerMemberName] string fileName = null) { var output = Path.Combine(SolutionFolder(), "output"); if (!Directory.Exists(output)) { Directory.CreateDirectory(output); } var plate = new PlateGenerator(config); var meshGenerator = plate.Generate(); var mesh = meshGenerator.MakeSimpleMesh(); fileName = fileName != null ? $"{fileName}.stl" : $"output.stl"; IOWriteResult result = StandardMeshWriter.WriteFile( Path.Combine(output, fileName), new List <WriteMesh>() { new WriteMesh(mesh) }, WriteOptions.Defaults); }
public virtual ExportStatus Export(FScene scene, string filename) { int[] vertexMap = new int[2048]; // temp List <WriteMesh> vMeshes = new List <WriteMesh>(); if (WriteFaceGroups) { throw new Exception("SceneMeshExporter.Export: writing face groups has not yet been implemented!"); } // extract all the mesh data we want to export foreach (SceneObject so in scene.SceneObjects) { if (so.IsTemporary || so.IsSurface == false || SceneUtil.IsVisible(so) == false) { continue; } if (SOFilterF != null && SOFilterF(so) == false) { continue; } // if this SO has an internal mesh we can just copy, use it if (so is DMeshSO) { DMeshSO meshSO = so as DMeshSO; // todo: flags // make a copy of mesh DMesh3 m = new DMesh3(meshSO.Mesh, true); // transform to scene coords and swap left/right foreach (int vid in m.VertexIndices()) { Vector3f v = (Vector3f)m.GetVertex(vid); v = SceneTransforms.ObjectToScene(meshSO, v); v = UnityUtil.SwapLeftRight(v); m.SetVertex(vid, v); } m.ReverseOrientation(); vMeshes.Add(new WriteMesh(m, so.Name)); } // Look for lower-level fGameObject items to export. By default // this is anything with a MeshFilter, override CollectGOChildren // or use GOFilterF to add restrictions List <fGameObject> vExports = CollectGOChildren(so); if (vExports.Count > 0) { SimpleMesh m = new SimpleMesh(); m.Initialize(WriteNormals, WriteVertexColors, WriteUVs, WriteFaceGroups); int groupCounter = 1; foreach (fGameObject childgo in vExports) { if (GOFilterF != null && GOFilterF(so, childgo) == false) { continue; } if (AppendGOMesh(childgo, m, vertexMap, scene, groupCounter)) { groupCounter++; } } vMeshes.Add(new WriteMesh(m, so.Name)); } } // ok, we are independent of Scene now and can write in bg thread if (WriteInBackgroundThreads) { ExportStatus status = new ExportStatus() { Exporter = this, IsComputing = true }; WriteOptions useOptions = Options; useOptions.ProgressFunc = (cur, max) => { status.Progress = cur; status.MaxProgress = max; }; BackgroundWriteThread t = new BackgroundWriteThread() { Meshes = vMeshes, options = useOptions, Filename = filename, CompletionF = (result) => { LastWriteStatus = result.code; LastErrorMessage = result.message; status.LastErrorMessage = result.message; status.Ok = (result.code == IOCode.Ok); status.IsComputing = false; if (BackgroundWriteCompleteF != null) { BackgroundWriteCompleteF(this, status); } } }; t.Start(); return(status); } else { IOWriteResult result = StandardMeshWriter.WriteFile(filename, vMeshes, Options); LastWriteStatus = result.code; LastErrorMessage = result.message; return(new ExportStatus() { Exporter = this, IsComputing = false, Ok = (result.code == IOCode.Ok), LastErrorMessage = result.message }); } }
/// <summary> /// Initialises a new instance of the <see cref="G3WriterException"/> class, /// which specifies that a problem occured in an external writer. /// </summary> /// <param name="result">The error message provided by the other writer.</param> /// <param name="innerException"> /// The exception that is the cause of the current exception. If the innerException /// parameter is not null, the current exception is raised in a catch block that /// handles the inner exception. /// </param> public G3WriterException(IOWriteResult result, Exception innerException) : this(result.message, innerException) { Result = result; }
/// <summary> /// Initialises a new instance of the <see cref="G3WriterException"/> class, /// which specifies that a problem occured in an external writer. /// </summary> /// <param name="result">The error message provided by the other writer.</param> public G3WriterException(IOWriteResult result) : this(result, null) { }
protected G3WriterException(SerializationInfo info, StreamingContext context) : base(info, context) { Result = info.GetValue <IOWriteResult>(serCode); }
public ExportStatus Export(FScene s, string filename) { List <WriteMesh> vMeshes = new List <WriteMesh>(); if (WriteFaceGroups) { throw new Exception("SceneMeshExporter.Export: writing face groups has not yet been implemented!"); } foreach (SceneObject so in s.SceneObjects) { if (so.IsTemporary) { continue; } SimpleMesh m = new SimpleMesh(); m.Initialize(WriteNormals, WriteVertexColors, WriteUVs, WriteFaceGroups); int groupCounter = 1; GameObject rootgo = so.RootGameObject; int[] vertexMap = new int[2048]; foreach (GameObject childgo in rootgo.Children()) { MeshFilter filter = childgo.GetComponent <MeshFilter>(); if (filter == null || filter.mesh == null) { continue; } if (GOFilterF != null && GOFilterF(so, childgo) == false) { continue; } Mesh curMesh = filter.sharedMesh; Vector3[] vertices = curMesh.vertices; Vector3[] normals = (WriteNormals) ? curMesh.normals : null; Color[] colors = (WriteVertexColors) ? curMesh.colors : null; Vector2[] uvs = (WriteUVs) ? curMesh.uv : null; if (vertexMap.Length < curMesh.vertexCount) { vertexMap = new int[curMesh.vertexCount * 2]; } for (int i = 0; i < curMesh.vertexCount; ++i) { NewVertexInfo vi = new NewVertexInfo(); vi.bHaveN = WriteNormals; vi.bHaveC = WriteVertexColors; vi.bHaveUV = WriteUVs; Vector3 v = vertices[i]; // local to world v = filter.gameObject.transform.TransformPoint(v); // world back to scene vi.v = UnityUtil.SwapLeftRight(s.RootGameObject.transform.InverseTransformPoint(v)); if (WriteNormals) { Vector3 n = normals[i]; n = filter.gameObject.transform.TransformDirection(n); vi.n = UnityUtil.SwapLeftRight(s.RootGameObject.transform.InverseTransformDirection(n)); } if (WriteVertexColors) { vi.c = colors[i]; } if (WriteUVs) { vi.uv = uvs[i]; } vertexMap[i] = m.AppendVertex(vi); } int[] triangles = curMesh.triangles; int nTriangles = triangles.Length / 3; for (int i = 0; i < nTriangles; ++i) { int a = vertexMap[triangles[3 * i]]; int b = vertexMap[triangles[3 * i + 1]]; int c = vertexMap[triangles[3 * i + 2]]; m.AppendTriangle(a, c, b, groupCounter); // TRI ORIENTATION IS REVERSED HERE!! } groupCounter++; } vMeshes.Add(new WriteMesh(m, so.Name)); } if (WriteInBackgroundThreads) { ExportStatus status = new ExportStatus() { Exporter = this, IsComputing = true }; WriteOptions useOptions = Options; useOptions.ProgressFunc = (cur, max) => { status.Progress = cur; status.MaxProgress = max; }; BackgroundWriteThread t = new BackgroundWriteThread() { Meshes = vMeshes, options = useOptions, Filename = filename, CompletionF = (result) => { LastWriteStatus = result.code; LastErrorMessage = result.message; status.LastErrorMessage = result.message; status.Ok = (result.code == IOCode.Ok); status.IsComputing = false; } }; t.Start(); return(status); } else { IOWriteResult result = StandardMeshWriter.WriteFile(filename, vMeshes, Options); LastWriteStatus = result.code; LastErrorMessage = result.message; return(new ExportStatus() { Exporter = this, IsComputing = false, Ok = (result.code == IOCode.Ok), LastErrorMessage = result.message }); } }
// // [TODO] // static void Main(string[] args) { CommandArgumentSet arguments = new CommandArgumentSet(); arguments.Register("-output", ""); if (arguments.Parse(args) == false) { return; } if (arguments.Filenames.Count != 1) { print_usage(); return; } string sInputFile = arguments.Filenames[0]; string sFilenameRoot = Path.GetFileNameWithoutExtension(sInputFile); if (!File.Exists(sInputFile)) { System.Console.WriteLine("cannot find file " + sInputFile); return; } DMesh3Builder builder = new DMesh3Builder(); StandardMeshReader reader = new StandardMeshReader() { MeshBuilder = builder }; ReadOptions read_options = ReadOptions.Defaults; read_options.ReadMaterials = true; IOReadResult readOK = reader.Read(sInputFile, read_options); if (readOK.code != IOCode.Ok) { System.Console.WriteLine("Error reading " + sInputFile); System.Console.WriteLine(readOK.message); return; } if (builder.Meshes.Count == 0) { System.Console.WriteLine("did not find any valid meshes in " + sInputFile); return; } // [TODO] out if count == 0 string sOutRoot = arguments.Strings["-output"]; if (sOutRoot.Length > 0) { bool bOutIsFolder = Directory.Exists(sOutRoot); if (!bOutIsFolder) { System.Console.WriteLine("-output folder {0} does not exist", sOutRoot); return; } } Dictionary <int, List <int> > MeshesByMaterial = new Dictionary <int, List <int> >(); MeshesByMaterial[-1] = new List <int>(); for (int i = 0; i < builder.Materials.Count; ++i) { MeshesByMaterial[i] = new List <int>(); } int N = builder.Meshes.Count; for (int i = 0; i < N; ++i) { int mati = builder.MaterialAssignment[i]; if (mati >= builder.Materials.Count) { mati = -1; } MeshesByMaterial[mati].Add(i); } int file_i = 0; foreach (int mat_i in MeshesByMaterial.Keys) { List <int> mesh_idxs = MeshesByMaterial[mat_i]; if (mesh_idxs.Count == 0) { continue; } WriteMesh[] write_meshes = new WriteMesh[mesh_idxs.Count]; for (int i = 0; i < mesh_idxs.Count; ++i) { write_meshes[i] = new WriteMesh(builder.Meshes[mesh_idxs[i]]); } string suffix = string.Format("_material{0}", file_i++); string sOutPath = Path.Combine(sOutRoot, sFilenameRoot + suffix + ".obj"); StandardMeshWriter writer = new StandardMeshWriter(); WriteOptions write_options = WriteOptions.Defaults; if (mat_i != -1) { write_options.bWriteMaterials = true; write_options.bPerVertexUVs = true; write_options.MaterialFilePath = Path.Combine(sOutRoot, sFilenameRoot + suffix + ".mtl"); GenericMaterial mat = builder.Materials[mat_i]; List <GenericMaterial> matList = new List <GenericMaterial>() { mat }; ConstantIndexMap idxmap = new ConstantIndexMap(0); for (int i = 0; i < write_meshes.Length; ++i) { write_meshes[i].Materials = matList; write_meshes[i].TriToMaterialMap = idxmap; } } IOWriteResult writeOK = writer.Write(sOutPath, new List <WriteMesh>(write_meshes), write_options); if (writeOK.code != IOCode.Ok) { System.Console.WriteLine("Error writing " + sOutPath); System.Console.WriteLine(writeOK.message); } } // ok done! //System.Console.ReadKey(); }
static void Main(string[] args) { CommandArgumentSet arguments = new CommandArgumentSet(); arguments.Register("-tcount", int.MaxValue); arguments.Register("-percent", 50.0f); arguments.Register("-v", false); arguments.Register("-output", ""); if (arguments.Parse(args) == false) { return; } if (arguments.Filenames.Count != 1) { print_usage(); return; } string inputFilename = arguments.Filenames[0]; if (!File.Exists(inputFilename)) { System.Console.WriteLine("File {0} does not exist", inputFilename); return; } string outputFilename = Path.GetFileNameWithoutExtension(inputFilename); string format = Path.GetExtension(inputFilename); outputFilename = outputFilename + ".reduced" + format; if (arguments.Saw("-output")) { outputFilename = arguments.Strings["-output"]; } int triCount = int.MaxValue; if (arguments.Saw("-tcount")) { triCount = arguments.Integers["-tcount"]; } float percent = 50.0f; if (arguments.Saw("-percent")) { percent = arguments.Floats["-percent"]; } bool verbose = false; if (arguments.Saw("-v")) { verbose = arguments.Flags["-v"]; } List <DMesh3> meshes; try { DMesh3Builder builder = new DMesh3Builder(); IOReadResult result = StandardMeshReader.ReadFile(inputFilename, ReadOptions.Defaults, builder); if (result.code != IOCode.Ok) { System.Console.WriteLine("Error reading {0} : {1}", inputFilename, result.message); return; } meshes = builder.Meshes; } catch (Exception e) { System.Console.WriteLine("Exception reading {0} : {1}", inputFilename, e.Message); return; } if (meshes.Count == 0) { System.Console.WriteLine("file did not contain any valid meshes"); return; } DMesh3 mesh = meshes[0]; for (int k = 1; k < meshes.Count; ++k) { MeshEditor.Append(mesh, meshes[k]); } if (mesh.TriangleCount == 0) { System.Console.WriteLine("mesh does not contain any triangles"); return; } if (verbose) { System.Console.WriteLine("initial mesh contains {0} triangles", mesh.TriangleCount); } Reducer r = new Reducer(mesh); if (triCount < int.MaxValue) { if (verbose) { System.Console.Write("reducing to {0} triangles...", triCount); } r.ReduceToTriangleCount(triCount); } else { int nT = (int)((float)mesh.TriangleCount * percent / 100.0f); nT = MathUtil.Clamp(nT, 1, mesh.TriangleCount); if (verbose) { System.Console.Write("reducing to {0} triangles...", nT); } r.ReduceToTriangleCount(nT); } if (verbose) { System.Console.WriteLine("done!"); } try { IOWriteResult wresult = StandardMeshWriter.WriteMesh(outputFilename, mesh, WriteOptions.Defaults); if (wresult.code != IOCode.Ok) { System.Console.WriteLine("Error writing {0} : {1}", inputFilename, wresult.message); return; } } catch (Exception e) { System.Console.WriteLine("Exception reading {0} : {1}", inputFilename, e.Message); return; } return; }
// // [TODO] // - binary output option // - option to strip data from inputs (eg remove normals/colors/uv/material from obj) // - option to remove material props from OBJ // - option to combine input meshes // - option to set float precision // - option to estimate normals for writing (eg for obj) // - option to set constant color for vertices // static void Main(string[] args) { if (args.Length != 2) { System.Console.WriteLine("gsMeshConvert v1.0 - Copyright gradientspace / Ryan Schmidt 2017"); System.Console.WriteLine("Questions? Comments? www.gradientspace.com or @gradientspace"); System.Console.WriteLine("usage: gsMeshConvert <input_mesh.format> (output_mesh.format)"); return; } string sInputFile = args[0]; if (!File.Exists(sInputFile)) { System.Console.WriteLine("cannot find file " + sInputFile); return; } string sOutputFile = args[1]; // check that can write output file DMesh3Builder builder = new DMesh3Builder(); StandardMeshReader reader = new StandardMeshReader() { MeshBuilder = builder }; ReadOptions read_options = ReadOptions.Defaults; IOReadResult readOK = reader.Read(sInputFile, read_options); if (readOK.code != IOCode.Ok) { System.Console.WriteLine("Error reading " + sInputFile); System.Console.WriteLine(readOK.message); return; } if (builder.Meshes.Count == 0) { System.Console.WriteLine("did not find any valid meshes in " + sInputFile); return; } List <WriteMesh> write_meshes = new List <WriteMesh>(); foreach (DMesh3 mesh in builder.Meshes) { write_meshes.Add(new WriteMesh(mesh)); } StandardMeshWriter writer = new StandardMeshWriter(); WriteOptions write_options = WriteOptions.Defaults; IOWriteResult writeOK = writer.Write(sOutputFile, write_meshes, write_options); if (writeOK.code != IOCode.Ok) { System.Console.WriteLine("Error writing " + sOutputFile); System.Console.WriteLine(writeOK.message); return; } // ok done! //System.Console.ReadKey(); }
public static void Main(string[] args) { CommandArgumentSet arguments = new CommandArgumentSet(); //arguments.Register("-tcount", int.MaxValue); //arguments.Register("-percent", 50.0f); //arguments.Register("-v", false); arguments.Register("-output", ""); if (arguments.Parse(args) == false) { return; } if (arguments.Filenames.Count != 1) { print_usage(); return; } string inputFilename = arguments.Filenames[0]; if (!File.Exists(inputFilename)) { System.Console.WriteLine("File {0} does not exist", inputFilename); return; } string outputFilename = Path.GetFileNameWithoutExtension(inputFilename); string format = Path.GetExtension(inputFilename); outputFilename = outputFilename + ".repaired" + format; if (arguments.Saw("-output")) { outputFilename = arguments.Strings["-output"]; } //int triCount = int.MaxValue; //if (arguments.Saw("-tcount")) // triCount = arguments.Integers["-tcount"]; //float percent = 50.0f; //if (arguments.Saw("-percent")) // percent = arguments.Floats["-percent"]; bool verbose = true; //if (arguments.Saw("-v")) // verbose = arguments.Flags["-v"]; List <DMesh3> meshes; try { DMesh3Builder builder = new DMesh3Builder(); IOReadResult result = StandardMeshReader.ReadFile(inputFilename, ReadOptions.Defaults, builder); if (result.code != IOCode.Ok) { System.Console.WriteLine("Error reading {0} : {1}", inputFilename, result.message); return; } meshes = builder.Meshes; } catch (Exception e) { System.Console.WriteLine("Exception reading {0} : {1}", inputFilename, e.Message); return; } if (meshes.Count == 0) { System.Console.WriteLine("file did not contain any valid meshes"); return; } DMesh3 mesh = meshes[0]; for (int k = 1; k < meshes.Count; ++k) { MeshEditor.Append(mesh, meshes[k]); } if (mesh.TriangleCount == 0) { System.Console.WriteLine("mesh does not contain any triangles"); return; } if (verbose) { System.Console.WriteLine("initial mesh contains {0} triangles", mesh.TriangleCount); } if (verbose) { System.Console.WriteLine("Repairing...", mesh.TriangleCount); } MeshAutoRepair repair = new MeshAutoRepair(mesh); repair.RemoveMode = MeshAutoRepair.RemoveModes.None; bool bOK = repair.Apply(); if (verbose) { if (bOK == false) { System.Console.WriteLine("repair failed!"); } else { System.Console.WriteLine("done! repaired mesh contains {0} triangles", mesh.TriangleCount); } } try { IOWriteResult wresult = StandardMeshWriter.WriteMesh(outputFilename, mesh, WriteOptions.Defaults); if (wresult.code != IOCode.Ok) { System.Console.WriteLine("Error writing {0} : {1}", inputFilename, wresult.message); return; } } catch (Exception e) { System.Console.WriteLine("Exception reading {0} : {1}", inputFilename, e.Message); return; } return; }
static void Main(string[] args) { bool INTERACTIVE = true; //string inFile = "c:\\scratch\\test_bunny.obj"; //string inFile = "c:\\scratch\\bunny_100k.obj"; //string inFile = "c:\\scratch\\test_bunny_ascii.stl"; string inFile = "c:\\scratch\\test_bunny_binary.stl"; string outFile = "c:\\scratch\\test_bunny_out.obj"; ReadOptions read_options = new ReadOptions(); read_options.ReadMaterials = false; StandardMeshReader reader = new StandardMeshReader(); DMesh3Builder builder = new DMesh3Builder(); IOReadResult read_result = StandardMeshReader.ReadFile(inFile, read_options, builder); if (read_result.code != IOCode.Ok) { System.Console.WriteLine("Error reading " + inFile + " : " + read_result.message); if (INTERACTIVE) { System.Console.WriteLine("press enter key to exit"); System.Console.ReadLine(); } return; } WriteOptions write_options = new WriteOptions(); write_options.bCombineMeshes = true; write_options.bWriteBinary = true; List <WriteMesh> outMeshes = new List <WriteMesh>(); foreach (DMesh3 m in builder.Meshes) { outMeshes.Add(new WriteMesh(m)); } IOWriteResult write_result = StandardMeshWriter.WriteFile(outFile, outMeshes, write_options); if (write_result.code != IOCode.Ok) { System.Console.WriteLine("Error writing " + outFile + " : " + write_result.message); if (INTERACTIVE) { System.Console.WriteLine("press enter key to exit"); System.Console.ReadLine(); } return; } if (INTERACTIVE) { System.Console.WriteLine("Done conversion, press enter key to exit"); System.Console.ReadLine(); } }