diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9de414f..9dc3be2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,7 +13,7 @@ jobs: strategy: fail-fast: false matrix: - os: [windows-latest, ubuntu-latest, macos-latest] + os: [windows-latest, ubuntu-latest, macos-15] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v7 diff --git a/Directory.Packages.props b/Directory.Packages.props index 67f779b..bda56ee 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -13,7 +13,7 @@ - + diff --git a/README.md b/README.md index fa7f8b2..ac9c3ad 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,7 @@ 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 the standalone 3D viewer, or choose the AutoCAD-style top view with `--mode 2d`: +Open the drawing in the standalone 3D viewer, or choose the AutoCAD-style top view with `--mode 2d`. Use `--mode auto` to start in 2D when the drawing has paper sheets or flat linework: ```sh dwgio drawing.dwg drawing.html diff --git a/docs/public-api.md b/docs/public-api.md index 9031880..21ac1a3 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -95,8 +95,10 @@ The CLI uses these exporters and adds a 2D HTML viewer: - `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 drawing.html --mode auto` opens paper sheets or flat linework in 2D. Paper sheets remain selectable when the viewer starts in 3D model space. - `dwgio drawing.dwg out.obj --unit mm` and `dwgio drawing.dwg out.glb --unit mm` pass `--unit` to the scene converter. - The scene, OBJ, GLB and HTML commands use metres by default. Pass `--unit auto` to use a supported `$INSUNITS`. +- External DWG references are skipped by default. Library callers can set `DwgSceneOptions.ResolveXrefs = true` to read trusted sibling DWG files by name. ## Diagnostics diff --git a/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs b/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs deleted file mode 100644 index 332423c..0000000 --- a/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs +++ /dev/null @@ -1,1614 +0,0 @@ -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); - if (document.HeaderVariables is { } header) - { - w.WriteNumber("pdmode", header.PdMode); - w.WriteNumber("pdsize", double.IsFinite(header.PdSize) ? header.PdSize : 0.0); - w.WriteString("insunits", header.InsUnits.ToString()); - } - - w.WriteString("theme", options.Theme switch - { - DwgCadTheme.Slate => "slate", - DwgCadTheme.Light => "light", - _ => "black", - }); - w.WriteNumber("totalEntities", document.Entities.Count); - - w.WriteStartArray("layers"); - foreach (var layer in document.Layers) - { - w.WriteStartObject(); - w.WriteString("handle", layer.Handle.ToString("X", CultureInfo.InvariantCulture)); - w.WriteString("name", layer.Name); - w.WriteNumber("colorIndex", layer.ColorIndex); - bool layerAdaptive = layer.TrueColorRgb is null && IsAdaptiveColor(layer.ColorIndex); - w.WriteBoolean("isAdaptiveColor", layerAdaptive); - w.WriteString("rgb", FormatFixedRgb(layer.ColorIndex, layer.TrueColorRgb)); - w.WriteBoolean("isOn", layer.IsOn); - w.WriteBoolean("isFrozen", layer.IsFrozen); - w.WriteBoolean("isLocked", layer.IsLocked); - w.WriteBoolean("visible", layer.IsVisible); - w.WriteEndObject(); - } - - w.WriteEndArray(); - - 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; - } - - string? textValue = entity.PlainText; - if (!TryExpandBounds(entity, textValue, ref minX, ref minY, ref maxX, ref maxY, out var ellipseMinor)) - { - continue; - } - - drawnCount++; - int effColorIndex = entity.EffectiveColorIndex; - uint? effTrueColor = entity.EffectiveTrueColorRgb; - w.WriteStartObject(); - w.WriteString("handle", entity.Handle.ToString("X", CultureInfo.InvariantCulture)); - w.WriteString("type", entity.TypeName); - w.WriteString("kind", entity.Kind.ToString().ToLowerInvariant()); - w.WriteString("layer", entity.LayerName ?? "0"); - if (entity.LayerHandle is { } layerHandle) - { - w.WriteString("layerHandle", layerHandle.ToString("X", CultureInfo.InvariantCulture)); - } - - w.WriteNumber("colorIndex", effColorIndex); - if (effColorIndex != entity.ColorIndex) - { - w.WriteNumber("rawColorIndex", entity.ColorIndex); - } - - bool adaptive = effTrueColor is null && IsAdaptiveColor(effColorIndex); - w.WriteBoolean("isAdaptiveColor", adaptive); - w.WriteString("rgb", FormatFixedRgb(effColorIndex, effTrueColor)); - if (effTrueColor is { } trueColor) - { - w.WriteString("trueColorRgb", string.Create(CultureInfo.InvariantCulture, $"#{trueColor:X6}")); - } - - w.WriteNumber("lineTypeScale", double.IsFinite(entity.LineTypeScale) ? Math.Round(entity.LineTypeScale, 6) : 1.0); - w.WriteBoolean("modelSpace", entity.IsModelSpace); - if (textValue is not null) - { - w.WriteString("text", textValue); - var (column, row) = TextPlacement.Alignment(entity.Kind, entity.Geometry); - w.WriteNumber("textColumn", column); - w.WriteNumber("textRow", row); - } - - if (ellipseMinor is { } minor) - { - w.WriteNumber("ellipseMinorX", minor.X); - w.WriteNumber("ellipseMinorY", minor.Y); - } - - 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, uint? trueColorRgb) - { - if (trueColorRgb is { } rgb) - { - return string.Create(CultureInfo.InvariantCulture, $"#{rgb:X6}"); - } - - 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, string? text, ref double minX, ref double minY, ref double maxX, ref double maxY, - out (double X, double Y, double Z)? ellipseMinor) - { - ellipseMinor = null; - 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; - case (DwgEntityKind.Polyline, { Length: >= 5 } g): - int count = (g.Length - 2) / 3; - for (int i = 0; i < count; i++) - { - Expand(g[2 + i * 3], g[2 + i * 3 + 1], ref minX, ref minY, ref maxX, ref maxY); - } - - return count > 0; - case (DwgEntityKind.Ellipse, { Length: 12 } g) when EllipseAxes.TryGetMinor(g, out var minor): - ellipseMinor = minor; - double centerX = g[0], centerY = g[1], mx = g[3], my = g[4]; - var (eStart, eSpan) = ArcAngles.Normalize(g[7], g[8]); - for (int i = 0; i <= 32; i++) - { - double a = eStart + eSpan * i / 32; - Expand(centerX + mx * Math.Cos(a) + minor.X * Math.Sin(a), centerY + my * Math.Cos(a) + minor.Y * Math.Sin(a), - ref minX, ref minY, ref maxX, ref maxY); - } - - return true; - case (DwgEntityKind.Solid or DwgEntityKind.Face3d, { Length: 12 } g): - for (int i = 0; i < 4; i++) - { - Expand(g[i * 3], g[i * 3 + 1], ref minX, ref minY, ref maxX, ref maxY); - } - - return true; - case (DwgEntityKind.Ray or DwgEntityKind.XLine, [var rx, var ry, _, _, _, _]): - Expand(rx, ry, ref minX, ref minY, ref maxX, ref maxY); - return true; - case (DwgEntityKind.Text or DwgEntityKind.MText, { Length: >= 5 } g) when g[3] > 0 && text is { Length: > 0 }: - var (column, row) = TextPlacement.Alignment(entity.Kind, g); - var textBounds = TextPlacement.EstimateBounds(g[0], -g[1], g[3], g[4], text, column, row); - Expand(textBounds.MinX, -textBounds.MaxY, ref minX, ref minY, ref maxX, ref maxY); - Expand(textBounds.MaxX, -textBounds.MinY, 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.Cli/Export/DwgViewerExport.cs b/src/DwgIO.Cli/Export/DwgViewerExport.cs index 153e1d9..cdcc506 100644 --- a/src/DwgIO.Cli/Export/DwgViewerExport.cs +++ b/src/DwgIO.Cli/Export/DwgViewerExport.cs @@ -1,4 +1,3 @@ -using DwgIO.Output; using DwgIO.Scene; using IOScene; using IOViewer.Exporters; @@ -6,18 +5,13 @@ namespace DwgIO.Export; /// -/// Exports a drawing as a standalone interactive HTML viewer: either an AutoCAD-style 2D vector canvas -/// () or a 3D WebGL viewer generated by -/// IOViewer (). +/// Exports a drawing as a standalone interactive HTML viewer powered by +/// IOViewer, with integrated 2D CAD mode, +/// sheets, native vector lines and text annotations. /// 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, @@ -27,50 +21,111 @@ public static DwgSceneResult SaveViewer( ArgumentNullException.ThrowIfNull(document); ArgumentException.ThrowIfNullOrEmpty(htmlPath); viewerOptions ??= new DwgViewerOptions(); - var sceneOptions = ViewerOptionsFor(htmlPath, options); + var sceneOptions = ViewerOptionsFor(htmlPath, options, viewerOptions); var result = DwgSceneReader.Read(document, sceneOptions); - if (viewerOptions.Mode == DwgViewerMode.Scene3D) + var htmlOptions = BuildHtmlOptions(result, viewerOptions); + Scene.DwgViewerExport.WriteViewer(result, htmlPath, htmlOptions); + return result; + } + + /// Writes an IOViewer HTML file from an existing . + public static void WriteViewer(SceneDocument scene, string htmlPath, HtmlViewerOptions? viewerOptions = null) => + Scene.DwgViewerExport.WriteViewer(scene, htmlPath, viewerOptions); + + internal static void ExportToStream(DwgDocument document, Stream stream, DwgViewerOptions? viewerOptions = null, string lengthUnit = "m") + { + ArgumentNullException.ThrowIfNull(document); + ArgumentNullException.ThrowIfNull(stream); + viewerOptions ??= new DwgViewerOptions(); + var sceneOptions = new DwgSceneOptions { - 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; - } + LengthUnit = lengthUnit, + ModelKey = string.IsNullOrWhiteSpace(document.Path) ? "drawing.dwg" : Path.GetFileName(document.Path), + IncludePaperSpace = viewerOptions.IncludePaperSpace, + }; + var result = DwgSceneReader.Read(document, sceneOptions); + var htmlOptions = BuildHtmlOptions(result, viewerOptions); + Scene.DwgViewerExport.WriteViewer(result, stream, htmlOptions); + } - WriteViewer(result.Document, htmlPath, html3dOptions); - } - else + private static HtmlViewerOptions BuildHtmlOptions(DwgSceneResult result, DwgViewerOptions viewerOptions) + { + var baseOpts = viewerOptions.Scene3DOptions; + string title = !string.IsNullOrWhiteSpace(viewerOptions.Title) + ? viewerOptions.Title! + : !string.IsNullOrEmpty(baseOpts?.Title) + ? baseOpts!.Title + : result.Document.Title; + + bool hasSheets = result.Sheets.Count > 0; + bool is2D = viewerOptions.Mode switch { - AtomicOutput.Write(htmlPath, stream => DwgCadHtmlViewer.Export(document, stream, viewerOptions, result.LengthUnit ?? sceneOptions.LengthUnit)); - } + DwgViewerMode.Cad2D => true, + DwgViewerMode.Auto => (baseOpts?.Initial2DMode ?? false) || hasSheets || IsFlat2DScene(result.Document), + _ => baseOpts?.Initial2DMode ?? false, + }; + string? bg = baseOpts?.InitialBackground ?? ThemeBackground(viewerOptions, is2D); - return result; + return new HtmlViewerOptions + { + Title = title, + IncludeProperties = baseOpts?.IncludeProperties ?? true, + IncludeViewpoints = baseOpts?.IncludeViewpoints ?? true, + IncludeGrids = baseOpts?.IncludeGrids ?? true, + IncludeTimeLiner = baseOpts?.IncludeTimeLiner ?? true, + IncludeClashes = baseOpts?.IncludeClashes ?? true, + InitialWireframe = baseOpts?.InitialWireframe ?? false, + InitialWhiteMode = baseOpts?.InitialWhiteMode ?? false, + Initial2DMode = is2D, + InitialBackground = bg, + MaxMeshVertices = baseOpts?.MaxMeshVertices ?? int.MaxValue, + }; } - /// Writes a 3D IOViewer HTML file from an existing . - public static void WriteViewer(SceneDocument scene, string htmlPath, HtmlViewerOptions? viewerOptions = null) => - Scene.DwgViewerExport.WriteViewer(scene, htmlPath, viewerOptions); + private static string? ThemeBackground(DwgViewerOptions options, bool is2D) => is2D + ? options.Theme switch + { + DwgCadTheme.Light => "#ffffff", + DwgCadTheme.Slate => "#212830", + _ => "#14171c", + } + : options.Theme switch + { + DwgCadTheme.Light => "#ffffff", + DwgCadTheme.Slate => "#212830", + _ => null, + }; - private static DwgSceneOptions ViewerOptionsFor(string path, DwgSceneOptions? options) + private static bool IsFlat2DScene(SceneDocument scene) { - if (options?.ModelKey is { Length: > 0 }) + if (scene.Geometries.Any(g => g.Topology == SceneTopology.Triangles)) + return false; + + double minZ = double.PositiveInfinity, maxZ = double.NegativeInfinity; + foreach (var geom in scene.Geometries) { - return options; + foreach (var v in geom.Vertices) + { + if (v.Z < minZ) minZ = v.Z; + if (v.Z > maxZ) maxZ = v.Z; + } } + return minZ > maxZ || (maxZ - minZ) <= 1e-3; + } + + private static DwgSceneOptions ViewerOptionsFor(string path, DwgSceneOptions? options, DwgViewerOptions viewerOptions) + { + string key = options?.ModelKey is { Length: > 0 } k ? k : Path.GetFileName(path); return new DwgSceneOptions { LengthUnit = options?.LengthUnit ?? "m", UseDrawingUnits = options?.UseDrawingUnits ?? false, - ModelKey = Path.GetFileName(path), + ExpandBlocks = options?.ExpandBlocks ?? true, + ResolveXrefs = options?.ResolveXrefs ?? false, + IncludePaperSpace = viewerOptions.IncludePaperSpace && (options?.IncludePaperSpace ?? true), + ModelKey = key, ReadProgress = options?.ReadProgress, }; } diff --git a/src/DwgIO.Cli/Export/DwgViewerOptions.cs b/src/DwgIO.Cli/Export/DwgViewerOptions.cs index 5dfebe1..647e182 100644 --- a/src/DwgIO.Cli/Export/DwgViewerOptions.cs +++ b/src/DwgIO.Cli/Export/DwgViewerOptions.cs @@ -10,6 +10,9 @@ public enum DwgViewerMode /// Interactive 3D WebGL viewer generated by IOViewer. Scene3D, + + /// Automatically choose 2D CAD view for flat plans or sheets and 3D view for 3D models. + Auto, } /// Initial canvas colour theme for the 2D AutoCAD HTML viewer. @@ -28,7 +31,7 @@ public enum DwgCadTheme /// Options for . public sealed class DwgViewerOptions { - /// Viewer mode: or (default). + /// Viewer mode: (default), , or . public DwgViewerMode Mode { get; set; } = DwgViewerMode.Scene3D; /// Document title shown in the browser tab and header; defaults to the file or scene title. @@ -37,8 +40,8 @@ public sealed class DwgViewerOptions /// 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; } + /// Include Paper Space sheets and floating viewports alongside Model Space (default: true). + public bool IncludePaperSpace { get; set; } = true; /// Options forwarded to IOViewer when is . public HtmlViewerOptions? Scene3DOptions { get; set; } diff --git a/src/DwgIO.Cli/Program.cs b/src/DwgIO.Cli/Program.cs index 3ebcd22..039f78d 100644 --- a/src/DwgIO.Cli/Program.cs +++ b/src/DwgIO.Cli/Program.cs @@ -103,7 +103,7 @@ private static void PrintUsage(TextWriter output) Usage: dwgio inspect Print version + section table - dwgio [--unit u] [--mode 2d|3d] [--bg black|slate|light] + dwgio [--unit u] [--mode 2d|3d|auto] [--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; 3D IOViewer by default) @@ -297,15 +297,16 @@ private static int Export(string[] args, TextWriter output, TextWriter error) case "--mode": if (i + 1 >= args.Length) { - error.WriteLine("error: --mode needs a value (2d or 3d)."); + error.WriteLine("error: --mode needs a value (2d, 3d or auto)."); return DwgExitCodes.Usage; } mode = args[++i].ToLowerInvariant() switch { + "auto" => DwgViewerMode.Auto, "2d" => DwgViewerMode.Cad2D, "3d" => DwgViewerMode.Scene3D, - var bad => throw new UsageException($"unknown viewer mode '{bad}'. Use 2d or 3d."), + var bad => throw new UsageException($"unknown viewer mode '{bad}'. Use auto, 2d or 3d."), }; break; case "--bg": diff --git a/src/DwgIO.Scene.Adapter/DwgSceneOptions.cs b/src/DwgIO.Scene.Adapter/DwgSceneOptions.cs index a40ab1c..3655806 100644 --- a/src/DwgIO.Scene.Adapter/DwgSceneOptions.cs +++ b/src/DwgIO.Scene.Adapter/DwgSceneOptions.cs @@ -31,4 +31,14 @@ public sealed class DwgSceneOptions /// opens the drawing. /// public IProgress? ReadProgress { get; set; } + + /// When true (default), expands INSERT/MINSERT block references into scene geometry. + public bool ExpandBlocks { get; set; } = true; + + /// When true, reads external reference (XREF) files by name from the host drawing's directory. + /// Defaults to false. Enable only when the sibling files are trusted. + public bool ResolveXrefs { get; set; } + + /// When true (default), includes active Paper Space sheets and floating VIEWPORT projections. + public bool IncludePaperSpace { get; set; } = true; } diff --git a/src/DwgIO.Scene.Adapter/DwgSceneReader.cs b/src/DwgIO.Scene.Adapter/DwgSceneReader.cs index 203df03..5194f5a 100644 --- a/src/DwgIO.Scene.Adapter/DwgSceneReader.cs +++ b/src/DwgIO.Scene.Adapter/DwgSceneReader.cs @@ -9,28 +9,20 @@ namespace DwgIO.Scene; /// Converts an AutoCAD drawing, or a read by DwgIO, into a . /// -/// The scene has one : Key and Name are , -/// else the file name; SourceFormat is dwg; Application is the producer from -/// AcDb:AppInfo; CreatedAt is the summary-info creation time in UTC. The drawing's entities become -/// flat scene elements with the handle as ; LINE, CIRCLE, ARC and POINT become -/// line and point geometries, tessellated for the round kinds. Every coordinate is scaled to metres by -/// ; the drawing itself names no unit, so the scene records the choice. +/// Expands INSERT / MINSERT blocks, resolves sibling external references (XREFs), converts +/// Paper Space sheets and floating VIEWPORTs, and maps Model Space and Paper Space text annotations. /// public static class DwgSceneReader { private static readonly string Producer = "DwgIO.Scene " + typeof(DwgSceneReader).Assembly.GetCustomAttribute()!.InformationalVersion.Split('+')[0]; - // A full circle tessellated into 64 segments (5.6 degrees); an arc gets one segment per 5 degrees, at least 8. private const int CircleSegments = 64; private const double ArcRadiansPerSegment = 5.0 * Math.PI / 180.0; private const int MinArcSegments = 8; + private const int MaxInsertDepth = 16; /// Reads the drawing at with and converts it. - /// The drawing file. - /// Conversion options; null uses the defaults. - /// The scene with a report of the conversion. - /// is empty. public static DwgSceneResult Read(string path, DwgSceneOptions? options = null) { ArgumentException.ThrowIfNullOrEmpty(path); @@ -46,14 +38,11 @@ public static DwgSceneResult Read(string path, DwgSceneOptions? options = null) ReleaseSectionBuffers = true, Progress = resolved.ReadProgress, }; - return Convert(DwgDocument.Open(path, readerOptions), key, path, resolved); + var document = DwgDocument.Open(path, readerOptions); + return Convert(document, key, document.SourcePath, 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); @@ -72,15 +61,7 @@ public static DwgSceneResult Read(Stream stream, string? documentName = null, Dw return Convert(DwgDocument.Open(stream, documentName ?? key, readerOptions), key, null, resolved); } - /// - /// Converts , which has no file name, so is - /// required. Give a document opened with the default ; a document read with - /// off has no entities, and the scene holds the drawing without geometry. - /// - /// The document. - /// Conversion options with . - /// The scene with a report of the conversion. - /// is null or empty. + /// Converts an already opened into a . public static DwgSceneResult Read(DwgDocument document, DwgSceneOptions options) { ArgumentNullException.ThrowIfNull(document); @@ -93,163 +74,750 @@ public static DwgSceneResult Read(DwgDocument document, DwgSceneOptions options) return Convert(document, options.ModelKey, document.SourcePath, options); } + /// Tells whether accepts . + public static bool IsSupportedUnit(string unit) => unit is "mm" or "cm" or "m" or "ft" or "in"; + private static DwgSceneResult Convert(DwgDocument document, string key, string? path, DwgSceneOptions options) { - string effectiveUnit = options.LengthUnit; - bool unitAssumed = true; - if (options.UseDrawingUnits && - document.HeaderVariables is { } header && - header.TryGetSceneUnit(out string headerUnit)) + (string effectiveUnit, bool unitAssumed) = ResolveLengthUnit(document, options); + double metresPerUnit = MetresPerUnit(effectiveUnit); + + var ctx = new ConversionContext(document, key, path, options, effectiveUnit, metresPerUnit); + ctx.Build(); + + return new DwgSceneResult + { + Document = ctx.Scene, + Diagnostics = ctx.Diagnostics, + ElementCount = ctx.ElementCount, + ElementsWithGeometry = ctx.ElementsWithGeometry, + EntitiesWithoutGeometry = ctx.WithoutGeometry.Values.Sum(), + LengthUnit = effectiveUnit, + MetresPerUnit = metresPerUnit, + UnitAssumed = unitAssumed, + Annotations = ctx.Annotations, + Sheets = ctx.Sheets, + InitialSheetKey = ctx.InitialSheetKey, + }; + } + + private static (string Unit, bool Assumed) ResolveLengthUnit(DwgDocument document, DwgSceneOptions options) + { + if (options.UseDrawingUnits && document.HeaderVariables is { } header && header.TryGetSceneUnit(out string headerUnit)) { - effectiveUnit = headerUnit; - unitAssumed = false; + return (headerUnit, false); } - double metresPerUnit = MetresPerUnit(effectiveUnit); - var scene = new SceneDocument { Title = key }; - var diagnostics = new List(); + return (options.LengthUnit, true); + } + + private static double MetresPerUnit(string unit) => unit switch + { + "mm" => 0.001, + "cm" => 0.01, + "m" => 1.0, + "ft" => 0.3048, + "in" => 0.0254, + _ => throw new ArgumentException($"DwgSceneOptions.LengthUnit '{unit}' is not supported; use mm, cm, m, ft or in.", nameof(unit)), + }; - scene.Models.Add(new SceneModel + private sealed class ConversionContext + { + private readonly DwgDocument _rootDoc; + private readonly string? _rootPath; + private readonly DwgSceneOptions _options; + private readonly double _rootScale; + private readonly Dictionary _xrefCache = new(StringComparer.OrdinalIgnoreCase); + private readonly HashSet _activeXrefPaths = new(StringComparer.OrdinalIgnoreCase); + private readonly List<(Vector3d A, Vector3d B, RgbaColor? Color, string? Layer, DwgEntity Source)> _modelSegments = []; + private readonly List<(DwgSceneAnnotation Ann, Vector3d WorldPos, double WorldHeight)> _modelAnnotations = []; + + public SceneDocument Scene { get; } + public List Diagnostics { get; } = []; + public SortedDictionary WithoutGeometry { get; } = new(StringComparer.Ordinal); + public List Annotations { get; } = []; + public List Sheets { get; } = []; + public string? InitialSheetKey { get; private set; } + public int ElementCount { get; private set; } + public int ElementsWithGeometry { get; private set; } + private int _geometryId; + private int _nonFiniteCount; + + public ConversionContext(DwgDocument doc, string key, string? path, DwgSceneOptions options, string effectiveUnit, double metresPerUnit) { - Id = 1, - Key = key, - Name = key, - Path = path, - SourceFormat = "dwg", - Producer = Producer, - SourceLengthUnit = effectiveUnit, - Application = document.AppInfo is { Name.Length: > 0 } appInfo ? appInfo.Name : null, - CreatedAt = document.SummaryInfo?.CreatedUtc?.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture), - }); + _rootDoc = doc; + _rootPath = path; + _options = options; + _rootScale = metresPerUnit; + Scene = new SceneDocument { Title = key }; + Scene.Models.Add(new SceneModel + { + Id = 1, + Key = key, + Name = key, + Path = path, + SourceFormat = "dwg", + Producer = Producer, + SourceLengthUnit = effectiveUnit, + Application = doc.AppInfo is { Name.Length: > 0 } appInfo ? appInfo.Name : null, + CreatedAt = doc.SummaryInfo?.CreatedUtc?.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture), + }); + + foreach (string message in doc.Diagnostics) + { + Diagnostics.Add(new SceneDiagnostic(SceneSeverity.Warning, "document", $"{key}: {message}")); + } + } - foreach (string message in document.Diagnostics) + public void Build() { - // Findings from the read: the scene is usable but something in the drawing was skipped. - diagnostics.Add(new SceneDiagnostic(SceneSeverity.Warning, "document", $"{key}: {message}")); + if (_rootDoc.Blocks.Count == 0 && _rootDoc.Layouts.Count == 0) + { + var ids = new List(); + foreach (var entity in _rootDoc.Entities) + { + EmitEntity(_rootDoc, entity, Affine3d.Identity, _rootScale, 256, null, sheetKey: null, recordForViewports: false, ids); + } + } + else + { + BuildStructured(); + } + + if (WithoutGeometry.Count > 0) + { + string kinds = string.Join(", ", WithoutGeometry.Select(kvp => $"{kvp.Key} {kvp.Value}")); + Diagnostics.Add(new SceneDiagnostic(SceneSeverity.Info, "entities-without-geometry", + $"{WithoutGeometry.Values.Sum()} entities have no geometry the scene places yet ({kinds}).")); + } + + if (_nonFiniteCount > 0) + { + Diagnostics.Add(new SceneDiagnostic(SceneSeverity.Warning, "non-finite-geometry", + $"{_nonFiniteCount} entities had non-finite coordinates and are placed without geometry.")); + } } - int elementCount = 0; - int elementsWithGeometry = 0; - var withoutGeometry = new SortedDictionary(StringComparer.Ordinal); - int nonFinite = 0; - int geometryId = 0; + private void BuildStructured() + { + var docIndex = IndexDocument(_rootDoc); + bool hasPaperLayouts = _options.IncludePaperSpace && docIndex.PaperLayouts.Count > 0; + bool needModelForViewports = hasPaperLayouts && docIndex.PaperLayouts.Any(l => l.Viewports.Count > 0); + + var modelElementIds = new List(); + if (docIndex.ModelBlockHandle is ulong modelHandle) + { + FlattenBlock(docIndex, modelHandle, Affine3d.Identity, _rootScale, 256, null, + sheetKey: hasPaperLayouts ? "model" : null, + recordForViewports: needModelForViewports, + depth: 0, + visitedBlocks: [], + elementIds: modelElementIds); + } + + if (_options.IncludePaperSpace && docIndex.PaperLayouts.Count > 0) + { + var paperSheets = new List(); + foreach (var layout in docIndex.PaperLayouts) + { + var sheetElementIds = new List(); + string sheetKey = $"sheet:{layout.Layout.Handle:X}"; + string sheetName = layout.Layout.Name; + + FlattenBlock(docIndex, layout.BlockHandle, Affine3d.Identity, _rootScale, 256, null, + sheetKey: sheetKey, + recordForViewports: false, + depth: 0, + visitedBlocks: [], + elementIds: sheetElementIds); + + foreach (var vp in layout.Viewports) + { + EmitViewportContent(vp, sheetKey, sheetElementIds); + } - foreach (var entity in document.Entities) + if (sheetElementIds.Count > 0) + { + var bounds = ComputeElementBounds(sheetElementIds); + paperSheets.Add(new DwgSceneSheet(sheetKey, sheetName, IsModelSpace: false, bounds, sheetElementIds)); + } + } + + if (paperSheets.Count > 0) + { + Sheets.AddRange(paperSheets); + InitialSheetKey = paperSheets[0].Key; + if (modelElementIds.Count > 0) + { + var modelBounds = ComputeElementBounds(modelElementIds); + Sheets.Add(new DwgSceneSheet("model", "Model", IsModelSpace: true, modelBounds, modelElementIds)); + } + else + { + // Tag un-sheeted model annotations cleanly if Model sheet isn't separate. + } + } + } + } + + private void FlattenBlock( + DocIndex index, + ulong blockHandle, + Affine3d transform, + double scaleToMetres, + int byBlockAci, + uint? byBlockRgb, + string? sheetKey, + bool recordForViewports, + int depth, + HashSet visitedBlocks, + List elementIds) { - elementCount++; - var element = new SceneElement + if (depth > MaxInsertDepth || !visitedBlocks.Add(blockHandle)) { - Id = elementCount, - ModelId = 1, - SourceId = entity.Handle.ToString("X", CultureInfo.InvariantCulture), - Name = $"{entity.TypeName} {entity.Handle:X}", - Category = entity.TypeName, - TypeName = entity.TypeName, - }; - scene.Elements.Add(element); + return; + } - if (entity.Geometry is { } coordinates && !coordinates.All(double.IsFinite)) + try { - nonFinite++; - continue; + if (!index.Blocks.TryGetValue(blockHandle, out var block)) + { + return; + } + + if (block.IsXref) + { + if (_options.ResolveXrefs && !string.IsNullOrWhiteSpace(block.XrefPath)) + { + ResolveAndFlattenXref(block.XrefPath, index.Document.SourcePath ?? _rootPath, transform, + scaleToMetres, byBlockAci, byBlockRgb, sheetKey, recordForViewports, depth + 1, elementIds); + } + + return; + } + + if (!index.EntitiesByBlock.TryGetValue(blockHandle, out var entities)) + { + return; + } + + foreach (var entity in entities) + { + if (entity.Kind == DwgEntityKind.Insert && entity.Geometry is { Length: >= 14 } ig && _options.ExpandBlocks) + { + if (entity.BlockHeaderHandle is not ulong targetHandle) + { + continue; + } + + var targetBase = index.Blocks.TryGetValue(targetHandle, out var tb) ? tb.BasePoint : default; + (int nextAci, uint? nextRgb) = ResolveByBlock(entity, byBlockAci, byBlockRgb); + int cols = Math.Clamp((int)Math.Round(ig[10]), 1, 256); + int rows = Math.Clamp((int)Math.Round(ig[11]), 1, 256); + double colSp = ig[12], rowSp = ig[13]; + + for (int r = 0; r < rows; r++) + { + for (int c = 0; c < cols; c++) + { + var local = Affine3d.FromInsert(ig, targetBase, c * colSp, r * rowSp); + var composed = Affine3d.Multiply(transform, local); + FlattenBlock(index, targetHandle, composed, scaleToMetres, nextAci, nextRgb, + sheetKey, recordForViewports, depth + 1, visitedBlocks, elementIds); + } + } + + continue; + } + + EmitEntity(index.Document, entity, transform, scaleToMetres, byBlockAci, byBlockRgb, sheetKey, recordForViewports, elementIds); + } + } + finally + { + visitedBlocks.Remove(blockHandle); + } + } + + private void ResolveAndFlattenXref( + string xrefRawPath, + string? hostPath, + Affine3d transform, + double hostScaleToMetres, + int byBlockAci, + uint? byBlockRgb, + string? sheetKey, + bool recordForViewports, + int depth, + List elementIds) + { + string? resolved = ResolveXrefFilePath(xrefRawPath, hostPath); + if (resolved is null) + { + Diagnostics.Add(new SceneDiagnostic(SceneSeverity.Info, "missing-xref", + $"External reference '{xrefRawPath}' could not be found next to the drawing.")); + return; + } + + if (!_activeXrefPaths.Add(resolved)) + { + return; + } + + try + { + if (!_xrefCache.TryGetValue(resolved, out var xrefDoc)) + { + xrefDoc = DwgDocument.Open(resolved, new DwgReaderOptions { ReleaseSectionBuffers = true }); + _xrefCache[resolved] = xrefDoc; + } + + double xrefScale = hostScaleToMetres; + if (_options.UseDrawingUnits && xrefDoc.HeaderVariables is { } xhv && xhv.TryGetSceneUnit(out string xUnit)) + { + xrefScale = MetresPerUnit(xUnit); + } + + // Scale transform translation by host->xref unit ratio when xref uses different drawing units. + double unitRatio = hostScaleToMetres / xrefScale; + var scaledTransform = new Affine3d( + transform.XAxis, + transform.YAxis, + transform.ZAxis, + new Vector3d(transform.Translation.X * unitRatio, transform.Translation.Y * unitRatio, transform.Translation.Z * unitRatio)); + + var xIndex = IndexDocument(xrefDoc); + if (xIndex.ModelBlockHandle is ulong modelHandle) + { + FlattenBlock(xIndex, modelHandle, scaledTransform, xrefScale, byBlockAci, byBlockRgb, + sheetKey, recordForViewports, depth, [], elementIds); + } + } + catch (Exception ex) + { + Diagnostics.Add(new SceneDiagnostic(SceneSeverity.Warning, "xref-load-failed", + $"Failed to load external reference '{resolved}': {ex.Message}")); + } + finally + { + _activeXrefPaths.Remove(resolved); + } + } + + private static string? ResolveXrefFilePath(string xrefRawPath, string? hostPath) + { + if (string.IsNullOrEmpty(hostPath)) + { + return null; + } + + string? hostDir = Path.GetDirectoryName(hostPath); + string fileName = Path.GetFileName(xrefRawPath.Replace('\\', '/')); + if (string.IsNullOrEmpty(hostDir) || string.IsNullOrEmpty(fileName) + || !Path.GetExtension(fileName).Equals(".dwg", StringComparison.OrdinalIgnoreCase) + || fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) + { + return null; + } + + var sibling = new FileInfo(Path.Combine(hostDir, fileName)); + return sibling.Exists && (sibling.Attributes & FileAttributes.ReparsePoint) == 0 + ? sibling.FullName + : null; + } + + private void EmitEntity( + DwgDocument ownerDoc, + DwgEntity entity, + Affine3d transform, + double scale, + int byBlockAci, + uint? byBlockRgb, + string? sheetKey, + bool recordForViewports, + List elementIds) + { + if (entity.TypeCode is 0x04 or 0x05 or 0x06 or 0x0A or 0x0B or 0x22) + { + return; + } + + if (entity.Kind is DwgEntityKind.Text or DwgEntityKind.MText && entity.Geometry is { Length: >= 5 } tg) + { + string? plain = entity.PlainText; + if (string.IsNullOrWhiteSpace(plain)) + { + return; + } + + var pos = transform.Apply(new Vector3d(tg[0], tg[1], tg[2])) * scale; + double textHeight = tg[3] * scale * transform.UniformScaleXY; + if (!IsFinite(pos) || !double.IsFinite(textHeight) || textHeight <= 0) + { + return; + } + + var xDir = transform.ApplyVector(new Vector3d(Math.Cos(tg[4]), Math.Sin(tg[4]), 0)); + double rot = Math.Atan2(xDir.Y, xDir.X); + double width = entity.Kind == DwgEntityKind.MText && tg.Length >= 6 ? tg[5] * scale * transform.UniformScaleXY : 0; + int att = MapAttachment(entity, tg); + RgbaColor? col = ColourOf(entity, byBlockAci, byBlockRgb); + + ElementCount++; + var el = CreateElement(ownerDoc, entity); + Scene.Elements.Add(el); + elementIds.Add(el.Id); + + var ann = new DwgSceneAnnotation(plain, pos, textHeight, rot, width, att, col, el.Id, sheetKey); + Annotations.Add(ann); + if (recordForViewports) + { + _modelAnnotations.Add((ann, pos, textHeight)); + } + + return; + } + + bool isStructured = _rootDoc.Blocks.Count > 0 || _rootDoc.Layouts.Count > 0; + ElementCount++; + var element = CreateElement(ownerDoc, entity); + Scene.Elements.Add(element); + elementIds.Add(element.Id); + + if (entity.Geometry is { } coords && !coords.All(double.IsFinite)) + { + _nonFiniteCount++; + return; } (SceneTopology topology, Vector3d[] vertices, IReadOnlyList indices)? built = entity.Kind switch { DwgEntityKind.Line when entity.Geometry is { Length: 6 } g => - (SceneTopology.Lines, LineVertices(g, metresPerUnit), Array.Empty()), + (SceneTopology.Lines, TransformVertices(LineVertices(g), transform, scale), Array.Empty()), DwgEntityKind.Circle when entity.Geometry is { Length: 4 } g => - BuildCircle(g, metresPerUnit), + (SceneTopology.Lines, TransformVertices(CircleVertices(g), transform, scale), SharedIndices(CircleSegments, closed: true)), DwgEntityKind.Arc when entity.Geometry is { Length: 6 } g => - BuildArc(g, metresPerUnit), + BuildArc(g, transform, scale), DwgEntityKind.Point when entity.Geometry is { Length: 3 } g => - (SceneTopology.Points, PointVertices(g, metresPerUnit), Array.Empty()), - DwgEntityKind.Polyline when entity.Geometry is { Length: >= 5 } g => - BuildPolyline(g, metresPerUnit), + (SceneTopology.Points, TransformVertices(PointVertices(g), transform, scale), Array.Empty()), + DwgEntityKind.Polyline when entity.Geometry is { Length: >= 8 } g => + BuildPolyline(g, transform, scale), + DwgEntityKind.Polyline3d when entity.Geometry is { Length: >= 7 } g => + BuildPolyline3d(g, transform, scale), + DwgEntityKind.Spline when entity.Geometry is { Length: >= 7 } g => + BuildSpline(g, transform, scale), DwgEntityKind.Ellipse when entity.Geometry is { Length: 12 } g => - BuildEllipse(g, metresPerUnit), + BuildEllipse(g, transform, scale), DwgEntityKind.Solid when entity.Geometry is { Length: 12 } g => - BuildQuad(g, metresPerUnit, bowtieOrder: true), + BuildQuad(g, transform, scale, bowtieOrder: true), DwgEntityKind.Face3d when entity.Geometry is { Length: 12 } g => - BuildQuad(g, metresPerUnit, bowtieOrder: false), + BuildQuad(g, transform, scale, bowtieOrder: false), _ => null, }; + if (built is null) { if (entity.Kind == DwgEntityKind.Unknown || entity.Geometry is null) { - withoutGeometry[entity.TypeName] = withoutGeometry.TryGetValue(entity.TypeName, out int n) ? n + 1 : 1; + if (!isStructured || entity.Kind != DwgEntityKind.Insert) + { + WithoutGeometry[entity.TypeName] = WithoutGeometry.TryGetValue(entity.TypeName, out int n) ? n + 1 : 1; + } } - continue; + return; } if (!built.Value.vertices.All(IsFinite)) { - // The IOScene contract forbids non-finite coordinates; the core JSON export writes them as null, - // the scene drops the geometry and reports it. - nonFinite++; - continue; + _nonFiniteCount++; + return; } - elementsWithGeometry++; - geometryId++; + ElementsWithGeometry++; + _geometryId++; var geometry = new SceneGeometry { - Id = geometryId, + Id = _geometryId, Topology = built.Value.topology, Vertices = built.Value.vertices, Indices = built.Value.indices, }; - scene.Geometries.Add(geometry); - scene.Instances.Add(new SceneInstance + Scene.Geometries.Add(geometry); + var instanceColor = ColourOf(entity, byBlockAci, byBlockRgb); + Scene.Instances.Add(new SceneInstance { ElementId = element.Id, GeometryId = geometry.Id, - Color = ColourOf(entity), + Color = instanceColor, }); + + if (recordForViewports && built.Value.topology == SceneTopology.Lines) + { + var idx = built.Value.indices; + var verts = built.Value.vertices; + int segVerts = idx.Count > 0 ? idx.Count : verts.Length; + for (int k = 0; k + 1 < segVerts; k += 2) + { + var a = idx.Count > 0 ? verts[idx[k]] : verts[k]; + var b = idx.Count > 0 ? verts[idx[k + 1]] : verts[k + 1]; + _modelSegments.Add((a, b, instanceColor, entity.LayerName, entity)); + } + } } - if (withoutGeometry.Count > 0) + private void EmitViewportContent(DwgViewportData vp, string sheetKey, List sheetElementIds) { - string kinds = string.Join(", ", withoutGeometry.Select(kvp => $"{kvp.Key} {kvp.Value}")); - diagnostics.Add(new SceneDiagnostic(SceneSeverity.Info, "entities-without-geometry", - $"{withoutGeometry.Values.Sum()} entities have no geometry the scene places yet ({kinds}).")); + double paperScale = _rootScale; + var centerPaper = new Vector3d(vp.Center.X * paperScale, vp.Center.Y * paperScale, vp.Center.Z * paperScale); + double halfW = vp.Width * paperScale * 0.5; + double halfH = vp.Height * paperScale * 0.5; + double minX = centerPaper.X - halfW, maxX = centerPaper.X + halfW; + double minY = centerPaper.Y - halfH, maxY = centerPaper.Y + halfH; + double vpScale = vp.Height / vp.ViewHeight; + + var dir = new Vector3d(vp.ViewDirection.X, vp.ViewDirection.Y, vp.ViewDirection.Z); + var (vx, vy, _) = ArbitraryAxisBasis(dir, vp.TwistAngleRadians); + var targetM = new Vector3d(vp.ViewTarget.X * paperScale, vp.ViewTarget.Y * paperScale, vp.ViewTarget.Z * paperScale); + double vcX = vp.ViewCenter.X * paperScale; + double vcY = vp.ViewCenter.Y * paperScale; + + Vector3d Project(Vector3d worldM) + { + var d = worldM - targetM; + double px = centerPaper.X + (Vector3d.Dot(d, vx) - vcX) * vpScale; + double py = centerPaper.Y + (Vector3d.Dot(d, vy) - vcY) * vpScale; + return new Vector3d(px, py, centerPaper.Z); + } + + // Batch clipped viewport linework per (layer, color) to keep sheets lean and responsive. + var batches = new Dictionary<(string Layer, RgbaColor? Color), List>(); + foreach (var seg in _modelSegments) + { + var p0 = Project(seg.A); + var p1 = Project(seg.B); + if (!ClipSegment2D(ref p0, ref p1, minX, minY, maxX, maxY)) + { + continue; + } + + string layer = seg.Layer ?? "0"; + var key = (layer, seg.Color); + if (!batches.TryGetValue(key, out var list)) + { + list = []; + batches[key] = list; + } + + list.Add(p0); + list.Add(p1); + } + + foreach (var ((layer, color), verts) in batches) + { + if (verts.Count < 2) + { + continue; + } + + ElementCount++; + ElementsWithGeometry++; + var el = new SceneElement + { + Id = ElementCount, + ModelId = 1, + SourceId = $"VP-{sheetKey}-{ElementCount}", + Name = $"{layer} (Viewport)", + Category = layer, + TypeName = "VIEWPORT_CONTENT", + }; + Scene.Elements.Add(el); + sheetElementIds.Add(el.Id); + + _geometryId++; + var geom = new SceneGeometry + { + Id = _geometryId, + Topology = SceneTopology.Lines, + Vertices = verts.ToArray(), + }; + Scene.Geometries.Add(geom); + Scene.Instances.Add(new SceneInstance { ElementId = el.Id, GeometryId = geom.Id, Color = color }); + } + + foreach (var (ann, worldPos, worldHeight) in _modelAnnotations) + { + var p = Project(worldPos); + if (p.X < minX || p.X > maxX || p.Y < minY || p.Y > maxY) + { + continue; + } + + double h = worldHeight * vpScale; + if (h <= 0 || !double.IsFinite(h)) + { + continue; + } + + Annotations.Add(ann with + { + Position = p, + Height = h, + RotationRadians = ann.RotationRadians - vp.TwistAngleRadians, + Width = ann.Width * vpScale, + ElementId = null, + SheetKey = sheetKey, + }); + } } - if (nonFinite > 0) + private SceneElement CreateElement(DwgDocument doc, DwgEntity entity) { - diagnostics.Add(new SceneDiagnostic(SceneSeverity.Warning, "non-finite-geometry", - $"{nonFinite} entities had non-finite coordinates and are placed without geometry.")); + _ = doc; + return new SceneElement + { + Id = ElementCount, + ModelId = 1, + SourceId = entity.Handle.ToString("X", CultureInfo.InvariantCulture), + Name = $"{entity.TypeName} {entity.Handle:X}", + Category = !string.IsNullOrEmpty(entity.LayerName) ? entity.LayerName : entity.TypeName, + TypeName = entity.TypeName, + }; } - return new DwgSceneResult + private BoundingBox3d? ComputeElementBounds(List elementIds) { - Document = scene, - Diagnostics = diagnostics, - ElementCount = elementCount, - ElementsWithGeometry = elementsWithGeometry, - EntitiesWithoutGeometry = withoutGeometry.Values.Sum(), - LengthUnit = effectiveUnit, - MetresPerUnit = metresPerUnit, - UnitAssumed = unitAssumed, - }; + var idSet = new HashSet(elementIds); + var geomById = new Dictionary(Scene.Geometries.Count); + foreach (var g in Scene.Geometries) geomById[g.Id] = g; + + var box = BoundingBox3d.Empty; + foreach (var inst in Scene.Instances) + { + if (!idSet.Contains(inst.ElementId) || !geomById.TryGetValue(inst.GeometryId, out var g)) + { + continue; + } + + var t = inst.Transform ?? Transform3d.Identity; + foreach (var v in g.Vertices) + { + box = box.Encapsulate(t.Apply(v)); + } + } + + return box.IsEmpty ? null : box; + } } - /// Tells whether accepts . - public static bool IsSupportedUnit(string unit) => unit is "mm" or "cm" or "m" or "ft" or "in"; + private sealed record DocIndex( + DwgDocument Document, + ulong? ModelBlockHandle, + Dictionary Blocks, + Dictionary> EntitiesByBlock, + List<(DwgLayoutInfo Layout, ulong BlockHandle, List Viewports)> PaperLayouts); - private static double MetresPerUnit(string unit) => unit switch + private static DocIndex IndexDocument(DwgDocument doc) { - "mm" => 0.001, - "cm" => 0.01, - "m" => 1.0, - "ft" => 0.3048, - "in" => 0.0254, - _ => throw new ArgumentException($"DwgSceneOptions.LengthUnit '{unit}' is not supported; use mm, cm, m, ft or in.", nameof(unit)), - }; + var blocks = new Dictionary(doc.Blocks.Count); + ulong? modelHandle = null; + ulong? defaultPaperHandle = null; + var entityOwnerFromBlock = new Dictionary(); + + foreach (var b in doc.Blocks) + { + blocks[b.Handle] = b; + if (b.Name.Equals("*Model_Space", StringComparison.OrdinalIgnoreCase)) + { + modelHandle = b.Handle; + } + else if (defaultPaperHandle is null && b.Name.Equals("*Paper_Space", StringComparison.OrdinalIgnoreCase)) + { + defaultPaperHandle = b.Handle; + } + + foreach (ulong eh in b.OwnedEntityHandles) + { + entityOwnerFromBlock.TryAdd(eh, b.Handle); + } + } + + var entityByHandle = new Dictionary(doc.Entities.Count); + var byBlock = new Dictionary>(); + void AddToBlock(ulong blkHandle, DwgEntity e) + { + if (!byBlock.TryGetValue(blkHandle, out var list)) + { + list = []; + byBlock[blkHandle] = list; + } + + list.Add(e); + } + + foreach (var e in doc.Entities) + { + entityByHandle.TryAdd(e.Handle, e); + if (e.IsModelSpace && modelHandle is ulong mh) + { + AddToBlock(mh, e); + } + else if (e.OwnerHandle is ulong oh && blocks.ContainsKey(oh)) + { + AddToBlock(oh, e); + } + else if (entityOwnerFromBlock.TryGetValue(e.Handle, out ulong bh)) + { + AddToBlock(bh, e); + } + else if (!e.IsModelSpace && defaultPaperHandle is ulong ph) + { + AddToBlock(ph, e); + } + } + + var paperLayouts = new List<(DwgLayoutInfo Layout, ulong BlockHandle, List Viewports)>(); + foreach (var l in doc.Layouts) + { + if (l.IsModelSpace || l.BlockHeaderHandle is not ulong bh) + { + continue; + } + + var vps = new List(); + foreach (ulong vh in l.ViewportHandles) + { + if (vh != l.OverallViewportHandle + && entityByHandle.TryGetValue(vh, out var ve) + && ve.Viewport is { IsActive: true } vpd) + { + vps.Add(vpd); + } + } + + bool hasEntities = byBlock.TryGetValue(bh, out var list) && list.Any(e => e.TypeCode is not (0x04 or 0x05 or 0x22)); + if (hasEntities || vps.Count > 0) + { + paperLayouts.Add((l, bh, vps)); + } + } + + return new DocIndex(doc, modelHandle, blocks, byBlock, paperLayouts); + } - private static RgbaColor? ColourOf(DwgEntity entity) + private static (int Aci, uint? Rgb) ResolveByBlock(DwgEntity insert, int parentAci, uint? parentRgb) + { + int aci = insert.EffectiveColorIndex; + uint? rgb = insert.EffectiveTrueColorRgb; + if (aci == 0 && rgb is null) + { + return (parentAci, parentRgb); + } + + return (aci, rgb); + } + + private static RgbaColor? ColourOf(DwgEntity entity, int byBlockAci, uint? byBlockRgb) { if (entity.EffectiveTrueColorRgb is { } rgb) { @@ -257,9 +825,18 @@ document.HeaderVariables is { } header && } int colorIndex = entity.EffectiveColorIndex; + if (colorIndex == 0) + { + if (byBlockRgb is { } brgb) + { + return new RgbaColor((byte)(brgb >> 16), (byte)(brgb >> 8), (byte)brgb); + } + + colorIndex = byBlockAci; + } + if (colorIndex is <= 0 or >= 256) { - // Unresolved BYBLOCK (0) or BYLAYER (256) has no fixed colour of its own. return null; } @@ -267,28 +844,107 @@ document.HeaderVariables is { } header && return new RgbaColor(r, g, b); } - private static (SceneTopology, Vector3d[], IReadOnlyList) BuildCircle(double[] g, double scale) + private static int MapAttachment(DwgEntity entity, double[] g) { - var vertices = CircleVertices(g, scale); - return (SceneTopology.Lines, vertices, SharedIndices(CircleSegments, closed: true)); + if (entity.Kind == DwgEntityKind.MText && g.Length >= 7) + { + return Math.Clamp((int)Math.Round(g[6]), 1, 9); + } + + if (entity.Kind == DwgEntityKind.Text && g.Length >= 9) + { + int h = (int)Math.Round(g[7]); // 0=L,1=C,2=R + int v = (int)Math.Round(g[8]); // 0=Base,1=B,2=M,3=T + int col = h == 1 ? 2 : h == 2 ? 3 : 1; + int row = v == 3 ? 0 : v == 2 ? 3 : 6; + return row + col; + } + + return 1; } - private static (SceneTopology, Vector3d[], IReadOnlyList) BuildArc(double[] g, double scale) + private static bool ClipSegment2D(ref Vector3d a, ref Vector3d b, double minX, double minY, double maxX, double maxY) { - var vertices = ArcVertices(g, scale); - return (SceneTopology.Lines, vertices, SharedIndices(vertices.Length, closed: false)); + double dx = b.X - a.X; + double dy = b.Y - a.Y; + double dz = b.Z - a.Z; + double t0 = 0.0, t1 = 1.0; + + bool Clip(double p, double q) + { + if (Math.Abs(p) < 1e-12) + { + return q >= 0; + } + + double r = q / p; + if (p < 0) + { + if (r > t1) return false; + if (r > t0) t0 = r; + } + else + { + if (r < t0) return false; + if (r < t1) t1 = r; + } + + return true; + } + + if (!Clip(-dx, a.X - minX) || !Clip(dx, maxX - a.X) || !Clip(-dy, a.Y - minY) || !Clip(dy, maxY - a.Y)) + { + return false; + } + + var na = new Vector3d(a.X + t0 * dx, a.Y + t0 * dy, a.Z + t0 * dz); + var nb = new Vector3d(a.X + t1 * dx, a.Y + t1 * dy, a.Z + t1 * dz); + a = na; + b = nb; + return true; } - private static (SceneTopology, Vector3d[], IReadOnlyList)? BuildPolyline(double[] g, double scale) + private static (Vector3d X, Vector3d Y, Vector3d Z) ArbitraryAxisBasis(Vector3d normal, double twistRad) { - int count = (g.Length - 2) / 3; - if (count < 2) + double len = normal.Length; + Vector3d n = len > 1e-12 ? normal / len : Vector3d.UnitZ; + Vector3d ax = Math.Abs(n.X) < 1.0 / 64.0 && Math.Abs(n.Y) < 1.0 / 64.0 + ? Vector3d.Cross(Vector3d.UnitY, n).Normalized() + : Vector3d.Cross(Vector3d.UnitZ, n).Normalized(); + Vector3d ay = Vector3d.Cross(n, ax).Normalized(); + if (Math.Abs(twistRad) > 1e-12) { - return null; + double c = Math.Cos(twistRad), s = Math.Sin(twistRad); + return (ax * c + ay * s, -ax * s + ay * c, n); + } + + return (ax, ay, n); + } + + private static Vector3d[] TransformVertices(Vector3d[] local, Affine3d transform, double scale) + { + var result = new Vector3d[local.Length]; + for (int i = 0; i < local.Length; i++) + { + result[i] = transform.Apply(local[i]) * scale; } + return result; + } + + private static (SceneTopology, Vector3d[], IReadOnlyList) BuildArc(double[] g, Affine3d t, double scale) + { + var vertices = TransformVertices(ArcVertices(g), t, scale); + return (SceneTopology.Lines, vertices, SharedIndices(vertices.Length, closed: false)); + } + + private static (SceneTopology, Vector3d[], IReadOnlyList)? BuildPolyline(double[] g, Affine3d t, double scale) + { + int count = (g.Length - 2) / 3; + if (count < 2) return null; + bool closed = g[0] != 0.0; - double z = g[1] * scale; + double z = g[1]; var vertices = new List(count); var indices = new List(count * 2); @@ -296,46 +952,65 @@ private static (SceneTopology, Vector3d[], IReadOnlyList)? BuildPolyline(do for (int i = 0; i < segments; i++) { int next = (i + 1) % count; - double x1 = g[2 + i * 3] * scale; - double y1 = g[2 + i * 3 + 1] * scale; - double bulge = g[2 + i * 3 + 2]; - double x2 = g[2 + next * 3] * scale; - double y2 = g[2 + next * 3 + 1] * scale; + double x1 = g[2 + i * 3], y1 = g[2 + i * 3 + 1], bulge = g[2 + i * 3 + 2]; + double x2 = g[2 + next * 3], y2 = g[2 + next * 3 + 1]; if (Math.Abs(bulge) < 1e-12) { int a = vertices.Count; - vertices.Add(new Vector3d(x1, y1, z)); - vertices.Add(new Vector3d(x2, y2, z)); + vertices.Add(t.Apply(new Vector3d(x1, y1, z)) * scale); + vertices.Add(t.Apply(new Vector3d(x2, y2, z)) * scale); indices.Add(a); indices.Add(a + 1); } else { - AppendBulgeSegments(vertices, indices, x1, y1, x2, y2, z, bulge); + AppendBulgeSegments(vertices, indices, x1, y1, x2, y2, z, bulge, t, scale); } } return vertices.Count >= 2 ? (SceneTopology.Lines, vertices.ToArray(), indices) : null; } + private static (SceneTopology, Vector3d[], IReadOnlyList)? BuildPolyline3d(double[] g, Affine3d t, double scale) + { + int count = (g.Length - 1) / 3; + if (count < 2) return null; + + bool closed = g[0] != 0.0; + var vertices = new Vector3d[count]; + for (int i = 0; i < count; i++) + { + vertices[i] = t.Apply(new Vector3d(g[1 + i * 3], g[1 + i * 3 + 1], g[1 + i * 3 + 2])) * scale; + } + + return (SceneTopology.Lines, vertices, SharedIndices(count, closed)); + } + + private static (SceneTopology, Vector3d[], IReadOnlyList)? BuildSpline(double[] g, Affine3d t, double scale) + { + int count = (g.Length - 1) / 3; + if (count < 2) return null; + + bool closed = g[0] != 0.0; + var vertices = new Vector3d[count]; + for (int i = 0; i < count; i++) + { + vertices[i] = t.Apply(new Vector3d(g[1 + i * 3], g[1 + i * 3 + 1], g[1 + i * 3 + 2])) * scale; + } + + return (SceneTopology.Lines, vertices, SharedIndices(count, closed)); + } + private static void AppendBulgeSegments( List vertices, List indices, - double x1, - double y1, - double x2, - double y2, - double z, - double bulge) + double x1, double y1, double x2, double y2, double z, double bulge, + Affine3d t, double scale) { - double dx = x2 - x1; - double dy = y2 - y1; + double dx = x2 - x1, dy = y2 - y1; double chord = double.Hypot(dx, dy); - if (chord <= 1e-15) - { - return; - } + if (chord <= 1e-15) return; double theta = 4.0 * Math.Atan(bulge); double radius = chord * (1.0 + bulge * bulge) / (4.0 * Math.Abs(bulge)); @@ -346,14 +1021,14 @@ private static void AppendBulgeSegments( int steps = Math.Clamp((int)Math.Ceiling(Math.Abs(theta) / ArcRadiansPerSegment), MinArcSegments, CircleSegments * 4); int first = vertices.Count; - vertices.Add(new Vector3d(x1, y1, z)); + vertices.Add(t.Apply(new Vector3d(x1, y1, z)) * scale); for (int s = 1; s < steps; s++) { double angle = start + theta * s / steps; - vertices.Add(new Vector3d(cx + radius * Math.Cos(angle), cy + radius * Math.Sin(angle), z)); + vertices.Add(t.Apply(new Vector3d(cx + radius * Math.Cos(angle), cy + radius * Math.Sin(angle), z)) * scale); } - vertices.Add(new Vector3d(x2, y2, z)); + vertices.Add(t.Apply(new Vector3d(x2, y2, z)) * scale); for (int s = 0; s < steps; s++) { indices.Add(first + s); @@ -361,16 +1036,13 @@ private static void AppendBulgeSegments( } } - private static (SceneTopology, Vector3d[], IReadOnlyList)? BuildEllipse(double[] g, double scale) + private static (SceneTopology, Vector3d[], IReadOnlyList)? BuildEllipse(double[] g, Affine3d t, double scale) { - double cx = g[0] * scale, cy = g[1] * scale, cz = g[2] * scale; - double mx = g[3] * scale, my = g[4] * scale, mz = g[5] * scale; - if (!EllipseAxes.TryGetMinor(g, out var minor)) - { - return null; - } + double cx = g[0], cy = g[1], cz = g[2]; + double mx = g[3], my = g[4], mz = g[5]; + if (!EllipseAxes.TryGetMinor(g, out var minor)) return null; - double nx = minor.X * scale, ny = minor.Y * scale, nz = minor.Z * scale; + double nx = minor.X, ny = minor.Y, nz = minor.Z; var (start, span) = ArcAngles.Normalize(g[7], g[8]); bool closed = span >= Math.Tau - 1e-9; int steps = closed ? CircleSegments : Math.Clamp((int)Math.Ceiling(span / ArcRadiansPerSegment), MinArcSegments, CircleSegments * 4); @@ -378,36 +1050,29 @@ private static (SceneTopology, Vector3d[], IReadOnlyList)? BuildEllipse(dou for (int i = 0; i < vertices.Length; i++) { double angle = start + span * i / steps; - double cos = Math.Cos(angle); - double sin = Math.Sin(angle); - vertices[i] = new Vector3d(cx + mx * cos + nx * sin, cy + my * cos + ny * sin, cz + mz * cos + nz * sin); + double cos = Math.Cos(angle), sin = Math.Sin(angle); + vertices[i] = t.Apply(new Vector3d(cx + mx * cos + nx * sin, cy + my * cos + ny * sin, cz + mz * cos + nz * sin)) * scale; } return (SceneTopology.Lines, vertices, SharedIndices(vertices.Length, closed)); } - private static (SceneTopology, Vector3d[], IReadOnlyList) BuildQuad(double[] g, double scale, bool bowtieOrder) + private static (SceneTopology, Vector3d[], IReadOnlyList) BuildQuad(double[] g, Affine3d t, double scale, bool bowtieOrder) { - var p0 = new Vector3d(g[0] * scale, g[1] * scale, g[2] * scale); - var p1 = new Vector3d(g[3] * scale, g[4] * scale, g[5] * scale); - var p2 = new Vector3d(g[6] * scale, g[7] * scale, g[8] * scale); - var p3 = new Vector3d(g[9] * scale, g[10] * scale, g[11] * scale); - // SOLID/TRACE store corners in bowtie order (0, 1, 2, 3 -> quad perimeter 0-1-3-2). + var p0 = t.Apply(new Vector3d(g[0], g[1], g[2])) * scale; + var p1 = t.Apply(new Vector3d(g[3], g[4], g[5])) * scale; + var p2 = t.Apply(new Vector3d(g[6], g[7], g[8])) * scale; + var p3 = t.Apply(new Vector3d(g[9], g[10], g[11])) * scale; Vector3d[] vertices = bowtieOrder ? [p0, p1, p3, p2] : [p0, p1, p2, p3]; int[] indices = [0, 1, 2, 0, 2, 3]; return (SceneTopology.Triangles, vertices, indices); } - private static Vector3d[] LineVertices(double[] g, double scale) => - [ - new(g[0] * scale, g[1] * scale, g[2] * scale), - new(g[3] * scale, g[4] * scale, g[5] * scale), - ]; + private static Vector3d[] LineVertices(double[] g) => [new(g[0], g[1], g[2]), new(g[3], g[4], g[5])]; - private static Vector3d[] CircleVertices(double[] g, double scale) + private static Vector3d[] CircleVertices(double[] g) { - double cx = g[0] * scale, cy = g[1] * scale, cz = g[2] * scale; - double radius = g[3] * scale; + double cx = g[0], cy = g[1], cz = g[2], radius = g[3]; var vertices = new Vector3d[CircleSegments]; for (int i = 0; i < CircleSegments; i++) { @@ -418,12 +1083,10 @@ private static Vector3d[] CircleVertices(double[] g, double scale) return vertices; } - private static Vector3d[] ArcVertices(double[] g, double scale) + private static Vector3d[] ArcVertices(double[] g) { - double cx = g[0] * scale, cy = g[1] * scale, cz = g[2] * scale; - double radius = g[3] * scale; + double cx = g[0], cy = g[1], cz = g[2], radius = g[3]; var (start, span) = ArcAngles.Normalize(g[4], g[5]); - int segments = Math.Clamp((int)Math.Ceiling(span / ArcRadiansPerSegment), MinArcSegments, CircleSegments * 4); var vertices = new Vector3d[segments + 1]; for (int i = 0; i <= segments; i++) @@ -435,9 +1098,8 @@ private static Vector3d[] ArcVertices(double[] g, double scale) return vertices; } - private static Vector3d[] PointVertices(double[] g, double scale) => [new(g[0] * scale, g[1] * scale, g[2] * scale)]; + private static Vector3d[] PointVertices(double[] g) => [new(g[0], g[1], g[2])]; - /// Line indices of a tessellated circle (closed ring) or arc (open chain), sharing the joints. private static List SharedIndices(int vertexCount, bool closed) { var indices = new List((vertexCount - (closed ? 0 : 1)) * 2); @@ -457,4 +1119,43 @@ private static List SharedIndices(int vertexCount, bool closed) } private static bool IsFinite(Vector3d v) => double.IsFinite(v.X) && double.IsFinite(v.Y) && double.IsFinite(v.Z); + + private readonly record struct Affine3d(Vector3d XAxis, Vector3d YAxis, Vector3d ZAxis, Vector3d Translation) + { + public static readonly Affine3d Identity = new(Vector3d.UnitX, Vector3d.UnitY, Vector3d.UnitZ, Vector3d.Zero); + + public double UniformScaleXY => Math.Max(XAxis.Length, YAxis.Length); + + public Vector3d Apply(Vector3d p) => XAxis * p.X + YAxis * p.Y + ZAxis * p.Z + Translation; + + public Vector3d ApplyVector(Vector3d v) => XAxis * v.X + YAxis * v.Y + ZAxis * v.Z; + + public static Affine3d Multiply(Affine3d a, Affine3d b) => new( + a.ApplyVector(b.XAxis), + a.ApplyVector(b.YAxis), + a.ApplyVector(b.ZAxis), + a.Apply(b.Translation)); + + public static Affine3d FromInsert(double[] ig, DwgPoint3D basePoint, double gridX, double gridY) + { + double ix = ig[0], iy = ig[1], iz = ig[2]; + double sx = ig[3], sy = ig[4], sz = ig[5]; + double rot = ig[6]; + var (ocsX, ocsY, ocsZ) = ArbitraryAxisBasis(new Vector3d(ig[7], ig[8], ig[9]), 0); + + double c = Math.Cos(rot), s = Math.Sin(rot); + // Local point p -> p - base -> scale -> rotate(rot) -> gridOffset -> OCS->WCS -> + insPt + var rx = new Vector3d(c * sx, s * sx, 0); + var ry = new Vector3d(-s * sy, c * sy, 0); + var rz = new Vector3d(0, 0, sz); + var rTrans = new Vector3d( + gridX - (rx.X * basePoint.X + ry.X * basePoint.Y), + gridY - (rx.Y * basePoint.X + ry.Y * basePoint.Y), + -sz * basePoint.Z); + + Vector3d ToWcs(Vector3d v) => ocsX * v.X + ocsY * v.Y + ocsZ * v.Z; + var insWcs = ToWcs(new Vector3d(ix, iy, iz)) + ToWcs(rTrans); + return new Affine3d(ToWcs(rx), ToWcs(ry), ToWcs(rz), insWcs); + } + } } diff --git a/src/DwgIO.Scene.Adapter/DwgSceneResult.cs b/src/DwgIO.Scene.Adapter/DwgSceneResult.cs index c0e4e97..cb33229 100644 --- a/src/DwgIO.Scene.Adapter/DwgSceneResult.cs +++ b/src/DwgIO.Scene.Adapter/DwgSceneResult.cs @@ -31,4 +31,33 @@ public sealed class DwgSceneResult /// True when the unit came from the default instead of the drawing, which never names its unit. public bool UnitAssumed { get; init; } + + /// Decoded CAD text annotations (TEXT/MTEXT) in scene coordinates. + public IReadOnlyList Annotations { get; init; } = []; + + /// Switchable spaces and Paper Space sheets in the drawing. + public IReadOnlyList Sheets { get; init; } = []; + + /// Key of the initial sheet to open when Paper Space layouts are present. + public string? InitialSheetKey { get; init; } } + +/// A CAD text label positioned in scene coordinates (metres). +public sealed record DwgSceneAnnotation( + string Text, + Vector3d Position, + double Height, + double RotationRadians, + double Width, + int Attachment, + RgbaColor? Color, + long? ElementId, + string? SheetKey); + +/// A space or Paper Space sheet grouping scene elements. +public sealed record DwgSceneSheet( + string Key, + string Name, + bool IsModelSpace, + BoundingBox3d? PaperBounds, + IReadOnlyList ElementIds); diff --git a/src/DwgIO.Scene/Compatibility/DwgSceneExport.cs b/src/DwgIO.Scene/Compatibility/DwgSceneExport.cs index 3d2f4ad..b64fd68 100644 --- a/src/DwgIO.Scene/Compatibility/DwgSceneExport.cs +++ b/src/DwgIO.Scene/Compatibility/DwgSceneExport.cs @@ -117,6 +117,9 @@ private static DwgSceneOptions OptionsFor(string path, DwgSceneOptions? options) { LengthUnit = options?.LengthUnit ?? "m", UseDrawingUnits = options?.UseDrawingUnits ?? false, + ExpandBlocks = options?.ExpandBlocks ?? true, + ResolveXrefs = options?.ResolveXrefs ?? false, + IncludePaperSpace = options?.IncludePaperSpace ?? true, ModelKey = Path.GetFileName(path), ReadProgress = options?.ReadProgress, }; diff --git a/src/DwgIO.Scene/Compatibility/DwgViewerExport.cs b/src/DwgIO.Scene/Compatibility/DwgViewerExport.cs index f58c8df..550bdda 100644 --- a/src/DwgIO.Scene/Compatibility/DwgViewerExport.cs +++ b/src/DwgIO.Scene/Compatibility/DwgViewerExport.cs @@ -1,23 +1,18 @@ using IOViewer.Exporters; +using IOViewer.Model; 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. +/// Exports a drawing as a standalone interactive HTML viewer powered by +/// IOViewer, supporting both 3D navigation and +/// integrated 2D CAD sheets, vector lines and text annotations in one self-contained HTML file. /// 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, @@ -25,29 +20,106 @@ public static DwgSceneResult SaveViewer( HtmlViewerOptions? viewerOptions = null) { var result = DwgSceneReader.Read(document, ViewerOptionsFor(document, htmlPath, options)); - WriteViewer(result.Document, htmlPath, viewerOptions); + WriteViewer(result, htmlPath, viewerOptions); return result; } + /// Writes a full (including sheets and text annotations) to an IOViewer HTML file. + public static void WriteViewer(DwgSceneResult result, string htmlPath, HtmlViewerOptions? viewerOptions = null) + { + ArgumentNullException.ThrowIfNull(result); + ArgumentException.ThrowIfNullOrEmpty(htmlPath); + + var resolved = NormalizeOptions(result.Document, viewerOptions); + var viewerDoc = ToViewerDocument(result, resolved); + AtomicOutput.Write(htmlPath, stream => HtmlViewerExporter.Export(viewerDoc, stream, resolved)); + } + /// 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); + + var resolved = NormalizeOptions(scene, viewerOptions); + AtomicOutput.Write(htmlPath, stream => HtmlViewerExporter.Export(new ViewerDocument(scene), stream, resolved)); + } + + /// Writes a full (including sheets and text annotations) to a stream. + public static void WriteViewer(DwgSceneResult result, Stream stream, HtmlViewerOptions? viewerOptions = null) + { + ArgumentNullException.ThrowIfNull(result); + ArgumentNullException.ThrowIfNull(stream); + + var resolved = NormalizeOptions(result.Document, viewerOptions); + var viewerDoc = ToViewerDocument(result, resolved); + HtmlViewerExporter.Export(viewerDoc, stream, resolved); + } + + private static HtmlViewerOptions NormalizeOptions(SceneDocument scene, HtmlViewerOptions? viewerOptions) + { if (viewerOptions is null) { - viewerOptions = new HtmlViewerOptions { Title = scene.Title }; + return new HtmlViewerOptions { Title = scene.Title }; } - else if (string.IsNullOrEmpty(viewerOptions.Title)) + + return new HtmlViewerOptions + { + Title = string.IsNullOrEmpty(viewerOptions.Title) ? scene.Title : viewerOptions.Title, + IncludeProperties = viewerOptions.IncludeProperties, + IncludeViewpoints = viewerOptions.IncludeViewpoints, + IncludeGrids = viewerOptions.IncludeGrids, + IncludeTimeLiner = viewerOptions.IncludeTimeLiner, + IncludeClashes = viewerOptions.IncludeClashes, + InitialWireframe = viewerOptions.InitialWireframe, + InitialWhiteMode = viewerOptions.InitialWhiteMode, + Initial2DMode = viewerOptions.Initial2DMode, + InitialBackground = viewerOptions.InitialBackground, + MaxMeshVertices = viewerOptions.MaxMeshVertices, + }; + } + + private static ViewerDocument ToViewerDocument(DwgSceneResult result, HtmlViewerOptions options) + { + var viewer = new ViewerDocument(result.Document) + { + InitialSheetKey = options.Initial2DMode + ? result.InitialSheetKey + : result.Sheets.FirstOrDefault(s => s.IsModelSpace)?.Key ?? result.InitialSheetKey, + }; + + foreach (var a in result.Annotations) + { + viewer.Annotations.Add(new ViewerAnnotation + { + Text = a.Text, + Position = a.Position, + Height = a.Height, + RotationRadians = a.RotationRadians, + Width = a.Width, + Attachment = a.Attachment, + Color = a.Color, + ElementId = a.ElementId, + SheetKey = a.SheetKey, + }); + } + + string modelBackground = string.IsNullOrWhiteSpace(options.InitialBackground) ? "#14171c" : options.InitialBackground!; + foreach (var s in result.Sheets) { - viewerOptions.Title = scene.Title; + viewer.Sheets.Add(new ViewerSheet + { + Key = s.Key, + Name = s.Name, + IsModelSpace = s.IsModelSpace, + Is2D = s.IsModelSpace ? options.Initial2DMode : true, + BackgroundColor = s.IsModelSpace ? modelBackground : "#ffffff", + PaperBounds = s.PaperBounds, + ElementIds = s.ElementIds, + }); } - var drawableScene = ViewerMeshGeometry.Adapt(scene); - AtomicOutput.Write(htmlPath, stream => HtmlViewerExporter.Export(drawableScene, stream, viewerOptions)); + return viewer; } private static DwgSceneOptions ViewerOptionsFor(DwgDocument document, string path, DwgSceneOptions? options) @@ -57,12 +129,15 @@ private static DwgSceneOptions ViewerOptionsFor(DwgDocument document, string pat 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", UseDrawingUnits = options?.UseDrawingUnits ?? false, + ExpandBlocks = options?.ExpandBlocks ?? true, + ResolveXrefs = options?.ResolveXrefs ?? false, + IncludePaperSpace = options?.IncludePaperSpace ?? true, ModelKey = Path.GetFileName(path), + ReadProgress = options?.ReadProgress, }; } } diff --git a/src/DwgIO.Scene/Compatibility/ViewerMeshGeometry.cs b/src/DwgIO.Scene/Compatibility/ViewerMeshGeometry.cs deleted file mode 100644 index 355ef95..0000000 --- a/src/DwgIO.Scene/Compatibility/ViewerMeshGeometry.cs +++ /dev/null @@ -1,109 +0,0 @@ -using IOScene; - -namespace DwgIO.Scene; - -internal static class ViewerMeshGeometry -{ - // 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)) - { - return scene; - } - - var bounds = scene.ComputeBounds(); - double extent = bounds.IsEmpty ? 0 : MaxComponent(bounds.Size); - double halfWidth = extent > 0 && double.IsFinite(extent) ? extent / 1500 : 0.001; - - return new SceneDocument - { - Title = scene.Title, - Models = scene.Models, - Materials = scene.Materials, - Textures = scene.Textures, - PropertySets = scene.PropertySets, - Levels = scene.Levels, - Elements = scene.Elements, - Instances = scene.Instances, - Grids = scene.Grids, - Viewpoints = scene.Viewpoints, - Schedules = scene.Schedules, - ClashTests = scene.ClashTests, - Geometries = scene.Geometries.ConvertAll(g => ToTriangles(g, halfWidth)), - }; - } - - private static SceneGeometry ToTriangles(SceneGeometry geometry, double halfWidth) - { - if (geometry.Topology is not (SceneTopology.Lines or SceneTopology.Points)) - { - return geometry; - } - - bool isLine = geometry.Topology == SceneTopology.Lines; - int count = geometry.Indices.Count == 0 ? geometry.Vertices.Count : geometry.Indices.Count; - int stride = isLine ? 2 : 1; - if (count % stride != 0) - { - throw new InvalidDataException($"Geometry {geometry.Id} has an incomplete line segment."); - } - - var vertices = new List(); - var indices = new List(); - for (int i = 0; i < count; i += stride) - { - Vector3d a = Vertex(i); - Vector3d b = isLine ? Vertex(i + 1) : a; - Vector3d delta = b - a; - double scale = MaxComponent(delta); - double radius = Math.Max(halfWidth, Math.Max(MaxComponent(a), MaxComponent(b)) * 1e-15); - if (scale == 0) - { - AddPoint(a, radius); - continue; - } - - Vector3d axis = (delta / scale).Normalized(); - Vector3d side = Vector3d.Cross(axis, Math.Abs(axis.Z) < 0.9 ? Vector3d.UnitZ : Vector3d.UnitX).Normalized(); - AddRibbon(a, b, side * radius); - AddRibbon(a, b, Vector3d.Cross(axis, side) * radius); - } - - return new SceneGeometry { Id = geometry.Id, Vertices = vertices, Indices = indices }; - - Vector3d Vertex(int i) - { - int index = geometry.Indices.Count == 0 ? i : geometry.Indices[i]; - if ((uint)index >= (uint)geometry.Vertices.Count) - { - throw new InvalidDataException($"Geometry {geometry.Id} references missing vertex {index}."); - } - - var vertex = geometry.Vertices[index]; - if (!double.IsFinite(MaxComponent(vertex))) - { - throw new InvalidDataException($"Geometry {geometry.Id} has a non-finite coordinate."); - } - - return vertex; - } - - void AddRibbon(Vector3d a, Vector3d b, Vector3d side) - { - int first = vertices.Count; - vertices.AddRange([a - side, b - side, b + side, a + side]); - indices.AddRange([first, first + 1, first + 2, first, first + 2, first + 3]); - } - - void AddPoint(Vector3d p, double radius) - { - AddRibbon(p - Vector3d.UnitX * radius, p + Vector3d.UnitX * radius, Vector3d.UnitY * radius); - AddRibbon(p - Vector3d.UnitX * radius, p + Vector3d.UnitX * radius, Vector3d.UnitZ * radius); - AddRibbon(p - Vector3d.UnitY * radius, p + Vector3d.UnitY * radius, Vector3d.UnitZ * radius); - } - } - - private static double MaxComponent(Vector3d vector) => - Math.Max(Math.Abs(vector.X), Math.Max(Math.Abs(vector.Y), Math.Abs(vector.Z))); -} diff --git a/src/DwgIO/DwgDocument.cs b/src/DwgIO/DwgDocument.cs index b696a4c..fce155d 100644 --- a/src/DwgIO/DwgDocument.cs +++ b/src/DwgIO/DwgDocument.cs @@ -77,6 +77,8 @@ private DwgDocument( Objects = ReadOptionalObjects(options.MaxObjectCount, classesByCode); Layers = options.ReadLayers ? ReadOptionalLayers() : []; var layersByHandle = BuildLayerLookup(Layers); + Blocks = ReadOptionalBlocks(); + Layouts = ReadOptionalLayouts(Blocks, Objects); if (options.ReadEntities) { options.Progress?.Report(new DwgReadProgress("entities", 0, Objects.Count)); @@ -169,6 +171,12 @@ private DwgDocument( /// Layer table records decoded from LAYER objects in AcDb:AcDbObjects. public IReadOnlyList Layers { get; } = []; + /// Block records decoded from BLOCK_RECORD objects in AcDb:AcDbObjects. + public IReadOnlyList Blocks { get; } = []; + + /// Layouts decoded from LAYOUT objects in AcDb:AcDbObjects. + public IReadOnlyList Layouts { get; } = []; + /// Decoded entities with geometry — requires ReadObjects. public IReadOnlyList Entities { get; } = []; @@ -178,7 +186,8 @@ private DwgDocument( /// Creates an in-memory document over a file header and a fixed entity list (tests). internal DwgDocument(string path, DwgFileHeader fileHeader, IReadOnlyList entities, DwgPreview? preview = null, IReadOnlyList? objects = null, IEnumerable? diagnostics = null, - DwgHeaderVariables? headerVariables = null, IReadOnlyList? layers = null) + DwgHeaderVariables? headerVariables = null, IReadOnlyList? layers = null, + IReadOnlyList? blocks = null, IReadOnlyList? layouts = null) { Path = path; SourcePath = null; @@ -192,6 +201,8 @@ internal DwgDocument(string path, DwgFileHeader fileHeader, IReadOnlyList ReadOptionalLayers() return map; } + private List ReadOptionalBlocks() + { + if (_objectStreamBytes is null) + { + return []; + } + + int year = FileHeader.Version.Year; + ushort codepage = FileHeader.Codepage; + var layoutHandles = new HashSet(); + foreach (var obj in Objects) + { + if (obj.TypeCode == LayoutParser.LayoutTypeCode) + { + layoutHandles.Add(obj.Handle); + } + } + + var blocks = new List(); + foreach (var info in Objects) + { + if (info.TypeCode != BlockRecordParser.BlockRecordTypeCode) + { + continue; + } + + try + { + blocks.Add(BlockRecordParser.Parse(info, _objectStreamBytes, year, codepage, layoutHandles)); + } + catch (Exception ex) when (IsParseFailure(ex)) + { + AddDiagnostic($"block {info.Handle:X} @{info.StreamOffset}: {ex.Message}"); + } + } + + return blocks; + } + + private List ReadOptionalLayouts( + IReadOnlyList blocks, + IReadOnlyList objects) + { + if (_objectStreamBytes is null) + { + return []; + } + + int year = FileHeader.Version.Year; + ushort codepage = FileHeader.Codepage; + var blockNames = new Dictionary(blocks.Count); + foreach (var b in blocks) + { + blockNames.TryAdd(b.Handle, b.Name); + } + + var viewportHandles = new HashSet(); + foreach (var obj in objects) + { + if (obj.TypeCode == 0x22) + { + viewportHandles.Add(obj.Handle); + } + } + + var layouts = new List(); + foreach (var info in objects) + { + if (info.TypeCode != LayoutParser.LayoutTypeCode) + { + continue; + } + + try + { + layouts.Add(LayoutParser.Parse(info, _objectStreamBytes, year, codepage, blockNames, viewportHandles)); + } + catch (Exception ex) when (IsParseFailure(ex)) + { + AddDiagnostic($"layout {info.Handle:X} @{info.StreamOffset}: {ex.Message}"); + } + } + + return layouts; + } + private List ReadOptionalEntities( Dictionary? classesByCode, Dictionary? layersByHandle) @@ -716,6 +813,9 @@ private List ReadOptionalEntities( int year = FileHeader.Version.Year; var entities = new List(); + var polylineVerticesByOwner = new Dictionary>(); + ulong? activePolylineHandle = null; + foreach (var info in Objects) { bool isEntity = EntityDecoder.IsEntityCode(info.TypeCode) @@ -729,6 +829,31 @@ private List ReadOptionalEntities( { if (EntityDecoder.Decode(info, _objectStreamBytes, year, isEntity, layersByHandle, FileHeader.Codepage) is { } entity) { + if (entity.TypeCode is 0x0F or 0x10) + { + activePolylineHandle = entity.Handle; + } + else if (entity.TypeCode is 0x0A or 0x0B && entity.Geometry is { Length: >= 4 } vg) + { + ulong? owner = entity.OwnerHandle ?? activePolylineHandle; + if (owner is ulong ownerKey) + { + if (!polylineVerticesByOwner.TryGetValue(ownerKey, out var list)) + { + list = []; + polylineVerticesByOwner[ownerKey] = list; + } + + list.Add((vg[0], vg[1], vg[2], vg[3])); + } + + entity = WithGeometry(entity, null); + } + else if (entity.TypeCode == 0x06) + { + activePolylineHandle = null; + } + entities.Add(entity); } } @@ -738,9 +863,76 @@ private List ReadOptionalEntities( } } + if (polylineVerticesByOwner.Count > 0) + { + for (int i = 0; i < entities.Count; i++) + { + var entity = entities[i]; + if (entity.TypeCode is not (0x0F or 0x10) + || !polylineVerticesByOwner.TryGetValue(entity.Handle, out var verts) + || verts.Count < 2) + { + continue; + } + + double isClosed = entity.Geometry is { Length: > 0 } ? entity.Geometry[0] : 0.0; + if (entity.TypeCode == 0x0F) + { + double elevation = entity.Geometry is { Length: > 1 } ? entity.Geometry[1] : verts[0].Z; + var payload = new double[2 + verts.Count * 3]; + payload[0] = isClosed; + payload[1] = elevation; + for (int v = 0; v < verts.Count; v++) + { + int o = 2 + v * 3; + payload[o] = verts[v].X; + payload[o + 1] = verts[v].Y; + payload[o + 2] = verts[v].Bulge; + } + + entities[i] = WithGeometry(entity, payload); + } + else + { + var payload = new double[1 + verts.Count * 3]; + payload[0] = isClosed; + for (int v = 0; v < verts.Count; v++) + { + int o = 1 + v * 3; + payload[o] = verts[v].X; + payload[o + 1] = verts[v].Y; + payload[o + 2] = verts[v].Z; + } + + entities[i] = WithGeometry(entity, payload); + } + } + } + return entities; } + private static DwgEntity WithGeometry(DwgEntity source, double[]? geometry) => new() + { + Handle = source.Handle, + TypeCode = source.TypeCode, + TypeName = source.TypeName, + Kind = source.Kind, + Geometry = geometry, + Text = source.Text, + IsModelSpace = source.IsModelSpace, + OwnerHandle = source.OwnerHandle, + BlockHeaderHandle = source.BlockHeaderHandle, + Viewport = source.Viewport, + ColorIndex = source.ColorIndex, + TrueColorRgb = source.TrueColorRgb, + LineTypeScale = source.LineTypeScale, + LayerHandle = source.LayerHandle, + LayerName = source.LayerName, + LayerColorIndex = source.LayerColorIndex, + LayerTrueColorRgb = source.LayerTrueColorRgb, + }; + private ReadOnlyMemory ReadAppInfoHistory() { if (!TryGetReadableSection("AcDb:AppInfoHistory", out var entry)) diff --git a/src/DwgIO/Internal/Parsing/BlockRecordParser.cs b/src/DwgIO/Internal/Parsing/BlockRecordParser.cs new file mode 100644 index 0000000..6242ac2 --- /dev/null +++ b/src/DwgIO/Internal/Parsing/BlockRecordParser.cs @@ -0,0 +1,136 @@ +using DwgIO.Internal.Container; +using DwgIO.Model; + +namespace DwgIO.Internal.Parsing; + +/// +/// Parses BLOCK_RECORD (0x31) table records from AcDb:AcDbObjects into . +/// +internal static class BlockRecordParser +{ + public const ushort BlockRecordTypeCode = 0x31; + + public static DwgBlockInfo Parse( + DwgObjectInfo info, + byte[] stream, + int year, + ushort codepage, + IReadOnlySet? knownLayoutHandles = null) + { + var reader = new BitReaderMsb(stream[info.BitsStart..(info.BitsStart + info.BitsLength)]); + ulong handleStreamBits = year >= 2010 ? reader.ReadVarUInt() : 0UL; + + _ = reader.ReadObjectType(year >= 2010); + _ = reader.ReadHandle(); + + EntityDecoder.SkipExtendedData(reader); + uint reactorCount = reader.ReadPackedInt(); + bool noXdic = reader.ReadBit(); + if (year >= 2013) + { + _ = reader.ReadBit(); // has AcDs binary data + } + + var strings = RecordStringStream.Open(info, stream, year, codepage, handleStreamBits, reader.PositionBit, "BLOCK_RECORD"); + string name = strings.Read(reader, "BLOCK_RECORD", year); + + bool hasNoXrefIndex = reader.ReadBit(); // 64-flag + if (!hasNoXrefIndex) + { + _ = reader.ReadPackedShort(); + } + + _ = reader.ReadBit(); // xref dependent + bool isAnonymous = reader.ReadBit(); + bool hasAttributes = reader.ReadBit(); + bool isXref = reader.ReadBit(); + bool isXrefOverlay = reader.ReadBit(); + bool isLoaded = year >= 2000 && reader.ReadBit(); + + uint ownedCount = year >= 2004 ? reader.ReadPackedInt() : 0U; + string? xrefPath = isXref ? strings.Read(reader, "BLOCK_RECORD", year) : null; + + var (ownedHandles, layoutHandle) = ReadHandles( + reader, info, year, handleStreamBits, reactorCount, noXdic, ownedCount, knownLayoutHandles); + + return new DwgBlockInfo + { + Handle = info.Handle, + Name = name, + IsAnonymous = isAnonymous, + HasAttributes = hasAttributes, + IsXref = isXref, + IsXrefOverlay = isXrefOverlay, + IsLoaded = isLoaded, + XrefPath = string.IsNullOrWhiteSpace(xrefPath) ? null : xrefPath, + LayoutHandle = layoutHandle, + OwnedEntityHandles = ownedHandles, + }; + } + + private static (List OwnedHandles, ulong? LayoutHandle) ReadHandles( + BitReaderMsb reader, + DwgObjectInfo info, + int year, + ulong handleStreamBits, + uint reactorCount, + bool noXdic, + uint ownedCount, + IReadOnlySet? knownLayoutHandles) + { + var owned = new List(); + if (year >= 2010) + { + if (handleStreamBits == 0 || handleStreamBits > (ulong)info.BitsLength * 8) + { + return (owned, null); + } + + reader.SeekBit(info.BitsLength * 8 - (int)handleStreamBits); + } + else if (year >= 2007) + { + return (owned, null); + } + + var allHandles = new List(); + try + { + while (reader.RemainingBits >= 8) + { + allHandles.Add(reader.ReadHandle().ResolveTarget(info.Handle)); + } + } + catch (DwgException) + { + // Return whatever handles were read cleanly. + } + + // Handle stream layout for BLOCK_RECORD: + // [0] BLOCK_CONTROL (owner), [1..reactorCount] reactors, [optional xdic], [owned entities...], BLOCK, ENDBLK, [inserts...], [LAYOUT]. + int skip = 1 + (int)Math.Min(reactorCount, (uint)allHandles.Count) + (noXdic ? 0 : 1); + for (int i = 0; i < (int)ownedCount && skip + i < allHandles.Count; i++) + { + ulong h = allHandles[skip + i]; + if (h != 0) + { + owned.Add(h); + } + } + + ulong? layoutHandle = null; + if (knownLayoutHandles is not null) + { + for (int i = allHandles.Count - 1; i >= skip; i--) + { + if (allHandles[i] != 0 && knownLayoutHandles.Contains(allHandles[i])) + { + layoutHandle = allHandles[i]; + break; + } + } + } + + return (owned, layoutHandle); + } +} diff --git a/src/DwgIO/Internal/Parsing/EntityDecoder.cs b/src/DwgIO/Internal/Parsing/EntityDecoder.cs index d22706e..618c4ce 100644 --- a/src/DwgIO/Internal/Parsing/EntityDecoder.cs +++ b/src/DwgIO/Internal/Parsing/EntityDecoder.cs @@ -91,37 +91,49 @@ RecordStringStream GetStrings() => } double lineTypeScale = reader.ReadPackedDouble(); - reader.ReadTwoBits(); // linetype flags - reader.ReadTwoBits(); // plot-style flags (R2000+) - reader.ReadTwoBits(); // material flag (R2007+) + uint ltypeFlags = reader.ReadTwoBits(); // linetype flags + uint plotFlags = reader.ReadTwoBits(); // plot-style flags (R2000+) + uint materialFlags = reader.ReadTwoBits(); // material flag (R2007+) reader.ReadRawByte(); // shadow flags (R2007+) + bool hasFullVisualStyle = false; + bool hasFaceVisualStyle = false; + bool hasEdgeVisualStyle = false; if (year >= 2010) { - reader.ReadBit(); // full visual style - reader.ReadBit(); // face visual style - reader.ReadBit(); // edge visual style + hasFullVisualStyle = reader.ReadBit(); + hasFaceVisualStyle = reader.ReadBit(); + hasEdgeVisualStyle = reader.ReadBit(); } reader.ReadPackedShort(); // invisibility reader.ReadRawByte(); // lineweight (R2000+) + DwgViewportData? viewportData = null; (DwgEntityKind kind, double[]? geometry, string? text)? body = info.TypeCode switch { 0x01 => DecodeText(reader, GetStrings(), year), + 0x07 => WithNoText(DecodeInsert(reader, year, isMInsert: false)), + 0x08 => WithNoText(DecodeInsert(reader, year, isMInsert: true)), + 0x0A => WithNoText(DecodeVertex2d(reader, year)), + 0x0B => WithNoText(DecodeVertex3d(reader)), + 0x0F => WithNoText(DecodePolyline2d(reader, year)), + 0x10 => WithNoText(DecodePolyline3d(reader)), 0x11 => WithNoText(DecodeArc(reader)), 0x12 => WithNoText(DecodeCircle(reader)), 0x13 => WithNoText(DecodeLine(reader)), 0x1B => WithNoText(DecodePoint(reader)), 0x1C => WithNoText(DecodeFace3d(reader)), 0x1F or 0x20 => WithNoText(DecodeSolidOrTrace(reader)), + 0x22 => DecodeViewport(reader, year, out viewportData), 0x23 => WithNoText(DecodeEllipse(reader)), + 0x24 => WithNoText(DecodeSpline(reader, year)), 0x28 or 0x29 => WithNoText(DecodeRayOrXLine(reader, info.TypeCode == 0x28 ? DwgEntityKind.Ray : DwgEntityKind.XLine)), 0x2C => DecodeMText(reader, GetStrings(), year), 0x4D => WithNoText(DecodeLwPolyline(reader, year)), _ => null, }; - ulong? layerHandle = TryReadLayerHandle( + (ulong? ownerHandle, ulong? layerHandle, ulong? blockHeaderHandle) = TryReadEntityHandles( reader, info, year, @@ -129,6 +141,12 @@ RecordStringStream GetStrings() => entityMode, reactorCount, noXdic, + ltypeFlags, + plotFlags, + materialFlags, + hasFullVisualStyle, + hasFaceVisualStyle, + hasEdgeVisualStyle, bodyDecoded: body is not null); DwgLayerInfo? layer = layerHandle is ulong lh && layersByHandle is not null && layersByHandle.TryGetValue(lh, out var resolved) ? resolved @@ -146,6 +164,9 @@ RecordStringStream GetStrings() => TrueColorRgb = trueColorRgb, LineTypeScale = lineTypeScale, IsModelSpace = isModelSpace, + OwnerHandle = ownerHandle, + BlockHeaderHandle = blockHeaderHandle, + Viewport = viewportData, LayerHandle = layerHandle, LayerName = layer?.Name, LayerColorIndex = layer?.ColorIndex, @@ -156,7 +177,7 @@ RecordStringStream GetStrings() => private static (DwgEntityKind kind, double[]? geometry, string? text) WithNoText((DwgEntityKind kind, double[] geometry) item) => (item.kind, item.geometry, null); - private static ulong? TryReadLayerHandle( + private static (ulong? OwnerHandle, ulong? LayerHandle, ulong? BlockHeaderHandle) TryReadEntityHandles( BitReaderMsb reader, DwgObjectInfo info, int year, @@ -164,45 +185,55 @@ private static (DwgEntityKind kind, double[]? geometry, string? text) WithNoText uint entityMode, uint reactorCount, bool noXdic, + uint ltypeFlags, + uint plotFlags, + uint materialFlags, + bool hasFullVisualStyle, + bool hasFaceVisualStyle, + bool hasEdgeVisualStyle, bool bodyDecoded) { if (year >= 2010) { if (handleStreamBits == 0 || handleStreamBits > (ulong)info.BitsLength * 8) { - return null; + return (null, null, null); } int handleStartBit = info.BitsLength * 8 - (int)handleStreamBits; if (handleStartBit < 0 || handleStartBit >= info.BitsLength * 8) { - return null; + return (null, null, null); } reader.SeekBit(handleStartBit); } else if (year >= 2007 || !bodyDecoded) { - return null; + return (null, null, null); } + ulong? ownerHandle = null; + ulong? layerHandle = null; + ulong? blockHeaderHandle = null; try { if (entityMode == 0) { if (reader.RemainingBits < 8) { - return null; + return (ownerHandle, layerHandle, blockHeaderHandle); } - _ = reader.ReadHandle(); // Owner + ulong resolvedOwner = reader.ReadHandle().ResolveTarget(info.Handle); + ownerHandle = resolvedOwner == 0 ? null : resolvedOwner; } for (uint i = 0; i < reactorCount && i < 65535; i++) { if (reader.RemainingBits < 8) { - return null; + return (ownerHandle, layerHandle, blockHeaderHandle); } _ = reader.ReadHandle(); @@ -212,7 +243,7 @@ private static (DwgEntityKind kind, double[]? geometry, string? text) WithNoText { if (reader.RemainingBits < 8) { - return null; + return (ownerHandle, layerHandle, blockHeaderHandle); } _ = reader.ReadHandle(); // XdicObj @@ -220,15 +251,57 @@ private static (DwgEntityKind kind, double[]? geometry, string? text) WithNoText if (reader.RemainingBits < 8) { - return null; + return (ownerHandle, layerHandle, blockHeaderHandle); + } + + ulong resolvedLayer = reader.ReadHandle().ResolveTarget(info.Handle); + layerHandle = resolvedLayer == 0 ? null : resolvedLayer; + + // Optional common entity handles preceding entity-specific handles (BLOCK_RECORD for INSERT/MINSERT). + if (ltypeFlags == 3 && reader.RemainingBits >= 8) + { + _ = reader.ReadHandle(); + } + + if (year >= 2000 && plotFlags == 3 && reader.RemainingBits >= 8) + { + _ = reader.ReadHandle(); + } + + if (year >= 2007 && materialFlags == 3 && reader.RemainingBits >= 8) + { + _ = reader.ReadHandle(); } - ulong resolved = reader.ReadHandle().ResolveTarget(info.Handle); - return resolved == 0 ? null : resolved; + if (year >= 2010) + { + if (hasFullVisualStyle && reader.RemainingBits >= 8) + { + _ = reader.ReadHandle(); + } + + if (hasFaceVisualStyle && reader.RemainingBits >= 8) + { + _ = reader.ReadHandle(); + } + + if (hasEdgeVisualStyle && reader.RemainingBits >= 8) + { + _ = reader.ReadHandle(); + } + } + + if (info.TypeCode is 0x07 or 0x08 && reader.RemainingBits >= 8) + { + ulong resolvedBlock = reader.ReadHandle().ResolveTarget(info.Handle); + blockHeaderHandle = resolvedBlock == 0 ? null : resolvedBlock; + } + + return (ownerHandle, layerHandle, blockHeaderHandle); } catch (DwgException) { - return null; + return (ownerHandle, layerHandle, blockHeaderHandle); } } @@ -545,4 +618,251 @@ private static (DwgEntityKind, double[]) DecodeLwPolyline(BitReaderMsb reader, i return (DwgEntityKind.Polyline, payload); } + + private static (DwgEntityKind, double[]) DecodeInsert(BitReaderMsb reader, int year, bool isMInsert) + { + double x = reader.ReadPackedDouble(); + double y = reader.ReadPackedDouble(); + double z = reader.ReadPackedDouble(); + + uint scaleFlag = reader.ReadTwoBits(); + double sx = 1.0, sy = 1.0, sz = 1.0; + switch (scaleFlag) + { + case 0: + sx = reader.ReadRawDouble(); + sy = reader.ReadDoubleWithDefault(sx); + sz = reader.ReadDoubleWithDefault(sx); + break; + case 1: + sx = 1.0; + sy = reader.ReadDoubleWithDefault(1.0); + sz = reader.ReadDoubleWithDefault(1.0); + break; + case 2: + sx = reader.ReadRawDouble(); + sy = sx; + sz = sx; + break; + } + + double rotation = reader.ReadPackedDouble(); + double nx = reader.ReadPackedDouble(); + double ny = reader.ReadPackedDouble(); + double nz = reader.ReadPackedDouble(); + + bool hasAttribs = reader.ReadBit(); + if (hasAttribs && year >= 2004) + { + _ = reader.ReadPackedInt(); // owned attrib count + } + + double colCount = 1, rowCount = 1, colSpacing = 0, rowSpacing = 0; + if (isMInsert) + { + colCount = reader.ReadPackedShort(); + rowCount = reader.ReadPackedShort(); + colSpacing = reader.ReadPackedDouble(); + rowSpacing = reader.ReadPackedDouble(); + } + + return (DwgEntityKind.Insert, [x, y, z, sx, sy, sz, rotation, nx, ny, nz, colCount, rowCount, colSpacing, rowSpacing]); + } + + private static (DwgEntityKind, double[]) DecodePolyline2d(BitReaderMsb reader, int year) + { + uint flags = reader.ReadPackedShort(); + _ = reader.ReadPackedShort(); // curve type + _ = reader.ReadPackedDouble(); // start width + _ = reader.ReadPackedDouble(); // end width + _ = ReadThickness(reader); + double elevation = reader.ReadPackedDouble(); + _ = ReadExtrusion(reader); + if (year >= 2004) + { + _ = reader.ReadPackedInt(); // owned vertex count + } + + return (DwgEntityKind.Polyline, [(flags & 1) != 0 ? 1.0 : 0.0, elevation]); + } + + private static (DwgEntityKind, double[]) DecodeVertex2d(BitReaderMsb reader, int year) + { + _ = reader.ReadRawByte(); // flags + double x = reader.ReadPackedDouble(); + double y = reader.ReadPackedDouble(); + double z = reader.ReadPackedDouble(); + double startWidth = reader.ReadPackedDouble(); + if (startWidth < 0) + { + _ = Math.Abs(startWidth); + } + else + { + _ = reader.ReadPackedDouble(); // end width + } + + double bulge = reader.ReadPackedDouble(); + if (year >= 2010) + { + _ = reader.ReadPackedInt(); // vertex id + } + + _ = reader.ReadPackedDouble(); // tangent dir + return (DwgEntityKind.Unknown, [x, y, z, bulge]); + } + + private static (DwgEntityKind, double[]) DecodePolyline3d(BitReaderMsb reader) + { + byte splineFlags = reader.ReadRawByte(); + byte flags = reader.ReadRawByte(); + _ = splineFlags; + return (DwgEntityKind.Polyline3d, [(flags & 1) != 0 ? 1.0 : 0.0]); + } + + private static (DwgEntityKind, double[]) DecodeVertex3d(BitReaderMsb reader) + { + _ = reader.ReadRawByte(); // flags + double x = reader.ReadPackedDouble(); + double y = reader.ReadPackedDouble(); + double z = reader.ReadPackedDouble(); + return (DwgEntityKind.Unknown, [x, y, z, 0.0]); + } + + private static (DwgEntityKind kind, double[]? geometry, string? text) DecodeViewport( + BitReaderMsb reader, + int year, + out DwgViewportData data) + { + double cx = reader.ReadPackedDouble(); + double cy = reader.ReadPackedDouble(); + double cz = reader.ReadPackedDouble(); + double width = reader.ReadPackedDouble(); + double height = reader.ReadPackedDouble(); + double tx = reader.ReadPackedDouble(); + double ty = reader.ReadPackedDouble(); + double tz = reader.ReadPackedDouble(); + double dx = reader.ReadPackedDouble(); + double dy = reader.ReadPackedDouble(); + double dz = reader.ReadPackedDouble(); + double twist = reader.ReadPackedDouble(); + double viewHeight = reader.ReadPackedDouble(); + double lens = reader.ReadPackedDouble(); + _ = reader.ReadPackedDouble(); // front clip Z + _ = reader.ReadPackedDouble(); // back clip Z + _ = reader.ReadPackedDouble(); // snap angle + + double vcx = reader.ReadRawDouble(); + double vcy = reader.ReadRawDouble(); + for (int i = 0; i < 6; i++) + { + _ = reader.ReadRawDouble(); // snapBase(2), snapSpacing(2), gridSpacing(2) + } + + _ = reader.ReadPackedShort(); // circle zoom + if (year >= 2007) + { + _ = reader.ReadPackedShort(); // grid major + } + + uint frozenCount = reader.ReadPackedInt(); + _ = frozenCount; + uint statusFlags = reader.ReadPackedInt(); + + data = new DwgViewportData + { + Center = new DwgPoint3D(cx, cy, cz), + Width = width, + Height = height, + ViewTarget = new DwgPoint3D(tx, ty, tz), + ViewDirection = new DwgPoint3D(dx, dy, dz), + ViewCenter = new DwgPoint2D(vcx, vcy), + ViewHeight = viewHeight, + TwistAngleRadians = twist, + LensLength = lens, + StatusFlags = statusFlags, + }; + + return (DwgEntityKind.Viewport, null, null); + } + + private static (DwgEntityKind, double[]) DecodeSpline(BitReaderMsb reader, int year) + { + uint scenario = reader.ReadPackedInt(); + if (year >= 2013) + { + _ = reader.ReadPackedInt(); // spline flags 1 + _ = reader.ReadPackedInt(); // knot parameterization + } + + bool closed = false; + var pts = new List<(double X, double Y, double Z)>(); + + if (scenario == 1) + { + int degree = (int)reader.ReadPackedInt(); + _ = reader.ReadBit(); // rational + closed = reader.ReadBit(); + _ = reader.ReadBit(); // periodic + _ = reader.ReadPackedDouble(); // knot tolerance + _ = reader.ReadPackedDouble(); // control tolerance + uint numKnots = reader.ReadPackedInt(); + uint numCtrl = reader.ReadPackedInt(); + bool weighted = reader.ReadBit(); + + if (numKnots > MaxPolylineVertices || numCtrl > MaxPolylineVertices) + { + throw new DwgException($"SPLINE element count ({numCtrl}) exceeds safety cap."); + } + + var knots = new double[numKnots]; + for (int i = 0; i < (int)numKnots; i++) + { + knots[i] = reader.ReadPackedDouble(); + } + + var ctrls = new (double X, double Y, double Z, double W)[numCtrl]; + for (int i = 0; i < (int)numCtrl; i++) + { + double x = reader.ReadPackedDouble(); + double y = reader.ReadPackedDouble(); + double z = reader.ReadPackedDouble(); + double w = weighted ? reader.ReadPackedDouble() : 1.0; + ctrls[i] = (x, y, z, w); + } + + pts = SplineEvaluator.Evaluate(degree, knots, ctrls, closed); + } + else if (scenario == 2) + { + _ = reader.ReadPackedDouble(); // fit tolerance + for (int i = 0; i < 6; i++) + { + _ = reader.ReadPackedDouble(); // start + end tangents + } + + uint numFit = reader.ReadPackedInt(); + if (numFit > MaxPolylineVertices) + { + throw new DwgException($"SPLINE fit point count ({numFit}) exceeds safety cap."); + } + + for (int i = 0; i < (int)numFit; i++) + { + pts.Add((reader.ReadPackedDouble(), reader.ReadPackedDouble(), reader.ReadPackedDouble())); + } + } + + var payload = new double[1 + pts.Count * 3]; + payload[0] = closed ? 1.0 : 0.0; + for (int i = 0; i < pts.Count; i++) + { + int o = 1 + i * 3; + payload[o] = pts[i].X; + payload[o + 1] = pts[i].Y; + payload[o + 2] = pts[i].Z; + } + + return (DwgEntityKind.Spline, payload); + } } diff --git a/src/DwgIO/Internal/Parsing/HeaderParser.cs b/src/DwgIO/Internal/Parsing/HeaderParser.cs index cbd1ced..1541d3d 100644 --- a/src/DwgIO/Internal/Parsing/HeaderParser.cs +++ b/src/DwgIO/Internal/Parsing/HeaderParser.cs @@ -191,10 +191,12 @@ public static DwgHeaderVariables Parse(byte[] bytes, int year, ushort codepage, short ceColorIndex = ReadCmcColorIndex(reader, stringReader, encoding, year, stringEndBit); ulong handseed = reader.ReadHandle().Value; + // DWG R2000+ header streams include a trailing packed short after HANDSEED/INSBASE before EXTMIN; + // skipping it after EXTMAX only worked when ExtMax.Z was 0 (2 bits). var insBase = ReadPoint3D(reader); + _ = reader.ReadPackedShort(); var extMin = ReadPoint3D(reader); var extMax = ReadPoint3D(reader); - _ = reader.ReadPackedShort(); var limMin = new DwgPoint2D(reader.ReadRawDouble(), reader.ReadRawDouble()); var limMax = new DwgPoint2D(reader.ReadRawDouble(), reader.ReadRawDouble()); diff --git a/src/DwgIO/Internal/Parsing/LayoutParser.cs b/src/DwgIO/Internal/Parsing/LayoutParser.cs new file mode 100644 index 0000000..75cbb6a --- /dev/null +++ b/src/DwgIO/Internal/Parsing/LayoutParser.cs @@ -0,0 +1,104 @@ +using DwgIO.Internal.Container; +using DwgIO.Model; + +namespace DwgIO.Internal.Parsing; + +/// +/// Parses LAYOUT (0x52) dictionary entries from AcDb:AcDbObjects into . +/// +internal static class LayoutParser +{ + public const ushort LayoutTypeCode = 0x52; + + public static DwgLayoutInfo Parse( + DwgObjectInfo info, + byte[] stream, + int year, + ushort codepage, + IReadOnlyDictionary blockNamesByHandle, + IReadOnlySet viewportHandles) + { + var reader = new BitReaderMsb(stream[info.BitsStart..(info.BitsStart + info.BitsLength)]); + ulong handleStreamBits = year >= 2010 ? reader.ReadVarUInt() : 0UL; + + _ = reader.ReadObjectType(year >= 2010); + _ = reader.ReadHandle(); + + EntityDecoder.SkipExtendedData(reader); + _ = reader.ReadPackedInt(); // reactor count + _ = reader.ReadBit(); // no extension dictionary + if (year >= 2013) + { + _ = reader.ReadBit(); // has AcDs binary data + } + + // PlotSettings contributes up to 4 strings (pageSetupName, plotConfigName, paperSize, plotViewName) before LayoutName. + var strings = RecordStringStream.Open(info, stream, year, codepage, handleStreamBits, reader.PositionBit, "LAYOUT"); + string name = string.Empty; + if (year >= 2007) + { + for (int i = 0; i < 4; i++) + { + _ = strings.Read(reader, "LAYOUT", year); + } + + name = strings.Read(reader, "LAYOUT", year); + } + + ulong? blockHeaderHandle = null; + ulong? overallViewportHandle = null; + var floatingViewports = new List(); + + if (year >= 2010 && handleStreamBits > 0 && handleStreamBits <= (ulong)info.BitsLength * 8) + { + reader.SeekBit(info.BitsLength * 8 - (int)handleStreamBits); + while (reader.RemainingBits >= 8) + { + ulong target; + try + { + target = reader.ReadHandle().ResolveTarget(info.Handle); + } + catch (DwgException) + { + break; + } + + if (target == 0) + { + continue; + } + + if (blockHeaderHandle is null && blockNamesByHandle.ContainsKey(target)) + { + blockHeaderHandle = target; + } + else if (viewportHandles.Contains(target)) + { + if (overallViewportHandle is null) + { + overallViewportHandle = target; + } + else + { + floatingViewports.Add(target); + } + } + } + } + + bool isModel = name.Equals("Model", StringComparison.OrdinalIgnoreCase) + || (blockHeaderHandle is ulong bh && blockNamesByHandle.TryGetValue(bh, out string? bName) + && bName.Equals("*Model_Space", StringComparison.OrdinalIgnoreCase)); + + return new DwgLayoutInfo + { + Handle = info.Handle, + Name = string.IsNullOrWhiteSpace(name) ? $"Layout_{info.Handle:X}" : name, + BlockHeaderHandle = blockHeaderHandle, + OverallViewportHandle = overallViewportHandle, + ViewportHandles = floatingViewports, + IsModelSpace = isModel, + }; + } +} diff --git a/src/DwgIO/Internal/Parsing/SplineEvaluator.cs b/src/DwgIO/Internal/Parsing/SplineEvaluator.cs new file mode 100644 index 0000000..ed6f9c3 --- /dev/null +++ b/src/DwgIO/Internal/Parsing/SplineEvaluator.cs @@ -0,0 +1,148 @@ +namespace DwgIO.Internal.Parsing; + +/// +/// Clean-room NURBS / B-spline evaluator producing polyline sample points along a SPLINE entity. +/// +internal static class SplineEvaluator +{ + public static List<(double X, double Y, double Z)> Evaluate( + int degree, + IReadOnlyList knots, + IReadOnlyList<(double X, double Y, double Z, double W)> controlPoints, + bool closed, + int samplesPerSpan = 8) + { + var result = new List<(double X, double Y, double Z)>(); + int n = controlPoints.Count; + if (n < 2) + { + return result; + } + + if (degree < 1 || knots.Count != n + degree + 1) + { + foreach (var p in controlPoints) + { + result.Add((p.X, p.Y, p.Z)); + } + + return result; + } + + double uMin = knots[degree]; + double uMax = knots[n]; + if (!double.IsFinite(uMin) || !double.IsFinite(uMax) || uMax <= uMin) + { + foreach (var p in controlPoints) + { + result.Add((p.X, p.Y, p.Z)); + } + + return result; + } + + int spans = 0; + for (int i = degree; i < n; i++) + { + if (knots[i + 1] > knots[i]) + { + spans++; + } + } + + int steps = Math.Clamp(Math.Max(spans, 1) * samplesPerSpan, 16, 1024); + for (int s = 0; s <= steps; s++) + { + double u = s == steps ? uMax : uMin + (uMax - uMin) * s / steps; + int span = FindSpan(n - 1, degree, u, knots); + var basis = BasisFunctions(span, u, degree, knots); + + double wx = 0, wy = 0, wz = 0, wSum = 0; + for (int j = 0; j <= degree; j++) + { + int idx = span - degree + j; + var cp = controlPoints[idx]; + double weight = basis[j] * (cp.W > 0 ? cp.W : 1.0); + wx += weight * cp.X; + wy += weight * cp.Y; + wz += weight * cp.Z; + wSum += weight; + } + + if (Math.Abs(wSum) > 1e-12) + { + result.Add((wx / wSum, wy / wSum, wz / wSum)); + } + } + + if (closed && result.Count >= 2) + { + var first = result[0]; + var last = result[^1]; + if (Math.Abs(first.X - last.X) > 1e-9 || Math.Abs(first.Y - last.Y) > 1e-9 || Math.Abs(first.Z - last.Z) > 1e-9) + { + result.Add(first); + } + } + + return result; + } + + private static int FindSpan(int lastControl, int degree, double u, IReadOnlyList knots) + { + if (u >= knots[lastControl + 1]) + { + return lastControl; + } + + if (u <= knots[degree]) + { + return degree; + } + + int low = degree; + int high = lastControl + 1; + int mid = (low + high) >> 1; + while (u < knots[mid] || u >= knots[mid + 1]) + { + if (u < knots[mid]) + { + high = mid; + } + else + { + low = mid; + } + + mid = (low + high) >> 1; + } + + return mid; + } + + private static double[] BasisFunctions(int span, double u, int degree, IReadOnlyList knots) + { + var n = new double[degree + 1]; + var left = new double[degree + 1]; + var right = new double[degree + 1]; + n[0] = 1.0; + + for (int j = 1; j <= degree; j++) + { + left[j] = u - knots[span + 1 - j]; + right[j] = knots[span + j] - u; + double saved = 0.0; + for (int r = 0; r < j; r++) + { + double denom = right[r + 1] + left[j - r]; + double temp = Math.Abs(denom) > 1e-18 ? n[r] / denom : 0.0; + n[r] = saved + right[r + 1] * temp; + saved = left[j - r] * temp; + } + + n[j] = saved; + } + + return n; + } +} diff --git a/src/DwgIO/Model/DwgBlockInfo.cs b/src/DwgIO/Model/DwgBlockInfo.cs new file mode 100644 index 0000000..a249b44 --- /dev/null +++ b/src/DwgIO/Model/DwgBlockInfo.cs @@ -0,0 +1,40 @@ +namespace DwgIO.Model; + +/// +/// A decoded BLOCK_RECORD (BLOCK_HEADER) entry: model space, paper space layouts, internal blocks and external references (XREFs). +/// +public sealed class DwgBlockInfo +{ + /// Handle of the BLOCK_RECORD object. + public required ulong Handle { get; init; } + + /// Block name (e.g. *Model_Space, *Paper_Space, or a block/XREF name). + public required string Name { get; init; } + + /// True when the block is anonymous (e.g. *U1, *D1). + public bool IsAnonymous { get; init; } + + /// True when the block contains attribute definitions. + public bool HasAttributes { get; init; } + + /// True when the block references an external drawing (XREF). + public bool IsXref { get; init; } + + /// True when the external reference is an overlay rather than an attachment. + public bool IsXrefOverlay { get; init; } + + /// True when an external reference is flagged as loaded in the host file. + public bool IsLoaded { get; init; } + + /// Optional external reference file path recorded on the block header. + public string? XrefPath { get; init; } + + /// Base point subtracted when inserting this block's entities (populated from BLOCK if non-zero). + public DwgPoint3D BasePoint { get; init; } + + /// Optional handle of the owning LAYOUT object when this block backs a space/layout. + public ulong? LayoutHandle { get; init; } + + /// Handles of entities directly owned by this block record, in drawing order. + public IReadOnlyList OwnedEntityHandles { get; init; } = []; +} diff --git a/src/DwgIO/Model/DwgEntity.cs b/src/DwgIO/Model/DwgEntity.cs index 04202ad..ee027d2 100644 --- a/src/DwgIO/Model/DwgEntity.cs +++ b/src/DwgIO/Model/DwgEntity.cs @@ -43,6 +43,18 @@ public enum DwgEntityKind /// MTEXT: multiline text annotation (position, height, rotation, reference width, attachment). MText, + + /// INSERT / MINSERT: block or XREF placement with transform and optional grid tiling. + Insert, + + /// POLYLINE_3D: 3D polyline with vertices and closed flag. + Polyline3d, + + /// SPLINE: evaluated B-spline / NURBS curve as sampled 3D vertices. + Spline, + + /// VIEWPORT: Paper Space viewport window into Model Space. + Viewport, } /// @@ -84,6 +96,15 @@ public sealed class DwgEntity /// Whether the entity belongs directly to model space. public bool IsModelSpace { get; init; } = true; + /// Explicit owner object handle (for entities inside named blocks or polylines, when entityMode == 0). + public ulong? OwnerHandle { get; init; } + + /// Referenced BLOCK_RECORD handle when the entity is an INSERT or MINSERT. + public ulong? BlockHeaderHandle { get; init; } + + /// Decoded Paper Space viewport portal data when the entity is a VIEWPORT. + public DwgViewportData? Viewport { get; init; } + /// DXF 62 colour index from the common preamble: the low 9 bits of the stored colour value, /// so 0 is BYBLOCK, 1 to 255 are indexed colours and 256 is BYLAYER. public int ColorIndex { get; init; } diff --git a/src/DwgIO/Model/DwgLayoutInfo.cs b/src/DwgIO/Model/DwgLayoutInfo.cs new file mode 100644 index 0000000..a3bf51b --- /dev/null +++ b/src/DwgIO/Model/DwgLayoutInfo.cs @@ -0,0 +1,25 @@ +namespace DwgIO.Model; + +/// +/// A decoded LAYOUT entry associating a sheet or Model Space name with its BLOCK_RECORD and viewports. +/// +public sealed class DwgLayoutInfo +{ + /// Handle of the LAYOUT object. + public required ulong Handle { get; init; } + + /// Layout display name (e.g. Model, Layout1). + public required string Name { get; init; } + + /// Handle of the associated BLOCK_RECORD (*Model_Space or *Paper_Space*). + public ulong? BlockHeaderHandle { get; init; } + + /// Handle of the layout's last active / overall viewport (typically Viewport #1 in Paper Space). + public ulong? OverallViewportHandle { get; init; } + + /// Handles of floating viewports attached to this layout. + public IReadOnlyList ViewportHandles { get; init; } = []; + + /// True when this layout represents Model Space (Model or *Model_Space). + public bool IsModelSpace { get; init; } +} diff --git a/src/DwgIO/Model/DwgViewportData.cs b/src/DwgIO/Model/DwgViewportData.cs new file mode 100644 index 0000000..c66a0e5 --- /dev/null +++ b/src/DwgIO/Model/DwgViewportData.cs @@ -0,0 +1,40 @@ +namespace DwgIO.Model; + +/// +/// Decoded geometry and view transform parameters of a Paper Space VIEWPORT entity (0x22). +/// +public sealed class DwgViewportData +{ + /// Viewport center on the paper sheet (X, Y, Z). + public DwgPoint3D Center { get; init; } + + /// Viewport window width on the paper sheet. + public double Width { get; init; } + + /// Viewport window height on the paper sheet. + public double Height { get; init; } + + /// 3D view target point in Model Space. + public DwgPoint3D ViewTarget { get; init; } + + /// 3D view direction vector from target toward camera. + public DwgPoint3D ViewDirection { get; init; } + + /// 2D view center in display coordinates. + public DwgPoint2D ViewCenter { get; init; } + + /// Height of the Model Space window mapped into the viewport. + public double ViewHeight { get; init; } + + /// View twist angle in radians. + public double TwistAngleRadians { get; init; } + + /// Lens length (used by perspective viewports). + public double LensLength { get; init; } + + /// Raw AutoCAD viewport status flags. + public uint StatusFlags { get; init; } + + /// True when the viewport is turned on and maps a positive Model Space height into paper coordinates. + public bool IsActive => Width > 0 && Height > 0 && ViewHeight > 0 && (StatusFlags & 0x20000) == 0; +} diff --git a/tests/DwgIO.Tests/BlocksAndSheetsTests.cs b/tests/DwgIO.Tests/BlocksAndSheetsTests.cs new file mode 100644 index 0000000..db0d05b --- /dev/null +++ b/tests/DwgIO.Tests/BlocksAndSheetsTests.cs @@ -0,0 +1,303 @@ +using System.Text; +using DwgIO.Export; +using DwgIO.Model; +using DwgIO.Scene; +using IOScene; +using Xunit; + +namespace DwgIO.Tests; + +public class BlocksAndSheetsTests +{ + private static readonly DwgFileHeader TestHeader = new() + { + Version = new DwgVersionInfo + { + Magic = "AC1032", + Release = "R2018", + Family = DwgContainerFamily.R2004Family, + Year = 2018, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }; + + [Fact] + public void Insert_ExpandsBlockGeometry_WithTransformBasePointAndByBlockColor() + { + const ulong modelHandle = 0x1F; + const ulong doorBlockHandle = 0x50; + + var blocks = new DwgBlockInfo[] + { + new() + { + Handle = modelHandle, + Name = "*Model_Space", + OwnedEntityHandles = [0x101], + }, + new() + { + Handle = doorBlockHandle, + Name = "DoorBlock", + BasePoint = new DwgPoint3D(1, 0, 0), + OwnedEntityHandles = [0x102], + }, + }; + + var entities = new DwgEntity[] + { + new() + { + Handle = 0x102, + TypeCode = 0x13, + TypeName = "LINE", + Kind = DwgEntityKind.Line, + IsModelSpace = false, + OwnerHandle = doorBlockHandle, + ColorIndex = 0, // BYBLOCK -> should inherit INSERT red (ACI 1) + Geometry = [1.0, 0.0, 0.0, 2.0, 0.0, 0.0], + }, + new() + { + Handle = 0x101, + TypeCode = 0x07, + TypeName = "INSERT", + Kind = DwgEntityKind.Insert, + IsModelSpace = true, + OwnerHandle = modelHandle, + BlockHeaderHandle = doorBlockHandle, + ColorIndex = 1, // ACI 1 = Red + Geometry = [10.0, 5.0, 0.0, 2.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0], + }, + }; + + var doc = new DwgDocument("blocks.dwg", TestHeader, entities, blocks: blocks); + var result = DwgSceneReader.Read(doc, new DwgSceneOptions { LengthUnit = "m", ModelKey = "blocks.dwg" }); + + Assert.Single(result.Document.Geometries); + var geom = result.Document.Geometries[0]; + Assert.Equal(SceneTopology.Lines, geom.Topology); + // BasePoint (1,0,0) subtracted -> [0..1] on X; scaled by sx=2 -> [0..2]; translated by (10,5,0) -> (10,5,0)..(12,5,0) + Assert.Equal(new Vector3d(10, 5, 0), geom.Vertices[0]); + Assert.Equal(new Vector3d(12, 5, 0), geom.Vertices[1]); + + var inst = Assert.Single(result.Document.Instances); + Assert.Equal(new RgbaColor(255, 0, 0), inst.Color); + } + + [Fact] + public void PaperSpaceLayoutAndViewport_ProjectAndClipModelSpaceGeometryIntoSheet() + { + const ulong modelHandle = 0x1F; + const ulong paperHandle = 0x20; + + var blocks = new DwgBlockInfo[] + { + new() + { + Handle = modelHandle, + Name = "*Model_Space", + LayoutHandle = 0x200, + OwnedEntityHandles = [0x101], + }, + new() + { + Handle = paperHandle, + Name = "*Paper_Space", + LayoutHandle = 0x201, + OwnedEntityHandles = [0x102, 0x103], + }, + }; + + var layouts = new DwgLayoutInfo[] + { + new() + { + Handle = 0x200, + Name = "Model", + BlockHeaderHandle = modelHandle, + IsModelSpace = true, + }, + new() + { + Handle = 0x201, + Name = "A102 - Plans", + BlockHeaderHandle = paperHandle, + OverallViewportHandle = 0x102, + ViewportHandles = [0x102, 0x103], + IsModelSpace = false, + }, + }; + + var entities = new DwgEntity[] + { + // Long model-space horizontal line from X=-20 to X=20 along Y=0 + new() + { + Handle = 0x101, + TypeCode = 0x13, + TypeName = "LINE", + Kind = DwgEntityKind.Line, + IsModelSpace = true, + OwnerHandle = modelHandle, + ColorIndex = 7, + Geometry = [-20.0, 0.0, 0.0, 20.0, 0.0, 0.0], + }, + // Paper space overall viewport (#1, skipped as portal) + new() + { + Handle = 0x102, + TypeCode = 0x22, + TypeName = "VIEWPORT", + Kind = DwgEntityKind.Viewport, + IsModelSpace = false, + OwnerHandle = paperHandle, + Viewport = new DwgViewportData + { + Center = new DwgPoint3D(10, 5, 0), + Width = 30, + Height = 20, + ViewHeight = 20, + StatusFlags = 0, + }, + }, + // Floating viewport centered on paper at (10, 5), paper box [8..12, 4..6], looking at model (0,0) with ViewHeight=2 -> 1:1 scale + new() + { + Handle = 0x103, + TypeCode = 0x22, + TypeName = "VIEWPORT", + Kind = DwgEntityKind.Viewport, + IsModelSpace = false, + OwnerHandle = paperHandle, + Viewport = new DwgViewportData + { + Center = new DwgPoint3D(10, 5, 0), + Width = 4, + Height = 2, + ViewTarget = new DwgPoint3D(0, 0, 0), + ViewDirection = new DwgPoint3D(0, 0, 1), + ViewCenter = new DwgPoint2D(0, 0), + ViewHeight = 2, + StatusFlags = 0, + }, + }, + }; + + var doc = new DwgDocument("sheets.dwg", TestHeader, entities, blocks: blocks, layouts: layouts); + var result = DwgSceneReader.Read(doc, new DwgSceneOptions + { + LengthUnit = "m", + ModelKey = "sheets.dwg", + IncludePaperSpace = true, + }); + + Assert.Equal(2, result.Sheets.Count); + Assert.False(result.Sheets[0].IsModelSpace); + Assert.Equal("A102 - Plans", result.Sheets[0].Name); + Assert.True(result.Sheets[1].IsModelSpace); + + // Projected line inside viewport must be clipped strictly inside paper box X=[8..12], Y=5 + var sheetIds = result.Sheets[0].ElementIds.ToHashSet(); + var sheetGeomIds = result.Document.Instances + .Where(i => sheetIds.Contains(i.ElementId)) + .Select(i => i.GeometryId) + .ToHashSet(); + var sheetVerts = result.Document.Geometries + .Where(g => sheetGeomIds.Contains(g.Id)) + .SelectMany(g => g.Vertices) + .ToArray(); + + Assert.True(sheetVerts.Length >= 2); + Assert.All(sheetVerts, v => + { + Assert.InRange(v.X, 7.999, 12.001); + Assert.InRange(v.Y, 3.999, 6.001); + }); + + using var defaultStream = new MemoryStream(); + Export.DwgViewerExport.ExportToStream(doc, defaultStream); + string defaultHtml = Encoding.UTF8.GetString(defaultStream.ToArray()); + Assert.Contains("\"initialSheet\":\"model\"", defaultHtml, StringComparison.Ordinal); + Assert.DoesNotContain("\"initial2DMode\":true", defaultHtml, StringComparison.Ordinal); + + using var autoStream = new MemoryStream(); + Export.DwgViewerExport.ExportToStream(doc, autoStream, new DwgViewerOptions { Mode = DwgViewerMode.Auto }); + string autoHtml = Encoding.UTF8.GetString(autoStream.ToArray()); + Assert.Contains("\"initialSheet\":\"sheet:201\"", autoHtml, StringComparison.Ordinal); + Assert.Contains("\"initial2DMode\":true", autoHtml, StringComparison.Ordinal); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ExternalReferenceRequiresOptIn(bool resolveXrefs) + { + var doc = new DwgDocument("drawing.dwg", TestHeader, + [ + new DwgEntity + { + Handle = 0x101, + TypeCode = 0x07, + TypeName = "INSERT", + Kind = DwgEntityKind.Insert, + IsModelSpace = true, + OwnerHandle = 0x1F, + BlockHeaderHandle = 0x50, + Geometry = [0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0], + }, + ], blocks: + [ + new DwgBlockInfo { Handle = 0x1F, Name = "*Model_Space", OwnedEntityHandles = [0x101] }, + new DwgBlockInfo { Handle = 0x50, Name = "Reference", IsXref = true, XrefPath = "reference.dwg" }, + ]); + + var options = new DwgSceneOptions { ModelKey = "drawing.dwg" }; + if (resolveXrefs) options.ResolveXrefs = true; + var result = DwgSceneReader.Read(doc, options); + + Assert.Equal(resolveXrefs, result.Diagnostics.Any(d => d.Code == "missing-xref")); + } + + [Fact] + public void Polyline3dAndSpline_ConvertToLines_AndAutoModeDetects2dVs3d() + { + var flatDoc = new DwgDocument("flat.dwg", TestHeader, + [ + new DwgEntity + { + Handle = 0x301, + TypeCode = 0x11, + TypeName = "SPLINE", + Kind = DwgEntityKind.Spline, + ColorIndex = 3, + Geometry = [0.0, 0.0, 0.0, 0.0, 5.0, 2.0, 0.0, 10.0, 0.0, 0.0], + }, + ]); + + var terrainDoc = new DwgDocument("terrain.dwg", TestHeader, + [ + new DwgEntity + { + Handle = 0x302, + TypeCode = 0x10, + TypeName = "POLYLINE_3D", + Kind = DwgEntityKind.Polyline3d, + ColorIndex = 5, + Geometry = [0.0, 0.0, 0.0, 0.0, 5.0, 0.0, 12.0, 10.0, 5.0, 2.0], + }, + ]); + + using var flatStream = new MemoryStream(); + Export.DwgViewerExport.ExportToStream(flatDoc, flatStream, new DwgViewerOptions { Mode = DwgViewerMode.Auto }, "m"); + string flatHtml = Encoding.UTF8.GetString(flatStream.ToArray()); + Assert.Contains("\"initial2DMode\":true", flatHtml, StringComparison.Ordinal); + + using var terrainStream = new MemoryStream(); + Export.DwgViewerExport.ExportToStream(terrainDoc, terrainStream, new DwgViewerOptions { Mode = DwgViewerMode.Auto }, "m"); + string terrainHtml = Encoding.UTF8.GetString(terrainStream.ToArray()); + Assert.DoesNotContain("\"initial2DMode\":true", terrainHtml, StringComparison.Ordinal); + } +} diff --git a/tests/DwgIO.Tests/ClassesAndEntitiesTests.cs b/tests/DwgIO.Tests/ClassesAndEntitiesTests.cs index a9dcb51..c77af80 100644 --- a/tests/DwgIO.Tests/ClassesAndEntitiesTests.cs +++ b/tests/DwgIO.Tests/ClassesAndEntitiesTests.cs @@ -232,15 +232,14 @@ public void SceneSvgAndViewer_RenderPolylineEllipseSolidAndTrueColor() Assert.Contains("stroke=\"#112233\"", svg, StringComparison.Ordinal); Assert.Contains("A ", svg, StringComparison.Ordinal); // bulge arc in SVG path - // 2D AutoCAD HTML viewer + // Unified IOViewer HTML keeps entity geometries and colors natively. string htmlPath = Path.Combine(_directory, "entities.html"); Export.DwgViewerExport.SaveViewer(doc, htmlPath, viewerOptions: new DwgViewerOptions { Mode = DwgViewerMode.Cad2D }); string html = File.ReadAllText(htmlPath); - Assert.Contains("\"trueColorRgb\":\"#112233\"", html, StringComparison.Ordinal); - Assert.Contains("\"kind\":\"polyline\"", html, StringComparison.Ordinal); - Assert.Contains("\"kind\":\"ellipse\"", html, StringComparison.Ordinal); - Assert.Contains("\"ellipseMinorY\":0", html, StringComparison.Ordinal); - Assert.Contains("\"kind\":\"solid\"", html, StringComparison.Ordinal); + Assert.Contains("id=\"ioviewer-meta\"", html, StringComparison.Ordinal); + Assert.Contains("\"lines\":{\"count\":2", html, StringComparison.Ordinal); + Assert.Contains("\"instances\":{\"count\":1", html, StringComparison.Ordinal); + Assert.Contains("\"initial2DMode\":true", html, StringComparison.Ordinal); } private static byte[] BuildStream(ushort typeCode, Action writeBody, ushort colorValue = 2) diff --git a/tests/DwgIO.Tests/CoreStandardTests.cs b/tests/DwgIO.Tests/CoreStandardTests.cs index b068f5e..7d776e4 100644 --- a/tests/DwgIO.Tests/CoreStandardTests.cs +++ b/tests/DwgIO.Tests/CoreStandardTests.cs @@ -169,8 +169,9 @@ public void Cli_HtmlDefaultsTo3dAndAccepts2d() using var e1 = new StringWriter(); 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); + Assert.Contains("id=\"ioviewer-meta\"", cadContent, StringComparison.Ordinal); + Assert.Contains("\"initial2DMode\":true", cadContent, StringComparison.Ordinal); + Assert.Contains("\"initialBackground\":\"#212830\"", cadContent, StringComparison.Ordinal); using var o2 = new StringWriter(); using var e2 = new StringWriter(); diff --git a/tests/DwgIO.Tests/DwgViewerExportTests.cs b/tests/DwgIO.Tests/DwgViewerExportTests.cs index fa0a17a..c5cda94 100644 --- a/tests/DwgIO.Tests/DwgViewerExportTests.cs +++ b/tests/DwgIO.Tests/DwgViewerExportTests.cs @@ -73,7 +73,14 @@ private static DwgDocument SampleDrawing() => CreateDocument( }); [Fact] - public void SaveViewer_Cad2DMode_WritesAutoCad2DHtml() + public void ViewerMode_KeepsExistingNumericValues() + { + Assert.Equal(0, (int)DwgViewerMode.Cad2D); + Assert.Equal(1, (int)DwgViewerMode.Scene3D); + } + + [Fact] + public void SaveViewer_Cad2DMode_WritesUnifiedIOViewer2DHtml() { string htmlPath = Path.Combine(_directory, "drawing.html"); @@ -82,24 +89,23 @@ public void SaveViewer_Cad2DMode_WritesAutoCad2DHtml() 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.Contains("id=\"ioviewer-canvas\"", 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()); + Assert.Contains("id=\"ioviewer-meta\"", html, StringComparison.Ordinal); + + int metaStart = html.IndexOf('>', html.IndexOf("id=\"ioviewer-meta\"", StringComparison.Ordinal)) + 1; + int metaEnd = html.IndexOf("", metaStart, StringComparison.Ordinal); + using var payload = JsonDocument.Parse(html[metaStart..metaEnd]); + Assert.True(payload.RootElement.GetProperty("options").GetProperty("initial2DMode").GetBoolean()); + Assert.Equal("#14171c", payload.RootElement.GetProperty("options").GetProperty("initialBackground").GetString()); + Assert.Equal(2, payload.RootElement.GetProperty("lines").GetProperty("count").GetInt32()); + Assert.Equal(1, payload.RootElement.GetProperty("points").GetProperty("count").GetInt32()); + Assert.Equal(3, payload.RootElement.GetProperty("elements").GetArrayLength()); } [Fact] - public void SaveViewer_Cad2D_ThemeOptionSetsHtmlAttributeAndPayload() + public void SaveViewer_Cad2D_ThemeOptionSetsBackgroundInIOViewer() { string htmlPath = Path.Combine(_directory, "slate.html"); @@ -111,7 +117,7 @@ public void SaveViewer_Cad2D_ThemeOptionSetsHtmlAttributeAndPayload() }); string html = File.ReadAllText(htmlPath); - Assert.Contains("data-theme=\"slate\"", html, StringComparison.Ordinal); + Assert.Contains("\"initialBackground\":\"#212830\"", html, StringComparison.Ordinal); Assert.Contains("Floor Plan", html, StringComparison.Ordinal); } diff --git a/tests/DwgIO.Tests/HeaderVariablesTests.cs b/tests/DwgIO.Tests/HeaderVariablesTests.cs index f1f1883..29ea91b 100644 --- a/tests/DwgIO.Tests/HeaderVariablesTests.cs +++ b/tests/DwgIO.Tests/HeaderVariablesTests.cs @@ -78,10 +78,10 @@ public void JsonAndCli_IncludeHeaderVariablesAndPdMode() Assert.Contains("Header: insunits=Unitless", stdout.ToString(), StringComparison.Ordinal); using var ms = new MemoryStream(); - DwgCadHtmlViewer.Export(doc, ms, new DwgViewerOptions(), "m"); + DwgIO.Export.DwgViewerExport.ExportToStream(doc, ms, new DwgViewerOptions { Mode = DwgViewerMode.Cad2D }, "m"); string html = Encoding.UTF8.GetString(ms.ToArray()); - Assert.Contains("\"pdmode\":0", html, StringComparison.Ordinal); - Assert.Contains("\"insunits\":\"Unitless\"", html, StringComparison.Ordinal); + Assert.Contains("id=\"ioviewer-meta\"", html, StringComparison.Ordinal); + Assert.Contains("\"initial2DMode\":true", html, StringComparison.Ordinal); } [Theory] @@ -275,9 +275,9 @@ private static byte[] BuildSyntheticR2004Header( w.WriteRawByte((byte)(handseed & 0xFF)); WritePoint3D(w, new DwgPoint3D(0, 0, 0)); + w.WriteTwoBits(2); WritePoint3D(w, extMin); WritePoint3D(w, extMax); - w.WriteTwoBits(2); w.WriteRawDouble(limMin.X); w.WriteRawDouble(limMin.Y); w.WriteRawDouble(limMax.X); diff --git a/tests/DwgIO.Tests/LayersTests.cs b/tests/DwgIO.Tests/LayersTests.cs index c7008be..1be2087 100644 --- a/tests/DwgIO.Tests/LayersTests.cs +++ b/tests/DwgIO.Tests/LayersTests.cs @@ -211,14 +211,13 @@ public void Consumers_ResolveByLayerColorsAndLayersInJsonSceneSvgCliAndHtmlViewe Assert.Contains("Walls (aci=1, on)", inspectText, StringComparison.Ordinal); Assert.Contains("Defpoints (aci=8, frozen)", inspectText, StringComparison.Ordinal); - // 2D HTML viewer exports layers, layer filter state, and resolved #ff0000 color. + // Unified IOViewer HTML exports layer name as category and resolved #ff0000 material color. using var htmlStream = new MemoryStream(); - DwgCadHtmlViewer.Export(doc, htmlStream, new DwgViewerOptions(), "m"); + DwgIO.Export.DwgViewerExport.ExportToStream(doc, htmlStream, new DwgViewerOptions { Mode = DwgViewerMode.Cad2D }, "m"); string html = Encoding.UTF8.GetString(htmlStream.ToArray()); - Assert.Contains("\"name\":\"Walls\"", html, StringComparison.Ordinal); - Assert.Contains("\"name\":\"Defpoints\",\"colorIndex\":8,\"isAdaptiveColor\":false,\"rgb\":\"#808080\",\"isOn\":true,\"isFrozen\":true,\"isLocked\":false,\"visible\":false", html, StringComparison.Ordinal); - Assert.Contains("\"layer\":\"Walls\"", html, StringComparison.Ordinal); - Assert.Contains("\"rgb\":\"#FF0000\"", html, StringComparison.Ordinal); + Assert.Contains("id=\"ioviewer-meta\"", html, StringComparison.Ordinal); + Assert.Contains("\"category\":\"Walls\"", html, StringComparison.Ordinal); + Assert.Contains("\"color\":[1,0,0]", html, StringComparison.Ordinal); } private static byte[] BuildSyntheticR2018LayerStream(ulong handle, string name, ushort flags, uint colorMethod) diff --git a/tests/DwgIO.Tests/TextEntitiesTests.cs b/tests/DwgIO.Tests/TextEntitiesTests.cs index f170ef4..af35bb1 100644 --- a/tests/DwgIO.Tests/TextEntitiesTests.cs +++ b/tests/DwgIO.Tests/TextEntitiesTests.cs @@ -98,9 +98,10 @@ public void PublicDrawing_RightAlignedTextPreservesItsAnchorInSvgAndHtml() Assert.Equal("end", (string?)label.Attribute("text-anchor")); using var html = new MemoryStream(); - DwgCadHtmlViewer.Export(document, html, new DwgViewerOptions(), "m"); + DwgIO.Export.DwgViewerExport.ExportToStream(document, html, new DwgViewerOptions { Mode = DwgViewerMode.Cad2D }, "m"); string content = Encoding.UTF8.GetString(html.ToArray()); - Assert.Contains("\"text\":\"Right aligned\",\"textColumn\":2", content, StringComparison.Ordinal); + Assert.Contains("id=\"ioviewer-meta\"", content, StringComparison.Ordinal); + Assert.Contains("\"text\":\"Right aligned\"", content, StringComparison.Ordinal); } [Fact] @@ -173,9 +174,10 @@ public void DecodeMText_R2018_StripsFormattingAndExportsJsonSvgAndHtml() Assert.Contains("Area 42 m1/2", svg, StringComparison.Ordinal); using var htmlStream = new MemoryStream(); - DwgCadHtmlViewer.Export(doc, htmlStream, new DwgViewerOptions(), "m"); + DwgIO.Export.DwgViewerExport.ExportToStream(doc, htmlStream, new DwgViewerOptions { Mode = DwgViewerMode.Cad2D }, "m"); string html = Encoding.UTF8.GetString(htmlStream.ToArray()); - Assert.Contains("\"kind\":\"mtext\"", html, StringComparison.Ordinal); + Assert.Contains("id=\"ioviewer-meta\"", html, StringComparison.Ordinal); + Assert.Contains("\"annotations\":[", html, StringComparison.Ordinal); Assert.Contains("Room 101\\nArea 42 m1/2", html, StringComparison.Ordinal); }