From a153bb764abda7b4b024d7c7947c9d60a6422acd Mon Sep 17 00:00:00 2001 From: mahach666 Date: Tue, 1 Dec 2026 14:17:34 +0300 Subject: [PATCH 1/2] feat: decode AcDb:Header variables and wire INSUNITS/PDMODE --- CHANGELOG.md | 1 + docs/public-api.md | 7 +- src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs | 16 +- src/DwgIO.Cli/Export/DwgViewerExport.cs | 3 +- src/DwgIO.Cli/Program.cs | 14 +- src/DwgIO.Scene/DwgSceneOptions.cs | 13 +- src/DwgIO.Scene/DwgSceneReader.cs | 18 +- src/DwgIO/DwgDocument.cs | 34 +- src/DwgIO/DwgReaderOptions.cs | 3 + src/DwgIO/Internal/Container/BitReaderMsb.cs | 51 ++ src/DwgIO/Internal/Parsing/ClassesParser.cs | 47 +- src/DwgIO/Internal/Parsing/HeaderParser.cs | 470 +++++++++++++++++++ src/DwgIO/Json/DwgJsonExporter.cs | 54 +++ src/DwgIO/Model/DwgHeaderVariables.cs | 199 ++++++++ tests/DwgIO.Tests/HeaderVariablesTests.cs | 376 +++++++++++++++ 15 files changed, 1249 insertions(+), 57 deletions(-) create mode 100644 src/DwgIO/Internal/Parsing/HeaderParser.cs create mode 100644 src/DwgIO/Model/DwgHeaderVariables.cs create mode 100644 tests/DwgIO.Tests/HeaderVariablesTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index f1c6f9d..e31742a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ API between minor releases. ## [Unreleased] ### Added +- `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`. - Entity geometry decoding for `LWPOLYLINE` (including bulges and elevation), `ELLIPSE`, `SOLID`/`TRACE`, `3DFACE`, `RAY`, `XLINE` and 24-bit `TrueColorRgb` across `DwgIO`, `DwgIO.Scene`, SVG and the 2D AutoCAD HTML viewer. - `DwgReaderOptions`: `Strict`, `MaxFileBytes`, `MaxSectionBytes`, `MaxDecompressedBytes`, `MaxObjectCount`, diff --git a/docs/public-api.md b/docs/public-api.md index b9642c2..66c224f 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -12,8 +12,8 @@ change in any release and is visible only to the test project through `Internals | Type | Use | |---|---| -| `DwgDocument` | Opens a drawing (`Open` / `OpenAsync` from path or stream) and gives `SourcePath` (null for streams), `Path`, `Version`, file and container headers, section catalog, metadata, handle map, object inventory, entities and `Diagnostics`. `ReadSection(name)` returns decompressed section bytes; `ReleaseSectionBuffers()` drops retained raw buffers; `SaveJson` / `ToJson` write JSON. | -| `DwgReaderOptions` | What `Open` reads and enforces: `ReadSectionMap`, `ReadSummaryInfo`, `ReadMetadata`, `ReadObjects`, `ReadEntities`, `VerifyChecksums`, `Strict` (throws on diagnostics), `ReleaseSectionBuffers`, `MaxFileBytes`, `MaxSectionBytes`, `MaxDecompressedBytes`, `MaxObjectCount`, `Progress` and `DiagnosticOutput`. | +| `DwgDocument` | Opens a drawing (`Open` / `OpenAsync` from path or stream) and gives `SourcePath` (null for streams), `Path`, `Version`, file and container headers, header variables (`HeaderVariables`), section catalog, metadata, handle map, object inventory, entities and `Diagnostics`. `ReadSection(name)` returns decompressed section bytes; `ReleaseSectionBuffers()` drops retained raw buffers; `SaveJson` / `ToJson` write JSON. | +| `DwgReaderOptions` | What `Open` reads and enforces: `ReadSectionMap`, `ReadSummaryInfo`, `ReadMetadata`, `ReadHeader`, `ReadClasses`, `ReadObjects`, `ReadEntities`, `VerifyChecksums`, `Strict` (throws on diagnostics), `ReleaseSectionBuffers`, `MaxFileBytes`, `MaxSectionBytes`, `MaxDecompressedBytes`, `MaxObjectCount`, `Progress` and `DiagnosticOutput`. | | `DwgReadProgress` | Synchronous phase updates (`Phase`, `Completed`, `Total`) delivered via `DwgReaderOptions.Progress`. | | `DwgExitCodes` | Standard CLI exit codes (`Ok = 0`, `Usage = 1`, `FileNotFound = 2`, `UnsupportedVersion = 3`, `ParseError = 4`, `NoPreview = 5`). | | `DwgException` | Thrown for a damaged or truncated file, exceeded reader limits, `Strict` diagnostic failures, and by `ReadSection` when buffers were released or a section is missing. | @@ -41,6 +41,7 @@ change in any release and is visible only to the test project through `Internals | `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. | +| `DwgHeaderVariables`, `DwgInsUnits`, `DwgPoint2D`, `DwgPoint3D` | Drawing system variables from `AcDb:Header`: `$INSUNITS` (`TryGetSceneUnit`), `$MEASUREMENT`, `$EXTMIN`/`$EXTMAX`, `$LIMMIN`/`$LIMMAX`, `$LUNITS`/`$LUPREC`, `$AUNITS`/`$AUPREC`, `$PDMODE`/`$PDSIZE`, `$LTSCALE`/`$CELTSCALE`/`$DIMSCALE`, `$CELWEIGHT`, `$TDCREATE`/`$TDUPDATE`, `$HANDSEED`, `$FINGERPRINTGUID` and `$VERSIONGUID`. | | `DwgTemplate` | The template description of `AcDb:Template`: description and unit system (English/metric). | ## JSON export (`DwgIO.Json`) @@ -73,7 +74,7 @@ line and point geometry in metres, ACI colours on placements and a report in `Dw | Type | Use | |---|---| | `DwgSceneReader` | `Read(path, options?)` opens and converts a drawing file (releasing raw section buffers automatically); `Read(stream, documentName?, options?)` converts a drawing from a stream; `Read(document, options)` converts an already opened `DwgDocument` (which needs `ModelKey`). | -| `DwgSceneOptions` | `LengthUnit` (`mm`, `cm`, `m`, `ft`, `in`; default `m`), `ModelKey`, and `ReadProgress` (`IProgress?`). | +| `DwgSceneOptions` | `LengthUnit` (`mm`, `cm`, `m`, `ft`, `in`; default `m`), `UseDrawingUnits` (prefers `$INSUNITS` when supported), `ModelKey`, and `ReadProgress` (`IProgress?`). | | `DwgSceneResult` | The `Document` (an `IOScene.SceneDocument`), `Diagnostics`, element and geometry counters, the applied `MetresPerUnit` and `UnitAssumed`. | ```csharp diff --git a/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs b/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs index 763f4e6..bb28b6c 100644 --- a/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs +++ b/src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs @@ -60,6 +60,13 @@ private static string BuildPayloadJson(DwgDocument document, DwgViewerOptions op w.WriteString("title", title); w.WriteString("version", document.Version.ToString()); w.WriteString("unit", lengthUnit); + if (document.HeaderVariables is { } header) + { + w.WriteNumber("pdmode", header.PdMode); + w.WriteNumber("pdsize", double.IsFinite(header.PdSize) ? header.PdSize : 0.0); + w.WriteString("insunits", header.InsUnits.ToString()); + } + w.WriteString("theme", options.Theme switch { DwgCadTheme.Slate => "slate", @@ -672,7 +679,13 @@ private static void Expand(double x, double y, ref double minX, ref double minY, let theme = data.theme || 'black'; let showGrid = true; let showCrosshair = true; - let pointStyle = 'target'; + let pointStyle = (() => { + const pm = typeof data.pdmode === 'number' ? data.pdmode : 0; + if ((pm & 0x20) !== 0 || (pm & 0x0F) === 3) return 'target'; + if (pm === 1) return 'dot'; + if (pm === 0 || (pm & 0x0F) === 2) return 'target'; + return 'target'; + })(); let activeType = 'ALL'; let searchQuery = ''; let selectedIndex = -1; @@ -1423,6 +1436,7 @@ function renderList() { }); new ResizeObserver(resizeCanvas).observe(canvas); + selPoint.value = pointStyle; applyTexts(); applyTheme(theme); requestAnimationFrame(() => { diff --git a/src/DwgIO.Cli/Export/DwgViewerExport.cs b/src/DwgIO.Cli/Export/DwgViewerExport.cs index bfccaa1..b429314 100644 --- a/src/DwgIO.Cli/Export/DwgViewerExport.cs +++ b/src/DwgIO.Cli/Export/DwgViewerExport.cs @@ -49,7 +49,7 @@ public static DwgSceneResult SaveViewer( } else { - AtomicOutput.Write(htmlPath, stream => DwgCadHtmlViewer.Export(document, stream, viewerOptions, sceneOptions.LengthUnit)); + AtomicOutput.Write(htmlPath, stream => DwgCadHtmlViewer.Export(document, stream, viewerOptions, result.LengthUnit ?? sceneOptions.LengthUnit)); } return result; @@ -83,6 +83,7 @@ private static DwgSceneOptions ViewerOptionsFor(string path, DwgSceneOptions? op return new DwgSceneOptions { LengthUnit = options?.LengthUnit ?? "m", + UseDrawingUnits = options?.UseDrawingUnits ?? false, ModelKey = Path.GetFileName(path), ReadProgress = options?.ReadProgress, }; diff --git a/src/DwgIO.Cli/Program.cs b/src/DwgIO.Cli/Program.cs index f583276..67b811e 100644 --- a/src/DwgIO.Cli/Program.cs +++ b/src/DwgIO.Cli/Program.cs @@ -180,6 +180,12 @@ internal static int InspectDocument(DwgDocument doc, TextWriter output) output.WriteLine($"Template: \"{Truncate(template.Description, 60)}\" units={units}"); } + if (doc.HeaderVariables is { } hv) + { + output.WriteLine( + $"Header: insunits={hv.InsUnits} lunits={hv.LUnits} pdmode={hv.PdMode} ltscale={Plain(hv.LtScale)} handseed={hv.Handseed:X}"); + } + if (doc.Preview is { } preview) { output.WriteLine($"Preview: {preview.ImageKind} {Count(preview.ImageBytes.Length)} bytes"); @@ -355,7 +361,9 @@ internal static int ExportDocument( return DwgExitCodes.Usage; } - var sceneOptions = unit is null ? null : new DwgSceneOptions { LengthUnit = unit }; + var sceneOptions = unit is null + ? new DwgSceneOptions { UseDrawingUnits = true } + : new DwgSceneOptions { LengthUnit = unit }; if (Path.GetExtension(target).Equals(".obj", StringComparison.OrdinalIgnoreCase)) { @@ -503,6 +511,10 @@ private static int Scene(string[] args, TextWriter output, TextWriter error) options.LengthUnit = unit; } + else + { + options.UseDrawingUnits = true; + } var result = DwgSceneReader.Read(positional[0], options); AtomicOutput.Write(positional[1], stream => SceneJson.Write(result.Document, stream)); diff --git a/src/DwgIO.Scene/DwgSceneOptions.cs b/src/DwgIO.Scene/DwgSceneOptions.cs index 4b69965..a40ab1c 100644 --- a/src/DwgIO.Scene/DwgSceneOptions.cs +++ b/src/DwgIO.Scene/DwgSceneOptions.cs @@ -6,12 +6,19 @@ public sealed class DwgSceneOptions /// /// Length unit of the drawing's coordinates and the scale the conversion applies, as one value: /// mm, cm, m (the default, one drawing unit = one metre), ft or in. - /// A DWG stores plain numbers without a unit; the header variable that names the unit is not decoded yet, - /// so the unit is a caller decision. The scene records the choice in - /// and reports it in . + /// Used when is , or as the fallback when + /// $INSUNITS is unitless or not mapped to a scene unit. The scene records the choice in + /// and reports it in . /// public string LengthUnit { get; set; } = "m"; + /// + /// When , prefers $INSUNITS from + /// whenever it maps to a supported scene unit (mm, cm, m, ft, or in), + /// and sets to . Defaults to . + /// + public bool UseDrawingUnits { get; set; } + /// /// Key of the scene model: stable, unique and non-empty, written to . The /// default is the source file name without directory. A key must be given when a document converted from memory diff --git a/src/DwgIO.Scene/DwgSceneReader.cs b/src/DwgIO.Scene/DwgSceneReader.cs index 929c8ab..ba4ba30 100644 --- a/src/DwgIO.Scene/DwgSceneReader.cs +++ b/src/DwgIO.Scene/DwgSceneReader.cs @@ -95,7 +95,17 @@ public static DwgSceneResult Read(DwgDocument document, DwgSceneOptions options) private static DwgSceneResult Convert(DwgDocument document, string key, string? path, DwgSceneOptions options) { - double metresPerUnit = MetresPerUnit(options.LengthUnit); + string effectiveUnit = options.LengthUnit; + bool unitAssumed = true; + if (options.UseDrawingUnits && + document.HeaderVariables is { } header && + header.TryGetSceneUnit(out string headerUnit)) + { + effectiveUnit = headerUnit; + unitAssumed = false; + } + + double metresPerUnit = MetresPerUnit(effectiveUnit); var scene = new SceneDocument { Title = key }; var diagnostics = new List(); @@ -107,7 +117,7 @@ private static DwgSceneResult Convert(DwgDocument document, string key, string? Path = path, SourceFormat = "dwg", Producer = Producer, - SourceLengthUnit = options.LengthUnit, + SourceLengthUnit = effectiveUnit, Application = document.AppInfo is { Name.Length: > 0 } appInfo ? appInfo.Name : null, CreatedAt = document.SummaryInfo?.CreatedUtc?.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture), }); @@ -220,9 +230,9 @@ private static DwgSceneResult Convert(DwgDocument document, string key, string? ElementCount = elementCount, ElementsWithGeometry = elementsWithGeometry, EntitiesWithoutGeometry = withoutGeometry.Values.Sum(), - LengthUnit = options.LengthUnit, + LengthUnit = effectiveUnit, MetresPerUnit = metresPerUnit, - UnitAssumed = true, + UnitAssumed = unitAssumed, }; } diff --git a/src/DwgIO/DwgDocument.cs b/src/DwgIO/DwgDocument.cs index 3335249..8e200af 100644 --- a/src/DwgIO/DwgDocument.cs +++ b/src/DwgIO/DwgDocument.cs @@ -57,6 +57,11 @@ private DwgDocument( Template = TryReadMetadata("AcDb:Template", b => TemplateParser.Parse(b, fileHeader.Codepage)); } + if (options.ReadHeader) + { + HeaderVariables = ReadOptionalHeader(); + } + if (options.ReadClasses) { options.Progress?.Report(new DwgReadProgress("classes")); @@ -150,6 +155,9 @@ private DwgDocument( /// Custom and class-indexed object definitions from AcDb:Classes (codes 500+). public IReadOnlyList Classes { get; } = []; + /// Drawing system variables decoded from AcDb:Header, when present and read. + public DwgHeaderVariables? HeaderVariables { get; } + /// Handle→offset index from AcDb:Handles (R2004-family files, ReadObjects on). public DwgHandleMap? HandleMap { get; } @@ -164,7 +172,8 @@ private DwgDocument( /// Creates an in-memory document over a file header and a fixed entity list (tests). internal DwgDocument(string path, DwgFileHeader fileHeader, IReadOnlyList entities, - DwgPreview? preview = null, IReadOnlyList? objects = null, IEnumerable? diagnostics = null) + DwgPreview? preview = null, IReadOnlyList? objects = null, IEnumerable? diagnostics = null, + DwgHeaderVariables? headerVariables = null) { Path = path; SourcePath = null; @@ -176,6 +185,7 @@ internal DwgDocument(string path, DwgFileHeader fileHeader, IReadOnlyList ReadOptionalClasses() { if (!TryGetReadableSection("AcDb:Classes", out var entry)) diff --git a/src/DwgIO/DwgReaderOptions.cs b/src/DwgIO/DwgReaderOptions.cs index 98050ac..803c9a4 100644 --- a/src/DwgIO/DwgReaderOptions.cs +++ b/src/DwgIO/DwgReaderOptions.cs @@ -31,6 +31,9 @@ public sealed class DwgReaderOptions /// Parse metadata sections: AppInfo, FileDepList, Preview, RevHistory, AuxHeader, Template (default: true). public bool ReadMetadata { get; set; } = true; + /// Parse drawing system variables from AcDb:Header (default: true). + public bool ReadHeader { get; set; } = true; + /// Parse the AcDb:Classes section to resolve class names and entity flags (default: true). public bool ReadClasses { get; set; } = true; diff --git a/src/DwgIO/Internal/Container/BitReaderMsb.cs b/src/DwgIO/Internal/Container/BitReaderMsb.cs index 0e9f534..67607b9 100644 --- a/src/DwgIO/Internal/Container/BitReaderMsb.cs +++ b/src/DwgIO/Internal/Container/BitReaderMsb.cs @@ -1,4 +1,5 @@ using System.Buffers.Binary; +using System.Text; using DwgIO.Model; namespace DwgIO.Internal.Container; @@ -16,6 +17,9 @@ internal sealed class BitReaderMsb(byte[] bytes) /// Bits left between the cursor and the end of the buffer. public int RemainingBits => (bytes.Length - _bytePos) * 8 - _bitPos; + /// Current zero-based bit position from the start of the buffer. + public int PositionBit => _bytePos * 8 + _bitPos; + /// Moves the bit cursor to an absolute bit offset within the buffer. public void SeekBit(int bitOffset) { @@ -312,4 +316,51 @@ public DwgHandle ReadHandle() return new DwgHandle(code, counter, value); } + + /// Packed-short character count followed by UTF-16LE bytes (R2007+ string stream). + public string ReadUtf16String(string sectionName) + { + int charCount = (int)ReadPackedShort(); + if (charCount == 0) + { + return string.Empty; + } + + int byteCount = charCount * 2; + if (byteCount * 8L > RemainingBits) + { + throw new DwgException($"{sectionName} UTF-16 string of {charCount} chars exceeds remaining bits."); + } + + var raw = new byte[byteCount]; + for (int i = 0; i < byteCount; i++) + { + raw[i] = ReadRawByte(); + } + + return Encoding.Unicode.GetString(raw).TrimEnd('\0'); + } + + /// Packed-short byte count followed by codepage-encoded bytes (R2004 inline string). + public string ReadCodepageString(Encoding encoding, string sectionName) + { + int byteCount = (int)ReadPackedShort(); + if (byteCount == 0) + { + return string.Empty; + } + + if (byteCount * 8L > RemainingBits) + { + throw new DwgException($"{sectionName} string of {byteCount} bytes exceeds remaining bits."); + } + + var raw = new byte[byteCount]; + for (int i = 0; i < byteCount; i++) + { + raw[i] = ReadRawByte(); + } + + return encoding.GetString(raw).TrimEnd('\0'); + } } diff --git a/src/DwgIO/Internal/Parsing/ClassesParser.cs b/src/DwgIO/Internal/Parsing/ClassesParser.cs index 8342bcf..e33cbb8 100644 --- a/src/DwgIO/Internal/Parsing/ClassesParser.cs +++ b/src/DwgIO/Internal/Parsing/ClassesParser.cs @@ -193,48 +193,9 @@ private static List ParseInlineStrings(byte[] data, ushort codepag return classes; } - private static string ReadUtf16String(BitReaderMsb reader) - { - int charCount = (int)reader.ReadPackedShort(); - if (charCount == 0) - { - return string.Empty; - } - - int byteCount = charCount * 2; - if (byteCount * 8L > reader.RemainingBits) - { - throw new DwgException($"AcDb:Classes UTF-16 string of {charCount} chars exceeds remaining bits."); - } - - var bytes = new byte[byteCount]; - for (int i = 0; i < byteCount; i++) - { - bytes[i] = reader.ReadRawByte(); - } - - return Encoding.Unicode.GetString(bytes).TrimEnd('\0'); - } + private static string ReadUtf16String(BitReaderMsb reader) => + reader.ReadUtf16String("AcDb:Classes"); - private static string ReadCodepageString(BitReaderMsb reader, Encoding encoding) - { - int byteCount = (int)reader.ReadPackedShort(); - if (byteCount == 0) - { - return string.Empty; - } - - if (byteCount * 8L > reader.RemainingBits) - { - throw new DwgException($"AcDb:Classes string of {byteCount} bytes exceeds remaining bits."); - } - - var bytes = new byte[byteCount]; - for (int i = 0; i < byteCount; i++) - { - bytes[i] = reader.ReadRawByte(); - } - - return encoding.GetString(bytes).TrimEnd('\0'); - } + private static string ReadCodepageString(BitReaderMsb reader, Encoding encoding) => + reader.ReadCodepageString(encoding, "AcDb:Classes"); } diff --git a/src/DwgIO/Internal/Parsing/HeaderParser.cs b/src/DwgIO/Internal/Parsing/HeaderParser.cs new file mode 100644 index 0000000..cbd1ced --- /dev/null +++ b/src/DwgIO/Internal/Parsing/HeaderParser.cs @@ -0,0 +1,470 @@ +using System.Buffers.Binary; +using System.Text; +using DwgIO.Internal.Container; +using DwgIO.Model; + +namespace DwgIO.Internal.Parsing; + +/// +/// Parses the AcDb:Header section into . +/// +internal static class HeaderParser +{ + private const int FlagCeLWeightMask = 0x001F; + private const short DefaultCeLWeightRaw = 31; + + private static ReadOnlySpan StartSentinel => + [0xCF, 0x7B, 0x1F, 0x23, 0xFD, 0xDE, 0x38, 0xA9, 0x5F, 0x7C, 0x68, 0xB8, 0x4E, 0x6D, 0x33, 0x5F]; + + public static DwgHeaderVariables Parse(byte[] bytes, int year, ushort codepage, int? templateMeasurement = null) + { + if (bytes.Length < 20) + { + throw new DwgException($"AcDb:Header is too short ({bytes.Length} bytes)."); + } + + if (!bytes.AsSpan(0, 16).SequenceEqual(StartSentinel)) + { + throw new DwgException("AcDb:Header is missing the expected start sentinel."); + } + + uint dataSize = BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(16, 4)); + int payloadOffset = year >= 2010 && bytes.Length >= 24 ? 24 : 20; + if (dataSize == 0) + { + throw new DwgException("AcDb:Header payload is empty."); + } + + if (payloadOffset + (long)dataSize > bytes.Length) + { + throw new DwgException( + $"AcDb:Header declares {dataSize} bytes at offset {payloadOffset}, exceeding section length {bytes.Length}."); + } + + byte[] data = bytes[payloadOffset..(payloadOffset + (int)dataSize)]; + BitReaderMsb reader; + BitReaderMsb? stringReader = null; + int stringEndBit = 0; + + if (year >= 2007) + { + if (data.Length < 8) + { + throw new DwgException("AcDb:Header payload is too short for R2007+ framing."); + } + + uint totalSizeInBits = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(0, 4)); + long maxBits = (long)data.Length * 8; + if (totalSizeInBits < 33 || totalSizeInBits > maxBits) + { + throw new DwgException($"AcDb:Header bit size {totalSizeInBits} is outside the {maxBits}-bit payload."); + } + + var tailReader = new BitReaderMsb(data); + tailReader.SeekBit((int)totalSizeInBits - 1); + bool hasStrings = tailReader.ReadBit(); + if (hasStrings) + { + if (totalSizeInBits < 32 + 17) + { + throw new DwgException("AcDb:Header string stream header is truncated."); + } + + var lenReader = new BitReaderMsb(data); + lenReader.SeekBit((int)totalSizeInBits - 17); + int stringBits = lenReader.ReadRawByte() | (lenReader.ReadRawByte() << 8); + int stringStart = (int)totalSizeInBits - 17 - stringBits; + if (stringStart < 32) + { + throw new DwgException($"AcDb:Header string stream start {stringStart} overlaps the header."); + } + + stringEndBit = (int)totalSizeInBits - 17; + stringReader = new BitReaderMsb(data); + stringReader.SeekBit(stringStart); + } + + reader = new BitReaderMsb(data); + reader.SeekBit(32); + if (year >= 2013) + { + _ = reader.ReadPackedLong(); // REQUIREDVERSIONS + } + } + else + { + reader = new BitReaderMsb(data); + } + + Encoding encoding = MetadataByteCursor.GetEncoding(codepage); + + // Preamble: 4 packed doubles, 3 packed ints, and 4 string slots (0..3). + for (int i = 0; i < 4; i++) + { + _ = reader.ReadPackedDouble(); + } + + for (int i = 0; i < 3; i++) + { + _ = reader.ReadPackedInt(); + } + + for (int i = 0; i < 4; i++) + { + _ = ReadString(reader, stringReader, encoding, stringEndBit); + } + + // 19 single-bit toggles (DIMASO .. DISPSILH). + for (int i = 0; i < 19; i++) + { + _ = reader.ReadBit(); + } + + _ = reader.ReadPackedShort(); // PROXYGRAPHICS + _ = reader.ReadPackedShort(); // TREEDEPTH + short lUnits = (short)reader.ReadPackedShort(); + short lUprec = (short)reader.ReadPackedShort(); + short aUnits = (short)reader.ReadPackedShort(); + short aUprec = (short)reader.ReadPackedShort(); + _ = reader.ReadPackedShort(); // ATTMODE + short pdMode = (short)reader.ReadPackedShort(); + + for (int i = 0; i < 3; i++) + { + _ = reader.ReadPackedInt(); + } + + for (int i = 0; i < 5; i++) + { + _ = reader.ReadPackedShort(); // USERI1..5 + } + + // SPLINESEGS, SURFU, SURFV, SURFTYPE, SURFTAB1, SURFTAB2, SPLINETYPE, + // SHADEDGE, SHADEDIF, UNITMODE, MAXACTVP, ISOLINES, CMLJUST, TEXTQLTY. + for (int i = 0; i < 14; i++) + { + _ = reader.ReadPackedShort(); + } + + double ltScale = reader.ReadPackedDouble(); + double textSize = reader.ReadPackedDouble(); + _ = reader.ReadPackedDouble(); // TRACEWID + _ = reader.ReadPackedDouble(); // SKETCHINC + _ = reader.ReadPackedDouble(); // FILLETRAD + _ = reader.ReadPackedDouble(); // THICKNESS + _ = reader.ReadPackedDouble(); // ANGBASE + double pdSize = reader.ReadPackedDouble(); + _ = reader.ReadPackedDouble(); // PLINEWID + + for (int i = 0; i < 5; i++) + { + _ = reader.ReadPackedDouble(); // USERR1..5 + } + + for (int i = 0; i < 4; i++) + { + _ = reader.ReadPackedDouble(); // CHAMFERA..D + } + + _ = reader.ReadPackedDouble(); // FACETRES + _ = reader.ReadPackedDouble(); // CMLSCALE + double ceLtScale = reader.ReadPackedDouble(); + + string menuName = ReadString(reader, stringReader, encoding, stringEndBit); + + uint tdCreateDay = reader.ReadPackedInt(); + uint tdCreateMs = reader.ReadPackedInt(); + uint tdUpdateDay = reader.ReadPackedInt(); + uint tdUpdateMs = reader.ReadPackedInt(); + + for (int i = 0; i < 3; i++) + { + _ = reader.ReadPackedInt(); + } + + // TDINDWG and TDUSRTIMER. + for (int i = 0; i < 4; i++) + { + _ = reader.ReadPackedInt(); + } + + short ceColorIndex = ReadCmcColorIndex(reader, stringReader, encoding, year, stringEndBit); + ulong handseed = reader.ReadHandle().Value; + + var insBase = ReadPoint3D(reader); + var extMin = ReadPoint3D(reader); + var extMax = ReadPoint3D(reader); + _ = reader.ReadPackedShort(); + + var limMin = new DwgPoint2D(reader.ReadRawDouble(), reader.ReadRawDouble()); + var limMax = new DwgPoint2D(reader.ReadRawDouble(), reader.ReadRawDouble()); + _ = reader.ReadPackedDouble(); // ELEVATION + + // UCSORG, UCSXDIR, UCSYDIR, UCSORTHOVIEW, and 6 ortho origins. + SkipUcsBlock(reader); + + // PINSBASE, PEXTMIN, PEXTMAX. + for (int i = 0; i < 3; i++) + { + _ = ReadPoint3D(reader); + } + + // PLIMMIN, PLIMMAX (4 raw doubles). + for (int i = 0; i < 4; i++) + { + _ = reader.ReadRawDouble(); + } + + _ = reader.ReadPackedDouble(); // PELEVATION + SkipUcsBlock(reader); + + double dimScale = reader.ReadPackedDouble(); + for (int i = 0; i < 8; i++) + { + _ = reader.ReadPackedDouble(); // DIMASZ .. DIMTM + } + + if (year >= 2007) + { + _ = reader.ReadPackedDouble(); // DIMFXL + _ = reader.ReadPackedDouble(); // DIMJOGANG + _ = reader.ReadPackedShort(); // DIMTFILL + _ = ReadCmcColorIndex(reader, stringReader, encoding, year, stringEndBit); // DIMTFILLCLR + } + + for (int i = 0; i < 6; i++) + { + _ = reader.ReadBit(); // DIMTOL .. DIMSE2 + } + + for (int i = 0; i < 3; i++) + { + _ = reader.ReadPackedShort(); // DIMTAD, DIMZIN, DIMAZIN + } + + if (year >= 2007) + { + _ = reader.ReadPackedShort(); // DIMARCSYM + } + + for (int i = 0; i < 9; i++) + { + _ = reader.ReadPackedDouble(); // DIMTXT .. DIMALTRND + } + + _ = reader.ReadBit(); // DIMALT + _ = reader.ReadPackedShort(); // DIMALTD + for (int i = 0; i < 4; i++) + { + _ = reader.ReadBit(); // DIMTOFL, DIMSAH, DIMTIX, DIMSOXD + } + + for (int i = 0; i < 3; i++) + { + _ = ReadCmcColorIndex(reader, stringReader, encoding, year, stringEndBit); // DIMCLRD, DIMCLRE, DIMCLRT + } + + for (int i = 0; i < 11; i++) + { + _ = reader.ReadPackedShort(); // DIMADEC .. DIMJUST + } + + _ = reader.ReadBit(); // DIMSD1 + _ = reader.ReadBit(); // DIMSD2 + for (int i = 0; i < 4; i++) + { + _ = reader.ReadPackedShort(); // DIMTOLJ .. DIMALTTZ + } + + _ = reader.ReadBit(); // DIMUPT + _ = reader.ReadPackedShort(); // DIMATFIT + if (year >= 2007) + { + _ = reader.ReadBit(); // DIMFXLON + } + + if (year >= 2010) + { + _ = reader.ReadBit(); // DIMTXTDIRECTION + _ = reader.ReadPackedDouble(); // DIMMZF + _ = reader.ReadPackedDouble(); // DIMALTMZF + } + + _ = reader.ReadPackedShort(); // DIMLWD + _ = reader.ReadPackedShort(); // DIMLWE + + _ = reader.ReadPackedShort(); + _ = reader.ReadPackedInt(); + + uint flags = reader.ReadPackedInt(); + short ceLWeight = DecodeLineWeight((int)(flags & FlagCeLWeightMask)); + var insUnits = (DwgInsUnits)reader.ReadPackedShort(); + + (string fingerprintGuid, string versionGuid) = year >= 2007 + ? ReadTrailingGuids(stringReader, stringEndBit) + : ReadInlineGuids(reader, encoding); + + return new DwgHeaderVariables + { + InsUnits = insUnits, + Measurement = templateMeasurement, + InsBase = insBase, + ExtMin = extMin, + ExtMax = extMax, + LimMin = limMin, + LimMax = limMax, + LUnits = lUnits, + LUprec = lUprec, + AUnits = aUnits, + AUprec = aUprec, + PdMode = pdMode, + PdSize = pdSize, + LtScale = ltScale, + TextSize = textSize, + CeLtScale = ceLtScale, + DimScale = dimScale, + CeColorIndex = ceColorIndex, + CeLWeight = ceLWeight, + CreatedUtc = ToUtc(tdCreateDay, tdCreateMs), + ModifiedUtc = ToUtc(tdUpdateDay, tdUpdateMs), + Handseed = handseed, + MenuName = menuName, + FingerprintGuid = fingerprintGuid, + VersionGuid = versionGuid, + }; + } + + private static DwgPoint3D ReadPoint3D(BitReaderMsb reader) => + new(reader.ReadPackedDouble(), reader.ReadPackedDouble(), reader.ReadPackedDouble()); + + private static void SkipUcsBlock(BitReaderMsb reader) + { + for (int i = 0; i < 3; i++) + { + _ = ReadPoint3D(reader); // ORG, XDIR, YDIR + } + + _ = reader.ReadPackedShort(); // ORTHOVIEW + for (int i = 0; i < 6; i++) + { + _ = ReadPoint3D(reader); // TOP, BOTTOM, LEFT, RIGHT, FRONT, BACK + } + } + + private static short ReadCmcColorIndex( + BitReaderMsb reader, + BitReaderMsb? stringReader, + Encoding encoding, + int year, + int stringEndBit) + { + short index = (short)reader.ReadPackedShort(); + if (year >= 2004) + { + _ = reader.ReadPackedInt(); + byte flag = reader.ReadRawByte(); + if ((flag & 1) != 0) + { + _ = ReadString(reader, stringReader, encoding, stringEndBit); + } + + if ((flag & 2) != 0) + { + _ = ReadString(reader, stringReader, encoding, stringEndBit); + } + } + + return index; + } + + private static string ReadString(BitReaderMsb reader, BitReaderMsb? stringReader, Encoding encoding, int stringEndBit) + { + if (stringReader is null) + { + return reader.ReadCodepageString(encoding, "AcDb:Header"); + } + + int currentBit = stringReader.PositionBit; + if (currentBit >= stringEndBit) + { + return string.Empty; + } + + return stringReader.ReadUtf16String("AcDb:Header"); + } + + private static (string Fingerprint, string Version) ReadTrailingGuids(BitReaderMsb? stringReader, int stringEndBit) + { + if (stringReader is null) + { + return (string.Empty, string.Empty); + } + + var remaining = new List(); + while (stringReader.PositionBit < stringEndBit && remaining.Count < 32) + { + remaining.Add(stringReader.ReadUtf16String("AcDb:Header")); + } + + if (remaining.Count >= 8 && + Guid.TryParse(remaining[6], out _) && + Guid.TryParse(remaining[7], out _)) + { + return (remaining[6], remaining[7]); + } + + // Fallback across R2007/R2010+ variations where intermediate empty string slots differ. + var guids = new List(2); + foreach (string candidate in remaining) + { + if (candidate.Length >= 32 && Guid.TryParse(candidate, out _)) + { + guids.Add(candidate); + if (guids.Count == 2) + { + break; + } + } + } + + return (guids.Count > 0 ? guids[0] : string.Empty, guids.Count > 1 ? guids[1] : string.Empty); + } + + private static (string Fingerprint, string Version) ReadInlineGuids(BitReaderMsb reader, Encoding encoding) + { + // In R2004 inline mode, HYPERLINKBASE / STYLESHEET / FINGERPRINTGUID / VERSIONGUID follow INSUNITS. + string first = string.Empty; + string second = string.Empty; + for (int i = 0; i < 4 && reader.RemainingBits >= 2; i++) + { + string value = reader.ReadCodepageString(encoding, "AcDb:Header"); + if (value.Length >= 32 && Guid.TryParse(value, out _)) + { + if (first.Length == 0) + { + first = value; + } + else + { + second = value; + break; + } + } + } + + return (first, second); + } + + private static short DecodeLineWeight(int encoded) => encoded switch + { + 29 => -3, // DEFAULT + 30 => -2, // BYBLOCK + DefaultCeLWeightRaw => -1, // BYLAYER + _ => (short)encoded, + }; + + private static DateTime? ToUtc(uint julianDay, uint milliseconds) => + SummaryInfoParser.ToDateTimeUtc(julianDay, milliseconds) is long ticks + ? new DateTime(ticks, DateTimeKind.Utc) + : null; +} diff --git a/src/DwgIO/Json/DwgJsonExporter.cs b/src/DwgIO/Json/DwgJsonExporter.cs index 275a180..08a24b7 100644 --- a/src/DwgIO/Json/DwgJsonExporter.cs +++ b/src/DwgIO/Json/DwgJsonExporter.cs @@ -1,4 +1,5 @@ using System.Text.Json; +using DwgIO.Model; namespace DwgIO.Json; @@ -129,6 +130,42 @@ public static void Write(DwgDocument document, Stream output, DwgJsonExportOptio writer.WriteEndObject(); } + if (document.HeaderVariables is { } headerVariables) + { + writer.WriteStartObject("headerVariables"); + writer.WriteString("insUnits", headerVariables.InsUnits.ToString()); + writer.WriteNumber("insUnitsCode", (ushort)headerVariables.InsUnits); + if (headerVariables.Measurement is int measurement) + { + writer.WriteNumber("measurement", measurement); + } + + writer.WriteNumber("lUnits", headerVariables.LUnits); + writer.WriteNumber("lUprec", headerVariables.LUprec); + writer.WriteNumber("aUnits", headerVariables.AUnits); + writer.WriteNumber("aUprec", headerVariables.AUprec); + writer.WriteNumber("pdMode", headerVariables.PdMode); + writer.WriteNumber("pdSize", headerVariables.PdSize); + writer.WriteNumber("ltScale", headerVariables.LtScale); + writer.WriteNumber("textSize", headerVariables.TextSize); + writer.WriteNumber("ceLtScale", headerVariables.CeLtScale); + writer.WriteNumber("dimScale", headerVariables.DimScale); + writer.WriteNumber("ceColorIndex", headerVariables.CeColorIndex); + writer.WriteNumber("ceLWeight", headerVariables.CeLWeight); + WritePoint3D(writer, "insBase", headerVariables.InsBase); + WritePoint3D(writer, "extMin", headerVariables.ExtMin); + WritePoint3D(writer, "extMax", headerVariables.ExtMax); + WritePoint2D(writer, "limMin", headerVariables.LimMin); + WritePoint2D(writer, "limMax", headerVariables.LimMax); + writer.WriteString("createdUtc", headerVariables.CreatedUtc?.ToString("O")); + writer.WriteString("modifiedUtc", headerVariables.ModifiedUtc?.ToString("O")); + writer.WriteNumber("handseed", headerVariables.Handseed); + writer.WriteString("menuName", headerVariables.MenuName); + writer.WriteString("fingerprintGuid", headerVariables.FingerprintGuid); + writer.WriteString("versionGuid", headerVariables.VersionGuid); + writer.WriteEndObject(); + } + if (document.Preview is { } preview) { writer.WriteStartObject("preview"); @@ -283,4 +320,21 @@ public static void Write(DwgDocument document, Stream output, DwgJsonExportOptio private static bool IsIncluded(string name, DwgJsonExportOptions options) => options.SectionsToInclude.Count == 0 || options.SectionsToInclude.Contains(name); + + private static void WritePoint2D(Utf8JsonWriter writer, string propertyName, DwgPoint2D point) + { + writer.WriteStartObject(propertyName); + writer.WriteNumber("x", point.X); + writer.WriteNumber("y", point.Y); + writer.WriteEndObject(); + } + + private static void WritePoint3D(Utf8JsonWriter writer, string propertyName, DwgPoint3D point) + { + writer.WriteStartObject(propertyName); + writer.WriteNumber("x", point.X); + writer.WriteNumber("y", point.Y); + writer.WriteNumber("z", point.Z); + writer.WriteEndObject(); + } } diff --git a/src/DwgIO/Model/DwgHeaderVariables.cs b/src/DwgIO/Model/DwgHeaderVariables.cs new file mode 100644 index 0000000..4dd4342 --- /dev/null +++ b/src/DwgIO/Model/DwgHeaderVariables.cs @@ -0,0 +1,199 @@ +namespace DwgIO.Model; + +/// +/// Drawing insertion units ($INSUNITS), used to scale blocks, xrefs and scene exports to physical units. +/// +public enum DwgInsUnits : ushort +{ + /// Unspecified / unitless (0). + Unitless = 0, + + /// Inches (1). + Inches = 1, + + /// Feet (2). + Feet = 2, + + /// Miles (3). + Miles = 3, + + /// Millimetres (4). + Millimeters = 4, + + /// Centimetres (5). + Centimeters = 5, + + /// Metres (6). + Meters = 6, + + /// Kilometres (7). + Kilometers = 7, + + /// Microinches (8). + Microinches = 8, + + /// Mils (9). + Mils = 9, + + /// Yards (10). + Yards = 10, + + /// Angstroms (11). + Angstroms = 11, + + /// Nanometres (12). + Nanometers = 12, + + /// Micrometres / microns (13). + Microns = 13, + + /// Decimetres (14). + Decimeters = 14, + + /// Decametres (15). + Decameters = 15, + + /// Hectometres (16). + Hectometers = 16, + + /// Gigametres (17). + Gigameters = 17, + + /// Astronomical units (18). + AstronomicalUnits = 18, + + /// Light years (19). + LightYears = 19, + + /// Parsecs (20). + Parsecs = 20, + + /// US Survey Feet (21). + UsSurveyFeet = 21, + + /// US Survey Inches (22). + UsSurveyInches = 22, + + /// US Survey Yards (23). + UsSurveyYards = 23, + + /// US Survey Miles (24). + UsSurveyMiles = 24, +} + +/// A 2D Cartesian point in drawing coordinates. +/// X coordinate. +/// Y coordinate. +public readonly record struct DwgPoint2D(double X, double Y); + +/// A 3D Cartesian point in drawing coordinates. +/// X coordinate. +/// Y coordinate. +/// Z coordinate. +public readonly record struct DwgPoint3D(double X, double Y, double Z); + +/// +/// Core drawing system variables decoded from the AcDb:Header section. +/// +public sealed class DwgHeaderVariables +{ + /// Default block and xref insertion units ($INSUNITS). + public DwgInsUnits InsUnits { get; init; } + + /// + /// Drawing measurement system ($MEASUREMENT, mirrored from AcDb:Template when present): + /// 0 = English (imperial), 1 = metric. + /// + public int? Measurement { get; init; } + + /// True when indicates metric units. + public bool? IsMetric => Measurement is int m ? m != 0 : null; + + /// Model-space drawing insertion base point ($INSBASE). + public DwgPoint3D InsBase { get; init; } + + /// Minimum X, Y, Z extents of the drawing ($EXTMIN). + public DwgPoint3D ExtMin { get; init; } + + /// Maximum X, Y, Z extents of the drawing ($EXTMAX). + public DwgPoint3D ExtMax { get; init; } + + /// Lower-left drawing limits ($LIMMIN). + public DwgPoint2D LimMin { get; init; } + + /// Upper-right drawing limits ($LIMMAX). + public DwgPoint2D LimMax { get; init; } + + /// Linear display units format ($LUNITS: 1=Scientific, 2=Decimal, 3=Engineering, 4=Architectural, 5=Fractional). + public short LUnits { get; init; } + + /// Linear display decimal precision ($LUPREC). + public short LUprec { get; init; } + + /// Angular display units format ($AUNITS: 0=DecimalDegrees, 1=DMS, 2=Grads, 3=Radians, 4=Surveyor). + public short AUnits { get; init; } + + /// Angular display decimal precision ($AUPREC). + public short AUprec { get; init; } + + /// Point display style ($PDMODE). + public short PdMode { get; init; } + + /// Point display size ($PDSIZE). + public double PdSize { get; init; } + + /// Global linetype scale ($LTSCALE). + public double LtScale { get; init; } + + /// Default text height ($TEXTSIZE). + public double TextSize { get; init; } + + /// Current entity linetype scale ($CELTSCALE). + public double CeLtScale { get; init; } + + /// Global dimension scale ($DIMSCALE). + public double DimScale { get; init; } + + /// Current entity ACI colour index ($CECOLOR; 0=BYBLOCK, 256=BYLAYER). + public short CeColorIndex { get; init; } + + /// Raw encoded current entity lineweight index ($CELWEIGHT from header flags). + public short CeLWeight { get; init; } + + /// Drawing creation timestamp in UTC ($TDCREATE), when valid. + public DateTime? CreatedUtc { get; init; } + + /// Drawing last-update timestamp in UTC ($TDUPDATE), when valid. + public DateTime? ModifiedUtc { get; init; } + + /// Next available handle seed recorded in the header ($HANDSEED). + public ulong Handseed { get; init; } + + /// Menu file name ($MENUNAME). + public string MenuName { get; init; } = ""; + + /// Unique drawing fingerprint GUID ($FINGERPRINTGUID). + public string FingerprintGuid { get; init; } = ""; + + /// Drawing version GUID ($VERSIONGUID). + public string VersionGuid { get; init; } = ""; + + /// + /// Attempts to map to a scene length unit symbol (mm, cm, m, ft, or in). + /// + /// Set to the unit symbol when is one of the directly supported scene units. + /// when maps to a supported scene unit; otherwise . + public bool TryGetSceneUnit(out string unit) + { + unit = InsUnits switch + { + DwgInsUnits.Millimeters => "mm", + DwgInsUnits.Centimeters => "cm", + DwgInsUnits.Meters => "m", + DwgInsUnits.Feet => "ft", + DwgInsUnits.Inches => "in", + _ => "", + }; + return unit.Length > 0; + } +} diff --git a/tests/DwgIO.Tests/HeaderVariablesTests.cs b/tests/DwgIO.Tests/HeaderVariablesTests.cs new file mode 100644 index 0000000..79617ac --- /dev/null +++ b/tests/DwgIO.Tests/HeaderVariablesTests.cs @@ -0,0 +1,376 @@ +using System.Buffers.Binary; +using System.Text; +using System.Text.Json; +using DwgIO.Cli; +using DwgIO.Export; +using DwgIO.Internal.Parsing; +using DwgIO.Model; +using DwgIO.Scene; +using Xunit; + +namespace DwgIO.Tests; + +public class HeaderVariablesTests +{ + private static readonly byte[] HeaderStartSentinel = + [0xCF, 0x7B, 0x1F, 0x23, 0xFD, 0xDE, 0x38, 0xA9, 0x5F, 0x7C, 0x68, 0xB8, 0x4E, 0x6D, 0x33, 0x5F]; + + [Theory] + [InlineData("primitives-ac1024.dwg")] + [InlineData("primitives-ac1027.dwg")] + [InlineData("primitives-ac1032.dwg")] + public void PublicDrawings_DecodeHeaderVariablesAccurately(string fileName) + { + var doc = DwgDocument.Open(TestFiles.PublicDrawing(fileName)); + + Assert.NotNull(doc.HeaderVariables); + var hv = doc.HeaderVariables!; + + Assert.Equal(DwgInsUnits.Unitless, hv.InsUnits); + Assert.Equal(1, hv.Measurement); + Assert.True(hv.IsMetric); + Assert.Equal(".", hv.MenuName); + Assert.Equal((short)2, hv.LUnits); + Assert.Equal((short)4, hv.LUprec); + Assert.Equal((short)0, hv.AUnits); + Assert.Equal((short)0, hv.AUprec); + Assert.Equal((short)0, hv.PdMode); + Assert.Equal(0.0, hv.PdSize); + Assert.Equal(1.0, hv.LtScale); + Assert.Equal(2.5, hv.TextSize); + Assert.Equal(1.0, hv.CeLtScale); + Assert.Equal(1.0, hv.DimScale); + Assert.Equal((short)0, hv.CeColorIndex); + Assert.Equal((short)-1, hv.CeLWeight); + Assert.Equal(0x4CUL, hv.Handseed); + Assert.NotNull(hv.CreatedUtc); + Assert.NotNull(hv.ModifiedUtc); + Assert.Equal(doc.AuxHeader?.CreatedUtc?.Date, hv.CreatedUtc?.Date); + Assert.True(Guid.TryParse(hv.FingerprintGuid, out _)); + Assert.True(Guid.TryParse(hv.VersionGuid, out _)); + } + + [Fact] + public void ReadHeader_Disabled_LeavesHeaderVariablesNull() + { + var doc = DwgDocument.Open( + TestFiles.PublicDrawing("primitives-ac1032.dwg"), + new DwgReaderOptions { ReadHeader = false }); + + Assert.Null(doc.HeaderVariables); + } + + [Fact] + public void JsonAndCli_IncludeHeaderVariablesAndPdMode() + { + var doc = DwgDocument.Open(TestFiles.PublicDrawing("primitives-ac1032.dwg")); + using var parsed = JsonDocument.Parse(doc.ToJson()); + + Assert.True(parsed.RootElement.TryGetProperty("headerVariables", out var hvJson)); + Assert.Equal("Unitless", hvJson.GetProperty("insUnits").GetString()); + Assert.Equal(2, hvJson.GetProperty("lUnits").GetInt32()); + Assert.Equal(0x4C, hvJson.GetProperty("handseed").GetInt64()); + Assert.Equal(".", hvJson.GetProperty("menuName").GetString()); + + using var stdout = new StringWriter(); + int exit = Program.InspectDocument(doc, stdout); + Assert.Equal(DwgExitCodes.Ok, exit); + Assert.Contains("Header: insunits=Unitless", stdout.ToString(), StringComparison.Ordinal); + + using var ms = new MemoryStream(); + DwgCadHtmlViewer.Export(doc, ms, new DwgViewerOptions(), "m"); + string html = Encoding.UTF8.GetString(ms.ToArray()); + Assert.Contains("\"pdmode\":0", html, StringComparison.Ordinal); + Assert.Contains("\"insunits\":\"Unitless\"", html, StringComparison.Ordinal); + } + + [Theory] + [InlineData(DwgInsUnits.Millimeters, true, "mm", 0.001, false)] + [InlineData(DwgInsUnits.Centimeters, true, "cm", 0.01, false)] + [InlineData(DwgInsUnits.Meters, true, "m", 1.0, false)] + [InlineData(DwgInsUnits.Feet, true, "ft", 0.3048, false)] + [InlineData(DwgInsUnits.Inches, true, "in", 0.0254, false)] + [InlineData(DwgInsUnits.Unitless, false, "m", 1.0, true)] + public void SceneReader_UseDrawingUnits_MapsInsUnitsAndFallsBackCleanly( + DwgInsUnits insUnits, + bool expectedMapped, + string expectedUnit, + double expectedScale, + bool expectedAssumed) + { + var hv = new DwgHeaderVariables { InsUnits = insUnits }; + Assert.Equal(expectedMapped, hv.TryGetSceneUnit(out string mapped)); + if (expectedMapped) + { + Assert.Equal(expectedUnit, mapped); + } + + var doc = new DwgDocument( + "synthetic.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1032", + Release = "R2018", + Family = DwgContainerFamily.R2004Family, + Year = 2018, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + [], + headerVariables: hv); + + var result = DwgSceneReader.Read(doc, new DwgSceneOptions { ModelKey = "synthetic", UseDrawingUnits = true }); + Assert.Equal(expectedUnit, result.LengthUnit); + Assert.Equal(expectedScale, result.MetresPerUnit); + Assert.Equal(expectedAssumed, result.UnitAssumed); + + // When UseDrawingUnits is false (default), LengthUnit stays as caller configured. + var defaultResult = DwgSceneReader.Read(doc, new DwgSceneOptions { ModelKey = "synthetic" }); + Assert.Equal("m", defaultResult.LengthUnit); + Assert.True(defaultResult.UnitAssumed); + } + + [Fact] + public void SyntheticR2004Header_DecodesInlineStringsAndVariables() + { + byte[] section = BuildSyntheticR2004Header( + insUnits: DwgInsUnits.Millimeters, + pdMode: 35, + pdSize: 1.5, + ltScale: 2.5, + ceLtScale: 0.5, + dimScale: 10.0, + extMin: new DwgPoint3D(-10, -20, -1), + extMax: new DwgPoint3D(100, 200, 5), + limMin: new DwgPoint2D(0, 0), + limMax: new DwgPoint2D(420, 297), + handseed: 0x123UL, + fingerprintGuid: "{11111111-2222-3333-4444-555555555555}", + versionGuid: "{AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE}"); + + var parsed = HeaderParser.Parse(section, year: 2004, codepage: 30, templateMeasurement: 1); + + Assert.Equal(DwgInsUnits.Millimeters, parsed.InsUnits); + Assert.Equal(1, parsed.Measurement); + Assert.Equal((short)35, parsed.PdMode); + Assert.Equal(1.5, parsed.PdSize); + Assert.Equal(2.5, parsed.LtScale); + Assert.Equal(0.5, parsed.CeLtScale); + Assert.Equal(10.0, parsed.DimScale); + Assert.Equal(new DwgPoint3D(-10, -20, -1), parsed.ExtMin); + Assert.Equal(new DwgPoint3D(100, 200, 5), parsed.ExtMax); + Assert.Equal(new DwgPoint2D(0, 0), parsed.LimMin); + Assert.Equal(new DwgPoint2D(420, 297), parsed.LimMax); + Assert.Equal(0x123UL, parsed.Handseed); + Assert.Equal("{11111111-2222-3333-4444-555555555555}", parsed.FingerprintGuid); + Assert.Equal("{AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE}", parsed.VersionGuid); + } + + [Fact] + public void Parse_MalformedHeaders_ThrowDwgException() + { + Assert.Throws(() => HeaderParser.Parse(new byte[10], year: 2018, codepage: 30)); + + byte[] badSentinel = new byte[40]; + Assert.Throws(() => HeaderParser.Parse(badSentinel, year: 2018, codepage: 30)); + + byte[] emptyPayload = new byte[24]; + HeaderStartSentinel.CopyTo(emptyPayload, 0); + Assert.Throws(() => HeaderParser.Parse(emptyPayload, year: 2018, codepage: 30)); + + byte[] truncated = new byte[28]; + HeaderStartSentinel.CopyTo(truncated, 0); + BinaryPrimitives.WriteUInt32LittleEndian(truncated.AsSpan(16, 4), 100); + Assert.Throws(() => HeaderParser.Parse(truncated, year: 2018, codepage: 30)); + } + + private static byte[] BuildSyntheticR2004Header( + DwgInsUnits insUnits, + short pdMode, + double pdSize, + double ltScale, + double ceLtScale, + double dimScale, + DwgPoint3D extMin, + DwgPoint3D extMax, + DwgPoint2D limMin, + DwgPoint2D limMax, + ulong handseed, + string fingerprintGuid, + string versionGuid) + { + var w = new RecordBitWriter(); + + // 4 preamble BDs, 3 preamble BLs, 4 TV strings. + for (int i = 0; i < 4; i++) w.WriteTwoBits(2); + for (int i = 0; i < 3; i++) w.WriteTwoBits(2); + for (int i = 0; i < 4; i++) WriteAsciiString(w, ""); + + // 19 bit toggles. + for (int i = 0; i < 19; i++) w.WriteBit(false); + + w.WriteTwoBits(2); // PROXYGRAPHICS + w.WriteTwoBits(2); // TREEDEPTH + WritePackedShort(w, 2); // LUNITS + WritePackedShort(w, 4); // LUPREC + WritePackedShort(w, 0); // AUNITS + WritePackedShort(w, 0); // AUPREC + WritePackedShort(w, 1); // ATTMODE + WritePackedShort(w, (ushort)pdMode); + for (int i = 0; i < 3; i++) w.WriteTwoBits(2); + for (int i = 0; i < 5; i++) w.WriteTwoBits(2); + for (int i = 0; i < 14; i++) w.WriteTwoBits(2); + + WritePackedDouble(w, ltScale); + WritePackedDouble(w, 2.5); // TEXTSIZE + for (int i = 0; i < 5; i++) w.WriteTwoBits(2); + WritePackedDouble(w, pdSize); + w.WriteTwoBits(2); // PLINEWID + for (int i = 0; i < 5; i++) w.WriteTwoBits(2); + for (int i = 0; i < 4; i++) w.WriteTwoBits(2); + w.WriteTwoBits(2); // FACETRES + w.WriteTwoBits(2); // CMLSCALE + WritePackedDouble(w, ceLtScale); + + WriteAsciiString(w, "."); // MENUNAME + for (int i = 0; i < 4; i++) w.WriteTwoBits(2); // TDCREATE, TDUPDATE + for (int i = 0; i < 3; i++) w.WriteTwoBits(2); + for (int i = 0; i < 4; i++) w.WriteTwoBits(2); // TDINDWG, TDUSRTIMER + + // CECOLOR (R2004 CMC) + w.WriteTwoBits(2); + w.WriteTwoBits(2); + w.WriteRawByte(0); + + // HANDSEED (4-bit code 0, 4-bit counter 2 -> 0x02 byte, followed by big-endian handle bytes) + w.WriteRawByte(0x02); + w.WriteRawByte((byte)((handseed >> 8) & 0xFF)); + w.WriteRawByte((byte)(handseed & 0xFF)); + + WritePoint3D(w, new DwgPoint3D(0, 0, 0)); + WritePoint3D(w, extMin); + WritePoint3D(w, extMax); + w.WriteTwoBits(2); + w.WriteRawDouble(limMin.X); + w.WriteRawDouble(limMin.Y); + w.WriteRawDouble(limMax.X); + w.WriteRawDouble(limMax.Y); + w.WriteTwoBits(2); // ELEVATION + + SkipSyntheticUcsBlock(w); + + for (int i = 0; i < 3; i++) WritePoint3D(w, new DwgPoint3D(0, 0, 0)); + for (int i = 0; i < 4; i++) w.WriteRawDouble(0); + w.WriteTwoBits(2); // PELEVATION + SkipSyntheticUcsBlock(w); + + WritePackedDouble(w, dimScale); + for (int i = 0; i < 8; i++) w.WriteTwoBits(2); + for (int i = 0; i < 6; i++) w.WriteBit(false); + for (int i = 0; i < 3; i++) w.WriteTwoBits(2); + for (int i = 0; i < 9; i++) w.WriteTwoBits(2); + w.WriteBit(false); + w.WriteTwoBits(2); + for (int i = 0; i < 4; i++) w.WriteBit(false); + for (int i = 0; i < 3; i++) + { + w.WriteTwoBits(2); + w.WriteTwoBits(2); + w.WriteRawByte(0); + } + + for (int i = 0; i < 11; i++) w.WriteTwoBits(2); + w.WriteBit(false); + w.WriteBit(false); + for (int i = 0; i < 4; i++) w.WriteTwoBits(2); + w.WriteBit(false); + w.WriteTwoBits(2); + w.WriteTwoBits(2); // DIMLWD + w.WriteTwoBits(2); // DIMLWE + w.WriteTwoBits(2); + w.WriteTwoBits(2); + WritePackedInt(w, 0x0E1F); // Flags (CELWEIGHT=-1) + WritePackedShort(w, (ushort)insUnits); + WriteAsciiString(w, ""); + WriteAsciiString(w, ""); + WriteAsciiString(w, fingerprintGuid); + WriteAsciiString(w, versionGuid); + + byte[] payload = w.ToArray(); + byte[] section = new byte[20 + payload.Length]; + HeaderStartSentinel.CopyTo(section, 0); + BinaryPrimitives.WriteUInt32LittleEndian(section.AsSpan(16, 4), (uint)payload.Length); + payload.CopyTo(section, 20); + return section; + } + + 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 WritePackedInt(RecordBitWriter w, uint value) + { + w.WriteTwoBits(0); + w.WriteRawByte((byte)(value & 0xFF)); + w.WriteRawByte((byte)((value >> 8) & 0xFF)); + w.WriteRawByte((byte)((value >> 16) & 0xFF)); + w.WriteRawByte((byte)((value >> 24) & 0xFF)); + } + + private static void WritePackedDouble(RecordBitWriter w, double value) + { + if (value == 0.0) + { + w.WriteTwoBits(2); + } + else if (value == 1.0) + { + w.WriteTwoBits(1); + } + else + { + w.WriteTwoBits(0); + w.WriteRawDouble(value); + } + } + + private static void WritePoint3D(RecordBitWriter w, DwgPoint3D p) + { + WritePackedDouble(w, p.X); + WritePackedDouble(w, p.Y); + WritePackedDouble(w, p.Z); + } + + private static void SkipSyntheticUcsBlock(RecordBitWriter w) + { + for (int i = 0; i < 3; i++) WritePoint3D(w, new DwgPoint3D(0, 0, 0)); + w.WriteTwoBits(2); + for (int i = 0; i < 6; i++) WritePoint3D(w, new DwgPoint3D(0, 0, 0)); + } + + private static void WriteAsciiString(RecordBitWriter w, string value) + { + WritePackedShort(w, (ushort)value.Length); + foreach (byte b in Encoding.ASCII.GetBytes(value)) + { + w.WriteRawByte(b); + } + } +} From e44162a2b6518179f0eab3204cdffdb0aff0a299 Mon Sep 17 00:00:00 2001 From: mahach666 Date: Wed, 2 Dec 2026 12:56:39 +0300 Subject: [PATCH 2/2] Make drawing unit detection opt in for CLI exports --- CHANGELOG.md | 1 + README.md | 6 ++- docs/public-api.md | 1 + src/DwgIO.Cli/Program.cs | 38 ++++++++----------- .../Compatibility/DwgSceneExport.cs | 1 + .../Compatibility/DwgViewerExport.cs | 1 + tests/DwgIO.Tests/HeaderVariablesTests.cs | 23 +++++++++++ 7 files changed, 47 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ecdd1c..ee47f1d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ API between minor releases. ## [Unreleased] ### Added +- `--unit auto` reads a supported `$INSUNITS` for scene, OBJ, GLB and HTML exports. These commands default to metres. - `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`. - Entity geometry decoding for `LWPOLYLINE` (including bulges and elevation), `ELLIPSE`, `SOLID`/`TRACE`, `3DFACE`, `RAY`, `XLINE` and 24-bit `TrueColorRgb` across `DwgIO`, `DwgIO.Scene`, SVG and the 2D AutoCAD HTML viewer. diff --git a/README.md b/README.md index 93ded99..fa7f8b2 100644 --- a/README.md +++ b/README.md @@ -60,13 +60,15 @@ Save the embedded thumbnail preview. Without an extension, `.png`, `.wmf` or `.b dwgio preview drawing.dwg thumbnail ``` -Export a neutral IOScene scene document (geometry in metres, ACI colours, one element per decoded entity). `--unit` names the drawing unit the coordinates are scaled from — one of `mm`, `cm`, `m` (default), `ft`, `in`: +Export a neutral IOScene scene document (geometry in metres, ACI colours, one element per decoded entity). Use +`--unit mm|cm|m|ft|in` to set the drawing unit. With `--unit auto`, a supported `$INSUNITS` provides the unit. +The default and the fallback for missing or unsupported drawing units are both metres. ```sh dwgio scene drawing.dwg drawing.scene.json --unit mm ``` -The plain export command writes OBJ, GLB and HTML by output extension (with `--unit mm|cm|m|ft|in`): +The plain export command writes OBJ, GLB and HTML by output extension and accepts the same `--unit` values: ```sh dwgio drawing.dwg drawing.obj --unit mm # Wavefront OBJ + drawing.mtl with the ACI colours diff --git a/docs/public-api.md b/docs/public-api.md index 440393f..35c1673 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -95,6 +95,7 @@ The CLI uses these exporters and adds a 2D HTML viewer: - `dwgio drawing.dwg drawing.html` exports the interactive 3D WebGL viewer via [IOViewer](https://github.com/IOExtend/IOViewer). You can also pass `--mode 3d`. - `dwgio drawing.dwg drawing.html --mode 2d` exports an AutoCAD-style top view. Use `--bg black|slate|light` to set its background. - `dwgio drawing.dwg out.obj --unit mm` and `dwgio drawing.dwg out.glb --unit mm` pass `--unit` to the scene converter. +- The scene, OBJ, GLB and HTML commands use metres by default. Pass `--unit auto` to use a supported `$INSUNITS`. ## Diagnostics diff --git a/src/DwgIO.Cli/Program.cs b/src/DwgIO.Cli/Program.cs index a1f1947..4ff01ee 100644 --- a/src/DwgIO.Cli/Program.cs +++ b/src/DwgIO.Cli/Program.cs @@ -110,7 +110,7 @@ or the scene to OBJ (.obj), GLB (.glb) or a standalone dwgio extract
Write a named section's decompressed bytes dwgio preview Write the embedded thumbnail image dwgio scene [--unit u] Export a neutral IOScene scene document - (u: mm, cm, m (default), ft or in) + (u: mm, cm, m (default), ft, in or auto) dwgio svg [--scale s] Draw model space to SVG (s: px per unit, default 1) dwgio entities [--type LINE,CIRCLE] [--json] List decoded entities, one line each or as JSON @@ -271,14 +271,14 @@ private static int Export(string[] args, TextWriter output, TextWriter error) case "--unit": if (i + 1 >= args.Length) { - error.WriteLine("error: --unit needs a value (mm, cm, m, ft or in)."); + error.WriteLine("error: --unit needs a value (mm, cm, m, ft, in or auto)."); return DwgExitCodes.Usage; } unit = args[++i]; - if (!DwgSceneReader.IsSupportedUnit(unit)) + if (!IsAutoUnit(unit) && !DwgSceneReader.IsSupportedUnit(unit)) { - error.WriteLine($"error: unknown length unit '{unit}'. Use mm, cm, m, ft or in."); + error.WriteLine($"error: unknown length unit '{unit}'. Use mm, cm, m, ft, in or auto."); return DwgExitCodes.Usage; } @@ -362,9 +362,7 @@ internal static int ExportDocument( return DwgExitCodes.Usage; } - var sceneOptions = unit is null - ? new DwgSceneOptions { UseDrawingUnits = true } - : new DwgSceneOptions { LengthUnit = unit }; + var sceneOptions = SceneOptionsFor(unit); if (Path.GetExtension(target).Equals(".obj", StringComparison.OrdinalIgnoreCase)) { @@ -474,7 +472,7 @@ private static int Scene(string[] args, TextWriter output, TextWriter error) { if (i + 1 >= args.Length) { - error.WriteLine("error: --unit needs a value (mm, cm, m, ft or in)."); + error.WriteLine("error: --unit needs a value (mm, cm, m, ft, in or auto)."); return DwgExitCodes.Usage; } @@ -501,23 +499,13 @@ private static int Scene(string[] args, TextWriter output, TextWriter error) return DwgExitCodes.Usage; } - var options = new DwgSceneOptions(); - if (unit is not null) + if (unit is not null && !IsAutoUnit(unit) && !DwgSceneReader.IsSupportedUnit(unit)) { - if (!DwgSceneReader.IsSupportedUnit(unit)) - { - error.WriteLine($"error: unknown length unit '{unit}'. Use mm, cm, m, ft or in."); - return DwgExitCodes.Usage; - } - - options.LengthUnit = unit; - } - else - { - options.UseDrawingUnits = true; + error.WriteLine($"error: unknown length unit '{unit}'. Use mm, cm, m, ft, in or auto."); + return DwgExitCodes.Usage; } - var result = DwgSceneReader.Read(positional[0], options); + var result = DwgSceneReader.Read(positional[0], SceneOptionsFor(unit)); AtomicOutput.Write(positional[1], stream => SceneJson.Write(result.Document, stream)); output.WriteLine( $"{result.Document.Title}: {Count(result.ElementCount)} elements ({Count(result.ElementsWithGeometry)} with geometry) -> {positional[1]}"); @@ -534,6 +522,12 @@ private static int Scene(string[] args, TextWriter output, TextWriter error) return DwgExitCodes.Ok; } + private static bool IsAutoUnit(string? unit) => string.Equals(unit, "auto", StringComparison.OrdinalIgnoreCase); + + private static DwgSceneOptions SceneOptionsFor(string? unit) => IsAutoUnit(unit) + ? new DwgSceneOptions { UseDrawingUnits = true } + : new DwgSceneOptions { LengthUnit = unit ?? "m" }; + private static int Preview(string[] args, TextWriter output, TextWriter error) { if (args.Length != 3) diff --git a/src/DwgIO.Scene/Compatibility/DwgSceneExport.cs b/src/DwgIO.Scene/Compatibility/DwgSceneExport.cs index 133cb5b..3d2f4ad 100644 --- a/src/DwgIO.Scene/Compatibility/DwgSceneExport.cs +++ b/src/DwgIO.Scene/Compatibility/DwgSceneExport.cs @@ -116,6 +116,7 @@ private static DwgSceneOptions OptionsFor(string path, DwgSceneOptions? options) return new DwgSceneOptions { LengthUnit = options?.LengthUnit ?? "m", + UseDrawingUnits = options?.UseDrawingUnits ?? false, ModelKey = Path.GetFileName(path), ReadProgress = options?.ReadProgress, }; diff --git a/src/DwgIO.Scene/Compatibility/DwgViewerExport.cs b/src/DwgIO.Scene/Compatibility/DwgViewerExport.cs index dc16fc1..f58c8df 100644 --- a/src/DwgIO.Scene/Compatibility/DwgViewerExport.cs +++ b/src/DwgIO.Scene/Compatibility/DwgViewerExport.cs @@ -61,6 +61,7 @@ private static DwgSceneOptions ViewerOptionsFor(DwgDocument document, string pat return new DwgSceneOptions { LengthUnit = options?.LengthUnit ?? "m", + UseDrawingUnits = options?.UseDrawingUnits ?? false, ModelKey = Path.GetFileName(path), }; } diff --git a/tests/DwgIO.Tests/HeaderVariablesTests.cs b/tests/DwgIO.Tests/HeaderVariablesTests.cs index 79617ac..f1f1883 100644 --- a/tests/DwgIO.Tests/HeaderVariablesTests.cs +++ b/tests/DwgIO.Tests/HeaderVariablesTests.cs @@ -134,6 +134,29 @@ public void SceneReader_UseDrawingUnits_MapsInsUnitsAndFallsBackCleanly( Assert.True(defaultResult.UnitAssumed); } + [Fact] + public void Cli_ObjUsesMetresByDefaultAndHeaderUnitsOnRequest() + { + var seed = DwgDocument.Open(TestFiles.PublicDrawing("primitives-ac1032.dwg")); + var document = new DwgDocument( + "synthetic.dwg", seed.FileHeader, seed.Entities, + headerVariables: new DwgHeaderVariables { InsUnits = DwgInsUnits.Millimeters }); + string directory = Directory.CreateTempSubdirectory("dwgio-units-").FullName; + try + { + string defaultPath = Path.Combine(directory, "default.obj"); + string autoPath = Path.Combine(directory, "auto.obj"); + Assert.Equal(DwgExitCodes.Ok, Program.ExportDocument(document, defaultPath, TextWriter.Null, TextWriter.Null)); + Assert.Equal(DwgExitCodes.Ok, Program.ExportDocument(document, autoPath, TextWriter.Null, TextWriter.Null, unit: "auto")); + Assert.Contains("v 1 2 3", File.ReadLines(defaultPath)); + Assert.Contains("v 0.001 0.002 0.003", File.ReadLines(autoPath)); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + [Fact] public void SyntheticR2004Header_DecodesInlineStringsAndVariables() {