diff --git a/docs/tools-changelog.md b/docs/tools-changelog.md index 2ec173c..028a2e2 100644 --- a/docs/tools-changelog.md +++ b/docs/tools-changelog.md @@ -2,7 +2,7 @@ ## [0.1.0-preview.1] -- `IOScene.Formats` reads embedded GLB and OBJ geometry and writes GLB from an IOScene document. +- `IOScene.Formats` reads embedded GLB and OBJ geometry and writes GLB and OBJ from an IOScene document. - `IOCoord` provides measurements, surface clearance, hard clashes with an estimated depth, box overlap checks, duplicate geometry detection, solid containment, grid queries, revision comparison and BCF 2.1 export. - Both packages use the public IOScene 0.1 API and can be installed independently. diff --git a/docs/tools.md b/docs/tools.md index b9ed6e1..1299ebb 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -11,6 +11,7 @@ using IOScene.Formats; var scene = SceneJson.Load("model.scene.json"); GlbSceneWriter.Save(scene, "model.glb"); +ObjSceneWriter.Save(scene, "model.obj"); ``` `GlbSceneReader.Load` reads embedded float32 positions and normals, unsigned indices and base material colours. @@ -18,6 +19,10 @@ It flattens the node placements into one model and imports triangle, line and po required glTF extensions are rejected. The OBJ reader `ObjSceneReader.Load` groups faces by object and assumes metres with Z up. +`ObjSceneWriter` bakes placed vertices into OBJ with Z up and writes triangle faces, line segments and points. +Its text-writer overload can also write an adjacent MTL library with effective colours and opacity. +The OBJ reader currently imports faces and ignores MTL libraries. + The writer emits [glTF 2.0 binary](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html) with the element tree, indexed and non-indexed triangles, lines and points, shared mesh buffers, and placements with rotation, translation, scale or reflection. The scene root rotates the metre-based geometry from Z up to glTF Y up. Materials carry diff --git a/src/IOScene.Formats/GlbSceneWriter.cs b/src/IOScene.Formats/GlbSceneWriter.cs index 5afd82a..653b885 100644 --- a/src/IOScene.Formats/GlbSceneWriter.cs +++ b/src/IOScene.Formats/GlbSceneWriter.cs @@ -12,19 +12,7 @@ public static class GlbSceneWriter public static void Save(SceneDocument scene, string path) { ArgumentNullException.ThrowIfNull(scene); - ArgumentException.ThrowIfNullOrWhiteSpace(path); - string fullPath = Path.GetFullPath(path); - string temporaryPath = Path.Combine(Path.GetDirectoryName(fullPath)!, $".{Guid.NewGuid():N}.glb.tmp"); - var file = new FileStream(temporaryPath, FileMode.CreateNew, FileAccess.Write, FileShare.None); - try - { - using (file) Write(scene, file); - File.Move(temporaryPath, fullPath, overwrite: true); - } - finally - { - File.Delete(temporaryPath); - } + SceneFormatFile.Replace(path, "glb", file => Write(scene, file)); } /// Writes the scene to an open stream. The stream remains open. diff --git a/src/IOScene.Formats/IOScene.Formats.csproj b/src/IOScene.Formats/IOScene.Formats.csproj index e6cbf01..d8765ba 100644 --- a/src/IOScene.Formats/IOScene.Formats.csproj +++ b/src/IOScene.Formats/IOScene.Formats.csproj @@ -3,7 +3,7 @@ 0.1.0-preview.1 IOScene.Formats - GLB and OBJ import and GLB export for IOScene models. + GLB and OBJ import and export for IOScene models. true $(NoWarn);NU5104 diff --git a/src/IOScene.Formats/ObjSceneWriter.cs b/src/IOScene.Formats/ObjSceneWriter.cs new file mode 100644 index 0000000..7c3f0d3 --- /dev/null +++ b/src/IOScene.Formats/ObjSceneWriter.cs @@ -0,0 +1,117 @@ +namespace IOScene.Formats; + +/// Writes placed scene geometry as Wavefront OBJ in metres with Z up. +public static class ObjSceneWriter +{ + /// Writes geometry to a UTF-8 OBJ file and replaces an existing file after a successful export. + /// The scene to export. + /// Path to the OBJ file. + public static void Save(SceneDocument scene, string path) + { + ArgumentNullException.ThrowIfNull(scene); + SceneFormatFile.Replace(path, "obj", file => + { + using var writer = new StreamWriter(file, leaveOpen: true); + Write(scene, writer); + }); + } + + /// Writes geometry to an OBJ text writer. The writer stays open. + /// The scene to export. + /// The OBJ text writer. + public static void Write(SceneDocument scene, TextWriter output) => WriteScene(scene, output, null, null); + + /// Writes OBJ geometry and an MTL library with the effective colours and opacity. Both writers stay open. + /// The scene to export. + /// The OBJ text writer. + /// The MTL text writer. + /// File name of the adjacent MTL library, without a path or whitespace. + public static void Write(SceneDocument scene, TextWriter output, TextWriter materials, string materialFileName) + { + ArgumentNullException.ThrowIfNull(materials); + ArgumentException.ThrowIfNullOrWhiteSpace(materialFileName); + if (ReferenceEquals(output, materials)) + throw new ArgumentException("OBJ and MTL require separate text writers.", nameof(materials)); + if (materialFileName is "." or ".." || materialFileName.Any(c => char.IsWhiteSpace(c) || char.IsControl(c) + || c is '/' or '\\' or ':' or '#')) + throw new ArgumentException("Use a single MTL file name without paths, spaces or comments.", nameof(materialFileName)); + WriteScene(scene, output, materials, materialFileName); + } + + private static void WriteScene(SceneDocument scene, TextWriter output, TextWriter? materials, string? materialFileName) + { + ArgumentNullException.ThrowIfNull(scene); + ArgumentNullException.ThrowIfNull(output); + if (scene.Validate().FirstOrDefault(issue => issue.Severity == SceneSeverity.Error) is { } error) + throw new InvalidDataException($"Invalid scene ({error.Code}): {error.Message}"); + + var elements = scene.Elements.ToDictionary(item => item.Id); + var geometries = scene.Geometries.ToDictionary(item => item.Id); + var materialColours = materials is null ? null : scene.Materials.ToDictionary(item => item.Id, item => item.Color); + var colourNames = new Dictionary(); + long vertexOffset = 1; + if (materialFileName is not null) output.WriteLine($"mtllib {materialFileName}"); + foreach (var instance in scene.Instances) + { + var geometry = geometries[instance.GeometryId]; + if (geometry.Vertices.Count == 0) continue; + var name = instance.Name ?? elements[instance.ElementId].Name; + string safeName = new(name.Select(c => char.IsWhiteSpace(c) || char.IsControl(c) || c is '#' or '\\' ? '_' : c).ToArray()); + output.WriteLine($"o {(safeName.Length == 0 ? "Element" : safeName)}"); + + if (materials is not null) + { + var colour = instance.Color ?? (instance.MaterialId is int id ? materialColours![id] : RgbaColor.White); + if (!colourNames.TryGetValue(colour, out string? materialName)) + { + materialName = FormattableString.Invariant($"material_{colourNames.Count + 1}"); + colourNames.Add(colour, materialName); + materials.WriteLine($"newmtl {materialName}"); + materials.WriteLine(FormattableString.Invariant($"Kd {colour.R / 255d:R} {colour.G / 255d:R} {colour.B / 255d:R}")); + materials.WriteLine(FormattableString.Invariant($"d {colour.A / 255d:R}")); + materials.WriteLine("illum 2"); + } + output.WriteLine($"usemtl {materialName}"); + } + + var transform = instance.Transform ?? Transform3d.Identity; + foreach (var vertex in geometry.Vertices) + { + var point = transform.Apply(vertex); + if (!double.IsFinite(point.X) || !double.IsFinite(point.Y) || !double.IsFinite(point.Z)) + throw new InvalidDataException("An OBJ vertex coordinate is outside the finite range."); + output.WriteLine(FormattableString.Invariant($"v {point.X:R} {point.Y:R} {point.Z:R}")); + } + + int stride = geometry.Topology switch + { + SceneTopology.Triangles => 3, + SceneTopology.Lines => 2, + SceneTopology.Points => 1, + _ => throw new InvalidDataException($"Unsupported OBJ topology: {geometry.Topology}."), + }; + bool mirrored = stride == 3 && + Vector3d.Dot(Vector3d.Cross(ScaleAxis(transform.XAxis), ScaleAxis(transform.YAxis)), ScaleAxis(transform.ZAxis)) < 0; + int count = geometry.Indices.Count == 0 ? geometry.Vertices.Count : geometry.Indices.Count; + for (int i = 0; i < count; i += stride) + { + var record = stride switch + { + 3 => FormattableString.Invariant($"f {Index(i)} {Index(i + (mirrored ? 2 : 1))} {Index(i + (mirrored ? 1 : 2))}"), + 2 => FormattableString.Invariant($"l {Index(i)} {Index(i + 1)}"), + _ => FormattableString.Invariant($"p {Index(i)}"), + }; + output.WriteLine(record); + } + vertexOffset += geometry.Vertices.Count; + + long Index(int index) => vertexOffset + (geometry.Indices.Count == 0 ? index : geometry.Indices[index]); + } + } + + private static Vector3d ScaleAxis(Vector3d axis) + { + double scale = Math.Max(Math.Abs(axis.X), Math.Max(Math.Abs(axis.Y), Math.Abs(axis.Z))); + return scale > 0 ? axis / scale : axis; + } +} diff --git a/src/IOScene.Formats/SceneFormatFile.cs b/src/IOScene.Formats/SceneFormatFile.cs new file mode 100644 index 0000000..77855b7 --- /dev/null +++ b/src/IOScene.Formats/SceneFormatFile.cs @@ -0,0 +1,21 @@ +namespace IOScene.Formats; + +internal static class SceneFormatFile +{ + internal static void Replace(string path, string extension, Action write) + { + ArgumentException.ThrowIfNullOrWhiteSpace(path); + string fullPath = Path.GetFullPath(path); + string temporaryPath = Path.Combine(Path.GetDirectoryName(fullPath)!, $".{Guid.NewGuid():N}.{extension}.tmp"); + var file = new FileStream(temporaryPath, FileMode.CreateNew, FileAccess.Write, FileShare.None); + try + { + using (file) write(file); + File.Move(temporaryPath, fullPath, overwrite: true); + } + finally + { + File.Delete(temporaryPath); + } + } +} diff --git a/tests/IOScene.Tools.Tests/ObjSceneWriterTests.cs b/tests/IOScene.Tools.Tests/ObjSceneWriterTests.cs new file mode 100644 index 0000000..66122e8 --- /dev/null +++ b/tests/IOScene.Tools.Tests/ObjSceneWriterTests.cs @@ -0,0 +1,85 @@ +using System.Text; +using IOScene.Formats; + +namespace IOScene.Tools.Tests; + +public class ObjSceneWriterTests +{ + [Fact] + public void Write_BakesPlacementAndPreservesWindingWhenMirrored() + { + var scene = new SceneDocument(); + scene.AddMesh("Left panel\nf 9 8 7\\", [Vector3d.Zero, Vector3d.UnitX, Vector3d.UnitZ], [0, 1, 2]); + scene.Instances[0].Transform = new(-Vector3d.UnitX, Vector3d.UnitY, Vector3d.UnitZ, new(10, 20, 30)); + using var obj = new StringWriter(); + + ObjSceneWriter.Write(scene, obj); + + string text = obj.ToString(); + Assert.Equal(["o Left_panel_f_9_8_7_", "v 10 20 30", "v 9 20 30", "v 10 20 31", "f 1 3 2"], + text.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries)); + using var input = new MemoryStream(Encoding.UTF8.GetBytes(text)); + var geometry = Assert.Single(ObjSceneReader.Load(input).Geometries); + Assert.Equal([new(10, 20, 30), new(10, 20, 31), new(9, 20, 30)], geometry.Vertices); + } + + [Fact] + public void Write_EmitsLinesPointsAndEffectiveMaterialColours() + { + var scene = new SceneDocument(); + scene.AddMesh("Line", [Vector3d.Zero, Vector3d.UnitX], []); + scene.Geometries[0].Topology = SceneTopology.Lines; + scene.AddMesh("Point", [Vector3d.UnitZ], []); + scene.Geometries[1].Topology = SceneTopology.Points; + scene.Materials.Add(new SceneMaterial { Id = 1, Color = new(255, 0, 0) }); + scene.Instances[0].MaterialId = 1; + scene.Instances[0].Color = new(0, 255, 0, 128); + scene.Instances[1].MaterialId = 1; + using var obj = new StringWriter(); + using var mtl = new StringWriter(); + + ObjSceneWriter.Write(scene, obj, mtl, "model.mtl"); + + string objText = obj.ToString(); + Assert.Contains("mtllib model.mtl", objText); + Assert.Contains("usemtl material_1", objText); + Assert.Contains("usemtl material_2", objText); + Assert.Contains("l 1 2", objText); + Assert.Contains("p 3", objText); + string mtlText = mtl.ToString(); + Assert.Contains("Kd 0 1 0", mtlText); + Assert.Contains("d 0.5019607843137255", mtlText); + Assert.Contains("Kd 1 0 0", mtlText); + } + + [Fact] + public void Write_InvalidMaterialNameLeavesBothWritersEmpty() + { + using var obj = new StringWriter(); + using var mtl = new StringWriter(); + + Assert.Throws(() => ObjSceneWriter.Write(new SceneDocument(), obj, mtl, "../model.mtl")); + Assert.Empty(obj.ToString()); + Assert.Empty(mtl.ToString()); + } + + [Fact] + public void Save_ExportFailurePreservesAnExistingFile() + { + var scene = new SceneDocument(); + scene.AddMesh("Panel", [Vector3d.Zero, new(double.MaxValue, 0, 0), Vector3d.UnitY], [0, 1, 2]); + scene.Instances[0].Transform = new(Vector3d.UnitX * 2, Vector3d.UnitY, Vector3d.UnitZ, Vector3d.Zero); + string path = Path.Combine(Path.GetTempPath(), $"scene-{Guid.NewGuid():N}.obj"); + try + { + File.WriteAllText(path, "existing content"); + + Assert.Throws(() => ObjSceneWriter.Save(scene, path)); + Assert.Equal("existing content", File.ReadAllText(path)); + } + finally + { + File.Delete(path); + } + } +}