From a88d12fb981d1f6dfa79e8d081b3697d1218d11a Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:10:56 +0300 Subject: [PATCH] Add GLB coordinate and camera export options --- CHANGELOG.md | 4 + docs/public-api.md | 12 +- src/NwcIO/Compatibility/Export/GlbExporter.cs | 173 +++++++++++-- .../NwcAssembly.Compatibility.cs | 14 +- .../Compatibility/NwcDocument.AsyncExports.cs | 14 +- .../NwcDocument.Compatibility.cs | 20 +- .../Compatibility/NwcGlbExportOptions.cs | 25 ++ tests/NwcIO.Tests/GlbExportTests.cs | 229 ++++++++++++++++++ 8 files changed, 451 insertions(+), 40 deletions(-) create mode 100644 src/NwcIO/Compatibility/NwcGlbExportOptions.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 860df49..7e91454 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to the `NwcIO` library, the CLI and the `NwcIO.Scene` adapte ## [Unreleased] +### Added + +- `NwcGlbExportOptions` supports Y-up conversion, unit scaling, precision-preserving recentering and optional saved cameras in GLB exports (#45). + ### Fixed - Path-based Wavefront OBJ export writes a sibling `.mtl` with diffuse colors and opacity from mesh materials (#93). diff --git a/docs/public-api.md b/docs/public-api.md index af71fc0..c84e535 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -128,7 +128,7 @@ region before testing for intersection. Proximity grouping finds nearby clashes | Type | Description | |---|---| | `NwcDocument.SaveIfc` / `NwcAssembly.SaveIfc` | ISO 10303-21 STEP export supporting IFC2x3 Coordination View and modern IFC4 mesh tessellation (`IfcTriangulatedFaceSet`), configured via `NwcIfcExportOptions` (`NwcIfcSchemaVersion`, `NwcIfcLengthUnit`). Frozen: bug fixes only. | -| `NwcDocument.SaveGlb` / `SaveObj`, `NwcAssembly.SaveGlb` / `SaveObj` | Binary glTF 2.0 and Wavefront OBJ geometry export entry points. Frozen: bug fixes only. | +| `NwcDocument.SaveGlb` / `SaveObj`, `NwcAssembly.SaveGlb` / `SaveObj` | Binary glTF 2.0 and Wavefront OBJ geometry export entry points. `NwcGlbExportOptions` configures GLB path and stream exports, including `NwcDocument.SaveGlbAsync`. | | `NwcDocument.SaveHtmlViewer` / `NwcAssembly.SaveHtmlViewer` | Interactive single-file 3D WebGL viewer exporter with 4D schedule playback (`NwcHtmlViewerExporter`, `NwcHtmlViewerOptions`). Frozen: bug fixes only. | | `NwcJsonExportOptions` | Indentation and content toggles for JSON export (`NwcDocument` and the CLI). | @@ -148,6 +148,16 @@ material channels remain outside this support. An OBJ save with materials requires a sibling filename that can be used in an `mtllib` directive. The export rejects a symbolic link at the material library path. +Use `NwcGlbExportOptions` to set the GLB coordinate system and camera options. + +| Option | Default | Effect | +|---|---|---| +| `WorldCoordinates` | `true` | Bake mesh placements into the exported vertices. Set to `false` to export local mesh vertices. Saved cameras start in document coordinates in either mode. | +| `ConvertZUpToYUp` | `false` | Rotate mesh positions, normals and cameras via `(x, y, z) → (x, z, -y)`. | +| `UnitScale` | `1.0` | Multiply positions and camera lengths by a positive finite factor. Use `0.001` for millimetres to metres, or use `NwcDocument.MetresPerUnit` when the source unit is known. | +| `RecenterToOrigin` | `false` | Subtract the exported mesh bounds' center in double precision before packing vertices as float32. A shared root node restores the offset in exported axes and units, including for saved cameras. | +| `ExportCameras` | `true` | Include cameras from saved viewpoints. | + GLB geometry export requires a writable system temporary directory for its BIN chunk. The exporter removes the temporary file when it closes. A path-based save replaces the destination after the export succeeds. The complete GLB is limited to 4,294,967,292 bytes, including its diff --git a/src/NwcIO/Compatibility/Export/GlbExporter.cs b/src/NwcIO/Compatibility/Export/GlbExporter.cs index c9ab015..7607ac7 100644 --- a/src/NwcIO/Compatibility/Export/GlbExporter.cs +++ b/src/NwcIO/Compatibility/Export/GlbExporter.cs @@ -7,7 +7,7 @@ namespace NwcIO.Internal.Export; /// -/// Exports 3D meshes, scene hierarchy, materials and PBR surface parameters +/// Exports 3D meshes, materials and saved cameras /// to standardized glTF 2.0 Binary container format (.glb). /// internal static class GlbExporter @@ -31,13 +31,22 @@ public static void WriteFile( string path, bool worldCoordinates = true, string? generatorName = null, + IReadOnlyList? viewpoints = null) => + WriteFile(meshes, materials, path, NwcGlbExportOptions.ForCoordinates(worldCoordinates), generatorName, viewpoints); + + public static void WriteFile( + IReadOnlyList meshes, + IReadOnlyList materials, + string path, + NwcGlbExportOptions options, + string? generatorName = null, IReadOnlyList? viewpoints = null) { ArgumentNullException.ThrowIfNull(meshes); ArgumentNullException.ThrowIfNull(materials); ArgumentNullException.ThrowIfNull(path); - AtomicFileWriter.Write(path, output => Write(meshes, materials, output, worldCoordinates, generatorName, viewpoints), default); + AtomicFileWriter.Write(path, output => Write(meshes, materials, output, options, generatorName, viewpoints), default); } public static void Write( @@ -47,11 +56,31 @@ public static void Write( bool worldCoordinates = true, string? generatorName = null, IReadOnlyList? viewpoints = null, + CancellationToken cancellationToken = default) => + Write(meshes, materials, output, NwcGlbExportOptions.ForCoordinates(worldCoordinates), generatorName, viewpoints, cancellationToken); + + public static void Write( + IReadOnlyList meshes, + IReadOnlyList materials, + Stream output, + NwcGlbExportOptions options, + string? generatorName = null, + IReadOnlyList? viewpoints = null, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(meshes); ArgumentNullException.ThrowIfNull(materials); ArgumentNullException.ThrowIfNull(output); + ArgumentNullException.ThrowIfNull(options); + if (!double.IsFinite(options.UnitScale) || options.UnitScale <= 0) + { + throw new ArgumentOutOfRangeException(nameof(options), options.UnitScale, "UnitScale must be positive and finite."); + } + + bool worldCoordinates = options.WorldCoordinates; + bool convertAxis = options.ConvertZUpToYUp; + var center = options.RecenterToOrigin ? FindCenter(meshes, worldCoordinates, cancellationToken) : null; + bool transformPositions = center.HasValue || convertAxis || options.UnitScale != 1; using var bin = new BinChunk(); var bufferViews = new List(); @@ -87,10 +116,7 @@ public static void Write( continue; } - if (vertices.Any(position => - !float.IsFinite((float)position.X) || - !float.IsFinite((float)position.Y) || - !float.IsFinite((float)position.Z))) + if (vertices.Any(static position => !FitsFloat(position))) { continue; } @@ -148,6 +174,11 @@ public static void Write( for (int i = 0; i < count; i++, v++) { var pt = vertices[v]; + if (transformPositions) + { + pt = TransformPosition(pt, center, options); + if (!FitsFloat(pt)) throw new InvalidOperationException("The converted GLB mesh position is outside the finite float32 range."); + } var packed = batch[(i * 12)..]; BinaryPrimitives.WriteSingleLittleEndian(packed, (float)pt.X); BinaryPrimitives.WriteSingleLittleEndian(packed[4..], (float)pt.Y); @@ -192,6 +223,7 @@ public static void Write( var (x, y, z) = len > 1e-6 ? ((float)(n.X / len), (float)(n.Y / len), (float)(n.Z / len)) : (0.0f, 0.0f, 1.0f); + if (convertAxis) (y, z) = (z, -y); var packed = batch[(i * 12)..]; BinaryPrimitives.WriteSingleLittleEndian(packed, x); BinaryPrimitives.WriteSingleLittleEndian(packed[4..], y); @@ -379,12 +411,15 @@ public static void Write( bufferViews, GetBinChunkLength(binFile?.Length ?? 0), generatorName ?? "NwcIO glTF 2.0 Exporter", - viewpoints, + options.ExportCameras ? viewpoints : null, + center, + options, materialsWithBlend, images, materialTextures, cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); WriteContainer(output, jsonData.Span, binFile); } @@ -441,6 +476,8 @@ private static ReadOnlyMemory BuildJsonChunk( long binByteLength, string generator, IReadOnlyList? viewpoints, + Vector3d? center, + NwcGlbExportOptions options, HashSet? materialsWithBlend, List images, Dictionary materialTextures, @@ -464,14 +501,19 @@ private static ReadOnlyMemory BuildJsonChunk( var cameras = viewpoints?.Where(vp => IsFinite(vp.Camera.Position) && IsFinite(vp.Camera.Rotation)).ToList(); int camCount = cameras?.Count ?? 0; int totalNodes = meshes.Count + camCount; + bool addRoot = center.HasValue && totalNodes > 0; // scenes writer.WriteStartArray("scenes"); writer.WriteStartObject(); if (totalNodes > 0) writer.WriteStartArray("nodes"); - for (int i = 0; i < totalNodes; i++) + if (addRoot) + { + writer.WriteNumberValue(totalNodes); + } + else { - writer.WriteNumberValue(i); + for (int i = 0; i < totalNodes; i++) writer.WriteNumberValue(i); } if (totalNodes > 0) writer.WriteEndArray(); @@ -500,23 +542,30 @@ private static ReadOnlyMemory BuildJsonChunk( writer.WriteString("name", vp.Name); writer.WriteNumber("camera", i); - writer.WriteStartArray("translation"); - writer.WriteNumberValue(cam.Position.X); - writer.WriteNumberValue(cam.Position.Y); - writer.WriteNumberValue(cam.Position.Z); - writer.WriteEndArray(); + WriteTranslation(writer, TransformPosition(cam.Position, center, options)); + var rotation = options.ConvertZUpToYUp ? ToYUp(cam.Rotation) : cam.Rotation; writer.WriteStartArray("rotation"); - writer.WriteNumberValue(cam.Rotation.X); - writer.WriteNumberValue(cam.Rotation.Y); - writer.WriteNumberValue(cam.Rotation.Z); - writer.WriteNumberValue(cam.Rotation.W); + writer.WriteNumberValue(rotation.X); + writer.WriteNumberValue(rotation.Y); + writer.WriteNumberValue(rotation.Z); + writer.WriteNumberValue(rotation.W); writer.WriteEndArray(); writer.WriteEndObject(); } } + if (addRoot) + { + writer.WriteStartObject(); + WriteTranslation(writer, TransformPosition(center.GetValueOrDefault(), null, options)); + writer.WriteStartArray("children"); + for (int i = 0; i < totalNodes; i++) writer.WriteNumberValue(i); + writer.WriteEndArray(); + writer.WriteEndObject(); + } + if (totalNodes > 0) writer.WriteEndArray(); // cameras @@ -537,10 +586,10 @@ private static ReadOnlyMemory BuildJsonChunk( writer.WriteStartObject("orthographic"); double xmag = Math.Max(1.0, PositiveOr(cam.FocalDistance * 0.5, 1.0)); double ymag = xmag / PositiveOr(cam.AspectRatio, 1.0); - writer.WriteNumber("xmag", xmag); - writer.WriteNumber("ymag", PositiveOr(ymag, xmag)); - writer.WriteNumber("zfar", PositiveOr(cam.FarDistance, 10000.0)); - writer.WriteNumber("znear", PositiveOr(cam.NearDistance, 0.1)); + writer.WriteNumber("xmag", ScaleLength(xmag, options.UnitScale)); + writer.WriteNumber("ymag", ScaleLength(PositiveOr(ymag, xmag), options.UnitScale)); + writer.WriteNumber("zfar", ScaleLength(PositiveOr(cam.FarDistance, 10000.0), options.UnitScale)); + writer.WriteNumber("znear", ScaleLength(PositiveOr(cam.NearDistance, 0.1), options.UnitScale)); writer.WriteEndObject(); } else @@ -549,8 +598,8 @@ private static ReadOnlyMemory BuildJsonChunk( writer.WriteStartObject("perspective"); writer.WriteNumber("aspectRatio", PositiveOr(cam.AspectRatio, 1.0)); writer.WriteNumber("yfov", PositiveOr(cam.FieldOfView * (Math.PI / 180.0), 1.04719755)); - writer.WriteNumber("zfar", PositiveOr(cam.FarDistance, 10000.0)); - writer.WriteNumber("znear", PositiveOr(cam.NearDistance, 0.1)); + writer.WriteNumber("zfar", ScaleLength(PositiveOr(cam.FarDistance, 10000.0), options.UnitScale)); + writer.WriteNumber("znear", ScaleLength(PositiveOr(cam.NearDistance, 0.1), options.UnitScale)); writer.WriteEndObject(); } @@ -718,6 +767,82 @@ private static ReadOnlyMemory BuildJsonChunk( return json.WrittenMemory; } + private static Vector3d? FindCenter(IReadOnlyList meshes, bool worldCoordinates, CancellationToken cancellationToken) + { + var bounds = BoundingBox3d.Empty; + foreach (var mesh in meshes) + { + cancellationToken.ThrowIfCancellationRequested(); + if (mesh.Indices.Count < 3 && mesh.LineIndices.Count < 2) continue; + + var vertices = worldCoordinates ? mesh.TransformVertices(cancellationToken) : mesh.Vertices; + if (vertices.Count < 2 || (!HasPrimitive(mesh.Indices, 3, vertices.Count, cancellationToken) && + !HasPrimitive(mesh.LineIndices, 2, vertices.Count, cancellationToken))) continue; + + var meshBounds = BoundingBox3d.Empty; + for (int i = 0; i < vertices.Count; i++) + { + if ((i & 4095) == 0) cancellationToken.ThrowIfCancellationRequested(); + var vertex = vertices[i]; + if (!FitsFloat(vertex)) + { + meshBounds = BoundingBox3d.Empty; + break; + } + meshBounds = meshBounds.Union(vertex); + } + bounds = bounds.Union(meshBounds); + } + + return bounds.IsEmpty ? null : bounds.Center; + } + + private static bool HasPrimitive(IReadOnlyList indices, int size, int vertexCount, CancellationToken cancellationToken) + { + for (int i = 0; i <= indices.Count - size; i += size) + { + if ((i & 4095) == 0) cancellationToken.ThrowIfCancellationRequested(); + if ((uint)indices[i] < (uint)vertexCount && (uint)indices[i + 1] < (uint)vertexCount && + (size == 2 || (uint)indices[i + 2] < (uint)vertexCount)) return true; + } + return false; + } + + private static Vector3d TransformPosition(Vector3d position, Vector3d? center, NwcGlbExportOptions options) + { + if (center is { } origin) position -= origin; + if (options.UnitScale != 1) position *= options.UnitScale; + return options.ConvertZUpToYUp ? new Vector3d(position.X, position.Z, -position.Y) : position; + } + + private static Quaterniond ToYUp(Quaterniond rotation) + { + // Left-compose -90 degrees around X. The camera's canonical local axes stay the same. + const double h = 0.7071067811865476; + var q = rotation.Normalized(); + return new Quaterniond(h * (q.X - q.W), h * (q.Y + q.Z), h * (q.Z - q.Y), h * (q.W + q.X)); + } + + private static void WriteTranslation(Utf8JsonWriter writer, Vector3d position) + { + if (!IsFinite(position)) throw new InvalidOperationException("The converted GLB node translation is not finite."); + writer.WriteStartArray("translation"); + writer.WriteNumberValue(position.X); + writer.WriteNumberValue(position.Y); + writer.WriteNumberValue(position.Z); + writer.WriteEndArray(); + } + + private static double ScaleLength(double length, double scale) + { + double converted = length * scale; + return double.IsFinite(converted) && converted > 0 ? converted : + throw new InvalidOperationException("The converted GLB camera length must be positive and finite."); + } + + private static bool FitsFloat(Vector3d position) => + float.IsFinite((float)position.X) && float.IsFinite((float)position.Y) && float.IsFinite((float)position.Z); + private static (double X, double Y, double Z)[] AccumulateNormals(IReadOnlyList vertices, List indices) { var normals = new (double X, double Y, double Z)[vertices.Count]; diff --git a/src/NwcIO/Compatibility/NwcAssembly.Compatibility.cs b/src/NwcIO/Compatibility/NwcAssembly.Compatibility.cs index 0d583ba..1cc461b 100644 --- a/src/NwcIO/Compatibility/NwcAssembly.Compatibility.cs +++ b/src/NwcIO/Compatibility/NwcAssembly.Compatibility.cs @@ -330,10 +330,16 @@ public void ExportClashMatrixBcf(string path) } /// Exports the entire federated assembly to a binary glTF 2.0 file (.glb). - public void SaveGlb(string path, bool worldCoordinates = true) - { - GlbExporter.WriteFile(AllMeshes, AllMaterials, path, worldCoordinates, "NwcIO Assembly", SavedViewpoints); - } + public void SaveGlb(string path, bool worldCoordinates = true) => + SaveGlb(path, NwcGlbExportOptions.ForCoordinates(worldCoordinates)); + + /// Exports the federated assembly to a binary glTF 2.0 file using the given options. + public void SaveGlb(string path, NwcGlbExportOptions options) => + GlbExporter.WriteFile(AllMeshes, AllMaterials, path, options, "NwcIO Assembly", SavedViewpoints); + + /// Exports the federated assembly to a binary glTF 2.0 stream using the given options. + public void SaveGlb(Stream stream, NwcGlbExportOptions options) => + GlbExporter.Write(AllMeshes, AllMaterials, stream, options, "NwcIO Assembly", SavedViewpoints); /// Exports the federated assembly as Wavefront OBJ with a sibling material library when needed. public void SaveObj(string path, bool worldCoordinates = true) diff --git a/src/NwcIO/Compatibility/NwcDocument.AsyncExports.cs b/src/NwcIO/Compatibility/NwcDocument.AsyncExports.cs index e34f6b5..d466508 100644 --- a/src/NwcIO/Compatibility/NwcDocument.AsyncExports.cs +++ b/src/NwcIO/Compatibility/NwcDocument.AsyncExports.cs @@ -28,12 +28,20 @@ public Task SaveObjAsync(TextWriter writer, bool worldCoordinates = true, Cancel /// Exports binary glTF to a file asynchronously. public Task SaveGlbAsync(string path, bool worldCoordinates = true, CancellationToken cancellationToken = default) => - CompatibilityExport.WriteFileAsync(path, output => GlbExporter.Write(Meshes, Materials, output, worldCoordinates, - viewpoints: SavedViewpoints, cancellationToken: cancellationToken), cancellationToken); + SaveGlbAsync(path, NwcGlbExportOptions.ForCoordinates(worldCoordinates), cancellationToken); /// Exports binary glTF to a stream asynchronously. public Task SaveGlbAsync(Stream stream, bool worldCoordinates = true, CancellationToken cancellationToken = default) => - CompatibilityExport.WriteAsync(stream, output => GlbExporter.Write(Meshes, Materials, output, worldCoordinates, + SaveGlbAsync(stream, NwcGlbExportOptions.ForCoordinates(worldCoordinates), cancellationToken); + + /// Exports binary glTF to a file asynchronously using the given options. + public Task SaveGlbAsync(string path, NwcGlbExportOptions options, CancellationToken cancellationToken = default) => + CompatibilityExport.WriteFileAsync(path, output => GlbExporter.Write(Meshes, Materials, output, options, + viewpoints: SavedViewpoints, cancellationToken: cancellationToken), cancellationToken); + + /// Exports binary glTF to a stream asynchronously using the given options. + public Task SaveGlbAsync(Stream stream, NwcGlbExportOptions options, CancellationToken cancellationToken = default) => + CompatibilityExport.WriteAsync(stream, output => GlbExporter.Write(Meshes, Materials, output, options, viewpoints: SavedViewpoints, cancellationToken: cancellationToken), cancellationToken); /// Exports an IFC STEP file asynchronously. diff --git a/src/NwcIO/Compatibility/NwcDocument.Compatibility.cs b/src/NwcIO/Compatibility/NwcDocument.Compatibility.cs index 72623b2..9facdae 100644 --- a/src/NwcIO/Compatibility/NwcDocument.Compatibility.cs +++ b/src/NwcIO/Compatibility/NwcDocument.Compatibility.cs @@ -268,16 +268,20 @@ public void SaveObj(TextWriter writer, bool worldCoordinates = true) } /// Exports 3D mesh geometry, materials, and saved cameras to a binary glTF 2.0 file (.glb). - public void SaveGlb(string path, bool worldCoordinates = true) - { - Internal.Export.GlbExporter.WriteFile(Meshes, Materials, path, worldCoordinates, viewpoints: SavedViewpoints); - } + public void SaveGlb(string path, bool worldCoordinates = true) => + SaveGlb(path, NwcGlbExportOptions.ForCoordinates(worldCoordinates)); /// Exports 3D mesh geometry, materials, and saved cameras to a binary glTF 2.0 stream (.glb). - public void SaveGlb(Stream stream, bool worldCoordinates = true) - { - Internal.Export.GlbExporter.Write(Meshes, Materials, stream, worldCoordinates, viewpoints: SavedViewpoints); - } + public void SaveGlb(Stream stream, bool worldCoordinates = true) => + SaveGlb(stream, NwcGlbExportOptions.ForCoordinates(worldCoordinates)); + + /// Exports binary glTF 2.0 to a file using the specified coordinate and camera options. + public void SaveGlb(string path, NwcGlbExportOptions options) => + Internal.Export.GlbExporter.WriteFile(Meshes, Materials, path, options, viewpoints: SavedViewpoints); + + /// Exports binary glTF 2.0 to a stream using the specified coordinate and camera options. + public void SaveGlb(Stream stream, NwcGlbExportOptions options) => + Internal.Export.GlbExporter.Write(Meshes, Materials, stream, options, viewpoints: SavedViewpoints); /// Exports 3D mesh geometry, materials, spatial structure, and properties to an IFC STEP physical file (.ifc). public void SaveIfc(string path, NwcIfcExportOptions? options = null) diff --git a/src/NwcIO/Compatibility/NwcGlbExportOptions.cs b/src/NwcIO/Compatibility/NwcGlbExportOptions.cs new file mode 100644 index 0000000..f3e07e6 --- /dev/null +++ b/src/NwcIO/Compatibility/NwcGlbExportOptions.cs @@ -0,0 +1,25 @@ +namespace NwcIO; + +/// Coordinate and camera options for the binary glTF 2.0 exporter. +public sealed class NwcGlbExportOptions +{ + private static readonly NwcGlbExportOptions World = new(); + private static readonly NwcGlbExportOptions Local = new() { WorldCoordinates = false }; + + /// Bakes mesh placements into world coordinates. The default is true. + public bool WorldCoordinates { get; init; } = true; + + /// Rotates positions, normals and saved cameras from +Z up to +Y up. The default is false. + public bool ConvertZUpToYUp { get; init; } + + /// Positive finite multiplier for geometry and camera lengths. The default is 1. + public double UnitScale { get; init; } = 1.0; + + /// Subtracts the mesh bounds' center before packing float positions and restores it on a root node. + public bool RecenterToOrigin { get; init; } + + /// Includes cameras from saved viewpoints. The default is true. + public bool ExportCameras { get; init; } = true; + + internal static NwcGlbExportOptions ForCoordinates(bool worldCoordinates) => worldCoordinates ? World : Local; +} diff --git a/tests/NwcIO.Tests/GlbExportTests.cs b/tests/NwcIO.Tests/GlbExportTests.cs index 5a921d5..93a3807 100644 --- a/tests/NwcIO.Tests/GlbExportTests.cs +++ b/tests/NwcIO.Tests/GlbExportTests.cs @@ -8,6 +8,235 @@ namespace NwcIO.Tests; public class GlbExportTests { + [Theory] + [InlineData(true)] + [InlineData(false)] + public void SaveGlb_ConvertsPositionsBoundsAndNormals(bool yUp) + { + var document = NwcDocument.Create(meshes: [new NwcMesh + { + Id = 1, + Vertices = [new(0, 0, 10), new(1000, 0, 0), new(0, 1000, 10), new(1000, 1000, 0)], + Indices = [0, 1, 2], + }]); + using var output = new MemoryStream(); + + document.SaveGlb(output, new NwcGlbExportOptions + { + ConvertZUpToYUp = yUp, + UnitScale = yUp ? 1 : 0.001, + }); + + byte[] glb = output.ToArray(); + using var json = ReadGlbJson(glb); + var root = json.RootElement; + var positions = GlbAccessor(root, 0, TrianglesMode, "POSITION"); + if (yUp) + { + Assert.Equal(new Vector3d(0, 10, 0), ReadGlbVector(glb, root, positions, 0)); + Assert.Equal(new Vector3d(0, 0, -1000), ReadJsonVector(positions.GetProperty("min"))); + Assert.Equal(new Vector3d(1000, 10, 0), ReadJsonVector(positions.GetProperty("max"))); + var normals = GlbAccessor(root, 0, TrianglesMode, "NORMAL"); + var normal = ReadGlbVector(glb, root, normals, 0); + Assert.Equal(0.0099995, normal.X, 7); + Assert.Equal(0.99995, normal.Y, 6); + Assert.Equal(0, normal.Z); + } + else + { + Assert.Equal(new Vector3d(1, 0, 0), ReadGlbVector(glb, root, positions, 1)); + Assert.Equal(Vector3d.Zero, ReadJsonVector(positions.GetProperty("min"))); + var max = positions.GetProperty("max"); + Assert.Equal(1f, max[0].GetSingle()); + Assert.Equal(1f, max[1].GetSingle()); + Assert.Equal(0.01f, max[2].GetSingle()); + } + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void SaveGlb_RecenterUsesDoublePrecisionBoundsOfExportedAssembly(bool worldCoordinates) + { + const double east = 1e12; + var first = NwcDocument.Create(meshes: [new NwcMesh + { + Id = 1, + Vertices = [new(0, 0, 0), new(2, 0, 0), new(0, 2, 0)], + Indices = [0, 1, 2], + Transform = new NwcTransform { Id = 1, Translation = new(east, 0, 0) }, + }]); + var second = NwcDocument.Create(meshes: + [ + new NwcMesh + { + Id = 2, + Vertices = [new(4, 2, 0), new(6, 2, 0)], + Indices = [], + LineIndices = [0, 1], + Transform = new NwcTransform { Id = 2, Translation = new(east, 0, 0) }, + }, + new NwcMesh + { + Id = 3, + Vertices = [new(50, 0, 0), new(100, 0, 0)], + Indices = [], + LineIndices = [0, 2], + }, + ]); + var assembly = NwcAssembly.Create("Recenter", first, second); + using var output = new MemoryStream(); + + assembly.SaveGlb(output, new NwcGlbExportOptions + { + WorldCoordinates = worldCoordinates, + RecenterToOrigin = true, + ExportCameras = false, + }); + + byte[] glb = output.ToArray(); + using var json = ReadGlbJson(glb); + var scene = json.RootElement; + Assert.Equal(2, Assert.Single(scene.GetProperty("scenes")[0].GetProperty("nodes").EnumerateArray()).GetInt32()); + var root = scene.GetProperty("nodes")[2]; + Assert.Equal(new Vector3d(worldCoordinates ? east + 3 : 3, 1, 0), ReadJsonVector(root.GetProperty("translation"))); + Assert.Collection(root.GetProperty("children").EnumerateArray(), + child => Assert.Equal(0, child.GetInt32()), child => Assert.Equal(1, child.GetInt32())); + Assert.False(scene.TryGetProperty("cameras", out _)); + Assert.Equal(new Vector3d(-3, -1, 0), ReadGlbVector(glb, scene, GlbAccessor(scene, 0, TrianglesMode, "POSITION"), 0)); + Assert.Equal(new Vector3d(3, 1, 0), ReadGlbVector(glb, scene, GlbAccessor(scene, 1, LinesMode, "POSITION"), 1)); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void SaveGlb_ConvertsCameraPoseAndProjectionWithGeometry(bool recenter) + { + var camera = new NwcCamera + { + Position = new(3000, 4000, 5000), + Rotation = new(0, Math.Sqrt(0.5), 0, Math.Sqrt(0.5)), + NearDistance = 100, + FarDistance = 50_000, + AspectRatio = 2, + FocalDistance = 4000, + }; + var document = NwcDocument.Create(meshes: [new NwcMesh + { + Id = 1, + Vertices = [new(1000, 1000, 3000), new(3000, 1000, 3000), new(1000, 3000, 3000)], + Indices = [0, 1, 2], + }], savedViewpoints: + [ + new NwcSavedViewpoint { Name = "Perspective", Camera = camera }, + new NwcSavedViewpoint { Name = "Orthographic", Camera = camera with { Projection = NwcCameraProjection.Orthographic } }, + ]); + using var output = new MemoryStream(); + + document.SaveGlb(output, new NwcGlbExportOptions + { + ConvertZUpToYUp = true, + UnitScale = 0.001, + RecenterToOrigin = recenter, + }); + + using var json = ReadGlbJson(output.ToArray()); + var scene = json.RootElement; + var nodes = scene.GetProperty("nodes"); + var offset = recenter ? ReadJsonVector(nodes[3].GetProperty("translation")) : Vector3d.Zero; + Assert.Equal(recenter ? new Vector3d(2, 3, -2) : Vector3d.Zero, offset); + for (int i = 0; i < 2; i++) + { + var node = nodes[1 + i]; + Assert.Equal(i, node.GetProperty("camera").GetInt32()); + var eye = ReadJsonVector(node.GetProperty("translation")); + Assert.Equal(recenter ? new Vector3d(1, 2, -2) : new Vector3d(3, 5, -4), eye); + Assert.Equal(new Vector3d(3, 5, -4), eye + offset); + var rotation = node.GetProperty("rotation"); + var rotated = new NwcCamera + { + Rotation = new(rotation[0].GetDouble(), rotation[1].GetDouble(), rotation[2].GetDouble(), rotation[3].GetDouble()), + }; + Assert.True(rotated.Rotation.IsNormalized()); + Assert.InRange((rotated.Direction - new Vector3d(-1, 0, 0)).Length, 0, 1e-12); + Assert.InRange((rotated.Up - new Vector3d(0, 0, -1)).Length, 0, 1e-12); + } + + var cameras = scene.GetProperty("cameras"); + var perspective = cameras[0].GetProperty("perspective"); + var orthographic = cameras[1].GetProperty("orthographic"); + Assert.Equal(2, perspective.GetProperty("aspectRatio").GetDouble()); + Assert.Equal(Math.PI / 3, perspective.GetProperty("yfov").GetDouble(), 12); + Assert.Equal(2, orthographic.GetProperty("xmag").GetDouble()); + Assert.Equal(1, orthographic.GetProperty("ymag").GetDouble()); + foreach (var projection in new[] { perspective, orthographic }) + { + Assert.Equal(0.1, projection.GetProperty("znear").GetDouble()); + Assert.Equal(50, projection.GetProperty("zfar").GetDouble()); + } + } + + [Theory] + [InlineData(0)] + [InlineData(-1)] + [InlineData(double.NaN)] + [InlineData(double.PositiveInfinity)] + public void SaveGlb_RejectsInvalidUnitScaleBeforeWriting(double scale) + { + using var output = new MemoryStream(); + + Assert.Throws(() => + NwcDocument.Create().SaveGlb(output, new NwcGlbExportOptions { UnitScale = scale })); + Assert.Equal(0, output.Length); + } + + [Fact] + public async Task SaveGlb_OptionsWorkAcrossPathStreamAndAsyncOverloads() + { + var document = NwcDocument.Create(meshes: [TriangleMesh(1, null)]); + var assembly = NwcAssembly.Create("Overloads", document); + var options = new NwcGlbExportOptions { ConvertZUpToYUp = true, UnitScale = 0.001 }; + using var expected = new MemoryStream(); + using var asyncStream = new MemoryStream(); + using var assemblyStream = new MemoryStream(); + string path = Path.Combine(Path.GetTempPath(), $"nwcio-test-{Guid.NewGuid():N}.glb"); + try + { + document.SaveGlb(expected, options); + document.SaveGlb(path, options); + Assert.Equal(expected.ToArray(), File.ReadAllBytes(path)); + await document.SaveGlbAsync(asyncStream, options); + Assert.Equal(expected.ToArray(), asyncStream.ToArray()); + await document.SaveGlbAsync(path, options); + Assert.Equal(expected.ToArray(), File.ReadAllBytes(path)); + + assembly.SaveGlb(assemblyStream, options); + assembly.SaveGlb(path, options); + Assert.Equal(assemblyStream.ToArray(), File.ReadAllBytes(path)); + } + finally + { + File.Delete(path); + } + } + + private static JsonElement GlbAccessor(JsonElement root, int mesh, int mode, string attribute) => + root.GetProperty("accessors")[PrimitiveOf(root, mesh, mode).GetProperty("attributes").GetProperty(attribute).GetInt32()]; + + private static Vector3d ReadGlbVector(byte[] glb, JsonElement root, JsonElement accessor, int index) + { + var view = root.GetProperty("bufferViews")[accessor.GetProperty("bufferView").GetInt32()]; + int start = 28 + BinaryPrimitives.ReadInt32LittleEndian(glb.AsSpan(12)) + + view.GetProperty("byteOffset").GetInt32() + accessor.GetProperty("byteOffset").GetInt32() + index * 12; + return new Vector3d( + BinaryPrimitives.ReadSingleLittleEndian(glb.AsSpan(start)), + BinaryPrimitives.ReadSingleLittleEndian(glb.AsSpan(start + 4)), + BinaryPrimitives.ReadSingleLittleEndian(glb.AsSpan(start + 8))); + } + + private static Vector3d ReadJsonVector(JsonElement array) => + new(array[0].GetDouble(), array[1].GetDouble(), array[2].GetDouble()); + [Theory] [InlineData(false)] [InlineData(true)]