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]

### Fixed

- Path-based Wavefront OBJ export writes a sibling `.mtl` with diffuse colors and opacity from mesh materials (#93). Texture coordinates and texture maps are pending.

## [0.16.0] - 2026-11-19

### Added
Expand Down
6 changes: 6 additions & 0 deletions docs/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,12 @@ In the HTML viewer, use Tab to reach the viewpoint, clash, hierarchy and set but
Space to activate them. With focus on the 3D model view, the arrow keys orbit, + and - zoom, and
Home resets the camera. Escape clears the current measurement while Measure is active.

OBJ saves to a path, including `SaveObjAsync`, write a sibling `<name>.mtl` when exported geometry
has materials. The library stores diffuse RGB (`Kd`) and opacity (`d`). OBJ saves to a stream or
`TextWriter` export geometry only. Texture coordinates and texture maps are currently unsupported.
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.

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
104 changes: 98 additions & 6 deletions src/NwcIO/Compatibility/Export/ObjExporter.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Globalization;
using System.Text;
using NwcIO.Model;

namespace NwcIO.Internal.Export;
Expand All @@ -9,6 +9,9 @@ namespace NwcIO.Internal.Export;
/// </summary>
internal static class ObjExporter
{
private static readonly Encoding Utf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
private const string DefaultMaterial = "nwc_default";

/// <summary>
/// Writes meshes to a file in Wavefront OBJ format.
/// </summary>
Expand All @@ -17,14 +20,68 @@ public static void WriteFile(
string path,
bool worldCoordinates = true,
string? sourceDocument = null,
Func<NwcMesh, string?>? objectNamePrefix = null)
Func<NwcMesh, string?>? objectNamePrefix = null) =>
WriteFileCore(meshes, path, worldCoordinates, sourceDocument, objectNamePrefix, asynchronous: false, default)
.GetSynchronousResult();

public static Task WriteFileAsync(IReadOnlyList<NwcMesh> meshes, string path, bool worldCoordinates,
string? sourceDocument, CancellationToken cancellationToken) =>
WriteFileCore(meshes, path, worldCoordinates, sourceDocument, null, asynchronous: true, cancellationToken).AsTask();

private static async ValueTask WriteFileCore(IReadOnlyList<NwcMesh> meshes, string path, bool worldCoordinates,
string? sourceDocument, Func<NwcMesh, string?>? objectNamePrefix, bool asynchronous, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(meshes);
ArgumentNullException.ThrowIfNull(path);
cancellationToken.ThrowIfCancellationRequested();

var materials = new Dictionary<NwcMaterial, string>();
bool hasUnassigned = false;
foreach (var mesh in meshes)
{
cancellationToken.ThrowIfCancellationRequested();
if (mesh.Vertices.Count == 0 || !HasPrimitives(mesh)) continue;
if (mesh.Material is { } material)
{
if (!materials.ContainsKey(material))
{
materials.Add(material, FormattableString.Invariant($"nwc_{materials.Count + 1}"));
}
}
else
{
hasUnassigned = true;
}
}

string? materialFileName = null;
(string, Func<Stream, ValueTask>)? companion = null;
if (materials.Count != 0)
{
string materialPath = Path.ChangeExtension(Path.GetFullPath(path), ".mtl");
materialFileName = Path.GetFileName(materialPath);
if (materialFileName != SanitizeObjLine(materialFileName) || materialFileName.Contains('#') || materialFileName.Contains('\\'))
{
throw new ArgumentException("The output file name cannot be written as an OBJ material library reference.", nameof(path));
}
companion = (materialPath, output => WriteText(output,
writer => WriteMaterials(writer, materials, hasUnassigned, cancellationToken)));
}

using var fs = File.Create(path);
using var writer = new StreamWriter(fs, new System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: false), bufferSize: 65536);
Write(meshes, writer, worldCoordinates, sourceDocument, objectNamePrefix);
await AtomicFileWriter.WriteCore(path, output => WriteText(output, writer => WriteCore(meshes, writer,
worldCoordinates, sourceDocument, objectNamePrefix, materialFileName, companion.HasValue ? materials : null, cancellationToken)),
asynchronous, cancellationToken, companion).ConfigureAwait(false);

ValueTask WriteText(Stream output, Action<TextWriter> write)
{
if (asynchronous)
{
return new ValueTask(CompatibilityExport.WriteAsync(output, stream => CompatibilityExport.WriteText(stream, Utf8, write),
cancellationToken));
}
CompatibilityExport.WriteText(output, Utf8, write);
return ValueTask.CompletedTask;
}
}

/// <summary>
Expand All @@ -36,7 +93,12 @@ public static void Write(
bool worldCoordinates = true,
string? sourceDocument = null,
Func<NwcMesh, string?>? objectNamePrefix = null,
CancellationToken cancellationToken = default)
CancellationToken cancellationToken = default) =>
WriteCore(meshes, writer, worldCoordinates, sourceDocument, objectNamePrefix, null, null, cancellationToken);

private static void WriteCore(IReadOnlyList<NwcMesh> meshes, TextWriter writer, bool worldCoordinates,
string? sourceDocument, Func<NwcMesh, string?>? objectNamePrefix,
string? materialFileName, Dictionary<NwcMaterial, string>? materials, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(meshes);
ArgumentNullException.ThrowIfNull(writer);
Expand All @@ -49,6 +111,7 @@ public static void Write(

writer.WriteLine(FormattableString.Invariant($"# Meshes: {meshes.Count}"));
writer.WriteLine(FormattableString.Invariant($"# Coordinate Space: {(worldCoordinates ? "World" : "Local")}"));
if (materialFileName is not null) writer.WriteLine($"mtllib {materialFileName}");
writer.WriteLine();

int baseVertexIndex = 1;
Expand Down Expand Up @@ -84,6 +147,12 @@ public static void Write(
writer.WriteLine(FormattableString.Invariant($"v {pt.X:F4} {pt.Y:F4} {pt.Z:F4}"));
}

if (materials is not null && HasPrimitives(mesh))
{
string materialName = mesh.Material is { } material ? materials[material] : DefaultMaterial;
writer.WriteLine($"usemtl {materialName}");
}

// Triangle faces (1-based global indices)
if (mesh.Indices.Count > 0)
{
Expand Down Expand Up @@ -113,6 +182,29 @@ public static void Write(
}
}

private static bool HasPrimitives(NwcMesh mesh) => mesh.Indices.Count >= 3 || mesh.LineIndices.Count >= 2;

private static void WriteMaterials(TextWriter writer, Dictionary<NwcMaterial, string> materials, bool hasUnassigned,
CancellationToken cancellationToken)
{
foreach (var (material, name) in materials)
{
cancellationToken.ThrowIfCancellationRequested();
WriteMaterial(name, material.Color);
}
if (hasUnassigned) WriteMaterial(DefaultMaterial, RgbaColor.White);

void WriteMaterial(string name, RgbaColor color)
{
writer.WriteLine($"newmtl {name}");
writer.WriteLine(FormattableString.Invariant($"Kd {Component(color.R):R} {Component(color.G):R} {Component(color.B):R}"));
writer.WriteLine(FormattableString.Invariant($"d {Component(color.A):R}"));
writer.WriteLine();
}

static float Component(float value) => float.IsFinite(value) ? Math.Clamp(value, 0, 1) : 0;
}

/// <summary>OBJ directives are line based; never let a name from the file inject its own line.</summary>
private static string SanitizeObjLine(string value)
{
Expand Down
2 changes: 1 addition & 1 deletion src/NwcIO/Compatibility/NwcAssembly.Compatibility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,7 @@ public void SaveGlb(string path, bool worldCoordinates = true)
GlbExporter.WriteFile(AllMeshes, AllMaterials, path, worldCoordinates, "NwcIO Assembly", SavedViewpoints);
}

/// <summary>Exports the entire federated assembly to a Wavefront OBJ file.</summary>
/// <summary>Exports the federated assembly as Wavefront OBJ with a sibling material library when needed.</summary>
public void SaveObj(string path, bool worldCoordinates = true)
{
ObjExporter.WriteFile(AllMeshes, path, worldCoordinates, Name, GetObjModelLabel);
Expand Down
6 changes: 2 additions & 4 deletions src/NwcIO/Compatibility/NwcDocument.AsyncExports.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,9 @@ public sealed partial class NwcDocument
{
private static readonly Encoding ExportUtf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);

/// <summary>Exports Wavefront OBJ to a file asynchronously.</summary>
/// <summary>Exports Wavefront OBJ and a sibling material library when needed, asynchronously.</summary>
public Task SaveObjAsync(string path, bool worldCoordinates = true, CancellationToken cancellationToken = default) =>
CompatibilityExport.WriteFileAsync(path, stream => CompatibilityExport.WriteText(stream, ExportUtf8,
writer => ObjExporter.Write(Meshes, writer, worldCoordinates, FileInfo.SourcePath, cancellationToken: cancellationToken)),
cancellationToken);
ObjExporter.WriteFileAsync(Meshes, path, worldCoordinates, FileInfo.SourcePath, cancellationToken);

/// <summary>Exports Wavefront OBJ to a UTF-8 stream asynchronously.</summary>
public Task SaveObjAsync(Stream stream, bool worldCoordinates = true, CancellationToken cancellationToken = default) =>
Expand Down
2 changes: 1 addition & 1 deletion src/NwcIO/Compatibility/NwcDocument.Compatibility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ public void ExportClashBcf(Stream stream, string? testName = null)
return tests;
}

/// <summary>Exports 3D mesh geometry to a Wavefront OBJ file.</summary>
/// <summary>Exports Wavefront OBJ geometry and a sibling material library when needed.</summary>
public void SaveObj(string path, bool worldCoordinates = true)
{
Internal.Export.ObjExporter.WriteFile(Meshes, path, worldCoordinates, FileInfo.SourcePath);
Expand Down
143 changes: 130 additions & 13 deletions src/NwcIO/Internal/AtomicFileWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,26 +14,72 @@ public static void Write(string path, Action<Stream> write, CancellationToken ca
public static ValueTask WriteAsync(string path, Func<Stream, ValueTask> write, CancellationToken cancellationToken)
=> WriteCore(path, write, asynchronous: true, cancellationToken);

private static async ValueTask WriteCore(
string path, Func<Stream, ValueTask> write, bool asynchronous, CancellationToken cancellationToken)
internal static async ValueTask WriteCore(
string path, Func<Stream, ValueTask> write, bool asynchronous, CancellationToken cancellationToken,
(string Path, Func<Stream, ValueTask> Write)? companion = null)
{
cancellationToken.ThrowIfCancellationRequested();
var primary = await StageFile(path, write, asynchronous, companion.HasValue, isCompanion: false, cancellationToken)
.ConfigureAwait(false);
StagedFile? secondary = null;
bool committed = false;
try
{
cancellationToken.ThrowIfCancellationRequested();
if (companion is { } pending)
{
var staged = await StageFile(pending.Path, pending.Write, asynchronous, paired: true, isCompanion: true, cancellationToken)
.ConfigureAwait(false);
secondary = staged;
if (string.Equals(primary.Target.FullName, staged.Target.FullName, StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException("The output and its companion must be different files.", nameof(path));
}
WithPairLock(() => CommitPair(primary, staged), cancellationToken);
}
else
{
File.Move(primary.Temp, primary.Target.FullName, overwrite: primary.Target.Exists);
}

committed = true;
}
finally
{
if (!committed)
{
File.Delete(primary.Temp);
if (secondary is { } staged) File.Delete(staged.Temp);
}
}
}

private static FileInfo GetTarget(string path, bool isCompanion)
{
var target = new FileInfo(Path.GetFullPath(path));
if (target.LinkTarget is not null)
{
if (isCompanion) throw new IOException($"The companion file '{path}' is a symbolic link.");
target = new FileInfo(target.ResolveLinkTarget(returnFinalTarget: true)!.FullName);
}

bool exists = target.Exists;
if (exists)
if (target.Exists)
{
// A rename can bypass the destination's file write permissions on Unix.
using var accessCheck = target.Open(FileMode.Open, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete);
}

string temp = Path.Combine(target.DirectoryName!, $"nwcio-{Guid.NewGuid():N}.tmp");
var output = CreateTemporaryFile(temp, target, exists, asynchronous);
bool committed = false;
return target;
}

private static async ValueTask<StagedFile> StageFile(string path, Func<Stream, ValueTask> write,
bool asynchronous, bool paired, bool isCompanion, CancellationToken cancellationToken)
{
StagedFile staged = default;
FileStream? stream = null;
if (paired) WithPairLock(Prepare, cancellationToken);
else Prepare();
var output = stream!;
try
{
try
Expand All @@ -52,19 +98,90 @@ private static async ValueTask WriteCore(
}
}

cancellationToken.ThrowIfCancellationRequested();
File.Move(temp, target.FullName, overwrite: exists);
committed = true;
return staged;
}
finally
catch
{
if (!committed)
File.Delete(staged.Temp);
throw;
}

void Prepare()
{
var target = GetTarget(path, isCompanion);
staged = new StagedFile(TemporarySibling(target.DirectoryName!), target);
stream = CreateTemporaryFile(staged.Temp, target, target.Exists, asynchronous);
}
}

private static void WithPairLock(Action action, CancellationToken cancellationToken)
{
// Serialize permission checks and renames across CLI processes. File contents are written outside the lock.
using var commitLock = new Mutex(initiallyOwned: false, "NwcIO.AtomicFileWriter.Pair");
bool acquired = false;
try
{
do
{
File.Delete(temp);
cancellationToken.ThrowIfCancellationRequested();
try
{
acquired = commitLock.WaitOne(50);
}
catch (AbandonedMutexException)
{
acquired = true;
}
}
while (!acquired);

cancellationToken.ThrowIfCancellationRequested();
action();
}
finally
{
if (acquired) commitLock.ReleaseMutex();
}
}

private static void CommitPair(StagedFile primary, StagedFile companion)
{
// Once publication starts it must finish or restore the original companion, even if cancelled.
string path = primary.Target.FullName;
string companionPath = companion.Target.FullName;
if (new FileInfo(companionPath).LinkTarget is not null)
{
throw new IOException($"The companion file '{companionPath}' is a symbolic link.");
}
string? backup = null;
if (File.Exists(companionPath))
{
backup = TemporarySibling(companion.Target.DirectoryName!);
File.Replace(companion.Temp, companionPath, backup);
}
else
{
File.Move(companion.Temp, companionPath);
}

try
{
File.Move(primary.Temp, path, overwrite: File.Exists(path));
}
catch
{
if (backup is null) File.Delete(companionPath);
else File.Move(backup, companionPath, overwrite: true);
throw;
}

if (backup is not null) File.Delete(backup);
}

private readonly record struct StagedFile(string Temp, FileInfo Target);

private static string TemporarySibling(string directory) => Path.Combine(directory, $"nwcio-{Guid.NewGuid():N}.tmp");

private static FileStream CreateTemporaryFile(string path, FileInfo target, bool exists, bool asynchronous)
{
var fileOptions = asynchronous ? FileOptions.Asynchronous : FileOptions.None;
Expand Down
Loading
Loading