From c9916eacc6d8cb00c76aeeaf9974cf6adb2ad958 Mon Sep 17 00:00:00 2001 From: mahach666 Date: Wed, 2 Dec 2026 16:09:55 +0300 Subject: [PATCH 1/2] Decode HATCH, DIMENSION, LEADER, ATTRIB/ATTDEF and CAD Unicode text escapes --- src/DwgIO.Cli/Export/DwgViewerExport.cs | 3 - src/DwgIO.Scene.Adapter/DwgSceneReader.cs | 236 +++++++- .../Compatibility/DwgSvgExporter.cs | 76 ++- src/DwgIO/Internal/Parsing/EntityDecoder.cs | 517 ++++++++++++++++++ src/DwgIO/Json/DwgJsonExporter.cs | 58 ++ src/DwgIO/Model/DwgAttribData.cs | 22 + src/DwgIO/Model/DwgDimensionData.cs | 35 ++ src/DwgIO/Model/DwgEntity.cs | 138 ++++- src/DwgIO/Model/DwgHatchData.cs | 46 ++ .../DwgIO.Tests/HatchDimensionAttribTests.cs | 346 ++++++++++++ 10 files changed, 1454 insertions(+), 23 deletions(-) create mode 100644 src/DwgIO/Model/DwgAttribData.cs create mode 100644 src/DwgIO/Model/DwgDimensionData.cs create mode 100644 src/DwgIO/Model/DwgHatchData.cs create mode 100644 tests/DwgIO.Tests/HatchDimensionAttribTests.cs diff --git a/src/DwgIO.Cli/Export/DwgViewerExport.cs b/src/DwgIO.Cli/Export/DwgViewerExport.cs index cdcc506..9ed3f1a 100644 --- a/src/DwgIO.Cli/Export/DwgViewerExport.cs +++ b/src/DwgIO.Cli/Export/DwgViewerExport.cs @@ -99,9 +99,6 @@ private static HtmlViewerOptions BuildHtmlOptions(DwgSceneResult result, DwgView private static bool IsFlat2DScene(SceneDocument scene) { - if (scene.Geometries.Any(g => g.Topology == SceneTopology.Triangles)) - return false; - double minZ = double.PositiveInfinity, maxZ = double.NegativeInfinity; foreach (var geom in scene.Geometries) { diff --git a/src/DwgIO.Scene.Adapter/DwgSceneReader.cs b/src/DwgIO.Scene.Adapter/DwgSceneReader.cs index 5194f5a..09cc5b8 100644 --- a/src/DwgIO.Scene.Adapter/DwgSceneReader.cs +++ b/src/DwgIO.Scene.Adapter/DwgSceneReader.cs @@ -330,6 +330,14 @@ private void FlattenBlock( continue; } + if (entity.Kind == DwgEntityKind.Dimension && entity.BlockHeaderHandle is ulong dimBlockHandle && index.Blocks.ContainsKey(dimBlockHandle)) + { + (int nextAci, uint? nextRgb) = ResolveByBlock(entity, byBlockAci, byBlockRgb); + FlattenBlock(index, dimBlockHandle, transform, scaleToMetres, nextAci, nextRgb, + sheetKey, recordForViewports, depth + 1, visitedBlocks, elementIds); + continue; + } + EmitEntity(index.Document, entity, transform, scaleToMetres, byBlockAci, byBlockRgb, sheetKey, recordForViewports, elementIds); } } @@ -437,12 +445,25 @@ private void EmitEntity( bool recordForViewports, List elementIds) { - if (entity.TypeCode is 0x04 or 0x05 or 0x06 or 0x0A or 0x0B or 0x22) + if (entity.Kind is DwgEntityKind.Block or DwgEntityKind.EndBlk or DwgEntityKind.SeqEnd or DwgEntityKind.Viewport + || entity.TypeCode is 0x04 or 0x05 or 0x06 or 0x0A or 0x0B or 0x22) { return; } - if (entity.Kind is DwgEntityKind.Text or DwgEntityKind.MText && entity.Geometry is { Length: >= 5 } tg) + if (entity.Kind is DwgEntityKind.Attrib or DwgEntityKind.AttDef) + { + bool isVisible = entity.Kind == DwgEntityKind.Attrib + ? entity.Attrib?.IsInvisible != true + : entity.Attrib is { IsConstant: true, IsInvisible: false }; + if (!isVisible) + { + return; + } + } + + if (entity.Kind is DwgEntityKind.Text or DwgEntityKind.MText or DwgEntityKind.Attrib or DwgEntityKind.AttDef + && entity.Geometry is { Length: >= 5 } tg) { string? plain = entity.PlainText; if (string.IsNullOrWhiteSpace(plain)) @@ -503,9 +524,20 @@ private void EmitEntity( DwgEntityKind.Polyline when entity.Geometry is { Length: >= 8 } g => BuildPolyline(g, transform, scale), DwgEntityKind.Polyline3d when entity.Geometry is { Length: >= 7 } g => - BuildPolyline3d(g, transform, scale), + BuildVertexStrip(g, transform, scale, allowClosed: true), DwgEntityKind.Spline when entity.Geometry is { Length: >= 7 } g => - BuildSpline(g, transform, scale), + BuildVertexStrip(g, transform, scale, allowClosed: true), + DwgEntityKind.Leader when entity.Geometry is { Length: >= 7 } g => + BuildVertexStrip(g, transform, scale, allowClosed: false), + DwgEntityKind.Hatch when entity.Hatch is { Loops.Count: > 0 } h => + BuildHatchOutline(h, transform, scale), + DwgEntityKind.Dimension when entity.Dimension is { XLine1Point: { } x1, XLine2Point: { } x2 } => + (SceneTopology.Lines, + [ + transform.Apply(new Vector3d(x1.X, x1.Y, x1.Z)) * scale, + transform.Apply(new Vector3d(x2.X, x2.Y, x2.Z)) * scale, + ], + Array.Empty()), DwgEntityKind.Ellipse when entity.Geometry is { Length: 12 } g => BuildEllipse(g, transform, scale), DwgEntityKind.Solid when entity.Geometry is { Length: 12 } g => @@ -564,6 +596,28 @@ private void EmitEntity( _modelSegments.Add((a, b, instanceColor, entity.LayerName, entity)); } } + + if (entity.Kind == DwgEntityKind.Hatch && entity.Hatch is { IsSolidFill: true, Loops.Count: > 0 } solidHatch) + { + if (BuildHatchSolidFill(solidHatch, transform, scale) is { } fill && fill.vertices.All(IsFinite)) + { + _geometryId++; + var fillGeom = new SceneGeometry + { + Id = _geometryId, + Topology = fill.topology, + Vertices = fill.vertices, + Indices = fill.indices, + }; + Scene.Geometries.Add(fillGeom); + Scene.Instances.Add(new SceneInstance + { + ElementId = element.Id, + GeometryId = fillGeom.Id, + Color = instanceColor, + }); + } + } } private void EmitViewportContent(DwgViewportData vp, string sheetKey, List sheetElementIds) @@ -851,7 +905,7 @@ private static int MapAttachment(DwgEntity entity, double[] g) return Math.Clamp((int)Math.Round(g[6]), 1, 9); } - if (entity.Kind == DwgEntityKind.Text && g.Length >= 9) + if (entity.Kind is DwgEntityKind.Text or DwgEntityKind.Attrib or DwgEntityKind.AttDef && g.Length >= 9) { int h = (int)Math.Round(g[7]); // 0=L,1=C,2=R int v = (int)Math.Round(g[8]); // 0=Base,1=B,2=M,3=T @@ -972,12 +1026,13 @@ private static (SceneTopology, Vector3d[], IReadOnlyList)? BuildPolyline(do return vertices.Count >= 2 ? (SceneTopology.Lines, vertices.ToArray(), indices) : null; } - private static (SceneTopology, Vector3d[], IReadOnlyList)? BuildPolyline3d(double[] g, Affine3d t, double scale) + private static (SceneTopology, Vector3d[], IReadOnlyList)? BuildVertexStrip( + double[] g, Affine3d t, double scale, bool allowClosed) { int count = (g.Length - 1) / 3; if (count < 2) return null; - bool closed = g[0] != 0.0; + bool closed = allowClosed && g[0] != 0.0; var vertices = new Vector3d[count]; for (int i = 0; i < count; i++) { @@ -987,19 +1042,170 @@ private static (SceneTopology, Vector3d[], IReadOnlyList)? BuildPolyline3d( return (SceneTopology.Lines, vertices, SharedIndices(count, closed)); } - private static (SceneTopology, Vector3d[], IReadOnlyList)? BuildSpline(double[] g, Affine3d t, double scale) + private static Vector3d LiftHatchPoint(DwgPoint2D pt, double elevation, Vector3d ax, Vector3d ay, Vector3d az, Affine3d t, double scale) { - int count = (g.Length - 1) / 3; - if (count < 2) return null; + var wcs = ax * pt.X + ay * pt.Y + az * elevation; + return t.Apply(wcs) * scale; + } - bool closed = g[0] != 0.0; - var vertices = new Vector3d[count]; - for (int i = 0; i < count; i++) + private static (SceneTopology, Vector3d[], IReadOnlyList)? BuildHatchOutline(DwgHatchData hatch, Affine3d t, double scale) + { + var (ax, ay, az) = ArbitraryAxisBasis(new Vector3d(hatch.Extrusion.X, hatch.Extrusion.Y, hatch.Extrusion.Z), 0); + var vertices = new List(); + var indices = new List(); + foreach (var loop in hatch.Loops) { - vertices[i] = t.Apply(new Vector3d(g[1 + i * 3], g[1 + i * 3 + 1], g[1 + i * 3 + 2])) * scale; + if (loop.Points.Count < 2) continue; + + int first = vertices.Count; + foreach (var p in loop.Points) + { + vertices.Add(LiftHatchPoint(p, hatch.Elevation, ax, ay, az, t, scale)); + } + + int segs = loop.IsClosed ? loop.Points.Count : loop.Points.Count - 1; + for (int i = 0; i < segs; i++) + { + indices.Add(first + i); + indices.Add(first + ((i + 1) % loop.Points.Count)); + } } - return (SceneTopology.Lines, vertices, SharedIndices(count, closed)); + return indices.Count >= 2 ? (SceneTopology.Lines, vertices.ToArray(), indices) : null; + } + + private static (SceneTopology topology, Vector3d[] vertices, IReadOnlyList indices)? BuildHatchSolidFill( + DwgHatchData hatch, Affine3d t, double scale) + { + // Triangulate simple outer/default boundary loops cleanly via 2D ear-clipping. + var (ax, ay, az) = ArbitraryAxisBasis(new Vector3d(hatch.Extrusion.X, hatch.Extrusion.Y, hatch.Extrusion.Z), 0); + var vertices = new List(); + var indices = new List(); + + var worldNormal = t.ApplyVector(az); + double normalLen = worldNormal.Length; + var offset = (normalLen > 1e-12 ? worldNormal / normalLen : Vector3d.UnitZ) * 0.0005; + + foreach (var loop in hatch.Loops) + { + if (loop.Points.Count < 3) continue; + var poly = CleanPolygon2D(loop.Points); + if (poly.Count < 3) continue; + + var tris = EarClip2D(poly); + if (tris.Count < 3) continue; + + int baseIdx = vertices.Count; + foreach (var p in poly) + { + // Offset solid fill slightly behind coplanar CAD linework/furniture to prevent WebGL depth-fighting. + vertices.Add(LiftHatchPoint(p, hatch.Elevation, ax, ay, az, t, scale) - offset); + } + + foreach (int ti in tris) + { + indices.Add(baseIdx + ti); + } + } + + return indices.Count >= 3 ? (SceneTopology.Triangles, vertices.ToArray(), indices) : null; + } + + private static List CleanPolygon2D(IReadOnlyList pts) + { + var result = new List(pts.Count); + foreach (var p in pts) + { + if (result.Count == 0 || Math.Abs(result[^1].X - p.X) > 1e-9 || Math.Abs(result[^1].Y - p.Y) > 1e-9) + { + result.Add(p); + } + } + + if (result.Count > 1 && Math.Abs(result[^1].X - result[0].X) <= 1e-9 && Math.Abs(result[^1].Y - result[0].Y) <= 1e-9) + { + result.RemoveAt(result.Count - 1); + } + + return result; + } + + private static List EarClip2D(List poly) + { + int n = poly.Count; + var indices = new List((n - 2) * 3); + if (n < 3) return indices; + + double area2 = 0; + for (int i = 0; i < n; i++) + { + var a = poly[i]; + var b = poly[(i + 1) % n]; + area2 += a.X * b.Y - b.X * a.Y; + } + + if (Math.Abs(area2) <= 1e-12) return indices; + + var rem = new List(n); + if (area2 > 0) + { + for (int i = 0; i < n; i++) rem.Add(i); + } + else + { + for (int i = n - 1; i >= 0; i--) rem.Add(i); + } + + int guard = rem.Count * rem.Count + 4; + while (rem.Count > 2 && guard-- > 0) + { + bool clipped = false; + for (int i = 0; i < rem.Count; i++) + { + int prev = rem[(i - 1 + rem.Count) % rem.Count]; + int curr = rem[i]; + int next = rem[(i + 1) % rem.Count]; + var a = poly[prev]; + var b = poly[curr]; + var c = poly[next]; + + double cross = (b.X - a.X) * (c.Y - a.Y) - (b.Y - a.Y) * (c.X - a.X); + if (cross <= 1e-12) continue; + + bool containsOther = false; + for (int j = 0; j < rem.Count; j++) + { + int vi = rem[j]; + if (vi == prev || vi == curr || vi == next) continue; + if (PointInTriangle(poly[vi], a, b, c)) + { + containsOther = true; + break; + } + } + + if (containsOther) continue; + + indices.Add(prev); + indices.Add(curr); + indices.Add(next); + rem.RemoveAt(i); + clipped = true; + break; + } + + if (!clipped) break; + } + + return indices; + } + + private static bool PointInTriangle(DwgPoint2D p, DwgPoint2D a, DwgPoint2D b, DwgPoint2D c) + { + double c1 = (b.X - a.X) * (p.Y - a.Y) - (b.Y - a.Y) * (p.X - a.X); + double c2 = (c.X - b.X) * (p.Y - b.Y) - (c.Y - b.Y) * (p.X - b.X); + double c3 = (a.X - c.X) * (p.Y - c.Y) - (a.Y - c.Y) * (p.X - c.X); + return c1 >= -1e-12 && c2 >= -1e-12 && c3 >= -1e-12; } private static void AppendBulgeSegments( diff --git a/src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs b/src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs index 3a35be3..1613d6e 100644 --- a/src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs +++ b/src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs @@ -300,7 +300,8 @@ private static List Collect(DwgDocument document, DwgSvgOptions option } break; - case (DwgEntityKind.Text or DwgEntityKind.MText, { Length: >= 5 } g): + case (DwgEntityKind.Text or DwgEntityKind.MText or DwgEntityKind.Attrib, { Length: >= 5 } g) + when entity.Kind != DwgEntityKind.Attrib || entity.Attrib?.IsInvisible != true: if (IsUsable(g[0] * scale, g[1] * scale, g[3] * scale, g[4]) && g[3] > 0 && entity.PlainText is { Length: > 0 } plain) { var (column, row) = TextPlacement.Alignment(entity.Kind, g); @@ -316,6 +317,20 @@ private static List Collect(DwgDocument document, DwgSvgOptions option entity.EffectiveTrueColorRgb)); } + break; + case (DwgEntityKind.Polyline3d or DwgEntityKind.Spline or DwgEntityKind.Leader, { Length: >= 7 } g): + if (TryBuildVertexStrip(g, scale, entity, allowClosed: entity.Kind != DwgEntityKind.Leader, out var strip)) + { + shapes.Add(strip); + } + + break; + case (DwgEntityKind.Hatch, _) when entity.Hatch is { Loops.Count: > 0 } hatch: + if (TryBuildHatch(hatch, scale, entity, out var hatchPath)) + { + shapes.Add(hatchPath); + } + break; } } @@ -323,6 +338,65 @@ private static List Collect(DwgDocument document, DwgSvgOptions option return shapes; } + private static bool TryBuildVertexStrip(double[] g, double scale, DwgEntity entity, bool allowClosed, out SvgPath path) + { + int count = (g.Length - 1) / 3; + if (count < 2 || !IsUsable(g)) + { + path = null!; + return false; + } + + bool closed = allowClosed && g[0] != 0.0; + var sb = new System.Text.StringBuilder(); + var bounds = new List<(double X, double Y)>(count); + for (int i = 0; i < count; i++) + { + double x = g[1 + i * 3] * scale; + double y = -g[1 + i * 3 + 1] * scale; + bounds.Add((x, y)); + sb.Append(FormattableString.Invariant($"{(i == 0 ? 'M' : 'L')} {Num(x)} {Num(y)} ")); + } + + if (closed) sb.Append('Z'); + path = new SvgPath(sb.ToString().TrimEnd(), bounds, false, entity.EffectiveColorIndex, entity.EffectiveTrueColorRgb); + return true; + } + + private static bool TryBuildHatch(DwgHatchData hatch, double scale, DwgEntity entity, out SvgPath path) + { + var sb = new System.Text.StringBuilder(); + var bounds = new List<(double X, double Y)>(); + foreach (var loop in hatch.Loops) + { + if (loop.Points.Count < 2) continue; + for (int i = 0; i < loop.Points.Count; i++) + { + double x = loop.Points[i].X * scale; + double y = -loop.Points[i].Y * scale; + if (!IsUsable(x, y)) + { + path = null!; + return false; + } + + bounds.Add((x, y)); + sb.Append(FormattableString.Invariant($"{(i == 0 ? 'M' : 'L')} {Num(x)} {Num(y)} ")); + } + + if (loop.IsClosed) sb.Append("Z "); + } + + if (bounds.Count < 2) + { + path = null!; + return false; + } + + path = new SvgPath(sb.ToString().TrimEnd(), bounds, hatch.IsSolidFill, entity.EffectiveColorIndex, entity.EffectiveTrueColorRgb); + return true; + } + private static bool TryBuildPolyline(double[] g, double scale, DwgEntity entity, out SvgPath path) { int count = (g.Length - 2) / 3; diff --git a/src/DwgIO/Internal/Parsing/EntityDecoder.cs b/src/DwgIO/Internal/Parsing/EntityDecoder.cs index 618c4ce..cf5c339 100644 --- a/src/DwgIO/Internal/Parsing/EntityDecoder.cs +++ b/src/DwgIO/Internal/Parsing/EntityDecoder.cs @@ -109,9 +109,17 @@ RecordStringStream GetStrings() => reader.ReadRawByte(); // lineweight (R2000+) DwgViewportData? viewportData = null; + DwgAttribData? attribData = null; + DwgDimensionData? dimensionData = null; + DwgHatchData? hatchData = null; (DwgEntityKind kind, double[]? geometry, string? text)? body = info.TypeCode switch { 0x01 => DecodeText(reader, GetStrings(), year), + 0x02 => DecodeAttribOrAttDef(reader, GetStrings(), year, isAttDef: false, out attribData), + 0x03 => DecodeAttribOrAttDef(reader, GetStrings(), year, isAttDef: true, out attribData), + 0x04 => (DwgEntityKind.Block, null, null), + 0x05 => (DwgEntityKind.EndBlk, null, null), + 0x06 => (DwgEntityKind.SeqEnd, null, null), 0x07 => WithNoText(DecodeInsert(reader, year, isMInsert: false)), 0x08 => WithNoText(DecodeInsert(reader, year, isMInsert: true)), 0x0A => WithNoText(DecodeVertex2d(reader, year)), @@ -121,6 +129,7 @@ RecordStringStream GetStrings() => 0x11 => WithNoText(DecodeArc(reader)), 0x12 => WithNoText(DecodeCircle(reader)), 0x13 => WithNoText(DecodeLine(reader)), + >= 0x14 and <= 0x1A => DecodeDimension(reader, GetStrings(), info.TypeCode, year, out dimensionData), 0x1B => WithNoText(DecodePoint(reader)), 0x1C => WithNoText(DecodeFace3d(reader)), 0x1F or 0x20 => WithNoText(DecodeSolidOrTrace(reader)), @@ -129,7 +138,9 @@ RecordStringStream GetStrings() => 0x24 => WithNoText(DecodeSpline(reader, year)), 0x28 or 0x29 => WithNoText(DecodeRayOrXLine(reader, info.TypeCode == 0x28 ? DwgEntityKind.Ray : DwgEntityKind.XLine)), 0x2C => DecodeMText(reader, GetStrings(), year), + 0x2D => WithNoText(DecodeLeader(reader)), 0x4D => WithNoText(DecodeLwPolyline(reader, year)), + 0x4E => DecodeHatch(reader, GetStrings(), year, out hatchData), _ => null, }; @@ -167,6 +178,9 @@ RecordStringStream GetStrings() => OwnerHandle = ownerHandle, BlockHeaderHandle = blockHeaderHandle, Viewport = viewportData, + Attrib = attribData, + Dimension = dimensionData, + Hatch = hatchData, LayerHandle = layerHandle, LayerName = layer?.Name, LayerColorIndex = layer?.ColorIndex, @@ -296,6 +310,15 @@ private static (ulong? OwnerHandle, ulong? LayerHandle, ulong? BlockHeaderHandle ulong resolvedBlock = reader.ReadHandle().ResolveTarget(info.Handle); blockHeaderHandle = resolvedBlock == 0 ? null : resolvedBlock; } + else if (info.TypeCode is >= 0x14 and <= 0x1A && reader.RemainingBits >= 8) + { + _ = reader.ReadHandle(); // dimstyle handle + if (reader.RemainingBits >= 8) + { + ulong resolvedBlock = reader.ReadHandle().ResolveTarget(info.Handle); + blockHeaderHandle = resolvedBlock == 0 ? null : resolvedBlock; + } + } return (ownerHandle, layerHandle, blockHeaderHandle); } @@ -865,4 +888,498 @@ private static (DwgEntityKind, double[]) DecodeSpline(BitReaderMsb reader, int y return (DwgEntityKind.Spline, payload); } + + private static DwgPoint3D ReadPackedPoint3d(BitReaderMsb reader) => + new(reader.ReadPackedDouble(), reader.ReadPackedDouble(), reader.ReadPackedDouble()); + + private static void SkipCmColor(BitReaderMsb reader, RecordStringStream strings, int year, string owner) + { + uint colorValue = reader.ReadPackedShort(); + uint colorFlags = colorValue >> 8; + if ((colorFlags & 0x40) == 0 && (colorFlags & 0x80) != 0) + { + _ = reader.ReadPackedInt(); + } + + if ((colorFlags & 0x20) != 0) + { + _ = reader.ReadPackedInt(); + } + + if ((colorFlags & 0x41) == 0x41) + { + _ = strings.Read(reader, owner, year); + } + + if ((colorFlags & 0x42) == 0x42) + { + _ = strings.Read(reader, owner, year); + } + } + + private static (DwgEntityKind, double[], string) DecodeAttribOrAttDef( + BitReaderMsb reader, + RecordStringStream strings, + int year, + bool isAttDef, + out DwgAttribData attrib) + { + (_, double[] geometry, string text) = DecodeText(reader, strings, year); + if (year >= 2010) + { + _ = reader.ReadRawByte(); // version / is_locked_in_block + } + + if (year >= 2018) + { + byte mtextType = reader.ReadRawByte(); + if (mtextType > 1 && reader.RemainingBits > 64) + { + (_, _, string embedded) = DecodeMText(reader, strings, year); + if (string.IsNullOrEmpty(text)) + { + text = embedded; + } + } + } + + string tag = strings.Read(reader, isAttDef ? "ATTDEF.tag" : "ATTRIB.tag", year); + _ = reader.ReadPackedShort(); // field_length + byte flags = reader.ReadRawByte(); + if (year >= 2007) + { + _ = reader.ReadBit(); // lock_position_flag + } + + string? prompt = isAttDef ? strings.Read(reader, "ATTDEF.prompt", year) : null; + attrib = new DwgAttribData + { + Tag = tag, + Prompt = prompt, + Flags = flags, + }; + return (isAttDef ? DwgEntityKind.AttDef : DwgEntityKind.Attrib, geometry, text); + } + + private static (DwgEntityKind, double[]?, string?) DecodeDimension( + BitReaderMsb reader, + RecordStringStream strings, + ushort typeCode, + int year, + out DwgDimensionData data) + { + if (year >= 2010) + { + _ = reader.ReadRawByte(); // class_version + } + + var extrusion = ReadPackedPoint3d(reader); + double textMidX = reader.ReadRawDouble(); + double textMidY = reader.ReadRawDouble(); + double elevation = reader.ReadPackedDouble(); + byte flags = reader.ReadRawByte(); + string userText = strings.Read(reader, "DIMENSION.userText", year); + _ = reader.ReadPackedDouble(); // text_rotation + _ = reader.ReadPackedDouble(); // horiz_dir + _ = ReadPackedPoint3d(reader); // ins_scale + _ = reader.ReadPackedDouble(); // ins_rotation + + double measurement = 0; + if (year >= 2000) + { + _ = reader.ReadPackedShort(); // attachment + _ = reader.ReadPackedShort(); // lspace_style + _ = reader.ReadPackedDouble(); // lspace_factor + measurement = reader.ReadPackedDouble(); // actual_measurement + } + + if (year >= 2007) + { + _ = reader.ReadBit(); // unknown + _ = reader.ReadBit(); // flip_arrow1 + _ = reader.ReadBit(); // flip_arrow2 + } + + _ = reader.ReadRawDouble(); + _ = reader.ReadRawDouble(); // clone_ins_pt + + var defPt = default(DwgPoint3D); + DwgPoint3D? xline1 = null; + DwgPoint3D? xline2 = null; + switch (typeCode) + { + case 0x14: // DIMENSION_ORDINATE + defPt = ReadPackedPoint3d(reader); + xline1 = ReadPackedPoint3d(reader); + xline2 = ReadPackedPoint3d(reader); + _ = reader.ReadRawByte(); + break; + case 0x15: // DIMENSION_LINEAR + xline1 = ReadPackedPoint3d(reader); + xline2 = ReadPackedPoint3d(reader); + defPt = ReadPackedPoint3d(reader); + _ = reader.ReadPackedDouble(); // oblique_angle + _ = reader.ReadPackedDouble(); // dim_rotation + break; + case 0x16: // DIMENSION_ALIGNED + xline1 = ReadPackedPoint3d(reader); + xline2 = ReadPackedPoint3d(reader); + defPt = ReadPackedPoint3d(reader); + _ = reader.ReadPackedDouble(); // oblique_angle + break; + case 0x17: // DIMENSION_ANG3PT + defPt = ReadPackedPoint3d(reader); + xline1 = ReadPackedPoint3d(reader); + xline2 = ReadPackedPoint3d(reader); + _ = ReadPackedPoint3d(reader); // center_pt + break; + case 0x18: // DIMENSION_ANG2LN + _ = reader.ReadRawDouble(); + _ = reader.ReadRawDouble(); // xline2end + xline1 = ReadPackedPoint3d(reader); + xline2 = ReadPackedPoint3d(reader); + _ = ReadPackedPoint3d(reader); // xline2start + defPt = ReadPackedPoint3d(reader); + break; + case 0x19: // DIMENSION_RADIUS + defPt = ReadPackedPoint3d(reader); + xline1 = ReadPackedPoint3d(reader); + _ = reader.ReadPackedDouble(); // leader_len + break; + case 0x1A: // DIMENSION_DIAMETER + xline1 = ReadPackedPoint3d(reader); + defPt = ReadPackedPoint3d(reader); + _ = reader.ReadPackedDouble(); // leader_len + break; + } + + data = new DwgDimensionData + { + UserText = userText, + ActualMeasurement = measurement, + TextMidPoint = new DwgPoint2D(textMidX, textMidY), + Elevation = elevation, + Extrusion = extrusion, + DefinitionPoint = defPt, + XLine1Point = xline1, + XLine2Point = xline2, + Flags = flags, + }; + return (DwgEntityKind.Dimension, null, string.IsNullOrEmpty(userText) ? null : userText); + } + + private static (DwgEntityKind, double[]) DecodeLeader(BitReaderMsb reader) + { + _ = reader.ReadBit(); // unknown_bit_1 + _ = reader.ReadPackedShort(); // annot_type + uint pathType = reader.ReadPackedShort(); + uint numPoints = reader.ReadPackedInt(); + if (numPoints > MaxPolylineVertices) + { + throw new DwgException($"LEADER vertex count ({numPoints}) exceeds safety cap."); + } + + var payload = new double[1 + (int)numPoints * 3]; + payload[0] = pathType; + for (int i = 0; i < (int)numPoints; i++) + { + int o = 1 + i * 3; + payload[o] = reader.ReadPackedDouble(); + payload[o + 1] = reader.ReadPackedDouble(); + payload[o + 2] = reader.ReadPackedDouble(); + } + + return (DwgEntityKind.Leader, payload); + } + + private static (DwgEntityKind, double[]?, string?) DecodeHatch( + BitReaderMsb reader, + RecordStringStream strings, + int year, + out DwgHatchData hatch) + { + if (year >= 2004) + { + uint isGradient = reader.ReadPackedInt(); + _ = reader.ReadPackedInt(); // reserved + _ = reader.ReadPackedDouble(); // gradient_angle + _ = reader.ReadPackedDouble(); // gradient_shift + _ = reader.ReadPackedInt(); // single_color_gradient + _ = reader.ReadPackedDouble(); // gradient_tint + uint numColors = reader.ReadPackedInt(); + if (isGradient != 0 && numColors > 1000) + { + throw new DwgException($"HATCH gradient color count ({numColors}) exceeds safety cap."); + } + + for (uint c = 0; c < numColors && c <= 1000; c++) + { + _ = reader.ReadPackedDouble(); + SkipCmColor(reader, strings, year, "HATCH.gradientColor"); + } + + _ = strings.Read(reader, "HATCH.gradientName", year); + } + + double elevation = reader.ReadPackedDouble(); + var extrusion = ReadPackedPoint3d(reader); + string patternName = strings.Read(reader, "HATCH.name", year); + bool isSolidFill = reader.ReadBit(); + bool isAssociative = reader.ReadBit(); + uint numPaths = reader.ReadPackedInt(); + if (numPaths > 10_000) + { + throw new DwgException($"HATCH path count ({numPaths}) exceeds safety cap."); + } + + var loops = new List((int)numPaths); + for (uint p = 0; p < numPaths; p++) + { + uint pathFlag = reader.ReadPackedInt(); + var pts = new List(); + bool isClosed = true; + + if ((pathFlag & 2) == 0) + { + uint numEdges = reader.ReadPackedInt(); + if (numEdges > 100_000) + { + throw new DwgException($"HATCH boundary edge count ({numEdges}) exceeds safety cap."); + } + + for (uint e = 0; e < numEdges; e++) + { + byte curveType = reader.ReadRawByte(); + switch (curveType) + { + case 1: // LINE + AddEdgePoint(pts, new DwgPoint2D(reader.ReadRawDouble(), reader.ReadRawDouble())); + AddEdgePoint(pts, new DwgPoint2D(reader.ReadRawDouble(), reader.ReadRawDouble())); + break; + case 2: // CIRCULAR ARC + { + double cx = reader.ReadRawDouble(); + double cy = reader.ReadRawDouble(); + double r = reader.ReadPackedDouble(); + double start = reader.ReadPackedDouble(); + double end = reader.ReadPackedDouble(); + bool ccw = reader.ReadBit(); + AppendHatchCircularArc(pts, cx, cy, r, start, end, ccw); + break; + } + case 3: // ELLIPTICAL ARC + { + double cx = reader.ReadRawDouble(); + double cy = reader.ReadRawDouble(); + double mx = reader.ReadRawDouble(); + double my = reader.ReadRawDouble(); + double ratio = reader.ReadPackedDouble(); + double start = reader.ReadPackedDouble(); + double end = reader.ReadPackedDouble(); + bool ccw = reader.ReadBit(); + AppendHatchEllipticArc(pts, cx, cy, mx, my, ratio, start, end, ccw); + break; + } + case 4: // SPLINE + { + int degree = (int)reader.ReadPackedInt(); + bool isRational = reader.ReadBit(); + _ = reader.ReadBit(); // periodic + uint numKnots = reader.ReadPackedInt(); + uint numCtrl = reader.ReadPackedInt(); + if (numKnots > MaxPolylineVertices || numCtrl > MaxPolylineVertices) + { + throw new DwgException($"HATCH spline count ({numCtrl}) exceeds safety cap."); + } + + var knots = new double[numKnots]; + for (uint k = 0; k < numKnots; k++) + { + knots[k] = reader.ReadPackedDouble(); + } + + var ctrls = new (double X, double Y, double Z, double W)[numCtrl]; + for (uint c = 0; c < numCtrl; c++) + { + double x = reader.ReadRawDouble(); + double y = reader.ReadRawDouble(); + double w = isRational ? reader.ReadPackedDouble() : 1.0; + ctrls[c] = (x, y, 0, w); + } + + if (year >= 2010) + { + uint numFit = reader.ReadPackedInt(); + for (uint f = 0; f < numFit && f < MaxPolylineVertices; f++) + { + _ = reader.ReadRawDouble(); + _ = reader.ReadRawDouble(); + } + + if (numFit > 0) + { + for (int t = 0; t < 4; t++) + { + _ = reader.ReadRawDouble(); + } + } + } + + foreach (var sp in SplineEvaluator.Evaluate(degree, knots, ctrls, closed: false)) + { + AddEdgePoint(pts, new DwgPoint2D(sp.X, sp.Y)); + } + + break; + } + } + } + } + else + { + bool hasBulges = reader.ReadBit(); + isClosed = reader.ReadBit(); + uint numVerts = reader.ReadPackedInt(); + if (numVerts > MaxPolylineVertices) + { + throw new DwgException($"HATCH polyline vertex count ({numVerts}) exceeds safety cap."); + } + + var raw = new (double X, double Y, double Bulge)[numVerts]; + for (uint v = 0; v < numVerts; v++) + { + double x = reader.ReadRawDouble(); + double y = reader.ReadRawDouble(); + double b = hasBulges ? reader.ReadPackedDouble() : 0.0; + raw[v] = (x, y, b); + } + + int segs = isClosed ? (int)numVerts : Math.Max(0, (int)numVerts - 1); + for (int i = 0; i < segs; i++) + { + var a = raw[i]; + var b = raw[(i + 1) % (int)numVerts]; + AddEdgePoint(pts, new DwgPoint2D(a.X, a.Y)); + if (Math.Abs(a.Bulge) >= 1e-9) + { + AppendHatchBulge(pts, a.X, a.Y, b.X, b.Y, a.Bulge); + } + } + + if (!isClosed && raw.Length > 0) + { + AddEdgePoint(pts, new DwgPoint2D(raw[^1].X, raw[^1].Y)); + } + } + + _ = reader.ReadPackedInt(); // num_boundary_handles (in handle stream) + if (pts.Count >= 2) + { + loops.Add(new DwgHatchLoop { Flags = pathFlag, IsClosed = isClosed, Points = pts }); + } + } + + _ = reader.ReadPackedShort(); // style + _ = reader.ReadPackedShort(); // pattern_type + double angle = 0; + double scaleSpacing = 1.0; + if (!isSolidFill) + { + angle = reader.ReadPackedDouble(); + scaleSpacing = reader.ReadPackedDouble(); + } + + hatch = new DwgHatchData + { + PatternName = string.IsNullOrEmpty(patternName) && isSolidFill ? "SOLID" : patternName, + IsSolidFill = isSolidFill, + IsAssociative = isAssociative, + Elevation = elevation, + Extrusion = extrusion, + AngleRadians = angle, + ScaleSpacing = scaleSpacing, + Loops = loops, + }; + return (DwgEntityKind.Hatch, null, null); + } + + private static void AddEdgePoint(List pts, DwgPoint2D pt) + { + if (pts.Count == 0 || Math.Abs(pts[^1].X - pt.X) > 1e-9 || Math.Abs(pts[^1].Y - pt.Y) > 1e-9) + { + pts.Add(pt); + } + } + + private static void AppendHatchCircularArc( + List pts, + double cx, + double cy, + double radius, + double start, + double end, + bool ccw) + { + double a0 = ccw ? start : (Math.Tau - start); + double a1 = ccw ? end : (Math.Tau - end); + double span = ccw ? (a1 - a0) : (a0 - a1); + while (span <= 0) span += Math.Tau; + while (span > Math.Tau + 1e-9) span -= Math.Tau; + int steps = Math.Clamp((int)Math.Ceiling(span / (Math.PI / 18)), 4, 128); + for (int i = 0; i <= steps; i++) + { + double a = ccw ? a0 + span * i / steps : a0 - span * i / steps; + AddEdgePoint(pts, new DwgPoint2D(cx + radius * Math.Cos(a), cy + radius * Math.Sin(a))); + } + } + + private static void AppendHatchEllipticArc( + List pts, + double cx, + double cy, + double mx, + double my, + double ratio, + double start, + double end, + bool ccw) + { + double nx = -my * ratio, ny = mx * ratio; + double span = ccw ? (end - start) : (start - end); + while (span <= 0) span += Math.Tau; + while (span > Math.Tau + 1e-9) span -= Math.Tau; + int steps = Math.Clamp((int)Math.Ceiling(span / (Math.PI / 18)), 6, 128); + for (int i = 0; i <= steps; i++) + { + double t = ccw ? start + span * i / steps : start - span * i / steps; + double c = Math.Cos(t), s = Math.Sin(t); + AddEdgePoint(pts, new DwgPoint2D(cx + mx * c + nx * s, cy + my * c + ny * s)); + } + } + + private static void AppendHatchBulge( + List pts, + double x1, + double y1, + double x2, + double y2, + double bulge) + { + double dx = x2 - x1, dy = y2 - y1; + double chord = double.Hypot(dx, dy); + if (chord <= 1e-12) 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 a0 = Math.Atan2(y1 - cy, x1 - cx); + int steps = Math.Clamp((int)Math.Ceiling(Math.Abs(theta) / (Math.PI / 18)), 2, 64); + for (int s = 1; s < steps; s++) + { + double a = a0 + theta * s / steps; + AddEdgePoint(pts, new DwgPoint2D(cx + radius * Math.Cos(a), cy + radius * Math.Sin(a))); + } + } } diff --git a/src/DwgIO/Json/DwgJsonExporter.cs b/src/DwgIO/Json/DwgJsonExporter.cs index 26490ec..f0c1806 100644 --- a/src/DwgIO/Json/DwgJsonExporter.cs +++ b/src/DwgIO/Json/DwgJsonExporter.cs @@ -329,6 +329,64 @@ public static void Write(DwgDocument document, Stream output, DwgJsonExportOptio } } + if (entity.Attrib is { } attrib) + { + writer.WriteStartObject("attrib"); + writer.WriteString("tag", attrib.Tag); + if (!string.IsNullOrEmpty(attrib.Prompt)) + { + writer.WriteString("prompt", attrib.Prompt); + } + + writer.WriteNumber("flags", attrib.Flags); + writer.WriteEndObject(); + } + + if (entity.Dimension is { } dim) + { + writer.WriteStartObject("dimension"); + if (!string.IsNullOrEmpty(dim.UserText)) + { + writer.WriteString("userText", dim.UserText); + } + + writer.WriteNumber("actualMeasurement", double.IsFinite(dim.ActualMeasurement) ? Math.Round(dim.ActualMeasurement, 6) : 0); + writer.WriteStartArray("textMidPoint"); + WriteFiniteNumber(writer, dim.TextMidPoint.X); + WriteFiniteNumber(writer, dim.TextMidPoint.Y); + writer.WriteEndArray(); + writer.WriteStartArray("definitionPoint"); + WriteFiniteNumber(writer, dim.DefinitionPoint.X); + WriteFiniteNumber(writer, dim.DefinitionPoint.Y); + WriteFiniteNumber(writer, dim.DefinitionPoint.Z); + writer.WriteEndArray(); + writer.WriteNumber("flags", dim.Flags); + writer.WriteEndObject(); + } + + if (entity.Hatch is { } hatch) + { + writer.WriteStartObject("hatch"); + writer.WriteString("patternName", hatch.PatternName); + writer.WriteBoolean("isSolidFill", hatch.IsSolidFill); + writer.WriteBoolean("isAssociative", hatch.IsAssociative); + writer.WriteNumber("elevation", double.IsFinite(hatch.Elevation) ? Math.Round(hatch.Elevation, 6) : 0); + writer.WriteNumber("loopCount", hatch.Loops.Count); + writer.WriteEndObject(); + } + + static void WriteFiniteNumber(Utf8JsonWriter w, double value) + { + if (double.IsFinite(value)) + { + w.WriteNumberValue(Math.Round(value, 6)); + } + else + { + w.WriteNullValue(); + } + } + writer.WriteEndObject(); } diff --git a/src/DwgIO/Model/DwgAttribData.cs b/src/DwgIO/Model/DwgAttribData.cs new file mode 100644 index 0000000..38ff7d7 --- /dev/null +++ b/src/DwgIO/Model/DwgAttribData.cs @@ -0,0 +1,22 @@ +namespace DwgIO.Model; + +/// +/// Metadata carried by an ATTRIB (0x02) or ATTDEF (0x03) attribute entity. +/// +public sealed class DwgAttribData +{ + /// Attribute tag name (DXF group 2). + public string Tag { get; init; } = string.Empty; + + /// Optional attribute prompt string (populated on ATTDEF, DXF group 3). + public string? Prompt { get; init; } + + /// Raw AutoCAD attribute flags (1 = invisible, 2 = constant, 4 = verify, 8 = preset). + public int Flags { get; init; } + + /// True when the attribute is marked invisible (DXF 70 bit 1). + public bool IsInvisible => (Flags & 1) != 0; + + /// True when the attribute is constant (DXF 70 bit 2). + public bool IsConstant => (Flags & 2) != 0; +} diff --git a/src/DwgIO/Model/DwgDimensionData.cs b/src/DwgIO/Model/DwgDimensionData.cs new file mode 100644 index 0000000..bebe7c1 --- /dev/null +++ b/src/DwgIO/Model/DwgDimensionData.cs @@ -0,0 +1,35 @@ +namespace DwgIO.Model; + +/// +/// Decoded metadata and definition points of a DIMENSION_* entity (0x14–0x1A). +/// Its rendered geometry block (*D...) is referenced via . +/// +public sealed class DwgDimensionData +{ + /// Explicit user override text (DXF group 1, empty or <> uses automatic measurement). + public string UserText { get; init; } = string.Empty; + + /// Computed measurement stored on the dimension (DXF group 42). + public double ActualMeasurement { get; init; } + + /// 2D text midpoint (DXF group 11) in OCS coordinates. + public DwgPoint2D TextMidPoint { get; init; } + + /// Elevation along the extrusion normal (DXF group 31). + public double Elevation { get; init; } + + /// Extrusion normal vector (DXF group 210). + public DwgPoint3D Extrusion { get; init; } = new(0, 0, 1); + + /// Primary definition point (DXF group 10). + public DwgPoint3D DefinitionPoint { get; init; } + + /// Optional first extension-line origin (DXF group 13, populated for linear/aligned/angular dimensions). + public DwgPoint3D? XLine1Point { get; init; } + + /// Optional second extension-line origin (DXF group 14, populated for linear/aligned/angular dimensions). + public DwgPoint3D? XLine2Point { get; init; } + + /// Raw dimension flags byte. + public int Flags { get; init; } +} diff --git a/src/DwgIO/Model/DwgEntity.cs b/src/DwgIO/Model/DwgEntity.cs index ee027d2..23fa0d5 100644 --- a/src/DwgIO/Model/DwgEntity.cs +++ b/src/DwgIO/Model/DwgEntity.cs @@ -55,6 +55,30 @@ public enum DwgEntityKind /// VIEWPORT: Paper Space viewport window into Model Space. Viewport, + + /// ATTRIB: attribute instance attached to a block insertion. + Attrib, + + /// ATTDEF: attribute definition template inside a block definition. + AttDef, + + /// DIMENSION_*: associative dimension with measurement, definition points and *D block. + Dimension, + + /// LEADER: leader annotation line path. + Leader, + + /// HATCH: associative boundary loops and pattern/solid fill. + Hatch, + + /// BLOCK: block definition header marker. + Block, + + /// ENDBLK: block definition end marker. + EndBlk, + + /// SEQEND: end-of-subentities sequence marker. + SeqEnd, } /// @@ -105,6 +129,15 @@ public sealed class DwgEntity /// Decoded Paper Space viewport portal data when the entity is a VIEWPORT. public DwgViewportData? Viewport { get; init; } + /// Decoded attribute metadata when the entity is an ATTRIB or ATTDEF. + public DwgAttribData? Attrib { get; init; } + + /// Decoded dimension definition points and measurement when the entity is a DIMENSION_*. + public DwgDimensionData? Dimension { get; init; } + + /// Decoded boundary paths and fill metadata when the entity is a HATCH. + public DwgHatchData? Hatch { get; init; } + /// DXF 62 colour index from the common preamble: the low 9 bits of the stored colour value, /// so 0 is BYBLOCK, 1 to 255 are indexed colours and 256 is BYLAYER. public int ColorIndex { get; init; } @@ -136,8 +169,14 @@ public sealed class DwgEntity /// Raw text payload for and entities. public string? Text { get; init; } - /// Human-readable text for and with MTEXT inline formatting stripped. - public string? PlainText => Text is null ? null : (Kind == DwgEntityKind.MText ? StripMTextFormatting(Text) : Text); + /// Human-readable text for , , + /// , and + /// with MTEXT formatting and CAD Unicode/special escapes decoded. + public string? PlainText => Text is null ? null : Kind switch + { + DwgEntityKind.MText or DwgEntityKind.Dimension => StripMTextFormatting(Text), + _ => DecodeCadEscapes(Text), + }; /// One-line description: type, handle and decoded geometry. public override string ToString() => @@ -161,14 +200,87 @@ public override string ToString() => 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})"), - DwgEntityKind.Text or DwgEntityKind.MText when Geometry is { Length: >= 4 } g => + DwgEntityKind.Text or DwgEntityKind.MText or DwgEntityKind.Attrib or DwgEntityKind.AttDef when Geometry is { Length: >= 4 } g => string.Create(CultureInfo.InvariantCulture, $"{TypeName} {Handle:X}: ({g[0]:F3},{g[1]:F3},{g[2]:F3}) h={g[3]:F3} \"{PlainText}\""), + DwgEntityKind.Dimension when Dimension is { } dim => + string.Create(CultureInfo.InvariantCulture, $"{TypeName} {Handle:X}: m={dim.ActualMeasurement:F3} \"{PlainText}\""), + DwgEntityKind.Leader when Geometry is { Length: >= 4 } g => + string.Create(CultureInfo.InvariantCulture, $"LEADER {Handle:X}: {(g.Length - 1) / 3} vertices"), + DwgEntityKind.Hatch when Hatch is { } hatch => + string.Create(CultureInfo.InvariantCulture, $"HATCH {Handle:X}: {(hatch.IsSolidFill ? "SOLID" : hatch.PatternName)} ({hatch.Loops.Count} loops)"), _ => $"{TypeName} {Handle:X}", }; + private static string DecodeCadEscapes(string raw) + { + if (raw.IndexOf("\\U+", StringComparison.OrdinalIgnoreCase) < 0 && raw.IndexOf("%%", StringComparison.Ordinal) < 0) + { + return raw; + } + + var sb = new System.Text.StringBuilder(raw.Length); + for (int i = 0; i < raw.Length; i++) + { + if (TryReadUnicodeEscape(raw, i, out char ch, out int nextIdx)) + { + sb.Append(ch); + i = nextIdx; + continue; + } + + if (raw[i] == '%' && i + 2 < raw.Length && raw[i + 1] == '%' && TryReadPercentEscape(raw[i + 2], out char? sym)) + { + if (sym is { } s) + { + sb.Append(s); + } + + i += 2; + continue; + } + + sb.Append(raw[i]); + } + + return sb.ToString(); + } + + private static bool TryReadUnicodeEscape(string s, int index, out char decoded, out int lastConsumedIndex) + { + // AutoCAD represents UTF-16 code units as \U+XXXX (hex). + if (index + 6 < s.Length + && s[index] == '\\' + && s[index + 1] is 'U' or 'u' + && s[index + 2] == '+' + && ushort.TryParse(s.AsSpan(index + 3, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ushort code)) + { + decoded = (char)code; + lastConsumedIndex = index + 6; + return true; + } + + decoded = default; + lastConsumedIndex = index; + return false; + } + + private static bool TryReadPercentEscape(char code, out char? symbol) + { + switch (char.ToLowerInvariant(code)) + { + case 'd': symbol = '\u00B0'; return true; // degree ° + case 'p': symbol = '\u00B1'; return true; // plus-minus ± + case 'c': symbol = '\u2300'; return true; // diameter ⌀ + case '%': symbol = '%'; return true; + case 'u': + case 'o': symbol = null; return true; // toggle underline / overline + default: symbol = null; return false; + } + } + private static string StripMTextFormatting(string raw) { - if (raw.IndexOf('\\') < 0 && raw.IndexOf('{') < 0 && raw.IndexOf('}') < 0) + if (raw.IndexOf('\\') < 0 && raw.IndexOf('{') < 0 && raw.IndexOf('}') < 0 && raw.IndexOf("%%", StringComparison.Ordinal) < 0) { return raw; } @@ -182,12 +294,30 @@ private static string StripMTextFormatting(string raw) continue; } + if (c == '%' && i + 2 < raw.Length && raw[i + 1] == '%' && TryReadPercentEscape(raw[i + 2], out char? sym)) + { + if (sym is { } s) + { + sb.Append(s); + } + + i += 2; + continue; + } + if (c != '\\' || i + 1 >= raw.Length) { sb.Append(c); continue; } + if (TryReadUnicodeEscape(raw, i, out char unicode, out int lastIdx)) + { + sb.Append(unicode); + i = lastIdx; + continue; + } + char next = raw[i + 1]; switch (next) { diff --git a/src/DwgIO/Model/DwgHatchData.cs b/src/DwgIO/Model/DwgHatchData.cs new file mode 100644 index 0000000..b05f8f9 --- /dev/null +++ b/src/DwgIO/Model/DwgHatchData.cs @@ -0,0 +1,46 @@ +namespace DwgIO.Model; + +/// +/// A sampled closed or open boundary loop belonging to a HATCH entity, in 2D OCS coordinates. +/// +public sealed class DwgHatchLoop +{ + /// Raw AutoCAD boundary path flags (bit 2 indicates a polyline boundary path). + public uint Flags { get; init; } + + /// True when the boundary loop is explicitly closed. + public bool IsClosed { get; init; } = true; + + /// Sampled boundary vertices in 2D OCS coordinates. + public IReadOnlyList Points { get; init; } = []; +} + +/// +/// Decoded boundary paths, pattern metadata and fill plane of a HATCH entity (0x4E). +/// +public sealed class DwgHatchData +{ + /// Pattern name (e.g. SOLID, ANSI31). + public string PatternName { get; init; } = string.Empty; + + /// True when filled with a solid colour rather than a hatch line pattern. + public bool IsSolidFill { get; init; } + + /// True when associated with boundary entities. + public bool IsAssociative { get; init; } + + /// OCS elevation in drawing units. + public double Elevation { get; init; } + + /// OCS extrusion normal vector. + public DwgPoint3D Extrusion { get; init; } = new(0, 0, 1); + + /// Pattern angle in radians (when not solid). + public double AngleRadians { get; init; } + + /// Pattern scale or spacing (when not solid). + public double ScaleSpacing { get; init; } = 1.0; + + /// Decoded boundary paths of the hatch. + public IReadOnlyList Loops { get; init; } = []; +} diff --git a/tests/DwgIO.Tests/HatchDimensionAttribTests.cs b/tests/DwgIO.Tests/HatchDimensionAttribTests.cs new file mode 100644 index 0000000..cb677a0 --- /dev/null +++ b/tests/DwgIO.Tests/HatchDimensionAttribTests.cs @@ -0,0 +1,346 @@ +using System.Text; +using System.Xml.Linq; +using DwgIO.Export; +using DwgIO.Internal.Parsing; +using DwgIO.Json; +using DwgIO.Model; +using DwgIO.Scene; +using IOScene; +using Xunit; + +namespace DwgIO.Tests; + +public class HatchDimensionAttribTests +{ + private static readonly DwgFileHeader Header2018 = new() + { + Version = new DwgVersionInfo + { + Magic = "AC1032", + Release = "R2018", + Family = DwgContainerFamily.R2004Family, + Year = 2018, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }; + + [Fact] + public void PlainText_DecodesUnicodeAndCadSpecialEscapes() + { + var mtext = new DwgEntity + { + Handle = 0x10, + TypeCode = 0x2C, + TypeName = "MTEXT", + Kind = DwgEntityKind.MText, + Text = @"{\fArial|b0;73 \U+043C\S2^;}", + }; + Assert.Equal("73 м2/", mtext.PlainText); + + var attrib = new DwgEntity + { + Handle = 0x11, + TypeCode = 0x02, + TypeName = "ATTRIB", + Kind = DwgEntityKind.Attrib, + Text = @"\U+041E\U+0441\U+044C 45%%d %%p0.5 %%c100 10%%%", + }; + Assert.Equal("Ось 45° ±0.5 ⌀100 10%", attrib.PlainText); + } + + [Fact] + public void Hatch_SolidAndPattern_EmitOutlineAndEarClippedFill_AndStayFlatInAutoMode() + { + var solidHatch = new DwgEntity + { + Handle = 0x20, + TypeCode = 0x4E, + TypeName = "HATCH", + Kind = DwgEntityKind.Hatch, + ColorIndex = 3, + Hatch = new DwgHatchData + { + PatternName = "SOLID", + IsSolidFill = true, + Elevation = 0, + Loops = + [ + new DwgHatchLoop + { + Flags = 2, + IsClosed = true, + Points = + [ + new(0, 0), + new(4, 0), + new(4, 3), + new(2, 1.5), + new(0, 3), + ], + }, + ], + }, + }; + + var doc = new DwgDocument("hatch.dwg", Header2018, [solidHatch]); + var scene = DwgSceneReader.Read(doc, new DwgSceneOptions { LengthUnit = "m", ModelKey = "hatch.dwg" }); + + Assert.Contains(scene.Document.Geometries, g => g.Topology == SceneTopology.Lines); + var fill = Assert.Single(scene.Document.Geometries, g => g.Topology == SceneTopology.Triangles); + Assert.Equal(9, fill.Indices.Count); // concave 5-vertex polygon -> 3 triangles + Assert.All(fill.Vertices, v => Assert.InRange(v.Z, -0.001, 0.0)); + + using var htmlStream = new MemoryStream(); + Export.DwgViewerExport.ExportToStream(doc, htmlStream, new DwgViewerOptions { Mode = DwgViewerMode.Auto }, "m"); + string html = Encoding.UTF8.GetString(htmlStream.ToArray()); + Assert.Contains("\"initial2DMode\":true", html, StringComparison.Ordinal); + + using var svg = new MemoryStream(); + DwgSvgExporter.Write(doc, svg); + svg.Position = 0; + var svgPath = Assert.Single(XDocument.Load(svg).Descendants(XName.Get("path", "http://www.w3.org/2000/svg"))); + Assert.NotNull(svgPath.Attribute("fill")); + + string json = ToJson(doc); + Assert.Contains("\"patternName\":\"SOLID\"", json, StringComparison.Ordinal); + Assert.Contains("\"isSolidFill\":true", json, StringComparison.Ordinal); + } + + [Fact] + public void Dimension_ExpandsAnonymousBlock_AndSupportsFallback() + { + const ulong modelHandle = 0x1F; + const ulong dimBlockHandle = 0x60; + + var blocks = new DwgBlockInfo[] + { + new() { Handle = modelHandle, Name = "*Model_Space", OwnedEntityHandles = [0x101] }, + new() { Handle = dimBlockHandle, Name = "*D1", OwnedEntityHandles = [0x102, 0x103] }, + }; + + var entities = new DwgEntity[] + { + new() + { + Handle = 0x101, + TypeCode = 0x15, + TypeName = "DIMENSION_LINEAR", + Kind = DwgEntityKind.Dimension, + IsModelSpace = true, + OwnerHandle = modelHandle, + BlockHeaderHandle = dimBlockHandle, + ColorIndex = 6, + Dimension = new DwgDimensionData + { + ActualMeasurement = 3000, + TextMidPoint = new DwgPoint2D(5, 2), + DefinitionPoint = new DwgPoint3D(10, 2, 0), + XLine1Point = new DwgPoint3D(0, 0, 0), + XLine2Point = new DwgPoint3D(10, 0, 0), + }, + }, + new() + { + Handle = 0x102, + TypeCode = 0x13, + TypeName = "LINE", + Kind = DwgEntityKind.Line, + IsModelSpace = false, + OwnerHandle = dimBlockHandle, + ColorIndex = 0, // BYBLOCK inherits magenta (6) + Geometry = [0.0, 2.0, 0.0, 10.0, 2.0, 0.0], + }, + new() + { + Handle = 0x103, + TypeCode = 0x2C, + TypeName = "MTEXT", + Kind = DwgEntityKind.MText, + IsModelSpace = false, + OwnerHandle = dimBlockHandle, + ColorIndex = 7, + Geometry = [5.0, 2.2, 0.0, 0.25, 0.0, 0.0, 5.0], + Text = "3000", + }, + }; + + var doc = new DwgDocument("dims.dwg", Header2018, entities, blocks: blocks); + var scene = DwgSceneReader.Read(doc, new DwgSceneOptions { LengthUnit = "m", ModelKey = "dims.dwg" }); + + Assert.Single(scene.Document.Geometries, g => g.Topology == SceneTopology.Lines); + var ann = Assert.Single(scene.Annotations); + Assert.Equal("3000", ann.Text); + + string json = ToJson(doc); + Assert.Contains("\"actualMeasurement\":3000", json, StringComparison.Ordinal); + + // Without *D block, dimension falls back cleanly to its XLine1..XLine2 line segment. + var fallbackDoc = new DwgDocument("dim-fallback.dwg", Header2018, [entities[0]]); + var fallbackScene = DwgSceneReader.Read(fallbackDoc, new DwgSceneOptions { LengthUnit = "m", ModelKey = "dim-fallback.dwg" }); + Assert.Single(fallbackScene.Document.Geometries, g => g.Topology == SceneTopology.Lines); + } + + [Fact] + public void AttribAttDefLeaderAndBlockMarkers_SceneJsonAndSvgIntegration() + { + var entities = new DwgEntity[] + { + new() { Handle = 0x30, TypeCode = 0x04, TypeName = "BLOCK", Kind = DwgEntityKind.Block }, + new() { Handle = 0x31, TypeCode = 0x05, TypeName = "ENDBLK", Kind = DwgEntityKind.EndBlk }, + new() { Handle = 0x32, TypeCode = 0x06, TypeName = "SEQEND", Kind = DwgEntityKind.SeqEnd }, + new() + { + Handle = 0x33, + TypeCode = 0x02, + TypeName = "ATTRIB", + Kind = DwgEntityKind.Attrib, + Geometry = [1, 2, 0, 0.5, 0, 1, 0, 0, 0], + Text = "VISIBLE_VAL", + Attrib = new DwgAttribData { Tag = "SHEET", Flags = 0 }, + }, + new() + { + Handle = 0x34, + TypeCode = 0x02, + TypeName = "ATTRIB", + Kind = DwgEntityKind.Attrib, + Geometry = [1, 3, 0, 0.5, 0, 1, 0, 0, 0], + Text = "HIDDEN_VAL", + Attrib = new DwgAttribData { Tag = "INTERNAL", Flags = 1 }, + }, + new() + { + Handle = 0x35, + TypeCode = 0x2D, + TypeName = "LEADER", + Kind = DwgEntityKind.Leader, + Geometry = [0, 0, 0, 0, 3, 2, 0, 5, 2, 0], + }, + }; + + var doc = new DwgDocument("attribs.dwg", Header2018, entities); + var scene = DwgSceneReader.Read(doc, new DwgSceneOptions { LengthUnit = "m", ModelKey = "attribs.dwg" }); + + Assert.Equal(0, scene.EntitiesWithoutGeometry); + var ann = Assert.Single(scene.Annotations); + Assert.Equal("VISIBLE_VAL", ann.Text); + Assert.Single(scene.Document.Geometries, g => g.Topology == SceneTopology.Lines && g.Vertices.Count == 3); + + string json = ToJson(doc); + Assert.Contains("\"tag\":\"SHEET\"", json, StringComparison.Ordinal); + + using var svg = new MemoryStream(); + DwgSvgExporter.Write(doc, svg); + svg.Position = 0; + var svgDoc = XDocument.Load(svg); + var svgText = Assert.Single(svgDoc.Descendants(XName.Get("text", "http://www.w3.org/2000/svg"))); + Assert.Equal("VISIBLE_VAL", svgText.Value); + Assert.Single(svgDoc.Descendants(XName.Get("path", "http://www.w3.org/2000/svg"))); + } + + [Fact] + public void DecodeLeader_SyntheticR2018Stream_DecodesPathAndVertices() + { + var w = new RecordBitWriter(); + WriteCommonEntityHeader2018(w, 0x2D, 0x70); + w.WriteBit(false); // unknown_bit_1 + WritePackedShort(w, 3); // annot_type + WritePackedShort(w, 0); // path_type (straight) + WritePackedInt(w, 2); // num_points + WritePackedDouble(w, 1.0); + WritePackedDouble(w, 2.0); + WritePackedDouble(w, 0.0); + WritePackedDouble(w, 6.0); + WritePackedDouble(w, 8.0); + WritePackedDouble(w, 0.0); + + byte[] payload = FinalizeR2018RecordNoStrings(w, layerHandle: 0x3C); + var info = new DwgObjectInfo + { + StreamOffset = 0, + SizeBytes = (uint)payload.Length, + TypeCode = 0x2D, + Handle = 0x70, + StreamHandle = new DwgHandle(0, 1, 0x70), + BitsStart = 0, + BitsLength = payload.Length, + }; + + var decoded = EntityDecoder.Decode(info, payload, year: 2018); + Assert.NotNull(decoded); + Assert.Equal(DwgEntityKind.Leader, decoded!.Kind); + Assert.Equal([0.0, 1.0, 2.0, 0.0, 6.0, 8.0, 0.0], decoded.Geometry!); + } + + private static void WriteCommonEntityHeader2018(RecordBitWriter w, ushort typeCode, ulong handle) + { + w.WriteTwoBits(0); + w.WriteRawByte((byte)typeCode); + w.WriteRawByte(0x01); + w.WriteRawByte((byte)handle); + w.WriteTwoBits(2); // XDATA end + w.WriteBit(false); + w.WriteTwoBits(2u); // Model Space + w.WriteTwoBits(2); // reactor count = 0 + w.WriteBit(true); // no extension dictionary + w.WriteBit(false); // hasAcDs + w.WriteTwoBits(2); // color = 0 + w.WriteTwoBits(1); // ltScale = 1 + w.WriteTwoBits(0); + w.WriteTwoBits(0); + w.WriteTwoBits(0); + w.WriteRawByte(0); + w.WriteBit(false); + w.WriteBit(false); + w.WriteBit(false); + w.WriteTwoBits(2); // invisibility + w.WriteRawByte(0); // lineweight + } + + private static byte[] FinalizeR2018RecordNoStrings(RecordBitWriter data, ulong layerHandle) + { + data.WriteBit(false); // hasStrings + int totalBeforeHandles = data.BitsUsed; + data.WriteRawByte(0x51); + data.WriteRawByte((byte)layerHandle); + int handleBits = (data.BitsUsed - totalBeforeHandles) + ((8 - (data.BitsUsed % 8)) % 8); + byte[] bodyBytes = data.ToArray(); + byte[] full = new byte[1 + bodyBytes.Length]; + full[0] = (byte)handleBits; + bodyBytes.CopyTo(full, 1); + return full; + } + + private static string ToJson(DwgDocument doc) + { + using var ms = new MemoryStream(); + DwgJsonExporter.Write(doc, ms, new DwgJsonExportOptions { Indented = false }); + return Encoding.UTF8.GetString(ms.ToArray()); + } + + private static void WritePackedShort(RecordBitWriter w, ushort value) + { + if (value == 0) { w.WriteTwoBits(2); return; } + if (value < 256) { w.WriteTwoBits(1); w.WriteRawByte((byte)value); return; } + w.WriteTwoBits(0); + w.WriteRawByte((byte)(value & 0xFF)); + w.WriteRawByte((byte)(value >> 8)); + } + + private static void WritePackedInt(RecordBitWriter w, uint value) + { + if (value == 0) { w.WriteTwoBits(2); return; } + w.WriteTwoBits(0); + for (int i = 0; i < 4; i++) w.WriteRawByte((byte)((value >> (i * 8)) & 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); + foreach (byte b in BitConverter.GetBytes(value)) w.WriteRawByte(b); + } +} From 79fff0ed0ea25dd9f3de1d9eb07e8e4b355a3873 Mon Sep 17 00:00:00 2001 From: mahach666 Date: Wed, 2 Dec 2026 17:09:41 +0300 Subject: [PATCH 2/2] Preserve hatch islands, viewport fills and CAD labels --- docs/public-api.md | 9 +- .../DwgIO.Scene.Adapter.csproj | 2 +- src/DwgIO.Scene.Adapter/DwgSceneReader.cs | 350 ++++++++++-------- src/DwgIO.Scene.Adapter/HatchFill.cs | 80 ++++ .../Compatibility/DwgSvgExporter.cs | 36 +- src/DwgIO.Scene/DwgIO.Scene.csproj | 2 +- src/DwgIO/Internal/Parsing/EntityDecoder.cs | 28 +- src/DwgIO/Json/DwgJsonExporter.cs | 1 + src/DwgIO/Model/DwgHatchData.cs | 3 + src/Shared/HatchBoundaries.cs | 14 + src/Shared/TextPlacement.cs | 2 +- .../DwgIO.Tests/HatchDimensionAttribTests.cs | 170 ++++++++- 12 files changed, 512 insertions(+), 185 deletions(-) create mode 100644 src/DwgIO.Scene.Adapter/HatchFill.cs create mode 100644 src/Shared/HatchBoundaries.cs diff --git a/docs/public-api.md b/docs/public-api.md index 21ac1a3..426f2ee 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -86,7 +86,14 @@ IOScene.SceneJson.Save(result.Document, "drawing.scene.json"); ``` The scene validates against the IOScene contract (`SceneDocument.Validate` reports no error) and round-trips through -IOScene JSON with its original line and point topology. +IOScene JSON with its line, point and triangle topology. + +Solid `HATCH` fills preserve islands according to the recorded detection style. Floating viewports project and clip +the fill to the paper viewport. `DwgHatchData.Style` and the drawing JSON `hatch.style` expose that setting. +[AutoCAD hatch island detection](https://help.autodesk.com/cloudhelp/2023/ENU/AutoCAD-Core/files/GUID-981679AC-7097-4724-A30D-33F1CAFDD81D.htm) + +Visible `ATTRIB` labels follow the space of their owning `INSERT`. A dimension without rendered block graphics +uses a label based on its override text or recorded measurement at its text midpoint. ## CLI Exporters (`dwgio`) diff --git a/src/DwgIO.Scene.Adapter/DwgIO.Scene.Adapter.csproj b/src/DwgIO.Scene.Adapter/DwgIO.Scene.Adapter.csproj index d79ca17..cf3f473 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 09cc5b8..2b65814 100644 --- a/src/DwgIO.Scene.Adapter/DwgSceneReader.cs +++ b/src/DwgIO.Scene.Adapter/DwgSceneReader.cs @@ -21,6 +21,7 @@ public static class DwgSceneReader private const double ArcRadiansPerSegment = 5.0 * Math.PI / 180.0; private const int MinArcSegments = 8; private const int MaxInsertDepth = 16; + private const double HatchFillOffset = 0.0005; /// Reads the drawing at with and converts it. public static DwgSceneResult Read(string path, DwgSceneOptions? options = null) @@ -129,8 +130,9 @@ private sealed class ConversionContext private readonly double _rootScale; private readonly Dictionary _xrefCache = new(StringComparer.OrdinalIgnoreCase); private readonly HashSet _activeXrefPaths = new(StringComparer.OrdinalIgnoreCase); - private readonly List<(Vector3d A, Vector3d B, RgbaColor? Color, string? Layer, DwgEntity Source)> _modelSegments = []; - private readonly List<(DwgSceneAnnotation Ann, Vector3d WorldPos, double WorldHeight)> _modelAnnotations = []; + private readonly List<(Vector3d A, Vector3d B, RgbaColor? Color, string? Layer)> _modelSegments = []; + private readonly List<(SceneGeometry Geometry, RgbaColor? Color, string? Layer)> _modelHatchFills = []; + private readonly List _modelAnnotations = []; public SceneDocument Scene { get; } public List Diagnostics { get; } = []; @@ -332,13 +334,20 @@ private void FlattenBlock( if (entity.Kind == DwgEntityKind.Dimension && entity.BlockHeaderHandle is ulong dimBlockHandle && index.Blocks.ContainsKey(dimBlockHandle)) { + int geometryBefore = ElementsWithGeometry; + int annotationsBefore = Annotations.Count; (int nextAci, uint? nextRgb) = ResolveByBlock(entity, byBlockAci, byBlockRgb); FlattenBlock(index, dimBlockHandle, transform, scaleToMetres, nextAci, nextRgb, sheetKey, recordForViewports, depth + 1, visitedBlocks, elementIds); - continue; + if (ElementsWithGeometry != geometryBefore || Annotations.Count != annotationsBefore) + { + continue; + } } - EmitEntity(index.Document, entity, transform, scaleToMetres, byBlockAci, byBlockRgb, sheetKey, recordForViewports, elementIds); + var owner = FindOwningInsert(entity, index.EntitiesByHandle); + var (aci, rgb) = owner is null ? (byBlockAci, byBlockRgb) : ResolveByBlock(owner, byBlockAci, byBlockRgb); + EmitEntity(index.Document, entity, transform, scaleToMetres, aci, rgb, sheetKey, recordForViewports, elementIds); } } finally @@ -490,11 +499,7 @@ private void EmitEntity( elementIds.Add(el.Id); var ann = new DwgSceneAnnotation(plain, pos, textHeight, rot, width, att, col, el.Id, sheetKey); - Annotations.Add(ann); - if (recordForViewports) - { - _modelAnnotations.Add((ann, pos, textHeight)); - } + AddAnnotation(ann, recordForViewports); return; } @@ -511,6 +516,15 @@ private void EmitEntity( return; } + var instanceColor = ColourOf(entity, byBlockAci, byBlockRgb); + var dimensionLabel = entity.Dimension is { } dimension + ? DimensionLabel(ownerDoc, entity, dimension, element.Id, sheetKey, transform, scale, instanceColor) + : null; + if (dimensionLabel is not null) + { + AddAnnotation(dimensionLabel, recordForViewports); + } + (SceneTopology topology, Vector3d[] vertices, IReadOnlyList indices)? built = entity.Kind switch { DwgEntityKind.Line when entity.Geometry is { Length: 6 } g => @@ -549,7 +563,7 @@ private void EmitEntity( if (built is null) { - if (entity.Kind == DwgEntityKind.Unknown || entity.Geometry is null) + if (dimensionLabel is null && (entity.Kind == DwgEntityKind.Unknown || entity.Geometry is null)) { if (!isStructured || entity.Kind != DwgEntityKind.Insert) { @@ -576,7 +590,6 @@ private void EmitEntity( Indices = built.Value.indices, }; Scene.Geometries.Add(geometry); - var instanceColor = ColourOf(entity, byBlockAci, byBlockRgb); Scene.Instances.Add(new SceneInstance { ElementId = element.Id, @@ -593,7 +606,7 @@ private void EmitEntity( { var a = idx.Count > 0 ? verts[idx[k]] : verts[k]; var b = idx.Count > 0 ? verts[idx[k + 1]] : verts[k + 1]; - _modelSegments.Add((a, b, instanceColor, entity.LayerName, entity)); + _modelSegments.Add((a, b, instanceColor, entity.LayerName)); } } @@ -616,6 +629,10 @@ private void EmitEntity( GeometryId = fillGeom.Id, Color = instanceColor, }); + if (recordForViewports) + { + _modelHatchFills.Add((fillGeom, instanceColor, entity.LayerName)); + } } } } @@ -644,8 +661,19 @@ Vector3d Project(Vector3d worldM) return new Vector3d(px, py, centerPaper.Z); } - // Batch clipped viewport linework per (layer, color) to keep sheets lean and responsive. - var batches = new Dictionary<(string Layer, RgbaColor? Color), List>(); + var batches = new Dictionary<(string Layer, RgbaColor? Color, SceneTopology Topology), List>(); + List GetBatch(string? layer, RgbaColor? color, SceneTopology topology) + { + var key = (layer ?? "0", color, topology); + if (!batches.TryGetValue(key, out var list)) + { + list = []; + batches[key] = list; + } + + return list; + } + foreach (var seg in _modelSegments) { var p0 = Project(seg.A); @@ -655,19 +683,39 @@ Vector3d Project(Vector3d worldM) continue; } - string layer = seg.Layer ?? "0"; - var key = (layer, seg.Color); - if (!batches.TryGetValue(key, out var list)) - { - list = []; - batches[key] = list; - } - + var list = GetBatch(seg.Layer, seg.Color, SceneTopology.Lines); list.Add(p0); list.Add(p1); } - foreach (var ((layer, color), verts) in batches) + Span polygon = stackalloc Vector3d[7]; + var fillOffset = Vector3d.UnitZ * HatchFillOffset; + foreach (var (fill, color, layer) in _modelHatchFills) + { + List? list = null; + for (int i = 0; i < fill.Indices.Count; i += 3) + { + polygon[0] = Project(fill.Vertices[fill.Indices[i]]) - fillOffset; + polygon[1] = Project(fill.Vertices[fill.Indices[i + 1]]) - fillOffset; + polygon[2] = Project(fill.Vertices[fill.Indices[i + 2]]) - fillOffset; + int count = ClipTriangleToViewport(polygon, minX, minY, maxX, maxY); + for (int j = 1; j + 1 < count; j++) + { + var a = polygon[0]; + var b = polygon[j]; + var c = polygon[j + 1]; + double area = (b.X - a.X) * (c.Y - a.Y) - (b.Y - a.Y) * (c.X - a.X); + if (area == 0 || !double.IsFinite(area)) continue; + + list ??= GetBatch(layer, color, SceneTopology.Triangles); + list.Add(a); + list.Add(area > 0 ? b : c); + list.Add(area > 0 ? c : b); + } + } + } + + foreach (var ((layer, color, topology), verts) in batches) { if (verts.Count < 2) { @@ -692,22 +740,23 @@ Vector3d Project(Vector3d worldM) var geom = new SceneGeometry { Id = _geometryId, - Topology = SceneTopology.Lines, + Topology = topology, Vertices = verts.ToArray(), + Indices = topology == SceneTopology.Triangles ? Enumerable.Range(0, verts.Count).ToArray() : [], }; Scene.Geometries.Add(geom); Scene.Instances.Add(new SceneInstance { ElementId = el.Id, GeometryId = geom.Id, Color = color }); } - foreach (var (ann, worldPos, worldHeight) in _modelAnnotations) + foreach (var ann in _modelAnnotations) { - var p = Project(worldPos); + var p = Project(ann.Position); if (p.X < minX || p.X > maxX || p.Y < minY || p.Y > maxY) { continue; } - double h = worldHeight * vpScale; + double h = ann.Height * vpScale; if (h <= 0 || !double.IsFinite(h)) { continue; @@ -725,6 +774,15 @@ Vector3d Project(Vector3d worldM) } } + private void AddAnnotation(DwgSceneAnnotation annotation, bool recordForViewports) + { + Annotations.Add(annotation); + if (recordForViewports) + { + _modelAnnotations.Add(annotation); + } + } + private SceneElement CreateElement(DwgDocument doc, DwgEntity entity) { _ = doc; @@ -768,6 +826,7 @@ private sealed record DocIndex( DwgDocument Document, ulong? ModelBlockHandle, Dictionary Blocks, + Dictionary EntitiesByHandle, Dictionary> EntitiesByBlock, List<(DwgLayoutInfo Layout, ulong BlockHandle, List Viewports)> PaperLayouts); @@ -797,6 +856,11 @@ private static DocIndex IndexDocument(DwgDocument doc) } var entityByHandle = new Dictionary(doc.Entities.Count); + foreach (var entity in doc.Entities) + { + entityByHandle.TryAdd(entity.Handle, entity); + } + var byBlock = new Dictionary>(); void AddToBlock(ulong blkHandle, DwgEntity e) { @@ -811,20 +875,21 @@ void AddToBlock(ulong blkHandle, DwgEntity e) foreach (var e in doc.Entities) { - entityByHandle.TryAdd(e.Handle, e); - if (e.IsModelSpace && modelHandle is ulong mh) + // ATTRIB coordinates are already in the insertion's containing space. + var placement = FindOwningInsert(e, entityByHandle) ?? e; + if (placement.IsModelSpace && modelHandle is ulong mh) { AddToBlock(mh, e); } - else if (e.OwnerHandle is ulong oh && blocks.ContainsKey(oh)) + else if (placement.OwnerHandle is ulong oh && blocks.ContainsKey(oh)) { AddToBlock(oh, e); } - else if (entityOwnerFromBlock.TryGetValue(e.Handle, out ulong bh)) + else if (entityOwnerFromBlock.TryGetValue(placement.Handle, out ulong bh)) { AddToBlock(bh, e); } - else if (!e.IsModelSpace && defaultPaperHandle is ulong ph) + else if (!placement.IsModelSpace && defaultPaperHandle is ulong ph) { AddToBlock(ph, e); } @@ -856,7 +921,50 @@ void AddToBlock(ulong blkHandle, DwgEntity e) } } - return new DocIndex(doc, modelHandle, blocks, byBlock, paperLayouts); + return new DocIndex(doc, modelHandle, blocks, entityByHandle, byBlock, paperLayouts); + } + + private static DwgEntity? FindOwningInsert(DwgEntity entity, Dictionary entities) => + entity.Kind == DwgEntityKind.Attrib && entity.OwnerHandle is ulong handle + && entities.TryGetValue(handle, out var owner) && owner.Kind == DwgEntityKind.Insert + ? owner : null; + + private static DwgSceneAnnotation? DimensionLabel(DwgDocument doc, DwgEntity entity, DwgDimensionData dim, + long elementId, string? sheetKey, Affine3d transform, double scale, RgbaColor? color) + { + string text = entity.PlainText ?? dim.UserText; + if (text.Length > 0 && string.IsNullOrWhiteSpace(text)) + { + return null; + } + + if (text.Length == 0 || text.Contains("<>", StringComparison.Ordinal)) + { + if (!double.IsFinite(dim.ActualMeasurement)) + { + return null; + } + + bool angular = entity.TypeCode is 0x17 or 0x18; + double value = angular ? double.RadiansToDegrees(dim.ActualMeasurement) : dim.ActualMeasurement; + string measurement = value.ToString("G", CultureInfo.InvariantCulture) + (angular ? "°" : ""); + text = text.Length == 0 ? measurement : text.Replace("<>", measurement, StringComparison.Ordinal); + } + + var (x, y, z) = ArbitraryAxisBasis(new Vector3d(dim.Extrusion.X, dim.Extrusion.Y, dim.Extrusion.Z), 0); + var pos = transform.Apply(x * dim.TextMidPoint.X + y * dim.TextMidPoint.Y + z * dim.Elevation) * scale; + double textHeight = doc.HeaderVariables?.TextSize ?? 0; + if (!double.IsFinite(textHeight) || textHeight <= 0) + { + textHeight = 2.5; + } + + textHeight *= scale * transform.UniformScaleXY; + var baseline = transform.ApplyVector(x); + double rotation = Math.Atan2(baseline.Y, baseline.X); + return IsFinite(pos) && double.IsFinite(textHeight) && textHeight > 0 && double.IsFinite(rotation) + ? new DwgSceneAnnotation(text, pos, textHeight, rotation, 0, 5, color, elementId, sheetKey) + : null; } private static (int Aci, uint? Rgb) ResolveByBlock(DwgEntity insert, int parentAci, uint? parentRgb) @@ -958,6 +1066,51 @@ bool Clip(double p, double q) return true; } + private static int ClipTriangleToViewport(Span polygon, double minX, double minY, double maxX, double maxY) + { + // A triangle clipped by a rectangle has at most seven vertices. + Span scratch = stackalloc Vector3d[7]; + int count = ClipPolygonEdge(polygon[..3], scratch, xAxis: true, minX, keepGreater: true); + count = ClipPolygonEdge(scratch[..count], polygon, xAxis: true, maxX, keepGreater: false); + count = ClipPolygonEdge(polygon[..count], scratch, xAxis: false, minY, keepGreater: true); + return ClipPolygonEdge(scratch[..count], polygon, xAxis: false, maxY, keepGreater: false); + } + + private static int ClipPolygonEdge(ReadOnlySpan input, Span output, + bool xAxis, double limit, bool keepGreater) + { + if (input.IsEmpty) return 0; + + double Distance(Vector3d point) + { + double value = xAxis ? point.X : point.Y; + return keepGreater ? value - limit : limit - value; + } + + int count = 0; + var previous = input[^1]; + double previousDistance = Distance(previous); + foreach (var current in input) + { + double distance = Distance(current); + if ((previousDistance < 0 && distance > 0) || (previousDistance > 0 && distance < 0)) + { + double fraction = previousDistance / (previousDistance - distance); + output[count++] = previous + (current - previous) * fraction; + } + + if (distance >= 0) + { + output[count++] = current; + } + + previous = current; + previousDistance = distance; + } + + return count; + } + private static (Vector3d X, Vector3d Y, Vector3d Z) ArbitraryAxisBasis(Vector3d normal, double twistRad) { double len = normal.Length; @@ -1077,135 +1230,14 @@ private static (SceneTopology, Vector3d[], IReadOnlyList)? BuildHatchOutlin private static (SceneTopology topology, Vector3d[] vertices, IReadOnlyList indices)? BuildHatchSolidFill( DwgHatchData hatch, Affine3d t, double scale) { - // Triangulate simple outer/default boundary loops cleanly via 2D ear-clipping. - var (ax, ay, az) = ArbitraryAxisBasis(new Vector3d(hatch.Extrusion.X, hatch.Extrusion.Y, hatch.Extrusion.Z), 0); - var vertices = new List(); - var indices = new List(); + if (HatchFill.Triangulate(hatch) is not { } fill) return null; + var (ax, ay, az) = ArbitraryAxisBasis(new Vector3d(hatch.Extrusion.X, hatch.Extrusion.Y, hatch.Extrusion.Z), 0); var worldNormal = t.ApplyVector(az); double normalLen = worldNormal.Length; - var offset = (normalLen > 1e-12 ? worldNormal / normalLen : Vector3d.UnitZ) * 0.0005; - - foreach (var loop in hatch.Loops) - { - if (loop.Points.Count < 3) continue; - var poly = CleanPolygon2D(loop.Points); - if (poly.Count < 3) continue; - - var tris = EarClip2D(poly); - if (tris.Count < 3) continue; - - int baseIdx = vertices.Count; - foreach (var p in poly) - { - // Offset solid fill slightly behind coplanar CAD linework/furniture to prevent WebGL depth-fighting. - vertices.Add(LiftHatchPoint(p, hatch.Elevation, ax, ay, az, t, scale) - offset); - } - - foreach (int ti in tris) - { - indices.Add(baseIdx + ti); - } - } - - return indices.Count >= 3 ? (SceneTopology.Triangles, vertices.ToArray(), indices) : null; - } - - private static List CleanPolygon2D(IReadOnlyList pts) - { - var result = new List(pts.Count); - foreach (var p in pts) - { - if (result.Count == 0 || Math.Abs(result[^1].X - p.X) > 1e-9 || Math.Abs(result[^1].Y - p.Y) > 1e-9) - { - result.Add(p); - } - } - - if (result.Count > 1 && Math.Abs(result[^1].X - result[0].X) <= 1e-9 && Math.Abs(result[^1].Y - result[0].Y) <= 1e-9) - { - result.RemoveAt(result.Count - 1); - } - - return result; - } - - private static List EarClip2D(List poly) - { - int n = poly.Count; - var indices = new List((n - 2) * 3); - if (n < 3) return indices; - - double area2 = 0; - for (int i = 0; i < n; i++) - { - var a = poly[i]; - var b = poly[(i + 1) % n]; - area2 += a.X * b.Y - b.X * a.Y; - } - - if (Math.Abs(area2) <= 1e-12) return indices; - - var rem = new List(n); - if (area2 > 0) - { - for (int i = 0; i < n; i++) rem.Add(i); - } - else - { - for (int i = n - 1; i >= 0; i--) rem.Add(i); - } - - int guard = rem.Count * rem.Count + 4; - while (rem.Count > 2 && guard-- > 0) - { - bool clipped = false; - for (int i = 0; i < rem.Count; i++) - { - int prev = rem[(i - 1 + rem.Count) % rem.Count]; - int curr = rem[i]; - int next = rem[(i + 1) % rem.Count]; - var a = poly[prev]; - var b = poly[curr]; - var c = poly[next]; - - double cross = (b.X - a.X) * (c.Y - a.Y) - (b.Y - a.Y) * (c.X - a.X); - if (cross <= 1e-12) continue; - - bool containsOther = false; - for (int j = 0; j < rem.Count; j++) - { - int vi = rem[j]; - if (vi == prev || vi == curr || vi == next) continue; - if (PointInTriangle(poly[vi], a, b, c)) - { - containsOther = true; - break; - } - } - - if (containsOther) continue; - - indices.Add(prev); - indices.Add(curr); - indices.Add(next); - rem.RemoveAt(i); - clipped = true; - break; - } - - if (!clipped) break; - } - - return indices; - } - - private static bool PointInTriangle(DwgPoint2D p, DwgPoint2D a, DwgPoint2D b, DwgPoint2D c) - { - double c1 = (b.X - a.X) * (p.Y - a.Y) - (b.Y - a.Y) * (p.X - a.X); - double c2 = (c.X - b.X) * (p.Y - b.Y) - (c.Y - b.Y) * (p.X - b.X); - double c3 = (a.X - c.X) * (p.Y - c.Y) - (a.Y - c.Y) * (p.X - c.X); - return c1 >= -1e-12 && c2 >= -1e-12 && c3 >= -1e-12; + var offset = (normalLen > 1e-12 ? worldNormal / normalLen : Vector3d.UnitZ) * HatchFillOffset; + var vertices = fill.Vertices.Select(p => LiftHatchPoint(p, hatch.Elevation, ax, ay, az, t, scale) - offset).ToArray(); + return (SceneTopology.Triangles, vertices, fill.Indices); } private static void AppendBulgeSegments( diff --git a/src/DwgIO.Scene.Adapter/HatchFill.cs b/src/DwgIO.Scene.Adapter/HatchFill.cs new file mode 100644 index 0000000..54458d0 --- /dev/null +++ b/src/DwgIO.Scene.Adapter/HatchFill.cs @@ -0,0 +1,80 @@ +using DwgIO.Model; + +namespace DwgIO.Scene; + +internal static class HatchFill +{ + private readonly record struct Edge(DwgPoint2D Lower, DwgPoint2D Upper) + { + public double XAt(double y) => Lower.X + (Upper.X - Lower.X) * ((y - Lower.Y) / (Upper.Y - Lower.Y)); + } + + public static (List Vertices, List Indices)? Triangulate(DwgHatchData hatch) + { + var edges = new List(); + var elevations = new SortedSet(); + foreach (var loop in hatch.Loops) + { + if (!HatchBoundaries.Fills(hatch, loop)) continue; + for (int i = 0; i < loop.Points.Count; i++) + { + var a = loop.Points[i]; + var b = loop.Points[(i + 1) % loop.Points.Count]; + if (!double.IsFinite(a.X) || !double.IsFinite(a.Y)) return null; + if (a.Y == b.Y) continue; + edges.Add(a.Y < b.Y ? new Edge(a, b) : new Edge(b, a)); + elevations.Add(a.Y); + elevations.Add(b.Y); + } + } + + edges.Sort((a, b) => a.Lower.Y.CompareTo(b.Lower.Y)); + var levels = elevations.ToArray(); + var active = new List(); + var vertices = new List(); + var indices = new List(); + int next = 0; + // Between vertex elevations each pair of consecutive crossings bounds a filled trapezoid. + for (int level = 0; level + 1 < levels.Length; level++) + { + double bottom = levels[level], top = levels[level + 1]; + double mid = bottom + (top - bottom) / 2; + active.RemoveAll(e => e.Upper.Y <= bottom); + while (next < edges.Count && edges[next].Lower.Y <= bottom) + { + active.Add(edges[next++]); + } + + active.Sort((a, b) => a.XAt(mid).CompareTo(b.XAt(mid))); + for (int i = 0; i + 1 < active.Count; i += 2) + { + var left = active[i]; + var right = active[i + 1]; + double leftBottom = left.XAt(bottom), rightBottom = right.XAt(bottom); + double leftTop = left.XAt(top), rightTop = right.XAt(top); + if (leftBottom >= rightBottom && leftTop >= rightTop) continue; + + int first = vertices.Count; + vertices.Add(new DwgPoint2D(leftBottom, bottom)); + vertices.Add(new DwgPoint2D(rightBottom, bottom)); + vertices.Add(new DwgPoint2D(rightTop, top)); + vertices.Add(new DwgPoint2D(leftTop, top)); + if (leftBottom < rightBottom) + { + indices.Add(first); + indices.Add(first + 1); + indices.Add(first + 2); + } + + if (leftTop < rightTop) + { + indices.Add(first); + indices.Add(first + 2); + indices.Add(first + 3); + } + } + } + + return indices.Count > 0 ? (vertices, indices) : null; + } +} diff --git a/src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs b/src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs index 1613d6e..8bfe7d4 100644 --- a/src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs +++ b/src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs @@ -114,6 +114,10 @@ public static void Write(DwgDocument document, XmlWriter writer, DwgSvgOptions? if (path.Fill) { writer.WriteAttributeString("fill", stroke); + if (path.EvenOdd) + { + writer.WriteAttributeString("fill-rule", "evenodd"); + } } writer.WriteAttributeString("stroke", stroke); @@ -201,7 +205,10 @@ private sealed record SvgPoint(double X, double Y, int ColorIndex, uint? TrueCol : SvgShape(ColorIndex, TrueColorRgb); private sealed record SvgPath(string Data, IReadOnlyList<(double X, double Y)> BoundsPoints, bool Fill, int ColorIndex, uint? TrueColorRgb) - : SvgShape(ColorIndex, TrueColorRgb); + : SvgShape(ColorIndex, TrueColorRgb) + { + public bool EvenOdd { get; init; } + } private sealed record SvgText( double X, double Y, double Height, double RotationRad, string Text, int Column, int Row, int ColorIndex, uint? TrueColorRgb) @@ -211,9 +218,21 @@ private static List Collect(DwgDocument document, DwgSvgOptions option { double scale = options.Scale; var shapes = new List(); + var inserts = new Dictionary(); + foreach (var entity in document.Entities) + { + if (entity.Kind == DwgEntityKind.Insert) + { + inserts.TryAdd(entity.Handle, entity); + } + } + foreach (var entity in document.Entities) { - if (!entity.IsModelSpace) + var insert = entity.Kind == DwgEntityKind.Attrib && entity.OwnerHandle is ulong owner + ? inserts.GetValueOrDefault(owner) + : null; + if (!(insert?.IsModelSpace ?? entity.IsModelSpace)) { continue; } @@ -305,6 +324,7 @@ private static List Collect(DwgDocument document, DwgSvgOptions option if (IsUsable(g[0] * scale, g[1] * scale, g[3] * scale, g[4]) && g[3] > 0 && entity.PlainText is { Length: > 0 } plain) { var (column, row) = TextPlacement.Alignment(entity.Kind, g); + bool byBlock = insert is not null && entity.EffectiveColorIndex == 0 && entity.EffectiveTrueColorRgb is null; shapes.Add(new SvgText( g[0] * scale, -g[1] * scale, @@ -313,8 +333,8 @@ private static List Collect(DwgDocument document, DwgSvgOptions option plain, column, row, - entity.EffectiveColorIndex, - entity.EffectiveTrueColorRgb)); + byBlock ? insert!.EffectiveColorIndex : entity.EffectiveColorIndex, + byBlock ? insert!.EffectiveTrueColorRgb : entity.EffectiveTrueColorRgb)); } break; @@ -367,9 +387,10 @@ private static bool TryBuildHatch(DwgHatchData hatch, double scale, DwgEntity en { var sb = new System.Text.StringBuilder(); var bounds = new List<(double X, double Y)>(); + bool fill = hatch.IsSolidFill && hatch.Loops.Any(loop => HatchBoundaries.Fills(hatch, loop)); foreach (var loop in hatch.Loops) { - if (loop.Points.Count < 2) continue; + if (loop.Points.Count < 2 || (fill && !HatchBoundaries.Fills(hatch, loop))) continue; for (int i = 0; i < loop.Points.Count; i++) { double x = loop.Points[i].X * scale; @@ -393,7 +414,10 @@ private static bool TryBuildHatch(DwgHatchData hatch, double scale, DwgEntity en return false; } - path = new SvgPath(sb.ToString().TrimEnd(), bounds, hatch.IsSolidFill, entity.EffectiveColorIndex, entity.EffectiveTrueColorRgb); + path = new SvgPath(sb.ToString().TrimEnd(), bounds, fill, entity.EffectiveColorIndex, entity.EffectiveTrueColorRgb) + { + EvenOdd = fill, + }; return true; } diff --git a/src/DwgIO.Scene/DwgIO.Scene.csproj b/src/DwgIO.Scene/DwgIO.Scene.csproj index 6a9cc65..0447d57 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 cf5c339..af9be5e 100644 --- a/src/DwgIO/Internal/Parsing/EntityDecoder.cs +++ b/src/DwgIO/Internal/Parsing/EntityDecoder.cs @@ -1279,7 +1279,7 @@ private static (DwgEntityKind, double[]?, string?) DecodeHatch( } } - _ = reader.ReadPackedShort(); // style + int style = (int)reader.ReadPackedShort(); _ = reader.ReadPackedShort(); // pattern_type double angle = 0; double scaleSpacing = 1.0; @@ -1294,6 +1294,7 @@ private static (DwgEntityKind, double[]?, string?) DecodeHatch( PatternName = string.IsNullOrEmpty(patternName) && isSolidFill ? "SOLID" : patternName, IsSolidFill = isSolidFill, IsAssociative = isAssociative, + Style = style, Elevation = elevation, Extrusion = extrusion, AngleRadians = angle, @@ -1320,11 +1321,7 @@ private static void AppendHatchCircularArc( double end, bool ccw) { - double a0 = ccw ? start : (Math.Tau - start); - double a1 = ccw ? end : (Math.Tau - end); - double span = ccw ? (a1 - a0) : (a0 - a1); - while (span <= 0) span += Math.Tau; - while (span > Math.Tau + 1e-9) span -= Math.Tau; + var (a0, span) = NormalizeHatchArc(ccw ? start : -start, ccw ? end : -end, ccw); int steps = Math.Clamp((int)Math.Ceiling(span / (Math.PI / 18)), 4, 128); for (int i = 0; i <= steps; i++) { @@ -1345,18 +1342,29 @@ private static void AppendHatchEllipticArc( bool ccw) { double nx = -my * ratio, ny = mx * ratio; - double span = ccw ? (end - start) : (start - end); - while (span <= 0) span += Math.Tau; - while (span > Math.Tau + 1e-9) span -= Math.Tau; + var (a0, span) = NormalizeHatchArc(start, end, ccw); int steps = Math.Clamp((int)Math.Ceiling(span / (Math.PI / 18)), 6, 128); for (int i = 0; i <= steps; i++) { - double t = ccw ? start + span * i / steps : start - span * i / steps; + double t = a0 + (ccw ? span : -span) * i / steps; double c = Math.Cos(t), s = Math.Sin(t); AddEdgePoint(pts, new DwgPoint2D(cx + mx * c + nx * s, cy + my * c + ny * s)); } } + private static (double Start, double Span) NormalizeHatchArc(double start, double end, bool ccw) + { + if (!double.IsFinite(start) || !double.IsFinite(end)) + { + throw new DwgException("HATCH arc angles must be finite."); + } + + start %= Math.Tau; + end %= Math.Tau; + double span = (ccw ? end - start : start - end) % Math.Tau; + return (start, span <= 0 ? span + Math.Tau : span); + } + private static void AppendHatchBulge( List pts, double x1, diff --git a/src/DwgIO/Json/DwgJsonExporter.cs b/src/DwgIO/Json/DwgJsonExporter.cs index f0c1806..38f2467 100644 --- a/src/DwgIO/Json/DwgJsonExporter.cs +++ b/src/DwgIO/Json/DwgJsonExporter.cs @@ -370,6 +370,7 @@ public static void Write(DwgDocument document, Stream output, DwgJsonExportOptio writer.WriteString("patternName", hatch.PatternName); writer.WriteBoolean("isSolidFill", hatch.IsSolidFill); writer.WriteBoolean("isAssociative", hatch.IsAssociative); + writer.WriteNumber("style", hatch.Style); writer.WriteNumber("elevation", double.IsFinite(hatch.Elevation) ? Math.Round(hatch.Elevation, 6) : 0); writer.WriteNumber("loopCount", hatch.Loops.Count); writer.WriteEndObject(); diff --git a/src/DwgIO/Model/DwgHatchData.cs b/src/DwgIO/Model/DwgHatchData.cs index b05f8f9..e85ce0a 100644 --- a/src/DwgIO/Model/DwgHatchData.cs +++ b/src/DwgIO/Model/DwgHatchData.cs @@ -29,6 +29,9 @@ public sealed class DwgHatchData /// True when associated with boundary entities. public bool IsAssociative { get; init; } + /// Island detection style: 0 for normal, 1 for outer, or 2 to ignore islands. + public int Style { get; init; } + /// OCS elevation in drawing units. public double Elevation { get; init; } diff --git a/src/Shared/HatchBoundaries.cs b/src/Shared/HatchBoundaries.cs new file mode 100644 index 0000000..dd84d30 --- /dev/null +++ b/src/Shared/HatchBoundaries.cs @@ -0,0 +1,14 @@ +using DwgIO.Model; + +namespace DwgIO.Scene; + +internal static class HatchBoundaries +{ + public static bool Fills(DwgHatchData hatch, DwgHatchLoop loop) => + loop.IsClosed && loop.Points.Count >= 3 && (hatch.Style switch + { + 1 => (loop.Flags & (1 | 16)) != 0, // External or Outermost + 2 => (loop.Flags & 1) != 0, // External + _ => true, + }); +} diff --git a/src/Shared/TextPlacement.cs b/src/Shared/TextPlacement.cs index 043d149..69c64a8 100644 --- a/src/Shared/TextPlacement.cs +++ b/src/Shared/TextPlacement.cs @@ -13,7 +13,7 @@ public static (int Column, int Row) Alignment(DwgEntityKind kind, double[] geome return (attachment % 3, attachment / 3); } - if (kind != DwgEntityKind.Text || geometry.Length < 9) + if (kind is not (DwgEntityKind.Text or DwgEntityKind.Attrib or DwgEntityKind.AttDef) || geometry.Length < 9) { return (0, kind == DwgEntityKind.MText ? 0 : -1); } diff --git a/tests/DwgIO.Tests/HatchDimensionAttribTests.cs b/tests/DwgIO.Tests/HatchDimensionAttribTests.cs index cb677a0..2b3e6c8 100644 --- a/tests/DwgIO.Tests/HatchDimensionAttribTests.cs +++ b/tests/DwgIO.Tests/HatchDimensionAttribTests.cs @@ -51,7 +51,7 @@ public void PlainText_DecodesUnicodeAndCadSpecialEscapes() } [Fact] - public void Hatch_SolidAndPattern_EmitOutlineAndEarClippedFill_AndStayFlatInAutoMode() + public void Hatch_Solid_EmitsOutlineAndFill_AndStaysFlatInAutoMode() { var solidHatch = new DwgEntity { @@ -89,7 +89,7 @@ public void Hatch_SolidAndPattern_EmitOutlineAndEarClippedFill_AndStayFlatInAuto Assert.Contains(scene.Document.Geometries, g => g.Topology == SceneTopology.Lines); var fill = Assert.Single(scene.Document.Geometries, g => g.Topology == SceneTopology.Triangles); - Assert.Equal(9, fill.Indices.Count); // concave 5-vertex polygon -> 3 triangles + Assert.Equal(9, TriangleArea(fill), precision: 9); Assert.All(fill.Vertices, v => Assert.InRange(v.Z, -0.001, 0.0)); using var htmlStream = new MemoryStream(); @@ -102,12 +102,82 @@ public void Hatch_SolidAndPattern_EmitOutlineAndEarClippedFill_AndStayFlatInAuto svg.Position = 0; var svgPath = Assert.Single(XDocument.Load(svg).Descendants(XName.Get("path", "http://www.w3.org/2000/svg"))); Assert.NotNull(svgPath.Attribute("fill")); + Assert.Equal("evenodd", (string?)svgPath.Attribute("fill-rule")); string json = ToJson(doc); Assert.Contains("\"patternName\":\"SOLID\"", json, StringComparison.Ordinal); Assert.Contains("\"isSolidFill\":true", json, StringComparison.Ordinal); } + [Theory] + [InlineData(0, 88, 24)] + [InlineData(1, 84, 20)] + [InlineData(2, 100, 36)] + public void Hatch_FillRespectsIslandsAndClipsToPaperViewport(int style, double modelArea, double paperArea) + { + const ulong model = 0x1F; + const ulong paper = 0x20; + DwgHatchLoop Square(double min, double max, uint flags) => new() + { + Flags = flags, + Points = [new(min, min), new(max, min), new(max, max), new(min, max)], + }; + var doc = new DwgDocument("hatch-sheet.dwg", Header2018, + [ + new DwgEntity + { + Handle = 0x101, + TypeCode = 0x4E, + TypeName = "HATCH", + Kind = DwgEntityKind.Hatch, + IsModelSpace = true, + Hatch = new DwgHatchData + { + IsSolidFill = true, + Style = style, + Loops = [Square(0, 10, 1), Square(3, 7, 16), Square(4, 6, 0)], + }, + }, + new DwgEntity + { + Handle = 0x102, + TypeCode = 0x22, + TypeName = "VIEWPORT", + Kind = DwgEntityKind.Viewport, + IsModelSpace = false, + OwnerHandle = paper, + Viewport = new DwgViewportData + { + Center = new(100, 200, 0), + Width = 6, + Height = 6, + ViewHeight = 6, + ViewTarget = new(5, 5, 0), + ViewDirection = new(0, 0, 1), + }, + }, + ], blocks: + [ + new DwgBlockInfo { Handle = model, Name = "*Model_Space" }, + new DwgBlockInfo { Handle = paper, Name = "*Paper_Space" }, + ], layouts: + [ + new DwgLayoutInfo { Handle = 0x201, Name = "Plot", BlockHeaderHandle = paper, ViewportHandles = [0x102] }, + ]); + + var scene = DwgSceneReader.Read(doc, new DwgSceneOptions { ModelKey = "hatch-sheet" }); + var modelFill = FillForSheet(scene, isModelSpace: true); + var paperFill = FillForSheet(scene, isModelSpace: false); + + Assert.Equal(modelArea, TriangleArea(modelFill), precision: 9); + Assert.Equal(paperArea, TriangleArea(paperFill), precision: 9); + Assert.All(paperFill.Vertices, point => + { + Assert.InRange(point.X, 97, 103); + Assert.InRange(point.Y, 197, 203); + }); + } + [Fact] public void Dimension_ExpandsAnonymousBlock_AndSupportsFallback() { @@ -176,14 +246,52 @@ public void Dimension_ExpandsAnonymousBlock_AndSupportsFallback() string json = ToJson(doc); Assert.Contains("\"actualMeasurement\":3000", json, StringComparison.Ordinal); - // Without *D block, dimension falls back cleanly to its XLine1..XLine2 line segment. + // Without *D the decoded midpoint and measurement still produce a label. var fallbackDoc = new DwgDocument("dim-fallback.dwg", Header2018, [entities[0]]); var fallbackScene = DwgSceneReader.Read(fallbackDoc, new DwgSceneOptions { LengthUnit = "m", ModelKey = "dim-fallback.dwg" }); Assert.Single(fallbackScene.Document.Geometries, g => g.Topology == SceneTopology.Lines); + var fallbackLabel = Assert.Single(fallbackScene.Annotations); + Assert.Equal("3000", fallbackLabel.Text); + Assert.Equal(new Vector3d(5, 2, 0), fallbackLabel.Position); + Assert.Equal(Assert.Single(fallbackScene.Document.Instances).ElementId, fallbackLabel.ElementId); + + var missingGraphicsDoc = new DwgDocument("dim-empty-block.dwg", Header2018, [entities[0]], blocks: blocks); + var missingGraphics = DwgSceneReader.Read(missingGraphicsDoc, new DwgSceneOptions { ModelKey = "dim-empty-block" }); + Assert.Equal("3000", Assert.Single(missingGraphics.Annotations).Text); + } + + [Theory] + [InlineData("Ten metres", "Ten metres")] + [InlineData("<> m", "10 m")] + [InlineData(" ", null)] + public void DimensionWithoutBlock_UsesOverrideMeasurementOrSuppression(string userText, string? expected) + { + var doc = new DwgDocument("dimension.dwg", Header2018, + [ + new DwgEntity + { + Handle = 0x14, + TypeCode = 0x16, + TypeName = "DIMENSION_ALIGNED", + Kind = DwgEntityKind.Dimension, + Text = userText, + Dimension = new DwgDimensionData { UserText = userText, ActualMeasurement = 10 }, + }, + ]); + + var scene = DwgSceneReader.Read(doc, new DwgSceneOptions { ModelKey = "dimension" }); + if (expected is null) + { + Assert.Empty(scene.Annotations); + } + else + { + Assert.Equal(expected, Assert.Single(scene.Annotations).Text); + } } [Fact] - public void AttribAttDefLeaderAndBlockMarkers_SceneJsonAndSvgIntegration() + public void AttribFollowsOwningInsert_AndInvisibleAttribIsOmitted_InSceneAndSvg() { var entities = new DwgEntity[] { @@ -191,12 +299,21 @@ public void AttribAttDefLeaderAndBlockMarkers_SceneJsonAndSvgIntegration() new() { Handle = 0x31, TypeCode = 0x05, TypeName = "ENDBLK", Kind = DwgEntityKind.EndBlk }, new() { Handle = 0x32, TypeCode = 0x06, TypeName = "SEQEND", Kind = DwgEntityKind.SeqEnd }, new() + { + Handle = 0x36, TypeCode = 0x07, TypeName = "INSERT", Kind = DwgEntityKind.Insert, + BlockHeaderHandle = 0x50, ColorIndex = 1, + Geometry = [30, 40, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0], + }, + new() { Handle = 0x33, TypeCode = 0x02, TypeName = "ATTRIB", Kind = DwgEntityKind.Attrib, - Geometry = [1, 2, 0, 0.5, 0, 1, 0, 0, 0], + IsModelSpace = false, + OwnerHandle = 0x36, + ColorIndex = 0, + Geometry = [31, 42, 0, 0.5, 0, 1, 0, 2, 0], Text = "VISIBLE_VAL", Attrib = new DwgAttribData { Tag = "SHEET", Flags = 0 }, }, @@ -206,6 +323,8 @@ public void AttribAttDefLeaderAndBlockMarkers_SceneJsonAndSvgIntegration() TypeCode = 0x02, TypeName = "ATTRIB", Kind = DwgEntityKind.Attrib, + IsModelSpace = false, + OwnerHandle = 0x36, Geometry = [1, 3, 0, 0.5, 0, 1, 0, 0, 0], Text = "HIDDEN_VAL", Attrib = new DwgAttribData { Tag = "INTERNAL", Flags = 1 }, @@ -218,14 +337,30 @@ public void AttribAttDefLeaderAndBlockMarkers_SceneJsonAndSvgIntegration() Kind = DwgEntityKind.Leader, Geometry = [0, 0, 0, 0, 3, 2, 0, 5, 2, 0], }, + new() + { + Handle = 0x37, TypeCode = 0x13, TypeName = "LINE", Kind = DwgEntityKind.Line, + IsModelSpace = false, OwnerHandle = 0x20, Geometry = [0, 0, 0, 1, 1, 0], + }, }; - var doc = new DwgDocument("attribs.dwg", Header2018, entities); + var doc = new DwgDocument("attribs.dwg", Header2018, entities, blocks: + [ + new DwgBlockInfo { Handle = 0x1F, Name = "*Model_Space" }, + new DwgBlockInfo { Handle = 0x20, Name = "*Paper_Space" }, + new DwgBlockInfo { Handle = 0x50, Name = "Tag" }, + ], layouts: + [ + new DwgLayoutInfo { Handle = 0x201, Name = "Plot", BlockHeaderHandle = 0x20 }, + ]); var scene = DwgSceneReader.Read(doc, new DwgSceneOptions { LengthUnit = "m", ModelKey = "attribs.dwg" }); Assert.Equal(0, scene.EntitiesWithoutGeometry); var ann = Assert.Single(scene.Annotations); Assert.Equal("VISIBLE_VAL", ann.Text); + Assert.Equal("model", ann.SheetKey); + Assert.Equal(new Vector3d(31, 42, 0), ann.Position); + Assert.Equal(new RgbaColor(255, 0, 0), ann.Color); Assert.Single(scene.Document.Geometries, g => g.Topology == SceneTopology.Lines && g.Vertices.Count == 3); string json = ToJson(doc); @@ -237,6 +372,8 @@ public void AttribAttDefLeaderAndBlockMarkers_SceneJsonAndSvgIntegration() var svgDoc = XDocument.Load(svg); var svgText = Assert.Single(svgDoc.Descendants(XName.Get("text", "http://www.w3.org/2000/svg"))); Assert.Equal("VISIBLE_VAL", svgText.Value); + Assert.Equal("end", (string?)svgText.Attribute("text-anchor")); + Assert.Equal("#FF0000", (string?)svgText.Attribute("fill"), ignoreCase: true); Assert.Single(svgDoc.Descendants(XName.Get("path", "http://www.w3.org/2000/svg"))); } @@ -313,6 +450,27 @@ private static byte[] FinalizeR2018RecordNoStrings(RecordBitWriter data, ulong l return full; } + private static SceneGeometry FillForSheet(DwgSceneResult scene, bool isModelSpace) + { + var ids = Assert.Single(scene.Sheets, s => s.IsModelSpace == isModelSpace).ElementIds.ToHashSet(); + var geometryIds = scene.Document.Instances.Where(i => ids.Contains(i.ElementId)).Select(i => i.GeometryId).ToHashSet(); + return Assert.Single(scene.Document.Geometries, g => geometryIds.Contains(g.Id) && g.Topology == SceneTopology.Triangles); + } + + private static double TriangleArea(SceneGeometry fill) + { + double area = 0; + for (int i = 0; i < fill.Indices.Count; i += 3) + { + var a = fill.Vertices[fill.Indices[i]]; + var b = fill.Vertices[fill.Indices[i + 1]]; + var c = fill.Vertices[fill.Indices[i + 2]]; + area += Math.Abs((b.X - a.X) * (c.Y - a.Y) - (b.Y - a.Y) * (c.X - a.X)) / 2; + } + + return area; + } + private static string ToJson(DwgDocument doc) { using var ms = new MemoryStream();