From c5e72e63cea054ebf473a710d7e65b7839743330 Mon Sep 17 00:00:00 2001 From: mahach666 Date: Tue, 1 Dec 2026 17:16:36 +0300 Subject: [PATCH 1/2] feat: decode and render TEXT and MTEXT entities --- CHANGELOG.md | 1 + docs/public-api.md | 2 +- src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs | 50 ++- src/DwgIO.Cli/Export/DwgSvgExporter.cs | 59 +++ src/DwgIO/DwgDocument.cs | 2 +- src/DwgIO/Internal/Parsing/EntityDecoder.cs | 120 +++++- src/DwgIO/Internal/Parsing/LayerParser.cs | 46 +-- .../Internal/Parsing/RecordStringStream.cs | 82 ++++ src/DwgIO/Json/DwgJsonExporter.cs | 9 + src/DwgIO/Model/DwgEntity.cs | 100 +++++ tests/DwgIO.Tests/TextEntitiesTests.cs | 383 ++++++++++++++++++ 11 files changed, 791 insertions(+), 63 deletions(-) create mode 100644 src/DwgIO/Internal/Parsing/RecordStringStream.cs create mode 100644 tests/DwgIO.Tests/TextEntitiesTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 65bc6f9..79932c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ API between minor releases. ## [Unreleased] ### Added +- `TEXT` (`0x01`) and `MTEXT` (`0x2C`) decoding (`DwgEntityKind.Text`, `DwgEntityKind.MText`, `DwgEntity.Text`, `DwgEntity.PlainText` formatting stripper) and text rendering across `DwgJsonExporter`, `DwgSvgExporter`, `dwgio inspect`/`entities`, and the 2D HTML viewer. - `LAYER` (`0x33`) table decoding (`DwgLayerInfo`, `DwgDocument.Layers`, `DwgReaderOptions.ReadLayers`) and entity `LayerHandle` / `LayerName` / `EffectiveColorIndex` / `EffectiveTrueColorRgb` `BYLAYER` colour resolution across `DwgIO`, `DwgIO.Scene`, JSON export, SVG, `dwgio inspect` and the 2D HTML viewer (with interactive layer visibility chips). - `AcDb:Header` parsing (`DwgHeaderVariables`, `DwgInsUnits`, `DwgPoint2D`, `DwgPoint3D`, `DwgDocument.HeaderVariables`, `DwgReaderOptions.ReadHeader`) exposing `$INSUNITS`, `$MEASUREMENT`, extents/limits, units formatting, point style (`$PDMODE`/`$PDSIZE`), linetype/text/dim scales, timestamps, `$HANDSEED`, and GUIDs in JSON export, `dwgio inspect`, `DwgSceneOptions.UseDrawingUnits` and the 2D HTML viewer. - `AcDb:Classes` parsing (`DwgClassInfo`, `DwgDocument.Classes`, `DwgReaderOptions.ReadClasses`) resolving class names (codes 500+) and `IsEntity` flags in `DwgObjectInfo`, JSON export and `dwgio inspect`. diff --git a/docs/public-api.md b/docs/public-api.md index 115a53c..3fdf1c1 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -38,7 +38,7 @@ change in any release and is visible only to the test project through `Internals | `DwgObjectInfo`, `DwgHandle` | One record of the object stream: offset, size, type code (`TypeName` resolves fixed names and `AcDb:Classes` names) and handle. | | `DwgClassInfo` | One class definition from `AcDb:Classes` (codes 500+): `ClassNumber`, `AppName`, `CppClassName`, `DxfName`, `ItemClassId`, `IsEntity`, `InstanceCount`. | | `DwgLayerInfo` | One layer record (`0x33`) from `AcDb:AcDbObjects`: `Handle`, `Name`, `ColorIndex`, `TrueColorRgb`, `IsFrozen`, `IsOff`/`IsOn`, `IsLocked`, `IsPlottable`, `LineWeight` and `IsVisible`. | -| `DwgEntity`, `DwgEntityKind` | A decoded entity with its handle, type, colour (`ColorIndex`, `TrueColorRgb`, and BYLAYER-resolved `EffectiveColorIndex`/`EffectiveTrueColorRgb`), layer (`LayerHandle`, `LayerName`), linetype scale, `IsModelSpace` flag and decoded `Geometry` for LINE, CIRCLE, ARC, POINT, LWPOLYLINE, ELLIPSE, SOLID/TRACE, 3DFACE, RAY and XLINE. | +| `DwgEntity`, `DwgEntityKind` | A decoded entity with its handle, type, colour (`ColorIndex`, `TrueColorRgb`, and BYLAYER-resolved `EffectiveColorIndex`/`EffectiveTrueColorRgb`), layer (`LayerHandle`, `LayerName`), linetype scale, `IsModelSpace` flag, `Text`/`PlainText` and decoded `Geometry` for LINE, CIRCLE, ARC, POINT, LWPOLYLINE, ELLIPSE, SOLID/TRACE, 3DFACE, RAY, XLINE, TEXT and MTEXT. | | `DwgDocument.AppInfoHistory` | Decompressed bytes of `AcDb:AppInfoHistory` when available. The record layout is unknown. | | `DwgRevHistory` | The save references of `AcDb:RevHistory`: layout version pair and one value per recorded save. | | `DwgAuxHeader` | The auxiliary header of `AcDb:AuxHeader`: version pair, save counter, creation and last-update times, next handle. | diff --git a/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs b/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs index 8e51606..4e372fe 100644 --- a/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs +++ b/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs @@ -149,6 +149,11 @@ private static string BuildPayloadJson(DwgDocument document, DwgViewerOptions op w.WriteNumber("lineTypeScale", double.IsFinite(entity.LineTypeScale) ? Math.Round(entity.LineTypeScale, 6) : 1.0); w.WriteBoolean("modelSpace", entity.IsModelSpace); + if (entity.PlainText is { } textValue) + { + w.WriteString("text", textValue); + } + w.WriteStartArray("geom"); foreach (double v in entity.Geometry) { @@ -264,6 +269,12 @@ private static bool TryExpandBounds(DwgEntity entity, ref double minX, ref doubl case (DwgEntityKind.Ray or DwgEntityKind.XLine, [var rx, var ry, _, _, _, _]): Expand(rx, ry, ref minX, ref minY, ref maxX, ref maxY); return true; + case (DwgEntityKind.Text or DwgEntityKind.MText, { Length: >= 5 } g): + double th = Math.Max(Math.Abs(g[3]), 0.1); + double approxW = Math.Max(th, (entity.PlainText?.Length ?? 1) * th * 0.6); + Expand(g[0], g[1], ref minX, ref minY, ref maxX, ref maxY); + Expand(g[0] + approxW, g[1] + th, ref minX, ref minY, ref maxX, ref maxY); + return true; default: return false; } @@ -1137,6 +1148,35 @@ function drawEntity(entity, w, h, overrideColor, lineWidth) { ctx.lineTo(sx2, sy2); ctx.stroke(); ctx.restore(); + } else if (entity.kind === 'text' || entity.kind === 'mtext') { + const content = entity.text || ''; + if (!content) return; + const th = g[3] > 0 ? g[3] : 1; + const hPx = th * cam.scale; + if (hPx < 0.7 || !Number.isFinite(hPx)) return; + const [sx, sy] = worldToScreen(g[0], g[1], w, h); + const rot = g[4] || 0; + const lines = content.split('\n'); + ctx.save(); + ctx.translate(sx, sy); + if (Math.abs(rot) > 1e-6) ctx.rotate(-rot); + ctx.fillStyle = color; + ctx.font = `${hPx}px ui-sans-serif, system-ui, sans-serif`; + if (entity.kind === 'mtext') { + const att = g[6] || 1; + const col = (att - 1) % 3; + const row = Math.floor((att - 1) / 3); + ctx.textAlign = col === 1 ? 'center' : col === 2 ? 'right' : 'left'; + ctx.textBaseline = row === 1 ? 'middle' : row === 2 ? 'bottom' : 'top'; + } else { + ctx.textAlign = 'left'; + ctx.textBaseline = 'alphabetic'; + } + const lineStep = hPx * 1.25; + for (let li = 0; li < lines.length; li++) { + ctx.fillText(lines[li], 0, li * lineStep); + } + ctx.restore(); } } @@ -1258,6 +1298,9 @@ function hitTest(wx, wy) { d = Math.hypot(wx - g[0], wy - g[1]); } } + } else if (e.kind === 'text' || e.kind === 'mtext') { + const th = Math.max(g[3] || 1, 0.1); + d = Math.hypot(wx - g[0], wy - g[1]) <= th * 1.5 ? 0 : Math.hypot(wx - g[0], wy - g[1]); } if (d <= bestDist) { bestDist = d; @@ -1327,6 +1370,11 @@ function renderProps(e) { } else if (e.kind === 'ray' || e.kind === 'xline') { rows.push([t('position'), `(${fmt(g[0])}, ${fmt(g[1])}, ${fmt(g[2])})`]); rows.push(['Direction', `(${fmt(g[3])}, ${fmt(g[4])}, ${fmt(g[5])})`]); + } else if (e.kind === 'text' || e.kind === 'mtext') { + rows.push([t('position'), `(${fmt(g[0])}, ${fmt(g[1])}, ${fmt(g[2])})`]); + rows.push(['Height', fmt(g[3])]); + rows.push(['Rotation', `${fmt((g[4] || 0) * 180 / Math.PI)}°`]); + if (e.text) rows.push(['Text', e.text]); } propsGrid.innerHTML = ''; @@ -1403,7 +1451,7 @@ function renderList() { const e = entities[i]; if (!isEntityVisible(e)) continue; if (activeType !== 'ALL' && e.type !== activeType) continue; - if (q && !e.type.toLowerCase().includes(q) && !e.handle.toLowerCase().includes(q) && !(e.layer || '').toLowerCase().includes(q)) continue; + if (q && !e.type.toLowerCase().includes(q) && !e.handle.toLowerCase().includes(q) && !(e.layer || '').toLowerCase().includes(q) && !(e.text || '').toLowerCase().includes(q)) continue; const row = document.createElement('div'); row.className = 'entity-row' + (i === selectedIndex ? ' selected' : ''); const swatch = document.createElement('span'); diff --git a/src/DwgIO.Cli/Export/DwgSvgExporter.cs b/src/DwgIO.Cli/Export/DwgSvgExporter.cs index 249b0c3..e9b2822 100644 --- a/src/DwgIO.Cli/Export/DwgSvgExporter.cs +++ b/src/DwgIO.Cli/Export/DwgSvgExporter.cs @@ -127,6 +127,43 @@ public static void Write(DwgDocument document, XmlWriter writer, DwgSvgOptions? writer.WriteAttributeString("r", Num(markerRadius)); writer.WriteAttributeString("fill", stroke); writer.WriteAttributeString("stroke", "none"); + writer.WriteEndElement(); + break; + case SvgText label: + writer.WriteStartElement("text"); + writer.WriteAttributeString("x", Num(label.X)); + writer.WriteAttributeString("y", Num(label.Y)); + writer.WriteAttributeString("font-size", Num(label.Height)); + writer.WriteAttributeString("font-family", "sans-serif"); + writer.WriteAttributeString("fill", stroke); + writer.WriteAttributeString("stroke", "none"); + if (Math.Abs(label.RotationRad) > 1e-6) + { + double deg = -label.RotationRad * 180.0 / Math.PI; + writer.WriteAttributeString("transform", FormattableString.Invariant($"rotate({Num(deg)} {Num(label.X)} {Num(label.Y)})")); + } + + string[] lines = label.Text.Split('\n'); + if (lines.Length == 1) + { + writer.WriteString(lines[0]); + } + else + { + for (int li = 0; li < lines.Length; li++) + { + writer.WriteStartElement("tspan"); + writer.WriteAttributeString("x", Num(label.X)); + if (li > 0) + { + writer.WriteAttributeString("dy", Num(label.Height * 1.25)); + } + + writer.WriteString(lines[li]); + writer.WriteEndElement(); + } + } + writer.WriteEndElement(); break; } @@ -154,6 +191,10 @@ private sealed record SvgPoint(double X, double Y, int ColorIndex, uint? TrueCol private sealed record SvgPath(string Data, IReadOnlyList<(double X, double Y)> BoundsPoints, bool Fill, int ColorIndex, uint? TrueColorRgb) : SvgShape(ColorIndex, TrueColorRgb); + private sealed record SvgText( + double X, double Y, double Height, double RotationRad, string Text, int ColorIndex, uint? TrueColorRgb) + : SvgShape(ColorIndex, TrueColorRgb); + private static List Collect(DwgDocument document, DwgSvgOptions options) { double scale = options.Scale; @@ -246,6 +287,20 @@ private static List Collect(DwgDocument document, DwgSvgOptions option Skip(options.ReportDiagnostic, entity, "non-finite coordinates"); } + break; + case (DwgEntityKind.Text or DwgEntityKind.MText, { Length: >= 5 } g): + if (IsUsable(g[0] * scale, g[1] * scale, g[3] * scale, g[4]) && g[3] > 0 && entity.PlainText is { Length: > 0 } plain) + { + shapes.Add(new SvgText( + g[0] * scale, + -g[1] * scale, + g[3] * scale, + g[4], + plain, + entity.EffectiveColorIndex, + entity.EffectiveTrueColorRgb)); + } + break; } } @@ -414,6 +469,10 @@ private static (double MinX, double MinY, double Width, double Height) ViewBox(L case SvgPoint point: Expand(point.X, point.Y); break; + case SvgText label: + Expand(label.X, label.Y); + Expand(label.X + label.Height * Math.Max(1, label.Text.Length) * 0.6, label.Y - label.Height); + break; } } diff --git a/src/DwgIO/DwgDocument.cs b/src/DwgIO/DwgDocument.cs index f879d6e..b696a4c 100644 --- a/src/DwgIO/DwgDocument.cs +++ b/src/DwgIO/DwgDocument.cs @@ -727,7 +727,7 @@ private List ReadOptionalEntities( try { - if (EntityDecoder.Decode(info, _objectStreamBytes, year, isEntity, layersByHandle) is { } entity) + if (EntityDecoder.Decode(info, _objectStreamBytes, year, isEntity, layersByHandle, FileHeader.Codepage) is { } entity) { entities.Add(entity); } diff --git a/src/DwgIO/Internal/Parsing/EntityDecoder.cs b/src/DwgIO/Internal/Parsing/EntityDecoder.cs index 2c3ffad..ed74764 100644 --- a/src/DwgIO/Internal/Parsing/EntityDecoder.cs +++ b/src/DwgIO/Internal/Parsing/EntityDecoder.cs @@ -27,7 +27,8 @@ internal static class EntityDecoder byte[] stream, int year, bool forceEntity = false, - IReadOnlyDictionary? layersByHandle = null) + IReadOnlyDictionary? layersByHandle = null, + ushort codepage = 30) { if (!forceEntity && !IsEntityCode(info.TypeCode)) { @@ -75,14 +76,18 @@ internal static class EntityDecoder reader.ReadPackedInt(); // transparency } + RecordStringStream? strings = null; + RecordStringStream GetStrings() => + strings ??= RecordStringStream.Open(info, stream, year, codepage, handleStreamBits, reader.PositionBit, info.TypeName); + if ((colorFlags & 0x41) == 0x41) { - SkipText(reader, year); + _ = GetStrings().Read(reader, info.TypeName, year); } if ((colorFlags & 0x42) == 0x42) { - SkipText(reader, year); + _ = GetStrings().Read(reader, info.TypeName, year); } double lineTypeScale = reader.ReadPackedDouble(); @@ -100,17 +105,19 @@ internal static class EntityDecoder reader.ReadPackedShort(); // invisibility reader.ReadRawByte(); // lineweight (R2000+) - (DwgEntityKind kind, double[]? geometry)? body = info.TypeCode switch + (DwgEntityKind kind, double[]? geometry, string? text)? body = info.TypeCode switch { - 0x11 => DecodeArc(reader), - 0x12 => DecodeCircle(reader), - 0x13 => DecodeLine(reader), - 0x1B => DecodePoint(reader), - 0x1C => DecodeFace3d(reader), - 0x1F or 0x20 => DecodeSolidOrTrace(reader), - 0x23 => DecodeEllipse(reader), - 0x28 or 0x29 => DecodeRayOrXLine(reader, info.TypeCode == 0x28 ? DwgEntityKind.Ray : DwgEntityKind.XLine), - 0x4D => DecodeLwPolyline(reader, year), + 0x01 => DecodeText(reader, GetStrings(), year), + 0x11 => WithNoText(DecodeArc(reader)), + 0x12 => WithNoText(DecodeCircle(reader)), + 0x13 => WithNoText(DecodeLine(reader)), + 0x1B => WithNoText(DecodePoint(reader)), + 0x1C => WithNoText(DecodeFace3d(reader)), + 0x1F or 0x20 => WithNoText(DecodeSolidOrTrace(reader)), + 0x23 => WithNoText(DecodeEllipse(reader)), + 0x28 or 0x29 => WithNoText(DecodeRayOrXLine(reader, info.TypeCode == 0x28 ? DwgEntityKind.Ray : DwgEntityKind.XLine)), + 0x2C => DecodeMText(reader, GetStrings(), year), + 0x4D => WithNoText(DecodeLwPolyline(reader, year)), _ => null, }; @@ -134,6 +141,7 @@ internal static class EntityDecoder TypeName = info.TypeName, Kind = body?.kind ?? DwgEntityKind.Unknown, Geometry = body?.geometry, + Text = body?.text, ColorIndex = colorIndex, TrueColorRgb = trueColorRgb, LineTypeScale = lineTypeScale, @@ -145,6 +153,9 @@ internal static class EntityDecoder }; } + private static (DwgEntityKind kind, double[]? geometry, string? text) WithNoText((DwgEntityKind kind, double[] geometry) item) => + (item.kind, item.geometry, null); + private static ulong? TryReadLayerHandle( BitReaderMsb reader, DwgObjectInfo info, @@ -241,17 +252,90 @@ internal static void SkipExtendedData(BitReaderMsb reader) throw new DwgException("Extended data loop exceeded 256 iterations; payload is malformed."); } - private static void SkipText(BitReaderMsb reader, int year) + private static (DwgEntityKind, double[], string) DecodeText(BitReaderMsb reader, RecordStringStream strings, int year) + { + byte dataFlags = reader.ReadRawByte(); + double elevation = (dataFlags & 0x01) == 0 ? reader.ReadRawDouble() : 0.0; + double insX = reader.ReadRawDouble(); + double insY = reader.ReadRawDouble(); + bool hasAlign = (dataFlags & 0x02) == 0; + double alignX = hasAlign ? reader.ReadRawDouble() : insX; + double alignY = hasAlign ? reader.ReadRawDouble() : insY; + + _ = ReadExtrusion(reader); + _ = ReadThickness(reader); + double oblique = (dataFlags & 0x04) == 0 ? reader.ReadRawDouble() : 0.0; + double rotation = (dataFlags & 0x08) == 0 ? reader.ReadRawDouble() : 0.0; + double height = reader.ReadRawDouble(); + double widthFactor = (dataFlags & 0x10) == 0 ? reader.ReadRawDouble() : 1.0; + + string text = strings.Read(reader, "TEXT", year); + + if ((dataFlags & 0x20) == 0) + { + _ = reader.ReadPackedShort(); // generation + } + + short horizAlign = (dataFlags & 0x40) == 0 ? (short)reader.ReadPackedShort() : (short)0; + short vertAlign = (dataFlags & 0x80) == 0 ? (short)reader.ReadPackedShort() : (short)0; + + // When alignment is specified (neither Left/Baseline nor Aligned/Fit), AutoCAD anchors at alignmentPt. + bool useAlign = hasAlign && (horizAlign != 0 || vertAlign != 0) && horizAlign is not (3 or 5); + double x = useAlign ? alignX : insX; + double y = useAlign ? alignY : insY; + + return (DwgEntityKind.Text, [x, y, elevation, height, rotation, widthFactor, oblique], text); + } + + private static (DwgEntityKind, double[], string) DecodeMText(BitReaderMsb reader, RecordStringStream strings, int year) { - int length = (int)reader.ReadPackedShort(); + double x = reader.ReadPackedDouble(); + double y = reader.ReadPackedDouble(); + double z = reader.ReadPackedDouble(); + + _ = reader.ReadPackedDouble(); + _ = reader.ReadPackedDouble(); + _ = reader.ReadPackedDouble(); // 3BD extrusion + + double xAxisX = reader.ReadPackedDouble(); + double xAxisY = reader.ReadPackedDouble(); + _ = reader.ReadPackedDouble(); // 3BD XAxisDir + + double rectWidth = reader.ReadPackedDouble(); if (year >= 2007) { - reader.SkipBytes(length * 2); + _ = reader.ReadPackedDouble(); // RectHeight } - else + + double textHeight = reader.ReadPackedDouble(); + uint attachment = reader.ReadPackedShort(); + _ = reader.ReadPackedShort(); // DrawingDir + _ = reader.ReadPackedDouble(); // ExtentsHeight + _ = reader.ReadPackedDouble(); // ExtentsWidth + + string text = strings.Read(reader, "MTEXT", year); + + _ = reader.ReadPackedShort(); // LinespacingStyle + _ = reader.ReadPackedDouble(); // LinespacingFactor + _ = reader.ReadBit(); // Unknown + if (year >= 2004) { - reader.SkipBytes(length); + uint bgFlags = reader.ReadPackedInt(); + if ((bgFlags & 0x01) != 0) + { + _ = reader.ReadPackedDouble(); // BackgroundScaleFactor + _ = reader.ReadPackedShort(); + _ = reader.ReadPackedInt(); + _ = reader.ReadRawByte(); + if ((bgFlags & 0x02) == 0) + { + _ = reader.ReadPackedInt(); + } + } } + + double rotation = Math.Atan2(xAxisY, xAxisX); + return (DwgEntityKind.MText, [x, y, z, textHeight, rotation, rectWidth, attachment], text); } private static double ReadThickness(BitReaderMsb reader) => reader.ReadBit() ? 0.0 : reader.ReadPackedDouble(); diff --git a/src/DwgIO/Internal/Parsing/LayerParser.cs b/src/DwgIO/Internal/Parsing/LayerParser.cs index ac8cf09..63a558f 100644 --- a/src/DwgIO/Internal/Parsing/LayerParser.cs +++ b/src/DwgIO/Internal/Parsing/LayerParser.cs @@ -1,4 +1,3 @@ -using System.Text; using DwgIO.Internal.Container; using DwgIO.Model; @@ -33,41 +32,8 @@ public static DwgLayerInfo Parse(DwgObjectInfo info, byte[] stream, int year, us _ = reader.ReadBit(); // has AcDs binary data } - Encoding encoding = MetadataByteCursor.GetEncoding(codepage); - BitReaderMsb? stringReader = null; - int stringEndBit = 0; - if (year >= 2007) - { - long totalPayloadBits = info.BitsLength * 8L; - if (handleStreamBits > (ulong)totalPayloadBits || totalPayloadBits - (long)handleStreamBits < 17) - { - throw new DwgException($"LAYER {info.Handle:X}: invalid R2007+ string/handle stream framing."); - } - - int dataEndBit = (int)(totalPayloadBits - (long)handleStreamBits); - var tailReader = new BitReaderMsb(stream[info.BitsStart..(info.BitsStart + info.BitsLength)]); - tailReader.SeekBit(dataEndBit - 1); - bool hasStrings = tailReader.ReadBit(); - if (hasStrings) - { - var lenReader = new BitReaderMsb(stream[info.BitsStart..(info.BitsStart + info.BitsLength)]); - lenReader.SeekBit(dataEndBit - 17); - int stringBits = lenReader.ReadRawByte() | (lenReader.ReadRawByte() << 8); - int stringStart = dataEndBit - 17 - stringBits; - if (stringStart < reader.PositionBit) - { - throw new DwgException($"LAYER {info.Handle:X}: string stream start {stringStart} overlaps data bits."); - } - - stringEndBit = dataEndBit - 17; - stringReader = new BitReaderMsb(stream[info.BitsStart..(info.BitsStart + info.BitsLength)]); - stringReader.SeekBit(stringStart); - } - } - - string name = stringReader is not null - ? (stringReader.PositionBit < stringEndBit ? stringReader.ReadUtf16String("LAYER") : string.Empty) - : reader.ReadCodepageString(encoding, "LAYER"); + var strings = RecordStringStream.Open(info, stream, year, codepage, handleStreamBits, reader.PositionBit, "LAYER"); + string name = strings.Read(reader, "LAYER", year); bool hasNoXrefIndex = reader.ReadBit(); // 64-flag if (!hasNoXrefIndex) @@ -121,16 +87,12 @@ public static DwgLayerInfo Parse(DwgObjectInfo info, byte[] stream, int year, us byte colorFlags = reader.ReadRawByte(); if ((colorFlags & 1) != 0) { - _ = stringReader is not null - ? (stringReader.PositionBit < stringEndBit ? stringReader.ReadUtf16String("LAYER") : string.Empty) - : reader.ReadCodepageString(encoding, "LAYER"); + _ = strings.Read(reader, "LAYER", year); } if ((colorFlags & 2) != 0) { - _ = stringReader is not null - ? (stringReader.PositionBit < stringEndBit ? stringReader.ReadUtf16String("LAYER") : string.Empty) - : reader.ReadCodepageString(encoding, "LAYER"); + _ = strings.Read(reader, "LAYER", year); } } diff --git a/src/DwgIO/Internal/Parsing/RecordStringStream.cs b/src/DwgIO/Internal/Parsing/RecordStringStream.cs new file mode 100644 index 0000000..55e83af --- /dev/null +++ b/src/DwgIO/Internal/Parsing/RecordStringStream.cs @@ -0,0 +1,82 @@ +using System.Text; +using DwgIO.Internal.Container; +using DwgIO.Model; + +namespace DwgIO.Internal.Parsing; + +/// +/// Reads inline codepage strings (R2004) or separate UTF-16LE string-stream strings (R2007+) +/// from an AcDb:AcDbObjects record. +/// +internal sealed class RecordStringStream +{ + private readonly BitReaderMsb? _stringReader; + private readonly int _stringEndBit; + private readonly Encoding _encoding; + + private RecordStringStream(BitReaderMsb? stringReader, int stringEndBit, Encoding encoding) + { + _stringReader = stringReader; + _stringEndBit = stringEndBit; + _encoding = encoding; + } + + public static RecordStringStream Open( + DwgObjectInfo info, + byte[] stream, + int year, + ushort codepage, + ulong handleStreamBits, + int minDataBit, + string recordLabel) + { + Encoding encoding = MetadataByteCursor.GetEncoding(codepage); + if (year < 2007) + { + return new RecordStringStream(null, 0, encoding); + } + + long totalPayloadBits = info.BitsLength * 8L; + if (handleStreamBits > (ulong)totalPayloadBits || totalPayloadBits - (long)handleStreamBits < 17) + { + throw new DwgException($"{recordLabel} {info.Handle:X}: invalid R2007+ string/handle stream framing."); + } + + int dataEndBit = (int)(totalPayloadBits - (long)handleStreamBits); + var slice = stream[info.BitsStart..(info.BitsStart + info.BitsLength)]; + var tailReader = new BitReaderMsb(slice); + tailReader.SeekBit(dataEndBit - 1); + if (!tailReader.ReadBit()) + { + return new RecordStringStream(null, 0, encoding); + } + + var lenReader = new BitReaderMsb(slice); + lenReader.SeekBit(dataEndBit - 17); + int stringBits = lenReader.ReadRawByte() | (lenReader.ReadRawByte() << 8); + int stringStart = dataEndBit - 17 - stringBits; + if (stringStart < minDataBit) + { + throw new DwgException($"{recordLabel} {info.Handle:X}: string stream start {stringStart} overlaps data bits."); + } + + var stringReader = new BitReaderMsb(slice); + stringReader.SeekBit(stringStart); + return new RecordStringStream(stringReader, dataEndBit - 17, encoding); + } + + public string Read(BitReaderMsb dataReader, string context, int year) + { + if (year >= 2007) + { + if (_stringReader is null || _stringReader.PositionBit >= _stringEndBit) + { + return string.Empty; + } + + return _stringReader.ReadUtf16String(context); + } + + return dataReader.ReadCodepageString(_encoding, context); + } +} diff --git a/src/DwgIO/Json/DwgJsonExporter.cs b/src/DwgIO/Json/DwgJsonExporter.cs index 2c94a25..26490ec 100644 --- a/src/DwgIO/Json/DwgJsonExporter.cs +++ b/src/DwgIO/Json/DwgJsonExporter.cs @@ -320,6 +320,15 @@ public static void Write(DwgDocument document, Stream output, DwgJsonExportOptio writer.WriteNumber("effectiveColorIndex", resolvedColor); } + if (entity.Text is { } rawText) + { + writer.WriteString("text", rawText); + if (entity.PlainText is { } plainText && plainText != rawText) + { + writer.WriteString("plainText", plainText); + } + } + writer.WriteEndObject(); } diff --git a/src/DwgIO/Model/DwgEntity.cs b/src/DwgIO/Model/DwgEntity.cs index 71ded8d..1b399ec 100644 --- a/src/DwgIO/Model/DwgEntity.cs +++ b/src/DwgIO/Model/DwgEntity.cs @@ -37,6 +37,12 @@ public enum DwgEntityKind /// XLINE: infinite construction line (base point + unit direction). XLine, + + /// TEXT: single-line text annotation (position, height, rotation, width factor, oblique). + Text, + + /// MTEXT: multiline text annotation (position, height, rotation, reference width, attachment). + MText, } /// @@ -68,6 +74,8 @@ public sealed class DwgEntity /// : [cx, cy, cz, mx, my, mz, ratio, startRad, endRad] /// / : [x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4] /// / : [x, y, z, dx, dy, dz] + /// : [x, y, elevation, height, rotationRad, widthFactor, obliqueRad] + /// : [x, y, z, height, rotationRad, rectWidth, attachment] /// /// Null for non-decoded kinds. /// @@ -104,6 +112,12 @@ public sealed class DwgEntity /// Effective 24-bit true colour: uses entity true colour, else resolves BYLAYER (256) to . public uint? EffectiveTrueColorRgb => TrueColorRgb ?? (ColorIndex == 256 ? LayerTrueColorRgb : null); + /// 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); + /// One-line description: type, handle and decoded geometry. public override string ToString() => Kind switch @@ -126,6 +140,92 @@ 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 => + string.Create(CultureInfo.InvariantCulture, $"{TypeName} {Handle:X}: ({g[0]:F3},{g[1]:F3},{g[2]:F3}) h={g[3]:F3} \"{PlainText}\""), _ => $"{TypeName} {Handle:X}", }; + + private static string StripMTextFormatting(string raw) + { + if (raw.IndexOf('\\') < 0 && raw.IndexOf('{') < 0 && raw.IndexOf('}') < 0) + { + return raw; + } + + var sb = new System.Text.StringBuilder(raw.Length); + for (int i = 0; i < raw.Length; i++) + { + char c = raw[i]; + if (c is '{' or '}') + { + continue; + } + + if (c != '\\' || i + 1 >= raw.Length) + { + sb.Append(c); + continue; + } + + char next = raw[i + 1]; + switch (next) + { + case 'P': + case 'p': + sb.Append('\n'); + i++; + break; + case '~': + sb.Append(' '); + i++; + break; + case '\\': + case '{': + case '}': + sb.Append(next); + i++; + break; + case 'L': + case 'l': + case 'O': + case 'o': + case 'K': + case 'k': + i++; + break; + case 'S': + case 's': + { + int semi = raw.IndexOf(';', i + 2); + if (semi > i + 2) + { + sb.Append(raw.AsSpan(i + 2, semi - i - 2).ToString().Replace('^', '/')); + i = semi; + } + else + { + i++; + } + + break; + } + default: + { + int semi = raw.IndexOf(';', i + 2); + if (semi > i + 1 && semi - i <= 128) + { + i = semi; + } + else + { + i++; + } + + break; + } + } + } + + return sb.ToString(); + } } diff --git a/tests/DwgIO.Tests/TextEntitiesTests.cs b/tests/DwgIO.Tests/TextEntitiesTests.cs new file mode 100644 index 0000000..12d3ed2 --- /dev/null +++ b/tests/DwgIO.Tests/TextEntitiesTests.cs @@ -0,0 +1,383 @@ +using System.Text; +using System.Text.Json; +using DwgIO.Export; +using DwgIO.Internal.Parsing; +using DwgIO.Model; +using Xunit; + +namespace DwgIO.Tests; + +public class TextEntitiesTests +{ + [Fact] + public void DecodeText_R2018AndR2004_ExtractsPositionHeightRotationAndString() + { + byte[] stream2018 = BuildSyntheticTextStream( + r2010Plus: true, + handle: 0x50, + insX: 12.5, + insY: 25.0, + elevation: 3.0, + rotationRad: Math.PI / 4, + height: 2.5, + widthFactor: 0.85, + obliqueRad: 0.1, + textValue: "Level 1 Plan", + layerHandle: 0x3C); + + var layer = new DwgLayerInfo { Handle = 0x3C, Name = "Annotations", ColorIndex = 3 }; + var layers = new Dictionary { [0x3C] = layer }; + var info = new DwgObjectInfo + { + StreamOffset = 0, + SizeBytes = (uint)stream2018.Length, + TypeCode = 0x01, + Handle = 0x50, + StreamHandle = new DwgHandle(0, 1, 0x50), + BitsStart = 0, + BitsLength = stream2018.Length, + }; + + var entity = EntityDecoder.Decode(info, stream2018, year: 2018, layersByHandle: layers); + Assert.NotNull(entity); + Assert.Equal(DwgEntityKind.Text, entity!.Kind); + Assert.Equal("Level 1 Plan", entity.Text); + Assert.Equal("Level 1 Plan", entity.PlainText); + Assert.Equal("Annotations", entity.LayerName); + Assert.NotNull(entity.Geometry); + Assert.Equal([12.5, 25.0, 3.0, 2.5, Math.PI / 4, 0.85, 0.1], entity.Geometry!); + Assert.Contains("Level 1 Plan", entity.ToString(), StringComparison.Ordinal); + + // Alignment anchor test in R2004 inline mode (DataFlags omits elevation/oblique/rotation, sets HorizAlign=1 -> uses AlignPt). + byte[] stream2004 = BuildSyntheticAlignedR2004TextStream( + handle: 0x51, + insX: 0, + insY: 0, + alignX: 40.0, + alignY: 50.0, + height: 4.0, + horizAlign: 1, + textValue: "Centered"); + var info2004 = new DwgObjectInfo + { + StreamOffset = 0, + SizeBytes = (uint)stream2004.Length, + TypeCode = 0x01, + Handle = 0x51, + StreamHandle = new DwgHandle(0, 1, 0x51), + BitsStart = 0, + BitsLength = stream2004.Length, + }; + + var aligned = EntityDecoder.Decode(info2004, stream2004, year: 2004); + Assert.NotNull(aligned); + Assert.Equal(DwgEntityKind.Text, aligned!.Kind); + Assert.Equal("Centered", aligned.Text); + Assert.Equal(40.0, aligned.Geometry![0]); + Assert.Equal(50.0, aligned.Geometry![1]); + Assert.Equal(4.0, aligned.Geometry![3]); + } + + [Fact] + public void DecodeMText_R2018_StripsFormattingAndExportsJsonSvgAndHtml() + { + const string formatted = @"{\fArial|b0|i0;Room 101\P\C1;Area 42\~m\S1^2;}"; + byte[] stream = BuildSyntheticMTextStream( + handle: 0x60, + x: 10.0, + y: 20.0, + z: 0.0, + xAxisX: 0.0, + xAxisY: 1.0, // rotated 90 deg CCW + rectWidth: 30.0, + textHeight: 2.0, + attachment: 5, + textValue: formatted); + + var info = new DwgObjectInfo + { + StreamOffset = 0, + SizeBytes = (uint)stream.Length, + TypeCode = 0x2C, + Handle = 0x60, + StreamHandle = new DwgHandle(0, 1, 0x60), + BitsStart = 0, + BitsLength = stream.Length, + }; + + var mtext = EntityDecoder.Decode(info, stream, year: 2018); + Assert.NotNull(mtext); + Assert.Equal(DwgEntityKind.MText, mtext!.Kind); + Assert.Equal(formatted, mtext.Text); + Assert.Equal("Room 101\nArea 42 m1/2", mtext.PlainText); + Assert.Equal(10.0, mtext.Geometry![0]); + Assert.Equal(20.0, mtext.Geometry![1]); + Assert.Equal(2.0, mtext.Geometry![3]); + Assert.Equal(Math.PI / 2, mtext.Geometry![4], 9); + Assert.Equal(30.0, mtext.Geometry![5]); + Assert.Equal(5.0, mtext.Geometry![6]); + + var doc = new DwgDocument( + "text.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1032", + Release = "R2018", + Family = DwgContainerFamily.R2004Family, + Year = 2018, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + [mtext]); + + using var jsonDoc = JsonDocument.Parse(doc.ToJson()); + var entJson = jsonDoc.RootElement.GetProperty("entities")[0]; + Assert.Equal(formatted, entJson.GetProperty("text").GetString()); + Assert.Equal("Room 101\nArea 42 m1/2", entJson.GetProperty("plainText").GetString()); + + using var svgStream = new MemoryStream(); + DwgSvgExporter.Write(doc, svgStream); + string svg = Encoding.UTF8.GetString(svgStream.ToArray()); + Assert.Contains("= 2010) + { + w.WriteTwoBits(0); + w.WriteRawByte((byte)typeCode); + } + else + { + WritePackedShort(w, typeCode); + } + + w.WriteRawByte(0x01); // handle code 0, cnt 1 + w.WriteRawByte((byte)handle); + w.WriteTwoBits(2); // XDATA end + w.WriteBit(false); // no graphics preview + w.WriteTwoBits(isModelSpace ? 2u : 1u); // entity mode + w.WriteTwoBits(2); // reactor count = 0 + w.WriteBit(true); // no extension dictionary + if (year >= 2013) + { + w.WriteBit(false); // hasAcDs + } + + w.WriteTwoBits(2); // color index = 0 (BYBLOCK) + w.WriteTwoBits(1); // linetype scale = 1.0 + w.WriteTwoBits(0); // linetype flags + w.WriteTwoBits(0); // plotstyle flags + w.WriteTwoBits(0); // material flags + w.WriteRawByte(0); // shadow flags + if (year >= 2010) + { + w.WriteBit(false); + w.WriteBit(false); + w.WriteBit(false); + } + + w.WriteTwoBits(2); // invisibility = 0 + w.WriteRawByte(0); // lineweight + } + + private static byte[] FinalizeR2018Record(RecordBitWriter data, string textValue, ulong layerHandle) + { + var strWriter = new RecordBitWriter(); + byte[] utf16 = Encoding.Unicode.GetBytes(textValue); + WritePackedShort(strWriter, (ushort)textValue.Length); + foreach (byte b in utf16) + { + strWriter.WriteRawByte(b); + } + + int stringBits = strWriter.BitsUsed; + foreach (bool bit in GetBits(strWriter.ToArray(), stringBits)) + { + data.WriteBit(bit); + } + + data.WriteRawByte((byte)(stringBits & 0xFF)); + data.WriteRawByte((byte)(stringBits >> 8)); + data.WriteBit(true); // hasStrings + + int totalBeforeHandles = data.BitsUsed; + data.WriteRawByte(0x51); // Layer handle code 5, cnt 1 + 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 void WritePackedShort(RecordBitWriter w, ushort value) + { + if (value == 0) + { + w.WriteTwoBits(2); + } + else if (value <= 255) + { + w.WriteTwoBits(1); + w.WriteRawByte((byte)value); + } + else + { + w.WritePackedShortRaw(value); + } + } + + private static void WritePackedDouble(RecordBitWriter w, double value) + { + if (value == 0.0) + { + w.WriteTwoBits(2); + } + else if (value == 1.0) + { + w.WriteTwoBits(1); + } + else + { + w.WriteTwoBits(0); + w.WriteRawDouble(value); + } + } + + private static void WriteAscii(RecordBitWriter w, string value) + { + WritePackedShort(w, (ushort)value.Length); + foreach (byte b in Encoding.ASCII.GetBytes(value)) + { + w.WriteRawByte(b); + } + } + + private static IEnumerable GetBits(byte[] bytes, int bitCount) + { + for (int i = 0; i < bitCount; i++) + { + yield return ((bytes[i >> 3] >> (7 - (i & 7))) & 1) != 0; + } + } +} From 6dd5bca0ca11efe0eab0ac12dc8f6a9206daaf24 Mon Sep 17 00:00:00 2001 From: mahach666 Date: Wed, 2 Dec 2026 13:00:25 +0300 Subject: [PATCH 2/2] Decode aligned TEXT coordinates and preserve text placement --- docs/test-fixtures.md | 4 +- src/DwgIO.Cli/DwgIO.Cli.csproj | 2 +- src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs | 36 +++++++-------- .../Compatibility/DwgSvgExporter.cs | 24 ++++++++-- src/DwgIO.Scene/DwgIO.Scene.csproj | 2 +- src/DwgIO/Internal/Parsing/EntityDecoder.cs | 6 +-- src/DwgIO/Model/DwgEntity.cs | 2 +- src/Shared/TextPlacement.cs | 42 ++++++++++++++++++ test-files/public/README.md | 25 +++++++++-- test-files/public/text-aligned-ac1032.dwg | Bin 0 -> 8363 bytes tests/DwgIO.Tests/DwgIO.Tests.csproj | 2 +- tests/DwgIO.Tests/TextEntitiesTests.cs | 29 +++++++++++- 12 files changed, 139 insertions(+), 35 deletions(-) create mode 100644 src/Shared/TextPlacement.cs create mode 100644 test-files/public/text-aligned-ac1032.dwg diff --git a/docs/test-fixtures.md b/docs/test-fixtures.md index c91303a..7e9c805 100644 --- a/docs/test-fixtures.md +++ b/docs/test-fixtures.md @@ -8,7 +8,7 @@ repository. ## Where the drawings are looked for -The required `PublicDrawing_DecodesAuthoredPrimitives` theory reads only the three committed drawings, copied +The required public fixture tests read the committed drawings, copied to a dedicated subfolder of the test output at build time. This works even when `--artifacts-path` places the assembly outside the checkout. @@ -30,7 +30,7 @@ planned release does not fail every test. Optional fixture checks are reported as **skipped with a reason** when no eligible drawing is available. If no drawing is found, the reason names `DWGIO_TEST_FILES`. The attributes `[SkippableFact]` and `[SkippableTheory]` (`SkippableFact.cs`) report `SkipException` as a skip, because xunit 2.9 has no runtime skip -of its own. The public geometry theory requires all three committed drawings and fails if any is missing +of its own. The public fixture tests fail if a required drawing is missing from the test output. No test uses a fixed absolute path. diff --git a/src/DwgIO.Cli/DwgIO.Cli.csproj b/src/DwgIO.Cli/DwgIO.Cli.csproj index 4f23f78..23576bf 100644 --- a/src/DwgIO.Cli/DwgIO.Cli.csproj +++ b/src/DwgIO.Cli/DwgIO.Cli.csproj @@ -17,7 +17,7 @@ - diff --git a/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs b/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs index f44b0c6..332423c 100644 --- a/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs +++ b/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs @@ -115,7 +115,8 @@ private static string BuildPayloadJson(DwgDocument document, DwgViewerOptions op continue; } - if (!TryExpandBounds(entity, ref minX, ref minY, ref maxX, ref maxY, out var ellipseMinor)) + string? textValue = entity.PlainText; + if (!TryExpandBounds(entity, textValue, ref minX, ref minY, ref maxX, ref maxY, out var ellipseMinor)) { continue; } @@ -149,9 +150,12 @@ private static string BuildPayloadJson(DwgDocument document, DwgViewerOptions op w.WriteNumber("lineTypeScale", double.IsFinite(entity.LineTypeScale) ? Math.Round(entity.LineTypeScale, 6) : 1.0); w.WriteBoolean("modelSpace", entity.IsModelSpace); - if (entity.PlainText is { } textValue) + if (textValue is not null) { w.WriteString("text", textValue); + var (column, row) = TextPlacement.Alignment(entity.Kind, entity.Geometry); + w.WriteNumber("textColumn", column); + w.WriteNumber("textRow", row); } if (ellipseMinor is { } minor) @@ -218,7 +222,7 @@ private static string BuildPayloadJson(DwgDocument document, DwgViewerOptions op } private static bool TryExpandBounds( - DwgEntity entity, ref double minX, ref double minY, ref double maxX, ref double maxY, + DwgEntity entity, string? text, ref double minX, ref double minY, ref double maxX, ref double maxY, out (double X, double Y, double Z)? ellipseMinor) { ellipseMinor = null; @@ -279,11 +283,11 @@ private static bool TryExpandBounds( case (DwgEntityKind.Ray or DwgEntityKind.XLine, [var rx, var ry, _, _, _, _]): Expand(rx, ry, ref minX, ref minY, ref maxX, ref maxY); return true; - case (DwgEntityKind.Text or DwgEntityKind.MText, { Length: >= 5 } g): - double th = Math.Max(Math.Abs(g[3]), 0.1); - double approxW = Math.Max(th, (entity.PlainText?.Length ?? 1) * th * 0.6); - Expand(g[0], g[1], ref minX, ref minY, ref maxX, ref maxY); - Expand(g[0] + approxW, g[1] + th, ref minX, ref minY, ref maxX, ref maxY); + case (DwgEntityKind.Text or DwgEntityKind.MText, { Length: >= 5 } g) when g[3] > 0 && text is { Length: > 0 }: + var (column, row) = TextPlacement.Alignment(entity.Kind, g); + var textBounds = TextPlacement.EstimateBounds(g[0], -g[1], g[3], g[4], text, column, row); + Expand(textBounds.MinX, -textBounds.MaxY, ref minX, ref minY, ref maxX, ref maxY); + Expand(textBounds.MaxX, -textBounds.MinY, ref minX, ref minY, ref maxX, ref maxY); return true; default: return false; @@ -1172,19 +1176,13 @@ function drawEntity(entity, w, h, overrideColor, lineWidth) { if (Math.abs(rot) > 1e-6) ctx.rotate(-rot); ctx.fillStyle = color; ctx.font = `${hPx}px ui-sans-serif, system-ui, sans-serif`; - if (entity.kind === 'mtext') { - const att = g[6] || 1; - const col = (att - 1) % 3; - const row = Math.floor((att - 1) / 3); - ctx.textAlign = col === 1 ? 'center' : col === 2 ? 'right' : 'left'; - ctx.textBaseline = row === 1 ? 'middle' : row === 2 ? 'bottom' : 'top'; - } else { - ctx.textAlign = 'left'; - ctx.textBaseline = 'alphabetic'; - } + const col = entity.textColumn, row = entity.textRow; + ctx.textAlign = col === 1 ? 'center' : col === 2 ? 'right' : 'left'; + ctx.textBaseline = row === 0 ? 'top' : row === 1 ? 'middle' : row === 2 ? 'bottom' : 'alphabetic'; const lineStep = hPx * 1.25; + const firstBaseline = row > 0 ? -(lines.length - 1) * lineStep * row / 2 : 0; for (let li = 0; li < lines.length; li++) { - ctx.fillText(lines[li], 0, li * lineStep); + ctx.fillText(lines[li], 0, firstBaseline + li * lineStep); } ctx.restore(); } diff --git a/src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs b/src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs index 37c54bb..3a35be3 100644 --- a/src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs +++ b/src/DwgIO.Scene/Compatibility/DwgSvgExporter.cs @@ -134,6 +134,14 @@ public static void Write(DwgDocument document, XmlWriter writer, DwgSvgOptions? writer.WriteAttributeString("y", Num(label.Y)); writer.WriteAttributeString("font-size", Num(label.Height)); writer.WriteAttributeString("font-family", "sans-serif"); + writer.WriteAttributeString("text-anchor", label.Column switch { 1 => "middle", 2 => "end", _ => "start" }); + writer.WriteAttributeString("dominant-baseline", label.Row switch + { + 0 => "text-before-edge", + 1 => "central", + 2 => "text-after-edge", + _ => "alphabetic", + }); writer.WriteAttributeString("fill", stroke); writer.WriteAttributeString("stroke", "none"); if (Math.Abs(label.RotationRad) > 1e-6) @@ -143,6 +151,11 @@ public static void Write(DwgDocument document, XmlWriter writer, DwgSvgOptions? } string[] lines = label.Text.Split('\n'); + if (label.Row > 0 && lines.Length > 1) + { + writer.WriteAttributeString("dy", Num(-(lines.Length - 1) * label.Height * 1.25 * label.Row / 2)); + } + if (lines.Length == 1) { writer.WriteString(lines[0]); @@ -191,7 +204,7 @@ private sealed record SvgPath(string Data, IReadOnlyList<(double X, double Y)> B : SvgShape(ColorIndex, TrueColorRgb); private sealed record SvgText( - double X, double Y, double Height, double RotationRad, string Text, int ColorIndex, uint? TrueColorRgb) + double X, double Y, double Height, double RotationRad, string Text, int Column, int Row, int ColorIndex, uint? TrueColorRgb) : SvgShape(ColorIndex, TrueColorRgb); private static List Collect(DwgDocument document, DwgSvgOptions options) @@ -290,12 +303,15 @@ private static List Collect(DwgDocument document, DwgSvgOptions option case (DwgEntityKind.Text or DwgEntityKind.MText, { Length: >= 5 } g): 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); shapes.Add(new SvgText( g[0] * scale, -g[1] * scale, g[3] * scale, g[4], plain, + column, + row, entity.EffectiveColorIndex, entity.EffectiveTrueColorRgb)); } @@ -467,8 +483,10 @@ private static (double MinX, double MinY, double Width, double Height) ViewBox(L Expand(point.X, point.Y); break; case SvgText label: - Expand(label.X, label.Y); - Expand(label.X + label.Height * Math.Max(1, label.Text.Length) * 0.6, label.Y - label.Height); + var textBounds = TextPlacement.EstimateBounds( + label.X, label.Y, label.Height, label.RotationRad, label.Text, label.Column, label.Row); + Expand(textBounds.MinX, textBounds.MinY); + Expand(textBounds.MaxX, textBounds.MaxY); break; } } diff --git a/src/DwgIO.Scene/DwgIO.Scene.csproj b/src/DwgIO.Scene/DwgIO.Scene.csproj index c130957..6a9cc65 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 bccd13f..d22706e 100644 --- a/src/DwgIO/Internal/Parsing/EntityDecoder.cs +++ b/src/DwgIO/Internal/Parsing/EntityDecoder.cs @@ -259,8 +259,8 @@ private static (DwgEntityKind, double[], string) DecodeText(BitReaderMsb reader, double insX = reader.ReadRawDouble(); double insY = reader.ReadRawDouble(); bool hasAlign = (dataFlags & 0x02) == 0; - double alignX = hasAlign ? reader.ReadRawDouble() : insX; - double alignY = hasAlign ? reader.ReadRawDouble() : insY; + double alignX = hasAlign ? reader.ReadDoubleWithDefault(insX) : insX; + double alignY = hasAlign ? reader.ReadDoubleWithDefault(insY) : insY; _ = ReadExtrusion(reader); _ = ReadThickness(reader); @@ -284,7 +284,7 @@ private static (DwgEntityKind, double[], string) DecodeText(BitReaderMsb reader, double x = useAlign ? alignX : insX; double y = useAlign ? alignY : insY; - return (DwgEntityKind.Text, [x, y, elevation, height, rotation, widthFactor, oblique], text); + return (DwgEntityKind.Text, [x, y, elevation, height, rotation, widthFactor, oblique, horizAlign, vertAlign], text); } private static (DwgEntityKind, double[], string) DecodeMText(BitReaderMsb reader, RecordStringStream strings, int year) diff --git a/src/DwgIO/Model/DwgEntity.cs b/src/DwgIO/Model/DwgEntity.cs index b7370b1..04202ad 100644 --- a/src/DwgIO/Model/DwgEntity.cs +++ b/src/DwgIO/Model/DwgEntity.cs @@ -74,7 +74,7 @@ public sealed class DwgEntity /// : [cx, cy, cz, mx, my, mz, ratio, startRad, endRad, nx, ny, nz] /// / : [x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4] /// / : [x, y, z, dx, dy, dz] - /// : [x, y, elevation, height, rotationRad, widthFactor, obliqueRad] + /// : [x, y, elevation, height, rotationRad, widthFactor, obliqueRad, horizontalAlignment, verticalAlignment] /// : [x, y, z, height, rotationRad, rectWidth, attachment] /// /// Null for non-decoded kinds. diff --git a/src/Shared/TextPlacement.cs b/src/Shared/TextPlacement.cs new file mode 100644 index 0000000..043d149 --- /dev/null +++ b/src/Shared/TextPlacement.cs @@ -0,0 +1,42 @@ +using DwgIO.Model; + +namespace DwgIO.Scene; + +internal static class TextPlacement +{ + // Columns run left to right, rows run top to bottom. Row -1 is the text baseline. + public static (int Column, int Row) Alignment(DwgEntityKind kind, double[] geometry) + { + if (kind == DwgEntityKind.MText && geometry.Length >= 7 && geometry[6] is >= 1 and <= 9) + { + int attachment = (int)geometry[6] - 1; + return (attachment % 3, attachment / 3); + } + + if (kind != DwgEntityKind.Text || geometry.Length < 9) + { + return (0, kind == DwgEntityKind.MText ? 0 : -1); + } + + int column = geometry[7] switch { 1 or 4 => 1, 2 => 2, _ => 0 }; + int row = geometry[8] switch { 1 => 2, 2 => 1, 3 => 0, _ => geometry[7] == 4 ? 1 : -1 }; + return (column, row); + } + + public static (double MinX, double MinY, double MaxX, double MaxY) EstimateBounds( + double x, double y, double height, double rotation, string text, int column, int row) + { + string[] lines = text.Split('\n'); + double width = height * Math.Max(1, lines.Max(line => line.Length)) * 0.6; + double blockHeight = height * (1 + 1.25 * (lines.Length - 1)); + double left = -width * column / 2; + double top = row < 0 ? -height : -blockHeight * row / 2; + double cos = Math.Cos(rotation), sin = Math.Sin(rotation); + double centerX = left + width / 2, centerY = top + blockHeight / 2; + double projectedX = x + centerX * cos + centerY * sin; + double projectedY = y - centerX * sin + centerY * cos; + double halfWidth = (width * Math.Abs(cos) + blockHeight * Math.Abs(sin)) / 2; + double halfHeight = (width * Math.Abs(sin) + blockHeight * Math.Abs(cos)) / 2; + return (projectedX - halfWidth, projectedY - halfHeight, projectedX + halfWidth, projectedY + halfHeight); + } +} diff --git a/test-files/public/README.md b/test-files/public/README.md index 5234741..6da53ec 100644 --- a/test-files/public/README.md +++ b/test-files/public/README.md @@ -57,6 +57,26 @@ above identify the committed drawings, not all equivalent regenerations. Validat geometry with DwgIO before replacing a file, then update the recorded hash. These fixtures exercise the independent writer's output, not every DWG writer or entity kind. +### Right-aligned TEXT + +`text-aligned-ac1032.dwg` is an original MIT-licensed drawing created for the TEXT alignment regression test +with the same ACadSharp 3.8.35 writer. Its SHA-256 is +`e1ffab79f12b9eee13047be11ca02d42675ab78c7859af267dda0861b633690d`. +It contains one model-space TEXT on layer `0`, with insertion point (1, 2, 0), alignment point (20, 10, 0), +height 2 and right alignment. To regenerate it with the console project above, replace the primitive loop with: + +```csharp +var drawing = new CadDocument(ACadVersion.AC1032); +drawing.Entities.Add(new TextEntity("Right aligned") +{ + InsertPoint = new XYZ(1, 2, 0), + AlignmentPoint = new XYZ(20, 10, 0), + Height = 2, + HorizontalAlignment = TextHorizontalAlignment.Right, +}); +DwgWriter.Write("text-aligned-ac1032.dwg", drawing); +``` + ## How a drawing qualifies Before committing a file, record here, next to the file name: @@ -73,6 +93,5 @@ see `docs/test-fixtures.md`) remains the place for larger local test sets. For optional fixture checks, `TestFiles` looks in `DWGIO_TEST_FILES`, ancestor `test_files` and `test-files/public` folders, and one level of subfolders. Unsupported versions are skipped and counted; -checks with no eligible drawing are skipped. The required `PublicDrawing_DecodesAuthoredPrimitives` theory -instead reads the three committed files copied into the test output at build time. A missing copy fails -that theory even when no private drawings are configured. +checks with no eligible drawing are skipped. The required public fixture tests read the files copied into +the test output at build time. A missing copy fails its test even when no private drawings are configured. diff --git a/test-files/public/text-aligned-ac1032.dwg b/test-files/public/text-aligned-ac1032.dwg new file mode 100644 index 0000000000000000000000000000000000000000..3d139dddf1e29221bc8405ad8561d054ddf62123 GIT binary patch literal 8363 zcmeG>eOwgRwdc;v?#vFm%K(ckpUy5ID}F70M~%!b3oNk0tSkf#=mHA?T#+DJOo$m2 zl_;7uHGRexlQlt#tIab_O?-__H$Kza#8i@JnlGD>mS+=98k^X}zF2){h_CPW+Vr)5 zyylPodgpiUoO|cqbM8I&+;i@^<0#0p&zcEp8ly*90Lxg$cP!D6{{NY` zNLN39AotkE=AXy><~PrNaOvHlw-;^JFMcR%g&|G*Oz}HU#VKrg?iBqw`f z-MN>p9eS;BVS?d4KJD!%W=`KH|JvU@_xBH!%>3+~drHnfR$=<2Z$Qpk29|pwK3mXYkYIUj5}J+eO_8Ra$C!KxtfJlO9PId$N|R=1Ql0d z{b$DJX)k~910ZMbo|yUjcjg~j+0$~oeD$oA0SX%64WWfV!YKXu#qY-tzpyXC#hi(e zLZwn$WYD5@gaXN!%}J4kl9^I~XTYV4L?Yoe6s=qf5-`GS$z%S7O#Re!2AvNqj=g_A*7@Yw=qlb=aJikpE!~8N zEBO(}rgMcA-_7{uf4Ujk9tBC>enhYR&Rz59k;7}RHaEg8Qozl{;<}CH_nRdEt(n0> zz0ysAwpVn=v+nphSD%-*UB8k4!;wVuL?eKl%ZQ?m0QlC&g4jbKpXL$)s(f&_X?pQ{ zod?7W)776ee>&w26ZioX0rYm@ZrsSfarVZiH?H@`v}oMA4oy|oR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using System.Text; using System.Text.Json; +using System.Xml.Linq; using DwgIO.Export; using DwgIO.Internal.Parsing; using DwgIO.Model; +using DwgIO.Scene; using Xunit; namespace DwgIO.Tests; @@ -45,7 +47,7 @@ public void DecodeText_R2018AndR2004_ExtractsPositionHeightRotationAndString() Assert.Equal("Level 1 Plan", entity.PlainText); Assert.Equal("Annotations", entity.LayerName); Assert.NotNull(entity.Geometry); - Assert.Equal([12.5, 25.0, 3.0, 2.5, Math.PI / 4, 0.85, 0.1], entity.Geometry!); + Assert.Equal([12.5, 25.0, 3.0, 2.5, Math.PI / 4, 0.85, 0.1, 0.0, 0.0], entity.Geometry!); Assert.Contains("Level 1 Plan", entity.ToString(), StringComparison.Ordinal); // Alignment anchor test in R2004 inline mode (DataFlags omits elevation/oblique/rotation, sets HorizAlign=1 -> uses AlignPt). @@ -78,6 +80,29 @@ public void DecodeText_R2018AndR2004_ExtractsPositionHeightRotationAndString() Assert.Equal(4.0, aligned.Geometry![3]); } + [Fact] + public void PublicDrawing_RightAlignedTextPreservesItsAnchorInSvgAndHtml() + { + var document = DwgDocument.Open(TestFiles.PublicDrawing("text-aligned-ac1032.dwg")); + var text = Assert.Single(document.Entities, entity => entity.Kind == DwgEntityKind.Text); + Assert.Equal("Right aligned", text.PlainText); + Assert.Equal([20.0, 10.0, 0.0, 2.0, 0.0, 1.0, 0.0, 2.0, 0.0], text.Geometry!); + + using var svg = new MemoryStream(); + DwgSvgExporter.Write(document, svg); + svg.Position = 0; + var label = Assert.Single(XDocument.Load(svg).Descendants(XName.Get("text", "http://www.w3.org/2000/svg"))); + Assert.Equal("20", (string?)label.Attribute("x")); + Assert.Equal("-10", (string?)label.Attribute("y")); + Assert.Equal("2", (string?)label.Attribute("font-size")); + Assert.Equal("end", (string?)label.Attribute("text-anchor")); + + using var html = new MemoryStream(); + DwgCadHtmlViewer.Export(document, html, new DwgViewerOptions(), "m"); + string content = Encoding.UTF8.GetString(html.ToArray()); + Assert.Contains("\"text\":\"Right aligned\",\"textColumn\":2", content, StringComparison.Ordinal); + } + [Fact] public void DecodeMText_R2018_StripsFormattingAndExportsJsonSvgAndHtml() { @@ -208,7 +233,9 @@ private static byte[] BuildSyntheticAlignedR2004TextStream( w.WriteRawByte(0xBD); w.WriteRawDouble(insX); w.WriteRawDouble(insY); + w.WriteTwoBits(3); // full double relative to the insertion X w.WriteRawDouble(alignX); + w.WriteTwoBits(3); // full double relative to the insertion Y w.WriteRawDouble(alignY); w.WriteBit(true); // Extrusion default w.WriteBit(true); // Thickness 0