From f6b85ef75e720544f4630d839aeccfafb809cbca Mon Sep 17 00:00:00 2001 From: mahach666 Date: Tue, 1 Dec 2026 13:22:21 +0300 Subject: [PATCH 1/2] Parse AcDb:Classes and decode LWPOLYLINE, ELLIPSE, SOLID, 3DFACE, RAY, XLINE and TrueColor --- CHANGELOG.md | 2 + docs/public-api.md | 5 +- src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs | 204 ++++++++++- src/DwgIO.Cli/Export/DwgSvgExporter.cs | 196 ++++++++++- src/DwgIO.Cli/Program.cs | 10 + src/DwgIO.Scene/DwgSceneReader.cs | 185 ++++++++-- src/DwgIO/DwgDocument.cs | 61 +++- src/DwgIO/DwgReaderOptions.cs | 3 + src/DwgIO/Internal/Container/BitReaderMsb.cs | 12 + src/DwgIO/Internal/Container/ObjectStream.cs | 18 +- src/DwgIO/Internal/Parsing/ClassesParser.cs | 240 +++++++++++++ src/DwgIO/Internal/Parsing/EntityDecoder.cs | 196 +++++++++-- .../Internal/Parsing/MetadataByteCursor.cs | 2 +- src/DwgIO/Json/DwgJsonExporter.cs | 28 +- src/DwgIO/Model/DwgClassInfo.cs | 49 +++ src/DwgIO/Model/DwgEntity.cs | 62 +++- src/DwgIO/Model/DwgObjectInfo.cs | 9 +- tests/DwgIO.Tests/ClassesAndEntitiesTests.cs | 320 ++++++++++++++++++ tests/DwgIO.Tests/CoreStandardTests.cs | 2 +- 19 files changed, 1507 insertions(+), 97 deletions(-) create mode 100644 src/DwgIO/Internal/Parsing/ClassesParser.cs create mode 100644 src/DwgIO/Model/DwgClassInfo.cs create mode 100644 tests/DwgIO.Tests/ClassesAndEntitiesTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index f5413b9..f1c6f9d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ API between minor releases. ## [Unreleased] ### Added +- `AcDb:Classes` parsing (`DwgClassInfo`, `DwgDocument.Classes`, `DwgReaderOptions.ReadClasses`) resolving class names (codes 500+) and `IsEntity` flags in `DwgObjectInfo`, JSON export and `dwgio inspect`. +- Entity geometry decoding for `LWPOLYLINE` (including bulges and elevation), `ELLIPSE`, `SOLID`/`TRACE`, `3DFACE`, `RAY`, `XLINE` and 24-bit `TrueColorRgb` across `DwgIO`, `DwgIO.Scene`, SVG and the 2D AutoCAD HTML viewer. - `DwgReaderOptions`: `Strict`, `MaxFileBytes`, `MaxSectionBytes`, `MaxDecompressedBytes`, `MaxObjectCount`, `ReleaseSectionBuffers`, `Progress` (`IProgress`), and `DiagnosticOutput` (`TextWriter?`). - `DwgDocument`: `SourcePath`, `OpenAsync` (path and stream overloads), `ReleaseSectionBuffers()`, `SaveJson` and `ToJson`. diff --git a/docs/public-api.md b/docs/public-api.md index 8173561..b9642c2 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -35,8 +35,9 @@ change in any release and is visible only to the test project through `Internals | `DwgFileDepList`, `DwgFileDependency` | External files the drawing refers to (fonts, images, references). | | `DwgPreview`, `DwgPreviewImageKind` | The embedded thumbnail and its format (BMP, PNG or WMF). `DwgDocument.PreviewReadError` provides the reason when the thumbnail section could not be read. | | `DwgHandleMap`, `DwgHandleMapEntry` | The handle to offset index of the object stream; `Find(handle)` looks up one object. | -| `DwgObjectInfo`, `DwgHandle` | One record of the object stream: offset, size, type code (`TypeName` names it) and handle. | -| `DwgEntity`, `DwgEntityKind` | A decoded entity with its handle, type, colour, linetype scale, `IsModelSpace` flag and the `Geometry` decoded for LINE, CIRCLE, ARC and POINT. | +| `DwgObjectInfo`, `DwgHandle` | One record of the object stream: offset, size, type code (`TypeName` resolves fixed names and `AcDb:Classes` names) and handle. | +| `DwgClassInfo` | One class definition from `AcDb:Classes` (codes 500+): `ClassNumber`, `AppName`, `CppClassName`, `DxfName`, `ItemClassId`, `IsEntity`, `InstanceCount`. | +| `DwgEntity`, `DwgEntityKind` | A decoded entity with its handle, type, colour (`ColorIndex` and optional `TrueColorRgb`), linetype scale, `IsModelSpace` flag and decoded `Geometry` for LINE, CIRCLE, ARC, POINT, LWPOLYLINE, ELLIPSE, SOLID/TRACE, 3DFACE, RAY and XLINE. | | `DwgDocument.AppInfoHistory` | Decompressed bytes of `AcDb:AppInfoHistory` when available. The record layout is unknown. | | `DwgRevHistory` | The save references of `AcDb:RevHistory`: layout version pair and one value per recorded save. | | `DwgAuxHeader` | The auxiliary header of `AcDb:AuxHeader`: version pair, save counter, creation and last-update times, next handle. | diff --git a/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs b/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs index df80a99..763f4e6 100644 --- a/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs +++ b/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs @@ -100,8 +100,14 @@ private static string BuildPayloadJson(DwgDocument document, DwgViewerOptions op w.WriteString("type", entity.TypeName); w.WriteString("kind", entity.Kind.ToString().ToLowerInvariant()); w.WriteNumber("colorIndex", entity.ColorIndex); - w.WriteBoolean("isAdaptiveColor", IsAdaptiveColor(entity.ColorIndex)); - w.WriteString("rgb", FormatFixedRgb(entity.ColorIndex)); + bool adaptive = entity.TrueColorRgb is null && IsAdaptiveColor(entity.ColorIndex); + w.WriteBoolean("isAdaptiveColor", adaptive); + w.WriteString("rgb", FormatFixedRgb(entity.ColorIndex, entity.TrueColorRgb)); + if (entity.TrueColorRgb 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); w.WriteStartArray("geom"); @@ -145,8 +151,13 @@ private static string BuildPayloadJson(DwgDocument document, DwgViewerOptions op private static bool IsAdaptiveColor(int colorIndex) => colorIndex is <= 0 or 7 or >= 256; - private static string? FormatFixedRgb(int colorIndex) + private static string? FormatFixedRgb(int colorIndex, uint? trueColorRgb) { + if (trueColorRgb is { } rgb) + { + return string.Create(CultureInfo.InvariantCulture, $"#{rgb:X6}"); + } + if (IsAdaptiveColor(colorIndex)) { return null; @@ -185,6 +196,35 @@ private static bool TryExpandBounds(DwgEntity entity, ref double minX, ref doubl 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, [var cx, var cy, _, var mx, var my, _, var ratio, var startRaw, var endRaw]) when ratio > 0: + double nx = -my * ratio, ny = mx * ratio; + var (eStart, eSpan) = ArcAngles.Normalize(startRaw, endRaw); + for (int i = 0; i <= 32; i++) + { + double a = eStart + eSpan * i / 32; + Expand(cx + mx * Math.Cos(a) + nx * Math.Sin(a), cy + my * Math.Cos(a) + ny * 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; default: return false; } @@ -735,6 +775,29 @@ function entityBounds(e) { const r = Math.max(g[3], 1); return { minX: g[0] - r, minY: g[1] - r, maxX: g[0] + r, maxY: g[1] + r }; } + if (e.kind === 'polyline') { + let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; + const n = Math.floor((g.length - 2) / 3); + for (let i = 0; i < n; i++) { + minX = Math.min(minX, g[2 + i * 3]); + minY = Math.min(minY, g[2 + i * 3 + 1]); + maxX = Math.max(maxX, g[2 + i * 3]); + maxY = Math.max(maxY, g[2 + i * 3 + 1]); + } + return { minX, minY, maxX, maxY }; + } + if (e.kind === 'ellipse') { + const r = Math.max(Math.hypot(g[3], g[4]), 1); + return { minX: g[0] - r, minY: g[1] - r, maxX: g[0] + r, maxY: g[1] + r }; + } + if (e.kind === 'solid' || e.kind === 'face3d') { + return { + minX: Math.min(g[0], g[3], g[6], g[9]), + minY: Math.min(g[1], g[4], g[7], g[10]), + maxX: Math.max(g[0], g[3], g[6], g[9]), + maxY: Math.max(g[1], g[4], g[7], g[10]), + }; + } return { minX: g[0] - 1, minY: g[1] - 1, maxX: g[0] + 1, maxY: g[1] + 1 }; } @@ -910,6 +973,84 @@ function drawEntity(entity, w, h, overrideColor, lineWidth) { } else if (entity.kind === 'point') { const [px, py] = worldToScreen(g[0], g[1], w, h); drawPoint(px, py, color, !!overrideColor); + } else if (entity.kind === 'polyline') { + const count = Math.floor((g.length - 2) / 3); + if (count < 2) return; + const closed = g[0] !== 0; + const segs = closed ? count : count - 1; + ctx.beginPath(); + const [sx0, sy0] = worldToScreen(g[2], g[3], w, h); + ctx.moveTo(sx0, sy0); + for (let i = 0; i < segs; i++) { + const next = (i + 1) % count; + const x1 = g[2 + i * 3], y1 = g[2 + i * 3 + 1], bulge = g[2 + i * 3 + 2]; + const x2 = g[2 + next * 3], y2 = g[2 + next * 3 + 1]; + if (Math.abs(bulge) < 1e-12) { + const [sx, sy] = worldToScreen(x2, y2, w, h); + ctx.lineTo(sx, sy); + } else { + const dx = x2 - x1, dy = y2 - y1; + const chord = Math.hypot(dx, dy); + if (chord <= 1e-12) continue; + const radius = chord * (1 + bulge * bulge) / (4 * Math.abs(bulge)); + const hOff = chord * (1 - bulge * bulge) / (4 * bulge); + const cx = (x1 + x2) * 0.5 - hOff * (dy / chord); + const cy = (y1 + y2) * 0.5 + hOff * (dx / chord); + const [scx, scy] = worldToScreen(cx, cy, w, h); + const a1 = Math.atan2(y1 - cy, x1 - cx); + const a2 = Math.atan2(y2 - cy, x2 - cx); + ctx.arc(scx, scy, radius * cam.scale, -a1, -a2, bulge > 0); + } + } + ctx.stroke(); + } else if (entity.kind === 'ellipse') { + const cx = g[0], cy = g[1], mx = g[3], my = g[4], ratio = g[6]; + if (!Number.isFinite(ratio) || ratio <= 0) return; + const nx = -my * ratio, ny = mx * ratio; + const [start, span] = arcSpan(g[7], g[8]); + const steps = Math.max(16, Math.min(256, Math.ceil(span / (5 * Math.PI / 180)))); + ctx.beginPath(); + for (let i = 0; i <= steps; i++) { + const a = start + (span * i) / steps; + const [sx, sy] = worldToScreen(cx + mx * Math.cos(a) + nx * Math.sin(a), cy + my * Math.cos(a) + ny * Math.sin(a), w, h); + if (i === 0) ctx.moveTo(sx, sy); + else ctx.lineTo(sx, sy); + } + ctx.stroke(); + } else if (entity.kind === 'solid' || entity.kind === 'face3d') { + const order = entity.kind === 'solid' ? [0, 3, 9, 6] : [0, 3, 6, 9]; + ctx.beginPath(); + for (let i = 0; i < 4; i++) { + const idx = order[i]; + const [sx, sy] = worldToScreen(g[idx], g[idx + 1], w, h); + if (i === 0) ctx.moveTo(sx, sy); + else ctx.lineTo(sx, sy); + } + ctx.closePath(); + if (entity.kind === 'solid') { + ctx.save(); + ctx.globalAlpha = 0.25; + ctx.fillStyle = color; + ctx.fill(); + ctx.restore(); + } + ctx.stroke(); + } else if (entity.kind === 'ray' || entity.kind === 'xline') { + const len = Math.max(w, h) / cam.scale + Math.hypot(cam.x - g[0], cam.y - g[1]) + 100; + const dirLen = Math.hypot(g[3], g[4]); + if (dirLen <= 1e-12) return; + const ux = g[3] / dirLen, uy = g[4] / dirLen; + const [sx1, sy1] = entity.kind === 'ray' + ? worldToScreen(g[0], g[1], w, h) + : worldToScreen(g[0] - ux * len, g[1] - uy * len, w, h); + const [sx2, sy2] = worldToScreen(g[0] + ux * len, g[1] + uy * len, w, h); + ctx.save(); + ctx.setLineDash([6, 4]); + ctx.beginPath(); + ctx.moveTo(sx1, sy1); + ctx.lineTo(sx2, sy2); + ctx.stroke(); + ctx.restore(); } } @@ -990,6 +1131,45 @@ function hitTest(wx, wy) { } } else if (e.kind === 'point') { d = Math.hypot(wx - g[0], wy - g[1]); + } else if (e.kind === 'polyline') { + const count = Math.floor((g.length - 2) / 3); + const closed = g[0] !== 0; + const segs = closed ? count : count - 1; + for (let k = 0; k < segs; k++) { + const next = (k + 1) % count; + d = Math.min(d, distanceToSegment(wx, wy, g[2 + k * 3], g[2 + k * 3 + 1], g[2 + next * 3], g[2 + next * 3 + 1])); + } + } else if (e.kind === 'ellipse') { + const cx = g[0], cy = g[1], mx = g[3], my = g[4], ratio = g[6]; + const nx = -my * ratio, ny = mx * ratio; + const [start, span] = arcSpan(g[7], g[8]); + let prevX = cx + mx * Math.cos(start) + nx * Math.sin(start); + let prevY = cy + my * Math.cos(start) + ny * Math.sin(start); + for (let s = 1; s <= 32; s++) { + const a = start + (span * s) / 32; + const curX = cx + mx * Math.cos(a) + nx * Math.sin(a); + const curY = cy + my * Math.cos(a) + ny * Math.sin(a); + d = Math.min(d, distanceToSegment(wx, wy, prevX, prevY, curX, curY)); + prevX = curX; + prevY = curY; + } + } else if (e.kind === 'solid' || e.kind === 'face3d') { + const order = e.kind === 'solid' ? [0, 3, 9, 6] : [0, 3, 6, 9]; + for (let k = 0; k < 4; k++) { + const a = order[k], b = order[(k + 1) % 4]; + d = Math.min(d, distanceToSegment(wx, wy, g[a], g[a + 1], g[b], g[b + 1])); + } + } else if (e.kind === 'ray' || e.kind === 'xline') { + const dirLen = Math.hypot(g[3], g[4]); + if (dirLen > 1e-12) { + const ux = g[3] / dirLen, uy = g[4] / dirLen; + const proj = (wx - g[0]) * ux + (wy - g[1]) * uy; + if (e.kind === 'xline' || proj >= 0) { + d = Math.hypot(wx - (g[0] + proj * ux), wy - (g[1] + proj * uy)); + } else { + d = Math.hypot(wx - g[0], wy - g[1]); + } + } } if (d <= bestDist) { bestDist = d; @@ -1004,6 +1184,7 @@ function fmt(n) { } function colorLabel(e) { + if (e.trueColorRgb) return `RGB ${e.trueColorRgb}`; if (e.colorIndex === 256) return `256 (${t('bylayer')})`; if (e.colorIndex === 0) return `0 (${t('byblock')})`; if (e.colorIndex === 7) return `7 (${t('white')})`; @@ -1040,6 +1221,23 @@ function renderProps(e) { rows.push([t('angles'), `${fmt(d1)}° .. ${fmt(d2)}°`]); } else if (e.kind === 'point') { rows.push([t('position'), `(${fmt(g[0])}, ${fmt(g[1])}, ${fmt(g[2])})`]); + } else if (e.kind === 'polyline') { + const count = Math.floor((g.length - 2) / 3); + rows.push(['Vertices', String(count)]); + rows.push(['Closed', g[0] !== 0 ? 'Yes' : 'No']); + rows.push(['Elevation', fmt(g[1])]); + } else if (e.kind === 'ellipse') { + rows.push([t('center'), `(${fmt(g[0])}, ${fmt(g[1])}, ${fmt(g[2])})`]); + rows.push(['Major Axis', `(${fmt(g[3])}, ${fmt(g[4])}, ${fmt(g[5])})`]); + rows.push(['Ratio', fmt(g[6])]); + } else if (e.kind === 'solid' || e.kind === 'face3d') { + rows.push(['P1', `(${fmt(g[0])}, ${fmt(g[1])}, ${fmt(g[2])})`]); + rows.push(['P2', `(${fmt(g[3])}, ${fmt(g[4])}, ${fmt(g[5])})`]); + rows.push(['P3', `(${fmt(g[6])}, ${fmt(g[7])}, ${fmt(g[8])})`]); + rows.push(['P4', `(${fmt(g[9])}, ${fmt(g[10])}, ${fmt(g[11])})`]); + } else if (e.kind === 'ray' || e.kind === 'xline') { + rows.push([t('position'), `(${fmt(g[0])}, ${fmt(g[1])}, ${fmt(g[2])})`]); + rows.push(['Direction', `(${fmt(g[3])}, ${fmt(g[4])}, ${fmt(g[5])})`]); } propsGrid.innerHTML = ''; diff --git a/src/DwgIO.Cli/Export/DwgSvgExporter.cs b/src/DwgIO.Cli/Export/DwgSvgExporter.cs index 45c67a7..c93b453 100644 --- a/src/DwgIO.Cli/Export/DwgSvgExporter.cs +++ b/src/DwgIO.Cli/Export/DwgSvgExporter.cs @@ -79,7 +79,7 @@ public static void Write(DwgDocument document, XmlWriter writer, DwgSvgOptions? foreach (var shape in shapes) { - string stroke = ColourOf(shape.ColorIndex); + string stroke = ColourOf(shape.ColorIndex, shape.TrueColorRgb); switch (shape) { case SvgLine line: @@ -109,6 +109,17 @@ public static void Write(DwgDocument document, XmlWriter writer, DwgSvgOptions? writer.WriteAttributeString("stroke", stroke); writer.WriteEndElement(); break; + case SvgPath path: + writer.WriteStartElement("path"); + writer.WriteAttributeString("d", path.Data); + if (path.Fill) + { + writer.WriteAttributeString("fill", stroke); + } + + writer.WriteAttributeString("stroke", stroke); + writer.WriteEndElement(); + break; case SvgPoint point: writer.WriteStartElement("circle"); writer.WriteAttributeString("cx", Num(point.X)); @@ -126,16 +137,22 @@ public static void Write(DwgDocument document, XmlWriter writer, DwgSvgOptions? writer.WriteEndDocument(); } - private abstract record SvgShape(int ColorIndex); + private abstract record SvgShape(int ColorIndex, uint? TrueColorRgb); - private sealed record SvgLine(double X1, double Y1, double X2, double Y2, int ColorIndex) : SvgShape(ColorIndex); + private sealed record SvgLine(double X1, double Y1, double X2, double Y2, int ColorIndex, uint? TrueColorRgb) + : SvgShape(ColorIndex, TrueColorRgb); - private sealed record SvgCircle(double Cx, double Cy, double Radius, int ColorIndex) : SvgShape(ColorIndex); + private sealed record SvgCircle(double Cx, double Cy, double Radius, int ColorIndex, uint? TrueColorRgb) + : SvgShape(ColorIndex, TrueColorRgb); - private sealed record SvgArc(double Cx, double Cy, double Radius, double Start, double Span, int ColorIndex) - : SvgShape(ColorIndex); + private sealed record SvgArc(double Cx, double Cy, double Radius, double Start, double Span, int ColorIndex, uint? TrueColorRgb) + : SvgShape(ColorIndex, TrueColorRgb); - private sealed record SvgPoint(double X, double Y, int ColorIndex) : SvgShape(ColorIndex); + private sealed record SvgPoint(double X, double Y, int ColorIndex, uint? TrueColorRgb) + : SvgShape(ColorIndex, TrueColorRgb); + + private sealed record SvgPath(string Data, IReadOnlyList<(double X, double Y)> BoundsPoints, bool Fill, int ColorIndex, uint? TrueColorRgb) + : SvgShape(ColorIndex, TrueColorRgb); private static List Collect(DwgDocument document, DwgSvgOptions options) { @@ -153,7 +170,7 @@ private static List Collect(DwgDocument document, DwgSvgOptions option case (DwgEntityKind.Line, [var x1, var y1, _, var x2, var y2, _]): if (IsUsable(x1 * scale, y1 * scale, x2 * scale, y2 * scale)) { - shapes.Add(new SvgLine(x1 * scale, -y1 * scale, x2 * scale, -y2 * scale, entity.ColorIndex)); + shapes.Add(new SvgLine(x1 * scale, -y1 * scale, x2 * scale, -y2 * scale, entity.ColorIndex, entity.TrueColorRgb)); } else { @@ -164,7 +181,7 @@ private static List Collect(DwgDocument document, DwgSvgOptions option case (DwgEntityKind.Circle, [var cx, var cy, _, var r]): if (IsUsable((Math.Abs(cx) + r) * scale, (Math.Abs(cy) + r) * scale) && r > 0) { - shapes.Add(new SvgCircle(cx * scale, -cy * scale, r * scale, entity.ColorIndex)); + shapes.Add(new SvgCircle(cx * scale, -cy * scale, r * scale, entity.ColorIndex, entity.TrueColorRgb)); } else { @@ -177,8 +194,8 @@ private static List Collect(DwgDocument document, DwgSvgOptions option { var (arcStart, span) = ArcAngles.Normalize(start, end); shapes.Add(span == Math.Tau - ? new SvgCircle(cx * scale, -cy * scale, r * scale, entity.ColorIndex) - : new SvgArc(cx * scale, -cy * scale, r * scale, arcStart, span, entity.ColorIndex)); + ? new SvgCircle(cx * scale, -cy * scale, r * scale, entity.ColorIndex, entity.TrueColorRgb) + : new SvgArc(cx * scale, -cy * scale, r * scale, arcStart, span, entity.ColorIndex, entity.TrueColorRgb)); } else { @@ -189,7 +206,40 @@ private static List Collect(DwgDocument document, DwgSvgOptions option case (DwgEntityKind.Point, [var x, var y, _]): if (IsUsable(x * scale, y * scale)) { - shapes.Add(new SvgPoint(x * scale, -y * scale, entity.ColorIndex)); + shapes.Add(new SvgPoint(x * scale, -y * scale, entity.ColorIndex, entity.TrueColorRgb)); + } + else + { + Skip(options.ReportDiagnostic, entity, "non-finite coordinates"); + } + + break; + case (DwgEntityKind.Polyline, { Length: >= 5 } g): + if (TryBuildPolyline(g, scale, entity, out var poly)) + { + shapes.Add(poly); + } + else + { + Skip(options.ReportDiagnostic, entity, "non-finite or insufficient vertices"); + } + + break; + case (DwgEntityKind.Ellipse, [var cx, var cy, _, var mx, var my, _, var ratio, var start, var end]): + if (TryBuildEllipse(cx, cy, mx, my, ratio, start, end, scale, entity, out var ellipse)) + { + shapes.Add(ellipse); + } + else + { + Skip(options.ReportDiagnostic, entity, "non-finite or invalid ellipse"); + } + + break; + case (DwgEntityKind.Solid or DwgEntityKind.Face3d, { Length: 12 } g): + if (TryBuildQuad(g, scale, entity, out var quad)) + { + shapes.Add(quad); } else { @@ -203,6 +253,114 @@ private static List Collect(DwgDocument document, DwgSvgOptions option return shapes; } + private static bool TryBuildPolyline(double[] g, double scale, DwgEntity entity, out SvgPath path) + { + int count = (g.Length - 2) / 3; + if (count < 2 || !IsUsable(g)) + { + path = null!; + return false; + } + + bool closed = g[0] != 0.0; + var sb = new System.Text.StringBuilder(); + var bounds = new List<(double X, double Y)>(count); + double x0 = g[2] * scale; + double y0 = -g[3] * scale; + sb.Append(FormattableString.Invariant($"M {Num(x0)} {Num(y0)}")); + bounds.Add((x0, y0)); + + int segments = closed ? count : count - 1; + 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; + bounds.Add((x2, y2)); + + if (Math.Abs(bulge) < 1e-12) + { + sb.Append(FormattableString.Invariant($" L {Num(x2)} {Num(y2)}")); + } + else + { + double chord = double.Hypot(x2 - x1, y2 - y1); + double r = chord * (1.0 + bulge * bulge) / (4.0 * Math.Abs(bulge)); + int largeArc = Math.Abs(bulge) > 1.0 ? 1 : 0; + // In SVG y-down space, positive world bulge (CCW) sweeps with flag 0, negative with flag 1. + int sweep = bulge > 0 ? 0 : 1; + sb.Append(FormattableString.Invariant($" A {Num(r)} {Num(r)} 0 {largeArc} {sweep} {Num(x2)} {Num(y2)}")); + } + } + + if (closed) + { + sb.Append(" Z"); + } + + path = new SvgPath(sb.ToString(), bounds, Fill: false, entity.ColorIndex, entity.TrueColorRgb); + return true; + } + + private static bool TryBuildEllipse( + double cx, double cy, double mx, double my, double ratio, double startRaw, double endRaw, + double scale, DwgEntity entity, out SvgPath path) + { + if (!IsUsable(cx, cy, mx, my, ratio, startRaw, endRaw) || ratio <= 0) + { + path = null!; + return false; + } + + double scx = cx * scale, scy = -cy * scale; + double smx = mx * scale, smy = -my * scale; + double snx = -my * ratio * scale, sny = -(mx * ratio * scale); + var (start, span) = ArcAngles.Normalize(startRaw, endRaw); + bool closed = span >= Math.Tau - 1e-9; + int steps = Math.Clamp((int)Math.Ceiling(span / (5.0 * Math.PI / 180.0)), 16, 256); + var sb = new System.Text.StringBuilder(); + var bounds = new List<(double X, double Y)>(steps + 1); + for (int i = 0; i <= steps; i++) + { + double angle = start + span * i / steps; + double px = scx + smx * Math.Cos(angle) + snx * Math.Sin(angle); + double py = scy + smy * Math.Cos(angle) + sny * Math.Sin(angle); + bounds.Add((px, py)); + sb.Append(i == 0 + ? FormattableString.Invariant($"M {Num(px)} {Num(py)}") + : FormattableString.Invariant($" L {Num(px)} {Num(py)}")); + } + + if (closed) + { + sb.Append(" Z"); + } + + path = new SvgPath(sb.ToString(), bounds, Fill: false, entity.ColorIndex, entity.TrueColorRgb); + return true; + } + + private static bool TryBuildQuad(double[] g, double scale, DwgEntity entity, out SvgPath path) + { + if (!IsUsable(g)) + { + path = null!; + return false; + } + + bool bowtie = entity.Kind == DwgEntityKind.Solid; + (double x0, double y0) = (g[0] * scale, -g[1] * scale); + (double x1, double y1) = (g[3] * scale, -g[4] * scale); + (double x2, double y2) = bowtie ? (g[9] * scale, -g[10] * scale) : (g[6] * scale, -g[7] * scale); + (double x3, double y3) = bowtie ? (g[6] * scale, -g[7] * scale) : (g[9] * scale, -g[10] * scale); + string data = FormattableString.Invariant($"M {Num(x0)} {Num(y0)} L {Num(x1)} {Num(y1)} L {Num(x2)} {Num(y2)} L {Num(x3)} {Num(y3)} Z"); + path = new SvgPath(data, [(x0, y0), (x1, y1), (x2, y2), (x3, y3)], Fill: entity.Kind == DwgEntityKind.Solid, entity.ColorIndex, entity.TrueColorRgb); + return true; + } + private static void Skip(Action? reportDiagnostic, DwgEntity entity, string reason) => reportDiagnostic?.Invoke($"svg: entity {entity.Handle:X} ({entity.TypeName}) skipped: {reason}"); @@ -245,6 +403,13 @@ private static (double MinX, double MinY, double Width, double Height) ViewBox(L } } + break; + case SvgPath path: + foreach ((double px, double py) in path.BoundsPoints) + { + Expand(px, py); + } + break; case SvgPoint point: Expand(point.X, point.Y); @@ -268,8 +433,13 @@ void Expand(double x, double y) } } - private static string ColourOf(int colorIndex) + private static string ColourOf(int colorIndex, uint? trueColorRgb) { + if (trueColorRgb is { } rgb) + { + return FormattableString.Invariant($"#{rgb:X6}"); + } + int resolved = colorIndex is > 0 and < 256 ? colorIndex : 7; if (resolved == 7) { diff --git a/src/DwgIO.Cli/Program.cs b/src/DwgIO.Cli/Program.cs index 8e16b47..f583276 100644 --- a/src/DwgIO.Cli/Program.cs +++ b/src/DwgIO.Cli/Program.cs @@ -194,6 +194,11 @@ internal static int InspectDocument(DwgDocument doc, TextWriter output) } } + if (doc.Classes.Count > 0) + { + output.WriteLine($"Classes: {Count(doc.Classes.Count)}"); + } + if (doc.Objects.Count > 0) { output.WriteLine($"Objects: {Count(doc.Objects.Count)} (handle map: {Count(doc.HandleMap?.Count ?? 0)})"); @@ -720,6 +725,11 @@ private static void WriteEntitiesJson(TextWriter output, IEnumerable } writer.WriteNumber("colorIndex", entity.ColorIndex); + if (entity.TrueColorRgb is { } trueColor) + { + writer.WriteString("trueColorRgb", $"#{trueColor:X6}"); + } + writer.WriteEndObject(); } diff --git a/src/DwgIO.Scene/DwgSceneReader.cs b/src/DwgIO.Scene/DwgSceneReader.cs index 781725a..929c8ab 100644 --- a/src/DwgIO.Scene/DwgSceneReader.cs +++ b/src/DwgIO.Scene/DwgSceneReader.cs @@ -144,15 +144,27 @@ private static DwgSceneResult Convert(DwgDocument document, string key, string? continue; } - Vector3d[]? vertices = entity.Kind switch + (SceneTopology topology, Vector3d[] vertices, IReadOnlyList indices)? built = entity.Kind switch { - DwgEntityKind.Line when entity.Geometry is { Length: 6 } g => LineVertices(g, metresPerUnit), - DwgEntityKind.Circle when entity.Geometry is { Length: 4 } g => CircleVertices(g, metresPerUnit), - DwgEntityKind.Arc when entity.Geometry is { Length: 6 } g => ArcVertices(g, metresPerUnit), - DwgEntityKind.Point when entity.Geometry is { Length: 3 } g => PointVertices(g, metresPerUnit), + DwgEntityKind.Line when entity.Geometry is { Length: 6 } g => + (SceneTopology.Lines, LineVertices(g, metresPerUnit), Array.Empty()), + DwgEntityKind.Circle when entity.Geometry is { Length: 4 } g => + BuildCircle(g, metresPerUnit), + DwgEntityKind.Arc when entity.Geometry is { Length: 6 } g => + BuildArc(g, metresPerUnit), + 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), + DwgEntityKind.Ellipse when entity.Geometry is { Length: 9 } g => + BuildEllipse(g, metresPerUnit), + DwgEntityKind.Solid when entity.Geometry is { Length: 12 } g => + BuildQuad(g, metresPerUnit, bowtieOrder: true), + DwgEntityKind.Face3d when entity.Geometry is { Length: 12 } g => + BuildQuad(g, metresPerUnit, bowtieOrder: false), _ => null, }; - if (vertices is null) + if (built is null) { if (entity.Kind == DwgEntityKind.Unknown || entity.Geometry is null) { @@ -162,7 +174,7 @@ private static DwgSceneResult Convert(DwgDocument document, string key, string? continue; } - if (!vertices.All(IsFinite)) + 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. @@ -172,27 +184,19 @@ private static DwgSceneResult Convert(DwgDocument document, string key, string? elementsWithGeometry++; geometryId++; - bool isPoint = entity.Kind == DwgEntityKind.Point; - // The contract wants whole pairs for non-indexed lines; polylines share their joints through indices. - IReadOnlyList indices = entity.Kind switch - { - DwgEntityKind.Circle => SharedIndices(CircleSegments, closed: true), - DwgEntityKind.Arc => SharedIndices(vertices!.Length, closed: false), - _ => [], - }; var geometry = new SceneGeometry { Id = geometryId, - Topology = isPoint ? SceneTopology.Points : SceneTopology.Lines, - Vertices = vertices!, - Indices = indices, + Topology = built.Value.topology, + Vertices = built.Value.vertices, + Indices = built.Value.indices, }; scene.Geometries.Add(geometry); scene.Instances.Add(new SceneInstance { ElementId = element.Id, GeometryId = geometry.Id, - Color = ColourOf(entity.ColorIndex), + Color = ColourOf(entity), }); } @@ -235,19 +239,156 @@ private static DwgSceneResult Convert(DwgDocument document, string key, string? _ => throw new ArgumentException($"DwgSceneOptions.LengthUnit '{unit}' is not supported; use mm, cm, m, ft or in.", nameof(unit)), }; - private static RgbaColor? ColourOf(int colorIndex) + private static RgbaColor? ColourOf(DwgEntity entity) { - if (colorIndex is <= 0 or >= 256) + if (entity.TrueColorRgb is { } rgb) + { + return new RgbaColor((byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb); + } + + if (entity.ColorIndex is <= 0 or >= 256) { // BYBLOCK (0) and BYLAYER (256) have no colour of their own; the scene leaves the choice to the // consumer until layers and blocks are decoded. return null; } - (byte r, byte g, byte b) = DwgAciPalette.RgbOf(colorIndex); + (byte r, byte g, byte b) = DwgAciPalette.RgbOf(entity.ColorIndex); return new RgbaColor(r, g, b); } + private static (SceneTopology, Vector3d[], IReadOnlyList) BuildCircle(double[] g, double scale) + { + var vertices = CircleVertices(g, scale); + return (SceneTopology.Lines, vertices, SharedIndices(CircleSegments, closed: true)); + } + + private static (SceneTopology, Vector3d[], IReadOnlyList) BuildArc(double[] g, double scale) + { + var vertices = ArcVertices(g, scale); + return (SceneTopology.Lines, vertices, SharedIndices(vertices.Length, closed: false)); + } + + private static (SceneTopology, Vector3d[], IReadOnlyList)? BuildPolyline(double[] g, double scale) + { + int count = (g.Length - 2) / 3; + if (count < 2) + { + return null; + } + + bool closed = g[0] != 0.0; + double z = g[1] * scale; + var vertices = new List(count); + var indices = new List(count * 2); + + int segments = closed ? count : count - 1; + 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; + + if (Math.Abs(bulge) < 1e-12) + { + int a = vertices.Count; + vertices.Add(new Vector3d(x1, y1, z)); + vertices.Add(new Vector3d(x2, y2, z)); + indices.Add(a); + indices.Add(a + 1); + } + else + { + AppendBulgeSegments(vertices, indices, x1, y1, x2, y2, z, bulge); + } + } + + return vertices.Count >= 2 ? (SceneTopology.Lines, vertices.ToArray(), indices) : null; + } + + private static void AppendBulgeSegments( + List vertices, + List indices, + double x1, + double y1, + double x2, + double y2, + double z, + double bulge) + { + double dx = x2 - x1; + double dy = y2 - y1; + double chord = double.Hypot(dx, dy); + if (chord <= 1e-15) + { + return; + } + + double theta = 4.0 * Math.Atan(bulge); + double radius = chord * (1.0 + bulge * bulge) / (4.0 * Math.Abs(bulge)); + double h = chord * (1.0 - bulge * bulge) / (4.0 * bulge); + double cx = (x1 + x2) * 0.5 - h * (dy / chord); + double cy = (y1 + y2) * 0.5 + h * (dx / chord); + double start = Math.Atan2(y1 - cy, x1 - cx); + + 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)); + 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(new Vector3d(x2, y2, z)); + for (int s = 0; s < steps; s++) + { + indices.Add(first + s); + indices.Add(first + s + 1); + } + } + + private static (SceneTopology, Vector3d[], IReadOnlyList)? BuildEllipse(double[] g, 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; + double ratio = g[6]; + if (!double.IsFinite(ratio) || ratio <= 0) + { + return null; + } + + double nx = -my * ratio, ny = mx * ratio, nz = mz * ratio; + 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); + var vertices = new Vector3d[closed ? steps : steps + 1]; + 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); + } + + return (SceneTopology.Lines, vertices, SharedIndices(vertices.Length, closed)); + } + + private static (SceneTopology, Vector3d[], IReadOnlyList) BuildQuad(double[] g, 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). + 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), diff --git a/src/DwgIO/DwgDocument.cs b/src/DwgIO/DwgDocument.cs index 10a0f7b..3335249 100644 --- a/src/DwgIO/DwgDocument.cs +++ b/src/DwgIO/DwgDocument.cs @@ -57,16 +57,23 @@ private DwgDocument( Template = TryReadMetadata("AcDb:Template", b => TemplateParser.Parse(b, fileHeader.Codepage)); } + if (options.ReadClasses) + { + options.Progress?.Report(new DwgReadProgress("classes")); + Classes = ReadOptionalClasses(); + } + if (options.ReadObjects) { + var classesByCode = BuildClassLookup(Classes); options.Progress?.Report(new DwgReadProgress("handles")); HandleMap = ReadOptionalHandleMap(options.MaxObjectCount); options.Progress?.Report(new DwgReadProgress("objects")); - Objects = ReadOptionalObjects(options.MaxObjectCount); + Objects = ReadOptionalObjects(options.MaxObjectCount, classesByCode); if (options.ReadEntities) { options.Progress?.Report(new DwgReadProgress("entities", 0, Objects.Count)); - Entities = ReadOptionalEntities(); + Entities = ReadOptionalEntities(classesByCode); options.Progress?.Report(new DwgReadProgress("entities", Entities.Count, Objects.Count)); } else @@ -140,6 +147,9 @@ private DwgDocument( /// Reason the thumbnail section could not be read, when reading it failed. public string? PreviewReadError { get; private set; } + /// Custom and class-indexed object definitions from AcDb:Classes (codes 500+). + public IReadOnlyList Classes { get; } = []; + /// Handle→offset index from AcDb:Handles (R2004-family files, ReadObjects on). public DwgHandleMap? HandleMap { get; } @@ -513,6 +523,40 @@ internal bool TryGetReadableSection(string name, [System.Diagnostics.CodeAnalysi return true; } + private IReadOnlyList ReadOptionalClasses() + { + if (!TryGetReadableSection("AcDb:Classes", out var entry)) + { + return []; + } + + try + { + return ClassesParser.Parse(ReadSectionCore(entry), FileHeader.Version.Year, FileHeader.Codepage); + } + catch (Exception ex) when (IsParseFailure(ex)) + { + AddDiagnostic($"AcDb:Classes: {ex.Message}"); + return []; + } + } + + private static Dictionary? BuildClassLookup(IReadOnlyList classes) + { + if (classes.Count == 0) + { + return null; + } + + var map = new Dictionary(classes.Count); + foreach (var cls in classes) + { + map.TryAdd(cls.ClassNumber, cls); + } + + return map; + } + private DwgHandleMap? ReadOptionalHandleMap(int maxObjectCount) { if (!TryGetReadableSection("AcDb:Handles", out var entry)) @@ -531,7 +575,7 @@ internal bool TryGetReadableSection(string name, [System.Diagnostics.CodeAnalysi } } - private IReadOnlyList ReadOptionalObjects(int maxObjectCount) + private IReadOnlyList ReadOptionalObjects(int maxObjectCount, Dictionary? classesByCode) { if (!TryGetReadableSection("AcDb:AcDbObjects", out var entry)) { @@ -551,7 +595,8 @@ private IReadOnlyList ReadOptionalObjects(int maxObjectCount) r2010Plus: FileHeader.Version.Year >= 2010, mapOffsets, AddDiagnostic, - maxObjectCount); + maxObjectCount, + classesByCode); if (HandleMap is { Count: > 0 } map) { int missing = CountUnreachedObjects(objects, map); @@ -576,7 +621,7 @@ internal static int CountUnreachedObjects(IReadOnlyList objects, return map.Entries.Count(e => !reached.Contains((e.Handle, e.Offset))); } - private List ReadOptionalEntities() + private List ReadOptionalEntities(Dictionary? classesByCode) { if (_objectStreamBytes is null) { @@ -587,14 +632,16 @@ private List ReadOptionalEntities() var entities = new List(); foreach (var info in Objects) { - if (!EntityDecoder.IsEntityCode(info.TypeCode)) + bool isEntity = EntityDecoder.IsEntityCode(info.TypeCode) + || (classesByCode is not null && classesByCode.TryGetValue(info.TypeCode, out var cls) && cls.IsEntity); + if (!isEntity) { continue; } try { - if (EntityDecoder.Decode(info, _objectStreamBytes, year) is { } entity) + if (EntityDecoder.Decode(info, _objectStreamBytes, year, isEntity) is { } entity) { entities.Add(entity); } diff --git a/src/DwgIO/DwgReaderOptions.cs b/src/DwgIO/DwgReaderOptions.cs index e053da6..98050ac 100644 --- a/src/DwgIO/DwgReaderOptions.cs +++ b/src/DwgIO/DwgReaderOptions.cs @@ -31,6 +31,9 @@ public sealed class DwgReaderOptions /// Parse metadata sections: AppInfo, FileDepList, Preview, RevHistory, AuxHeader, Template (default: true). public bool ReadMetadata { get; set; } = true; + /// Parse the AcDb:Classes section to resolve class names and entity flags (default: true). + public bool ReadClasses { get; set; } = true; + /// /// Decompress AcDb:Handles + AcDb:AcDbObjects and build the /// handle→offset index and object inventory (default: true). diff --git a/src/DwgIO/Internal/Container/BitReaderMsb.cs b/src/DwgIO/Internal/Container/BitReaderMsb.cs index d489e4c..0e9f534 100644 --- a/src/DwgIO/Internal/Container/BitReaderMsb.cs +++ b/src/DwgIO/Internal/Container/BitReaderMsb.cs @@ -16,6 +16,18 @@ internal sealed class BitReaderMsb(byte[] bytes) /// Bits left between the cursor and the end of the buffer. public int RemainingBits => (bytes.Length - _bytePos) * 8 - _bitPos; + /// Moves the bit cursor to an absolute bit offset within the buffer. + public void SeekBit(int bitOffset) + { + if (bitOffset < 0 || bitOffset > bytes.Length * 8L) + { + throw new DwgException($"Bit offset {bitOffset} is outside the {bytes.Length * 8L}-bit buffer."); + } + + _bytePos = bitOffset / 8; + _bitPos = bitOffset % 8; + } + /// Reads raw bits, MSB-first. public ulong ReadBits(int n) diff --git a/src/DwgIO/Internal/Container/ObjectStream.cs b/src/DwgIO/Internal/Container/ObjectStream.cs index 23aca10..2c85f56 100644 --- a/src/DwgIO/Internal/Container/ObjectStream.cs +++ b/src/DwgIO/Internal/Container/ObjectStream.cs @@ -25,12 +25,14 @@ internal static class ObjectStreamWalker /// Handle-map offsets into the stream, ascending, or null when the map is absent. /// Receives one message per early stop or gap that was skipped. /// Maximum number of object records to collect before stopping with a diagnostic. + /// Optional class table keyed by class number (500+) to resolve class names. public static IReadOnlyList Walk( byte[] data, bool r2010Plus, IReadOnlyList? mapOffsets = null, Action? diagnostic = null, - int maxRecords = DefaultMaxRecords) + int maxRecords = DefaultMaxRecords, + IReadOnlyDictionary? classesByCode = null) { var objects = new List(); int pos = StartOffset(data); @@ -41,7 +43,8 @@ public static IReadOnlyList Walk( Report(diagnostic, $"object stream: stopped after reaching MaxObjectCount ({maxRecords})"); break; } - var (end, failure, nextPos) = TryReadRecord(data, pos, r2010Plus, objects); + + var (end, failure, nextPos) = TryReadRecord(data, pos, r2010Plus, objects, classesByCode); if (!end && failure is null) { pos = nextPos; @@ -77,7 +80,12 @@ public static IReadOnlyList Walk( /// Returns End true for a clean stream end (zero-length record) and Failure naming a broken /// record that a gap resync may recover from. /// - private static (bool End, string? Failure, int NextPos) TryReadRecord(byte[] data, int pos, bool r2010Plus, List objects) + private static (bool End, string? Failure, int NextPos) TryReadRecord( + byte[] data, + int pos, + bool r2010Plus, + List objects, + IReadOnlyDictionary? classesByCode) { int nextPos = pos; var (sizeBytes, prefixLength) = ReadSizePrefix(data, pos); @@ -118,11 +126,15 @@ private static (bool End, string? Failure, int NextPos) TryReadRecord(byte[] dat ushort typeCode = reader.ReadObjectType(r2010Plus); var handle = reader.ReadHandle(); + string? className = typeCode >= 500 && classesByCode is not null && classesByCode.TryGetValue(typeCode, out var cls) + ? cls.DisplayName + : null; objects.Add(new DwgObjectInfo { StreamOffset = pos, SizeBytes = sizeBytes, TypeCode = typeCode, + ClassName = className, Handle = handle.Value, StreamHandle = handle, BitsStart = bitsStart, diff --git a/src/DwgIO/Internal/Parsing/ClassesParser.cs b/src/DwgIO/Internal/Parsing/ClassesParser.cs new file mode 100644 index 0000000..8342bcf --- /dev/null +++ b/src/DwgIO/Internal/Parsing/ClassesParser.cs @@ -0,0 +1,240 @@ +using System.Buffers.Binary; +using System.Text; +using DwgIO.Internal.Container; +using DwgIO.Model; + +namespace DwgIO.Internal.Parsing; + +/// +/// Parses the AcDb:Classes section into entries. +/// +internal static class ClassesParser +{ + private const ushort FirstClassNumber = 500; + private const int MaxClassCount = 65535; + + private static ReadOnlySpan StartSentinel => + [0x8D, 0xA1, 0xC4, 0xB8, 0xC4, 0xA9, 0xF8, 0xC5, 0xC0, 0xDC, 0xF4, 0x5F, 0xE7, 0xCF, 0xB6, 0x8A]; + + public static IReadOnlyList Parse(byte[] bytes, int year, ushort codepage) + { + if (bytes.Length < 20) + { + throw new DwgException($"AcDb:Classes is too short ({bytes.Length} bytes)."); + } + + if (!bytes.AsSpan(0, 16).SequenceEqual(StartSentinel)) + { + throw new DwgException("AcDb:Classes is missing the expected start sentinel."); + } + + uint dataSize = BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(16, 4)); + int payloadOffset = year >= 2010 && bytes.Length >= 24 ? 24 : 20; + if (dataSize == 0) + { + return []; + } + + if (payloadOffset + (long)dataSize > bytes.Length) + { + throw new DwgException($"AcDb:Classes declares {dataSize} bytes at offset {payloadOffset}, exceeding section length {bytes.Length}."); + } + + byte[] data = bytes[payloadOffset..(payloadOffset + (int)dataSize)]; + return year >= 2007 + ? ParseWithSeparateStrings(data) + : ParseInlineStrings(data, codepage); + } + + private static List ParseWithSeparateStrings(byte[] data) + { + if (data.Length < 8) + { + throw new DwgException("AcDb:Classes payload is too short for R2007+ framing."); + } + + uint totalSizeInBits = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(0, 4)); + long maxBits = (long)data.Length * 8; + if (totalSizeInBits < 33 || totalSizeInBits > maxBits) + { + throw new DwgException($"AcDb:Classes bit size {totalSizeInBits} is outside the {maxBits}-bit payload."); + } + + var tailReader = new BitReaderMsb(data); + tailReader.SeekBit((int)totalSizeInBits - 1); + bool hasStrings = tailReader.ReadBit(); + + BitReaderMsb? stringReader = null; + if (hasStrings) + { + if (totalSizeInBits < 32 + 17) + { + throw new DwgException("AcDb:Classes string stream header is truncated."); + } + + var lenReader = new BitReaderMsb(data); + lenReader.SeekBit((int)totalSizeInBits - 17); + int stringBits = lenReader.ReadRawByte() | (lenReader.ReadRawByte() << 8); + int stringStart = (int)totalSizeInBits - 17 - stringBits; + if (stringStart < 32) + { + throw new DwgException($"AcDb:Classes string stream start {stringStart} overlaps the header."); + } + + stringReader = new BitReaderMsb(data); + stringReader.SeekBit(stringStart); + } + + var reader = new BitReaderMsb(data); + reader.SeekBit(32); + uint maxClassNumber = reader.ReadPackedShort(); + if (maxClassNumber < FirstClassNumber) + { + return []; + } + + int count = (int)(maxClassNumber - FirstClassNumber + 1); + if (count > MaxClassCount) + { + throw new DwgException($"AcDb:Classes declares {count} classes, exceeding the safety cap."); + } + + // R2004+ class header trailing fields: 2 bytes + 1 bit. + reader.ReadRawByte(); + reader.ReadRawByte(); + reader.ReadBit(); + + var classes = new List(count); + for (int i = 0; i < count; i++) + { + ushort classNumber = (ushort)reader.ReadPackedShort(); + ushort proxyFlags = (ushort)reader.ReadPackedShort(); + bool wasZombie = reader.ReadBit(); + ushort itemClassId = (ushort)reader.ReadPackedShort(); + uint instanceCount = reader.ReadPackedInt(); + uint dwgVersion = reader.ReadPackedInt(); + uint maintVersion = reader.ReadPackedInt(); + _ = reader.ReadPackedInt(); + _ = reader.ReadPackedInt(); + + string appName = stringReader is not null ? ReadUtf16String(stringReader) : string.Empty; + string cppName = stringReader is not null ? ReadUtf16String(stringReader) : string.Empty; + string dxfName = stringReader is not null ? ReadUtf16String(stringReader) : string.Empty; + + classes.Add(new DwgClassInfo + { + ClassNumber = classNumber, + ProxyFlags = proxyFlags, + AppName = appName, + CppClassName = cppName, + DxfName = dxfName, + WasZombie = wasZombie, + ItemClassId = itemClassId, + InstanceCount = instanceCount, + DwgVersion = dwgVersion, + MaintVersion = maintVersion, + }); + } + + return classes; + } + + private static List ParseInlineStrings(byte[] data, ushort codepage) + { + var reader = new BitReaderMsb(data); + uint maxClassNumber = reader.ReadPackedShort(); + if (maxClassNumber < FirstClassNumber) + { + return []; + } + + int count = (int)(maxClassNumber - FirstClassNumber + 1); + if (count > MaxClassCount) + { + throw new DwgException($"AcDb:Classes declares {count} classes, exceeding the safety cap."); + } + + reader.ReadRawByte(); + reader.ReadRawByte(); + reader.ReadBit(); + + Encoding encoding = MetadataByteCursor.GetEncoding(codepage); + var classes = new List(count); + for (int i = 0; i < count; i++) + { + ushort classNumber = (ushort)reader.ReadPackedShort(); + ushort proxyFlags = (ushort)reader.ReadPackedShort(); + string appName = ReadCodepageString(reader, encoding); + string cppName = ReadCodepageString(reader, encoding); + string dxfName = ReadCodepageString(reader, encoding); + bool wasZombie = reader.ReadBit(); + ushort itemClassId = (ushort)reader.ReadPackedShort(); + uint instanceCount = reader.ReadPackedInt(); + uint dwgVersion = reader.ReadPackedInt(); + uint maintVersion = reader.ReadPackedInt(); + _ = reader.ReadPackedInt(); + _ = reader.ReadPackedInt(); + + classes.Add(new DwgClassInfo + { + ClassNumber = classNumber, + ProxyFlags = proxyFlags, + AppName = appName, + CppClassName = cppName, + DxfName = dxfName, + WasZombie = wasZombie, + ItemClassId = itemClassId, + InstanceCount = instanceCount, + DwgVersion = dwgVersion, + MaintVersion = maintVersion, + }); + } + + return classes; + } + + private static string ReadUtf16String(BitReaderMsb reader) + { + int charCount = (int)reader.ReadPackedShort(); + if (charCount == 0) + { + return string.Empty; + } + + int byteCount = charCount * 2; + if (byteCount * 8L > reader.RemainingBits) + { + throw new DwgException($"AcDb:Classes UTF-16 string of {charCount} chars exceeds remaining bits."); + } + + var bytes = new byte[byteCount]; + for (int i = 0; i < byteCount; i++) + { + bytes[i] = reader.ReadRawByte(); + } + + return Encoding.Unicode.GetString(bytes).TrimEnd('\0'); + } + + private static string ReadCodepageString(BitReaderMsb reader, Encoding encoding) + { + int byteCount = (int)reader.ReadPackedShort(); + if (byteCount == 0) + { + return string.Empty; + } + + if (byteCount * 8L > reader.RemainingBits) + { + throw new DwgException($"AcDb:Classes string of {byteCount} bytes exceeds remaining bits."); + } + + var bytes = new byte[byteCount]; + for (int i = 0; i < byteCount; i++) + { + bytes[i] = reader.ReadRawByte(); + } + + return encoding.GetString(bytes).TrimEnd('\0'); + } +} diff --git a/src/DwgIO/Internal/Parsing/EntityDecoder.cs b/src/DwgIO/Internal/Parsing/EntityDecoder.cs index 95a7376..6d36869 100644 --- a/src/DwgIO/Internal/Parsing/EntityDecoder.cs +++ b/src/DwgIO/Internal/Parsing/EntityDecoder.cs @@ -5,37 +5,31 @@ namespace DwgIO.Internal.Parsing; /// /// Decodes entity records: the common entity preamble followed by the -/// type-specific body. This milestone decodes geometry for LINE, CIRCLE, ARC and POINT; +/// type-specific body for LINE, CIRCLE, ARC, POINT, LWPOLYLINE, ELLIPSE, SOLID, TRACE, 3DFACE, RAY and XLINE; /// other entity codes are reported by name only. /// internal static class EntityDecoder { - /// - /// Name for a fixed type code, via . - /// + private const int MaxPolylineVertices = 1_000_000; + + /// Name for a fixed type code, via . public static string TypeName(ushort typeCode) => DwgObjectTypes.Name(typeCode); - /// - /// Tells whether a record of this code is a drawable entity; see . - /// + /// Tells whether a record of this code is a drawable entity; see . public static bool IsEntityCode(ushort typeCode) => DwgObjectTypes.IsEntity(typeCode); /// /// Decodes an entity from the record payload (starting right after the size prefix). - /// Returns null when the type has no geometry decoder yet or the record is not an entity. + /// Returns null when the record is not an entity. /// - public static DwgEntity? Decode(DwgObjectInfo info, byte[] stream, int year) + public static DwgEntity? Decode(DwgObjectInfo info, byte[] stream, int year, bool forceEntity = false) { - if (!IsEntityCode(info.TypeCode)) + if (!forceEntity && !IsEntityCode(info.TypeCode)) { return null; } var reader = new BitReaderMsb(stream[info.BitsStart..(info.BitsStart + info.BitsLength)]); - // -- Record header re-read --------------------------------------------- - // The payload layout is [handle-stream size in bits (R2010+)][type][handle][common data…]; - // the inventory walk already consumed these fields for its own fields, so the body - // decoder re-reads them to position itself at the common entity data. if (year >= 2010) { reader.ReadVarUInt(); @@ -44,11 +38,9 @@ internal static class EntityDecoder reader.ReadObjectType(year >= 2010); reader.ReadHandle(); - // -- Common entity data ------------------------------------------------ SkipExtendedData(reader); if (reader.ReadBit()) { - // graphics preview block: raw 32-bit size up to R2007, packed 64-bit size from R2010 ulong graphicsSize = year >= 2010 ? reader.ReadPackedLong() : reader.ReadRawUInt32(); if (graphicsSize > 64 * 1024 * 1024) { @@ -59,7 +51,7 @@ internal static class EntityDecoder } bool isModelSpace = reader.ReadTwoBits() == 2; - reader.ReadPackedInt(); // reactor count: back-reference handles consumed from the tail later + reader.ReadPackedInt(); // reactor count reader.ReadBit(); // no extension dictionary flag (R2004+) if (year >= 2013) { @@ -67,14 +59,12 @@ internal static class EntityDecoder } uint colorValue = reader.ReadPackedShort(); - // The colour index takes the low 9 bits (0 BYBLOCK, 1-255 indexed, 256 BYLAYER); the upper byte holds - // the flag bits, whose bit 0 doubles as the "index 256" bit of a discrete colour (see libredwg's - // common_entity_data.spec, which keeps the same flag = raw >> 8 split). int colorIndex = (int)(colorValue & 0x1FF); uint colorFlags = colorValue >> 8; + uint? trueColorRgb = null; if ((colorFlags & 0x40) == 0 && (colorFlags & 0x80) != 0) { - reader.ReadPackedInt(); // true-colour RGB + trueColorRgb = reader.ReadPackedInt() & 0x00FFFFFF; } if ((colorFlags & 0x20) != 0) @@ -107,13 +97,17 @@ internal static class EntityDecoder reader.ReadPackedShort(); // invisibility reader.ReadRawByte(); // lineweight (R2000+) - // -- Type-specific body ------------------------------------------------ (DwgEntityKind kind, double[]? geometry)? body = info.TypeCode switch { - 0x13 => DecodeLine(reader), - 0x12 => DecodeCircle(reader), 0x11 => DecodeArc(reader), + 0x12 => DecodeCircle(reader), + 0x13 => DecodeLine(reader), 0x1B => DecodePoint(reader), + 0x1C => DecodeFace3d(reader), + 0x1F or 0x20 => DecodeSolidOrTrace(reader), + 0x23 => DecodeEllipse(reader), + 0x28 or 0x29 => DecodeRayOrXLine(reader, info.TypeCode == 0x28 ? DwgEntityKind.Ray : DwgEntityKind.XLine), + 0x4D => DecodeLwPolyline(reader, year), _ => null, }; @@ -121,10 +115,11 @@ internal static class EntityDecoder { Handle = info.Handle, TypeCode = info.TypeCode, - TypeName = TypeName(info.TypeCode), + TypeName = info.TypeName, Kind = body?.kind ?? DwgEntityKind.Unknown, Geometry = body?.geometry, ColorIndex = colorIndex, + TrueColorRgb = trueColorRgb, LineTypeScale = lineTypeScale, IsModelSpace = isModelSpace, }; @@ -140,7 +135,7 @@ private static void SkipExtendedData(BitReaderMsb reader) return; } - reader.ReadHandle(); // appid + reader.ReadHandle(); for (uint j = 0; j < size; j++) { reader.ReadRawByte(); @@ -152,8 +147,6 @@ private static void SkipExtendedData(BitReaderMsb reader) private static void SkipText(BitReaderMsb reader, int year) { - // Text value: packed 16-bit length; R2007+ counts UTF-16 characters, earlier releases count - // codepage bytes. int length = (int)reader.ReadPackedShort(); if (year >= 2007) { @@ -171,7 +164,7 @@ private static double[] ReadExtrusion(BitReaderMsb reader) { if (reader.ReadBit()) { - return [0.0, 0.0, 1.0]; // default extrusion + return [0.0, 0.0, 1.0]; } return [reader.ReadPackedDouble(), reader.ReadPackedDouble(), reader.ReadPackedDouble()]; @@ -179,8 +172,6 @@ private static double[] ReadExtrusion(BitReaderMsb reader) private static (DwgEntityKind, double[]) DecodeLine(BitReaderMsb reader) { - // R2000+: z-is-zero flag, start coordinates as raw doubles, end coordinates relative - // to them, thickness, extrusion. bool zIsZero = reader.ReadBit(); double x1 = reader.ReadRawDouble(); double x2 = reader.ReadDoubleWithDefault(x1); @@ -230,7 +221,148 @@ private static (DwgEntityKind, double[]) DecodePoint(BitReaderMsb reader) double z = reader.ReadPackedDouble(); ReadThickness(reader); ReadExtrusion(reader); - reader.ReadPackedDouble(); // x-axis angle + reader.ReadPackedDouble(); return (DwgEntityKind.Point, [x, y, z]); } + + private static (DwgEntityKind, double[]) DecodeEllipse(BitReaderMsb reader) + { + double cx = reader.ReadPackedDouble(); + double cy = reader.ReadPackedDouble(); + double cz = reader.ReadPackedDouble(); + double mx = reader.ReadPackedDouble(); + double my = reader.ReadPackedDouble(); + double mz = reader.ReadPackedDouble(); + _ = reader.ReadPackedDouble(); + _ = reader.ReadPackedDouble(); + _ = reader.ReadPackedDouble(); // 3BD extrusion + double ratio = reader.ReadPackedDouble(); + double startAngle = reader.ReadPackedDouble(); + double endAngle = reader.ReadPackedDouble(); + return (DwgEntityKind.Ellipse, [cx, cy, cz, mx, my, mz, ratio, startAngle, endAngle]); + } + + private static (DwgEntityKind, double[]) DecodeRayOrXLine(BitReaderMsb reader, DwgEntityKind kind) + { + double x = reader.ReadPackedDouble(); + double y = reader.ReadPackedDouble(); + double z = reader.ReadPackedDouble(); + double dx = reader.ReadPackedDouble(); + double dy = reader.ReadPackedDouble(); + double dz = reader.ReadPackedDouble(); + return (kind, [x, y, z, dx, dy, dz]); + } + + private static (DwgEntityKind, double[]) DecodeSolidOrTrace(BitReaderMsb reader) + { + ReadThickness(reader); + double elevation = reader.ReadPackedDouble(); + double x1 = reader.ReadRawDouble(); + double y1 = reader.ReadRawDouble(); + double x2 = reader.ReadRawDouble(); + double y2 = reader.ReadRawDouble(); + double x3 = reader.ReadRawDouble(); + double y3 = reader.ReadRawDouble(); + double x4 = reader.ReadRawDouble(); + double y4 = reader.ReadRawDouble(); + ReadExtrusion(reader); + return (DwgEntityKind.Solid, [x1, y1, elevation, x2, y2, elevation, x3, y3, elevation, x4, y4, elevation]); + } + + private static (DwgEntityKind, double[]) DecodeFace3d(BitReaderMsb reader) + { + bool hasNoFlags = reader.ReadBit(); + bool zIsZero = reader.ReadBit(); + double x1 = reader.ReadRawDouble(); + double y1 = reader.ReadRawDouble(); + double z1 = zIsZero ? 0.0 : reader.ReadRawDouble(); + double x2 = reader.ReadDoubleWithDefault(x1); + double y2 = reader.ReadDoubleWithDefault(y1); + double z2 = zIsZero ? 0.0 : reader.ReadDoubleWithDefault(z1); + double x3 = reader.ReadDoubleWithDefault(x2); + double y3 = reader.ReadDoubleWithDefault(y2); + double z3 = zIsZero ? 0.0 : reader.ReadDoubleWithDefault(z2); + double x4 = reader.ReadDoubleWithDefault(x3); + double y4 = reader.ReadDoubleWithDefault(y3); + double z4 = zIsZero ? 0.0 : reader.ReadDoubleWithDefault(z3); + if (!hasNoFlags) + { + reader.ReadPackedShort(); // invisible edge flags + } + + return (DwgEntityKind.Face3d, [x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4]); + } + + private static (DwgEntityKind, double[]) DecodeLwPolyline(BitReaderMsb reader, int year) + { + uint flags = reader.ReadPackedShort(); + if ((flags & 0x04) != 0) + { + reader.ReadPackedDouble(); // constant width + } + + double elevation = (flags & 0x08) != 0 ? reader.ReadPackedDouble() : 0.0; + if ((flags & 0x02) != 0) + { + reader.ReadPackedDouble(); // thickness + } + + if ((flags & 0x01) != 0) + { + reader.ReadPackedDouble(); + reader.ReadPackedDouble(); + reader.ReadPackedDouble(); // extrusion + } + + uint pointCount = reader.ReadPackedInt(); + uint bulgeCount = (flags & 0x10) != 0 ? reader.ReadPackedInt() : 0; + uint vertexIdCount = (flags & 0x400) != 0 && year >= 2010 ? reader.ReadPackedInt() : 0; + uint widthCount = (flags & 0x20) != 0 ? reader.ReadPackedInt() : 0; + + if (pointCount > MaxPolylineVertices || bulgeCount > MaxPolylineVertices || + vertexIdCount > MaxPolylineVertices || widthCount > MaxPolylineVertices) + { + throw new DwgException($"LWPOLYLINE vertex count ({pointCount}) exceeds safety cap."); + } + + var xs = new double[pointCount]; + var ys = new double[pointCount]; + for (int i = 0; i < (int)pointCount; i++) + { + if (i == 0) + { + xs[0] = reader.ReadRawDouble(); + ys[0] = reader.ReadRawDouble(); + } + else + { + xs[i] = reader.ReadDoubleWithDefault(xs[i - 1]); + ys[i] = reader.ReadDoubleWithDefault(ys[i - 1]); + } + } + + var bulges = new double[pointCount]; + for (int i = 0; i < (int)bulgeCount; i++) + { + double bulge = reader.ReadPackedDouble(); + if (i < bulges.Length) + { + bulges[i] = bulge; + } + } + + bool isClosed = (flags & 0x200) != 0; + var payload = new double[2 + (int)pointCount * 3]; + payload[0] = isClosed ? 1.0 : 0.0; + payload[1] = elevation; + for (int i = 0; i < (int)pointCount; i++) + { + int offset = 2 + i * 3; + payload[offset] = xs[i]; + payload[offset + 1] = ys[i]; + payload[offset + 2] = bulges[i]; + } + + return (DwgEntityKind.Polyline, payload); + } } diff --git a/src/DwgIO/Internal/Parsing/MetadataByteCursor.cs b/src/DwgIO/Internal/Parsing/MetadataByteCursor.cs index 3192f0c..226b259 100644 --- a/src/DwgIO/Internal/Parsing/MetadataByteCursor.cs +++ b/src/DwgIO/Internal/Parsing/MetadataByteCursor.cs @@ -17,7 +17,7 @@ internal sealed class MetadataByteCursor(byte[] bytes, int codepage) public int Remaining => bytes.Length - _pos; - private static Encoding GetEncoding(int codepage) + internal static Encoding GetEncoding(int codepage) { // AutoCAD's own codepage enumeration → Windows codepage numbers. var windowsCodepage = codepage switch diff --git a/src/DwgIO/Json/DwgJsonExporter.cs b/src/DwgIO/Json/DwgJsonExporter.cs index 926c129..275a180 100644 --- a/src/DwgIO/Json/DwgJsonExporter.cs +++ b/src/DwgIO/Json/DwgJsonExporter.cs @@ -176,12 +176,33 @@ public static void Write(DwgDocument document, Stream output, DwgJsonExportOptio writer.WriteStartObject("byTypeName"); foreach (var group in typesByCode) { - writer.WriteNumber(DwgIO.Model.DwgObjectTypes.Name(group.Key), group.Count()); + writer.WriteNumber(group.First().TypeName, group.Count()); } writer.WriteEndObject(); writer.WriteEndObject(); + if (document.Classes.Count > 0) + { + writer.WriteStartArray("classes"); + foreach (var cls in document.Classes) + { + writer.WriteStartObject(); + writer.WriteNumber("classNumber", cls.ClassNumber); + writer.WriteNumber("proxyFlags", cls.ProxyFlags); + writer.WriteString("appName", cls.AppName); + writer.WriteString("cppClassName", cls.CppClassName); + writer.WriteString("dxfName", cls.DxfName); + writer.WriteBoolean("wasZombie", cls.WasZombie); + writer.WriteNumber("itemClassId", cls.ItemClassId); + writer.WriteBoolean("isEntity", cls.IsEntity); + writer.WriteNumber("instanceCount", cls.InstanceCount); + writer.WriteEndObject(); + } + + writer.WriteEndArray(); + } + writer.WriteNumber("entityCount", document.Entities.Count); writer.WriteStartArray("entities"); foreach (var entity in document.Entities) @@ -217,6 +238,11 @@ public static void Write(DwgDocument document, Stream output, DwgJsonExportOptio // Written always: 0 (BYBLOCK) and 256 (BYLAYER) must be distinguishable. writer.WriteNumber("colorIndex", entity.ColorIndex); + if (entity.TrueColorRgb is { } trueColor) + { + writer.WriteString("trueColorRgb", $"#{trueColor:X6}"); + } + writer.WriteEndObject(); } diff --git a/src/DwgIO/Model/DwgClassInfo.cs b/src/DwgIO/Model/DwgClassInfo.cs new file mode 100644 index 0000000..007b9ca --- /dev/null +++ b/src/DwgIO/Model/DwgClassInfo.cs @@ -0,0 +1,49 @@ +namespace DwgIO.Model; + +/// +/// One class entry from the AcDb:Classes section defining a custom or class-indexed object type +/// (codes 500 and above). +/// +public sealed class DwgClassInfo +{ + /// Class type code assigned in this drawing (500 and above). + public required ushort ClassNumber { get; init; } + + /// AutoCAD proxy capability flags. + public required ushort ProxyFlags { get; init; } + + /// Application name (e.g. ObjectDBX Classes). + public required string AppName { get; init; } + + /// C++ class name (e.g. AcDbLayout). + public required string CppClassName { get; init; } + + /// DXF record name (e.g. LAYOUT). + public required string DxfName { get; init; } + + /// Whether the class was a zombie when saved. + public bool WasZombie { get; init; } + + /// Base class identifier: 0x1F2 (498) for drawable entities, 0x1F3 (499) for non-entity objects. + public required ushort ItemClassId { get; init; } + + /// True when is 0x1F2 (drawable entity). + public bool IsEntity => ItemClassId == 0x1F2; + + /// Number of instances declared in the class table (R2004+). + public uint InstanceCount { get; init; } + + /// DWG version that introduced the class. + public uint DwgVersion { get; init; } + + /// Maintenance version that introduced the class. + public uint MaintVersion { get; init; } + + /// Resolved display name: when non-empty, else . + public string DisplayName => !string.IsNullOrEmpty(DxfName) + ? DxfName + : !string.IsNullOrEmpty(CppClassName) ? CppClassName : $"Class_{ClassNumber}"; + + /// Short summary of class number and DXF/C++ name. + public override string ToString() => $"{ClassNumber} {DisplayName} ({CppClassName})"; +} diff --git a/src/DwgIO/Model/DwgEntity.cs b/src/DwgIO/Model/DwgEntity.cs index 4bc4fbd..898fb72 100644 --- a/src/DwgIO/Model/DwgEntity.cs +++ b/src/DwgIO/Model/DwgEntity.cs @@ -1,3 +1,5 @@ +using System.Globalization; + namespace DwgIO.Model; /// The decoded geometry flavour of an entity. @@ -17,11 +19,29 @@ public enum DwgEntityKind /// POINT: a single location. Point, + + /// LWPOLYLINE: 2D lightweight polyline with elevation, closed flag, vertices and bulges. + Polyline, + + /// ELLIPSE: centre, major axis vector, minor-to-major ratio and start/end parameters. + Ellipse, + + /// SOLID / TRACE: planar 4-corner filled quadrilateral (bowtie corner order). + Solid, + + /// 3DFACE: 3D 3- or 4-corner planar face. + Face3d, + + /// RAY: semi-infinite ray (origin + unit direction). + Ray, + + /// XLINE: infinite construction line (base point + unit direction). + XLine, } /// -/// A decoded drawing entity (LINE/CIRCLE/ARC/POINT): common data plus geometry. -/// Entities of other type codes remain inventory-only in this milestone. +/// A decoded drawing entity: common data plus geometry for supported entity types. +/// Entities of other type codes remain inventory-only. /// public sealed class DwgEntity { @@ -37,9 +57,20 @@ public sealed class DwgEntity /// Which geometry, if any, was decoded. public required DwgEntityKind Kind { get; init; } - /// Geometry payload — meaning depends on : - /// Line = [x1,y1,z1,x2,y2,z2]; Circle/Arc = [cx,cy,cz,radius] (+ [start,end] radians for Arc); - /// Point = [x,y,z]. Null for non-decoded kinds. + /// + /// Geometry payload — meaning depends on : + /// + /// : [x1, y1, z1, x2, y2, z2] + /// : [cx, cy, cz, radius] + /// : [cx, cy, cz, radius, startRad, endRad] + /// : [x, y, z] + /// : [isClosed (0|1), elevation, x0, y0, bulge0, ...] + /// : [cx, cy, cz, mx, my, mz, ratio, startRad, endRad] + /// / : [x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4] + /// / : [x, y, z, dx, dy, dz] + /// + /// Null for non-decoded kinds. + /// public double[]? Geometry { get; init; } /// Whether the entity belongs directly to model space. @@ -49,6 +80,9 @@ public sealed class DwgEntity /// so 0 is BYBLOCK, 1 to 255 are indexed colours and 256 is BYLAYER. public int ColorIndex { get; init; } + /// Optional 24-bit true colour (0x00RRGGBB) from the common preamble when stored. + public uint? TrueColorRgb { get; init; } + /// DXF 48 linetype scale from the common preamble. public double LineTypeScale { get; init; } @@ -57,13 +91,23 @@ public override string ToString() => Kind switch { DwgEntityKind.Line when Geometry is { Length: 6 } g => - $"LINE {Handle:X}: ({g[0]:F3},{g[1]:F3},{g[2]:F3}) → ({g[3]:F3},{g[4]:F3},{g[5]:F3})", + string.Create(CultureInfo.InvariantCulture, $"LINE {Handle:X}: ({g[0]:F3},{g[1]:F3},{g[2]:F3}) → ({g[3]:F3},{g[4]:F3},{g[5]:F3})"), DwgEntityKind.Circle when Geometry is { Length: 4 } g => - $"CIRCLE {Handle:X}: c=({g[0]:F3},{g[1]:F3},{g[2]:F3}) r={g[3]:F3}", + string.Create(CultureInfo.InvariantCulture, $"CIRCLE {Handle:X}: c=({g[0]:F3},{g[1]:F3},{g[2]:F3}) r={g[3]:F3}"), DwgEntityKind.Arc when Geometry is { Length: 6 } g => - $"ARC {Handle:X}: c=({g[0]:F3},{g[1]:F3},{g[2]:F3}) r={g[3]:F3} [{g[4]:F3}..{g[5]:F3} rad]", + string.Create(CultureInfo.InvariantCulture, $"ARC {Handle:X}: c=({g[0]:F3},{g[1]:F3},{g[2]:F3}) r={g[3]:F3} [{g[4]:F3}..{g[5]:F3} rad]"), DwgEntityKind.Point when Geometry is { Length: 3 } g => - $"POINT {Handle:X}: ({g[0]:F3},{g[1]:F3},{g[2]:F3})", + string.Create(CultureInfo.InvariantCulture, $"POINT {Handle:X}: ({g[0]:F3},{g[1]:F3},{g[2]:F3})"), + DwgEntityKind.Polyline when Geometry is { Length: >= 2 } g => + string.Create(CultureInfo.InvariantCulture, $"LWPOLYLINE {Handle:X}: {(g.Length - 2) / 3} vertices{(g[0] != 0 ? " (closed)" : "")}"), + DwgEntityKind.Ellipse when Geometry is { Length: 9 } g => + string.Create(CultureInfo.InvariantCulture, $"ELLIPSE {Handle:X}: c=({g[0]:F3},{g[1]:F3},{g[2]:F3}) major=({g[3]:F3},{g[4]:F3},{g[5]:F3}) ratio={g[6]:F3}"), + DwgEntityKind.Solid when Geometry is { Length: 12 } g => + string.Create(CultureInfo.InvariantCulture, $"{TypeName} {Handle:X}: ({g[0]:F3},{g[1]:F3},{g[2]:F3}) .. ({g[9]:F3},{g[10]:F3},{g[11]:F3})"), + DwgEntityKind.Face3d when Geometry is { Length: 12 } g => + string.Create(CultureInfo.InvariantCulture, $"3DFACE {Handle:X}: ({g[0]:F3},{g[1]:F3},{g[2]:F3}) .. ({g[9]:F3},{g[10]:F3},{g[11]:F3})"), + DwgEntityKind.Ray or DwgEntityKind.XLine when Geometry is { Length: 6 } g => + string.Create(CultureInfo.InvariantCulture, $"{TypeName} {Handle:X}: p=({g[0]:F3},{g[1]:F3},{g[2]:F3}) d=({g[3]:F3},{g[4]:F3},{g[5]:F3})"), _ => $"{TypeName} {Handle:X}", }; } diff --git a/src/DwgIO/Model/DwgObjectInfo.cs b/src/DwgIO/Model/DwgObjectInfo.cs index 7febb2d..1cd77b7 100644 --- a/src/DwgIO/Model/DwgObjectInfo.cs +++ b/src/DwgIO/Model/DwgObjectInfo.cs @@ -25,9 +25,12 @@ public sealed record DwgObjectInfo /// Object type code (e.g. LINE, LWPOLYLINE). public required ushort TypeCode { get; init; } - /// Name for : the AutoCAD or table name, or Object_XX/Class_XX - /// when the code is not in the fixed table (see ). - public string TypeName => DwgObjectTypes.Name(TypeCode); + /// Optional resolved class name from AcDb:Classes for codes 500 and above. + public string? ClassName { get; init; } + + /// Name for : the AutoCAD or table name, the resolved class name from + /// AcDb:Classes, or Object_XX/Class_XX when unresolved (see ). + public string TypeName => ClassName ?? DwgObjectTypes.Name(TypeCode); /// Absolute object handle as read from the record (the value of ). public required ulong Handle { get; init; } diff --git a/tests/DwgIO.Tests/ClassesAndEntitiesTests.cs b/tests/DwgIO.Tests/ClassesAndEntitiesTests.cs new file mode 100644 index 0000000..1f0b795 --- /dev/null +++ b/tests/DwgIO.Tests/ClassesAndEntitiesTests.cs @@ -0,0 +1,320 @@ +using System.Text; +using System.Text.Json; +using DwgIO.Export; +using DwgIO.Internal.Container; +using DwgIO.Internal.Parsing; +using DwgIO.Model; +using DwgIO.Scene; +using IOScene; +using Xunit; +using Vector3d = IOScene.Vector3d; + +namespace DwgIO.Tests; + +public class ClassesAndEntitiesTests : IDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), "dwgio-cls-" + Guid.NewGuid().ToString("N")); + + public ClassesAndEntitiesTests() + { + Directory.CreateDirectory(_directory); + } + + public void Dispose() + { + GC.SuppressFinalize(this); + try + { + Directory.Delete(_directory, recursive: true); + } + catch (DirectoryNotFoundException) + { + } + } + + [Theory] + [InlineData("primitives-ac1024.dwg")] + [InlineData("primitives-ac1027.dwg")] + [InlineData("primitives-ac1032.dwg")] + public void PublicDrawings_ParseClassesAndResolveObjectNames(string fileName) + { + var doc = DwgDocument.Open(TestFiles.PublicDrawing(fileName)); + + Assert.Equal(6, doc.Classes.Count); + Assert.Equal("SCALE", doc.Classes[0].DxfName); + Assert.Equal("AcDbScale", doc.Classes[0].CppClassName); + Assert.Equal("ObjectDBX Classes", doc.Classes[0].AppName); + Assert.Equal(500, doc.Classes[0].ClassNumber); + Assert.False(doc.Classes[0].IsEntity); + + Assert.Contains(doc.Classes, c => c.ClassNumber == 503 && c.DxfName == "DICTIONARYVAR"); + Assert.Contains(doc.Classes, c => c.ClassNumber == 504 && c.DxfName == "MATERIAL"); + Assert.Contains(doc.Classes, c => c.ClassNumber == 505 && c.DxfName == "LAYOUT"); + + // Objects with codes >= 500 resolve through the class table. + Assert.Contains(doc.Objects, o => o.TypeCode == 500 && o.TypeName == "SCALE"); + Assert.DoesNotContain(doc.Objects, o => o.TypeName.StartsWith("Class_", StringComparison.Ordinal)); + + using var jsonDoc = JsonDocument.Parse(doc.ToJson()); + Assert.Equal(6, jsonDoc.RootElement.GetProperty("classes").GetArrayLength()); + Assert.True(jsonDoc.RootElement.GetProperty("objects").GetProperty("byTypeName").TryGetProperty("SCALE", out _)); + } + + [Fact] + public void ClassesParser_RejectsMissingSentinelAndTruncatedPayload() + { + Assert.Throws(() => ClassesParser.Parse(new byte[10], 2018, 30)); + Assert.Throws(() => ClassesParser.Parse(new byte[32], 2018, 30)); + } + + [Fact] + public void EntityDecoder_DecodesTrueColorAndLwPolylineWithBulge() + { + var stream = BuildStream(0x4D, w => + { + w.WriteTwoBits(0); // flags: full 16-bit LE + w.WriteRawByte(0x18); // 0x218 = closed (0x200) | bulges (0x10) | elevation (0x08) + w.WriteRawByte(0x02); + WritePackedDouble(w, 2.5); // elevation + WritePackedInt(w, 3); // 3 vertices + WritePackedInt(w, 1); // 1 bulge + w.WriteRawDouble(0.0); + w.WriteRawDouble(0.0); + WriteNewDouble(w, 10.0); + WriteNewDouble(w, 0.0); + WriteNewDouble(w, 10.0); + WriteNewDouble(w, 10.0); + WritePackedDouble(w, 1.0); // semicircle bulge on segment 0 -> 1 + }, colorValue: 0x8007); // 0x80 true-color flag + + var objects = ObjectStreamWalker.Walk(stream, r2010Plus: true); + var info = Assert.Single(objects); + var entity = EntityDecoder.Decode(info, stream, 2018); + + Assert.NotNull(entity); + Assert.Equal(DwgEntityKind.Polyline, entity.Kind); + Assert.Equal(0x00123456u, entity.TrueColorRgb); + Assert.NotNull(entity.Geometry); + Assert.Equal(11, entity.Geometry.Length); + Assert.Equal(1.0, entity.Geometry[0]); // closed + Assert.Equal(2.5, entity.Geometry[1]); // elevation + Assert.Equal(0.0, entity.Geometry[2]); + Assert.Equal(0.0, entity.Geometry[3]); + Assert.Equal(1.0, entity.Geometry[4]); // bulge 0 + Assert.Equal(10.0, entity.Geometry[5]); + Assert.Equal(0.0, entity.Geometry[6]); + Assert.Equal(10.0, entity.Geometry[8]); + Assert.Equal(10.0, entity.Geometry[9]); + } + + [Fact] + public void EntityDecoder_DecodesEllipseSolidFace3dAndRay() + { + byte[] ellipseStream = BuildStream(0x23, w => + { + WritePackedDouble(w, 1.0); WritePackedDouble(w, 2.0); WritePackedDouble(w, 0.0); // center + WritePackedDouble(w, 5.0); WritePackedDouble(w, 0.0); WritePackedDouble(w, 0.0); // major axis + WritePackedDouble(w, 0.0); WritePackedDouble(w, 0.0); WritePackedDouble(w, 1.0); // extrusion + WritePackedDouble(w, 0.5); // ratio + WritePackedDouble(w, 0.0); + WritePackedDouble(w, Math.PI); + }); + var ellipse = EntityDecoder.Decode(Assert.Single(ObjectStreamWalker.Walk(ellipseStream, true)), ellipseStream, 2018)!; + Assert.Equal(DwgEntityKind.Ellipse, ellipse.Kind); + Assert.Equal([1.0, 2.0, 0.0, 5.0, 0.0, 0.0, 0.5, 0.0, Math.PI], ellipse.Geometry!); + + byte[] solidStream = BuildStream(0x1F, w => + { + w.WriteBit(true); // thickness 0 + WritePackedDouble(w, 3.0); // elevation + w.WriteRawDouble(0.0); w.WriteRawDouble(0.0); + w.WriteRawDouble(4.0); w.WriteRawDouble(0.0); + w.WriteRawDouble(0.0); w.WriteRawDouble(2.0); + w.WriteRawDouble(4.0); w.WriteRawDouble(2.0); + w.WriteBit(true); // default extrusion + }); + var solid = EntityDecoder.Decode(Assert.Single(ObjectStreamWalker.Walk(solidStream, true)), solidStream, 2018)!; + Assert.Equal(DwgEntityKind.Solid, solid.Kind); + Assert.Equal(12, solid.Geometry!.Length); + Assert.Equal(3.0, solid.Geometry[2]); + + byte[] faceStream = BuildStream(0x1C, w => + { + w.WriteBit(true); // hasNoFlags + w.WriteBit(true); // zIsZero + w.WriteRawDouble(0.0); w.WriteRawDouble(0.0); + WriteNewDouble(w, 1.0); WriteNewDouble(w, 0.0); + WriteNewDouble(w, 1.0); WriteNewDouble(w, 1.0); + WriteNewDouble(w, 0.0); WriteNewDouble(w, 1.0); + }); + var face = EntityDecoder.Decode(Assert.Single(ObjectStreamWalker.Walk(faceStream, true)), faceStream, 2018)!; + Assert.Equal(DwgEntityKind.Face3d, face.Kind); + Assert.Equal([0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0], face.Geometry!); + + byte[] rayStream = BuildStream(0x28, w => + { + WritePackedDouble(w, 2.0); WritePackedDouble(w, 3.0); WritePackedDouble(w, 0.0); + WritePackedDouble(w, 1.0); WritePackedDouble(w, 0.0); WritePackedDouble(w, 0.0); + }); + var ray = EntityDecoder.Decode(Assert.Single(ObjectStreamWalker.Walk(rayStream, true)), rayStream, 2018)!; + Assert.Equal(DwgEntityKind.Ray, ray.Kind); + Assert.Equal([2.0, 3.0, 0.0, 1.0, 0.0, 0.0], ray.Geometry!); + } + + [Fact] + public void SceneSvgAndViewer_RenderPolylineEllipseSolidAndTrueColor() + { + var doc = new DwgDocument( + "entities.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1032", + Release = "R2018", + Family = DwgContainerFamily.R2004Family, + Year = 2018, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + [ + new DwgEntity + { + Handle = 0x10, + TypeCode = 0x4D, + TypeName = "LWPOLYLINE", + Kind = DwgEntityKind.Polyline, + Geometry = [1.0, 0.0, 0.0, 0.0, 1.0, 10.0, 0.0, 0.0, 10.0, 10.0, 0.0], + ColorIndex = 256, + TrueColorRgb = 0x112233u, + }, + new DwgEntity + { + Handle = 0x11, + TypeCode = 0x23, + TypeName = "ELLIPSE", + Kind = DwgEntityKind.Ellipse, + Geometry = [5.0, 5.0, 0.0, 4.0, 0.0, 0.0, 0.5, 0.0, Math.Tau], + ColorIndex = 3, + }, + new DwgEntity + { + Handle = 0x12, + TypeCode = 0x1F, + TypeName = "SOLID", + Kind = DwgEntityKind.Solid, + Geometry = [0, 0, 0, 2, 0, 0, 0, 2, 0, 2, 2, 0], + ColorIndex = 1, + }, + ]); + + // IOScene + var sceneResult = DwgSceneReader.Read(doc, new DwgSceneOptions { ModelKey = "entities" }); + Assert.Equal(3, sceneResult.ElementsWithGeometry); + Assert.DoesNotContain(sceneResult.Document.Validate(), d => d.Severity == SceneSeverity.Error); + Assert.Equal(new RgbaColor(0x11, 0x22, 0x33), sceneResult.Document.Instances[0].Color); + Assert.Equal(SceneTopology.Lines, sceneResult.Document.Geometries[0].Topology); + Assert.True(sceneResult.Document.Geometries[0].Vertices.Count > 10); // bulge tessellated + Assert.Equal(SceneTopology.Lines, sceneResult.Document.Geometries[1].Topology); + Assert.Equal(SceneTopology.Triangles, sceneResult.Document.Geometries[2].Topology); + Assert.Equal(new Vector3d(2.0, 2.0, 0.0), sceneResult.Document.Geometries[2].Vertices[2]); + + // SVG + using var svgStream = new MemoryStream(); + DwgSvgExporter.Write(doc, svgStream); + string svg = Encoding.UTF8.GetString(svgStream.ToArray()); + Assert.Contains("stroke=\"#112233\"", svg, StringComparison.Ordinal); + Assert.Contains("A ", svg, StringComparison.Ordinal); // bulge arc in SVG path + + // 2D AutoCAD HTML viewer + string htmlPath = Path.Combine(_directory, "entities.html"); + DwgViewerExport.SaveViewer(doc, htmlPath); + 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("\"kind\":\"solid\"", html, StringComparison.Ordinal); + } + + private static byte[] BuildStream(ushort typeCode, Action writeBody, ushort colorValue = 2) + { + var w = new RecordBitWriter(); + w.WriteRawByte(0xCA); + w.WriteRawByte(0x0D); + w.WriteRawByte(0x00); + w.WriteRawByte(0x00); + w.WriteRecord(p => + { + p.WriteRawByte(0x00); // R2010+ handle-stream size placeholder + p.WriteTwoBits(0); + p.WriteRawByte((byte)typeCode); + p.WriteHandle(0, 1); + p.WriteTwoBits(2); // no extended data + p.WriteBit(false); // no graphics + p.WriteTwoBits(2); // model space + p.WriteTwoBits(2); // 0 reactors + p.WriteBit(false); // no xdict + p.WriteBit(false); // no AcDs (R2013+) + if (colorValue == 2) + { + p.WriteTwoBits(2); // BYBLOCK + } + else + { + p.WritePackedShortRaw(colorValue); + if ((colorValue & 0x8000) != 0) + { + WritePackedInt(p, 0x00123456); + } + } + + p.WriteTwoBits(1); // ltscale = 1.0 + p.WriteTwoBits(0); // lt flags + p.WriteTwoBits(0); // plot style flags + p.WriteTwoBits(0); // material flags + p.WriteRawByte(0); // shadow flags + p.WriteBit(false); // full visual style + p.WriteBit(false); // face visual style + p.WriteBit(false); // edge visual style + p.WriteTwoBits(2); // invisibility 0 + p.WriteRawByte(0); // lineweight + writeBody(p); + }); + return w.ToArray(); + } + + private static void WritePackedInt(RecordBitWriter w, uint value) + { + w.WriteTwoBits(0); + w.WriteRawByte((byte)(value & 0xFF)); + w.WriteRawByte((byte)((value >> 8) & 0xFF)); + w.WriteRawByte((byte)((value >> 16) & 0xFF)); + w.WriteRawByte((byte)((value >> 24) & 0xFF)); + } + + private static void WritePackedDouble(RecordBitWriter w, double value) + { + if (value == 0.0) + { + w.WriteTwoBits(2); + return; + } + + if (value == 1.0) + { + w.WriteTwoBits(1); + return; + } + + w.WriteTwoBits(0); + w.WriteRawDouble(value); + } + + private static void WriteNewDouble(RecordBitWriter w, double value) + { + w.WriteTwoBits(3); + w.WriteRawDouble(value); + } +} diff --git a/tests/DwgIO.Tests/CoreStandardTests.cs b/tests/DwgIO.Tests/CoreStandardTests.cs index e3f24d3..d6e036f 100644 --- a/tests/DwgIO.Tests/CoreStandardTests.cs +++ b/tests/DwgIO.Tests/CoreStandardTests.cs @@ -94,7 +94,7 @@ public void Open_ProgressAndDiagnosticOutput_ReportSynchronously() DiagnosticOutput = writer, }); - Assert.Equal(["header", "container", "metadata", "handles", "objects", "entities", "entities", "complete"], phases); + Assert.Equal(["header", "container", "metadata", "classes", "handles", "objects", "entities", "entities", "complete"], phases); Assert.Equal(doc.Diagnostics.Count > 0, writer.ToString().Length > 0); } From f86b7763787cfb0d11494fdc5690a75014f341d5 Mon Sep 17 00:00:00 2001 From: mahach666 Date: Wed, 2 Dec 2026 12:55:21 +0300 Subject: [PATCH 2/2] Project ellipses using the decoded plane normal --- src/DwgIO.Cli/DwgIO.Cli.csproj | 2 +- src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs | 36 ++++++++++++------- .../DwgIO.Scene.Adapter.csproj | 2 +- src/DwgIO.Scene.Adapter/DwgSceneReader.cs | 7 ++-- .../Compatibility/DwgSvgExporter.cs | 18 +++++----- src/DwgIO.Scene/DwgIO.Scene.csproj | 2 +- src/DwgIO/Internal/Parsing/EntityDecoder.cs | 8 ++--- src/DwgIO/Model/DwgEntity.cs | 6 ++-- src/Shared/EllipseAxes.cs | 23 ++++++++++++ tests/DwgIO.Tests/ClassesAndEntitiesTests.cs | 13 ++++--- 10 files changed, 76 insertions(+), 41 deletions(-) create mode 100644 src/Shared/EllipseAxes.cs diff --git a/src/DwgIO.Cli/DwgIO.Cli.csproj b/src/DwgIO.Cli/DwgIO.Cli.csproj index 0c3dbc8..4f23f78 100644 --- a/src/DwgIO.Cli/DwgIO.Cli.csproj +++ b/src/DwgIO.Cli/DwgIO.Cli.csproj @@ -17,7 +17,7 @@ - diff --git a/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs b/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs index 763f4e6..9a324e2 100644 --- a/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs +++ b/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs @@ -89,7 +89,7 @@ private static string BuildPayloadJson(DwgDocument document, DwgViewerOptions op continue; } - if (!TryExpandBounds(entity, ref minX, ref minY, ref maxX, ref maxY)) + if (!TryExpandBounds(entity, ref minX, ref minY, ref maxX, ref maxY, out var ellipseMinor)) { continue; } @@ -110,6 +110,12 @@ private static string BuildPayloadJson(DwgDocument document, DwgViewerOptions op w.WriteNumber("lineTypeScale", double.IsFinite(entity.LineTypeScale) ? Math.Round(entity.LineTypeScale, 6) : 1.0); w.WriteBoolean("modelSpace", entity.IsModelSpace); + if (ellipseMinor is { } minor) + { + w.WriteNumber("ellipseMinorX", minor.X); + w.WriteNumber("ellipseMinorY", minor.Y); + } + w.WriteStartArray("geom"); foreach (double v in entity.Geometry) { @@ -167,8 +173,11 @@ private static string BuildPayloadJson(DwgDocument document, DwgViewerOptions op return string.Create(CultureInfo.InvariantCulture, $"#{r:X2}{g:X2}{b:X2}"); } - private static bool TryExpandBounds(DwgEntity entity, ref double minX, ref double minY, ref double maxX, ref double maxY) + private static bool TryExpandBounds( + DwgEntity entity, 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, _]): @@ -204,13 +213,14 @@ private static bool TryExpandBounds(DwgEntity entity, ref double minX, ref doubl } return count > 0; - case (DwgEntityKind.Ellipse, [var cx, var cy, _, var mx, var my, _, var ratio, var startRaw, var endRaw]) when ratio > 0: - double nx = -my * ratio, ny = mx * ratio; - var (eStart, eSpan) = ArcAngles.Normalize(startRaw, endRaw); + 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(cx + mx * Math.Cos(a) + nx * Math.Sin(a), cy + my * Math.Cos(a) + ny * Math.Sin(a), + 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); } @@ -787,8 +797,9 @@ function entityBounds(e) { return { minX, minY, maxX, maxY }; } if (e.kind === 'ellipse') { - const r = Math.max(Math.hypot(g[3], g[4]), 1); - return { minX: g[0] - r, minY: g[1] - r, maxX: g[0] + r, maxY: g[1] + r }; + const rx = Math.hypot(g[3], e.ellipseMinorX); + const ry = Math.hypot(g[4], e.ellipseMinorY); + return { minX: g[0] - rx, minY: g[1] - ry, maxX: g[0] + rx, maxY: g[1] + ry }; } if (e.kind === 'solid' || e.kind === 'face3d') { return { @@ -1004,9 +1015,8 @@ function drawEntity(entity, w, h, overrideColor, lineWidth) { } ctx.stroke(); } else if (entity.kind === 'ellipse') { - const cx = g[0], cy = g[1], mx = g[3], my = g[4], ratio = g[6]; - if (!Number.isFinite(ratio) || ratio <= 0) return; - const nx = -my * ratio, ny = mx * ratio; + const cx = g[0], cy = g[1], mx = g[3], my = g[4]; + const nx = entity.ellipseMinorX, ny = entity.ellipseMinorY; const [start, span] = arcSpan(g[7], g[8]); const steps = Math.max(16, Math.min(256, Math.ceil(span / (5 * Math.PI / 180)))); ctx.beginPath(); @@ -1140,8 +1150,8 @@ function hitTest(wx, wy) { d = Math.min(d, distanceToSegment(wx, wy, g[2 + k * 3], g[2 + k * 3 + 1], g[2 + next * 3], g[2 + next * 3 + 1])); } } else if (e.kind === 'ellipse') { - const cx = g[0], cy = g[1], mx = g[3], my = g[4], ratio = g[6]; - const nx = -my * ratio, ny = mx * ratio; + const cx = g[0], cy = g[1], mx = g[3], my = g[4]; + const nx = e.ellipseMinorX, ny = e.ellipseMinorY; const [start, span] = arcSpan(g[7], g[8]); let prevX = cx + mx * Math.cos(start) + nx * Math.sin(start); let prevY = cy + my * Math.cos(start) + ny * Math.sin(start); diff --git a/src/DwgIO.Scene.Adapter/DwgIO.Scene.Adapter.csproj b/src/DwgIO.Scene.Adapter/DwgIO.Scene.Adapter.csproj index e1c56ab..d79ca17 100644 --- a/src/DwgIO.Scene.Adapter/DwgIO.Scene.Adapter.csproj +++ b/src/DwgIO.Scene.Adapter/DwgIO.Scene.Adapter.csproj @@ -15,7 +15,7 @@ - + diff --git a/src/DwgIO.Scene.Adapter/DwgSceneReader.cs b/src/DwgIO.Scene.Adapter/DwgSceneReader.cs index 929c8ab..f10dd1c 100644 --- a/src/DwgIO.Scene.Adapter/DwgSceneReader.cs +++ b/src/DwgIO.Scene.Adapter/DwgSceneReader.cs @@ -156,7 +156,7 @@ private static DwgSceneResult Convert(DwgDocument document, string key, string? (SceneTopology.Points, PointVertices(g, metresPerUnit), Array.Empty()), DwgEntityKind.Polyline when entity.Geometry is { Length: >= 5 } g => BuildPolyline(g, metresPerUnit), - DwgEntityKind.Ellipse when entity.Geometry is { Length: 9 } g => + DwgEntityKind.Ellipse when entity.Geometry is { Length: 12 } g => BuildEllipse(g, metresPerUnit), DwgEntityKind.Solid when entity.Geometry is { Length: 12 } g => BuildQuad(g, metresPerUnit, bowtieOrder: true), @@ -355,13 +355,12 @@ private static (SceneTopology, Vector3d[], IReadOnlyList)? BuildEllipse(dou { 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; - double ratio = g[6]; - if (!double.IsFinite(ratio) || ratio <= 0) + if (!EllipseAxes.TryGetMinor(g, out var minor)) { return null; } - double nx = -my * ratio, ny = mx * ratio, nz = mz * ratio; + double nx = minor.X * scale, ny = minor.Y * scale, nz = minor.Z * scale; 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); diff --git a/src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs b/src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs index 01fdec6..f476056 100644 --- a/src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs +++ b/src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs @@ -224,8 +224,8 @@ private static List Collect(DwgDocument document, DwgSvgOptions option } break; - case (DwgEntityKind.Ellipse, [var cx, var cy, _, var mx, var my, _, var ratio, var start, var end]): - if (TryBuildEllipse(cx, cy, mx, my, ratio, start, end, scale, entity, out var ellipse)) + case (DwgEntityKind.Ellipse, { Length: 12 } g): + if (TryBuildEllipse(g, scale, entity, out var ellipse)) { shapes.Add(ellipse); } @@ -304,20 +304,18 @@ private static bool TryBuildPolyline(double[] g, double scale, DwgEntity entity, return true; } - private static bool TryBuildEllipse( - double cx, double cy, double mx, double my, double ratio, double startRaw, double endRaw, - double scale, DwgEntity entity, out SvgPath path) + private static bool TryBuildEllipse(double[] g, double scale, DwgEntity entity, out SvgPath path) { - if (!IsUsable(cx, cy, mx, my, ratio, startRaw, endRaw) || ratio <= 0) + if (!IsUsable(g) || !EllipseAxes.TryGetMinor(g, out var minor)) { path = null!; return false; } - double scx = cx * scale, scy = -cy * scale; - double smx = mx * scale, smy = -my * scale; - double snx = -my * ratio * scale, sny = -(mx * ratio * scale); - var (start, span) = ArcAngles.Normalize(startRaw, endRaw); + double scx = g[0] * scale, scy = -g[1] * scale; + double smx = g[3] * scale, smy = -g[4] * scale; + double snx = minor.X * scale, sny = -minor.Y * scale; + var (start, span) = ArcAngles.Normalize(g[7], g[8]); bool closed = span >= Math.Tau - 1e-9; int steps = Math.Clamp((int)Math.Ceiling(span / (5.0 * Math.PI / 180.0)), 16, 256); var sb = new System.Text.StringBuilder(); diff --git a/src/DwgIO.Scene/DwgIO.Scene.csproj b/src/DwgIO.Scene/DwgIO.Scene.csproj index a5d8f87..c130957 100644 --- a/src/DwgIO.Scene/DwgIO.Scene.csproj +++ b/src/DwgIO.Scene/DwgIO.Scene.csproj @@ -23,7 +23,7 @@ - diff --git a/src/DwgIO/Internal/Parsing/EntityDecoder.cs b/src/DwgIO/Internal/Parsing/EntityDecoder.cs index 6d36869..92dd0e9 100644 --- a/src/DwgIO/Internal/Parsing/EntityDecoder.cs +++ b/src/DwgIO/Internal/Parsing/EntityDecoder.cs @@ -233,13 +233,13 @@ private static (DwgEntityKind, double[]) DecodeEllipse(BitReaderMsb reader) double mx = reader.ReadPackedDouble(); double my = reader.ReadPackedDouble(); double mz = reader.ReadPackedDouble(); - _ = reader.ReadPackedDouble(); - _ = reader.ReadPackedDouble(); - _ = reader.ReadPackedDouble(); // 3BD extrusion + double nx = reader.ReadPackedDouble(); + double ny = reader.ReadPackedDouble(); + double nz = reader.ReadPackedDouble(); double ratio = reader.ReadPackedDouble(); double startAngle = reader.ReadPackedDouble(); double endAngle = reader.ReadPackedDouble(); - return (DwgEntityKind.Ellipse, [cx, cy, cz, mx, my, mz, ratio, startAngle, endAngle]); + return (DwgEntityKind.Ellipse, [cx, cy, cz, mx, my, mz, ratio, startAngle, endAngle, nx, ny, nz]); } private static (DwgEntityKind, double[]) DecodeRayOrXLine(BitReaderMsb reader, DwgEntityKind kind) diff --git a/src/DwgIO/Model/DwgEntity.cs b/src/DwgIO/Model/DwgEntity.cs index 898fb72..3e935da 100644 --- a/src/DwgIO/Model/DwgEntity.cs +++ b/src/DwgIO/Model/DwgEntity.cs @@ -23,7 +23,7 @@ public enum DwgEntityKind /// LWPOLYLINE: 2D lightweight polyline with elevation, closed flag, vertices and bulges. Polyline, - /// ELLIPSE: centre, major axis vector, minor-to-major ratio and start/end parameters. + /// ELLIPSE: centre, major axis, axis ratio, start/end parameters and plane normal. Ellipse, /// SOLID / TRACE: planar 4-corner filled quadrilateral (bowtie corner order). @@ -65,7 +65,7 @@ public sealed class DwgEntity /// : [cx, cy, cz, radius, startRad, endRad] /// : [x, y, z] /// : [isClosed (0|1), elevation, x0, y0, bulge0, ...] - /// : [cx, cy, cz, mx, my, mz, ratio, startRad, endRad] + /// : [cx, cy, cz, mx, my, mz, ratio, startRad, endRad, nx, ny, nz] /// / : [x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4] /// / : [x, y, z, dx, dy, dz] /// @@ -100,7 +100,7 @@ public override string ToString() => string.Create(CultureInfo.InvariantCulture, $"POINT {Handle:X}: ({g[0]:F3},{g[1]:F3},{g[2]:F3})"), DwgEntityKind.Polyline when Geometry is { Length: >= 2 } g => string.Create(CultureInfo.InvariantCulture, $"LWPOLYLINE {Handle:X}: {(g.Length - 2) / 3} vertices{(g[0] != 0 ? " (closed)" : "")}"), - DwgEntityKind.Ellipse when Geometry is { Length: 9 } g => + DwgEntityKind.Ellipse when Geometry is { Length: 12 } g => string.Create(CultureInfo.InvariantCulture, $"ELLIPSE {Handle:X}: c=({g[0]:F3},{g[1]:F3},{g[2]:F3}) major=({g[3]:F3},{g[4]:F3},{g[5]:F3}) ratio={g[6]:F3}"), DwgEntityKind.Solid when Geometry is { Length: 12 } g => string.Create(CultureInfo.InvariantCulture, $"{TypeName} {Handle:X}: ({g[0]:F3},{g[1]:F3},{g[2]:F3}) .. ({g[9]:F3},{g[10]:F3},{g[11]:F3})"), diff --git a/src/Shared/EllipseAxes.cs b/src/Shared/EllipseAxes.cs new file mode 100644 index 0000000..b9d9d2b --- /dev/null +++ b/src/Shared/EllipseAxes.cs @@ -0,0 +1,23 @@ +namespace DwgIO.Scene; + +internal static class EllipseAxes +{ + public static bool TryGetMinor(double[] geometry, out (double X, double Y, double Z) minor) + { + minor = default; + double nx = geometry[9], ny = geometry[10], nz = geometry[11]; + double normalLength = double.Hypot(double.Hypot(nx, ny), nz); + double ratio = geometry[6]; + if (normalLength == 0 || !double.IsFinite(normalLength) || ratio <= 0 || !double.IsFinite(ratio)) + { + return false; + } + + nx /= normalLength; + ny /= normalLength; + nz /= normalLength; + double mx = geometry[3] * ratio, my = geometry[4] * ratio, mz = geometry[5] * ratio; + minor = (ny * mz - nz * my, nz * mx - nx * mz, nx * my - ny * mx); + return double.IsFinite(minor.X) && double.IsFinite(minor.Y) && double.IsFinite(minor.Z); + } +} diff --git a/tests/DwgIO.Tests/ClassesAndEntitiesTests.cs b/tests/DwgIO.Tests/ClassesAndEntitiesTests.cs index 1f0b795..a9dcb51 100644 --- a/tests/DwgIO.Tests/ClassesAndEntitiesTests.cs +++ b/tests/DwgIO.Tests/ClassesAndEntitiesTests.cs @@ -114,14 +114,14 @@ public void EntityDecoder_DecodesEllipseSolidFace3dAndRay() { WritePackedDouble(w, 1.0); WritePackedDouble(w, 2.0); WritePackedDouble(w, 0.0); // center WritePackedDouble(w, 5.0); WritePackedDouble(w, 0.0); WritePackedDouble(w, 0.0); // major axis - WritePackedDouble(w, 0.0); WritePackedDouble(w, 0.0); WritePackedDouble(w, 1.0); // extrusion + WritePackedDouble(w, 0.0); WritePackedDouble(w, 1.0); WritePackedDouble(w, 0.0); // normal WritePackedDouble(w, 0.5); // ratio WritePackedDouble(w, 0.0); WritePackedDouble(w, Math.PI); }); var ellipse = EntityDecoder.Decode(Assert.Single(ObjectStreamWalker.Walk(ellipseStream, true)), ellipseStream, 2018)!; Assert.Equal(DwgEntityKind.Ellipse, ellipse.Kind); - Assert.Equal([1.0, 2.0, 0.0, 5.0, 0.0, 0.0, 0.5, 0.0, Math.PI], ellipse.Geometry!); + Assert.Equal([1.0, 2.0, 0.0, 5.0, 0.0, 0.0, 0.5, 0.0, Math.PI, 0.0, 1.0, 0.0], ellipse.Geometry!); byte[] solidStream = BuildStream(0x1F, w => { @@ -196,7 +196,7 @@ public void SceneSvgAndViewer_RenderPolylineEllipseSolidAndTrueColor() TypeCode = 0x23, TypeName = "ELLIPSE", Kind = DwgEntityKind.Ellipse, - Geometry = [5.0, 5.0, 0.0, 4.0, 0.0, 0.0, 0.5, 0.0, Math.Tau], + Geometry = [5.0, 5.0, 0.0, 4.0, 0.0, 0.0, 0.5, 0.0, Math.Tau, 0.0, 1.0, 0.0], ColorIndex = 3, }, new DwgEntity @@ -218,6 +218,10 @@ public void SceneSvgAndViewer_RenderPolylineEllipseSolidAndTrueColor() Assert.Equal(SceneTopology.Lines, sceneResult.Document.Geometries[0].Topology); Assert.True(sceneResult.Document.Geometries[0].Vertices.Count > 10); // bulge tessellated Assert.Equal(SceneTopology.Lines, sceneResult.Document.Geometries[1].Topology); + var ellipseVertices = sceneResult.Document.Geometries[1].Vertices; + Assert.All(ellipseVertices, vertex => Assert.Equal(5.0, vertex.Y)); + Assert.Equal(-2.0, ellipseVertices.Min(vertex => vertex.Z), 10); + Assert.Equal(2.0, ellipseVertices.Max(vertex => vertex.Z), 10); Assert.Equal(SceneTopology.Triangles, sceneResult.Document.Geometries[2].Topology); Assert.Equal(new Vector3d(2.0, 2.0, 0.0), sceneResult.Document.Geometries[2].Vertices[2]); @@ -230,11 +234,12 @@ public void SceneSvgAndViewer_RenderPolylineEllipseSolidAndTrueColor() // 2D AutoCAD HTML viewer string htmlPath = Path.Combine(_directory, "entities.html"); - DwgViewerExport.SaveViewer(doc, htmlPath); + 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); }