Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
12 changes: 11 additions & 1 deletion docs/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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). |

Expand All @@ -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
Expand Down
173 changes: 149 additions & 24 deletions src/NwcIO/Compatibility/Export/GlbExporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
namespace NwcIO.Internal.Export;

/// <summary>
/// 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).
/// </summary>
internal static class GlbExporter
Expand All @@ -31,13 +31,22 @@ public static void WriteFile(
string path,
bool worldCoordinates = true,
string? generatorName = null,
IReadOnlyList<NwcSavedViewpoint>? viewpoints = null) =>
WriteFile(meshes, materials, path, NwcGlbExportOptions.ForCoordinates(worldCoordinates), generatorName, viewpoints);

public static void WriteFile(
IReadOnlyList<NwcMesh> meshes,
IReadOnlyList<NwcMaterial> materials,
string path,
NwcGlbExportOptions options,
string? generatorName = null,
IReadOnlyList<NwcSavedViewpoint>? 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(
Expand All @@ -47,11 +56,31 @@ public static void Write(
bool worldCoordinates = true,
string? generatorName = null,
IReadOnlyList<NwcSavedViewpoint>? viewpoints = null,
CancellationToken cancellationToken = default) =>
Write(meshes, materials, output, NwcGlbExportOptions.ForCoordinates(worldCoordinates), generatorName, viewpoints, cancellationToken);

public static void Write(
IReadOnlyList<NwcMesh> meshes,
IReadOnlyList<NwcMaterial> materials,
Stream output,
NwcGlbExportOptions options,
string? generatorName = null,
IReadOnlyList<NwcSavedViewpoint>? 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<BufferViewDef>();
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
}

Expand Down Expand Up @@ -441,6 +476,8 @@ private static ReadOnlyMemory<byte> BuildJsonChunk(
long binByteLength,
string generator,
IReadOnlyList<NwcSavedViewpoint>? viewpoints,
Vector3d? center,
NwcGlbExportOptions options,
HashSet<int>? materialsWithBlend,
List<string> images,
Dictionary<int, int> materialTextures,
Expand All @@ -464,14 +501,19 @@ private static ReadOnlyMemory<byte> 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();
Expand Down Expand Up @@ -500,23 +542,30 @@ private static ReadOnlyMemory<byte> 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
Expand All @@ -537,10 +586,10 @@ private static ReadOnlyMemory<byte> 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
Expand All @@ -549,8 +598,8 @@ private static ReadOnlyMemory<byte> 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();
}

Expand Down Expand Up @@ -718,6 +767,82 @@ private static ReadOnlyMemory<byte> BuildJsonChunk(
return json.WrittenMemory;
}

private static Vector3d? FindCenter(IReadOnlyList<NwcMesh> 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<int> 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<Vector3d> vertices, List<int> indices)
{
var normals = new (double X, double Y, double Z)[vertices.Count];
Expand Down
14 changes: 10 additions & 4 deletions src/NwcIO/Compatibility/NwcAssembly.Compatibility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -330,10 +330,16 @@ public void ExportClashMatrixBcf(string path)
}

/// <summary>Exports the entire federated assembly to a binary glTF 2.0 file (.glb).</summary>
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));

/// <summary>Exports the federated assembly to a binary glTF 2.0 file using the given options.</summary>
public void SaveGlb(string path, NwcGlbExportOptions options) =>
GlbExporter.WriteFile(AllMeshes, AllMaterials, path, options, "NwcIO Assembly", SavedViewpoints);

/// <summary>Exports the federated assembly to a binary glTF 2.0 stream using the given options.</summary>
public void SaveGlb(Stream stream, NwcGlbExportOptions options) =>
GlbExporter.Write(AllMeshes, AllMaterials, stream, options, "NwcIO Assembly", SavedViewpoints);

/// <summary>Exports the federated assembly as Wavefront OBJ with a sibling material library when needed.</summary>
public void SaveObj(string path, bool worldCoordinates = true)
Expand Down
14 changes: 11 additions & 3 deletions src/NwcIO/Compatibility/NwcDocument.AsyncExports.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,20 @@ public Task SaveObjAsync(TextWriter writer, bool worldCoordinates = true, Cancel

/// <summary>Exports binary glTF to a file asynchronously.</summary>
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);

/// <summary>Exports binary glTF to a stream asynchronously.</summary>
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);

/// <summary>Exports binary glTF to a file asynchronously using the given options.</summary>
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);

/// <summary>Exports binary glTF to a stream asynchronously using the given options.</summary>
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);

/// <summary>Exports an IFC STEP file asynchronously.</summary>
Expand Down
Loading
Loading