Here is my C# code for writing binary STL files.
Unfortunately it doesn’t work right now.
I am not really experienced with C#, so can someone please point out the problem with this component?
STL specification: https://en.wikipedia.org/wiki/STL_(file_format)#Binary_STL
//Adapted from https://csharp.hotexamples.com/de/examples/IxMilia.Stl/StlFile/-/php-stlfile-class-examples.html
// https://github.com/mcneel/rhino-developer-samples/blob/6/rhinocommon/cs/SampleCsCommands/SampleCsWriteStl.cs
var m = mesh.DuplicateMesh();
m.Faces.ConvertQuadsToTriangles();
m.FaceNormals.ComputeFaceNormals();
m.Normals.ComputeNormals();
m.Compact();
string stlString;
using (var stream = new System.IO.MemoryStream())
{var writer = new System.IO.BinaryWriter(stream);
var header = new byte[80];
writer.Write(header);
writer.Write((uint) mesh.Faces.Count);
for (var i = 0; i < m.Faces.Count; i++)
{
var f = m.Faces[i];
var n = m.FaceNormals[i];
var a = m.Vertices[f.A];
var b = m.Vertices[f.B];
var c = m.Vertices[f.C];
writer.Write((float) n.X);
writer.Write((float) n.Y);
writer.Write((float) n.Z);
writer.Write((float) a.X);
writer.Write((float) a.Y);
writer.Write((float) a.Z);
writer.Write((float) b.X);
writer.Write((float) b.Y);
writer.Write((float) b.Z);
writer.Write((float) c.X);
writer.Write((float) c.Y);
writer.Write((float) c.Z);
writer.Write((ushort) 0);
}
writer.Flush();
stream.Seek(0, System.IO.SeekOrigin.Begin);
var sr = new System.IO.StreamReader(stream);
stlString = sr.ReadToEnd();
//Print(stream.Length.ToString());
//Print(stlString);//.Length.ToString());
//var folder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
//var path = System.IO.Path.Combine(folder, "SampleCsWriteStl.stl");
//System.IO.File.WriteAllBytes(path, stream.ToArray());
}
A = stlString;```