From 58f0e35591c6c4ad4c10de478eb45b21121d4545 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:18:40 +0300 Subject: [PATCH] Write Wavefront materials alongside OBJ files --- CHANGELOG.md | 4 + docs/public-api.md | 6 + src/NwcIO/Compatibility/Export/ObjExporter.cs | 104 ++++++++++++- .../NwcAssembly.Compatibility.cs | 2 +- .../Compatibility/NwcDocument.AsyncExports.cs | 6 +- .../NwcDocument.Compatibility.cs | 2 +- src/NwcIO/Internal/AtomicFileWriter.cs | 143 ++++++++++++++++-- tests/NwcIO.Tests/AsyncDocumentIoTests.cs | 27 +++- tests/NwcIO.Tests/ObjExportTests.cs | 134 ++++++++++++++++ 9 files changed, 398 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d44fb3..fa81466 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] +### 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 diff --git a/docs/public-api.md b/docs/public-api.md index 19ccca1..b3837b2 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -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 `.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 diff --git a/src/NwcIO/Compatibility/Export/ObjExporter.cs b/src/NwcIO/Compatibility/Export/ObjExporter.cs index 10fd3db..78253d4 100644 --- a/src/NwcIO/Compatibility/Export/ObjExporter.cs +++ b/src/NwcIO/Compatibility/Export/ObjExporter.cs @@ -1,4 +1,4 @@ -using System.Globalization; +using System.Text; using NwcIO.Model; namespace NwcIO.Internal.Export; @@ -9,6 +9,9 @@ namespace NwcIO.Internal.Export; /// internal static class ObjExporter { + private static readonly Encoding Utf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); + private const string DefaultMaterial = "nwc_default"; + /// /// Writes meshes to a file in Wavefront OBJ format. /// @@ -17,14 +20,68 @@ public static void WriteFile( string path, bool worldCoordinates = true, string? sourceDocument = null, - Func? objectNamePrefix = null) + Func? objectNamePrefix = null) => + WriteFileCore(meshes, path, worldCoordinates, sourceDocument, objectNamePrefix, asynchronous: false, default) + .GetSynchronousResult(); + + public static Task WriteFileAsync(IReadOnlyList 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 meshes, string path, bool worldCoordinates, + string? sourceDocument, Func? objectNamePrefix, bool asynchronous, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(meshes); ArgumentNullException.ThrowIfNull(path); + cancellationToken.ThrowIfCancellationRequested(); + + var materials = new Dictionary(); + 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)? 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 write) + { + if (asynchronous) + { + return new ValueTask(CompatibilityExport.WriteAsync(output, stream => CompatibilityExport.WriteText(stream, Utf8, write), + cancellationToken)); + } + CompatibilityExport.WriteText(output, Utf8, write); + return ValueTask.CompletedTask; + } } /// @@ -36,7 +93,12 @@ public static void Write( bool worldCoordinates = true, string? sourceDocument = null, Func? objectNamePrefix = null, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default) => + WriteCore(meshes, writer, worldCoordinates, sourceDocument, objectNamePrefix, null, null, cancellationToken); + + private static void WriteCore(IReadOnlyList meshes, TextWriter writer, bool worldCoordinates, + string? sourceDocument, Func? objectNamePrefix, + string? materialFileName, Dictionary? materials, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(meshes); ArgumentNullException.ThrowIfNull(writer); @@ -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; @@ -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) { @@ -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 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; + } + /// OBJ directives are line based; never let a name from the file inject its own line. private static string SanitizeObjLine(string value) { diff --git a/src/NwcIO/Compatibility/NwcAssembly.Compatibility.cs b/src/NwcIO/Compatibility/NwcAssembly.Compatibility.cs index 56d4fcf..0d583ba 100644 --- a/src/NwcIO/Compatibility/NwcAssembly.Compatibility.cs +++ b/src/NwcIO/Compatibility/NwcAssembly.Compatibility.cs @@ -335,7 +335,7 @@ public void SaveGlb(string path, bool worldCoordinates = true) GlbExporter.WriteFile(AllMeshes, AllMaterials, path, worldCoordinates, "NwcIO Assembly", SavedViewpoints); } - /// Exports the entire federated assembly to a Wavefront OBJ file. + /// Exports the federated assembly as Wavefront OBJ with a sibling material library when needed. public void SaveObj(string path, bool worldCoordinates = true) { ObjExporter.WriteFile(AllMeshes, path, worldCoordinates, Name, GetObjModelLabel); diff --git a/src/NwcIO/Compatibility/NwcDocument.AsyncExports.cs b/src/NwcIO/Compatibility/NwcDocument.AsyncExports.cs index 0df07b5..e34f6b5 100644 --- a/src/NwcIO/Compatibility/NwcDocument.AsyncExports.cs +++ b/src/NwcIO/Compatibility/NwcDocument.AsyncExports.cs @@ -10,11 +10,9 @@ public sealed partial class NwcDocument { private static readonly Encoding ExportUtf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); - /// Exports Wavefront OBJ to a file asynchronously. + /// Exports Wavefront OBJ and a sibling material library when needed, asynchronously. 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); /// Exports Wavefront OBJ to a UTF-8 stream asynchronously. public Task SaveObjAsync(Stream stream, bool worldCoordinates = true, CancellationToken cancellationToken = default) => diff --git a/src/NwcIO/Compatibility/NwcDocument.Compatibility.cs b/src/NwcIO/Compatibility/NwcDocument.Compatibility.cs index 42ddbe4..72623b2 100644 --- a/src/NwcIO/Compatibility/NwcDocument.Compatibility.cs +++ b/src/NwcIO/Compatibility/NwcDocument.Compatibility.cs @@ -255,7 +255,7 @@ public void ExportClashBcf(Stream stream, string? testName = null) return tests; } - /// Exports 3D mesh geometry to a Wavefront OBJ file. + /// Exports Wavefront OBJ geometry and a sibling material library when needed. public void SaveObj(string path, bool worldCoordinates = true) { Internal.Export.ObjExporter.WriteFile(Meshes, path, worldCoordinates, FileInfo.SourcePath); diff --git a/src/NwcIO/Internal/AtomicFileWriter.cs b/src/NwcIO/Internal/AtomicFileWriter.cs index 7b90cb6..49aac1a 100644 --- a/src/NwcIO/Internal/AtomicFileWriter.cs +++ b/src/NwcIO/Internal/AtomicFileWriter.cs @@ -14,26 +14,72 @@ public static void Write(string path, Action write, CancellationToken ca public static ValueTask WriteAsync(string path, Func write, CancellationToken cancellationToken) => WriteCore(path, write, asynchronous: true, cancellationToken); - private static async ValueTask WriteCore( - string path, Func write, bool asynchronous, CancellationToken cancellationToken) + internal static async ValueTask WriteCore( + string path, Func write, bool asynchronous, CancellationToken cancellationToken, + (string Path, Func 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 StageFile(string path, Func 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 @@ -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; diff --git a/tests/NwcIO.Tests/AsyncDocumentIoTests.cs b/tests/NwcIO.Tests/AsyncDocumentIoTests.cs index 34de480..274b246 100644 --- a/tests/NwcIO.Tests/AsyncDocumentIoTests.cs +++ b/tests/NwcIO.Tests/AsyncDocumentIoTests.cs @@ -221,19 +221,28 @@ public async Task CompatibilityExports_PreCancelled_PreserveExistingOutput(strin } [Theory] - [InlineData(false)] - [InlineData(true)] - public async Task CancelledGeometryExport_PreservesExistingDestination(bool glb) + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(false, true)] + public async Task CancelledGeometryExport_PreservesExistingDestination(bool glb, bool withMaterial) { var directory = Directory.CreateTempSubdirectory("nwcio-cancel-geometry-"); string path = Path.Combine(directory.FullName, glb ? "model.glb" : "model.obj"); + string library = Path.ChangeExtension(path, ".mtl"); try { byte[] original = [1, 2, 3]; File.WriteAllBytes(path, original); + if (withMaterial) File.WriteAllText(library, "original materials"); using var cancellation = new CancellationTokenSource(); var vertices = new CancellingVertices(cancellation); - var doc = NwcDocument.Create(meshes: [new NwcMesh { Id = 1, Vertices = vertices, Indices = [0, 1, 2] }]); + var doc = NwcDocument.Create(meshes: [new NwcMesh + { + Id = 1, + Vertices = vertices, + Indices = [0, 1, 2], + Material = withMaterial ? new NwcMaterial { Id = 1, Name = "Glass", Color = RgbaColor.Glass } : null, + }]); Task save = glb ? doc.SaveGlbAsync(path, worldCoordinates: false, cancellationToken: cancellation.Token) @@ -243,7 +252,15 @@ public async Task CancelledGeometryExport_PreservesExistingDestination(bool glb) Assert.Equal(cancellation.Token, error.CancellationToken); Assert.True(save.IsCanceled); Assert.Equal(original, File.ReadAllBytes(path)); - Assert.Equal(path, Assert.Single(Directory.GetFiles(directory.FullName))); + if (withMaterial) + { + Assert.Equal("original materials", File.ReadAllText(library)); + Assert.Equal(2, Directory.GetFiles(directory.FullName).Length); + } + else + { + Assert.Equal(path, Assert.Single(Directory.GetFiles(directory.FullName))); + } } finally { diff --git a/tests/NwcIO.Tests/ObjExportTests.cs b/tests/NwcIO.Tests/ObjExportTests.cs index a4dac85..6a28dd4 100644 --- a/tests/NwcIO.Tests/ObjExportTests.cs +++ b/tests/NwcIO.Tests/ObjExportTests.cs @@ -6,6 +6,140 @@ namespace NwcIO.Tests; public class ObjExportTests { + [Theory] + [InlineData("document")] + [InlineData("async")] + [InlineData("assembly")] + public async Task SaveObj_WritesAndReferencesSiblingMaterialLibrary(string entryPoint) + { + var directory = Directory.CreateTempSubdirectory("nwcio-obj-materials-"); + try + { + var glass = new NwcMaterial { Id = 1, Name = "Shared\nName", Color = new(0.25f, 0.5f, 0.75f, 0.5f) }; + var paint = new NwcMaterial { Id = 1, Name = glass.Name, Color = new(1, 0.25f, 0) }; + var first = NwcDocument.Create(meshes: [Triangle(1, glass), Triangle(2, null), Triangle(3, glass)]); + var second = NwcDocument.Create(meshes: [Triangle(4, paint)]); + string path = Path.Combine(directory.FullName, "model with spaces.obj"); + var document = NwcDocument.Create(meshes: [.. first.Meshes, .. second.Meshes]); + switch (entryPoint) + { + case "async": await document.SaveObjAsync(path); break; + case "assembly": NwcAssembly.Create("Federation", first, second).SaveObj(path); break; + default: document.SaveObj(path); break; + } + + var obj = File.ReadAllLines(path); + Assert.Equal("mtllib model with spaces.mtl", Assert.Single(obj, line => line.StartsWith("mtllib ", StringComparison.Ordinal))); + Assert.Equal(["usemtl nwc_1", "f 1 2 3", "usemtl nwc_default", "f 4 5 6", "usemtl nwc_1", "f 7 8 9", "usemtl nwc_2", "f 10 11 12"], + obj.Where(line => line.StartsWith("f ", StringComparison.Ordinal) || line.StartsWith("usemtl ", StringComparison.Ordinal))); + var mtl = File.ReadAllLines(Path.ChangeExtension(path, ".mtl")); + Assert.Equal(["newmtl nwc_1", "Kd 0.25 0.5 0.75", "d 0.5", "newmtl nwc_2", "Kd 1 0.25 0", "d 1", "newmtl nwc_default", "Kd 1 1 1", "d 1"], + mtl.Where(line => line.Length != 0)); + + using var writer = new StringWriter(); + document.SaveObj(writer); + Assert.DoesNotContain("mtllib ", writer.ToString()); + Assert.DoesNotContain("usemtl ", writer.ToString()); + } + finally + { + directory.Delete(recursive: true); + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void SaveObj_FailedObjReplacement_RollsBackMaterialLibrary(bool existingLibrary) + { + var directory = Directory.CreateTempSubdirectory("nwcio-obj-rollback-"); + try + { + string path = Directory.CreateDirectory(Path.Combine(directory.FullName, "model.obj")).FullName; + string library = Path.ChangeExtension(path, ".mtl"); + if (existingLibrary) File.WriteAllText(library, "original materials"); + var document = NwcDocument.Create(meshes: [Triangle(1, new NwcMaterial { Id = 1, Name = "Glass", Color = RgbaColor.Glass })]); + + var failure = Record.Exception(() => document.SaveObj(path)); + + Assert.True(failure is IOException or UnauthorizedAccessException, failure?.ToString()); + Assert.True(Directory.Exists(path)); + if (existingLibrary) + { + Assert.Equal(library, Assert.Single(Directory.GetFiles(directory.FullName))); + Assert.Equal("original materials", File.ReadAllText(library)); + } + else + { + Assert.Empty(Directory.GetFiles(directory.FullName)); + } + } + finally + { + directory.Delete(recursive: true); + } + } + + [Fact] + public void SaveObj_RejectsLinkedMaterialPathAndPreservesExistingFiles() + { + if (OperatingSystem.IsWindows()) return; + var directory = Directory.CreateTempSubdirectory("nwcio-obj-linked-material-"); + try + { + string path = Path.Combine(directory.FullName, "model.obj"); + string library = Path.ChangeExtension(path, ".mtl"); + string otherFile = Path.Combine(directory.FullName, "untouched.txt"); + File.WriteAllText(path, "original geometry"); + File.WriteAllText(otherFile, "original target"); + File.CreateSymbolicLink(library, otherFile); + var document = NwcDocument.Create(meshes: [Triangle(1, new NwcMaterial { Id = 1, Name = "Glass", Color = RgbaColor.Glass })]); + + Assert.Throws(() => document.SaveObj(path)); + + Assert.Equal("original geometry", File.ReadAllText(path)); + Assert.Equal("original target", File.ReadAllText(otherFile)); + Assert.Equal(otherFile, new FileInfo(library).LinkTarget); + Assert.Equal(3, Directory.GetFiles(directory.FullName).Length); + } + finally + { + directory.Delete(recursive: true); + } + } + + [Fact] + public async Task SaveObjAsync_ConcurrentSaves_KeepGeometryAndMaterialFromSameDocument() + { + var directory = Directory.CreateTempSubdirectory("nwcio-obj-concurrent-"); + try + { + string path = Path.Combine(directory.FullName, "model.obj"); + var black = NwcDocument.Create(meshes: [Triangle(1, new NwcMaterial { Id = 1, Name = "Black", Color = RgbaColor.Black })]); + var white = NwcDocument.Create(meshes: [Triangle(2, new NwcMaterial { Id = 1, Name = "White", Color = RgbaColor.White })]); + + await Task.WhenAll(Enumerable.Range(0, 6).Select(i => (i % 2 == 0 ? black : white).SaveObjAsync(path))); + + string name = Assert.Single(File.ReadLines(path), line => line.StartsWith("o ", StringComparison.Ordinal)); + Assert.True(name is "o Mesh_1" or "o Mesh_2", name); + string diffuse = name == "o Mesh_1" ? "Kd 0 0 0" : "Kd 1 1 1"; + Assert.Contains(diffuse, File.ReadAllLines(Path.ChangeExtension(path, ".mtl"))); + Assert.Equal(2, Directory.GetFiles(directory.FullName).Length); + } + finally + { + directory.Delete(recursive: true); + } + } + + private static NwcMesh Triangle(int id, NwcMaterial? material) => new() + { + Id = id, + Vertices = [new(0, 0, 0), new(1, 0, 0), new(0, 1, 0)], + Indices = [0, 1, 2], + Material = material, + }; + [Theory] [InlineData(true, "f 1 3 2", "f 3 4 2")] [InlineData(false, "f 1 2 3", "f 3 2 4")]