From a53d9e46e9f625931ae0c755b6e68fcb45890a09 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:46:12 +0000 Subject: [PATCH 1/6] Bump IOScene from 0.1.1 to 0.1.2 --- updated-dependencies: - dependency-name: IOScene dependency-version: 0.1.2 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 02fe636..635fc31 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -12,7 +12,7 @@ - + From 0f669a4af02cb447171d1718d750d9f515584beb Mon Sep 17 00:00:00 2001 From: mahach666 Date: Tue, 1 Dec 2026 13:09:34 +0300 Subject: [PATCH 2/6] Align DwgIO core and scene adapter with org standard and add 2D AutoCAD HTML viewer --- .github/workflows/ci.yml | 1 + CHANGELOG.md | 16 + CONTRIBUTING.md | 7 +- Directory.Build.props | 4 +- Directory.Packages.props | 9 +- DwgIO.slnx | 1 - README.md | 32 +- docfx.json | 3 +- docs/public-api.md | 47 +- src/DwgIO.Cli/DwgIO.Cli.csproj | 8 +- src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs | 1239 +++++++++++++++++ .../Export}/DwgSceneExport.cs | 45 +- .../Export}/DwgSvgExporter.cs | 29 +- .../Export}/DwgSvgOptions.cs | 2 +- src/DwgIO.Cli/Export/DwgViewerExport.cs | 90 ++ src/DwgIO.Cli/Export/DwgViewerOptions.cs | 45 + .../Export}/ViewerMeshGeometry.cs | 4 +- src/DwgIO.Cli/Program.cs | 286 +++- .../DwgIO.Scene.Adapter.csproj | 27 - .../Compatibility/DwgViewerExport.cs | 67 - src/DwgIO.Scene/DwgIO.Scene.csproj | 21 +- .../DwgSceneOptions.cs | 6 + .../DwgSceneReader.cs | 41 +- .../DwgSceneResult.cs | 0 src/DwgIO.Scene/TypeForwarders.cs | 6 - .../DwgDocument.Compatibility.cs | 13 + src/DwgIO/DiagnosticSink.cs | 47 + src/DwgIO/DwgDocument.cs | 327 ++++- src/DwgIO/DwgExitCodes.cs | 23 + src/DwgIO/DwgReaderOptions.cs | 93 +- src/DwgIO/Internal/Container/ObjectStream.cs | 13 +- .../Internal/Container/R2004Container.cs | 14 +- src/DwgIO/Model/DwgHandleMap.cs | 6 +- src/DwgIO/Model/DwgReadProgress.cs | 7 + tests/DwgIO.Tests/CoreStandardTests.cs | 212 +++ tests/DwgIO.Tests/DwgSceneExportTests.cs | 1 + tests/DwgIO.Tests/DwgSceneReaderTests.cs | 47 +- tests/DwgIO.Tests/DwgSvgExporterTests.cs | 2 +- tests/DwgIO.Tests/DwgViewerExportTests.cs | 58 +- 39 files changed, 2550 insertions(+), 349 deletions(-) create mode 100644 src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs rename src/{DwgIO.Scene/Compatibility => DwgIO.Cli/Export}/DwgSceneExport.cs (59%) rename src/{DwgIO.Scene/Compatibility => DwgIO.Cli/Export}/DwgSvgExporter.cs (89%) rename src/{DwgIO.Scene/Compatibility => DwgIO.Cli/Export}/DwgSvgOptions.cs (97%) create mode 100644 src/DwgIO.Cli/Export/DwgViewerExport.cs create mode 100644 src/DwgIO.Cli/Export/DwgViewerOptions.cs rename src/{DwgIO.Scene/Compatibility => DwgIO.Cli/Export}/ViewerMeshGeometry.cs (96%) delete mode 100644 src/DwgIO.Scene.Adapter/DwgIO.Scene.Adapter.csproj delete mode 100644 src/DwgIO.Scene/Compatibility/DwgViewerExport.cs rename src/{DwgIO.Scene.Adapter => DwgIO.Scene}/DwgSceneOptions.cs (78%) rename src/{DwgIO.Scene.Adapter => DwgIO.Scene}/DwgSceneReader.cs (85%) rename src/{DwgIO.Scene.Adapter => DwgIO.Scene}/DwgSceneResult.cs (100%) delete mode 100644 src/DwgIO.Scene/TypeForwarders.cs create mode 100644 src/DwgIO/Compatibility/DwgDocument.Compatibility.cs create mode 100644 src/DwgIO/DiagnosticSink.cs create mode 100644 src/DwgIO/DwgExitCodes.cs create mode 100644 src/DwgIO/Model/DwgReadProgress.cs create mode 100644 tests/DwgIO.Tests/CoreStandardTests.cs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 595d0e8..9bfe51e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -41,4 +41,5 @@ jobs: dotnet-version: | 8.0.x 10.0.x + - run: dotnet build src/DwgIO/DwgIO.csproj -c Release -p:BuildNativeCoreOnly=true --artifacts-path native-core-check - run: dotnet build src/DwgIO.Scene/DwgIO.Scene.csproj -c Release -p:BuildNativeCoreOnly=true --artifacts-path native-core-check diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e87d04..f5413b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,22 @@ API between minor releases. ## [Unreleased] +### Added +- `DwgReaderOptions`: `Strict`, `MaxFileBytes`, `MaxSectionBytes`, `MaxDecompressedBytes`, `MaxObjectCount`, + `ReleaseSectionBuffers`, `Progress` (`IProgress`), and `DiagnosticOutput` (`TextWriter?`). +- `DwgDocument`: `SourcePath`, `OpenAsync` (path and stream overloads), `ReleaseSectionBuffers()`, `SaveJson` and `ToJson`. +- `DwgExitCodes` public constants matching the CLI exit codes. +- `DwgSceneReader.Read(Stream, ...)` and `DwgSceneOptions.ReadProgress`. +- AutoCAD-style 2D HTML viewer (`DwgViewerMode.Cad2D`, default for `.html` exports): crisp top-down vector canvas, + Black / Slate / Light themes (`--bg`), adaptive ACI colour 7, grid, UCS icon, crosshair, coordinate readout, + entity search/filter and properties palette; `--mode 3d` retains the IOViewer WebGL 3D export. +- `--unit` support on direct `.obj`, `.glb` and `.html` CLI exports, and input/output collision checks across CLI commands. + +### Changed (breaking) +- Unified `DwgIO.Scene` as the pure `IOScene` adapter (matching `RvtIO.Scene` and `NwcIO.Scene`), removing `DwgIO.Scene.Adapter`. +- Moved `DwgSceneExport`, `DwgSvgExporter`, `DwgSvgOptions` and `DwgViewerExport` into `DwgIO.Cli` (`DwgIO.Export` namespace) so `DwgIO.Scene` has no dependency on `IOViewer` or `IOScene.Formats`. +- Updated package dependencies to `IOScene` `[0.1.2, 0.2.0-0.0)`, `IOScene.Formats` `0.1.0-preview.2` and `IOViewer` `0.4.2`. + ## [0.5.0] - 2026-11-20 ### Added diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6cb6835..ef5896c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -56,14 +56,15 @@ The library is in `src/DwgIO`, the CLI in `src/DwgIO.Cli`, and tests in `tests/DwgIO.Tests`. The engine owns DWG reading, its model and the JSON representation of the decoded drawing. -`DwgIO.Scene.Adapter` uses the public API of `DwgIO` and the IOScene contract. OBJ, GLB, SVG and HTML output -live in the existing `DwgIO.Scene` package alongside forwards for the adapter types. +`DwgIO.Scene` uses the public API of `DwgIO` and the IOScene contract (matching `RvtIO.Scene` and `NwcIO.Scene`). +OBJ, GLB, SVG and standalone HTML output live in `DwgIO.Cli` alongside the command line interface. Output file replacement and export diagnostics belong to the writers. -CI also builds the engine and adapter without the compatibility output code or its dependencies. +CI also builds the engine and scene adapter without the compatibility output code or its dependencies. Run the compile check with a separate artifact directory. ```sh +dotnet build src/DwgIO/DwgIO.csproj -c Release -p:BuildNativeCoreOnly=true --artifacts-path ./artifacts/native-core-check dotnet build src/DwgIO.Scene/DwgIO.Scene.csproj -c Release -p:BuildNativeCoreOnly=true --artifacts-path ./artifacts/native-core-check ``` diff --git a/Directory.Build.props b/Directory.Build.props index fb33cf2..3669aea 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -7,6 +7,8 @@ net8.0;net10.0 true true + true + $(MSBuildThisFileDirectory.Replace(',', ',,').Replace('=', '=='))=/_/ true true true @@ -14,7 +16,7 @@ - 0.5.0 + 0.6.0 mahach666 Copyright (c) 2026 IOExtend DwgIO diff --git a/Directory.Packages.props b/Directory.Packages.props index 02fe636..ddbfa87 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -11,11 +11,10 @@ - - - - + IOScene.Formats and IOViewer are used by the CLI tool only. --> + + + diff --git a/DwgIO.slnx b/DwgIO.slnx index a4ceab2..5cd14c6 100644 --- a/DwgIO.slnx +++ b/DwgIO.slnx @@ -1,6 +1,5 @@ - diff --git a/README.md b/README.md index 1928624..bb53bb0 100644 --- a/README.md +++ b/README.md @@ -12,10 +12,10 @@ DwgIO is a .NET library and command line tool that reads Autodesk AutoCAD drawin - Parses drawing metadata: summary information with custom properties and dates, application information, file dependencies and the embedded thumbnail preview. - 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.Adapter` 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). +- 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) through the CLI. - 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. +- Writes a standalone interactive HTML viewer (`.html`): defaults to an AutoCAD-style 2D CAD canvas (dark model-space background, orthographic top view, ACI colours, entity selection & properties), with `--mode 3d` for the WebGL viewer of [IOViewer](https://github.com/IOExtend/IOViewer). ## Install @@ -29,12 +29,9 @@ and add the libraries to a .NET project: ```sh dotnet add package DwgIO -dotnet add package DwgIO.Scene.Adapter +dotnet add package DwgIO.Scene ``` -Install `DwgIO.Scene` for the existing scene API with OBJ, GLB, SVG and HTML exporters. -It includes the adapter. - The libraries target .NET 8 and .NET 10. They use managed code without native dependencies or Windows-only APIs and support Windows, Linux and macOS. Tests run on Windows, Linux and macOS. ## Command line @@ -69,11 +66,11 @@ 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: +The plain export command writes OBJ, GLB and HTML by output extension (with `--unit mm|cm|m|ft|in`): ```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 +dwgio drawing.dwg drawing.obj --unit mm # Wavefront OBJ + drawing.mtl with the ACI colours +dwgio drawing.dwg drawing.glb --unit mm # 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): @@ -82,10 +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: +Open the drawing in a standalone interactive HTML viewer (AutoCAD-style 2D CAD view by default, or `--mode 3d` for WebGL 3D): ```sh dwgio drawing.dwg drawing.html +dwgio drawing.dwg drawing-slate.html --bg slate +dwgio drawing.dwg drawing-3d.html --mode 3d ``` List the decoded entities, one line each, optionally filtered by type and as JSON: @@ -146,8 +145,7 @@ foreach (var entity in doc.Entities) The JSON export is `DwgJsonExporter` in the `DwgIO.Json` namespace. See [Getting started](docs/getting-started.md) and [Public API](docs/public-api.md) for the supported types. -`DwgSceneReader` converts a drawing into an `IOScene.SceneDocument`, the neutral model shared with RvtIO and NwcIO. -The converter is available in `DwgIO.Scene.Adapter` and through the existing `DwgIO.Scene` API. +`DwgSceneReader` converts a drawing into an `IOScene.SceneDocument`, the neutral model shared with RvtIO and NwcIO (`DwgIO.Scene` package). ```csharp using DwgIO.Scene; @@ -158,8 +156,6 @@ 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 (with rollback if replacement fails), `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 @@ -175,10 +171,8 @@ The documentation site with the API reference is at ?`). | | `DwgSceneResult` | The `Document` (an `IOScene.SceneDocument`), `Diagnostics`, element and geometry counters, the applied `MetresPerUnit` and `UnitAssumed`. | -| `DwgSceneExport` | `SaveObj(document, objPath, options?)` writes an OBJ file with an adjacent MTL colour library; `SaveGlb(document, glbPath, options?)` writes binary glTF. Both return the conversion report; `WriteObj(scene, path)` and `WriteGlb(scene, path)` export an existing scene document. | -| `DwgSvgExporter`, `DwgSvgOptions` | Draws model space (LINE, CIRCLE, ARC, POINT) to SVG in the top view, in ACI colours, with a view box that contains every drawn entity. `WriteFile(document, path, options?)`, `Write(document, stream, options?)`. `DwgSvgOptions` holds `Scale` (pixels per drawing unit), `StrokeWidth`, `Background` and an optional `ReportDiagnostic` callback for skipped entities. | -| `DwgViewerExport` | `SaveViewer(document, htmlPath, options?, viewerOptions?)` writes a standalone interactive 3D HTML viewer (IOViewer) of the scene; `WriteViewer(scene, path, viewerOptions?)` embeds an existing scene document. | ```csharp using DwgIO.Scene; @@ -87,15 +83,16 @@ IOScene.SceneJson.Save(result.Document, "drawing.scene.json"); ``` The scene validates against the IOScene contract (`SceneDocument.Validate` reports no error) and round-trips through -IOScene JSON with its original line and point topology. Use `dwgio scene drawing.dwg drawing.scene.json --unit mm` -for a millimetre drawing when the consumer supports that topology. `DwgSceneExport` also preserves lines and points -when writing OBJ (with an adjacent MTL colour library) or GLB through the IOScene.Formats writers. - -For standalone HTML, use `dwgio drawing.dwg drawing.html` or `DwgViewerExport.SaveViewer`. DwgIO turns lines and -points into display-only triangle meshes without changing the source scene. In contrast, passing the raw scene -JSON to stock `ioviewer drawing.scene.json -o drawing.html` in IOViewer 0.3.1 warns about and skips non-triangle -instances. For example, on LibreDWG's [R2010 example drawing][dwg-example], DwgIO 0.5.0 exported 74 line and 46 point -instances. IOViewer 0.3.1 embedded no drawable instances from that JSON, while direct DwgIO HTML included all 120. +IOScene JSON with its original line and point topology. + +## CLI Exporters (`dwgio`) + +`DwgIO.Cli` bundles the exchange exporters (`DwgSceneExport` for OBJ/GLB via `IOScene.Formats`, `DwgSvgExporter` for SVG, +and `DwgViewerExport` for standalone HTML): + +- `dwgio drawing.dwg drawing.html` defaults to an AutoCAD-style 2D CAD canvas (`--mode 2d`, `--bg black|slate|light`): orthographic top view, crisp vector rendering of LINE, CIRCLE, ARC and POINT, ACI colours (white on dark backgrounds, black on light), pan/zoom, coordinate readout and entity properties inspector. +- `dwgio drawing.dwg drawing.html --mode 3d` exports the interactive 3D WebGL viewer via [IOViewer](https://github.com/IOExtend/IOViewer). +- `dwgio drawing.dwg out.obj --unit mm` and `dwgio drawing.dwg out.glb --unit mm` pass `--unit` to the scene converter. ## Diagnostics diff --git a/src/DwgIO.Cli/DwgIO.Cli.csproj b/src/DwgIO.Cli/DwgIO.Cli.csproj index a608187..6b4e844 100644 --- a/src/DwgIO.Cli/DwgIO.Cli.csproj +++ b/src/DwgIO.Cli/DwgIO.Cli.csproj @@ -6,7 +6,8 @@ true dwgio DwgIO.Cli - Command line tool that reads Autodesk DWG drawings (.dwg) without AutoCAD and writes JSON. + Command line tool that reads Autodesk DWG drawings (.dwg) without AutoCAD and exports JSON, IOScene, OBJ, GLB, SVG and standalone HTML viewers. + $(NoWarn);NU5104 @@ -15,7 +16,10 @@ - + + + diff --git a/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs b/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs new file mode 100644 index 0000000..df80a99 --- /dev/null +++ b/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs @@ -0,0 +1,1239 @@ +using System.Globalization; +using System.Net; +using System.Text; +using System.Text.Json; +using DwgIO.Model; +using DwgIO.Scene; + +namespace DwgIO.Export; + +/// +/// Generates a self-contained AutoCAD-style 2D interactive HTML viewer for decoded DWG entities. +/// +internal static class DwgCadHtmlViewer +{ + public static void Export(DwgDocument document, Stream output, DwgViewerOptions options, string lengthUnit) + { + ArgumentNullException.ThrowIfNull(document); + ArgumentNullException.ThrowIfNull(output); + + string title = string.IsNullOrWhiteSpace(options.Title) + ? System.IO.Path.GetFileName(document.Path) + : options.Title; + if (string.IsNullOrWhiteSpace(title)) + { + title = "DWG 2D Viewer"; + } + + string payloadJson = BuildPayloadJson(document, options, title, lengthUnit); + string safeJson = payloadJson.Replace(" "slate", + DwgCadTheme.Light => "light", + _ => "black", + }; + + string html = HtmlTemplate + .Replace("{{TITLE}}", WebUtility.HtmlEncode(title), StringComparison.Ordinal) + .Replace("{{THEME}}", themeAttr, StringComparison.Ordinal) + .Replace("{{PAYLOAD}}", safeJson, StringComparison.Ordinal); + + byte[] bytes = Encoding.UTF8.GetBytes(html); + output.Write(bytes); + output.Flush(); + } + + private static string BuildPayloadJson(DwgDocument document, DwgViewerOptions options, string title, string lengthUnit) + { + double minX = double.PositiveInfinity; + double minY = double.PositiveInfinity; + double maxX = double.NegativeInfinity; + double maxY = double.NegativeInfinity; + + using var ms = new MemoryStream(); + using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = false })) + { + w.WriteStartObject(); + w.WriteString("kind", "dwgio-cad2d"); + w.WriteNumber("format", 1); + w.WriteString("title", title); + w.WriteString("version", document.Version.ToString()); + w.WriteString("unit", lengthUnit); + w.WriteString("theme", options.Theme switch + { + DwgCadTheme.Slate => "slate", + DwgCadTheme.Light => "light", + _ => "black", + }); + w.WriteNumber("totalEntities", document.Entities.Count); + + w.WriteStartArray("entities"); + int drawnCount = 0; + int skippedNonFinite = 0; + foreach (var entity in document.Entities) + { + if (!options.IncludePaperSpace && !entity.IsModelSpace) + { + continue; + } + + if (entity.Kind == DwgEntityKind.Unknown || entity.Geometry is null) + { + continue; + } + + if (!entity.Geometry.All(double.IsFinite)) + { + skippedNonFinite++; + continue; + } + + if (!TryExpandBounds(entity, ref minX, ref minY, ref maxX, ref maxY)) + { + continue; + } + + drawnCount++; + w.WriteStartObject(); + w.WriteString("handle", entity.Handle.ToString("X", CultureInfo.InvariantCulture)); + w.WriteString("type", entity.TypeName); + w.WriteString("kind", entity.Kind.ToString().ToLowerInvariant()); + w.WriteNumber("colorIndex", entity.ColorIndex); + w.WriteBoolean("isAdaptiveColor", IsAdaptiveColor(entity.ColorIndex)); + w.WriteString("rgb", FormatFixedRgb(entity.ColorIndex)); + w.WriteNumber("lineTypeScale", double.IsFinite(entity.LineTypeScale) ? Math.Round(entity.LineTypeScale, 6) : 1.0); + w.WriteBoolean("modelSpace", entity.IsModelSpace); + w.WriteStartArray("geom"); + foreach (double v in entity.Geometry) + { + w.WriteNumberValue(v); + } + + w.WriteEndArray(); + w.WriteEndObject(); + } + + w.WriteEndArray(); + w.WriteNumber("drawnCount", drawnCount); + w.WriteNumber("skippedNonFinite", skippedNonFinite); + + w.WriteStartObject("bounds"); + if (minX <= maxX && minY <= maxY) + { + w.WriteBoolean("empty", false); + w.WriteNumber("minX", minX); + w.WriteNumber("minY", minY); + w.WriteNumber("maxX", maxX); + w.WriteNumber("maxY", maxY); + } + else + { + w.WriteBoolean("empty", true); + w.WriteNumber("minX", -10); + w.WriteNumber("minY", -10); + w.WriteNumber("maxX", 10); + w.WriteNumber("maxY", 10); + } + + w.WriteEndObject(); + w.WriteEndObject(); + } + + return Encoding.UTF8.GetString(ms.ToArray()); + } + + private static bool IsAdaptiveColor(int colorIndex) => colorIndex is <= 0 or 7 or >= 256; + + private static string? FormatFixedRgb(int colorIndex) + { + if (IsAdaptiveColor(colorIndex)) + { + return null; + } + + (byte r, byte g, byte b) = DwgAciPalette.RgbOf(colorIndex); + return string.Create(CultureInfo.InvariantCulture, $"#{r:X2}{g:X2}{b:X2}"); + } + + private static bool TryExpandBounds(DwgEntity entity, ref double minX, ref double minY, ref double maxX, ref double maxY) + { + switch (entity.Kind, entity.Geometry) + { + case (DwgEntityKind.Line, [var x1, var y1, _, var x2, var y2, _]): + Expand(x1, y1, ref minX, ref minY, ref maxX, ref maxY); + Expand(x2, y2, ref minX, ref minY, ref maxX, ref maxY); + return true; + case (DwgEntityKind.Circle, [var cx, var cy, _, var r]) when r > 0: + Expand(cx - r, cy - r, ref minX, ref minY, ref maxX, ref maxY); + Expand(cx + r, cy + r, ref minX, ref minY, ref maxX, ref maxY); + return true; + case (DwgEntityKind.Arc, [var cx, var cy, _, var r, var startRaw, var endRaw]) when r > 0: + var (start, span) = ArcAngles.Normalize(startRaw, endRaw); + Expand(cx + r * Math.Cos(start), cy + r * Math.Sin(start), ref minX, ref minY, ref maxX, ref maxY); + Expand(cx + r * Math.Cos(start + span), cy + r * Math.Sin(start + span), ref minX, ref minY, ref maxX, ref maxY); + for (int k = 0; k < 4; k++) + { + double angle = k * Math.PI / 2.0; + if (ArcAngles.PositiveAngle(angle - start) <= span) + { + Expand(cx + r * Math.Cos(angle), cy + r * Math.Sin(angle), ref minX, ref minY, ref maxX, ref maxY); + } + } + + return true; + case (DwgEntityKind.Point, [var x, var y, _]): + Expand(x, y, ref minX, ref minY, ref maxX, ref maxY); + return true; + default: + return false; + } + } + + private static void Expand(double x, double y, ref double minX, ref double minY, ref double maxX, ref double maxY) + { + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + private const string HtmlTemplate = """ + + + + + +{{TITLE}} — DwgIO 2D CAD + + + +
+
+
+ 2D CAD + {{TITLE}} + +
+
+ + + + + + + +
+
+
+ +
+ + + +
+
+
+
+ X: 0.000 Y: 0.000 + 100% +
+
+ + +
+
+
+ + + + +"""; +} diff --git a/src/DwgIO.Scene/Compatibility/DwgSceneExport.cs b/src/DwgIO.Cli/Export/DwgSceneExport.cs similarity index 59% rename from src/DwgIO.Scene/Compatibility/DwgSceneExport.cs rename to src/DwgIO.Cli/Export/DwgSceneExport.cs index bcbbba9..6972ae2 100644 --- a/src/DwgIO.Scene/Compatibility/DwgSceneExport.cs +++ b/src/DwgIO.Cli/Export/DwgSceneExport.cs @@ -1,38 +1,28 @@ using System.Security.Cryptography; using System.Text; using DwgIO.Output; +using DwgIO.Scene; using IOScene; using IOScene.Formats; -namespace DwgIO.Scene; +namespace DwgIO.Export; /// -/// 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. +/// Exports a drawing to the mesh exchange formats written by : Wavefront OBJ +/// with an adjacent MTL library and binary glTF (GLB). Both go through the adapter, +/// preserving colours, line/point topologies and drawing-unit scaling. /// 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. + /// Converts the drawing and writes it to a Wavefront OBJ file with an adjacent MTL library. public static DwgSceneResult SaveObj(DwgDocument document, string objPath, DwgSceneOptions? options = null) { - var result = DwgSceneReader.Read(document, OptionsFor(document, objPath, options)); + var result = DwgSceneReader.Read(document, OptionsFor(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 pair is replaced so that a - /// failure at any step leaves the previous pair untouched: the old MTL is first renamed aside, the new - /// MTL moves in, and the OBJ — which names that MTL in its mtllib — moves in last, after which - /// the old MTL backup is dropped. - /// The scene to export. - /// Path to the OBJ file. + /// Writes a scene to a Wavefront OBJ file with an adjacent MTL library atomically. public static void WriteObj(SceneDocument scene, string objPath) { ArgumentNullException.ThrowIfNull(scene); @@ -60,16 +50,14 @@ public static void WriteObj(SceneDocument scene, string objPath) { objTemp = AtomicOutput.CreateTemporary(fullPath); mtlTemp = AtomicOutput.CreateTemporary(mtlPath); - // Both temporary files are written first; the OBJ names the MTL by its stable name. using (var objStream = new FileStream(objTemp, FileMode.Truncate, FileAccess.Write, FileShare.None)) - using (var objWriter = new StreamWriter(objStream, new System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: false))) + using (var objWriter = new StreamWriter(objStream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false))) using (var mtlStream = new FileStream(mtlTemp, FileMode.Truncate, FileAccess.Write, FileShare.None)) - using (var mtlWriter = new StreamWriter(mtlStream, new System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: false))) + using (var mtlWriter = new StreamWriter(mtlStream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false))) { ObjSceneWriter.Write(scene, objWriter, mtlWriter, mtlName); } - // The old MTL steps aside first, so it can step back in when either move fails. if (File.Exists(mtlPath)) { mtlBackup = Path.Combine(directory, $".dwgio-{Guid.NewGuid():N}.bak"); @@ -86,7 +74,6 @@ public static void WriteObj(SceneDocument scene, string objPath) } catch { - // Restore the previous pair: the old MTL comes back, and a fresh export leaves no MTL behind. if (mtlBackup is not null && File.Exists(mtlBackup)) { File.Move(mtlBackup, mtlPath, overwrite: true); @@ -106,38 +93,32 @@ public static void WriteObj(SceneDocument scene, string objPath) } /// 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)); + var result = DwgSceneReader.Read(document, OptionsFor(glbPath, options)); WriteGlb(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); AtomicOutput.Write(glbPath, stream => GlbSceneWriter.Write(scene, stream)); } - private static DwgSceneOptions OptionsFor(DwgDocument document, string path, DwgSceneOptions? options) + private static DwgSceneOptions OptionsFor(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), + ReadProgress = options?.ReadProgress, }; } } diff --git a/src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs b/src/DwgIO.Cli/Export/DwgSvgExporter.cs similarity index 89% rename from src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs rename to src/DwgIO.Cli/Export/DwgSvgExporter.cs index f968dcf..45c67a7 100644 --- a/src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs +++ b/src/DwgIO.Cli/Export/DwgSvgExporter.cs @@ -1,19 +1,16 @@ using System.Globalization; using System.Xml; -using DwgIO.Output; using DwgIO.Model; +using DwgIO.Output; +using DwgIO.Scene; -namespace DwgIO.Scene; +namespace DwgIO.Export; /// /// 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 . @@ -52,7 +49,6 @@ public static void Write(DwgDocument document, XmlWriter writer, DwgSvgOptions? var shapes = Collect(document, options); (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); if (!IsUsable(minX - margin, minY - margin, width + 2 * margin, height + 2 * margin)) { @@ -105,8 +101,6 @@ public static void Write(DwgDocument document, XmlWriter writer, DwgSvgOptions? 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", @@ -115,10 +109,10 @@ public static void Write(DwgDocument document, XmlWriter writer, DwgSvgOptions? writer.WriteAttributeString("stroke", stroke); writer.WriteEndElement(); break; - case SvgPoint: + case SvgPoint point: writer.WriteStartElement("circle"); - writer.WriteAttributeString("cx", Num(((SvgPoint)shape).X)); - writer.WriteAttributeString("cy", Num(((SvgPoint)shape).Y)); + writer.WriteAttributeString("cx", Num(point.X)); + writer.WriteAttributeString("cy", Num(point.Y)); writer.WriteAttributeString("r", Num(markerRadius)); writer.WriteAttributeString("fill", stroke); writer.WriteAttributeString("stroke", "none"); @@ -138,7 +132,6 @@ private sealed record SvgLine(double X1, double Y1, double X2, double Y2, int Co 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); @@ -157,7 +150,7 @@ private static List Collect(DwgDocument document, DwgSvgOptions option switch (entity.Kind, entity.Geometry) { - case (DwgEntityKind.Line, [var x1, var y1, var z1, var x2, var y2, var z2]): + case (DwgEntityKind.Line, [var x1, var y1, _, var x2, var y2, _]): if (IsUsable(x1 * scale, y1 * scale, x2 * scale, y2 * scale)) { shapes.Add(new SvgLine(x1 * scale, -y1 * scale, x2 * scale, -y2 * scale, entity.ColorIndex)); @@ -168,7 +161,7 @@ private static List Collect(DwgDocument document, DwgSvgOptions option } break; - case (DwgEntityKind.Circle, [var cx, var cy, var cz, var r]): + case (DwgEntityKind.Circle, [var cx, var cy, _, var r]): if (IsUsable((Math.Abs(cx) + r) * scale, (Math.Abs(cy) + r) * scale) && r > 0) { shapes.Add(new SvgCircle(cx * scale, -cy * scale, r * scale, entity.ColorIndex)); @@ -243,8 +236,6 @@ private static (double MinX, double MinY, double Width, double Height) ViewBox(L (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; @@ -279,8 +270,6 @@ void Expand(double x, double 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) { @@ -295,7 +284,7 @@ private static string Num(double value) { if (value == 0.0) { - value = 0.0; // normalise -0 + value = 0.0; } return value.ToString("0.######", CultureInfo.InvariantCulture); diff --git a/src/DwgIO.Scene/Compatibility/DwgSvgOptions.cs b/src/DwgIO.Cli/Export/DwgSvgOptions.cs similarity index 97% rename from src/DwgIO.Scene/Compatibility/DwgSvgOptions.cs rename to src/DwgIO.Cli/Export/DwgSvgOptions.cs index 15ddff7..4da955d 100644 --- a/src/DwgIO.Scene/Compatibility/DwgSvgOptions.cs +++ b/src/DwgIO.Cli/Export/DwgSvgOptions.cs @@ -1,4 +1,4 @@ -namespace DwgIO.Scene; +namespace DwgIO.Export; /// Options of the SVG export of model space. public sealed class DwgSvgOptions diff --git a/src/DwgIO.Cli/Export/DwgViewerExport.cs b/src/DwgIO.Cli/Export/DwgViewerExport.cs new file mode 100644 index 0000000..bfccaa1 --- /dev/null +++ b/src/DwgIO.Cli/Export/DwgViewerExport.cs @@ -0,0 +1,90 @@ +using DwgIO.Output; +using DwgIO.Scene; +using IOScene; +using IOViewer.Exporters; + +namespace DwgIO.Export; + +/// +/// Exports a drawing as a standalone interactive HTML viewer: either an AutoCAD-style 2D vector canvas +/// (, default) or a 3D WebGL viewer generated by +/// IOViewer (). +/// +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 mode and display options; null defaults to . + /// The conversion report. is the IOScene document for the drawing. + public static DwgSceneResult SaveViewer( + DwgDocument document, + string htmlPath, + DwgSceneOptions? options = null, + DwgViewerOptions? viewerOptions = null) + { + ArgumentNullException.ThrowIfNull(document); + ArgumentException.ThrowIfNullOrEmpty(htmlPath); + viewerOptions ??= new DwgViewerOptions(); + var sceneOptions = ViewerOptionsFor(htmlPath, options); + var result = DwgSceneReader.Read(document, sceneOptions); + + if (viewerOptions.Mode == DwgViewerMode.Scene3D) + { + var html3dOptions = viewerOptions.Scene3DOptions; + if (html3dOptions is null) + { + html3dOptions = new HtmlViewerOptions + { + Title = string.IsNullOrWhiteSpace(viewerOptions.Title) ? result.Document.Title : viewerOptions.Title, + }; + } + else if (string.IsNullOrEmpty(html3dOptions.Title)) + { + html3dOptions.Title = string.IsNullOrWhiteSpace(viewerOptions.Title) ? result.Document.Title : viewerOptions.Title; + } + + WriteViewer(result.Document, htmlPath, html3dOptions); + } + else + { + AtomicOutput.Write(htmlPath, stream => DwgCadHtmlViewer.Export(document, stream, viewerOptions, sceneOptions.LengthUnit)); + } + + return result; + } + + /// Writes a 3D IOViewer HTML file from an existing . + public static void WriteViewer(SceneDocument scene, string htmlPath, HtmlViewerOptions? viewerOptions = null) + { + ArgumentNullException.ThrowIfNull(scene); + ArgumentException.ThrowIfNullOrEmpty(htmlPath); + if (viewerOptions is null) + { + viewerOptions = new HtmlViewerOptions { Title = scene.Title }; + } + else if (string.IsNullOrEmpty(viewerOptions.Title)) + { + viewerOptions.Title = scene.Title; + } + + var drawableScene = ViewerMeshGeometry.Adapt(scene); + AtomicOutput.Write(htmlPath, stream => HtmlViewerExporter.Export(drawableScene, stream, viewerOptions)); + } + + private static DwgSceneOptions ViewerOptionsFor(string path, DwgSceneOptions? options) + { + if (options?.ModelKey is { Length: > 0 }) + { + return options; + } + + return new DwgSceneOptions + { + LengthUnit = options?.LengthUnit ?? "m", + ModelKey = Path.GetFileName(path), + ReadProgress = options?.ReadProgress, + }; + } +} diff --git a/src/DwgIO.Cli/Export/DwgViewerOptions.cs b/src/DwgIO.Cli/Export/DwgViewerOptions.cs new file mode 100644 index 0000000..295c8f8 --- /dev/null +++ b/src/DwgIO.Cli/Export/DwgViewerOptions.cs @@ -0,0 +1,45 @@ +using IOViewer.Exporters; + +namespace DwgIO.Export; + +/// Presentation mode for standalone HTML viewer exports. +public enum DwgViewerMode +{ + /// AutoCAD-style 2D top-down vector canvas viewer (default for DWG drawings). + Cad2D, + + /// Interactive 3D WebGL viewer generated by IOViewer. + Scene3D, +} + +/// Initial canvas colour theme for the 2D AutoCAD HTML viewer. +public enum DwgCadTheme +{ + /// Classic AutoCAD model-space black (#000000); ACI 7 renders white. + Black, + + /// Modern AutoCAD dark slate (#212830); ACI 7 renders white. + Slate, + + /// Paper / light background (#FFFFFF); ACI 7 renders black. + Light, +} + +/// Options for . +public sealed class DwgViewerOptions +{ + /// Viewer mode: (default) or . + public DwgViewerMode Mode { get; set; } = DwgViewerMode.Cad2D; + + /// Document title shown in the browser tab and header; defaults to the file or scene title. + public string? Title { get; set; } + + /// Initial colour theme in mode (default: ). + public DwgCadTheme Theme { get; set; } = DwgCadTheme.Black; + + /// Include paper-space entities alongside model space in mode (default: false). + public bool IncludePaperSpace { get; set; } + + /// Options forwarded to IOViewer when is . + public HtmlViewerOptions? Scene3DOptions { get; set; } +} diff --git a/src/DwgIO.Scene/Compatibility/ViewerMeshGeometry.cs b/src/DwgIO.Cli/Export/ViewerMeshGeometry.cs similarity index 96% rename from src/DwgIO.Scene/Compatibility/ViewerMeshGeometry.cs rename to src/DwgIO.Cli/Export/ViewerMeshGeometry.cs index 355ef95..eac28a6 100644 --- a/src/DwgIO.Scene/Compatibility/ViewerMeshGeometry.cs +++ b/src/DwgIO.Cli/Export/ViewerMeshGeometry.cs @@ -1,10 +1,10 @@ using IOScene; -namespace DwgIO.Scene; +namespace DwgIO.Export; internal static class ViewerMeshGeometry { - // shortcut: IOViewer 0.3.1 draws triangles only; use thin display meshes until it supports lines and points. + // IOViewer 0.4.2 draws triangles and point clouds; convert lines and drawing points to display meshes in Scene3D mode. public static SceneDocument Adapt(SceneDocument scene) { if (!scene.Geometries.Any(g => g.Topology is SceneTopology.Lines or SceneTopology.Points)) diff --git a/src/DwgIO.Cli/Program.cs b/src/DwgIO.Cli/Program.cs index e4e1811..8e16b47 100644 --- a/src/DwgIO.Cli/Program.cs +++ b/src/DwgIO.Cli/Program.cs @@ -2,10 +2,10 @@ using System.Reflection; using System.Text; using System.Text.Json; -using DwgIO; -using DwgIO.Output; +using DwgIO.Export; using DwgIO.Json; using DwgIO.Model; +using DwgIO.Output; using DwgIO.Scene; using IOScene; @@ -20,13 +20,6 @@ internal static class Program /// Formats a bare number, invariantly. internal static string Plain(double value) => value.ToString(CultureInfo.InvariantCulture); - private const int ExitOk = 0; - private const int ExitUsage = 1; - private const int ExitFileNotFound = 2; - private const int ExitUnsupportedVersion = 3; - private const int ExitParseError = 4; - private const int ExitNoPreview = 5; - private static int Main(string[] args) => Run(args, Console.Out, Console.Error); /// Runs one command. Internal for the CLI tests. @@ -35,7 +28,7 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) if (args.Length == 0) { PrintUsage(output); - return ExitUsage; + return DwgExitCodes.Usage; } try @@ -54,47 +47,52 @@ string option when option.StartsWith('-') => UnknownOption(option, output, error _ => Export(args, output, error), }; } + catch (UsageException ex) + { + error.WriteLine($"error: {ex.Message}"); + return DwgExitCodes.Usage; + } catch (FileNotFoundException ex) { error.WriteLine($"error: {ex.Message}"); - return ExitFileNotFound; + return DwgExitCodes.FileNotFound; } catch (DwgUnsupportedVersionException ex) { error.WriteLine($"error: {ex.Message}"); - return ExitUnsupportedVersion; + return DwgExitCodes.UnsupportedVersion; } catch (DwgException ex) { error.WriteLine($"error: {ex.Message}"); - return ExitParseError; + return DwgExitCodes.ParseError; } catch (Exception ex) { error.WriteLine($"unexpected error: {ex.Message}"); - return ExitParseError; + return DwgExitCodes.ParseError; } } private static int PrintVersion(TextWriter output) { - string version = typeof(Program).Assembly.GetCustomAttribute() + string version = typeof(Program).Assembly.GetCustomAttribute() ?.InformationalVersion.Split('+')[0] ?? "unknown"; output.WriteLine(version); - return ExitOk; + return DwgExitCodes.Ok; } private static int PrintHelp(TextWriter output) { PrintUsage(output); - return ExitOk; + return DwgExitCodes.Ok; } private static int UnknownOption(string option, TextWriter output, TextWriter error) { error.WriteLine($"error: unknown option {option}."); PrintUsage(output); - return ExitUsage; + return DwgExitCodes.Usage; } private static void PrintUsage(TextWriter output) @@ -104,9 +102,10 @@ private static void PrintUsage(TextWriter output) Usage: dwgio inspect Print version + section table - dwgio Export metadata, section catalog and entities to JSON, + dwgio [--unit u] [--mode 2d|3d] [--bg black|slate|light] + Export metadata, section catalog and entities to JSON, or the scene to OBJ (.obj), GLB (.glb) or a standalone - interactive 3D HTML viewer (.html) + interactive HTML viewer (.html; 2D AutoCAD mode by default) 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 @@ -129,7 +128,7 @@ private static int Inspect(string[] args, TextWriter output, TextWriter error) if (args.Length != 2) { PrintUsage(output); - return ExitUsage; + return DwgExitCodes.Usage; } var doc = DwgDocument.Open(args[1]); @@ -233,7 +232,7 @@ internal static int InspectDocument(DwgDocument doc, TextWriter output) if (doc.Sections.Count == 0) { output.WriteLine("(section map not read)"); - return ExitOk; + return DwgExitCodes.Ok; } output.WriteLine($"{"Name",-28} {"Size",12} {"Pages",6} {"Compr",6} {"Enc",4} Id"); @@ -243,23 +242,98 @@ internal static int InspectDocument(DwgDocument doc, TextWriter output) output.WriteLine($"{name,-28} {Count(s.Size),12} {s.PageCount,6} {s.Compression,6} {s.Encryption,4} {s.SectionId}"); } - return ExitOk; + return DwgExitCodes.Ok; } private static int Export(string[] args, TextWriter output, TextWriter error) { - if (args.Length != 2) + string? unit = null; + DwgViewerMode? mode = null; + DwgCadTheme? theme = null; + var positional = new List(2); + + for (int i = 0; i < args.Length; i++) + { + switch (args[i]) + { + case "--unit": + if (i + 1 >= args.Length) + { + error.WriteLine("error: --unit needs a value (mm, cm, m, ft or in)."); + return DwgExitCodes.Usage; + } + + unit = args[++i]; + if (!DwgSceneReader.IsSupportedUnit(unit)) + { + error.WriteLine($"error: unknown length unit '{unit}'. Use mm, cm, m, ft or in."); + return DwgExitCodes.Usage; + } + + break; + case "--mode": + if (i + 1 >= args.Length) + { + error.WriteLine("error: --mode needs a value (2d or 3d)."); + return DwgExitCodes.Usage; + } + + mode = args[++i].ToLowerInvariant() switch + { + "2d" => DwgViewerMode.Cad2D, + "3d" => DwgViewerMode.Scene3D, + var bad => throw new UsageException($"unknown viewer mode '{bad}'. Use 2d or 3d."), + }; + break; + case "--bg": + if (i + 1 >= args.Length) + { + error.WriteLine("error: --bg needs a value (black, slate or light)."); + return DwgExitCodes.Usage; + } + + theme = args[++i].ToLowerInvariant() switch + { + "black" => DwgCadTheme.Black, + "slate" => DwgCadTheme.Slate, + "light" => DwgCadTheme.Light, + var bad => throw new UsageException($"unknown background theme '{bad}'. Use black, slate or light."), + }; + break; + case string option when option.StartsWith('-') && !(option == "-" && positional.Count == 1): + return UnknownOption(option, output, error); + default: + positional.Add(args[i]); + break; + } + } + + if (positional.Count != 2) { PrintUsage(output); - return ExitUsage; + return DwgExitCodes.Usage; + } + + string source = positional[0]; + string target = positional[1]; + if (!CheckOutputDistinct(source, target, error)) + { + return DwgExitCodes.Usage; } - var doc = DwgDocument.Open(args[0]); - return ExportDocument(doc, args[1], output, error); + var doc = DwgDocument.Open(source); + return ExportDocument(doc, target, output, error, unit, mode, theme); } /// Exports an opened document to a target path, where - means standard output. Internal for the CLI tests. - internal static int ExportDocument(DwgDocument doc, string target, TextWriter output, TextWriter error) + internal static int ExportDocument( + DwgDocument doc, + string target, + TextWriter output, + TextWriter error, + string? unit = null, + DwgViewerMode? mode = null, + DwgCadTheme? theme = null) { if (target == "-") { @@ -267,22 +341,41 @@ internal static int ExportDocument(DwgDocument doc, string target, TextWriter ou using var json = new MemoryStream(); DwgJsonExporter.Write(doc, json, DwgJsonExportOptions.Default); output.Write(Encoding.UTF8.GetString(json.ToArray())); - return ExitOk; + return DwgExitCodes.Ok; } + string? inputPath = doc.SourcePath ?? (File.Exists(doc.Path) ? doc.Path : null); + if (inputPath is not null && !CheckOutputDistinct(inputPath, target, error)) + { + return DwgExitCodes.Usage; + } + + var sceneOptions = unit is null ? null : new DwgSceneOptions { LengthUnit = unit }; + if (Path.GetExtension(target).Equals(".obj", StringComparison.OrdinalIgnoreCase)) { - var objResult = DwgSceneExport.SaveObj(doc, target); + string mtlTarget = Path.ChangeExtension(Path.GetFullPath(target), ".mtl"); + if (inputPath is not null && !CheckOutputDistinct(inputPath, mtlTarget, error)) + { + return DwgExitCodes.Usage; + } + + var objResult = DwgSceneExport.SaveObj(doc, target, sceneOptions); output.WriteLine($"{doc.Version} elements={objResult.ElementCount} ({objResult.ElementsWithGeometry} with geometry) -> {target}"); } else if (Path.GetExtension(target).Equals(".glb", StringComparison.OrdinalIgnoreCase)) { - var glbResult = DwgSceneExport.SaveGlb(doc, target); + var glbResult = DwgSceneExport.SaveGlb(doc, target, sceneOptions); output.WriteLine($"{doc.Version} elements={glbResult.ElementCount} ({glbResult.ElementsWithGeometry} with geometry) -> {target}"); } else if (Path.GetExtension(target).Equals(".html", StringComparison.OrdinalIgnoreCase)) { - var htmlResult = DwgViewerExport.SaveViewer(doc, target); + var viewerOptions = new DwgViewerOptions + { + Mode = mode ?? DwgViewerMode.Cad2D, + Theme = theme ?? DwgCadTheme.Black, + }; + var htmlResult = DwgViewerExport.SaveViewer(doc, target, sceneOptions, viewerOptions); output.WriteLine($"{doc.Version} elements={htmlResult.ElementCount} ({htmlResult.ElementsWithGeometry} with geometry) -> {target}"); } else @@ -291,7 +384,7 @@ internal static int ExportDocument(DwgDocument doc, string target, TextWriter ou output.WriteLine($"{doc.Version} sections={doc.Sections.Count} -> {target}"); } - return ExitOk; + return DwgExitCodes.Ok; } private static int Extract(string[] args, TextWriter output, TextWriter error) @@ -299,14 +392,19 @@ private static int Extract(string[] args, TextWriter output, TextWriter error) if (args.Length != 4) { PrintUsage(output); - return ExitUsage; + return DwgExitCodes.Usage; + } + + if (!CheckOutputDistinct(args[1], args[3], error)) + { + return DwgExitCodes.Usage; } var doc = DwgDocument.Open(args[1]); var bytes = doc.ReadSection(args[2]); - File.WriteAllBytes(args[3], bytes); + AtomicOutput.Write(args[3], stream => stream.Write(bytes)); output.WriteLine($"{args[2]}: {Count(bytes.Length)} bytes -> {args[3]}"); - return ExitOk; + return DwgExitCodes.Ok; } private static int Svg(string[] args, TextWriter output, TextWriter error) @@ -317,14 +415,18 @@ private static int Svg(string[] args, TextWriter output, TextWriter error) { if (args[i] == "--scale") { - if (i + 1 >= args.Length || !double.TryParse(args[i + 1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out scale) || !double.IsFinite(scale) || scale <= 0) + if (i + 1 >= args.Length || !double.TryParse(args[i + 1], NumberStyles.Float, CultureInfo.InvariantCulture, out scale) || !double.IsFinite(scale) || scale <= 0) { error.WriteLine("error: --scale needs a positive number of pixels per drawing unit."); - return ExitUsage; + return DwgExitCodes.Usage; } i++; } + else if (args[i].StartsWith('-')) + { + return UnknownOption(args[i], output, error); + } else { positional.Add(args[i]); @@ -334,13 +436,18 @@ private static int Svg(string[] args, TextWriter output, TextWriter error) if (positional.Count != 2) { PrintUsage(output); - return ExitUsage; + return DwgExitCodes.Usage; + } + + if (!CheckOutputDistinct(positional[0], positional[1], error)) + { + return DwgExitCodes.Usage; } var doc = DwgDocument.Open(positional[0]); DwgSvgExporter.WriteFile(doc, positional[1], new DwgSvgOptions { Scale = scale }); output.WriteLine($"{doc.Version} entities={Count(doc.Entities.Count)} -> {positional[1]}"); - return ExitOk; + return DwgExitCodes.Ok; } private static int Scene(string[] args, TextWriter output, TextWriter error) @@ -354,11 +461,15 @@ private static int Scene(string[] args, TextWriter output, TextWriter error) if (i + 1 >= args.Length) { error.WriteLine("error: --unit needs a value (mm, cm, m, ft or in)."); - return ExitUsage; + return DwgExitCodes.Usage; } unit = args[++i]; } + else if (args[i].StartsWith('-')) + { + return UnknownOption(args[i], output, error); + } else { positional.Add(args[i]); @@ -368,7 +479,12 @@ private static int Scene(string[] args, TextWriter output, TextWriter error) if (positional.Count != 2) { PrintUsage(output); - return ExitUsage; + return DwgExitCodes.Usage; + } + + if (!CheckOutputDistinct(positional[0], positional[1], error)) + { + return DwgExitCodes.Usage; } var options = new DwgSceneOptions(); @@ -377,7 +493,7 @@ private static int Scene(string[] args, TextWriter output, TextWriter error) if (!DwgSceneReader.IsSupportedUnit(unit)) { error.WriteLine($"error: unknown length unit '{unit}'. Use mm, cm, m, ft or in."); - return ExitUsage; + return DwgExitCodes.Usage; } options.LengthUnit = unit; @@ -397,7 +513,7 @@ private static int Scene(string[] args, TextWriter output, TextWriter error) output.WriteLine($" ... and {Count(result.Diagnostics.Count - 5)} more"); } - return ExitOk; + return DwgExitCodes.Ok; } private static int Preview(string[] args, TextWriter output, TextWriter error) @@ -405,7 +521,12 @@ private static int Preview(string[] args, TextWriter output, TextWriter error) if (args.Length != 3) { PrintUsage(output); - return ExitUsage; + return DwgExitCodes.Usage; + } + + if (!CheckOutputDistinct(args[1], args[2], error)) + { + return DwgExitCodes.Usage; } var doc = DwgDocument.Open(args[1]); @@ -418,25 +539,31 @@ internal static int PreviewDocument(DwgDocument doc, string requested, TextWrite if (doc.PreviewReadError is not null) { error.WriteLine($"error: {doc.PreviewReadError}"); - return ExitParseError; + return DwgExitCodes.ParseError; } var preview = doc.Preview; if (preview is null || !preview.HasImage) { error.WriteLine("error: this drawing has no thumbnail preview."); - return ExitNoPreview; + return DwgExitCodes.NoPreview; } var (target, warning) = ResolvePreviewTarget(preview.ImageKind, requested); + string? inputPath = doc.SourcePath ?? (File.Exists(doc.Path) ? doc.Path : null); + if (inputPath is not null && !CheckOutputDistinct(inputPath, target, error)) + { + return DwgExitCodes.Usage; + } + if (warning is not null) { error.WriteLine(warning); } - File.WriteAllBytes(target, preview.ImageBytes); + AtomicOutput.Write(target, stream => stream.Write(preview.ImageBytes)); output.WriteLine($"Preview: {preview.ImageKind} {Count(preview.ImageBytes.Length)} bytes -> {target}"); - return ExitOk; + return DwgExitCodes.Ok; } /// Chooses the output path for a preview: the kind's extension is added when the path has none, and @@ -478,7 +605,7 @@ private static int Entities(string[] args, TextWriter output, TextWriter error) if (i + 1 >= args.Length) { error.WriteLine("error: --type needs a comma-separated list of type names (e.g. LINE,CIRCLE)."); - return ExitUsage; + return DwgExitCodes.Usage; } types = args[++i]; @@ -492,7 +619,7 @@ private static int Entities(string[] args, TextWriter output, TextWriter error) if (file is not null) { error.WriteLine($"error: unexpected argument '{args[i]}'."); - return ExitUsage; + return DwgExitCodes.Usage; } file = args[i]; @@ -515,7 +642,7 @@ private static int Entities(string[] args, TextWriter output, TextWriter error) if (!DwgObjectTypes.KnownNames.Contains(trimmed)) { error.WriteLine($"error: unknown type '{trimmed}'. Known types include LINE, CIRCLE, ARC, POINT, TEXT and MTEXT."); - return ExitUsage; + return DwgExitCodes.Usage; } filter.Add(trimmed); @@ -524,14 +651,14 @@ private static int Entities(string[] args, TextWriter output, TextWriter error) if (filter.Count == 0) { error.WriteLine("error: --type needs at least one type name."); - return ExitUsage; + return DwgExitCodes.Usage; } } if (file is null) { PrintUsage(output); - return ExitUsage; + return DwgExitCodes.Usage; } var doc = DwgDocument.Open(file); @@ -559,7 +686,7 @@ internal static int EntitiesDocument(DwgDocument document, bool json, HashSet entities) @@ -601,4 +728,53 @@ private static void WriteEntitiesJson(TextWriter output, IEnumerable output.Write(Encoding.UTF8.GetString(json.ToArray())); } + + private static bool CheckOutputDistinct(string inputPath, string outputPath, TextWriter error) + { + if (outputPath == "-") + { + return true; + } + + if (PathsReferToSameFile(inputPath, outputPath)) + { + error.WriteLine($"error: output path '{outputPath}' must differ from the input file '{inputPath}'."); + return false; + } + + return true; + } + + private static bool PathsReferToSameFile(string a, string b) + { + StringComparison comparison = OperatingSystem.IsWindows() || OperatingSystem.IsMacOS() + ? StringComparison.OrdinalIgnoreCase + : StringComparison.Ordinal; + string fullA = ResolvePath(a); + string fullB = ResolvePath(b); + return string.Equals(fullA, fullB, comparison); + } + + private static string ResolvePath(string path) + { + string full = Path.GetFullPath(path); + try + { + var info = new FileInfo(full); + if (info.LinkTarget is not null && info.ResolveLinkTarget(returnFinalTarget: true) is { } target) + { + return target.FullName; + } + } + catch (IOException) + { + } + catch (UnauthorizedAccessException) + { + } + + return full; + } + + private sealed class UsageException(string message) : DwgException(message); } diff --git a/src/DwgIO.Scene.Adapter/DwgIO.Scene.Adapter.csproj b/src/DwgIO.Scene.Adapter/DwgIO.Scene.Adapter.csproj deleted file mode 100644 index e1c56ab..0000000 --- a/src/DwgIO.Scene.Adapter/DwgIO.Scene.Adapter.csproj +++ /dev/null @@ -1,27 +0,0 @@ - - - - Converts a DWG drawing read by DwgIO to an IOScene document. - dwg;autocad;cad;ioscene - - $(NoWarn);NU5104 - true - - - - false - - - - - - - - - - - - - - - diff --git a/src/DwgIO.Scene/Compatibility/DwgViewerExport.cs b/src/DwgIO.Scene/Compatibility/DwgViewerExport.cs deleted file mode 100644 index dc16fc1..0000000 --- a/src/DwgIO.Scene/Compatibility/DwgViewerExport.cs +++ /dev/null @@ -1,67 +0,0 @@ -using IOViewer.Exporters; -using DwgIO.Output; -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) - { - viewerOptions = new HtmlViewerOptions { Title = scene.Title }; - } - else if (string.IsNullOrEmpty(viewerOptions.Title)) - { - viewerOptions.Title = scene.Title; - } - - var drawableScene = ViewerMeshGeometry.Adapt(scene); - AtomicOutput.Write(htmlPath, stream => HtmlViewerExporter.Export(drawableScene, stream, 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/src/DwgIO.Scene/DwgIO.Scene.csproj b/src/DwgIO.Scene/DwgIO.Scene.csproj index a5d8f87..c54318e 100644 --- a/src/DwgIO.Scene/DwgIO.Scene.csproj +++ b/src/DwgIO.Scene/DwgIO.Scene.csproj @@ -1,8 +1,11 @@ - Preserves the DwgIO scene API and writes DWG drawings as OBJ, GLB, SVG and standalone HTML. - dwg;autocad;cad;ioscene;export + true + DwgIO.Scene + Converts a DWG drawing read by DwgIO into an IOScene scene document. + dwg;autocad;cad;ioscene;scene + $(NoWarn);NU5104 true @@ -11,20 +14,14 @@ false - - - - - - - - - + + + + diff --git a/src/DwgIO.Scene.Adapter/DwgSceneOptions.cs b/src/DwgIO.Scene/DwgSceneOptions.cs similarity index 78% rename from src/DwgIO.Scene.Adapter/DwgSceneOptions.cs rename to src/DwgIO.Scene/DwgSceneOptions.cs index 9a00f22..4b69965 100644 --- a/src/DwgIO.Scene.Adapter/DwgSceneOptions.cs +++ b/src/DwgIO.Scene/DwgSceneOptions.cs @@ -18,4 +18,10 @@ public sealed class DwgSceneOptions /// is read, which has no file name. /// public string? ModelKey { get; set; } + + /// + /// Receives file-read progress when or + /// opens the drawing. + /// + public IProgress? ReadProgress { get; set; } } diff --git a/src/DwgIO.Scene.Adapter/DwgSceneReader.cs b/src/DwgIO.Scene/DwgSceneReader.cs similarity index 85% rename from src/DwgIO.Scene.Adapter/DwgSceneReader.cs rename to src/DwgIO.Scene/DwgSceneReader.cs index 01917f8..781725a 100644 --- a/src/DwgIO.Scene.Adapter/DwgSceneReader.cs +++ b/src/DwgIO.Scene/DwgSceneReader.cs @@ -2,8 +2,8 @@ using System.Reflection; using DwgIO.Model; using IOScene; -using Vector3d = IOScene.Vector3d; using RgbaColor = IOScene.RgbaColor; +using Vector3d = IOScene.Vector3d; namespace DwgIO.Scene; @@ -34,7 +34,42 @@ public static class DwgSceneReader public static DwgSceneResult Read(string path, DwgSceneOptions? options = null) { ArgumentException.ThrowIfNullOrEmpty(path); - return Convert(DwgDocument.Open(path), options?.ModelKey ?? Path.GetFileName(path), path, options ?? new DwgSceneOptions()); + var resolved = options ?? new DwgSceneOptions(); + string key = resolved.ModelKey is { Length: > 0 } explicitKey ? explicitKey : Path.GetFileName(path); + if (resolved.ModelKey is { Length: 0 }) + { + throw new ArgumentException("DwgSceneOptions.ModelKey must not be empty; leave it null to use the file name.", nameof(options)); + } + + var readerOptions = new DwgReaderOptions + { + ReleaseSectionBuffers = true, + Progress = resolved.ReadProgress, + }; + return Convert(DwgDocument.Open(path, readerOptions), key, path, resolved); + } + + /// Reads a drawing from without closing it and converts it. + /// Readable stream positioned at the start of the DWG bytes. + /// Optional fallback document name when is not set. + /// Conversion options with (or non-empty ). + /// The scene with a report of the conversion. + public static DwgSceneResult Read(Stream stream, string? documentName = null, DwgSceneOptions? options = null) + { + ArgumentNullException.ThrowIfNull(stream); + var resolved = options ?? new DwgSceneOptions(); + string? key = resolved.ModelKey ?? documentName; + if (string.IsNullOrEmpty(key)) + { + throw new ArgumentException("DwgSceneOptions.ModelKey or documentName must not be empty when reading a stream.", nameof(options)); + } + + var readerOptions = new DwgReaderOptions + { + ReleaseSectionBuffers = true, + Progress = resolved.ReadProgress, + }; + return Convert(DwgDocument.Open(stream, documentName ?? key, readerOptions), key, null, resolved); } /// @@ -55,7 +90,7 @@ public static DwgSceneResult Read(DwgDocument document, DwgSceneOptions options) throw new ArgumentException("DwgSceneOptions.ModelKey must not be empty; a document converted from memory has no file name.", nameof(options)); } - return Convert(document, options.ModelKey, null, options); + return Convert(document, options.ModelKey, document.SourcePath, options); } private static DwgSceneResult Convert(DwgDocument document, string key, string? path, DwgSceneOptions options) diff --git a/src/DwgIO.Scene.Adapter/DwgSceneResult.cs b/src/DwgIO.Scene/DwgSceneResult.cs similarity index 100% rename from src/DwgIO.Scene.Adapter/DwgSceneResult.cs rename to src/DwgIO.Scene/DwgSceneResult.cs diff --git a/src/DwgIO.Scene/TypeForwarders.cs b/src/DwgIO.Scene/TypeForwarders.cs deleted file mode 100644 index ae3c119..0000000 --- a/src/DwgIO.Scene/TypeForwarders.cs +++ /dev/null @@ -1,6 +0,0 @@ -using System.Runtime.CompilerServices; -using DwgIO.Scene; - -[assembly: TypeForwardedTo(typeof(DwgSceneReader))] -[assembly: TypeForwardedTo(typeof(DwgSceneOptions))] -[assembly: TypeForwardedTo(typeof(DwgSceneResult))] diff --git a/src/DwgIO/Compatibility/DwgDocument.Compatibility.cs b/src/DwgIO/Compatibility/DwgDocument.Compatibility.cs new file mode 100644 index 0000000..dea7a2c --- /dev/null +++ b/src/DwgIO/Compatibility/DwgDocument.Compatibility.cs @@ -0,0 +1,13 @@ +using DwgIO.Json; + +namespace DwgIO; + +public sealed partial class DwgDocument +{ + /// Writes this document as JSON to atomically. + public void SaveJson(string path, DwgJsonExportOptions? options = null) + { + ArgumentException.ThrowIfNullOrEmpty(path); + DwgJsonExporter.WriteFile(this, path, options ?? DwgJsonExportOptions.Default); + } +} diff --git a/src/DwgIO/DiagnosticSink.cs b/src/DwgIO/DiagnosticSink.cs new file mode 100644 index 0000000..a3860f0 --- /dev/null +++ b/src/DwgIO/DiagnosticSink.cs @@ -0,0 +1,47 @@ +namespace DwgIO; + +/// +/// Scoped destination for diagnostic messages during a DWG read. Nothing is written unless a public entry point +/// receives a writer; the writer is scoped to the logical call so +/// concurrent reads with different writers do not mix. +/// +internal static class DiagnosticSink +{ + private static readonly AsyncLocal Current = new(); + + /// Sets as the active sink until the returned scope is disposed. + internal static IDisposable Use(TextWriter? writer) => writer is null ? NullScope.Instance : new Scope(writer); + + /// Writes one line to the active sink; does nothing when none is set. + internal static void WriteLine(string message) + { + var writer = Current.Value; + if (writer is null) + { + return; + } + + lock (writer) + { + writer.WriteLine(message); + } + } + + private sealed class Scope : IDisposable + { + private readonly TextWriter? _previous = Current.Value; + + internal Scope(TextWriter writer) => Current.Value = writer; + + public void Dispose() => Current.Value = _previous; + } + + private sealed class NullScope : IDisposable + { + internal static readonly NullScope Instance = new(); + + public void Dispose() + { + } + } +} diff --git a/src/DwgIO/DwgDocument.cs b/src/DwgIO/DwgDocument.cs index 3e0326c..10a0f7b 100644 --- a/src/DwgIO/DwgDocument.cs +++ b/src/DwgIO/DwgDocument.cs @@ -1,5 +1,7 @@ +using System.Text; using DwgIO.Internal.Container; using DwgIO.Internal.Parsing; +using DwgIO.Json; using DwgIO.Model; namespace DwgIO; @@ -8,18 +10,27 @@ namespace DwgIO; /// An opened Autodesk DWG file parsed without AutoCAD installed. /// Exposes version info, the named-section catalog and per-section decompressed reads. /// -public sealed class DwgDocument +public sealed partial class DwgDocument { - private readonly byte[] _fileBytes; private readonly R2004Container? _container; private readonly bool _verifyChecksums; private readonly List _diagnostics = []; + private byte[] _fileBytes; private byte[]? _objectStreamBytes; - - private DwgDocument(string path, byte[] fileBytes, DwgFileHeader fileHeader, R2004Container? container, DwgReaderOptions options) + private bool _buffersReleased; + + private DwgDocument( + string path, + string? sourcePath, + byte[] fileBytes, + DwgFileHeader fileHeader, + R2004Container? container, + DwgReaderOptions options) { Path = path; + SourcePath = sourcePath; _fileBytes = fileBytes; + FileSize = fileBytes.Length; FileHeader = fileHeader; _container = container; _verifyChecksums = options.VerifyChecksums; @@ -27,12 +38,16 @@ private DwgDocument(string path, byte[] fileBytes, DwgFileHeader fileHeader, R20 Sections = container is null ? [] : [.. container.SectionMap.Sections.Select(ToSectionInfo)]; - SummaryInfo = container is null || !options.ReadSummaryInfo ? null : ReadOptionalSummaryInfo(); Diagnostics = _diagnostics; + + options.Progress?.Report(new DwgReadProgress("container", Sections.Count, Sections.Count)); + SummaryInfo = container is null || !options.ReadSummaryInfo ? null : ReadOptionalSummaryInfo(); + if (container is not null) { if (options.ReadMetadata) { + options.Progress?.Report(new DwgReadProgress("metadata")); AppInfo = TryReadMetadata("AcDb:AppInfo", b => AppInfoParser.Parse(b, fileHeader.Codepage)); FileDepList = TryReadMetadata("AcDb:FileDepList", b => FileDepListParser.Parse(b, fileHeader.Codepage)); Preview = ReadOptionalPreview(); @@ -44,18 +59,44 @@ private DwgDocument(string path, byte[] fileBytes, DwgFileHeader fileHeader, R20 if (options.ReadObjects) { - HandleMap = ReadOptionalHandleMap(); - Objects = ReadOptionalObjects(); - Entities = !options.ReadEntities ? [] : ReadOptionalEntities(); + options.Progress?.Report(new DwgReadProgress("handles")); + HandleMap = ReadOptionalHandleMap(options.MaxObjectCount); + options.Progress?.Report(new DwgReadProgress("objects")); + Objects = ReadOptionalObjects(options.MaxObjectCount); + if (options.ReadEntities) + { + options.Progress?.Report(new DwgReadProgress("entities", 0, Objects.Count)); + Entities = ReadOptionalEntities(); + options.Progress?.Report(new DwgReadProgress("entities", Entities.Count, Objects.Count)); + } + else + { + Entities = []; + } } } + + if (options.Strict && _diagnostics.Count > 0) + { + throw new DwgException($"DWG read produced {_diagnostics.Count} diagnostic(s); first: {_diagnostics[0]}"); + } + + if (options.ReleaseSectionBuffers) + { + ReleaseSectionBuffers(); + } + + options.Progress?.Report(new DwgReadProgress("complete", Entities.Count, Objects.Count)); } - /// Absolute or relative path the document was opened from. + /// Path or caller-supplied document name the drawing was opened with. public string Path { get; } + /// Full local file path when opened from disk; null when opened from a stream or in memory. + public string? SourcePath { get; } + /// Size of the file in bytes. - public long FileSize => _fileBytes.Length; + public long FileSize { get; } /// The DWG release identified from the file's version magic. public DwgVersionInfo Version { get; } @@ -116,7 +157,9 @@ internal DwgDocument(string path, DwgFileHeader fileHeader, IReadOnlyList? objects = null, IEnumerable? diagnostics = null) { Path = path; + SourcePath = null; _fileBytes = []; + FileSize = 0; FileHeader = fileHeader; Version = fileHeader.Version; Sections = []; @@ -129,7 +172,7 @@ internal DwgDocument(string path, DwgFileHeader fileHeader, IReadOnlyListCreates a document over a container built in the tests; reads follow . internal DwgDocument(string path, R2004Container container, DwgFileHeader fileHeader, DwgReaderOptions options) - : this(path, [], fileHeader, container, options) + : this(path, null, [], fileHeader, container, options) { } @@ -137,19 +180,37 @@ internal DwgDocument(string path, R2004Container container, DwgFileHeader fileHe /// The file does not exist. /// The file's container is not implemented yet /// (R13-R2000, R2007). - /// The file is corrupt or truncated. + /// The file is corrupt, truncated, exceeds , + /// or triggers . public static DwgDocument Open(string path, DwgReaderOptions? options = null) { + ArgumentException.ThrowIfNullOrEmpty(path); if (!File.Exists(path)) { throw new FileNotFoundException($"DWG file not found: {path}", path); } options ??= DwgReaderOptions.Default; - var fileBytes = File.ReadAllBytes(path); + var info = new FileInfo(path); + if (info.Length > options.MaxFileBytes) + { + throw new DwgException($"DWG file '{path}' is {info.Length} bytes, exceeding MaxFileBytes ({options.MaxFileBytes})."); + } + + byte[] fileBytes; try { - return Parse(path, fileBytes, options); + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); + fileBytes = ReadBoundedBytes(stream, options.MaxFileBytes, info.Length); + } + catch (Exception ex) when (ex is not DwgException && IsParseFailure(ex)) + { + throw Corrupt(ex); + } + + try + { + return Parse(path, System.IO.Path.GetFullPath(path), fileBytes, options); } catch (Exception ex) when (ex is not DwgException && IsParseFailure(ex)) { @@ -159,13 +220,13 @@ public static DwgDocument Open(string path, DwgReaderOptions? options = null) /// /// Opens and parses a DWG from a stream (a network handle, an archive entry, an already-open file). The - /// stream is read to the end into memory once, so the results are identical to - /// on the same bytes; names the document in , error - /// messages and exports (the default is "stream"). + /// stream is read to the end into memory once (without closing the caller's stream), so the results are + /// identical to on the same bytes; + /// names the document in , error messages and exports (the default is "stream"). /// /// The stream cannot be read. /// The file's container is not implemented yet (R13-R2000, R2007). - /// The file is corrupt or truncated. + /// The file is corrupt, truncated, or exceeds . public static DwgDocument Open(Stream stream, string? documentName = null, DwgReaderOptions? options = null) { ArgumentNullException.ThrowIfNull(stream); @@ -177,14 +238,15 @@ public static DwgDocument Open(Stream stream, string? documentName = null, DwgRe options ??= DwgReaderOptions.Default; string name = string.IsNullOrEmpty(documentName) ? "stream" : documentName; long? expectedLength = stream.CanSeek ? stream.Length - stream.Position : null; + if (expectedLength is long knownLength && knownLength > options.MaxFileBytes) + { + throw new DwgException($"DWG stream '{name}' is {knownLength} bytes, exceeding MaxFileBytes ({options.MaxFileBytes})."); + } + byte[] fileBytes; try { - using var buffer = expectedLength is long length and >= 0 - ? new MemoryStream((int)Math.Min(length, int.MaxValue)) - : new MemoryStream(); - stream.CopyTo(buffer); - fileBytes = buffer.ToArray(); + fileBytes = ReadBoundedBytes(stream, options.MaxFileBytes, expectedLength); } catch (Exception ex) when (ex is not DwgException && IsParseFailure(ex)) { @@ -193,7 +255,7 @@ public static DwgDocument Open(Stream stream, string? documentName = null, DwgRe try { - return Parse(name, fileBytes, options); + return Parse(name, null, fileBytes, options); } catch (Exception ex) when (ex is not DwgException && IsParseFailure(ex)) { @@ -201,8 +263,171 @@ public static DwgDocument Open(Stream stream, string? documentName = null, DwgRe } } - private static DwgDocument Parse(string path, byte[] fileBytes, DwgReaderOptions options) + /// Opens and parses a DWG file using asynchronous I/O. + public static async Task OpenAsync( + string path, + DwgReaderOptions? options = null, + CancellationToken cancellationToken = default) { + cancellationToken.ThrowIfCancellationRequested(); + ArgumentException.ThrowIfNullOrEmpty(path); + if (!File.Exists(path)) + { + throw new FileNotFoundException($"DWG file not found: {path}", path); + } + + options ??= DwgReaderOptions.Default; + var info = new FileInfo(path); + if (info.Length > options.MaxFileBytes) + { + throw new DwgException($"DWG file '{path}' is {info.Length} bytes, exceeding MaxFileBytes ({options.MaxFileBytes})."); + } + + byte[] fileBytes; + try + { + var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 81920, FileOptions.Asynchronous); + await using (stream.ConfigureAwait(false)) + { + fileBytes = await ReadBoundedBytesAsync(stream, options.MaxFileBytes, info.Length, cancellationToken).ConfigureAwait(false); + } + } + catch (Exception ex) when (ex is not DwgException and not OperationCanceledException && IsParseFailure(ex)) + { + throw Corrupt(ex); + } + + cancellationToken.ThrowIfCancellationRequested(); + try + { + return Parse(path, System.IO.Path.GetFullPath(path), fileBytes, options); + } + catch (Exception ex) when (ex is not DwgException && IsParseFailure(ex)) + { + throw Corrupt(ex); + } + } + + /// Opens and parses a DWG from a stream using asynchronous I/O without closing the caller's stream. + public static async Task OpenAsync( + Stream stream, + string? documentName = null, + DwgReaderOptions? options = null, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + ArgumentNullException.ThrowIfNull(stream); + if (!stream.CanRead) + { + throw new ArgumentException("The stream cannot be read.", nameof(stream)); + } + + options ??= DwgReaderOptions.Default; + string name = string.IsNullOrEmpty(documentName) ? "stream" : documentName; + long? expectedLength = stream.CanSeek ? stream.Length - stream.Position : null; + if (expectedLength is long knownLength && knownLength > options.MaxFileBytes) + { + throw new DwgException($"DWG stream '{name}' is {knownLength} bytes, exceeding MaxFileBytes ({options.MaxFileBytes})."); + } + + byte[] fileBytes; + try + { + fileBytes = await ReadBoundedBytesAsync(stream, options.MaxFileBytes, expectedLength, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not DwgException and not OperationCanceledException && IsParseFailure(ex)) + { + throw Corrupt(ex); + } + + cancellationToken.ThrowIfCancellationRequested(); + try + { + return Parse(name, null, fileBytes, options); + } + catch (Exception ex) when (ex is not DwgException && IsParseFailure(ex)) + { + throw Corrupt(ex); + } + } + + /// Releases retained raw file and object-stream byte buffers when section reads are no longer needed. + public void ReleaseSectionBuffers() + { + _fileBytes = []; + _objectStreamBytes = null; + _buffersReleased = true; + } + + /// Writes this document as JSON to . + public void SaveJson(Stream output, DwgJsonExportOptions? options = null) + { + ArgumentNullException.ThrowIfNull(output); + DwgJsonExporter.Write(this, output, options ?? DwgJsonExportOptions.Default); + } + + /// Serializes this document to a JSON string. + public string ToJson(DwgJsonExportOptions? options = null) + { + using var ms = new MemoryStream(); + SaveJson(ms, options); + return Encoding.UTF8.GetString(ms.ToArray()); + } + + private static byte[] ReadBoundedBytes(Stream stream, long maxFileBytes, long? expectedLength) + { + int capacity = expectedLength is long len and >= 0 + ? (int)Math.Min(len, Math.Min(maxFileBytes, Array.MaxLength)) + : 0; + using var buffer = capacity > 0 ? new MemoryStream(capacity) : new MemoryStream(); + var chunk = new byte[81920]; + long total = 0; + int read; + while ((read = stream.Read(chunk, 0, chunk.Length)) > 0) + { + total += read; + if (total > maxFileBytes) + { + throw new DwgException($"DWG input exceeds MaxFileBytes ({maxFileBytes} bytes)."); + } + + buffer.Write(chunk, 0, read); + } + + return buffer.ToArray(); + } + + private static async Task ReadBoundedBytesAsync( + Stream stream, + long maxFileBytes, + long? expectedLength, + CancellationToken cancellationToken) + { + int capacity = expectedLength is long len and >= 0 + ? (int)Math.Min(len, Math.Min(maxFileBytes, Array.MaxLength)) + : 0; + using var buffer = capacity > 0 ? new MemoryStream(capacity) : new MemoryStream(); + var chunk = new byte[81920]; + long total = 0; + int read; + while ((read = await stream.ReadAsync(chunk, cancellationToken).ConfigureAwait(false)) > 0) + { + total += read; + if (total > maxFileBytes) + { + throw new DwgException($"DWG input exceeds MaxFileBytes ({maxFileBytes} bytes)."); + } + + buffer.Write(chunk, 0, read); + } + + return buffer.ToArray(); + } + + private static DwgDocument Parse(string path, string? sourcePath, byte[] fileBytes, DwgReaderOptions options) + { + using var _ = DiagnosticSink.Use(options.DiagnosticOutput); + options.Progress?.Report(new DwgReadProgress("header")); var fileHeader = DwgFileHeader.Parse(fileBytes); if (fileHeader.Version.Family != DwgContainerFamily.R2004Family) @@ -214,19 +439,26 @@ private static DwgDocument Parse(string path, byte[] fileBytes, DwgReaderOptions : "the R13-R2000 container is planned.")); } - var container = options.ReadSectionMap ? R2004Container.Parse(fileBytes) : null; - return new DwgDocument(path, fileBytes, fileHeader, container, options); + var container = options.ReadSectionMap + ? R2004Container.Parse(fileBytes, options.MaxDecompressedBytes, options.MaxSectionBytes) + : null; + return new DwgDocument(path, sourcePath, fileBytes, fileHeader, container, options); } /// /// Reads and decompresses a named section (e.g. "AcDb:Header", "AcDb:SummaryInfo"). /// - public byte[] ReadSection(string name) => ReadSection(name, _diagnostics.Add); + public byte[] ReadSection(string name) => ReadSection(name, AddDiagnostic); internal byte[] ReadSection(string name, Action? reportDiagnostic) { var container = _container ?? throw new DwgException("The document was opened without its section map (ReadSectionMap = false)."); + if (_buffersReleased) + { + throw new DwgException("Section buffers were released (DwgReaderOptions.ReleaseSectionBuffers = true)."); + } + var entry = container.SectionMap.FindByName(name) ?? throw new DwgException($"Section '{name}' not found. Available: {string.Join(", ", container.SectionMap.Sections.Select(s => s.Name))}"); try @@ -239,6 +471,12 @@ internal byte[] ReadSection(string name, Action? reportDiagnostic) } } + private void AddDiagnostic(string message) + { + _diagnostics.Add(message); + DiagnosticSink.WriteLine(message); + } + // Malformed data can surface as these runtime exceptions before a parser check rejects it. private static bool IsParseFailure(Exception ex) => ex is DwgException or ArgumentException or OverflowException or IndexOutOfRangeException or InvalidOperationException; @@ -268,14 +506,14 @@ internal bool TryGetReadableSection(string name, [System.Diagnostics.CodeAnalysi if (entry.Encryption == 1) { - _diagnostics.Add($"{name}: the section is encrypted (encryption flag 1) and was skipped; decrypting it is not supported"); + AddDiagnostic($"{name}: the section is encrypted (encryption flag 1) and was skipped; decrypting it is not supported"); return false; } return true; } - private DwgHandleMap? ReadOptionalHandleMap() + private DwgHandleMap? ReadOptionalHandleMap(int maxObjectCount) { if (!TryGetReadableSection("AcDb:Handles", out var entry)) { @@ -284,16 +522,16 @@ internal bool TryGetReadableSection(string name, [System.Diagnostics.CodeAnalysi try { - return DwgHandleMap.Parse(ReadSectionCore(entry), _diagnostics.Add); + return DwgHandleMap.Parse(ReadSectionCore(entry), AddDiagnostic, maxObjectCount); } catch (Exception ex) when (IsParseFailure(ex)) { - _diagnostics.Add($"AcDb:Handles: {ex.Message}"); + AddDiagnostic($"AcDb:Handles: {ex.Message}"); return null; } } - private IReadOnlyList ReadOptionalObjects() + private IReadOnlyList ReadOptionalObjects(int maxObjectCount) { if (!TryGetReadableSection("AcDb:AcDbObjects", out var entry)) { @@ -308,13 +546,18 @@ private IReadOnlyList ReadOptionalObjects() var mapOffsets = HandleMap is null ? null : HandleMap.Entries.Select(e => e.Offset).Distinct().OrderBy(o => o).ToList(); - var objects = ObjectStreamWalker.Walk(_objectStreamBytes, r2010Plus: FileHeader.Version.Year >= 2010, mapOffsets, _diagnostics.Add); + var objects = ObjectStreamWalker.Walk( + _objectStreamBytes, + r2010Plus: FileHeader.Version.Year >= 2010, + mapOffsets, + AddDiagnostic, + maxObjectCount); if (HandleMap is { Count: > 0 } map) { int missing = CountUnreachedObjects(objects, map); if (missing > 0) { - _diagnostics.Add($"AcDb:AcDbObjects: inventory holds {objects.Count} records; {missing} of {map.Count} handle-map entries were unreached"); + AddDiagnostic($"AcDb:AcDbObjects: inventory holds {objects.Count} records; {missing} of {map.Count} handle-map entries were unreached"); } } @@ -322,7 +565,7 @@ private IReadOnlyList ReadOptionalObjects() } catch (Exception ex) when (IsParseFailure(ex)) { - _diagnostics.Add($"AcDb:AcDbObjects: {ex.Message}"); + AddDiagnostic($"AcDb:AcDbObjects: {ex.Message}"); return []; } } @@ -358,7 +601,7 @@ private List ReadOptionalEntities() } catch (Exception ex) when (IsParseFailure(ex)) { - _diagnostics.Add($"entity {info.Handle:X} @{info.StreamOffset} (type 0x{info.TypeCode:X}): {ex.Message}"); + AddDiagnostic($"entity {info.Handle:X} @{info.StreamOffset} (type 0x{info.TypeCode:X}): {ex.Message}"); } } @@ -378,7 +621,7 @@ private ReadOnlyMemory ReadAppInfoHistory() } catch (Exception ex) when (IsParseFailure(ex)) { - _diagnostics.Add($"AcDb:AppInfoHistory: {ex.Message}"); + AddDiagnostic($"AcDb:AppInfoHistory: {ex.Message}"); return ReadOnlyMemory.Empty; } } @@ -397,13 +640,13 @@ private ReadOnlyMemory ReadAppInfoHistory() try { var pageLayout = new List(); - var bytes = _container!.ReadSection(_fileBytes, entry, _verifyChecksums, _diagnostics.Add, pageLayout); + var bytes = _container!.ReadSection(_fileBytes, entry, _verifyChecksums, AddDiagnostic, pageLayout); return PreviewParser.Parse(bytes, pageLayout); } catch (Exception ex) when (IsParseFailure(ex)) { PreviewReadError = $"AcDb:Preview: {ex.Message}"; - _diagnostics.Add(PreviewReadError); + AddDiagnostic(PreviewReadError); return null; } } @@ -429,13 +672,13 @@ private ReadOnlyMemory ReadAppInfoHistory() catch (Exception ex) when (IsParseFailure(ex)) { // Metadata is best-effort: a malformed section must not fail the whole document. - _diagnostics.Add($"{sectionName}: {ex.Message}"); + AddDiagnostic($"{sectionName}: {ex.Message}"); return null; } } private byte[] ReadSectionCore(SectionEntry entry) => - _container!.ReadSection(_fileBytes, entry, _verifyChecksums, _diagnostics.Add); + _container!.ReadSection(_fileBytes, entry, _verifyChecksums, AddDiagnostic); private static DwgSectionInfo ToSectionInfo(SectionEntry entry) => new() { diff --git a/src/DwgIO/DwgExitCodes.cs b/src/DwgIO/DwgExitCodes.cs new file mode 100644 index 0000000..0f4d360 --- /dev/null +++ b/src/DwgIO/DwgExitCodes.cs @@ -0,0 +1,23 @@ +namespace DwgIO; + +/// Exit codes returned by the dwgio command line tool. +public static class DwgExitCodes +{ + /// The command succeeded. + public const int Ok = 0; + + /// The command line arguments or options are invalid. + public const int Usage = 1; + + /// The input DWG file does not exist. + public const int FileNotFound = 2; + + /// The DWG version is not supported yet or not recognised. + public const int UnsupportedVersion = 3; + + /// The file could not be parsed, or an unexpected error occurred. + public const int ParseError = 4; + + /// The drawing has no embedded thumbnail preview. + public const int NoPreview = 5; +} diff --git a/src/DwgIO/DwgReaderOptions.cs b/src/DwgIO/DwgReaderOptions.cs index 62184c3..e053da6 100644 --- a/src/DwgIO/DwgReaderOptions.cs +++ b/src/DwgIO/DwgReaderOptions.cs @@ -1,8 +1,18 @@ namespace DwgIO; -/// Options controlling what reads. +/// Options controlling what reads and keeps. public sealed class DwgReaderOptions { + internal const long DefaultMaxFileBytes = 512L * 1024 * 1024; + internal const long DefaultMaxSectionBytes = 512L * 1024 * 1024; + internal const long DefaultMaxDecompressedBytes = 2L * 1024 * 1024 * 1024; + internal const int DefaultMaxObjectCount = 1 << 21; + + private long _maxFileBytes = DefaultMaxFileBytes; + private long _maxSectionBytes = DefaultMaxSectionBytes; + private long _maxDecompressedBytes = DefaultMaxDecompressedBytes; + private int _maxObjectCount = DefaultMaxObjectCount; + /// Options with every default value. public static DwgReaderOptions Default { get; } = new(); @@ -18,7 +28,7 @@ public sealed class DwgReaderOptions /// Parse the AcDb:SummaryInfo section when present (default: true). public bool ReadSummaryInfo { get; set; } = true; - /// Parse metadata sections: AppInfo, FileDepList, Preview (default: true). + /// Parse metadata sections: AppInfo, FileDepList, Preview, RevHistory, AuxHeader, Template (default: true). public bool ReadMetadata { get; set; } = true; /// @@ -30,4 +40,83 @@ public sealed class DwgReaderOptions /// Decode entity bodies (common preamble + geometry for LINE/CIRCLE/ARC/POINT) /// into (default: true; requires ReadObjects). public bool ReadEntities { get; set; } = true; + + /// + /// Throw when opening the document records any diagnostic warning + /// (default: false; diagnostics are collected in ). + /// + public bool Strict { get; set; } + + /// + /// Drop raw file and decompressed object-stream buffers once + /// finishes parsing (default: false). Enable for consumers such as scene adapters that do not call + /// after opening. + /// + public bool ReleaseSectionBuffers { get; set; } + + /// + /// Positive ceiling on the input file or stream size in bytes (default: 512 MiB). Exceeding it makes + /// throw . + /// + /// The assigned value is zero or negative. + public long MaxFileBytes + { + get => _maxFileBytes; + set + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); + _maxFileBytes = value; + } + } + + /// + /// Positive ceiling on the decompressed size of any single section in bytes (default: 512 MiB). + /// + /// The assigned value is zero or negative. + public long MaxSectionBytes + { + get => _maxSectionBytes; + set + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); + _maxSectionBytes = value; + } + } + + /// + /// Positive ceiling on the total decompressed section bytes across one document (default: 2 GiB). + /// + /// The assigned value is zero or negative. + public long MaxDecompressedBytes + { + get => _maxDecompressedBytes; + set + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); + _maxDecompressedBytes = value; + } + } + + /// + /// Positive ceiling on the number of object records and handle-map entries decoded from one drawing (default: 2,097,152). + /// + /// The assigned value is zero or negative. + public int MaxObjectCount + { + get => _maxObjectCount; + set + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); + _maxObjectCount = value; + } + } + + /// + /// Receives phase updates from synchronously on the reading + /// thread in phase order. Avoid when ordered synchronous delivery is required. + /// + public IProgress? Progress { get; set; } + + /// Optional destination for diagnostic messages while opening a drawing. Null keeps the library silent. + public TextWriter? DiagnosticOutput { get; set; } } diff --git a/src/DwgIO/Internal/Container/ObjectStream.cs b/src/DwgIO/Internal/Container/ObjectStream.cs index 89bb52f..23aca10 100644 --- a/src/DwgIO/Internal/Container/ObjectStream.cs +++ b/src/DwgIO/Internal/Container/ObjectStream.cs @@ -12,7 +12,7 @@ namespace DwgIO.Internal.Container; /// internal static class ObjectStreamWalker { - private const int MaxRecords = 1 << 21; + private const int DefaultMaxRecords = 1 << 21; /// /// Walks the object records sequentially and returns their inventory. The walk assumes records follow each @@ -24,16 +24,23 @@ internal static class ObjectStreamWalker /// R2010 and later carry the handle-stream size in bits. /// Handle-map offsets into the stream, ascending, or null when the map is absent. /// Receives one message per early stop or gap that was skipped. + /// Maximum number of object records to collect before stopping with a diagnostic. public static IReadOnlyList Walk( byte[] data, bool r2010Plus, IReadOnlyList? mapOffsets = null, - Action? diagnostic = null) + Action? diagnostic = null, + int maxRecords = DefaultMaxRecords) { var objects = new List(); int pos = StartOffset(data); - while (pos + 2 < data.Length && objects.Count < MaxRecords) + while (pos + 2 < data.Length) { + if (objects.Count >= maxRecords) + { + Report(diagnostic, $"object stream: stopped after reaching MaxObjectCount ({maxRecords})"); + break; + } var (end, failure, nextPos) = TryReadRecord(data, pos, r2010Plus, objects); if (!end && failure is null) { diff --git a/src/DwgIO/Internal/Container/R2004Container.cs b/src/DwgIO/Internal/Container/R2004Container.cs index b7e9a5c..db191c9 100644 --- a/src/DwgIO/Internal/Container/R2004Container.cs +++ b/src/DwgIO/Internal/Container/R2004Container.cs @@ -29,7 +29,10 @@ internal sealed class R2004Container private long _decompressedBytes; /// Ceiling on section buffers allocated plus page bytes produced by all section reads of one document. - public long MaxDecompressedBytes { get; init; } = 8L * 1024 * 1024 * 1024; + public long MaxDecompressedBytes { get; init; } = DwgReaderOptions.DefaultMaxDecompressedBytes; + + /// Ceiling on the decompressed size of any single section. + public long MaxSectionBytes { get; init; } = DwgReaderOptions.DefaultMaxSectionBytes; private void Charge(long bytes) { @@ -49,7 +52,10 @@ private void Charge(long bytes) public required SectionMap SectionMap { get; init; } /// Parses the header, page map and section map of an R2004-family file. - public static R2004Container Parse(byte[] fileBytes) + public static R2004Container Parse( + byte[] fileBytes, + long maxDecompressedBytes = DwgReaderOptions.DefaultMaxDecompressedBytes, + long maxSectionBytes = DwgReaderOptions.DefaultMaxSectionBytes) { var header = DwgContainerHeader.Parse(fileBytes); var pageMap = PageMap.Parse(fileBytes, header); @@ -59,6 +65,8 @@ public static R2004Container Parse(byte[] fileBytes) Header = header, PageMap = pageMap, SectionMap = sectionMap, + MaxDecompressedBytes = maxDecompressedBytes, + MaxSectionBytes = maxSectionBytes, }; } @@ -91,7 +99,7 @@ public byte[] ReadSection( // The size comes from the file: check it before allocating the result. ulong pageBudget = (ulong)entry.PageCount * (ulong)pageLimits.MaxOutputBytes; - if (entry.Size > (ulong)Array.MaxLength || entry.Size > pageBudget + MaxSizeOvershoot) + if (entry.Size > (ulong)Array.MaxLength || entry.Size > (ulong)MaxSectionBytes || entry.Size > pageBudget + MaxSizeOvershoot) { throw new DwgException( $"Section '{entry.Name}' declares {entry.Size} bytes, more than {entry.PageCount} pages of up to {pageLimits.MaxOutputBytes} bytes " + diff --git a/src/DwgIO/Model/DwgHandleMap.cs b/src/DwgIO/Model/DwgHandleMap.cs index 3317d41..14c86a3 100644 --- a/src/DwgIO/Model/DwgHandleMap.cs +++ b/src/DwgIO/Model/DwgHandleMap.cs @@ -15,7 +15,7 @@ public sealed record DwgHandleMapEntry(ulong Handle, ulong Offset); /// public sealed class DwgHandleMap { - private const int MaxEntries = 1 << 22; + internal const int DefaultMaxEntries = 1 << 22; private Dictionary? _byHandle; @@ -34,7 +34,7 @@ public sealed class DwgHandleMap /// Parses the decompressed AcDb:Handles section. Where the parse stops early, or an entry /// is dropped, a message goes to instead of vanishing. - internal static DwgHandleMap Parse(byte[] data, Action? diagnostic = null) + internal static DwgHandleMap Parse(byte[] data, Action? diagnostic = null, int maxEntries = DefaultMaxEntries) { var entries = new List(); int pos = 0; @@ -85,7 +85,7 @@ internal static DwgHandleMap Parse(byte[] data, Action? diagnostic = nul continue; } - if (entries.Count >= MaxEntries) + if (entries.Count >= maxEntries) { throw new DwgException("Handle map exceeds the entry cap; file is malformed."); } diff --git a/src/DwgIO/Model/DwgReadProgress.cs b/src/DwgIO/Model/DwgReadProgress.cs new file mode 100644 index 0000000..86d0a06 --- /dev/null +++ b/src/DwgIO/Model/DwgReadProgress.cs @@ -0,0 +1,7 @@ +namespace DwgIO; + +/// A progress update from a DWG file read. +/// Machine-readable name of the current reader phase. +/// Completed units of work within the phase. +/// Total units of work in that phase, or zero when no count is available. +public readonly record struct DwgReadProgress(string Phase, long Completed = 0, long Total = 0); diff --git a/tests/DwgIO.Tests/CoreStandardTests.cs b/tests/DwgIO.Tests/CoreStandardTests.cs new file mode 100644 index 0000000..e3f24d3 --- /dev/null +++ b/tests/DwgIO.Tests/CoreStandardTests.cs @@ -0,0 +1,212 @@ +using System.Text.Json; +using DwgIO.Cli; +using IOScene.Formats; +using Xunit; + +namespace DwgIO.Tests; + +public class CoreStandardTests : IDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), "dwgio-std-" + Guid.NewGuid().ToString("N")); + + public CoreStandardTests() + { + Directory.CreateDirectory(_directory); + } + + public void Dispose() + { + GC.SuppressFinalize(this); + try + { + Directory.Delete(_directory, recursive: true); + } + catch (DirectoryNotFoundException) + { + } + } + + [Fact] + public void ReaderOptions_InvalidLimits_ThrowArgumentOutOfRange() + { + var options = new DwgReaderOptions(); + Assert.Throws(() => options.MaxFileBytes = 0); + Assert.Throws(() => options.MaxSectionBytes = -1); + Assert.Throws(() => options.MaxDecompressedBytes = 0); + Assert.Throws(() => options.MaxObjectCount = 0); + } + + [Fact] + public void Open_SourcePath_SetForDiskAndNullForStream() + { + string path = TestFiles.PublicDrawing("primitives-ac1032.dwg"); + var fromPath = DwgDocument.Open(path); + + using var stream = File.OpenRead(path); + var fromStream = DwgDocument.Open(stream, "mem.dwg"); + + Assert.Equal(Path.GetFullPath(path), fromPath.SourcePath); + Assert.Null(fromStream.SourcePath); + Assert.Equal("mem.dwg", fromStream.Path); + } + + [Fact] + public void Open_MaxFileBytesExceeded_ThrowsDwgException() + { + string path = TestFiles.PublicDrawing("primitives-ac1032.dwg"); + var options = new DwgReaderOptions { MaxFileBytes = 64 }; + + Assert.Throws(() => DwgDocument.Open(path, options)); + using var stream = File.OpenRead(path); + Assert.Throws(() => DwgDocument.Open(stream, "small.dwg", options)); + } + + [Fact] + public void Open_StrictWithDiagnostic_ThrowsDwgException() + { + // primitives-ac1032.dwg has small declared-size tail diagnostics on FileDepList/RevHistory. + string path = TestFiles.PublicDrawing("primitives-ac1032.dwg"); + + Assert.Throws(() => DwgDocument.Open(path, new DwgReaderOptions { Strict = true })); + } + + [Fact] + public void Open_ReleaseSectionBuffers_PreventsLaterReadSectionAndPreservesEntities() + { + string path = TestFiles.PublicDrawing("primitives-ac1032.dwg"); + var doc = DwgDocument.Open(path, new DwgReaderOptions { ReleaseSectionBuffers = true }); + + Assert.NotEmpty(doc.Entities); + Assert.True(doc.FileSize > 0); + Assert.Throws(() => doc.ReadSection("AcDb:Header")); + } + + [Fact] + public void Open_ProgressAndDiagnosticOutput_ReportSynchronously() + { + string path = TestFiles.PublicDrawing("primitives-ac1032.dwg"); + var phases = new List(); + using var writer = new StringWriter(); + + var doc = DwgDocument.Open(path, new DwgReaderOptions + { + Progress = new SyncProgress(p => phases.Add(p.Phase)), + DiagnosticOutput = writer, + }); + + Assert.Equal(["header", "container", "metadata", "handles", "objects", "entities", "entities", "complete"], phases); + Assert.Equal(doc.Diagnostics.Count > 0, writer.ToString().Length > 0); + } + + [Fact] + public async Task OpenAsync_PathAndStream_MatchSyncOpen() + { + string path = TestFiles.PublicDrawing("primitives-ac1032.dwg"); + var syncDoc = DwgDocument.Open(path); + var asyncDoc = await DwgDocument.OpenAsync(path); + + using var stream = File.OpenRead(path); + var asyncStreamDoc = await DwgDocument.OpenAsync(stream, "async.dwg"); + + Assert.Equal(syncDoc.ToJson(), asyncDoc.ToJson()); + Assert.Null(asyncStreamDoc.SourcePath); + Assert.Equal(syncDoc.Entities.Count, asyncStreamDoc.Entities.Count); + } + + [Fact] + public void SaveJson_ToFileAndStream_ProducesValidJson() + { + string path = TestFiles.PublicDrawing("primitives-ac1032.dwg"); + var doc = DwgDocument.Open(path); + string outPath = Path.Combine(_directory, "out.json"); + + doc.SaveJson(outPath); + using var parsed = JsonDocument.Parse(File.ReadAllBytes(outPath)); + Assert.Equal(doc.Version.Magic, parsed.RootElement.GetProperty("version").GetProperty("magic").GetString()); + } + + [Fact] + public void ExitCodes_MatchDocumentedCliCodes() + { + Assert.Equal(0, DwgExitCodes.Ok); + Assert.Equal(1, DwgExitCodes.Usage); + Assert.Equal(2, DwgExitCodes.FileNotFound); + Assert.Equal(3, DwgExitCodes.UnsupportedVersion); + Assert.Equal(4, DwgExitCodes.ParseError); + Assert.Equal(5, DwgExitCodes.NoPreview); + } + + [Fact] + public void Cli_DirectGlbAndObjRespectUnitOption() + { + string fixture = TestFiles.PublicDrawing("primitives-ac1027.dwg"); + string glbPath = Path.Combine(_directory, "scaled.glb"); + string objPath = Path.Combine(_directory, "scaled.obj"); + + using var out1 = new StringWriter(); + using var err1 = new StringWriter(); + int exitGlb = Program.Run([fixture, glbPath, "--unit", "mm"], out1, err1); + Assert.Equal(DwgExitCodes.Ok, exitGlb); + + var loaded = GlbSceneReader.Load(glbPath); + Assert.All(loaded.Geometries.SelectMany(g => g.Vertices), v => Assert.True(Math.Abs(v.X) < 0.1 && Math.Abs(v.Y) < 0.1)); + + using var out2 = new StringWriter(); + using var err2 = new StringWriter(); + int exitObj = Program.Run([fixture, objPath, "--unit", "mm"], out2, err2); + Assert.Equal(DwgExitCodes.Ok, exitObj); + Assert.Contains("v 0.001 0.002 0.003", File.ReadAllText(objPath), StringComparison.Ordinal); + } + + [Fact] + public void Cli_HtmlMode2dDefaultAnd3dOption() + { + string fixture = TestFiles.PublicDrawing("primitives-ac1032.dwg"); + string html2d = Path.Combine(_directory, "cad.html"); + string html3d = Path.Combine(_directory, "web3d.html"); + + using var o1 = new StringWriter(); + using var e1 = new StringWriter(); + Assert.Equal(DwgExitCodes.Ok, Program.Run([fixture, html2d, "--bg", "slate"], o1, e1)); + string cadContent = File.ReadAllText(html2d); + Assert.Contains("id=\"dwgio-cad-data\"", cadContent, StringComparison.Ordinal); + Assert.Contains("data-theme=\"slate\"", cadContent, StringComparison.Ordinal); + + using var o2 = new StringWriter(); + using var e2 = new StringWriter(); + Assert.Equal(DwgExitCodes.Ok, Program.Run([fixture, html3d, "--mode", "3d"], o2, e2)); + Assert.Contains("id=\"ioviewer-meta\"", File.ReadAllText(html3d), StringComparison.Ordinal); + + using var o3 = new StringWriter(); + using var e3 = new StringWriter(); + Assert.Equal(DwgExitCodes.Usage, Program.Run([fixture, html2d, "--mode", "invalid"], o3, e3)); + } + + [Fact] + public void Cli_RejectsOutputCollidingWithInputDwg() + { + string fixture = TestFiles.PublicDrawing("primitives-ac1032.dwg"); + string copy = Path.Combine(_directory, "copy.dwg"); + File.Copy(fixture, copy); + byte[] original = File.ReadAllBytes(copy); + + using var out1 = new StringWriter(); + using var err1 = new StringWriter(); + int exit = Program.Run([copy, copy], out1, err1); + + Assert.Equal(DwgExitCodes.Usage, exit); + Assert.Contains("must differ", err1.ToString(), StringComparison.Ordinal); + Assert.Equal(original, File.ReadAllBytes(copy)); + + using var out2 = new StringWriter(); + using var err2 = new StringWriter(); + int exitSvg = Program.Run(["svg", copy, copy], out2, err2); + Assert.Equal(DwgExitCodes.Usage, exitSvg); + Assert.Equal(original, File.ReadAllBytes(copy)); + } + + private sealed class SyncProgress(Action onReport) : IProgress + { + public void Report(T value) => onReport(value); + } +} diff --git a/tests/DwgIO.Tests/DwgSceneExportTests.cs b/tests/DwgIO.Tests/DwgSceneExportTests.cs index 9402f1e..a2be83d 100644 --- a/tests/DwgIO.Tests/DwgSceneExportTests.cs +++ b/tests/DwgIO.Tests/DwgSceneExportTests.cs @@ -1,3 +1,4 @@ +using DwgIO.Export; using DwgIO.Model; using DwgIO.Scene; using IOScene.Formats; diff --git a/tests/DwgIO.Tests/DwgSceneReaderTests.cs b/tests/DwgIO.Tests/DwgSceneReaderTests.cs index 758b464..eba7606 100644 --- a/tests/DwgIO.Tests/DwgSceneReaderTests.cs +++ b/tests/DwgIO.Tests/DwgSceneReaderTests.cs @@ -41,14 +41,49 @@ private static DwgEntity Entity(ulong handle, DwgEntityKind kind, string typeNam }; [Fact] - public void LegacyAssemblyForwardsSceneApiToTheAdapter() + public void SceneAdapterDependsOnlyOnEngineAndIoScene() { var adapter = typeof(DwgSceneReader).Assembly; - var legacy = System.Reflection.Assembly.Load("DwgIO.Scene"); - Assert.Contains(typeof(DwgSceneReader), legacy.GetForwardedTypes()); - Assert.Contains(typeof(DwgSceneOptions), legacy.GetForwardedTypes()); - Assert.Contains(typeof(DwgSceneResult), legacy.GetForwardedTypes()); - Assert.DoesNotContain(adapter.GetReferencedAssemblies(), name => name.Name is "IOScene.Formats" or "IOViewer"); + Assert.Equal("DwgIO.Scene", adapter.GetName().Name); + var references = adapter.GetReferencedAssemblies().Select(a => a.Name).ToArray(); + Assert.Contains("DwgIO", references); + Assert.Contains("IOScene", references); + Assert.DoesNotContain(references, name => name is "IOScene.Formats" or "IOViewer"); + } + + [Fact] + public void Read_FromStream_ProducesSameSceneAsPath() + { + string path = TestFiles.PublicDrawing("primitives-ac1032.dwg"); + var fromPath = DwgSceneReader.Read(path, new DwgSceneOptions { ModelKey = "fixture", LengthUnit = "mm" }); + + using var stream = File.OpenRead(path); + var fromStream = DwgSceneReader.Read(stream, "fixture.dwg", new DwgSceneOptions { ModelKey = "fixture", LengthUnit = "mm" }); + + Assert.True(stream.CanRead); + Assert.Equal(fromPath.ElementCount, fromStream.ElementCount); + Assert.Equal(fromPath.ElementsWithGeometry, fromStream.ElementsWithGeometry); + Assert.Null(fromStream.Document.Models[0].Path); + fromPath.Document.Models[0].Path = null; + Assert.Equal(SceneJson.Write(fromPath.Document), SceneJson.Write(fromStream.Document)); + } + + [Fact] + public void Read_ForwardsProgressUpdates() + { + string path = TestFiles.PublicDrawing("primitives-ac1032.dwg"); + var phases = new List(); + var progress = new SyncProgress(p => phases.Add(p.Phase)); + + DwgSceneReader.Read(path, new DwgSceneOptions { ReadProgress = progress }); + + Assert.Contains("header", phases); + Assert.Contains("complete", phases); + } + + private sealed class SyncProgress(Action onReport) : IProgress + { + public void Report(T value) => onReport(value); } [Fact] diff --git a/tests/DwgIO.Tests/DwgSvgExporterTests.cs b/tests/DwgIO.Tests/DwgSvgExporterTests.cs index a603bc4..aa64c55 100644 --- a/tests/DwgIO.Tests/DwgSvgExporterTests.cs +++ b/tests/DwgIO.Tests/DwgSvgExporterTests.cs @@ -1,7 +1,7 @@ using System.Text; using System.Xml; +using DwgIO.Export; using DwgIO.Model; -using DwgIO.Scene; using Xunit; namespace DwgIO.Tests; diff --git a/tests/DwgIO.Tests/DwgViewerExportTests.cs b/tests/DwgIO.Tests/DwgViewerExportTests.cs index c8c9d03..3313bb3 100644 --- a/tests/DwgIO.Tests/DwgViewerExportTests.cs +++ b/tests/DwgIO.Tests/DwgViewerExportTests.cs @@ -1,6 +1,6 @@ using System.Text.Json; +using DwgIO.Export; using DwgIO.Model; -using DwgIO.Scene; using Xunit; namespace DwgIO.Tests; @@ -73,24 +73,68 @@ private static DwgDocument SampleDrawing() => CreateDocument( }); [Fact] - public void SaveViewer_WritesSelfContainedHtml() + public void SaveViewer_DefaultMode_WritesAutoCad2DHtml() + { + string htmlPath = Path.Combine(_directory, "drawing.html"); + + var result = DwgViewerExport.SaveViewer(SampleDrawing(), htmlPath); + + Assert.Equal(3, result.ElementCount); + string html = File.ReadAllText(htmlPath); + Assert.Contains("", html, StringComparison.OrdinalIgnoreCase); + Assert.Contains("", html, StringComparison.Ordinal); + Assert.Contains("data-theme=\"black\"", html, StringComparison.Ordinal); + Assert.DoesNotContain("", dataStart, StringComparison.Ordinal); + using var payload = JsonDocument.Parse(html[dataStart..dataEnd]); + Assert.Equal("dwgio-cad2d", payload.RootElement.GetProperty("kind").GetString()); + Assert.Equal(3, payload.RootElement.GetProperty("drawnCount").GetInt32()); + Assert.Equal(3, payload.RootElement.GetProperty("entities").GetArrayLength()); + Assert.Equal("#FF0000", payload.RootElement.GetProperty("entities")[0].GetProperty("rgb").GetString()); + Assert.True(payload.RootElement.GetProperty("entities")[2].GetProperty("isAdaptiveColor").GetBoolean()); + } + + [Fact] + public void SaveViewer_Cad2D_ThemeOptionSetsHtmlAttributeAndPayload() + { + string htmlPath = Path.Combine(_directory, "slate.html"); + + DwgViewerExport.SaveViewer(SampleDrawing(), htmlPath, viewerOptions: new DwgViewerOptions + { + Mode = DwgViewerMode.Cad2D, + Theme = DwgCadTheme.Slate, + Title = "Floor Plan", + }); + + string html = File.ReadAllText(htmlPath); + Assert.Contains("data-theme=\"slate\"", html, StringComparison.Ordinal); + Assert.Contains("Floor Plan", html, StringComparison.Ordinal); + } + + [Fact] + public void SaveViewer_Scene3DMode_WritesSelfContainedIOViewerHtml() { string htmlPath = Environment.GetEnvironmentVariable("DWGIO_VIEWER_DEBUG_PATH") is { Length: > 0 } debug ? debug - : Path.Combine(_directory, "drawing.html"); + : Path.Combine(_directory, "drawing-3d.html"); - var result = DwgViewerExport.SaveViewer(SampleDrawing(), htmlPath); + var result = DwgViewerExport.SaveViewer( + SampleDrawing(), + htmlPath, + viewerOptions: new DwgViewerOptions { Mode = DwgViewerMode.Scene3D }); Assert.Equal(3, result.ElementCount); Assert.Contains(result.Document.Geometries, geometry => geometry.Topology == IOScene.SceneTopology.Lines); Assert.Contains(result.Document.Geometries, geometry => geometry.Topology == IOScene.SceneTopology.Points); 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); @@ -104,7 +148,7 @@ public void SaveViewer_TitleFollowsTheScene() { string htmlPath = Path.Combine(_directory, "drawing.html"); - DwgViewerExport.SaveViewer(SampleDrawing(), htmlPath); + DwgViewerExport.SaveViewer(SampleDrawing(), htmlPath, viewerOptions: new DwgViewerOptions { Mode = DwgViewerMode.Scene3D }); string html = File.ReadAllText(htmlPath); Assert.Contains("drawing.html", html, StringComparison.Ordinal); From 33365c47d9f1fda1988c86304ee3df84fb37243b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:46:25 +0000 Subject: [PATCH 3/6] Bump IOScene.Formats from 0.1.0-preview.1 to 0.1.0-preview.2 --- updated-dependencies: - dependency-name: IOScene.Formats dependency-version: 0.1.0-preview.2 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 02fe636..2fa422d 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -13,7 +13,7 @@ - + From caead3aa97a7240fbf25f605bee80345fa3d1b84 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:46:49 +0000 Subject: [PATCH 4/6] Bump IOViewer from 0.3.1 to 0.4.2 --- updated-dependencies: - dependency-name: IOViewer dependency-version: 0.4.2 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 02fe636..deeddfd 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -15,7 +15,7 @@ - + From 31e288f26384eabb4d660b50b3a32492049bc51d Mon Sep 17 00:00:00 2001 From: mahach666 Date: Wed, 2 Dec 2026 12:52:45 +0300 Subject: [PATCH 5/6] Keep the published scene API and default HTML viewer --- .github/workflows/ci.yml | 1 + CHANGELOG.md | 8 +-- CONTRIBUTING.md | 5 +- Directory.Packages.props | 3 +- DwgIO.slnx | 1 + README.md | 11 +-- docs/public-api.md | 12 ++-- src/DwgIO.Cli/DwgIO.Cli.csproj | 1 - src/DwgIO.Cli/Export/DwgViewerExport.cs | 22 ++---- src/DwgIO.Cli/Export/DwgViewerOptions.cs | 6 +- src/DwgIO.Cli/Program.cs | 5 +- .../DwgIO.Scene.Adapter.csproj | 27 ++++++++ .../DwgSceneOptions.cs | 0 .../DwgSceneReader.cs | 0 .../DwgSceneResult.cs | 0 .../Compatibility}/DwgSceneExport.cs | 3 +- .../Compatibility}/DwgSvgExporter.cs | 3 +- .../Compatibility}/DwgSvgOptions.cs | 2 +- .../Compatibility/DwgViewerExport.cs | 67 +++++++++++++++++++ .../Compatibility}/ViewerMeshGeometry.cs | 4 +- src/DwgIO.Scene/DwgIO.Scene.csproj | 21 +++--- src/DwgIO.Scene/TypeForwarders.cs | 6 ++ tests/DwgIO.Tests/CoreStandardTests.cs | 6 +- tests/DwgIO.Tests/DwgSceneExportTests.cs | 1 - tests/DwgIO.Tests/DwgSceneReaderTests.cs | 2 +- tests/DwgIO.Tests/DwgSvgExporterTests.cs | 2 +- tests/DwgIO.Tests/DwgViewerExportTests.cs | 11 ++- 27 files changed, 157 insertions(+), 73 deletions(-) create mode 100644 src/DwgIO.Scene.Adapter/DwgIO.Scene.Adapter.csproj rename src/{DwgIO.Scene => DwgIO.Scene.Adapter}/DwgSceneOptions.cs (100%) rename src/{DwgIO.Scene => DwgIO.Scene.Adapter}/DwgSceneReader.cs (100%) rename src/{DwgIO.Scene => DwgIO.Scene.Adapter}/DwgSceneResult.cs (100%) rename src/{DwgIO.Cli/Export => DwgIO.Scene/Compatibility}/DwgSceneExport.cs (99%) rename src/{DwgIO.Cli/Export => DwgIO.Scene/Compatibility}/DwgSvgExporter.cs (99%) rename src/{DwgIO.Cli/Export => DwgIO.Scene/Compatibility}/DwgSvgOptions.cs (97%) create mode 100644 src/DwgIO.Scene/Compatibility/DwgViewerExport.cs rename src/{DwgIO.Cli/Export => DwgIO.Scene/Compatibility}/ViewerMeshGeometry.cs (96%) create mode 100644 src/DwgIO.Scene/TypeForwarders.cs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9bfe51e..9de414f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -42,4 +42,5 @@ jobs: 8.0.x 10.0.x - run: dotnet build src/DwgIO/DwgIO.csproj -c Release -p:BuildNativeCoreOnly=true --artifacts-path native-core-check + - run: dotnet build src/DwgIO.Scene.Adapter/DwgIO.Scene.Adapter.csproj -c Release -p:BuildNativeCoreOnly=true --artifacts-path native-core-check - run: dotnet build src/DwgIO.Scene/DwgIO.Scene.csproj -c Release -p:BuildNativeCoreOnly=true --artifacts-path native-core-check diff --git a/CHANGELOG.md b/CHANGELOG.md index f5413b9..1828ba5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,14 +12,12 @@ API between minor releases. - `DwgDocument`: `SourcePath`, `OpenAsync` (path and stream overloads), `ReleaseSectionBuffers()`, `SaveJson` and `ToJson`. - `DwgExitCodes` public constants matching the CLI exit codes. - `DwgSceneReader.Read(Stream, ...)` and `DwgSceneOptions.ReadProgress`. -- AutoCAD-style 2D HTML viewer (`DwgViewerMode.Cad2D`, default for `.html` exports): crisp top-down vector canvas, +- AutoCAD-style 2D HTML viewer (`--mode 2d`): top-down vector canvas, Black / Slate / Light themes (`--bg`), adaptive ACI colour 7, grid, UCS icon, crosshair, coordinate readout, - entity search/filter and properties palette; `--mode 3d` retains the IOViewer WebGL 3D export. + entity search/filter and properties palette. HTML defaults to the IOViewer WebGL 3D export. - `--unit` support on direct `.obj`, `.glb` and `.html` CLI exports, and input/output collision checks across CLI commands. -### Changed (breaking) -- Unified `DwgIO.Scene` as the pure `IOScene` adapter (matching `RvtIO.Scene` and `NwcIO.Scene`), removing `DwgIO.Scene.Adapter`. -- Moved `DwgSceneExport`, `DwgSvgExporter`, `DwgSvgOptions` and `DwgViewerExport` into `DwgIO.Cli` (`DwgIO.Export` namespace) so `DwgIO.Scene` has no dependency on `IOViewer` or `IOScene.Formats`. +### Changed - Updated package dependencies to `IOScene` `[0.1.2, 0.2.0-0.0)`, `IOScene.Formats` `0.1.0-preview.2` and `IOViewer` `0.4.2`. ## [0.5.0] - 2026-11-20 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ef5896c..bebbc11 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -56,8 +56,8 @@ The library is in `src/DwgIO`, the CLI in `src/DwgIO.Cli`, and tests in `tests/DwgIO.Tests`. The engine owns DWG reading, its model and the JSON representation of the decoded drawing. -`DwgIO.Scene` uses the public API of `DwgIO` and the IOScene contract (matching `RvtIO.Scene` and `NwcIO.Scene`). -OBJ, GLB, SVG and standalone HTML output live in `DwgIO.Cli` alongside the command line interface. +`DwgIO.Scene.Adapter` uses the public API of `DwgIO` and the IOScene contract. +`DwgIO.Scene` keeps the existing scene API and OBJ, GLB, SVG and 3D HTML exporters. The 2D HTML viewer lives in `DwgIO.Cli`. Output file replacement and export diagnostics belong to the writers. CI also builds the engine and scene adapter without the compatibility output code or its dependencies. @@ -65,6 +65,7 @@ Run the compile check with a separate artifact directory. ```sh dotnet build src/DwgIO/DwgIO.csproj -c Release -p:BuildNativeCoreOnly=true --artifacts-path ./artifacts/native-core-check +dotnet build src/DwgIO.Scene.Adapter/DwgIO.Scene.Adapter.csproj -c Release -p:BuildNativeCoreOnly=true --artifacts-path ./artifacts/native-core-check dotnet build src/DwgIO.Scene/DwgIO.Scene.csproj -c Release -p:BuildNativeCoreOnly=true --artifacts-path ./artifacts/native-core-check ``` diff --git a/Directory.Packages.props b/Directory.Packages.props index ddbfa87..67f779b 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -10,8 +10,7 @@ - + diff --git a/DwgIO.slnx b/DwgIO.slnx index 5cd14c6..a4ceab2 100644 --- a/DwgIO.slnx +++ b/DwgIO.slnx @@ -1,5 +1,6 @@ + diff --git a/README.md b/README.md index bb53bb0..93ded99 100644 --- a/README.md +++ b/README.md @@ -12,10 +12,10 @@ DwgIO is a .NET library and command line tool that reads Autodesk AutoCAD drawin - Parses drawing metadata: summary information with custom properties and dates, application information, file dependencies and the embedded thumbnail preview. - 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. +- Converts a drawing into a neutral [IOScene](https://www.nuget.org/packages/IOScene) scene document (`DwgIO.Scene.Adapter` 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) through the CLI. - Draws model space to SVG (`dwgio svg`): LINE, CIRCLE, ARC and POINT in the top view, in their ACI colours. -- Writes a standalone interactive HTML viewer (`.html`): defaults to an AutoCAD-style 2D CAD canvas (dark model-space background, orthographic top view, ACI colours, entity selection & properties), with `--mode 3d` for the WebGL viewer of [IOViewer](https://github.com/IOExtend/IOViewer). +- Writes a standalone interactive [IOViewer](https://github.com/IOExtend/IOViewer) HTML file. Use `--mode 2d` for the AutoCAD-style top view. ## Install @@ -79,11 +79,11 @@ 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 HTML viewer (AutoCAD-style 2D CAD view by default, or `--mode 3d` for WebGL 3D): +Open the drawing in the standalone 3D viewer, or choose the AutoCAD-style top view with `--mode 2d`: ```sh dwgio drawing.dwg drawing.html -dwgio drawing.dwg drawing-slate.html --bg slate +dwgio drawing.dwg drawing-slate.html --mode 2d --bg slate dwgio drawing.dwg drawing-3d.html --mode 3d ``` @@ -145,7 +145,8 @@ foreach (var entity in doc.Entities) The JSON export is `DwgJsonExporter` in the `DwgIO.Json` namespace. See [Getting started](docs/getting-started.md) and [Public API](docs/public-api.md) for the supported types. -`DwgSceneReader` converts a drawing into an `IOScene.SceneDocument`, the neutral model shared with RvtIO and NwcIO (`DwgIO.Scene` package). +`DwgSceneReader` converts a drawing into an `IOScene.SceneDocument`, the neutral model shared with RvtIO and NwcIO. +Install `DwgIO.Scene.Adapter` for conversion or `DwgIO.Scene` for conversion and the existing export APIs. ```csharp using DwgIO.Scene; diff --git a/docs/public-api.md b/docs/public-api.md index 8173561..e3fc6d9 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -64,8 +64,8 @@ For `appInfoHistory`, the export reports the byte size. Section bytes can be emb ## Scene conversion (`DwgIO.Scene`) -Install `DwgIO.Scene` to turn a drawing into a neutral [IOScene](https://www.nuget.org/packages/IOScene) -scene document. Like `RvtIO.Scene` and `NwcIO.Scene`, `DwgIO.Scene` depends only on `DwgIO` and `IOScene`. +Install `DwgIO.Scene.Adapter` to turn a drawing into a neutral [IOScene](https://www.nuget.org/packages/IOScene) +scene document. The adapter depends on `DwgIO` and `IOScene`. `DwgIO.Scene` includes the adapter and the existing exporter APIs. It produces one model per drawing and one element per decoded entity, with its handle as `SourceId`, line and point geometry in metres, ACI colours on placements and a report in `DwgSceneResult.Diagnostics`. @@ -87,11 +87,11 @@ IOScene JSON with its original line and point topology. ## CLI Exporters (`dwgio`) -`DwgIO.Cli` bundles the exchange exporters (`DwgSceneExport` for OBJ/GLB via `IOScene.Formats`, `DwgSvgExporter` for SVG, -and `DwgViewerExport` for standalone HTML): +`DwgIO.Scene` provides `DwgSceneExport` for OBJ/GLB, `DwgSvgExporter` for SVG and `DwgViewerExport` for standalone 3D HTML. +The CLI uses these exporters and adds a 2D HTML viewer: -- `dwgio drawing.dwg drawing.html` defaults to an AutoCAD-style 2D CAD canvas (`--mode 2d`, `--bg black|slate|light`): orthographic top view, crisp vector rendering of LINE, CIRCLE, ARC and POINT, ACI colours (white on dark backgrounds, black on light), pan/zoom, coordinate readout and entity properties inspector. -- `dwgio drawing.dwg drawing.html --mode 3d` exports the interactive 3D WebGL viewer via [IOViewer](https://github.com/IOExtend/IOViewer). +- `dwgio drawing.dwg drawing.html` exports the interactive 3D WebGL viewer via [IOViewer](https://github.com/IOExtend/IOViewer). You can also pass `--mode 3d`. +- `dwgio drawing.dwg drawing.html --mode 2d` exports an AutoCAD-style top view. Use `--bg black|slate|light` to set its background. - `dwgio drawing.dwg out.obj --unit mm` and `dwgio drawing.dwg out.glb --unit mm` pass `--unit` to the scene converter. ## Diagnostics diff --git a/src/DwgIO.Cli/DwgIO.Cli.csproj b/src/DwgIO.Cli/DwgIO.Cli.csproj index 6b4e844..0c3dbc8 100644 --- a/src/DwgIO.Cli/DwgIO.Cli.csproj +++ b/src/DwgIO.Cli/DwgIO.Cli.csproj @@ -16,7 +16,6 @@ - diff --git a/src/DwgIO.Cli/Export/DwgViewerExport.cs b/src/DwgIO.Cli/Export/DwgViewerExport.cs index bfccaa1..916a95a 100644 --- a/src/DwgIO.Cli/Export/DwgViewerExport.cs +++ b/src/DwgIO.Cli/Export/DwgViewerExport.cs @@ -7,7 +7,7 @@ namespace DwgIO.Export; /// /// Exports a drawing as a standalone interactive HTML viewer: either an AutoCAD-style 2D vector canvas -/// (, default) or a 3D WebGL viewer generated by +/// () or a 3D WebGL viewer generated by /// IOViewer (). /// public static class DwgViewerExport @@ -16,7 +16,7 @@ public static class DwgViewerExport /// The drawing, for example from . /// Path to the HTML file. /// Scene conversion options; null uses the defaults. - /// Viewer mode and display options; null defaults to . + /// Viewer mode and display options; null defaults to . /// The conversion report. is the IOScene document for the drawing. public static DwgSceneResult SaveViewer( DwgDocument document, @@ -56,22 +56,8 @@ public static DwgSceneResult SaveViewer( } /// Writes a 3D IOViewer HTML file from an existing . - public static void WriteViewer(SceneDocument scene, string htmlPath, HtmlViewerOptions? viewerOptions = null) - { - ArgumentNullException.ThrowIfNull(scene); - ArgumentException.ThrowIfNullOrEmpty(htmlPath); - if (viewerOptions is null) - { - viewerOptions = new HtmlViewerOptions { Title = scene.Title }; - } - else if (string.IsNullOrEmpty(viewerOptions.Title)) - { - viewerOptions.Title = scene.Title; - } - - var drawableScene = ViewerMeshGeometry.Adapt(scene); - AtomicOutput.Write(htmlPath, stream => HtmlViewerExporter.Export(drawableScene, stream, viewerOptions)); - } + public static void WriteViewer(SceneDocument scene, string htmlPath, HtmlViewerOptions? viewerOptions = null) => + Scene.DwgViewerExport.WriteViewer(scene, htmlPath, viewerOptions); private static DwgSceneOptions ViewerOptionsFor(string path, DwgSceneOptions? options) { diff --git a/src/DwgIO.Cli/Export/DwgViewerOptions.cs b/src/DwgIO.Cli/Export/DwgViewerOptions.cs index 295c8f8..5dfebe1 100644 --- a/src/DwgIO.Cli/Export/DwgViewerOptions.cs +++ b/src/DwgIO.Cli/Export/DwgViewerOptions.cs @@ -5,7 +5,7 @@ namespace DwgIO.Export; /// Presentation mode for standalone HTML viewer exports. public enum DwgViewerMode { - /// AutoCAD-style 2D top-down vector canvas viewer (default for DWG drawings). + /// AutoCAD-style 2D top-down vector canvas viewer. Cad2D, /// Interactive 3D WebGL viewer generated by IOViewer. @@ -28,8 +28,8 @@ public enum DwgCadTheme /// Options for . public sealed class DwgViewerOptions { - /// Viewer mode: (default) or . - public DwgViewerMode Mode { get; set; } = DwgViewerMode.Cad2D; + /// Viewer mode: or (default). + public DwgViewerMode Mode { get; set; } = DwgViewerMode.Scene3D; /// Document title shown in the browser tab and header; defaults to the file or scene title. public string? Title { get; set; } diff --git a/src/DwgIO.Cli/Program.cs b/src/DwgIO.Cli/Program.cs index 8e16b47..f570438 100644 --- a/src/DwgIO.Cli/Program.cs +++ b/src/DwgIO.Cli/Program.cs @@ -7,6 +7,7 @@ using DwgIO.Model; using DwgIO.Output; using DwgIO.Scene; +using DwgViewerExport = DwgIO.Export.DwgViewerExport; using IOScene; namespace DwgIO.Cli; @@ -105,7 +106,7 @@ dwgio inspect Print version + section table dwgio [--unit u] [--mode 2d|3d] [--bg black|slate|light] Export metadata, section catalog and entities to JSON, or the scene to OBJ (.obj), GLB (.glb) or a standalone - interactive HTML viewer (.html; 2D AutoCAD mode by default) + interactive HTML viewer (.html; 3D IOViewer by default) 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 @@ -372,7 +373,7 @@ internal static int ExportDocument( { var viewerOptions = new DwgViewerOptions { - Mode = mode ?? DwgViewerMode.Cad2D, + Mode = mode ?? DwgViewerMode.Scene3D, Theme = theme ?? DwgCadTheme.Black, }; var htmlResult = DwgViewerExport.SaveViewer(doc, target, sceneOptions, viewerOptions); diff --git a/src/DwgIO.Scene.Adapter/DwgIO.Scene.Adapter.csproj b/src/DwgIO.Scene.Adapter/DwgIO.Scene.Adapter.csproj new file mode 100644 index 0000000..e1c56ab --- /dev/null +++ b/src/DwgIO.Scene.Adapter/DwgIO.Scene.Adapter.csproj @@ -0,0 +1,27 @@ + + + + Converts a DWG drawing read by DwgIO to an IOScene document. + dwg;autocad;cad;ioscene + + $(NoWarn);NU5104 + true + + + + false + + + + + + + + + + + + + + + diff --git a/src/DwgIO.Scene/DwgSceneOptions.cs b/src/DwgIO.Scene.Adapter/DwgSceneOptions.cs similarity index 100% rename from src/DwgIO.Scene/DwgSceneOptions.cs rename to src/DwgIO.Scene.Adapter/DwgSceneOptions.cs diff --git a/src/DwgIO.Scene/DwgSceneReader.cs b/src/DwgIO.Scene.Adapter/DwgSceneReader.cs similarity index 100% rename from src/DwgIO.Scene/DwgSceneReader.cs rename to src/DwgIO.Scene.Adapter/DwgSceneReader.cs diff --git a/src/DwgIO.Scene/DwgSceneResult.cs b/src/DwgIO.Scene.Adapter/DwgSceneResult.cs similarity index 100% rename from src/DwgIO.Scene/DwgSceneResult.cs rename to src/DwgIO.Scene.Adapter/DwgSceneResult.cs diff --git a/src/DwgIO.Cli/Export/DwgSceneExport.cs b/src/DwgIO.Scene/Compatibility/DwgSceneExport.cs similarity index 99% rename from src/DwgIO.Cli/Export/DwgSceneExport.cs rename to src/DwgIO.Scene/Compatibility/DwgSceneExport.cs index 6972ae2..133cb5b 100644 --- a/src/DwgIO.Cli/Export/DwgSceneExport.cs +++ b/src/DwgIO.Scene/Compatibility/DwgSceneExport.cs @@ -1,11 +1,10 @@ using System.Security.Cryptography; using System.Text; using DwgIO.Output; -using DwgIO.Scene; using IOScene; using IOScene.Formats; -namespace DwgIO.Export; +namespace DwgIO.Scene; /// /// Exports a drawing to the mesh exchange formats written by : Wavefront OBJ diff --git a/src/DwgIO.Cli/Export/DwgSvgExporter.cs b/src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs similarity index 99% rename from src/DwgIO.Cli/Export/DwgSvgExporter.cs rename to src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs index 45c67a7..2dd4e42 100644 --- a/src/DwgIO.Cli/Export/DwgSvgExporter.cs +++ b/src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs @@ -2,9 +2,8 @@ using System.Xml; using DwgIO.Model; using DwgIO.Output; -using DwgIO.Scene; -namespace DwgIO.Export; +namespace DwgIO.Scene; /// /// Draws the model space of a drawing as SVG: LINE, CIRCLE, ARC and POINT entities in the top view, with the diff --git a/src/DwgIO.Cli/Export/DwgSvgOptions.cs b/src/DwgIO.Scene/Compatibility/DwgSvgOptions.cs similarity index 97% rename from src/DwgIO.Cli/Export/DwgSvgOptions.cs rename to src/DwgIO.Scene/Compatibility/DwgSvgOptions.cs index 4da955d..15ddff7 100644 --- a/src/DwgIO.Cli/Export/DwgSvgOptions.cs +++ b/src/DwgIO.Scene/Compatibility/DwgSvgOptions.cs @@ -1,4 +1,4 @@ -namespace DwgIO.Export; +namespace DwgIO.Scene; /// Options of the SVG export of model space. public sealed class DwgSvgOptions diff --git a/src/DwgIO.Scene/Compatibility/DwgViewerExport.cs b/src/DwgIO.Scene/Compatibility/DwgViewerExport.cs new file mode 100644 index 0000000..dc16fc1 --- /dev/null +++ b/src/DwgIO.Scene/Compatibility/DwgViewerExport.cs @@ -0,0 +1,67 @@ +using IOViewer.Exporters; +using DwgIO.Output; +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) + { + viewerOptions = new HtmlViewerOptions { Title = scene.Title }; + } + else if (string.IsNullOrEmpty(viewerOptions.Title)) + { + viewerOptions.Title = scene.Title; + } + + var drawableScene = ViewerMeshGeometry.Adapt(scene); + AtomicOutput.Write(htmlPath, stream => HtmlViewerExporter.Export(drawableScene, stream, 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/src/DwgIO.Cli/Export/ViewerMeshGeometry.cs b/src/DwgIO.Scene/Compatibility/ViewerMeshGeometry.cs similarity index 96% rename from src/DwgIO.Cli/Export/ViewerMeshGeometry.cs rename to src/DwgIO.Scene/Compatibility/ViewerMeshGeometry.cs index eac28a6..355ef95 100644 --- a/src/DwgIO.Cli/Export/ViewerMeshGeometry.cs +++ b/src/DwgIO.Scene/Compatibility/ViewerMeshGeometry.cs @@ -1,10 +1,10 @@ using IOScene; -namespace DwgIO.Export; +namespace DwgIO.Scene; internal static class ViewerMeshGeometry { - // IOViewer 0.4.2 draws triangles and point clouds; convert lines and drawing points to display meshes in Scene3D mode. + // shortcut: IOViewer 0.3.1 draws triangles only; use thin display meshes until it supports lines and points. public static SceneDocument Adapt(SceneDocument scene) { if (!scene.Geometries.Any(g => g.Topology is SceneTopology.Lines or SceneTopology.Points)) diff --git a/src/DwgIO.Scene/DwgIO.Scene.csproj b/src/DwgIO.Scene/DwgIO.Scene.csproj index c54318e..a5d8f87 100644 --- a/src/DwgIO.Scene/DwgIO.Scene.csproj +++ b/src/DwgIO.Scene/DwgIO.Scene.csproj @@ -1,11 +1,8 @@ - true - DwgIO.Scene - Converts a DWG drawing read by DwgIO into an IOScene scene document. - dwg;autocad;cad;ioscene;scene - + Preserves the DwgIO scene API and writes DWG drawings as OBJ, GLB, SVG and standalone HTML. + dwg;autocad;cad;ioscene;export $(NoWarn);NU5104 true @@ -14,14 +11,20 @@ false + + + + + - - - - + + + + diff --git a/src/DwgIO.Scene/TypeForwarders.cs b/src/DwgIO.Scene/TypeForwarders.cs new file mode 100644 index 0000000..ae3c119 --- /dev/null +++ b/src/DwgIO.Scene/TypeForwarders.cs @@ -0,0 +1,6 @@ +using System.Runtime.CompilerServices; +using DwgIO.Scene; + +[assembly: TypeForwardedTo(typeof(DwgSceneReader))] +[assembly: TypeForwardedTo(typeof(DwgSceneOptions))] +[assembly: TypeForwardedTo(typeof(DwgSceneResult))] diff --git a/tests/DwgIO.Tests/CoreStandardTests.cs b/tests/DwgIO.Tests/CoreStandardTests.cs index e3f24d3..fc10716 100644 --- a/tests/DwgIO.Tests/CoreStandardTests.cs +++ b/tests/DwgIO.Tests/CoreStandardTests.cs @@ -159,7 +159,7 @@ public void Cli_DirectGlbAndObjRespectUnitOption() } [Fact] - public void Cli_HtmlMode2dDefaultAnd3dOption() + public void Cli_HtmlDefaultsTo3dAndAccepts2d() { string fixture = TestFiles.PublicDrawing("primitives-ac1032.dwg"); string html2d = Path.Combine(_directory, "cad.html"); @@ -167,14 +167,14 @@ public void Cli_HtmlMode2dDefaultAnd3dOption() using var o1 = new StringWriter(); using var e1 = new StringWriter(); - Assert.Equal(DwgExitCodes.Ok, Program.Run([fixture, html2d, "--bg", "slate"], o1, e1)); + Assert.Equal(DwgExitCodes.Ok, Program.Run([fixture, html2d, "--mode", "2d", "--bg", "slate"], o1, e1)); string cadContent = File.ReadAllText(html2d); Assert.Contains("id=\"dwgio-cad-data\"", cadContent, StringComparison.Ordinal); Assert.Contains("data-theme=\"slate\"", cadContent, StringComparison.Ordinal); using var o2 = new StringWriter(); using var e2 = new StringWriter(); - Assert.Equal(DwgExitCodes.Ok, Program.Run([fixture, html3d, "--mode", "3d"], o2, e2)); + Assert.Equal(DwgExitCodes.Ok, Program.Run([fixture, html3d], o2, e2)); Assert.Contains("id=\"ioviewer-meta\"", File.ReadAllText(html3d), StringComparison.Ordinal); using var o3 = new StringWriter(); diff --git a/tests/DwgIO.Tests/DwgSceneExportTests.cs b/tests/DwgIO.Tests/DwgSceneExportTests.cs index a2be83d..9402f1e 100644 --- a/tests/DwgIO.Tests/DwgSceneExportTests.cs +++ b/tests/DwgIO.Tests/DwgSceneExportTests.cs @@ -1,4 +1,3 @@ -using DwgIO.Export; using DwgIO.Model; using DwgIO.Scene; using IOScene.Formats; diff --git a/tests/DwgIO.Tests/DwgSceneReaderTests.cs b/tests/DwgIO.Tests/DwgSceneReaderTests.cs index eba7606..b818b4b 100644 --- a/tests/DwgIO.Tests/DwgSceneReaderTests.cs +++ b/tests/DwgIO.Tests/DwgSceneReaderTests.cs @@ -44,7 +44,7 @@ private static DwgEntity Entity(ulong handle, DwgEntityKind kind, string typeNam public void SceneAdapterDependsOnlyOnEngineAndIoScene() { var adapter = typeof(DwgSceneReader).Assembly; - Assert.Equal("DwgIO.Scene", adapter.GetName().Name); + Assert.Equal("DwgIO.Scene.Adapter", adapter.GetName().Name); var references = adapter.GetReferencedAssemblies().Select(a => a.Name).ToArray(); Assert.Contains("DwgIO", references); Assert.Contains("IOScene", references); diff --git a/tests/DwgIO.Tests/DwgSvgExporterTests.cs b/tests/DwgIO.Tests/DwgSvgExporterTests.cs index aa64c55..1feb5b6 100644 --- a/tests/DwgIO.Tests/DwgSvgExporterTests.cs +++ b/tests/DwgIO.Tests/DwgSvgExporterTests.cs @@ -1,6 +1,6 @@ using System.Text; using System.Xml; -using DwgIO.Export; +using DwgIO.Scene; using DwgIO.Model; using Xunit; diff --git a/tests/DwgIO.Tests/DwgViewerExportTests.cs b/tests/DwgIO.Tests/DwgViewerExportTests.cs index 3313bb3..fa0a17a 100644 --- a/tests/DwgIO.Tests/DwgViewerExportTests.cs +++ b/tests/DwgIO.Tests/DwgViewerExportTests.cs @@ -73,11 +73,11 @@ private static DwgDocument SampleDrawing() => CreateDocument( }); [Fact] - public void SaveViewer_DefaultMode_WritesAutoCad2DHtml() + public void SaveViewer_Cad2DMode_WritesAutoCad2DHtml() { string htmlPath = Path.Combine(_directory, "drawing.html"); - var result = DwgViewerExport.SaveViewer(SampleDrawing(), htmlPath); + var result = DwgViewerExport.SaveViewer(SampleDrawing(), htmlPath, viewerOptions: new DwgViewerOptions { Mode = DwgViewerMode.Cad2D }); Assert.Equal(3, result.ElementCount); string html = File.ReadAllText(htmlPath); @@ -116,16 +116,13 @@ public void SaveViewer_Cad2D_ThemeOptionSetsHtmlAttributeAndPayload() } [Fact] - public void SaveViewer_Scene3DMode_WritesSelfContainedIOViewerHtml() + public void SaveViewer_CompatibilityApi_WritesSelfContainedIOViewerHtml() { string htmlPath = Environment.GetEnvironmentVariable("DWGIO_VIEWER_DEBUG_PATH") is { Length: > 0 } debug ? debug : Path.Combine(_directory, "drawing-3d.html"); - var result = DwgViewerExport.SaveViewer( - SampleDrawing(), - htmlPath, - viewerOptions: new DwgViewerOptions { Mode = DwgViewerMode.Scene3D }); + var result = Scene.DwgViewerExport.SaveViewer(SampleDrawing(), htmlPath); Assert.Equal(3, result.ElementCount); Assert.Contains(result.Document.Geometries, geometry => geometry.Topology == IOScene.SceneTopology.Lines); From 99a18010058975700a9822b2bc36dec3dde75b4d Mon Sep 17 00:00:00 2001 From: mahach666 Date: Wed, 2 Dec 2026 13:03:58 +0300 Subject: [PATCH 6/6] Document the scene adapter in the API reference --- docfx.json | 1 + 1 file changed, 1 insertion(+) diff --git a/docfx.json b/docfx.json index 8a3251b..58c6c02 100644 --- a/docfx.json +++ b/docfx.json @@ -3,6 +3,7 @@ { "src": [ { "src": "src/DwgIO", "files": ["DwgIO.csproj"] }, + { "src": "src/DwgIO.Scene.Adapter", "files": ["DwgIO.Scene.Adapter.csproj"] }, { "src": "src/DwgIO.Scene", "files": ["DwgIO.Scene.csproj"] } ], "dest": "docs/api",