From b13d5d13227d514e36c814b2cdf5c96b8240bb2d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 01:46:11 +0000 Subject: [PATCH 01/20] Bump Microsoft.NET.Test.Sdk from 18.11.1 to 18.12.0 --- updated-dependencies: - dependency-name: Microsoft.NET.Test.Sdk dependency-version: 18.12.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- Directory.Packages.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index e6746b9..1b330be 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -11,7 +11,7 @@ - + From c3899c63e180b10a5f232578d9ef96fd62c7c37e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 01:46:39 +0000 Subject: [PATCH 02/20] Bump Microsoft.SourceLink.GitHub from 10.0.403 to 10.0.404 --- updated-dependencies: - dependency-name: Microsoft.SourceLink.GitHub dependency-version: 10.0.404 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- Directory.Packages.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index e6746b9..f0c1938 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -6,7 +6,7 @@ - + From 8b7ed944cd208df2a8fcf58ff5056a6960673f34 Mon Sep 17 00:00:00 2001 From: mahach666 Date: Fri, 20 Nov 2026 02:14:15 +0300 Subject: [PATCH 03/20] Export drawings to OBJ and GLB through the scene DwgSceneExport writes the IOScene scene of a drawing to Wavefront OBJ with an adjacent MTL colour library (both files written as a pair and moved in atomically) and to binary glTF, through the IOScene.Formats writers. The plain export command dispatches on the output extension, so dwgio drawing.dwg out.obj and out.glb work like out.json. IOScene.Formats ships as a preview and needs IOScene 0.1.1 or later, so the IOScene floor moves from 0.1.0 to 0.1.1. --- CHANGELOG.md | 3 + Directory.Packages.props | 6 +- README.md | 11 ++ docs/public-api.md | 4 +- src/DwgIO.Cli/Program.cs | 22 ++- src/DwgIO.Scene/DwgIO.Scene.csproj | 1 + src/DwgIO.Scene/DwgSceneExport.cs | 114 ++++++++++++++++ tests/DwgIO.Tests/DwgSceneExportTests.cs | 164 +++++++++++++++++++++++ 8 files changed, 319 insertions(+), 6 deletions(-) create mode 100644 src/DwgIO.Scene/DwgSceneExport.cs create mode 100644 tests/DwgIO.Tests/DwgSceneExportTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index bdcb187..e3694cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,9 @@ API between minor releases. placements and a conversion report (`DwgSceneResult`). The scene passes the IOScene structural validation and round-trips through the IOScene JSON format. - `dwgio scene [--unit mm|cm|m|ft|in]` writes the scene document. +- `DwgSceneExport.SaveObj`/`SaveGlb` write a drawing to Wavefront OBJ (with an adjacent MTL colour library, + written as a pair) and binary glTF (GLB) through the IOScene writers; `dwgio drawing.dwg out.obj` and + `dwgio drawing.dwg out.glb` dispatch by extension. ### Fixed - Packed 16-bit and 32-bit integers in their full-width form are read little-endian. They were read with their bytes diff --git a/Directory.Packages.props b/Directory.Packages.props index daf5c72..847b947 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -10,8 +10,10 @@ - - + + + diff --git a/README.md b/README.md index b877fb3..19cc1ff 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ DwgIO is a .NET library and command line tool that reads Autodesk AutoCAD drawin - Lists the objects of a drawing through its handle map and decodes the geometry of LINE, CIRCLE, ARC and POINT entities. - Writes a JSON export of the metadata, the section catalog and the decoded entities. - Converts a drawing into a neutral [IOScene](https://www.nuget.org/packages/IOScene) scene document (`DwgIO.Scene` package): geometry in metres, ACI entity colours, one element per entity with its handle. +- Exports the scene to Wavefront OBJ (with an MTL colour library) and binary glTF (GLB). ## Install @@ -63,6 +64,13 @@ Export a neutral IOScene scene document (geometry in metres, ACI colours, one el dwgio scene drawing.dwg drawing.scene.json --unit mm ``` +The plain export command writes OBJ and GLB by output extension, through the same scene: + +```sh +dwgio drawing.dwg drawing.obj # Wavefront OBJ + drawing.mtl with the ACI colours +dwgio drawing.dwg drawing.glb # binary glTF for viewers and web scenes +``` + Errors go to standard error. ### Exit codes @@ -115,6 +123,8 @@ IOScene.SceneJson.Save(scene.Document, "drawing.scene.json"); Every coordinate is scaled to metres by `LengthUnit` (a DWG stores plain numbers, so the unit is a caller decision and `UnitAssumed` records it), each entity becomes an element with its handle as `SourceId`, and LINE, CIRCLE, ARC and POINT become line and point geometries with their ACI colour. +`DwgSceneExport` writes that scene out in the exchange formats: `SaveObj(document, "drawing.obj", options)` produces an OBJ with an adjacent MTL colour library (written as a pair, atomically), `SaveGlb(document, "drawing.glb", options)` produces binary glTF. Both return the same `DwgSceneResult` report. + The documentation site with the API reference is at . [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/IOExtend/DwgIO) offers an automatically generated overview of the repository. ## Status @@ -131,6 +141,7 @@ The documentation site with the API reference is at Print version + section table - dwgio Export metadata, section catalog and decoded entities to JSON + dwgio Export metadata, section catalog and entities to JSON, + or the scene to OBJ (.obj) or GLB (.glb) dwgio extract
Write a named section's decompressed bytes dwgio preview Write the embedded thumbnail image dwgio scene [--unit u] Export a neutral IOScene scene document @@ -173,8 +174,23 @@ private static int Export(string[] args) } var doc = DwgDocument.Open(args[0]); - DwgJsonExporter.WriteFile(doc, args[1], DwgJsonExportOptions.Default); - Console.WriteLine($"{doc.Version} sections={doc.Sections.Count} -> {args[1]}"); + string output = args[1]; + if (Path.GetExtension(output).Equals(".obj", StringComparison.OrdinalIgnoreCase)) + { + var objResult = DwgSceneExport.SaveObj(doc, output); + Console.WriteLine($"{doc.Version} elements={objResult.ElementCount} ({objResult.ElementsWithGeometry} with geometry) -> {output}"); + } + else if (Path.GetExtension(output).Equals(".glb", StringComparison.OrdinalIgnoreCase)) + { + var glbResult = DwgSceneExport.SaveGlb(doc, output); + Console.WriteLine($"{doc.Version} elements={glbResult.ElementCount} ({glbResult.ElementsWithGeometry} with geometry) -> {output}"); + } + else + { + DwgJsonExporter.WriteFile(doc, output, DwgJsonExportOptions.Default); + Console.WriteLine($"{doc.Version} sections={doc.Sections.Count} -> {output}"); + } + return ExitOk; } diff --git a/src/DwgIO.Scene/DwgIO.Scene.csproj b/src/DwgIO.Scene/DwgIO.Scene.csproj index 0520f69..33967db 100644 --- a/src/DwgIO.Scene/DwgIO.Scene.csproj +++ b/src/DwgIO.Scene/DwgIO.Scene.csproj @@ -11,6 +11,7 @@ + diff --git a/src/DwgIO.Scene/DwgSceneExport.cs b/src/DwgIO.Scene/DwgSceneExport.cs new file mode 100644 index 0000000..56da831 --- /dev/null +++ b/src/DwgIO.Scene/DwgSceneExport.cs @@ -0,0 +1,114 @@ +using IOScene; +using IOScene.Formats; + +namespace DwgIO.Scene; + +/// +/// Exports a drawing to the mesh and viewer formats the IOScene toolchain writes: Wavefront OBJ with an +/// adjacent MTL library and binary glTF (GLB). Both go through the IOScene scene document, so colors, line +/// and point topologies and instancing behave exactly as in the scene JSON export. +/// +public static class DwgSceneExport +{ + /// Converts the drawing and writes it to a Wavefront OBJ file with an adjacent MTL library + /// (<objPath> with .mtl instead of its extension). + /// The drawing, for example from . + /// Path to the OBJ file; the MTL library is written beside it. + /// Conversion options; null uses the defaults. + /// The conversion report. is the intermediate scene. + public static DwgSceneResult SaveObj(DwgDocument document, string objPath, DwgSceneOptions? options = null) + { + var result = DwgSceneReader.Read(document, OptionsFor(document, objPath, options)); + WriteObj(result.Document, objPath); + return result; + } + + /// Writes a scene to a Wavefront OBJ file with an adjacent MTL library + /// (<objPath> with .mtl instead of its extension). + /// The scene to export. + /// Path to the OBJ file. + public static void WriteObj(SceneDocument scene, string objPath) + { + ArgumentNullException.ThrowIfNull(scene); + ArgumentException.ThrowIfNullOrEmpty(objPath); + string fullPath = Path.GetFullPath(objPath); + string directory = Path.GetDirectoryName(fullPath) ?? Directory.GetCurrentDirectory(); + string mtlName = Path.ChangeExtension(Path.GetFileName(fullPath), ".mtl"); + string mtlPath = Path.Combine(directory, mtlName); + string objTemp = Path.Combine(directory, $".dwgio-{Guid.NewGuid():N}.obj"); + string mtlTemp = Path.Combine(directory, $".dwgio-{Guid.NewGuid():N}.mtl"); + try + { + // OBJ and MTL are written as a pair: both temporary files are written first, then moved in, so a + // failure leaves the previous pair in place. + using (var objStream = new FileStream(objTemp, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + using (var objWriter = new StreamWriter(objStream, new System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: false))) + using (var mtlStream = new FileStream(mtlTemp, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + using (var mtlWriter = new StreamWriter(mtlStream, new System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: false))) + { + ObjSceneWriter.Write(scene, objWriter, mtlWriter, mtlName); + } + + File.Move(mtlTemp, mtlPath, overwrite: true); + File.Move(objTemp, fullPath, overwrite: true); + } + catch + { + TryDelete(objTemp); + TryDelete(mtlTemp); + throw; + } + } + + /// Converts the drawing and writes it to a binary glTF (GLB) file. + /// The drawing, for example from . + /// Path to the GLB file. + /// Conversion options; null uses the defaults. + /// The conversion report. is the intermediate scene. + public static DwgSceneResult SaveGlb(DwgDocument document, string glbPath, DwgSceneOptions? options = null) + { + var result = DwgSceneReader.Read(document, OptionsFor(document, glbPath, options)); + GlbSceneWriter.Save(result.Document, glbPath); + return result; + } + + /// Writes a scene to a binary glTF (GLB) file. + /// The scene to export. + /// Path to the GLB file. + public static void WriteGlb(SceneDocument scene, string glbPath) + { + ArgumentNullException.ThrowIfNull(scene); + GlbSceneWriter.Save(scene, glbPath); + } + + private static DwgSceneOptions OptionsFor(DwgDocument document, string path, DwgSceneOptions? options) + { + if (options?.ModelKey is { Length: > 0 }) + { + return options; + } + + // The file name doubles as the model key; a document from memory falls back to the export file name. + return new DwgSceneOptions + { + LengthUnit = options?.LengthUnit ?? "m", + ModelKey = Path.GetFileName(path), + }; + } + + private static void TryDelete(string path) + { + try + { + File.Delete(path); + } + catch (IOException) + { + // Best-effort cleanup: the original export failure is the error worth reporting. + } + catch (UnauthorizedAccessException) + { + // Best-effort cleanup: the original export failure is the error worth reporting. + } + } +} diff --git a/tests/DwgIO.Tests/DwgSceneExportTests.cs b/tests/DwgIO.Tests/DwgSceneExportTests.cs new file mode 100644 index 0000000..b0e044a --- /dev/null +++ b/tests/DwgIO.Tests/DwgSceneExportTests.cs @@ -0,0 +1,164 @@ +using DwgIO.Model; +using DwgIO.Scene; +using IOScene.Formats; +using Xunit; +using Vector3d = IOScene.Vector3d; + +namespace DwgIO.Tests; + +public class DwgSceneExportTests : IDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), "dwgio-tests-" + Guid.NewGuid().ToString("N")); + + public DwgSceneExportTests() + { + Directory.CreateDirectory(_directory); + } + + public void Dispose() + { + GC.SuppressFinalize(this); + try + { + Directory.Delete(_directory, recursive: true); + } + catch (DirectoryNotFoundException) + { + } + } + + private static DwgDocument CreateDocument(params DwgEntity[] entities) => + new( + "synthetic.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1024", + Release = "R2010", + Family = DwgContainerFamily.R2004Family, + Year = 2010, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + entities); + + private static DwgDocument SampleDrawing() => CreateDocument( + new DwgEntity + { + Handle = 0x2A, + TypeCode = 0x13, + TypeName = "LINE", + Kind = DwgEntityKind.Line, + Geometry = [1.0, 2.0, 0.0, 11.0, 2.0, 0.0], + ColorIndex = 1, + }, + new DwgEntity + { + Handle = 0x2B, + TypeCode = 0x12, + TypeName = "CIRCLE", + Kind = DwgEntityKind.Circle, + Geometry = [6.0, 2.0, 0.0, 5.0], + ColorIndex = 40, + }, + new DwgEntity + { + Handle = 0x2C, + TypeCode = 0x1B, + TypeName = "POINT", + Kind = DwgEntityKind.Point, + Geometry = [20.0, 2.0, 0.0], + }); + + [Fact] + public void SaveObj_WritesObjWithMtlLibrary() + { + string objPath = Path.Combine(_directory, "drawing.obj"); + + var result = DwgSceneExport.SaveObj(SampleDrawing(), objPath); + + Assert.Equal(3, result.ElementCount); + Assert.True(File.Exists(objPath)); + Assert.True(File.Exists(Path.Combine(_directory, "drawing.mtl"))); + string obj = File.ReadAllText(objPath); + Assert.Contains("mtllib drawing.mtl", obj, StringComparison.Ordinal); + Assert.Contains("usemtl material_1", obj, StringComparison.Ordinal); + Assert.Contains("v 1 2 0", obj, StringComparison.Ordinal); + Assert.Contains("l ", obj, StringComparison.Ordinal); + Assert.Contains("p ", obj, StringComparison.Ordinal); + string mtl = File.ReadAllText(Path.Combine(_directory, "drawing.mtl")); + Assert.Contains("newmtl material_1", mtl, StringComparison.Ordinal); + } + + [Fact] + public void SaveObj_WritesLineAndPointRecords() + { + string objPath = Path.Combine(_directory, "drawing.obj"); + + DwgSceneExport.SaveObj(SampleDrawing(), objPath); + + // The OBJ preview reader of IOScene.Formats reads faces only, so the line and point records are asserted + // on the text: one segment for the LINE, 64 for the tessellated CIRCLE, one point for the POINT. + string[] objLines = File.ReadAllLines(objPath); + Assert.Equal(65, objLines.Count(l => l.StartsWith("l ", StringComparison.Ordinal))); + Assert.Equal(1, objLines.Count(l => l.StartsWith("p ", StringComparison.Ordinal))); + Assert.Contains(objLines, l => l == "v 1 2 0"); + Assert.Contains(objLines, l => l == "v 20 2 0"); + } + + [Fact] + public void SaveObj_ReplacesExistingFiles() + { + string objPath = Path.Combine(_directory, "drawing.obj"); + File.WriteAllText(objPath, "stale"); + string mtlPath = Path.Combine(_directory, "drawing.mtl"); + File.WriteAllText(mtlPath, "stale"); + + DwgSceneExport.SaveObj(SampleDrawing(), objPath); + + Assert.DoesNotContain("stale", File.ReadAllText(objPath), StringComparison.Ordinal); + Assert.DoesNotContain("stale", File.ReadAllText(mtlPath), StringComparison.Ordinal); + Assert.Empty(Directory.EnumerateFiles(_directory, ".dwgio-*")); + } + + [Fact] + public void SaveGlb_RoundTripsThroughGlbSceneReader() + { + string glbPath = Path.Combine(_directory, "drawing.glb"); + + var result = DwgSceneExport.SaveGlb(SampleDrawing(), glbPath); + + Assert.Equal(3, result.ElementCount); + var loaded = GlbSceneReader.Load(glbPath); + Assert.Equal(3, loaded.Elements.Count); + Assert.Equal(3, loaded.Instances.Count); + // The GLB reader turns instance colours into materials: red for the LINE (ACI 1), gold for the CIRCLE (ACI 40). + Assert.Contains(loaded.Materials, m => m.Color.R == 255 && m.Color.G == 0 && m.Color.B == 0); + Assert.Contains(loaded.Materials, m => m.Color.R == 255 && m.Color.G == 191 && m.Color.B == 0); + var lineInstance = Assert.Single(loaded.Instances, i => loaded.Geometries.Single(g => g.Id == i.GeometryId).Topology == IOScene.SceneTopology.Lines && loaded.Geometries.Single(g => g.Id == i.GeometryId).Vertices.Count == 2); + Assert.NotNull(lineInstance); + } + + [Fact] + public void SaveGlb_ScalesByLengthUnit() + { + string glbPath = Path.Combine(_directory, "drawing.glb"); + var document = CreateDocument(new DwgEntity + { + Handle = 0x2A, + TypeCode = 0x13, + TypeName = "LINE", + Kind = DwgEntityKind.Line, + Geometry = [1000.0, 0.0, 0.0, 2000.0, 0.0, 0.0], + }); + + DwgSceneExport.SaveGlb(document, glbPath, new DwgSceneOptions { LengthUnit = "mm" }); + + var loaded = GlbSceneReader.Load(glbPath); + var geometry = Assert.Single(loaded.Geometries); + Assert.Equal(new Vector3d(1.0, 0.0, 0.0), geometry.Vertices[0]); + } +} From d3d1adab300d7eb407bfc7bb5dd75a0bdf20b844 Mon Sep 17 00:00:00 2001 From: mahach666 Date: Fri, 20 Nov 2026 02:22:10 +0300 Subject: [PATCH 04/20] Draw model space to SVG DwgSvgExporter writes the decoded entities (LINE, CIRCLE, ARC and POINT) of a drawing as SVG, the first step of #32: the top view with the drawing's X to the right and Y up, entities in their ACI colours (BYBLOCK, BYLAYER and 7 render black on the light background), arcs as SVG arc paths with correct sweep under the y flip, and a viewBox that covers every drawn entity including the cardinal extremes of an arc. Skipped non-finite entities are reported in Diagnostics; the file is written through a temporary file and moved in atomically. dwgio svg [--scale n] drives it; --scale sets pixels per drawing unit, and the stroke width and point markers stay fixed in pixels while the drawing zooms. --- CHANGELOG.md | 3 + README.md | 8 + docs/public-api.md | 1 + src/DwgIO.Cli/Program.cs | 36 +++ src/DwgIO.Scene/DwgSvgExporter.cs | 328 +++++++++++++++++++++++ src/DwgIO.Scene/DwgSvgOptions.cs | 19 ++ src/DwgIO/DwgIO.csproj | 1 + tests/DwgIO.Tests/DwgSvgExporterTests.cs | 189 +++++++++++++ 8 files changed, 585 insertions(+) create mode 100644 src/DwgIO.Scene/DwgSvgExporter.cs create mode 100644 src/DwgIO.Scene/DwgSvgOptions.cs create mode 100644 tests/DwgIO.Tests/DwgSvgExporterTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index e3694cd..0b2bacc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,9 @@ API between minor releases. - `DwgSceneExport.SaveObj`/`SaveGlb` write a drawing to Wavefront OBJ (with an adjacent MTL colour library, written as a pair) and binary glTF (GLB) through the IOScene writers; `dwgio drawing.dwg out.obj` and `dwgio drawing.dwg out.glb` dispatch by extension. +- `DwgSvgExporter` and `dwgio svg [--scale n]` draw model space to SVG (#32): LINE, + CIRCLE, ARC and POINT in the top view with the y axis up, in their ACI colours, inside a view box that + contains every exported entity. Polylines, curves and text follow as the core decodes them. ### Fixed - Packed 16-bit and 32-bit integers in their full-width form are read little-endian. They were read with their bytes diff --git a/README.md b/README.md index 19cc1ff..4e9493c 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ DwgIO is a .NET library and command line tool that reads Autodesk AutoCAD drawin - Writes a JSON export of the metadata, the section catalog and the decoded entities. - Converts a drawing into a neutral [IOScene](https://www.nuget.org/packages/IOScene) scene document (`DwgIO.Scene` package): geometry in metres, ACI entity colours, one element per entity with its handle. - Exports the scene to Wavefront OBJ (with an MTL colour library) and binary glTF (GLB). +- Draws model space to SVG (`dwgio svg`): LINE, CIRCLE, ARC and POINT in the top view, in their ACI colours. ## Install @@ -71,6 +72,12 @@ dwgio drawing.dwg drawing.obj # Wavefront OBJ + drawing.mtl with the ACI colou dwgio drawing.dwg drawing.glb # binary glTF for viewers and web scenes ``` +Draw model space to SVG (X to the right, Y up, ACI colours; `--scale` sets pixels per drawing unit): + +```sh +dwgio svg drawing.dwg drawing.svg --scale 2 +``` + Errors go to standard error. ### Exit codes @@ -142,6 +149,7 @@ The documentation site with the API reference is at Extract(args), "preview" => Preview(args), "scene" => Scene(args), + "svg" => Svg(args), _ => Export(args), }; } @@ -68,6 +69,7 @@ dwgio extract
Write a named section's decompressed by dwgio preview Write the embedded thumbnail image dwgio scene [--unit u] Export a neutral IOScene scene document (u: mm, cm, m (default), ft or in) + dwgio svg [--scale s] Draw model space to SVG (s: px per unit, default 1) Sections are named as stored, e.g. AcDb:Header, AcDb:Classes, AcDb:SummaryInfo. """); @@ -209,6 +211,40 @@ private static int Extract(string[] args) return ExitOk; } + private static int Svg(string[] args) + { + double scale = 1.0; + var positional = new List(2); + for (int i = 1; i < args.Length; i++) + { + if (args[i] == "--scale") + { + if (i + 1 >= args.Length || !double.TryParse(args[i + 1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out scale) || scale <= 0) + { + Console.Error.WriteLine("error: --scale needs a positive number of pixels per drawing unit."); + return ExitUsage; + } + + i++; + } + else + { + positional.Add(args[i]); + } + } + + if (positional.Count != 2) + { + PrintUsage(); + return ExitUsage; + } + + var doc = DwgDocument.Open(positional[0]); + DwgSvgExporter.WriteFile(doc, positional[1], new DwgSvgOptions { Scale = scale }); + Console.WriteLine($"{doc.Version} entities={doc.Entities.Count} -> {positional[1]}"); + return ExitOk; + } + private static int Scene(string[] args) { string? unit = null; diff --git a/src/DwgIO.Scene/DwgSvgExporter.cs b/src/DwgIO.Scene/DwgSvgExporter.cs new file mode 100644 index 0000000..94499b7 --- /dev/null +++ b/src/DwgIO.Scene/DwgSvgExporter.cs @@ -0,0 +1,328 @@ +using System.Globalization; +using System.Xml; +using DwgIO.Model; + +namespace DwgIO.Scene; + +/// +/// Draws the model space of a drawing as SVG: LINE, CIRCLE, ARC and POINT entities in the top view, with the +/// drawing's X to the right and Y up, in the entities' ACI colours. The viewBox is the bounding box of +/// everything drawn plus a margin, in drawing units with y flipped, so the output contains every exported entity. +/// +/// +/// This is the first step of issue #32: polylines, curves and text join as the core decodes them. SVG is a 2D +/// format; the drawing's Z is dropped, so entities off the XY plane are drawn flattened onto it. +/// +public static class DwgSvgExporter +{ + /// Writes the model space of to a new SVG file at . + public static void WriteFile(DwgDocument document, string path, DwgSvgOptions? options = null) + { + var fullPath = Path.GetFullPath(path); + var directory = Path.GetDirectoryName(fullPath) ?? Directory.GetCurrentDirectory(); + var tempPath = Path.Combine(directory, $".dwgio-{Guid.NewGuid():N}.svg"); + try + { + using (var stream = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + Write(document, stream, options); + } + + File.Move(tempPath, fullPath, overwrite: true); + } + catch + { + try + { + File.Delete(tempPath); + } + catch (IOException) + { + // Best-effort cleanup: the original export failure is the error worth reporting. + } + catch (UnauthorizedAccessException) + { + // Best-effort cleanup: the original export failure is the error worth reporting. + } + + throw; + } + } + + /// Writes the model space of to a stream. The stream stays open. + public static void Write(DwgDocument document, Stream output, DwgSvgOptions? options = null) + { + ArgumentNullException.ThrowIfNull(output); + using var writer = XmlWriter.Create(output, new XmlWriterSettings + { + Indent = true, + Encoding = new System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: false), + }); + Write(document, writer, options); + } + + /// Writes the model space of to an XML writer. + public static void Write(DwgDocument document, XmlWriter writer, DwgSvgOptions? options = null) + { + ArgumentNullException.ThrowIfNull(document); + ArgumentNullException.ThrowIfNull(writer); + options ??= new DwgSvgOptions(); + if (options.Scale <= 0) + { + throw new ArgumentException("DwgSvgOptions.Scale must be positive.", nameof(options)); + } + + var shapes = Collect(document, options.Scale); + (double minX, double minY, double width, double height) = ViewBox(shapes); + // Margins and markers are pixel values: they stay fixed while the scale zooms the drawing. + double margin = Math.Max(0.02 * Math.Max(width, height), 8.0); + double markerRadius = Math.Max(0.015 * Math.Max(width, height), 3.0); + + writer.WriteStartDocument(); + writer.WriteStartElement("svg", "http://www.w3.org/2000/svg"); + writer.WriteAttributeString("viewBox", $"{Num(minX - margin)} {Num(minY - margin)} {Num(width + 2 * margin)} {Num(height + 2 * margin)}"); + writer.WriteAttributeString("width", Num(width + 2 * margin)); + writer.WriteAttributeString("height", Num(height + 2 * margin)); + + writer.WriteStartElement("rect"); + writer.WriteAttributeString("x", Num(minX - margin)); + writer.WriteAttributeString("y", Num(minY - margin)); + writer.WriteAttributeString("width", Num(width + 2 * margin)); + writer.WriteAttributeString("height", Num(height + 2 * margin)); + writer.WriteAttributeString("fill", options.Background); + writer.WriteEndElement(); + + writer.WriteStartElement("g"); + writer.WriteAttributeString("fill", "none"); + writer.WriteAttributeString("stroke", "#000000"); + writer.WriteAttributeString("stroke-width", Num(options.StrokeWidth)); + writer.WriteAttributeString("stroke-linecap", "round"); + + foreach (var shape in shapes) + { + string stroke = ColourOf(shape.ColorIndex); + switch (shape) + { + case SvgLine line: + writer.WriteStartElement("line"); + writer.WriteAttributeString("x1", Num(line.X1)); + writer.WriteAttributeString("y1", Num(line.Y1)); + writer.WriteAttributeString("x2", Num(line.X2)); + writer.WriteAttributeString("y2", Num(line.Y2)); + writer.WriteAttributeString("stroke", stroke); + writer.WriteEndElement(); + break; + case SvgCircle circle: + writer.WriteStartElement("circle"); + writer.WriteAttributeString("cx", Num(circle.Cx)); + writer.WriteAttributeString("cy", Num(circle.Cy)); + writer.WriteAttributeString("r", Num(circle.Radius)); + writer.WriteAttributeString("stroke", stroke); + writer.WriteEndElement(); + break; + case SvgArc arc: + (double x1, double y1, double x2, double y2) = ArcEndpoints(arc); + // The drawing's CCW arc becomes a CW trace in SVG's y-down space, hence sweep 0; the y flip + // is baked into the endpoints already. + writer.WriteStartElement("path"); + writer.WriteAttributeString( + "d", + FormattableString.Invariant( + $"M {Num(x1)} {Num(y1)} A {Num(arc.Radius)} {Num(arc.Radius)} 0 {(arc.Span > Math.PI ? 1 : 0):D} 0 {Num(x2)} {Num(y2)}")); + writer.WriteAttributeString("stroke", stroke); + writer.WriteEndElement(); + break; + case SvgPoint: + writer.WriteStartElement("circle"); + writer.WriteAttributeString("cx", Num(((SvgPoint)shape).X)); + writer.WriteAttributeString("cy", Num(((SvgPoint)shape).Y)); + writer.WriteAttributeString("r", Num(markerRadius)); + writer.WriteAttributeString("fill", stroke); + writer.WriteAttributeString("stroke", "none"); + writer.WriteEndElement(); + break; + } + } + + writer.WriteEndElement(); + writer.WriteEndElement(); + writer.WriteEndDocument(); + } + + private abstract record SvgShape(int ColorIndex); + + private sealed record SvgLine(double X1, double Y1, double X2, double Y2, int ColorIndex) : SvgShape(ColorIndex); + + private sealed record SvgCircle(double Cx, double Cy, double Radius, int ColorIndex) : SvgShape(ColorIndex); + + // Start and span are normalised (span > 0); the endpoints follow in SVG coordinates. + private sealed record SvgArc(double Cx, double Cy, double Radius, double Start, double Span, int ColorIndex) + : SvgShape(ColorIndex); + + private sealed record SvgPoint(double X, double Y, int ColorIndex) : SvgShape(ColorIndex); + + private static List Collect(DwgDocument document, double scale) + { + var shapes = new List(); + foreach (var entity in document.Entities) + { + switch (entity.Kind, entity.Geometry) + { + case (DwgEntityKind.Line, [var x1, var y1, var z1, var x2, var y2, var z2]): + if (IsUsable(x1, y1, x2, y2)) + { + shapes.Add(new SvgLine(x1 * scale, -y1 * scale, x2 * scale, -y2 * scale, entity.ColorIndex)); + } + else + { + Skip(document, entity, "non-finite coordinates"); + } + + break; + case (DwgEntityKind.Circle, [var cx, var cy, var cz, var r]): + if (IsUsable(cx, cy) && IsUsable(r) && r > 0) + { + shapes.Add(new SvgCircle(cx * scale, -cy * scale, r * scale, entity.ColorIndex)); + } + else + { + Skip(document, entity, "non-finite or non-positive radius"); + } + + break; + case (DwgEntityKind.Arc, [var cx, var cy, _, var r, var start, var end]): + if (IsUsable(cx, cy) && IsUsable(r, start, end) && r > 0) + { + shapes.Add(ArcShape(cx * scale, -cy * scale, r * scale, start, end, entity.ColorIndex)); + } + else + { + Skip(document, entity, "non-finite or non-positive radius"); + } + + break; + case (DwgEntityKind.Point, [var x, var y, _]): + if (IsUsable(x, y)) + { + shapes.Add(new SvgPoint(x * scale, -y * scale, entity.ColorIndex)); + } + else + { + Skip(document, entity, "non-finite coordinates"); + } + + break; + } + } + + return shapes; + } + + private static void Skip(DwgDocument document, DwgEntity entity, string reason) => + document.ReportDiagnostic($"svg: entity {entity.Handle:X} ({entity.TypeName}) skipped: {reason}"); + + private static bool IsUsable(params double[] values) => values.All(double.IsFinite); + + private static SvgArc ArcShape(double cx, double cy, double radius, double start, double end, int colorIndex) + { + double span = end - start; + while (span <= 0) + { + // AutoCAD draws an arc with equal start and end angles as a full circle. + span += 2.0 * Math.PI; + } + + return new SvgArc(cx, cy, radius, start, span, colorIndex); + } + + private static (double X1, double Y1, double X2, double Y2) ArcEndpoints(SvgArc arc) => + ( + arc.Cx + arc.Radius * Math.Cos(arc.Start), + arc.Cy - arc.Radius * Math.Sin(arc.Start), + arc.Cx + arc.Radius * Math.Cos(arc.Start + arc.Span), + arc.Cy - arc.Radius * Math.Sin(arc.Start + arc.Span) + ); + + private static (double MinX, double MinY, double Width, double Height) ViewBox(List shapes) + { + double minX = double.PositiveInfinity, minY = double.PositiveInfinity; + double maxX = double.NegativeInfinity, maxY = double.NegativeInfinity; + foreach (var shape in shapes) + { + switch (shape) + { + case SvgLine line: + Expand(line.X1, line.Y1); + Expand(line.X2, line.Y2); + break; + case SvgCircle circle: + Expand(circle.Cx - circle.Radius, circle.Cy - circle.Radius); + Expand(circle.Cx + circle.Radius, circle.Cy + circle.Radius); + break; + case SvgArc arc: + (double x1, double y1, double x2, double y2) = ArcEndpoints(arc); + Expand(x1, y1); + Expand(x2, y2); + // The extremes of the four cardinal directions lie inside the arc when their angle falls + // within its span; without them the view box could cut through the drawn curve. + for (int k = 0; k < 4; k++) + { + double angle = k * Math.PI / 2.0; + while (angle < arc.Start) + { + angle += 2.0 * Math.PI; + } + + if (angle <= arc.Start + arc.Span) + { + Expand(arc.Cx + arc.Radius * Math.Cos(angle), -Math.Sin(angle) * arc.Radius + arc.Cy); + } + } + + break; + case SvgPoint point: + Expand(point.X, point.Y); + break; + } + } + + if (minX > maxX) + { + return (0, 0, 0, 0); + } + + return (minX, minY, maxX - minX, maxY - minY); + + void Expand(double x, double y) + { + minX = Math.Min(minX, x); + minY = Math.Min(minY, y); + maxX = Math.Max(maxX, x); + maxY = Math.Max(maxY, y); + } + } + + private static string ColourOf(int colorIndex) + { + // BYBLOCK (0) and BYLAYER (256) resolve to the default layer colour, which is 7; on a light background + // AutoCAD renders 7 (white) as black. + int resolved = colorIndex is > 0 and < 256 ? colorIndex : 7; + if (resolved == 7) + { + return "#000000"; + } + + (byte r, byte g, byte b) = DwgAciPalette.RgbOf(resolved); + return FormattableString.Invariant($"#{r:X2}{g:X2}{b:X2}"); + } + + private static string Num(double value) + { + if (value == 0.0) + { + value = 0.0; // normalise -0 + } + + return value.ToString("0.######", CultureInfo.InvariantCulture); + } +} diff --git a/src/DwgIO.Scene/DwgSvgOptions.cs b/src/DwgIO.Scene/DwgSvgOptions.cs new file mode 100644 index 0000000..ce403ce --- /dev/null +++ b/src/DwgIO.Scene/DwgSvgOptions.cs @@ -0,0 +1,19 @@ +namespace DwgIO.Scene; + +/// Options of the SVG export of model space. +public sealed class DwgSvgOptions +{ + /// + /// Pixels per drawing unit. The geometry is scaled by it, so the viewBox, width and + /// height grow together: the drawing keeps its aspect at every scale, and one viewBox unit is + /// one pixel. + /// + public double Scale { get; set; } = 1.0; + + /// Stroke width of the drawn entities, in pixels; it stays fixed while the scale zooms the drawing. + public double StrokeWidth { get; set; } = 1.0; + + /// Background colour, as CSS. AutoCAD renders on a dark background, but SVG files are usually + /// viewed on light ones, so the default is white and colour 7 (white/black) renders black. + public string Background { get; set; } = "white"; +} diff --git a/src/DwgIO/DwgIO.csproj b/src/DwgIO/DwgIO.csproj index 74dacaf..4aea63d 100644 --- a/src/DwgIO/DwgIO.csproj +++ b/src/DwgIO/DwgIO.csproj @@ -8,6 +8,7 @@ + diff --git a/tests/DwgIO.Tests/DwgSvgExporterTests.cs b/tests/DwgIO.Tests/DwgSvgExporterTests.cs new file mode 100644 index 0000000..871483e --- /dev/null +++ b/tests/DwgIO.Tests/DwgSvgExporterTests.cs @@ -0,0 +1,189 @@ +using System.Text; +using System.Xml; +using DwgIO.Model; +using DwgIO.Scene; +using Xunit; + +namespace DwgIO.Tests; + +public class DwgSvgExporterTests +{ + private static DwgDocument CreateDocument(params DwgEntity[] entities) => + new( + "synthetic.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1024", + Release = "R2010", + Family = DwgContainerFamily.R2004Family, + Year = 2010, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + entities); + + private static DwgEntity Entity(ulong handle, DwgEntityKind kind, string typeName, double[] geometry, int colorIndex = 256) => + new() + { + Handle = handle, + TypeCode = 0x13, + TypeName = typeName, + Kind = kind, + Geometry = geometry, + ColorIndex = colorIndex, + }; + + private static string WriteToString(DwgDocument document, DwgSvgOptions? options = null) + { + using var stream = new MemoryStream(); + DwgSvgExporter.Write(document, stream, options); + return Encoding.UTF8.GetString(stream.ToArray()); + } + + private static string SingleLineSvg() => WriteToString(CreateDocument( + Entity(0x2A, DwgEntityKind.Line, "LINE", [10.0, 20.0, 0.0, 30.0, 20.0, 0.0], colorIndex: 1))); + + [Fact] + public void Write_DrawsLineWithFlippedYAndAciColour() + { + string svg = SingleLineSvg(); + + // The Y flip puts the line at y = -20, and ACI 1 is pure red. + Assert.Contains("", svg, StringComparison.Ordinal); + } + + [Fact] + public void Write_ViewBoxContainsEveryEntity() + { + var document = CreateDocument( + Entity(0x2A, DwgEntityKind.Line, "LINE", [10.0, 20.0, 0.0, 30.0, 20.0, 0.0]), + Entity(0x2B, DwgEntityKind.Circle, "CIRCLE", [-50.0, 0.0, 0.0, 5.0]), + Entity(0x2C, DwgEntityKind.Arc, "ARC", [0.0, 0.0, 0.0, 40.0, 0.1, 1.7]), + Entity(0x2D, DwgEntityKind.Point, "POINT", [100.0, -60.0, 0.0])); + + string svg = WriteToString(document); + + string viewBox = Between(svg, "viewBox=\"", "\""); + string[] parts = viewBox.Split(' '); + double minX = Parse(parts[0]); + double minY = Parse(parts[1]); + double width = Parse(parts[2]); + double height = Parse(parts[3]); + // Every coordinate the entities occupy after the y flip: the circle's left edge (-55), the arc's top + // extreme at angle 90° (y -40), the point at x 100 (flipped to y 60). + Assert.True(minX <= -55); + Assert.True(minY <= -40); + Assert.True(minX + width >= 100); + Assert.True(minY + height >= 60); + } + + [Fact] + public void Write_ArcPathIsWellFormedAndContinuous() + { + // An arc through the top cardinal: from 10° to 170° around (0,0) with r 40 passes (0, 40). + var document = CreateDocument(Entity(0x2A, DwgEntityKind.Arc, "ARC", [0.0, 0.0, 0.0, 40.0, 10.0 * Math.PI / 180.0, 170.0 * Math.PI / 180.0])); + + string svg = WriteToString(document); + + string path = Between(svg, "", svg, StringComparison.Ordinal); + Assert.Contains("stroke=\"#545454\" />", svg, StringComparison.Ordinal); + Assert.Equal(3, svg.Split("stroke=\"#000000\" />").Length - 1); + } + + [Fact] + public void Write_ScaleMultipliesWidthAndHeight() + { + string svg = WriteToString(CreateDocument(Entity(0x2A, DwgEntityKind.Line, "LINE", [0.0, 0.0, 0.0, 10.0, 0.0, 0.0])), new DwgSvgOptions { Scale = 2.5 }); + + // 10 units × 2.5 px/unit = 25 px, plus the 8 px margin on every side. + Assert.Equal("41", Between(svg, "width=\"", "\"")); + } + + [Fact] + public void WriteFile_IsAtomicAndLeavesNoTemporaryFile() + { + string directory = Path.Combine(Path.GetTempPath(), "dwgio-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + try + { + string path = Path.Combine(directory, "drawing.svg"); + DwgSvgExporter.WriteFile(SingleLineSvgDocument(), path, null); + + Assert.Contains(" CreateDocument( + Entity(0x2A, DwgEntityKind.Line, "LINE", [0.0, 0.0, 0.0, 10.0, 0.0, 0.0])); + + private static System.Xml.Linq.XName XName(string local) => System.Xml.Linq.XName.Get(local, "http://www.w3.org/2000/svg"); + + private static string Between(string text, string start, string end) + { + int from = text.IndexOf(start, StringComparison.Ordinal) + start.Length; + int to = text.IndexOf(end, from, StringComparison.Ordinal); + return text[from..to]; + } + + private static double Parse(string value) => + double.Parse(value, System.Globalization.CultureInfo.InvariantCulture); +} From 946d20cba3fea6bee0df2b546f8ee6c3b008f346 Mon Sep 17 00:00:00 2001 From: mahach666 Date: Fri, 20 Nov 2026 02:26:07 +0300 Subject: [PATCH 05/20] Write a standalone HTML viewer of the drawing DwgViewerExport.SaveViewer converts the drawing to an IOScene scene and embeds it with the IOViewer WebGL runtime into one interactive HTML file (no server, no external scripts); the default viewer title follows the scene. dwgio drawing.dwg out.html drives it through the output extension, next to OBJ, GLB and JSON. --- CHANGELOG.md | 2 + Directory.Packages.props | 2 + README.md | 8 ++ docs/public-api.md | 1 + src/DwgIO.Cli/Program.cs | 8 +- src/DwgIO.Scene/DwgIO.Scene.csproj | 1 + src/DwgIO.Scene/DwgViewerExport.cs | 67 ++++++++++++++++ tests/DwgIO.Tests/DwgViewerExportTests.cs | 97 +++++++++++++++++++++++ 8 files changed, 185 insertions(+), 1 deletion(-) create mode 100644 src/DwgIO.Scene/DwgViewerExport.cs create mode 100644 tests/DwgIO.Tests/DwgViewerExportTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b2bacc..87ae920 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,8 @@ API between minor releases. - `DwgSvgExporter` and `dwgio svg [--scale n]` draw model space to SVG (#32): LINE, CIRCLE, ARC and POINT in the top view with the y axis up, in their ACI colours, inside a view box that contains every exported entity. Polylines, curves and text follow as the core decodes them. +- `DwgViewerExport.SaveViewer` and `dwgio drawing.dwg out.html` write a standalone interactive 3D HTML viewer + (the IOViewer WebGL runtime embedded with the IOScene scene document; no server, no external scripts). ### Fixed - Packed 16-bit and 32-bit integers in their full-width form are read little-endian. They were read with their bytes diff --git a/Directory.Packages.props b/Directory.Packages.props index 847b947..adb5083 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -14,6 +14,8 @@ IOScene.Formats (GLB and OBJ writers) ships as a preview and needs IOScene 0.1.1 or later. --> + + diff --git a/README.md b/README.md index 4e9493c..72f49e4 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ DwgIO is a .NET library and command line tool that reads Autodesk AutoCAD drawin - Converts a drawing into a neutral [IOScene](https://www.nuget.org/packages/IOScene) scene document (`DwgIO.Scene` package): geometry in metres, ACI entity colours, one element per entity with its handle. - Exports the scene to Wavefront OBJ (with an MTL colour library) and binary glTF (GLB). - Draws model space to SVG (`dwgio svg`): LINE, CIRCLE, ARC and POINT in the top view, in their ACI colours. +- Writes a standalone interactive 3D HTML viewer (`.html`): the WebGL viewer of [IOViewer](https://github.com/IOExtend/IOViewer) embedded with the scene, no server or external scripts. ## Install @@ -78,6 +79,12 @@ Draw model space to SVG (X to the right, Y up, ACI colours; `--scale` sets pixel dwgio svg drawing.dwg drawing.svg --scale 2 ``` +Open the drawing in a standalone interactive 3D HTML viewer: + +```sh +dwgio drawing.dwg drawing.html +``` + Errors go to standard error. ### Exit codes @@ -150,6 +157,7 @@ The documentation site with the API reference is at Print version + section table dwgio Export metadata, section catalog and entities to JSON, - or the scene to OBJ (.obj) or GLB (.glb) + or the scene to OBJ (.obj), GLB (.glb) or a standalone + interactive 3D HTML viewer (.html) dwgio extract
Write a named section's decompressed bytes dwgio preview Write the embedded thumbnail image dwgio scene [--unit u] Export a neutral IOScene scene document @@ -187,6 +188,11 @@ private static int Export(string[] args) var glbResult = DwgSceneExport.SaveGlb(doc, output); Console.WriteLine($"{doc.Version} elements={glbResult.ElementCount} ({glbResult.ElementsWithGeometry} with geometry) -> {output}"); } + else if (Path.GetExtension(output).Equals(".html", StringComparison.OrdinalIgnoreCase)) + { + var htmlResult = DwgViewerExport.SaveViewer(doc, output); + Console.WriteLine($"{doc.Version} elements={htmlResult.ElementCount} ({htmlResult.ElementsWithGeometry} with geometry) -> {output}"); + } else { DwgJsonExporter.WriteFile(doc, output, DwgJsonExportOptions.Default); diff --git a/src/DwgIO.Scene/DwgIO.Scene.csproj b/src/DwgIO.Scene/DwgIO.Scene.csproj index 33967db..c333a16 100644 --- a/src/DwgIO.Scene/DwgIO.Scene.csproj +++ b/src/DwgIO.Scene/DwgIO.Scene.csproj @@ -12,6 +12,7 @@ + diff --git a/src/DwgIO.Scene/DwgViewerExport.cs b/src/DwgIO.Scene/DwgViewerExport.cs new file mode 100644 index 0000000..aa86662 --- /dev/null +++ b/src/DwgIO.Scene/DwgViewerExport.cs @@ -0,0 +1,67 @@ +using IOViewer.Exporters; +using IOScene; + +namespace DwgIO.Scene; + +/// +/// Exports a drawing as a standalone interactive 3D HTML viewer: one self-contained file with the scene and the +/// WebGL viewer runtime embedded, no server and no external scripts. The viewer is generated by +/// IOViewer from the IOScene scene document, so the +/// drawing shows exactly what the scene JSON and the OBJ/GLB exports describe. +/// +public static class DwgViewerExport +{ + /// Converts the drawing and writes it to a standalone interactive HTML viewer file. + /// The drawing, for example from . + /// Path to the HTML file. + /// Scene conversion options; null uses the defaults. + /// Viewer options (title, initial mode, vertex budget); null uses the defaults. + /// The conversion report. is the scene the viewer embeds. + public static DwgSceneResult SaveViewer( + DwgDocument document, + string htmlPath, + DwgSceneOptions? options = null, + HtmlViewerOptions? viewerOptions = null) + { + var result = DwgSceneReader.Read(document, ViewerOptionsFor(document, htmlPath, options)); + WriteViewer(result.Document, htmlPath, viewerOptions); + return result; + } + + /// Writes a scene to a standalone interactive HTML viewer file. + /// The scene to embed. + /// Path to the HTML file. + /// Viewer options; null uses the defaults. + public static void WriteViewer(SceneDocument scene, string htmlPath, HtmlViewerOptions? viewerOptions = null) + { + ArgumentNullException.ThrowIfNull(scene); + ArgumentException.ThrowIfNullOrEmpty(htmlPath); + if (viewerOptions is null) + { + // Default options take their title from the scene; a caller's options are respected as given, + // with an empty title filled from the scene. + viewerOptions = new HtmlViewerOptions { Title = scene.Title }; + } + else if (string.IsNullOrEmpty(viewerOptions.Title)) + { + viewerOptions.Title = scene.Title; + } + + HtmlViewerExporter.Save(scene, htmlPath, viewerOptions); + } + + private static DwgSceneOptions ViewerOptionsFor(DwgDocument document, string path, DwgSceneOptions? options) + { + if (options?.ModelKey is { Length: > 0 }) + { + return options; + } + + // The export file name doubles as the model key; a document from memory falls back to it. + return new DwgSceneOptions + { + LengthUnit = options?.LengthUnit ?? "m", + ModelKey = Path.GetFileName(path), + }; + } +} diff --git a/tests/DwgIO.Tests/DwgViewerExportTests.cs b/tests/DwgIO.Tests/DwgViewerExportTests.cs new file mode 100644 index 0000000..9ae16b6 --- /dev/null +++ b/tests/DwgIO.Tests/DwgViewerExportTests.cs @@ -0,0 +1,97 @@ +using DwgIO.Model; +using DwgIO.Scene; +using Xunit; + +namespace DwgIO.Tests; + +public class DwgViewerExportTests : IDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), "dwgio-tests-" + Guid.NewGuid().ToString("N")); + + public DwgViewerExportTests() + { + Directory.CreateDirectory(_directory); + } + + public void Dispose() + { + GC.SuppressFinalize(this); + try + { + Directory.Delete(_directory, recursive: true); + } + catch (DirectoryNotFoundException) + { + } + } + + private static DwgDocument CreateDocument(params DwgEntity[] entities) => + new( + "synthetic.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1024", + Release = "R2010", + Family = DwgContainerFamily.R2004Family, + Year = 2010, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + entities); + + private static DwgDocument SampleDrawing() => CreateDocument( + new DwgEntity + { + Handle = 0x2A, + TypeCode = 0x13, + TypeName = "LINE", + Kind = DwgEntityKind.Line, + Geometry = [0.0, 0.0, 0.0, 10.0, 0.0, 0.0], + ColorIndex = 1, + }, + new DwgEntity + { + Handle = 0x2B, + TypeCode = 0x12, + TypeName = "CIRCLE", + Kind = DwgEntityKind.Circle, + Geometry = [5.0, 0.0, 0.0, 5.0], + ColorIndex = 40, + }); + + [Fact] + public void SaveViewer_WritesSelfContainedHtml() + { + string htmlPath = Environment.GetEnvironmentVariable("DWGIO_VIEWER_DEBUG_PATH") is { Length: > 0 } debug + ? debug + : Path.Combine(_directory, "drawing.html"); + + var result = DwgViewerExport.SaveViewer(SampleDrawing(), htmlPath); + + Assert.Equal(2, result.ElementCount); + string html = File.ReadAllText(htmlPath); + // A standalone viewer: the WebGL runtime is embedded, no external script or stylesheet is referenced. + Assert.Contains("", html, StringComparison.OrdinalIgnoreCase); + Assert.Contains("canvas", html, StringComparison.Ordinal); + Assert.DoesNotContain("", metaStart, StringComparison.Ordinal); + using var metadata = JsonDocument.Parse(html[metaStart..metaEnd]); + Assert.Equal(3, metadata.RootElement.GetProperty("geometries").GetArrayLength()); Assert.Contains("id=\"ioviewer-bin\"", html, StringComparison.Ordinal); } diff --git a/tests/DwgIO.Tests/EncryptedSectionTests.cs b/tests/DwgIO.Tests/EncryptedSectionTests.cs index 04ceb06..8dba824 100644 --- a/tests/DwgIO.Tests/EncryptedSectionTests.cs +++ b/tests/DwgIO.Tests/EncryptedSectionTests.cs @@ -7,7 +7,9 @@ namespace DwgIO.Tests; /// A section map with an encrypted entry: the section is skipped with a diagnostic, not silently (#38). public class EncryptedSectionTests { - private static DwgDocument CreateDocument(params SectionEntry[] entries) + private static DwgDocument CreateDocument(params SectionEntry[] entries) => CreateDocument(readMetadata: false, entries); + + private static DwgDocument CreateDocument(bool readMetadata, params SectionEntry[] entries) { var container = new R2004Container { @@ -52,7 +54,7 @@ private static DwgDocument CreateDocument(params SectionEntry[] entries) PreviewOffset = 0, Codepage = 30, }, - new DwgReaderOptions { ReadSummaryInfo = false, ReadMetadata = false, ReadObjects = false }); + new DwgReaderOptions { ReadSummaryInfo = false, ReadMetadata = readMetadata, ReadObjects = false }); return document; } @@ -69,6 +71,20 @@ private static DwgDocument CreateDocument(params SectionEntry[] entries) }; + [Theory] + [InlineData(0u)] + [InlineData(1u)] + public void PreviewCommand_WhenSectionCannotBeRead_ReturnsParseError(uint encryption) + { + var document = CreateDocument(readMetadata: true, Section("AcDb:Preview", encryption)); + using var output = new StringWriter(); + using var error = new StringWriter(); + + Assert.Equal(4, Cli.Program.PreviewDocument(document, "unused", output, error)); + Assert.Contains("AcDb:Preview:", error.ToString(), StringComparison.Ordinal); + Assert.Empty(output.ToString()); + } + [Fact] public void TryGetReadableSection_EncryptedEntry_IsSkippedWithADiagnostic() { diff --git a/tests/DwgIO.Tests/EntityTypeTests.cs b/tests/DwgIO.Tests/EntityTypeTests.cs index e1142e4..69931f5 100644 --- a/tests/DwgIO.Tests/EntityTypeTests.cs +++ b/tests/DwgIO.Tests/EntityTypeTests.cs @@ -25,6 +25,7 @@ public void DrawableFixedCodes_AreEntities(ushort typeCode) [Theory] [InlineData(0x00)] // UNUSED + [InlineData(0x09)] // reserved in the supported versions [InlineData(0x30)] // BLOCK CONTROL OBJ public void ObjectsAndOutOfRangeCodes_AreNotEntities(ushort typeCode) { diff --git a/tests/DwgIO.Tests/HistorySectionsTests.cs b/tests/DwgIO.Tests/HistorySectionsTests.cs index 8a63859..7c938ba 100644 --- a/tests/DwgIO.Tests/HistorySectionsTests.cs +++ b/tests/DwgIO.Tests/HistorySectionsTests.cs @@ -93,10 +93,9 @@ public void AuxHeader_ParsesTheFixedLayout() Assert.Equal(0x2Bul, aux.Handseed); Assert.Equal(2460311u, aux.CreatedRaw.JulianDay); Assert.Equal(43200000u, aux.CreatedRaw.Milliseconds); - Assert.NotNull(aux.CreatedUtc); - Assert.InRange(aux.CreatedUtc!.Value.Year, 2020, 2030); - Assert.NotNull(aux.ModifiedUtc); - Assert.InRange(aux.ModifiedUtc!.Value.Year, 2020, 2030); + var midnight = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc); + Assert.Equal(midnight.AddHours(12), aux.CreatedUtc); + Assert.Equal(midnight.AddDays(1).AddMilliseconds(-1), aux.ModifiedUtc); } [Fact] @@ -126,53 +125,6 @@ public void AuxHeader_Truncated_Throws() Assert.Throws(() => AuxHeaderParser.Parse(new byte[50])); } - // ------------------------------------------------------------------ AppInfoHistory - - [Fact] - public void AppInfoHistory_WalksTheRecordSequence() - { - var data = new List(); - WriteAnsiAppInfo(data, "AppInfoDataList", "1.0", "First"); - WriteAnsiAppInfo(data, "AppInfoDataList", "2.0", "Second"); - - var diagnostics = new List(); - var records = AppInfoHistoryParser.Parse([.. data], 30, diagnostics.Add); - - Assert.Equal(2, records.Count); - Assert.Equal("1.0", records[0].Version); - Assert.Equal("2.0", records[1].Version); - Assert.Empty(diagnostics); - } - - [Fact] - public void AppInfoHistory_TruncatedTail_IsReported() - { - var data = new List(); - WriteAnsiAppInfo(data, "AppInfoDataList", "1.0", "First"); - data.AddRange([0x00, 0x00]); // two trailing bytes: too small for a record - - var diagnostics = new List(); - var records = AppInfoHistoryParser.Parse([.. data], 30, diagnostics.Add); - - Assert.Single(records); - Assert.Contains(diagnostics, d => d.Contains("too small for a record", StringComparison.Ordinal)); - } - - [Fact] - public void AppInfoHistory_BrokenRecord_IsReported() - { - var data = new List(); - WriteAnsiAppInfo(data, "AppInfoDataList", "1.0", "First"); - // A record whose string runs past the payload. - data.AddRange([0x20, 0x00, (byte)'x', (byte)'y']); - - var diagnostics = new List(); - var records = AppInfoHistoryParser.Parse([.. data], 30, diagnostics.Add); - - Assert.Single(records); - Assert.Contains(diagnostics, d => d.Contains("does not decode", StringComparison.Ordinal)); - } - private static void WriteAnsiString16(List data, string text) { var bytes = System.Text.Encoding.ASCII.GetBytes(text); @@ -180,13 +132,4 @@ private static void WriteAnsiString16(List data, string text) data.AddRange(bytes); data.Add(0); } - - private static void WriteAnsiAppInfo(List data, string name, string version, string product) - { - WriteAnsiString16(data, name); - data.AddRange([0x00, 0x00, 0x00, 0x00]); // u32 marker/unknown word - WriteAnsiString16(data, string.Empty); - WriteAnsiString16(data, $""); - WriteAnsiString16(data, version); - } } diff --git a/tests/DwgIO.Tests/JsonExporterTests.cs b/tests/DwgIO.Tests/JsonExporterTests.cs index 7ab59d9..11afcaa 100644 --- a/tests/DwgIO.Tests/JsonExporterTests.cs +++ b/tests/DwgIO.Tests/JsonExporterTests.cs @@ -35,6 +35,29 @@ private static DwgEntity CreateEntity(double[] geometry) => Geometry = geometry, }; + [Fact] + public void Write_LeavesObjectTypeCodesAndAddsNames() + { + var header = new DwgFileHeader + { + Version = DwgVersionInfo.FromMagic("AC1032"u8.ToArray()), + Codepage = 30, MaintenanceVersion = 0, PreviewOffset = 0, + }; + var item = new DwgObjectInfo + { + TypeCode = 0x13, Handle = 1, StreamHandle = new DwgHandle(0, 1, 1), + StreamOffset = 4, SizeBytes = 2, BitsStart = 6, BitsLength = 16, + }; + var document = new DwgDocument("synthetic.dwg", header, [], objects: [item]); + using var buffer = new MemoryStream(); + DwgJsonExporter.Write(document, buffer, DwgJsonExportOptions.Default); + using var json = JsonDocument.Parse(buffer.ToArray()); + var objects = json.RootElement.GetProperty("objects"); + + Assert.Equal(1, objects.GetProperty("byType").GetProperty("13").GetInt32()); + Assert.Equal(1, objects.GetProperty("byTypeName").GetProperty("LINE").GetInt32()); + } + [Fact] public void Write_NonFiniteGeometry_WritesNullAndRecordsDiagnostic() { diff --git a/tests/DwgIO.Tests/MetadataParserTests.cs b/tests/DwgIO.Tests/MetadataParserTests.cs index c7dc503..c957281 100644 --- a/tests/DwgIO.Tests/MetadataParserTests.cs +++ b/tests/DwgIO.Tests/MetadataParserTests.cs @@ -156,6 +156,18 @@ public void AppInfo_Product_ComesFromTheXmlNameAttribute() Assert.Equal("AutoCAD", appInfo.Product); } + [Theory] + [InlineData("", "AutoCAD")] + [InlineData("", "AutoCAD LT")] + [InlineData("", "A & B")] + [InlineData("", "Writer")] + public void AppInfo_Product_HandlesXmlAttributeForms(string xml, string expected) + { + var data = BuildUnicodeAppInfo("AppInfoDataList", (ProductXmlEntryId, xml)); + + Assert.Equal(expected, AppInfoParser.Parse(data, 30).Product); + } + [Fact] public void AppInfo_Product_IsEmptyWithoutANameAttribute() { diff --git a/tests/DwgIO.Tests/ObjectStreamGapTests.cs b/tests/DwgIO.Tests/ObjectStreamGapTests.cs index e9e1840..cde7768 100644 --- a/tests/DwgIO.Tests/ObjectStreamGapTests.cs +++ b/tests/DwgIO.Tests/ObjectStreamGapTests.cs @@ -70,6 +70,21 @@ public void Walk_ZeroGapWithoutMap_EndsCleanly() Assert.Empty(diagnostics); } + [Fact] + public void CountUnreachedObjects_UsesBothHandleAndOffset() + { + var stream = new RecordBitWriter(); + stream.WriteRecord(r => r.WriteLineRecord()); + var objects = ObjectStreamWalker.Walk(stream.ToArray(), r2010Plus: true); + var item = Assert.Single(objects); + var map = new DwgHandleMap + { + Entries = [new DwgHandleMapEntry(item.Handle, (ulong)item.StreamOffset + 1)], + }; + + Assert.Equal(1, DwgDocument.CountUnreachedObjects(objects, map)); + } + [Fact] public void Walk_TruncatedTailWithoutRecovery_ReportsTheStop() { diff --git a/tests/DwgIO.Tests/OpenStreamTests.cs b/tests/DwgIO.Tests/OpenStreamTests.cs index 71423f8..2a5272e 100644 --- a/tests/DwgIO.Tests/OpenStreamTests.cs +++ b/tests/DwgIO.Tests/OpenStreamTests.cs @@ -99,22 +99,19 @@ public void Open_Stream_DefaultName_IsStream() private static string Core(string message) => message[(message.IndexOf(": ", StringComparison.Ordinal) + 2)..]; [SkippableFact] - public void Open_Stream_MatchesPath_OnEveryAvailableDrawing() + public void Open_Stream_MatchesPath_OnEveryAvailableDrawing() => DwgFixtureTests.CheckAll(path => { - // The same-results gate of #37; runs when private drawings are available (see docs/test-fixtures.md). - foreach (string path in TestFiles.DwgFiles()) - { - var fromPath = DwgDocument.Open(path, new DwgReaderOptions { ReadObjects = true }); - byte[] bytes = File.ReadAllBytes(path); - using var stream = new MemoryStream(bytes); - var fromStream = DwgDocument.Open(stream, Path.GetFileName(path), new DwgReaderOptions { ReadObjects = true }); - - Assert.Equal(fromPath.Version.Magic, fromStream.Version.Magic); - Assert.Equal(fromPath.FileSize, fromStream.FileSize); - Assert.Equal(fromPath.Sections.Count, fromStream.Sections.Count); - Assert.Equal(fromPath.Objects.Count, fromStream.Objects.Count); - Assert.Equal(fromPath.Entities.Count, fromStream.Entities.Count); - Assert.Equal(fromPath.Diagnostics.Count, fromStream.Diagnostics.Count); - } - } + var fromPath = DwgDocument.Open(path); + using var stream = File.OpenRead(path); + var fromStream = DwgDocument.Open(stream, path); + using var fileJson = new MemoryStream(); + using var streamJson = new MemoryStream(); + Json.DwgJsonExporter.Write(fromPath, fileJson, Json.DwgJsonExportOptions.Default); + Json.DwgJsonExporter.Write(fromStream, streamJson, Json.DwgJsonExportOptions.Default); + + Assert.Equal(fromPath.Diagnostics, fromStream.Diagnostics); + Assert.True(fileJson.GetBuffer().AsSpan(0, (int)fileJson.Length) + .SequenceEqual(streamJson.GetBuffer().AsSpan(0, (int)streamJson.Length))); + return true; + }, "a readable container"); } From 22b3cfc3fce40bfbf99c924504761179ac59c55a Mon Sep 17 00:00:00 2001 From: mahach666 Date: Fri, 20 Nov 2026 04:38:29 +0300 Subject: [PATCH 20/20] Apply protected ACL fixtures to both OBJ output files --- tests/DwgIO.Tests/DwgSceneExportTests.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/DwgIO.Tests/DwgSceneExportTests.cs b/tests/DwgIO.Tests/DwgSceneExportTests.cs index 1d317d3..9402f1e 100644 --- a/tests/DwgIO.Tests/DwgSceneExportTests.cs +++ b/tests/DwgIO.Tests/DwgSceneExportTests.cs @@ -232,13 +232,13 @@ public void SaveObj_Overwrite_PreservesBothFilesAccessRules() if (OperatingSystem.IsWindows()) { var user = System.Security.Principal.WindowsIdentity.GetCurrent().User!; - var acl = new System.Security.AccessControl.FileSecurity(); - acl.SetAccessRuleProtection(true, preserveInheritance: false); - acl.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(user, - System.Security.AccessControl.FileSystemRights.FullControl, - System.Security.AccessControl.AccessControlType.Allow)); foreach (string path in paths) { + var acl = new System.Security.AccessControl.FileSecurity(); + acl.SetAccessRuleProtection(true, preserveInheritance: false); + acl.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(user, + System.Security.AccessControl.FileSystemRights.FullControl, + System.Security.AccessControl.AccessControlType.Allow)); new FileInfo(path).SetAccessControl(acl); }