From 5786ea39a9df64e3847d2c98293e872f0aa6034b Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:50:52 +0300 Subject: [PATCH] Add cancellable async compatibility exports --- docs/public-api.md | 7 + src/NwcIO/Compatibility/Export/BcfExporter.cs | 5 +- .../Export/CompatibilityExport.cs | 184 +++++++++++ src/NwcIO/Compatibility/Export/GlbExporter.cs | 24 +- src/NwcIO/Compatibility/Export/IfcExporter.cs | 4 +- src/NwcIO/Compatibility/Export/ObjExporter.cs | 4 +- .../Compatibility/NwcDocument.AsyncExports.cs | 96 ++++++ .../Sectioning/NwcXmlViewpointSerializer.cs | 12 +- .../Viewer/NwcHtmlViewerExporter.cs | 57 +++- tests/NwcIO.Tests/AsyncDocumentIoTests.cs | 307 +++++++++++++++++- 10 files changed, 676 insertions(+), 24 deletions(-) create mode 100644 src/NwcIO/Compatibility/Export/CompatibilityExport.cs create mode 100644 src/NwcIO/Compatibility/NwcDocument.AsyncExports.cs diff --git a/docs/public-api.md b/docs/public-api.md index 61edd8b..761697a 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -45,6 +45,13 @@ use asynchronous reads and writes for file and stream overloads and pass the can to the underlying I/O. Parsing, serialization and compression perform synchronous CPU work between I/O operations. Stream overloads leave the supplied stream open. +The document's `SaveObjAsync`, `SaveGlbAsync`, `SaveIfcAsync`, `SaveViewpointsBcfAsync`, +`SaveViewpointsXmlAsync` and `SaveHtmlViewerAsync` accept file paths or streams and a +`CancellationToken`. OBJ and IFC also accept a `TextWriter`. The compatibility formatters +run on a worker thread and forward writes and flushes to the destination's async methods with +the token. Successful path exports replace the destination atomically. Cancellation may leave +partial output in a caller-owned stream or writer, which remains open. + `NwcAssembly.LoadFromDirectoryAsync` and `NwcAssembly.OpenNwfAsync` read model files asynchronously and pass cancellation through to each read. They load models sequentially in the same order as their synchronous counterparts. Directory discovery and reference resolution use synchronous filesystem metadata. diff --git a/src/NwcIO/Compatibility/Export/BcfExporter.cs b/src/NwcIO/Compatibility/Export/BcfExporter.cs index c5d274f..e3ed4bb 100644 --- a/src/NwcIO/Compatibility/Export/BcfExporter.cs +++ b/src/NwcIO/Compatibility/Export/BcfExporter.cs @@ -58,7 +58,9 @@ public static void WriteViewpointsFile(IReadOnlyList viewpoin /// /// Writes the saved viewpoints list as a BCF 2.1 (.bcfzip) archive into the provided stream. /// - public static void WriteViewpoints(IReadOnlyList viewpoints, Stream stream, string? assemblyName = null) + public static void WriteViewpoints( + IReadOnlyList viewpoints, Stream stream, string? assemblyName = null, + CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(viewpoints); ArgumentNullException.ThrowIfNull(stream); @@ -79,6 +81,7 @@ public static void WriteViewpoints(IReadOnlyList viewpoints, // 2. Per-viewpoint topic folder for (int i = 0; i < viewpoints.Count; i++) { + cancellationToken.ThrowIfCancellationRequested(); var vp = viewpoints[i]; string topicGuid = (vp.Id ?? Guid.NewGuid()).ToString("D"); string viewpointGuid = Guid.NewGuid().ToString("D"); diff --git a/src/NwcIO/Compatibility/Export/CompatibilityExport.cs b/src/NwcIO/Compatibility/Export/CompatibilityExport.cs new file mode 100644 index 0000000..52ef6c0 --- /dev/null +++ b/src/NwcIO/Compatibility/Export/CompatibilityExport.cs @@ -0,0 +1,184 @@ +using System.Buffers; +using System.Text; + +namespace NwcIO.Internal.Export; + +internal static class CompatibilityExport +{ + private const int ByteBufferSize = 64 * 1024; + private const int TextBufferSize = 4096; + + public static Task WriteFileAsync( + string path, Action write, CancellationToken cancellationToken) => + AtomicFileWriter.WriteAsync(path, output => new ValueTask(WriteAsync(output, write, cancellationToken)), + cancellationToken).AsTask(); + + public static Task WriteAsync(Stream output, Action write, CancellationToken cancellationToken) => + Task.Run(() => + { + ArgumentNullException.ThrowIfNull(output); + + // The legacy formatter runs on a worker. Every destination write still uses cancellable async I/O. + using var destination = new AsyncStream(output, cancellationToken); + write(destination); + destination.Flush(); + cancellationToken.ThrowIfCancellationRequested(); + }, cancellationToken); + + public static Task WriteAsync(TextWriter output, Action write, CancellationToken cancellationToken) => + Task.Run(() => + { + ArgumentNullException.ThrowIfNull(output); + using var destination = new AsyncTextWriter(output, cancellationToken); + write(destination); + destination.Flush(); + cancellationToken.ThrowIfCancellationRequested(); + }, cancellationToken); + + public static void WriteText(Stream stream, Encoding encoding, Action write) + { + using var writer = new StreamWriter(stream, encoding, ByteBufferSize, leaveOpen: true); + write(writer); + } + + private sealed class AsyncStream(Stream output, CancellationToken token) : Stream + { + private byte[]? _buffer; + private bool _failed; + + public override void Write(byte[] buffer, int offset, int count) => WriteMemory(buffer.AsMemory(offset, count)); + + public override void Write(ReadOnlySpan buffer) + { + if (buffer.IsEmpty) return; + + _buffer ??= ArrayPool.Shared.Rent(ByteBufferSize); + while (!buffer.IsEmpty) + { + int count = Math.Min(buffer.Length, ByteBufferSize); + buffer[..count].CopyTo(_buffer); + WriteMemory(_buffer.AsMemory(0, count)); + buffer = buffer[count..]; + } + } + + private void WriteMemory(ReadOnlyMemory buffer) + { + // StreamWriter and ZipArchive can attempt more writes while unwinding a failure. + if (_failed) return; + token.ThrowIfCancellationRequested(); + try + { + output.WriteAsync(buffer, token).AsTask().GetAwaiter().GetResult(); + } + catch + { + _failed = true; + throw; + } + } + + public override void Flush() + { + if (_failed) return; + token.ThrowIfCancellationRequested(); + try + { + output.FlushAsync(token).GetAwaiter().GetResult(); + } + catch + { + _failed = true; + throw; + } + } + + public override bool CanRead => false; + public override bool CanSeek => output.CanSeek; + public override bool CanWrite => output.CanWrite; + public override long Length => output.Length; + public override long Position + { + get => output.Position; + set + { + if (_failed) return; + token.ThrowIfCancellationRequested(); + output.Position = value; + } + } + + public override long Seek(long offset, SeekOrigin origin) + { + if (_failed) return output.Position; + token.ThrowIfCancellationRequested(); + return output.Seek(offset, origin); + } + + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + if (disposing && _buffer is not null) + { + ArrayPool.Shared.Return(_buffer); + _buffer = null; + } + + base.Dispose(disposing); + } + } + + private sealed class AsyncTextWriter : TextWriter + { + private readonly TextWriter _output; + private readonly CancellationToken _token; + private readonly char[] _buffer = new char[TextBufferSize]; + private int _length; + + public AsyncTextWriter(TextWriter output, CancellationToken token) : base(output.FormatProvider) + { + _output = output; + _token = token; + NewLine = output.NewLine; + } + + public override Encoding Encoding => _output.Encoding; + + public override void Write(char value) + { + Span single = [value]; + Write(single); + } + + public override void Write(string? value) => Write(value.AsSpan()); + + public override void Write(ReadOnlySpan buffer) + { + _token.ThrowIfCancellationRequested(); + while (!buffer.IsEmpty) + { + int count = Math.Min(buffer.Length, _buffer.Length - _length); + buffer[..count].CopyTo(_buffer.AsSpan(_length)); + _length += count; + buffer = buffer[count..]; + if (_length == _buffer.Length) WriteBuffer(); + } + } + + public override void Flush() + { + WriteBuffer(); + _output.FlushAsync(_token).GetAwaiter().GetResult(); + } + + private void WriteBuffer() + { + _token.ThrowIfCancellationRequested(); + if (_length == 0) return; + _output.WriteAsync(_buffer.AsMemory(0, _length), _token).GetAwaiter().GetResult(); + _length = 0; + } + } +} diff --git a/src/NwcIO/Compatibility/Export/GlbExporter.cs b/src/NwcIO/Compatibility/Export/GlbExporter.cs index 1aaebb8..2031409 100644 --- a/src/NwcIO/Compatibility/Export/GlbExporter.cs +++ b/src/NwcIO/Compatibility/Export/GlbExporter.cs @@ -46,7 +46,8 @@ public static void Write( Stream output, bool worldCoordinates = true, string? generatorName = null, - IReadOnlyList? viewpoints = null) + IReadOnlyList? viewpoints = null, + CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(meshes); ArgumentNullException.ThrowIfNull(materials); @@ -73,6 +74,7 @@ public static void Write( for (int m = 0; m < meshes.Count; m++) { + cancellationToken.ThrowIfCancellationRequested(); var mesh = meshes[m]; var vertices = worldCoordinates ? mesh.GetWorldVertices() : mesh.Vertices; int vCount = vertices.Count; @@ -94,6 +96,7 @@ public static void Write( var indices = new List(); for (int i = 0; i <= faces.Count - 3; i += 3) { + if ((i & 4095) == 0) cancellationToken.ThrowIfCancellationRequested(); int i0 = faces[i]; int i1 = faces[i + 1]; int i2 = faces[i + 2]; @@ -111,6 +114,7 @@ public static void Write( var lineIndices = new List(); for (int i = 0; i <= mesh.LineIndices.Count - 2; i += 2) { + if ((i & 4095) == 0) cancellationToken.ThrowIfCancellationRequested(); int i0 = mesh.LineIndices[i]; int i1 = mesh.LineIndices[i + 1]; if (i0 < 0 || i0 >= vCount || i1 < 0 || i1 >= vCount) @@ -135,6 +139,7 @@ public static void Write( for (int v = 0; v < vCount;) { + cancellationToken.ThrowIfCancellationRequested(); var batch = bin.ReserveRecords(vCount - v, 12, out int count); for (int i = 0; i < count; i++, v++) { @@ -174,6 +179,7 @@ public static void Write( var normals = AccumulateNormals(vertices, indices); for (int v = 0; v < vCount;) { + cancellationToken.ThrowIfCancellationRequested(); var batch = bin.ReserveRecords(vCount - v, 12, out int count); for (int i = 0; i < count; i++, v++) { @@ -214,6 +220,7 @@ public static void Write( long colOffset = bin.BeginView(colLength); for (int v = 0; v < vCount;) { + cancellationToken.ThrowIfCancellationRequested(); var batch = bin.ReserveRecords(vCount - v, 16, out int count); for (int i = 0; i < count; i++, v++) { @@ -326,7 +333,8 @@ public static void Write( GetBinChunkLength(binFile?.Length ?? 0), generatorName ?? "NwcIO glTF 2.0 Exporter", viewpoints, - materialsWithBlend); + materialsWithBlend, + cancellationToken); WriteContainer(output, jsonData.Span, binFile); } @@ -383,8 +391,9 @@ private static ReadOnlyMemory BuildJsonChunk( List bufferViews, long binByteLength, string generator, - IReadOnlyList? viewpoints = null, - HashSet? materialsWithBlend = null) + IReadOnlyList? viewpoints, + HashSet? materialsWithBlend, + CancellationToken cancellationToken) { var json = new ArrayBufferWriter(); using (var writer = new Utf8JsonWriter(json)) @@ -422,6 +431,7 @@ private static ReadOnlyMemory BuildJsonChunk( if (totalNodes > 0) writer.WriteStartArray("nodes"); for (int i = 0; i < meshes.Count; i++) { + cancellationToken.ThrowIfCancellationRequested(); writer.WriteStartObject(); writer.WriteString("name", meshes[i].Name); writer.WriteNumber("mesh", i); @@ -432,6 +442,7 @@ private static ReadOnlyMemory BuildJsonChunk( { for (int i = 0; i < cameras.Count; i++) { + cancellationToken.ThrowIfCancellationRequested(); var vp = cameras[i]; var cam = vp.Camera; writer.WriteStartObject(); @@ -463,6 +474,7 @@ private static ReadOnlyMemory BuildJsonChunk( writer.WriteStartArray("cameras"); for (int i = 0; i < cameras.Count; i++) { + cancellationToken.ThrowIfCancellationRequested(); var vp = cameras[i]; var cam = vp.Camera; writer.WriteStartObject(); @@ -500,6 +512,7 @@ private static ReadOnlyMemory BuildJsonChunk( if (meshes.Count > 0) writer.WriteStartArray("meshes"); for (int i = 0; i < meshes.Count; i++) { + cancellationToken.ThrowIfCancellationRequested(); var m = meshes[i]; writer.WriteStartObject(); writer.WriteString("name", m.Name); @@ -538,6 +551,7 @@ private static ReadOnlyMemory BuildJsonChunk( if (materials.Count > 0) writer.WriteStartArray("materials"); for (int i = 0; i < materials.Count; i++) { + cancellationToken.ThrowIfCancellationRequested(); var mat = materials[i]; writer.WriteStartObject(); writer.WriteString("name", mat.Name); @@ -568,6 +582,7 @@ private static ReadOnlyMemory BuildJsonChunk( if (accessors.Count > 0) writer.WriteStartArray("accessors"); for (int i = 0; i < accessors.Count; i++) { + cancellationToken.ThrowIfCancellationRequested(); var acc = accessors[i]; writer.WriteStartObject(); writer.WriteNumber("bufferView", acc.BufferView); @@ -596,6 +611,7 @@ private static ReadOnlyMemory BuildJsonChunk( if (bufferViews.Count > 0) writer.WriteStartArray("bufferViews"); for (int i = 0; i < bufferViews.Count; i++) { + cancellationToken.ThrowIfCancellationRequested(); var bv = bufferViews[i]; writer.WriteStartObject(); writer.WriteNumber("buffer", 0); diff --git a/src/NwcIO/Compatibility/Export/IfcExporter.cs b/src/NwcIO/Compatibility/Export/IfcExporter.cs index e4247dd..a3a5525 100644 --- a/src/NwcIO/Compatibility/Export/IfcExporter.cs +++ b/src/NwcIO/Compatibility/Export/IfcExporter.cs @@ -38,7 +38,8 @@ public static void Write( NwcDocument doc, TextWriter writer, NwcIfcExportOptions? options = null, - string? fileName = null) + string? fileName = null, + CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(doc); ArgumentNullException.ThrowIfNull(writer); @@ -147,6 +148,7 @@ public static void Write( for (int m = 0; m < doc.Meshes.Count; m++) { + cancellationToken.ThrowIfCancellationRequested(); var mesh = doc.Meshes[m]; if (activePlanes.Count > 0 && options.ClipGeometryWithSectionPlanes) { diff --git a/src/NwcIO/Compatibility/Export/ObjExporter.cs b/src/NwcIO/Compatibility/Export/ObjExporter.cs index 31bdb49..10fd3db 100644 --- a/src/NwcIO/Compatibility/Export/ObjExporter.cs +++ b/src/NwcIO/Compatibility/Export/ObjExporter.cs @@ -35,7 +35,8 @@ public static void Write( TextWriter writer, bool worldCoordinates = true, string? sourceDocument = null, - Func? objectNamePrefix = null) + Func? objectNamePrefix = null, + CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(meshes); ArgumentNullException.ThrowIfNull(writer); @@ -54,6 +55,7 @@ public static void Write( for (int m = 0; m < meshes.Count; m++) { + cancellationToken.ThrowIfCancellationRequested(); var mesh = meshes[m]; var vertices = worldCoordinates ? mesh.GetWorldVertices() : mesh.Vertices; if (vertices.Count == 0 || (mesh.Indices.Count == 0 && mesh.LineIndices.Count == 0)) diff --git a/src/NwcIO/Compatibility/NwcDocument.AsyncExports.cs b/src/NwcIO/Compatibility/NwcDocument.AsyncExports.cs new file mode 100644 index 0000000..5540cd3 --- /dev/null +++ b/src/NwcIO/Compatibility/NwcDocument.AsyncExports.cs @@ -0,0 +1,96 @@ +using System.Text; +using NwcIO.Internal.Export; +using NwcIO.Model; +using NwcIO.Model.Sectioning; +using NwcIO.Model.Viewer; + +namespace NwcIO; + +public sealed partial class NwcDocument +{ + private static readonly Encoding ExportUtf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); + + /// Exports Wavefront OBJ to a file 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); + + /// Exports Wavefront OBJ to a UTF-8 stream asynchronously. + public Task SaveObjAsync(Stream stream, bool worldCoordinates = true, CancellationToken cancellationToken = default) => + CompatibilityExport.WriteAsync(stream, output => CompatibilityExport.WriteText(output, ExportUtf8, + writer => ObjExporter.Write(Meshes, writer, worldCoordinates, FileInfo.SourcePath, cancellationToken: cancellationToken)), + cancellationToken); + + /// Exports Wavefront OBJ to a text writer asynchronously. + public Task SaveObjAsync(TextWriter writer, bool worldCoordinates = true, CancellationToken cancellationToken = default) => + CompatibilityExport.WriteAsync(writer, + output => ObjExporter.Write(Meshes, output, worldCoordinates, FileInfo.SourcePath, cancellationToken: cancellationToken), + cancellationToken); + + /// 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); + + /// 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, + viewpoints: SavedViewpoints, cancellationToken: cancellationToken), cancellationToken); + + /// Exports an IFC STEP file asynchronously. + public Task SaveIfcAsync(string path, NwcIfcExportOptions? options = null, CancellationToken cancellationToken = default) => + CompatibilityExport.WriteFileAsync(path, stream => CompatibilityExport.WriteText(stream, ExportUtf8, + writer => IfcExporter.Write(this, writer, options, Path.GetFileName(path), cancellationToken)), cancellationToken); + + /// Exports IFC STEP to a UTF-8 stream asynchronously. + public Task SaveIfcAsync(Stream stream, NwcIfcExportOptions? options = null, CancellationToken cancellationToken = default) => + CompatibilityExport.WriteAsync(stream, output => CompatibilityExport.WriteText(output, ExportUtf8, + writer => IfcExporter.Write(this, writer, options, cancellationToken: cancellationToken)), cancellationToken); + + /// Exports IFC STEP to a text writer asynchronously. + public Task SaveIfcAsync(TextWriter writer, NwcIfcExportOptions? options = null, CancellationToken cancellationToken = default) => + CompatibilityExport.WriteAsync(writer, + output => IfcExporter.Write(this, output, options, cancellationToken: cancellationToken), cancellationToken); + + /// Exports saved viewpoints to a BCF 2.1 file asynchronously. + public async Task SaveViewpointsBcfAsync(string path, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!); + await CompatibilityExport.WriteFileAsync(path, output => WriteViewpointsBcf(output, cancellationToken), + cancellationToken).ConfigureAwait(false); + } + + /// Exports saved viewpoints to a BCF 2.1 stream asynchronously. + public Task SaveViewpointsBcfAsync(Stream stream, CancellationToken cancellationToken = default) => + CompatibilityExport.WriteAsync(stream, output => WriteViewpointsBcf(output, cancellationToken), cancellationToken); + + private void WriteViewpointsBcf(Stream output, CancellationToken cancellationToken) => + BcfExporter.WriteViewpoints(SavedViewpoints, output, Path.GetFileNameWithoutExtension(FileInfo.SourcePath ?? "Model"), + cancellationToken); + + /// Exports saved viewpoints to a Navisworks XML file asynchronously. + public Task SaveViewpointsXmlAsync(string path, string units = "m", CancellationToken cancellationToken = default) => + CompatibilityExport.WriteFileAsync(path, output => WriteViewpointsXml(output, units, cancellationToken), cancellationToken); + + /// Exports saved viewpoints to a Navisworks XML stream asynchronously. + public Task SaveViewpointsXmlAsync(Stream stream, string units = "m", CancellationToken cancellationToken = default) => + CompatibilityExport.WriteAsync(stream, output => WriteViewpointsXml(output, units, cancellationToken), cancellationToken); + + private void WriteViewpointsXml(Stream output, string units, CancellationToken cancellationToken) => + CompatibilityExport.WriteText(output, Encoding.UTF8, + writer => writer.Write(NwcXmlViewpointSerializer.Serialize(SavedViewpoints, units, cancellationToken))); + + /// Exports a standalone HTML viewer to a file asynchronously. + public Task SaveHtmlViewerAsync(string path, NwcHtmlViewerOptions? options = null, CancellationToken cancellationToken = default) => + CompatibilityExport.WriteFileAsync(path, output => CompatibilityExport.WriteText(output, Encoding.UTF8, + writer => NwcHtmlViewerExporter.WriteDocument(writer, this, options, Path.GetFileNameWithoutExtension(path), cancellationToken)), + cancellationToken); + + /// Exports a standalone HTML viewer to a stream asynchronously. + public Task SaveHtmlViewerAsync(Stream stream, NwcHtmlViewerOptions? options = null, CancellationToken cancellationToken = default) => + CompatibilityExport.WriteAsync(stream, output => CompatibilityExport.WriteText(output, Encoding.UTF8, + writer => NwcHtmlViewerExporter.WriteDocument(writer, this, options, Path.GetFileNameWithoutExtension(FileInfo.SourcePath ?? "Model"), + cancellationToken)), cancellationToken); +} diff --git a/src/NwcIO/Compatibility/Sectioning/NwcXmlViewpointSerializer.cs b/src/NwcIO/Compatibility/Sectioning/NwcXmlViewpointSerializer.cs index fa42628..f743b56 100644 --- a/src/NwcIO/Compatibility/Sectioning/NwcXmlViewpointSerializer.cs +++ b/src/NwcIO/Compatibility/Sectioning/NwcXmlViewpointSerializer.cs @@ -14,7 +14,11 @@ public static class NwcXmlViewpointSerializer private const string SchemaLocation = "http://download.autodesk.com/us/navisworks/schemas/nw-exchange-12.0.xsd"; /// Serializes a list of saved viewpoints to a Navisworks exchange XML string. - public static string Serialize(IEnumerable viewpoints, string units = "m") + public static string Serialize(IEnumerable viewpoints, string units = "m") => + Serialize(viewpoints, units, default); + + internal static string Serialize( + IEnumerable viewpoints, string units, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(viewpoints); @@ -23,7 +27,11 @@ public static string Serialize(IEnumerable viewpoints, string new XElement("exchange", new XAttribute(XNamespace.None + "units", units), new XElement("viewpoints", - viewpoints.Select(SerializeViewpoint)))); + viewpoints.Select(viewpoint => + { + cancellationToken.ThrowIfCancellationRequested(); + return SerializeViewpoint(viewpoint); + })))); return doc.Declaration + Environment.NewLine + doc.ToString(); } diff --git a/src/NwcIO/Compatibility/Viewer/NwcHtmlViewerExporter.cs b/src/NwcIO/Compatibility/Viewer/NwcHtmlViewerExporter.cs index dc34110..11842a2 100644 --- a/src/NwcIO/Compatibility/Viewer/NwcHtmlViewerExporter.cs +++ b/src/NwcIO/Compatibility/Viewer/NwcHtmlViewerExporter.cs @@ -80,16 +80,22 @@ public static NwcHtmlViewerExportResult SaveWithResult(string path, NwcDocument ArgumentNullException.ThrowIfNull(path); ArgumentNullException.ThrowIfNull(doc); - options ??= new NwcHtmlViewerOptions { Title = Path.GetFileNameWithoutExtension(path) }; - // Fill in document defaults on a copy: the caller's options instance must stay - // untouched so it can be reused for other documents without leaking state. + using var fs = File.Create(path); + using var writer = new StreamWriter(fs, Encoding.UTF8); + return WriteDocument(writer, doc, options, Path.GetFileNameWithoutExtension(path), default); + } + + internal static NwcHtmlViewerExportResult WriteDocument( + TextWriter writer, NwcDocument doc, NwcHtmlViewerOptions? options, string title, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + options ??= new NwcHtmlViewerOptions { Title = title }; + // Default on a copy so callers can reuse their options for other documents. options = ShallowCopy(options); options.GridSystem ??= doc.GridSystem; options.TimeLiner ??= doc.TimeLiner; options.SelectionSets ??= doc.SelectionSets; - using var fs = File.Create(path); - using var writer = new StreamWriter(fs, Encoding.UTF8); - return WriteWithResult(writer, doc.Meshes, doc.SavedViewpoints, doc.ClashTests, doc.BoundingBox, options); + return WriteWithResult(writer, doc.Meshes, doc.SavedViewpoints, doc.ClashTests, doc.BoundingBox, options, cancellationToken); } /// @@ -169,12 +175,22 @@ public static NwcHtmlViewerExportResult WriteWithResult( IReadOnlyList clashTests, BoundingBox3d bounds, NwcHtmlViewerOptions options) + => WriteWithResult(writer, meshes, viewpoints, clashTests, bounds, options, default); + + private static NwcHtmlViewerExportResult WriteWithResult( + TextWriter writer, + IReadOnlyList meshes, + IReadOnlyList viewpoints, + IReadOnlyList clashTests, + BoundingBox3d bounds, + NwcHtmlViewerOptions options, + CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(writer); ArgumentNullException.ThrowIfNull(meshes); options ??= new NwcHtmlViewerOptions(); - var (jsonPayload, result) = BuildJsonPayload(meshes, viewpoints, clashTests, bounds, options); + var (jsonPayload, result) = BuildJsonPayload(meshes, viewpoints, clashTests, bounds, options, cancellationToken); writer.WriteLine(""); writer.WriteLine(""); @@ -1578,12 +1594,12 @@ function resetSectionBox() { private static bool IsFinite(Vector3d v) => double.IsFinite(v.X) && double.IsFinite(v.Y) && double.IsFinite(v.Z); // WebGL1 supports unsigned short indices without requiring an extension. - private static IEnumerable<(IReadOnlyList Vertices, IReadOnlyList Indices)> SplitMesh(NwcMesh mesh) + private static IEnumerable<(IReadOnlyList Vertices, IReadOnlyList Indices)> SplitMesh(NwcMesh mesh, CancellationToken cancellationToken) { const int maxVertices = 65535; if (mesh.Vertices.Count <= maxVertices) { - yield return (mesh.Vertices, ValidTriangles(mesh)); + yield return (mesh.Vertices, ValidTriangles(mesh, cancellationToken)); yield break; } @@ -1592,6 +1608,7 @@ function resetSectionBox() { var indices = new List(); for (var i = 0; i + 2 < mesh.Indices.Count; i += 3) { + if ((i & 4095) == 0) cancellationToken.ThrowIfCancellationRequested(); // Reject the whole triangle before adding vertices or splitting a chunk. var a = mesh.Indices[i]; var b = mesh.Indices[i + 1]; @@ -1633,11 +1650,15 @@ function resetSectionBox() { // Indices are written as unsigned integers, so a triangle that references a // missing vertex (or a trailing partial triangle) is dropped, as SplitMesh does. - private static IReadOnlyList ValidTriangles(NwcMesh mesh) + private static IReadOnlyList ValidTriangles(NwcMesh mesh, CancellationToken cancellationToken) { var count = mesh.Vertices.Count; var indices = mesh.Indices; - if (indices.Count % 3 == 0 && indices.All(i => i >= 0 && i < count)) + if (indices.Count % 3 == 0 && indices.All(i => + { + cancellationToken.ThrowIfCancellationRequested(); + return i >= 0 && i < count; + })) { return indices; } @@ -1645,6 +1666,7 @@ private static IReadOnlyList ValidTriangles(NwcMesh mesh) var valid = new List(indices.Count); for (var i = 0; i + 2 < indices.Count; i += 3) { + if ((i & 4095) == 0) cancellationToken.ThrowIfCancellationRequested(); int a = indices[i], b = indices[i + 1], c = indices[i + 2]; if (a >= 0 && a < count && b >= 0 && b < count && c >= 0 && c < count) { @@ -1731,7 +1753,8 @@ private static (string Json, NwcHtmlViewerExportResult Result) BuildJsonPayload( IReadOnlyList viewpoints, IReadOnlyList clashTests, BoundingBox3d bounds, - NwcHtmlViewerOptions options) + NwcHtmlViewerOptions options, + CancellationToken cancellationToken) { using var stream = new MemoryStream(); using var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = false }); @@ -1767,9 +1790,10 @@ private static (string Json, NwcHtmlViewerExportResult Result) BuildJsonPayload( long skippedVertices = 0; foreach (var mesh in meshes) { + cancellationToken.ThrowIfCancellationRequested(); // The budget counts the vertices actually written, which chunk splitting can // raise above the source count. - var chunks = SplitMesh(mesh).ToList(); + var chunks = SplitMesh(mesh, cancellationToken).ToList(); var meshVertexCount = chunks.Sum(c => c.Vertices.Count); totalVertices += meshVertexCount; @@ -1822,6 +1846,7 @@ private static (string Json, NwcHtmlViewerExportResult Result) BuildJsonPayload( writer.WriteStartArray("chunks"); foreach (var chunk in chunks) { + cancellationToken.ThrowIfCancellationRequested(); WriteChunk(writer, chunk, ref meshBounds); } writer.WriteEndArray(); @@ -1870,6 +1895,7 @@ private static (string Json, NwcHtmlViewerExportResult Result) BuildJsonPayload( writer.WriteStartArray("viewpoints"); foreach (var vp in viewpoints) { + cancellationToken.ThrowIfCancellationRequested(); writer.WriteStartObject(); writer.WriteString("name", vp.Name); @@ -1906,6 +1932,7 @@ private static (string Json, NwcHtmlViewerExportResult Result) BuildJsonPayload( writer.WriteStartArray("clashTests"); foreach (var test in clashTests) { + cancellationToken.ThrowIfCancellationRequested(); writer.WriteStartObject(); writer.WriteString("name", test.Name); writer.WriteNumber("tolerance", test.Tolerance); @@ -1931,6 +1958,7 @@ private static (string Json, NwcHtmlViewerExportResult Result) BuildJsonPayload( writer.WriteStartArray("allClashes"); foreach (var clash in test.AllClashes) { + cancellationToken.ThrowIfCancellationRequested(); writer.WriteStartObject(); writer.WriteString("name", clash.Name); writer.WriteString("status", clash.Status.ToString()); @@ -1965,6 +1993,7 @@ private static (string Json, NwcHtmlViewerExportResult Result) BuildJsonPayload( writer.WriteStartArray("grids"); foreach (var line in options.GridSystem.Lines) { + cancellationToken.ThrowIfCancellationRequested(); writer.WriteStartObject(); writer.WriteString("name", line.Name); writer.WriteStartArray("start"); @@ -1988,6 +2017,7 @@ private static (string Json, NwcHtmlViewerExportResult Result) BuildJsonPayload( writer.WriteStartArray("selectionSets"); foreach (var item in options.SelectionSets) { + cancellationToken.ThrowIfCancellationRequested(); WriteSetItem(writer, item); } writer.WriteEndArray(); @@ -2007,6 +2037,7 @@ private static (string Json, NwcHtmlViewerExportResult Result) BuildJsonPayload( writer.WriteStartArray("tasks"); foreach (var task in options.TimeLiner.FlattenTasks()) { + cancellationToken.ThrowIfCancellationRequested(); writer.WriteStartObject(); writer.WriteString("id", task.Id); writer.WriteString("name", task.Name); diff --git a/tests/NwcIO.Tests/AsyncDocumentIoTests.cs b/tests/NwcIO.Tests/AsyncDocumentIoTests.cs index fa3bad6..34de480 100644 --- a/tests/NwcIO.Tests/AsyncDocumentIoTests.cs +++ b/tests/NwcIO.Tests/AsyncDocumentIoTests.cs @@ -1,7 +1,10 @@ +using System.IO.Compression; using System.Text; +using System.Text.RegularExpressions; using NwcIO.Internal; using NwcIO.Internal.Container; using NwcIO.Model; +using NwcIO.Model.Viewer; using Xunit; namespace NwcIO.Tests; @@ -161,11 +164,311 @@ await Assert.ThrowsAnyAsync(() => } } - private static async Task AssertPendingCancellation(Task operation, AsyncOnlyStream stream, CancellationTokenSource cancellation) + [Theory] + [InlineData("obj")] + [InlineData("glb")] + [InlineData("ifc")] + [InlineData("bcf")] + [InlineData("xml")] + [InlineData("html")] + public async Task CompatibilityExports_CancelWhileAwaitingDestinationWrite(string format) + { + using var cancellation = new CancellationTokenSource(); + using var output = new AsyncOnlyStream(seekable: false) { BlockAt = 1 }; + var document = CompatibilityDocument(); + + await AssertPendingCancellation(ExportToStream(document, format, output, cancellation.Token), output, cancellation); + + Assert.True(output.CanWrite); + Assert.Equal(1, output.Calls); + } + + [Theory] + [InlineData("obj")] + [InlineData("glb")] + [InlineData("ifc")] + [InlineData("bcf")] + [InlineData("xml")] + [InlineData("html")] + public async Task CompatibilityExports_PreCancelled_PreserveExistingOutput(string format) + { + var directory = Directory.CreateTempSubdirectory("nwcio-cancel-export-"); + string path = Path.Combine(directory.FullName, "model." + format); + try + { + byte[] original = [1, 2, 3]; + File.WriteAllBytes(path, original); + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + using var output = new AsyncOnlyStream(); + var document = CompatibilityDocument(); + + var file = ExportToPath(document, format, path, cancellation.Token); + var stream = ExportToStream(document, format, output, cancellation.Token); + await Assert.ThrowsAnyAsync(() => file); + await Assert.ThrowsAnyAsync(() => stream); + + Assert.True(file.IsCanceled && stream.IsCanceled); + Assert.Equal(original, File.ReadAllBytes(path)); + Assert.Equal(path, Assert.Single(Directory.GetFiles(directory.FullName))); + Assert.Equal(0, output.Calls); + Assert.True(output.CanWrite); + } + finally + { + directory.Delete(recursive: true); + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task CancelledGeometryExport_PreservesExistingDestination(bool glb) + { + var directory = Directory.CreateTempSubdirectory("nwcio-cancel-geometry-"); + string path = Path.Combine(directory.FullName, glb ? "model.glb" : "model.obj"); + try + { + byte[] original = [1, 2, 3]; + File.WriteAllBytes(path, original); + 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] }]); + + Task save = glb + ? doc.SaveGlbAsync(path, worldCoordinates: false, cancellationToken: cancellation.Token) + : doc.SaveObjAsync(path, worldCoordinates: false, cancellationToken: cancellation.Token); + var error = await Assert.ThrowsAnyAsync(() => save.WaitAsync(Timeout)); + + 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))); + } + finally + { + directory.Delete(recursive: true); + } + } + + [Theory] + [InlineData("obj")] + [InlineData("glb")] + [InlineData("ifc")] + [InlineData("bcf")] + [InlineData("xml")] + [InlineData("html")] + public async Task CompatibilityExports_ProduceEquivalentPathAndStreamOutput(string format) + { + var directory = Directory.CreateTempSubdirectory("nwcio-async-export-"); + string path = Path.Combine(directory.FullName, "model." + format); + try + { + var document = CompatibilityDocument(); + switch (format) + { + case "obj": document.SaveObj(path, worldCoordinates: false); break; + case "glb": document.SaveGlb(path, worldCoordinates: false); break; + case "ifc": document.SaveIfc(path); break; + case "bcf": document.SaveViewpointsBcf(path); break; + case "xml": document.SaveViewpointsXml(path, units: "ft"); break; + case "html": document.SaveHtmlViewer(path, new NwcHtmlViewerOptions { Title = "Async viewer" }); break; + } + + byte[] expected = File.ReadAllBytes(path); + using var output = new AsyncOnlyStream(seekable: false); + await ExportToPath(document, format, path, default); + await ExportToStream(document, format, output, default); + + byte[] actual = File.ReadAllBytes(path); + switch (format) + { + case "bcf": + foreach (byte[] bytes in new[] { expected, actual, output.ToArray() }) + { + using var archive = new ZipArchive(new MemoryStream(bytes), ZipArchiveMode.Read); + BcfSchemaAssert.ValidArchive(archive, 1); + } + break; + case "ifc": + Assert.Contains("FILE_NAME('model.ifc'", Encoding.UTF8.GetString(actual), StringComparison.Ordinal); + Assert.Equal(NormalizeIfc(expected), NormalizeIfc(actual)); + Assert.Equal(NormalizeIfc(expected), NormalizeIfc(output.ToArray())); + break; + default: + Assert.Equal(expected, actual); + Assert.Equal(expected, output.ToArray()); + break; + } + + Assert.True(output.CanWrite && output.Flushed); + Assert.Equal(path, Assert.Single(Directory.GetFiles(directory.FullName))); + } + finally + { + directory.Delete(recursive: true); + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task TextCompatibilityExports_UseAsyncWriterAndLeaveItOpen(bool ifc) + { + var doc = CompatibilityDocument(); + using var writer = new AsyncOnlyTextWriter { NewLine = "\n" }; + using var expected = new StringWriter { NewLine = "\n" }; + if (ifc) + { + doc.SaveIfc(expected); + await doc.SaveIfcAsync(writer); + Assert.Equal(NormalizeIfc(Encoding.UTF8.GetBytes(expected.ToString())), + NormalizeIfc(Encoding.UTF8.GetBytes(writer.ToString()))); + } + else + { + doc.SaveObj(expected); + await doc.SaveObjAsync(writer); + Assert.Equal(expected.ToString(), writer.ToString()); + } + + Assert.True(writer.Flushed); + Assert.False(writer.Disposed); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task TextCompatibilityExports_CancelWhileAwaitingWrite(bool ifc) + { + var doc = CompatibilityDocument(); + using var cancellation = new CancellationTokenSource(); + using var writer = new AsyncOnlyTextWriter { BlockWrites = true }; + + var save = ifc + ? doc.SaveIfcAsync(writer, cancellationToken: cancellation.Token) + : doc.SaveObjAsync(writer, cancellationToken: cancellation.Token); + await AssertPendingCancellation(save, writer.Blocked.Task, cancellation); + + Assert.False(writer.Disposed); + Assert.False(writer.Flushed); + } + + private static string NormalizeIfc(byte[] bytes) + { + // STEP headers include the target filename and a clock timestamp, and owner history includes an epoch timestamp. + var text = Encoding.UTF8.GetString(bytes); + text = Regex.Replace(text, "^FILE_NAME.*$", "FILE_NAME", RegexOptions.Multiline); + return Regex.Replace(text, @"^([^\r\n]*=IFCOWNERHISTORY\(.*),[0-9]+\);", "$1,0);", RegexOptions.Multiline); + } + + private static NwcDocument CompatibilityDocument() => NwcDocument.Create( + fileInfo: new NwcFileInfo { SourcePath = "model.nwc" }, + 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(1, 2, 3) }, + }, + ], + savedViewpoints: [NwcSavedViewpoint.CreateDefault(new BoundingBox3d(new(0, 0, 0), new(3, 3, 3)), "Coordination")]); + + private static Task ExportToStream(NwcDocument document, string format, Stream stream, CancellationToken token) => format switch + { + "obj" => document.SaveObjAsync(stream, worldCoordinates: false, cancellationToken: token), + "glb" => document.SaveGlbAsync(stream, worldCoordinates: false, cancellationToken: token), + "ifc" => document.SaveIfcAsync(stream, cancellationToken: token), + "bcf" => document.SaveViewpointsBcfAsync(stream, token), + "xml" => document.SaveViewpointsXmlAsync(stream, units: "ft", cancellationToken: token), + "html" => document.SaveHtmlViewerAsync(stream, new NwcHtmlViewerOptions { Title = "Async viewer" }, token), + _ => throw new ArgumentOutOfRangeException(nameof(format)), + }; + + private static Task ExportToPath(NwcDocument document, string format, string path, CancellationToken token) => format switch + { + "obj" => document.SaveObjAsync(path, worldCoordinates: false, cancellationToken: token), + "glb" => document.SaveGlbAsync(path, worldCoordinates: false, cancellationToken: token), + "ifc" => document.SaveIfcAsync(path, cancellationToken: token), + "bcf" => document.SaveViewpointsBcfAsync(path, token), + "xml" => document.SaveViewpointsXmlAsync(path, units: "ft", cancellationToken: token), + "html" => document.SaveHtmlViewerAsync(path, new NwcHtmlViewerOptions { Title = "Async viewer" }, token), + _ => throw new ArgumentOutOfRangeException(nameof(format)), + }; + + private sealed class CancellingVertices(CancellationTokenSource cancellation) : IReadOnlyList + { + public int Count => 8192; + + public Vector3d this[int index] + { + get + { + if (index == Count - 2) cancellation.Cancel(); + return new Vector3d(index, index % 3, 0); + } + } + + public IEnumerator GetEnumerator() + { + for (int i = 0; i < Count; i++) + { + yield return this[i]; + } + } + + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + } + + private sealed class AsyncOnlyTextWriter : TextWriter + { + private readonly StringBuilder _text = new(); + public override Encoding Encoding => Encoding.UTF8; + public bool Flushed { get; private set; } + public bool Disposed { get; private set; } + public bool BlockWrites { get; init; } + public TaskCompletionSource Blocked { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public override void Write(char value) => throw new NotSupportedException("Synchronous write"); + public override void Flush() => throw new NotSupportedException("Synchronous flush"); + + public override async Task WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + if (BlockWrites) + { + Blocked.SetResult(cancellationToken); + await Task.Delay(System.Threading.Timeout.InfiniteTimeSpan, cancellationToken); + } + + _text.Append(buffer.Span); + } + + public override Task FlushAsync(CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + Flushed = true; + return Task.CompletedTask; + } + + public override string ToString() => _text.ToString(); + + protected override void Dispose(bool disposing) + { + if (disposing) Disposed = true; + base.Dispose(disposing); + } + } + + private static Task AssertPendingCancellation(Task operation, AsyncOnlyStream stream, CancellationTokenSource cancellation) => + AssertPendingCancellation(operation, stream.Blocked.Task, cancellation); + + private static async Task AssertPendingCancellation(Task operation, Task blocked, CancellationTokenSource cancellation) { try { - var blocked = stream.Blocked.Task; Assert.Same(blocked, await Task.WhenAny(blocked, operation).WaitAsync(Timeout)); Assert.False(operation.IsCompleted); Assert.Equal(cancellation.Token, await blocked);