diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 08ba7bd..5be8449 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,7 +13,7 @@ jobs: strategy: fail-fast: false matrix: - os: [windows-latest] + os: [windows-latest, ubuntu-latest, macos-latest] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v7 @@ -31,14 +31,3 @@ jobs: name: packages-${{ matrix.os }} path: artifacts/*.nupkg if-no-files-found: error - - build-linux: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - - uses: actions/setup-dotnet@v6 - with: - dotnet-version: | - 8.0.x - 10.0.x - - run: dotnet build src/DwgIO.Cli/DwgIO.Cli.csproj -c Release diff --git a/CHANGELOG.md b/CHANGELOG.md index d950a3a..3c34da7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,63 @@ API between minor releases. ## [Unreleased] +### Added +- CI runs the tests on Linux and macOS as well as Windows (both target frameworks), replacing the Linux + build-only job (#34). +- `test-files/public`: the folder for committed redistributable test drawings, with the origin and licence + recorded next to each file; the fixture search includes it, so a committed drawing turns the skipped + fixture tests into real runs in CI (#33, infrastructure — the drawings themselves follow). +- `DwgDocument.Open(Stream, documentName?, options?)`: a drawing can now come from a stream (a network + handle, an archive entry, an already-open file). The stream is read to memory once, so the results are + identical to `Open(path)` on the same bytes; the unsupported-version message names the source (#37, first + step — reading data pages on demand remains open). +- `AcDb:RevHistory`, `AcDb:AuxHeader` and `AcDb:Template` parsing exposes the revision values, auxiliary + header and template description on `DwgDocument`, in JSON and in `dwgio inspect`. The undecoded + `AcDb:AppInfoHistory` section is exposed as decompressed bytes, with its size in JSON and CLI output (#36). +- Fixed object type names are available in `DwgObjectInfo.TypeName`, `dwgio inspect` and the JSON + `objects.byTypeName` field. Existing `objects.byType` keys are preserved (#20, fixed types only). +- `dwgio --version` and `--help` (and `-v`/`-h`) print the version and the usage with exit code 0; an unknown + option still exits 1 (#18). +- `dwgio entities [--type LINE,CIRCLE] [--json]` lists decoded entities one line each or as a JSON + array, with the type filter validated against the known type names (#19). The JSON export writes to standard + output when the target is `-` (#19). +- `DwgIO.Scene` package: converts a drawing into a neutral [IOScene](https://www.nuget.org/packages/IOScene) scene + document, the shared scene model of the IOExtend tools. One element per decoded entity with the handle as + `SourceId`, line and point geometries scaled to metres (`DwgSceneOptions.LengthUnit`), ACI colours on the + placements and a conversion report (`DwgSceneResult`). The scene passes the IOScene structural validation and + round-trips through the IOScene JSON format. +- `dwgio scene [--unit mm|cm|m|ft|in]` writes the scene document. +- `DwgSceneExport.SaveObj`/`SaveGlb` write a drawing to Wavefront OBJ (with an adjacent MTL colour library, + written as a pair) and binary glTF (GLB) through the IOScene writers; `dwgio drawing.dwg out.obj` and + `dwgio drawing.dwg out.glb` dispatch by extension. +- `DwgSvgExporter` and `dwgio svg [--scale n]` draw model space to SVG (#32): LINE, + CIRCLE, ARC and POINT in the top view with the y axis up, in their ACI colours, inside a view box that + contains every exported entity. Polylines, curves and text follow as the core decodes them. +- `DwgViewerExport.SaveViewer` and `dwgio drawing.dwg out.html` write a standalone interactive 3D HTML viewer + (the IOViewer WebGL runtime embedded with the IOScene scene document; no server, no external scripts). +- `dwgio inspect` is written through a `TextWriter`, so the report is testable directly. + ### Fixed +- `DwgAppInfo.Product` is filled from the product XML's `name` attribute ("AutoCAD", "AutoCAD LT", + "Teigha(R)", ...), so `dwgio inspect` and the JSON export name the product instead of an empty string (#35). +- `dwgio preview` exits with code 5 when the drawing has no thumbnail, distinct from the parse-error code, and + reports a mismatch between the requested output extension and the image kind on standard error instead of + keeping both silent (#14). +- Encrypted sections (encryption flag 1) are reported in `Diagnostics` and by `dwgio inspect` (the section + table marks them) instead of being skipped silently; decrypting them remains out of scope (#38). +- Object stream: after a gap (a zero run or a broken record) the object walk resynchronises at the next + handle-map offset instead of stopping, and every early stop or skipped gap is reported in `Diagnostics`; the + inventory-versus-handle-map difference is reported as well, and `DwgHandleMap.Parse` reports truncated blocks + and drops negative offsets with a diagnostic (#13). +- Fixture tests skip drawings of an unsupported version and count them in the skip reason, so one AC1021 file + in the fixture folder does not fail every test (#17). +- Entity colour: the DXF 62 index takes the low 9 bits of the stored colour value, so BYLAYER (256) is reported + as 256 and not as 0 (which also means BYBLOCK) (#40). The JSON export writes `colorIndex` for BYBLOCK and + BYLAYER so they are distinguishable. +- `dwgio` formats counts and byte sizes invariantly; the output no longer follows the machine's digit grouping + (#15). +- `dwgio inspect` always prints the diagnostic total and the first diagnostics, whether or not any entity was + decoded (#16). - Packed 16-bit and 32-bit integers in their full-width form are read little-endian. They were read with their bytes reversed, so entity records that store a colour, extended data size or reactor count in that form were decoded from the wrong bit position and failed or gave NaN or absurd coordinates (#7). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a7205a1..1de5a63 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -29,8 +29,9 @@ facts as they are observed in DWG files, in your own words, in code comments, documentation and commit messages. Do not add vendor code, SDKs, SDK internals, headers or binaries, decompiled or -leaked source, or anything taken from analysing vendor binaries. Do not add DWG -or DXF drawings, customer data, or names, paths, sizes or other details of +leaked source, or anything taken from analysing vendor binaries. +Add DWG fixtures only under `test-files/public` and only when they meet its origin and licence rules. +Do not add other drawings, customer data, or names, paths, sizes or other details of private sample drawings to the repository, including tests, comments and documentation. Test inputs are built synthetically in the tests; tests that need private drawings read them from the folder named by `DWGIO_TEST_FILES` and @@ -87,7 +88,7 @@ Include: - The build and test commands run, their results, and any skipped checks. - Before and after output comparison results when the output is affected. -Do not add drawings, customer data, vendor code or binaries to the +Do not add private drawings, customer data, vendor code or binaries to the repository. Keep private test drawings outside version control. Write commit messages in the imperative mood, for example, diff --git a/Directory.Packages.props b/Directory.Packages.props index a9d9560..02fe636 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -9,6 +9,15 @@ + + + + + + + + diff --git a/DwgIO.slnx b/DwgIO.slnx index 5835494..5cd14c6 100644 --- a/DwgIO.slnx +++ b/DwgIO.slnx @@ -1,5 +1,6 @@ + diff --git a/README.md b/README.md index 5f79c84..14f224d 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,10 @@ DwgIO is a .NET library and command line tool that reads Autodesk AutoCAD drawin - Parses drawing metadata: summary information with custom properties and dates, application information, file dependencies and the embedded thumbnail preview. - Lists the objects of a drawing through its handle map and decodes the geometry of LINE, CIRCLE, ARC and POINT entities. - Writes a JSON export of the metadata, the section catalog and the decoded entities. +- Converts a drawing into a neutral [IOScene](https://www.nuget.org/packages/IOScene) scene document (`DwgIO.Scene` package): geometry in metres, ACI entity colours, one element per entity with its handle. +- Exports the scene to Wavefront OBJ (with an MTL colour library) and binary glTF (GLB). +- Draws model space to SVG (`dwgio svg`): LINE, CIRCLE, ARC and POINT in the top view, in their ACI colours. +- Writes a standalone interactive 3D HTML viewer (`.html`): the WebGL viewer of [IOViewer](https://github.com/IOExtend/IOViewer) embedded with the scene, no server or external scripts. ## Install @@ -21,13 +25,14 @@ Install the command line tool: dotnet tool install --global DwgIO.Cli ``` -and add the library to a .NET project: +and add the libraries to a .NET project: ```sh dotnet add package DwgIO +dotnet add package DwgIO.Scene ``` -The library targets .NET 8 and .NET 10. It uses managed code without native dependencies or Windows-only APIs and supports Windows, Linux and macOS. Tests currently run on Windows. +The libraries target .NET 8 and .NET 10. They use managed code without native dependencies or Windows-only APIs and support Windows, Linux and macOS. Tests run on Windows, Linux and macOS. ## Command line @@ -49,13 +54,51 @@ Write the decompressed bytes of one named section: dwgio extract drawing.dwg AcDb:Header header.bin ``` -Save the embedded thumbnail preview. Without an extension, `.png`, `.wmf` or `.bmp` is added to match the image: +Save the embedded thumbnail preview. Without an extension, `.png`, `.wmf` or `.bmp` is added to match the image; a mismatching extension is reported on standard error, and a drawing without a thumbnail exits with code 5: ```sh dwgio preview drawing.dwg thumbnail ``` -Errors go to standard error. +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`: + +```sh +dwgio scene drawing.dwg drawing.scene.json --unit mm +``` + +The plain export command writes OBJ and GLB by output extension, through the same scene: + +```sh +dwgio drawing.dwg drawing.obj # Wavefront OBJ + drawing.mtl with the ACI colours +dwgio drawing.dwg drawing.glb # binary glTF for viewers and web scenes +``` + +Draw model space to SVG (X to the right, Y up, ACI colours; `--scale` sets pixels per drawing unit): + +```sh +dwgio svg drawing.dwg drawing.svg --scale 2 +``` + +Open the drawing in a standalone interactive 3D HTML viewer: + +```sh +dwgio drawing.dwg drawing.html +``` + +List the decoded entities, one line each, optionally filtered by type and as JSON: + +```sh +dwgio entities drawing.dwg --type LINE,CIRCLE +dwgio entities drawing.dwg --json +``` + +The JSON export also writes to standard output when the target is `-`: + +```sh +dwgio drawing.dwg - | jq .summaryInfo +``` + +`dwgio --version` prints the package version, `dwgio --help` the usage. Errors go to standard error. ### Exit codes @@ -65,11 +108,12 @@ Errors go to standard error. | 1 | The command line is wrong. | | 2 | The input file does not exist. | | 3 | The DWG version is not supported yet (R13 to R2000, R2007) or not recognised. | -| 4 | The file could not be parsed, the drawing has no thumbnail preview (`preview`), or an unexpected error occurred. | +| 4 | The file could not be parsed, or an unexpected error occurred. | +| 5 | The drawing has no thumbnail preview (`preview`). | ## Library -Open a drawing, list its sections and read one of them: +Open a drawing (from a path or from a stream — a network handle, an archive entry, an already-open file; the stream is read to memory once and `Open(Stream)` gives the same results as `Open(path)`), list its sections and read one of them: ```csharp using System; @@ -79,6 +123,9 @@ var doc = DwgDocument.Open("drawing.dwg"); Console.WriteLine($"{doc.Version.Release} ({doc.Version.Magic})"); +// or from a stream: +// var doc = DwgDocument.Open(httpResponse.Content.ReadAsStream(), "remote.dwg"); + foreach (var section in doc.Sections) { Console.WriteLine($"{section.Name,-24} {section.Size,12} bytes pages={section.PageCount}"); @@ -96,6 +143,19 @@ foreach (var entity in doc.Entities) The JSON export is `DwgJsonExporter` in the `DwgIO.Json` namespace. See [Getting started](docs/getting-started.md) and [Public API](docs/public-api.md) for the supported types. +The scene export is `DwgSceneReader` in the `DwgIO.Scene` package. It converts a drawing into an `IOScene.SceneDocument` — the neutral scene model of the IOExtend tools, shared with RvtIO and NwcIO: + +```csharp +using DwgIO.Scene; + +var scene = DwgSceneReader.Read("drawing.dwg", new DwgSceneOptions { LengthUnit = "mm" }); +IOScene.SceneJson.Save(scene.Document, "drawing.scene.json"); +``` + +Every coordinate is scaled to metres by `LengthUnit` (a DWG stores plain numbers, so the unit is a caller decision and `UnitAssumed` records it), each entity becomes an element with its handle as `SourceId`, and LINE, CIRCLE, ARC and POINT become line and point geometries with their ACI colour. + +`DwgSceneExport` writes that scene out in the exchange formats: `SaveObj(document, "drawing.obj", options)` produces an OBJ with an adjacent MTL colour library (with rollback if replacement fails), `SaveGlb(document, "drawing.glb", options)` produces binary glTF. Both return the same `DwgSceneResult` report. + The documentation site with the API reference is at . [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/IOExtend/DwgIO) offers an automatically generated overview of the repository. ## Status @@ -111,6 +171,10 @@ The documentation site with the API reference is at + + + + + diff --git a/src/DwgIO.Cli/Program.cs b/src/DwgIO.Cli/Program.cs index f2e48aa..6512a89 100644 --- a/src/DwgIO.Cli/Program.cs +++ b/src/DwgIO.Cli/Program.cs @@ -1,22 +1,40 @@ +using System.Globalization; +using System.Reflection; +using System.Text; +using System.Text.Json; using DwgIO; +using DwgIO.Internal; using DwgIO.Json; using DwgIO.Model; +using DwgIO.Scene; +using IOScene; namespace DwgIO.Cli; internal static class Program { + /// Formats a count or byte size with digit grouping, invariantly, so the output does not depend + /// on the machine's locale. + internal static string Count(long value) => value.ToString("N0", CultureInfo.InvariantCulture); + + /// Formats a bare number, invariantly. + internal static string Plain(double value) => value.ToString(CultureInfo.InvariantCulture); + private const int ExitOk = 0; private const int ExitUsage = 1; private const int ExitFileNotFound = 2; private const int ExitUnsupportedVersion = 3; private const int ExitParseError = 4; + private const int ExitNoPreview = 5; + + private static int Main(string[] args) => Run(args, Console.Out, Console.Error); - private static int Main(string[] args) + /// Runs one command. Internal for the CLI tests. + internal static int Run(string[] args, TextWriter output, TextWriter error) { if (args.Length == 0) { - PrintUsage(); + PrintUsage(output); return ExitUsage; } @@ -24,44 +42,80 @@ private static int Main(string[] args) { return args[0] switch { - "inspect" => Inspect(args), - "extract" => Extract(args), - "preview" => Preview(args), - _ => Export(args), + "--version" or "-v" => PrintVersion(output), + "--help" or "-h" => PrintHelp(output), + "inspect" => Inspect(args, output, error), + "extract" => Extract(args, output, error), + "preview" => Preview(args, output, error), + "scene" => Scene(args, output, error), + "svg" => Svg(args, output, error), + "entities" => Entities(args, output, error), + string option when option.StartsWith('-') => UnknownOption(option, output, error), + _ => Export(args, output, error), }; } catch (FileNotFoundException ex) { - Console.Error.WriteLine($"error: {ex.Message}"); + error.WriteLine($"error: {ex.Message}"); return ExitFileNotFound; } catch (DwgUnsupportedVersionException ex) { - Console.Error.WriteLine($"error: {ex.Message}"); + error.WriteLine($"error: {ex.Message}"); return ExitUnsupportedVersion; } catch (DwgException ex) { - Console.Error.WriteLine($"error: {ex.Message}"); + error.WriteLine($"error: {ex.Message}"); return ExitParseError; } catch (Exception ex) { - Console.Error.WriteLine($"unexpected error: {ex.Message}"); + error.WriteLine($"unexpected error: {ex.Message}"); return ExitParseError; } } - private static void PrintUsage() + private static int PrintVersion(TextWriter output) + { + string version = typeof(Program).Assembly.GetCustomAttribute() + ?.InformationalVersion.Split('+')[0] ?? "unknown"; + output.WriteLine(version); + return ExitOk; + } + + private static int PrintHelp(TextWriter output) + { + PrintUsage(output); + return ExitOk; + } + + private static int UnknownOption(string option, TextWriter output, TextWriter error) { - Console.WriteLine(""" + error.WriteLine($"error: unknown option {option}."); + PrintUsage(output); + return ExitUsage; + } + + private static void PrintUsage(TextWriter output) + { + output.WriteLine(""" dwgio — read Autodesk DWG files without AutoCAD Usage: dwgio inspect Print version + section table - dwgio Export metadata + section catalog to JSON + dwgio Export metadata, section catalog and entities to JSON, + or the scene to OBJ (.obj), GLB (.glb) or a standalone + interactive 3D HTML viewer (.html) 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) + 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 + dwgio --version Print the version + dwgio --help Print this usage Sections are named as stored, e.g. AcDb:Header, AcDb:Classes, AcDb:SummaryInfo. """); @@ -70,154 +124,481 @@ dwgio preview Write the embedded thumbnail image private static string Truncate(string text, int maxLength) => text.Length <= maxLength ? text : text[..maxLength] + "…"; - private static int Inspect(string[] args) + private static int Inspect(string[] args, TextWriter output, TextWriter error) { if (args.Length != 2) { - PrintUsage(); + PrintUsage(output); return ExitUsage; } var doc = DwgDocument.Open(args[1]); - Console.WriteLine($"{doc.Path} ({doc.FileSize:N0} bytes)"); - Console.WriteLine($"Version: {doc.Version} codepage={doc.FileHeader.CodepageName} pages={doc.PageCount} headerCrc={(doc.ContainerHeader?.HeaderCrcValid == true ? "ok" : doc.ContainerHeader is null ? "n/a" : "MISMATCH")}"); + return InspectDocument(doc, output); + } + + /// Writes the inspect report of an opened document. Internal for the CLI tests. + internal static int InspectDocument(DwgDocument doc, TextWriter output) + { + output.WriteLine($"{doc.Path} ({Count(doc.FileSize)} bytes)"); + output.WriteLine($"Version: {doc.Version} codepage={doc.FileHeader.CodepageName} pages={doc.PageCount} headerCrc={(doc.ContainerHeader?.HeaderCrcValid == true ? "ok" : doc.ContainerHeader is null ? "n/a" : "MISMATCH")}"); if (doc.SummaryInfo is { } summary) { var title = string.IsNullOrWhiteSpace(summary.Title) ? "(no title)" : summary.Title; - Console.WriteLine($"Summary: \"{title}\" author={summary.Author} savedBy={summary.LastSavedBy} modified={summary.ModifiedUtc:yyyy-MM-dd HH:mm} UTC revision={summary.RevisionNumber}"); + output.WriteLine($"Summary: \"{title}\" author={summary.Author} savedBy={summary.LastSavedBy} modified={summary.ModifiedUtc:yyyy-MM-dd HH:mm} UTC revision={summary.RevisionNumber}"); foreach (var property in summary.Properties) { - Console.WriteLine($" custom: {property.Key} = {property.Value}"); + output.WriteLine($" custom: {property.Key} = {property.Value}"); } } if (doc.AppInfo is { } appInfo) { - Console.WriteLine($"App: {appInfo.Name} version={appInfo.Version} product={appInfo.Product}"); + output.WriteLine($"App: {appInfo.Name} version={appInfo.Version} product={appInfo.Product}"); if (!string.IsNullOrEmpty(appInfo.Comment)) { - Console.WriteLine($" comment: {Truncate(appInfo.Comment, 120)}"); + output.WriteLine($" comment: {Truncate(appInfo.Comment, 120)}"); } } + if (!doc.AppInfoHistory.IsEmpty) + { + output.WriteLine($"App history: {Count(doc.AppInfoHistory.Length)} bytes (raw)"); + } + + if (doc.RevHistory is { } revHistory) + { + output.WriteLine($"Rev history: layout {revHistory.ClassVersion}.{revHistory.ClassMinor} saves={Count(revHistory.Histories.Count)}"); + } + + if (doc.AuxHeader is { } auxHeader) + { + output.WriteLine($"Aux header: saves={Count(auxHeader.Numsaves)} created={auxHeader.CreatedUtc:yyyy-MM-dd HH:mm} UTC updated={auxHeader.ModifiedUtc:yyyy-MM-dd HH:mm} UTC handseed={auxHeader.Handseed:X}"); + } + + if (doc.Template is { } template) + { + string units = template.IsMetric ? "metric" : "english"; + output.WriteLine($"Template: \"{Truncate(template.Description, 60)}\" units={units}"); + } + if (doc.Preview is { } preview) { - Console.WriteLine($"Preview: {preview.ImageKind} {preview.ImageBytes.Length:N0} bytes"); + output.WriteLine($"Preview: {preview.ImageKind} {Count(preview.ImageBytes.Length)} bytes"); } if (doc.FileDepList is { } deps && deps.Files.Count > 0) { - Console.WriteLine($"File dependencies: {deps.Files.Count}"); + output.WriteLine($"File dependencies: {deps.Files.Count}"); foreach (var dep in deps.Files.Take(5)) { - Console.WriteLine($" {dep.Filename} ({dep.FileSize:N0} bytes)"); + output.WriteLine($" {dep.Filename} ({Count(dep.FileSize)} bytes)"); } } if (doc.Objects.Count > 0) { - Console.WriteLine($"Objects: {doc.Objects.Count:N0} (handle map: {doc.HandleMap?.Count ?? 0:N0})"); - foreach (var group in doc.Objects.GroupBy(o => o.TypeCode).OrderByDescending(g => g.Count()).Take(8)) + output.WriteLine($"Objects: {Count(doc.Objects.Count)} (handle map: {Count(doc.HandleMap?.Count ?? 0)})"); + foreach (var group in doc.Objects.GroupBy(o => o.TypeName).OrderByDescending(g => g.Count()).Take(8)) { - Console.WriteLine($" type 0x{group.Key:X3}: {group.Count():N0}"); + output.WriteLine($" {group.Key}: {Count(group.Count())}"); } } if (doc.Entities.Count > 0) { - Console.WriteLine($"Entities decoded: {doc.Entities.Count:N0}"); + output.WriteLine($"Entities decoded: {Count(doc.Entities.Count)}"); foreach (var group in doc.Entities.GroupBy(e => e.Kind).OrderByDescending(g => g.Count())) { - Console.WriteLine($" {group.Key}: {group.Count():N0}"); + output.WriteLine($" {group.Key}: {Count(group.Count())}"); } foreach (var entity in doc.Entities.Where(e => e.Kind != DwgEntityKind.Unknown).Take(5)) { - Console.WriteLine($" {entity}"); + output.WriteLine($" {entity}"); } + } + if (doc.Diagnostics.Count > 0) + { + // Always printed, whether or not any entity was decoded: a failed section shows up here alone. + output.WriteLine($"Diagnostics: {Count(doc.Diagnostics.Count)}"); foreach (var diagnostic in doc.Diagnostics.Take(3)) { - Console.WriteLine($" diagnostics: {diagnostic}"); + output.WriteLine($" {diagnostic}"); } } - Console.WriteLine(); + output.WriteLine(); if (doc.Sections.Count == 0) { - Console.WriteLine("(section map not read)"); + output.WriteLine("(section map not read)"); return ExitOk; } - Console.WriteLine($"{"Name",-28} {"Size",12} {"Pages",6} {"Compr",6} {"Enc",4} Id"); + output.WriteLine($"{"Name",-28} {"Size",12} {"Pages",6} {"Compr",6} {"Enc",4} Id"); foreach (var s in doc.Sections) { - Console.WriteLine($"{s.Name,-28} {s.Size,12:N0} {s.PageCount,6} {s.Compression,6} {s.Encryption,4} {s.SectionId}"); + string name = s.Encryption == 1 ? $"{s.Name} [encrypted]" : s.Name; + output.WriteLine($"{name,-28} {Count(s.Size),12} {s.PageCount,6} {s.Compression,6} {s.Encryption,4} {s.SectionId}"); } return ExitOk; } - private static int Export(string[] args) + private static int Export(string[] args, TextWriter output, TextWriter error) { if (args.Length != 2) { - PrintUsage(); + PrintUsage(output); return ExitUsage; } var doc = DwgDocument.Open(args[0]); - DwgJsonExporter.WriteFile(doc, args[1], DwgJsonExportOptions.Default); - Console.WriteLine($"{doc.Version} sections={doc.Sections.Count} -> {args[1]}"); + return ExportDocument(doc, args[1], output, error); + } + + /// Exports an opened document to a target path, where - means standard output. Internal for the CLI tests. + internal static int ExportDocument(DwgDocument doc, string target, TextWriter output, TextWriter error) + { + if (target == "-") + { + // The JSON export to standard output: no summary line may pollute the stream. + using var json = new MemoryStream(); + DwgJsonExporter.Write(doc, json, DwgJsonExportOptions.Default); + output.Write(Encoding.UTF8.GetString(json.ToArray())); + return ExitOk; + } + + if (Path.GetExtension(target).Equals(".obj", StringComparison.OrdinalIgnoreCase)) + { + var objResult = DwgSceneExport.SaveObj(doc, target); + output.WriteLine($"{doc.Version} elements={objResult.ElementCount} ({objResult.ElementsWithGeometry} with geometry) -> {target}"); + } + else if (Path.GetExtension(target).Equals(".glb", StringComparison.OrdinalIgnoreCase)) + { + var glbResult = DwgSceneExport.SaveGlb(doc, target); + output.WriteLine($"{doc.Version} elements={glbResult.ElementCount} ({glbResult.ElementsWithGeometry} with geometry) -> {target}"); + } + else if (Path.GetExtension(target).Equals(".html", StringComparison.OrdinalIgnoreCase)) + { + var htmlResult = DwgViewerExport.SaveViewer(doc, target); + output.WriteLine($"{doc.Version} elements={htmlResult.ElementCount} ({htmlResult.ElementsWithGeometry} with geometry) -> {target}"); + } + else + { + DwgJsonExporter.WriteFile(doc, target, DwgJsonExportOptions.Default); + output.WriteLine($"{doc.Version} sections={doc.Sections.Count} -> {target}"); + } + return ExitOk; } - private static int Extract(string[] args) + private static int Extract(string[] args, TextWriter output, TextWriter error) { if (args.Length != 4) { - PrintUsage(); + PrintUsage(output); return ExitUsage; } var doc = DwgDocument.Open(args[1]); var bytes = doc.ReadSection(args[2]); File.WriteAllBytes(args[3], bytes); - Console.WriteLine($"{args[2]}: {bytes.Length:N0} bytes -> {args[3]}"); + output.WriteLine($"{args[2]}: {Count(bytes.Length)} bytes -> {args[3]}"); + return ExitOk; + } + + private static int Svg(string[] args, TextWriter output, TextWriter error) + { + double scale = 1.0; + var positional = new List(2); + for (int i = 1; i < args.Length; i++) + { + if (args[i] == "--scale") + { + if (i + 1 >= args.Length || !double.TryParse(args[i + 1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out scale) || !double.IsFinite(scale) || scale <= 0) + { + error.WriteLine("error: --scale needs a positive number of pixels per drawing unit."); + return ExitUsage; + } + + i++; + } + else + { + positional.Add(args[i]); + } + } + + if (positional.Count != 2) + { + PrintUsage(output); + return ExitUsage; + } + + var doc = DwgDocument.Open(positional[0]); + DwgSvgExporter.WriteFile(doc, positional[1], new DwgSvgOptions { Scale = scale }); + output.WriteLine($"{doc.Version} entities={Count(doc.Entities.Count)} -> {positional[1]}"); return ExitOk; } - private static int Preview(string[] args) + private static int Scene(string[] args, TextWriter output, TextWriter error) + { + string? unit = null; + var positional = new List(3); + for (int i = 1; i < args.Length; i++) + { + if (args[i] == "--unit") + { + if (i + 1 >= args.Length) + { + error.WriteLine("error: --unit needs a value (mm, cm, m, ft or in)."); + return ExitUsage; + } + + unit = args[++i]; + } + else + { + positional.Add(args[i]); + } + } + + if (positional.Count != 2) + { + PrintUsage(output); + return ExitUsage; + } + + var options = new DwgSceneOptions(); + if (unit is not null) + { + if (!DwgSceneReader.IsSupportedUnit(unit)) + { + error.WriteLine($"error: unknown length unit '{unit}'. Use mm, cm, m, ft or in."); + return ExitUsage; + } + + options.LengthUnit = unit; + } + + var result = DwgSceneReader.Read(positional[0], options); + 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]}"); + foreach (var diagnostic in result.Diagnostics.Take(5)) + { + output.WriteLine($" {diagnostic.Severity.ToString().ToLowerInvariant()}: {diagnostic.Message}"); + } + + if (result.Diagnostics.Count > 5) + { + output.WriteLine($" ... and {Count(result.Diagnostics.Count - 5)} more"); + } + + return ExitOk; + } + + private static int Preview(string[] args, TextWriter output, TextWriter error) { if (args.Length != 3) { - PrintUsage(); + PrintUsage(output); return ExitUsage; } var doc = DwgDocument.Open(args[1]); + return PreviewDocument(doc, args[2], output, error); + } + + /// Writes the thumbnail of an opened document. Internal for the CLI tests. + internal static int PreviewDocument(DwgDocument doc, string requested, TextWriter output, TextWriter error) + { + if (doc.PreviewReadError is not null) + { + error.WriteLine($"error: {doc.PreviewReadError}"); + return ExitParseError; + } + var preview = doc.Preview; if (preview is null || !preview.HasImage) { - Console.Error.WriteLine("error: this drawing has no thumbnail preview."); - return ExitParseError; + error.WriteLine("error: this drawing has no thumbnail preview."); + return ExitNoPreview; + } + + var (target, warning) = ResolvePreviewTarget(preview.ImageKind, requested); + if (warning is not null) + { + error.WriteLine(warning); } - var extension = preview.ImageKind switch + File.WriteAllBytes(target, preview.ImageBytes); + output.WriteLine($"Preview: {preview.ImageKind} {Count(preview.ImageBytes.Length)} bytes -> {target}"); + return ExitOk; + } + + /// Chooses the output path for a preview: the kind's extension is added when the path has none, and + /// a mismatching extension is reported instead of being changed. Internal for the CLI tests. + internal static (string Target, string? Warning) ResolvePreviewTarget(DwgPreviewImageKind kind, string requested) + { + string expected = kind switch { DwgPreviewImageKind.Png => ".png", DwgPreviewImageKind.Wmf => ".wmf", _ => ".bmp", }; - var target = args[2]; - if (!Path.HasExtension(target) && target.EndsWith(Path.DirectorySeparatorChar) is false && target.EndsWith('/') is false) + bool isDirectory = requested.EndsWith(Path.DirectorySeparatorChar) || requested.EndsWith('/'); + if (!Path.HasExtension(requested) || isDirectory) { - target += extension; + return (requested + expected, null); + } + + string actual = Path.GetExtension(requested); + if (!actual.Equals(expected, StringComparison.OrdinalIgnoreCase)) + { + return (requested, $"warning: the image is {kind} (expected {expected}); the requested path keeps {actual}"); + } + + return (requested, null); + } + + /// Lists decoded entities, one line each, or as a JSON array with --json (#19). + private static int Entities(string[] args, TextWriter output, TextWriter error) + { + string? file = null; + string? types = null; + bool json = false; + for (int i = 1; i < args.Length; i++) + { + switch (args[i]) + { + case "--type": + if (i + 1 >= args.Length) + { + error.WriteLine("error: --type needs a comma-separated list of type names (e.g. LINE,CIRCLE)."); + return ExitUsage; + } + + types = args[++i]; + break; + case "--json": + json = true; + break; + case string option when option.StartsWith('-'): + return UnknownOption(option, output, error); + default: + if (file is not null) + { + error.WriteLine($"error: unexpected argument '{args[i]}'."); + return ExitUsage; + } + + file = args[i]; + break; + } + } + + HashSet? filter = null; + if (types is not null) + { + filter = []; + foreach (string name in types.Split(',')) + { + string trimmed = name.Trim(); + if (trimmed.Length == 0) + { + continue; + } + + if (!DwgObjectTypes.KnownNames.Contains(trimmed)) + { + error.WriteLine($"error: unknown type '{trimmed}'. Known types include LINE, CIRCLE, ARC, POINT, TEXT and MTEXT."); + return ExitUsage; + } + + filter.Add(trimmed); + } + + if (filter.Count == 0) + { + error.WriteLine("error: --type needs at least one type name."); + return ExitUsage; + } + } + + if (file is null) + { + PrintUsage(output); + return ExitUsage; + } + + var doc = DwgDocument.Open(file); + return EntitiesDocument(doc, json, filter, output); + } + + /// Writes the entities of an opened document, filtered by type; internal for the CLI tests. + internal static int EntitiesDocument(DwgDocument document, bool json, HashSet? filter, TextWriter output) + { + IEnumerable entities = document.Entities; + if (filter is not null) + { + entities = entities.Where(e => filter.Contains(e.TypeName)); + } + + if (json) + { + WriteEntitiesJson(output, entities); + } + else + { + foreach (var entity in entities) + { + output.WriteLine(entity.ToString()); + } } - File.WriteAllBytes(target, preview.ImageBytes); - Console.WriteLine($"Preview: {preview.ImageKind} {preview.ImageBytes.Length:N0} bytes -> {target}"); return ExitOk; } + + private static void WriteEntitiesJson(TextWriter output, IEnumerable entities) + { + using var json = new MemoryStream(); + using (var writer = new Utf8JsonWriter(json, new JsonWriterOptions { Indented = false })) + { + writer.WriteStartArray(); + foreach (var entity in entities) + { + writer.WriteStartObject(); + writer.WriteString("type", entity.TypeName); + writer.WriteString("handle", entity.Handle.ToString("X", CultureInfo.InvariantCulture)); + writer.WriteString("kind", entity.Kind.ToString()); + if (entity.Geometry is { } geometry) + { + writer.WriteStartArray("geometry"); + foreach (var value in geometry) + { + if (double.IsFinite(value)) + { + writer.WriteNumberValue(Math.Round(value, 6)); + } + else + { + writer.WriteNullValue(); + } + } + + writer.WriteEndArray(); + } + + writer.WriteNumber("colorIndex", entity.ColorIndex); + writer.WriteEndObject(); + } + + writer.WriteEndArray(); + } + + output.Write(Encoding.UTF8.GetString(json.ToArray())); + } } diff --git a/src/DwgIO.Scene/ArcAngles.cs b/src/DwgIO.Scene/ArcAngles.cs new file mode 100644 index 0000000..1828ad2 --- /dev/null +++ b/src/DwgIO.Scene/ArcAngles.cs @@ -0,0 +1,17 @@ +namespace DwgIO.Scene; + +internal static class ArcAngles +{ + public static (double Start, double Span) Normalize(double start, double end) + { + start = PositiveAngle(start); + double span = PositiveAngle(end) - start; + return (start, span <= 0 ? span + Math.Tau : span); + } + + public static double PositiveAngle(double radians) + { + double turn = radians % Math.Tau; + return turn < 0 ? turn + Math.Tau : turn; + } +} diff --git a/src/DwgIO.Scene/DwgAciPalette.cs b/src/DwgIO.Scene/DwgAciPalette.cs new file mode 100644 index 0000000..f0204b0 --- /dev/null +++ b/src/DwgIO.Scene/DwgAciPalette.cs @@ -0,0 +1,51 @@ +namespace DwgIO.Scene; + +/// +/// The AutoCAD Color Index palette (DXF 62): the fixed RGB values of indexes 1-255, as AutoCAD shows them. +/// Position in the table is the index. Index 0 (BYBLOCK) and 256 (BYLAYER) are not in the table: they name a +/// colour source, not a colour; the scene reader leaves the colour to the consumer until layers and blocks are +/// decoded. +/// +/// +/// Values from the published AutoCAD palette: fixed values for 1-9, 24 hue rows of 10 shades for 10-249 and the +/// 250-255 grays; duplicated pairs (1 and 10, 2 and 50, 7 and 255, ...) share their RGB. +/// +internal static class DwgAciPalette +{ + private static readonly int[] Rgb = + [ + 0x000000, 0xFF0000, 0xFFFF00, 0x00FF00, 0x00FFFF, 0x0000FF, 0xFF00FF, 0xFFFFFF, 0x808080, 0xC0C0C0, // 0 = placeholder; 1-9 = base colours + 0xFF0000, 0xFF8080, 0xA60000, 0xA65353, 0x800000, 0x804040, 0x4D0000, 0x4D2626, 0x260000, 0x261313, // 10-19 + 0xFF4000, 0xFF9F80, 0xA62900, 0xA66853, 0x802000, 0x805040, 0x4D1300, 0x4D3026, 0x260A00, 0x261813, // 20-29 + 0xFF8000, 0xFFBF80, 0xA65300, 0xA67C53, 0x804000, 0x806040, 0x4D2600, 0x4D3926, 0x261300, 0x261D13, // 30-39 + 0xFFBF00, 0xFFDF80, 0xA67C00, 0xA69153, 0x806000, 0x807040, 0x4D3900, 0x4D4326, 0x261D00, 0x262113, // 40-49 + 0xFFFF00, 0xFFFF80, 0xA6A600, 0xA6A653, 0x808000, 0x808040, 0x4D4D00, 0x4D4D26, 0x262600, 0x262613, // 50-59 + 0xBFFF00, 0xDFFF80, 0x7CA600, 0x91A653, 0x608000, 0x708040, 0x394D00, 0x434D26, 0x1D2600, 0x212613, // 60-69 + 0x80FF00, 0xBFFF80, 0x53A600, 0x7CA653, 0x408000, 0x608040, 0x264D00, 0x394D26, 0x132600, 0x1D2613, // 70-79 + 0x40FF00, 0x9FFF80, 0x29A600, 0x68A653, 0x208000, 0x508040, 0x134D00, 0x304D26, 0x0A2600, 0x182613, // 80-89 + 0x00FF00, 0x80FF80, 0x00A600, 0x53A653, 0x008000, 0x408040, 0x004D00, 0x264D26, 0x002600, 0x132613, // 90-99 + 0x00FF40, 0x80FF9F, 0x00A629, 0x53A668, 0x008020, 0x408050, 0x004D13, 0x264D30, 0x00260A, 0x132618, // 100-109 + 0x00FF80, 0x80FFBF, 0x00A653, 0x53A67C, 0x008040, 0x408060, 0x004D26, 0x264D39, 0x002613, 0x13261D, // 110-119 + 0x00FFBF, 0x80FFDF, 0x00A67C, 0x53A691, 0x008060, 0x408070, 0x004D39, 0x264D43, 0x00261D, 0x132621, // 120-129 + 0x00FFFF, 0x80FFFF, 0x00A6A6, 0x53A6A6, 0x008080, 0x408080, 0x004D4D, 0x264D4D, 0x002626, 0x132626, // 130-139 + 0x00BFFF, 0x80DFFF, 0x007CA6, 0x5391A6, 0x006080, 0x407080, 0x00394D, 0x26434D, 0x001D26, 0x132126, // 140-149 + 0x0080FF, 0x80BFFF, 0x0053A6, 0x537CA6, 0x004080, 0x406080, 0x00264D, 0x26394D, 0x001326, 0x131D26, // 150-159 + 0x0040FF, 0x809FFF, 0x0029A6, 0x5368A6, 0x002080, 0x405080, 0x00134D, 0x26304D, 0x000A26, 0x131826, // 160-169 + 0x0000FF, 0x8080FF, 0x0000A6, 0x5353A6, 0x000080, 0x404080, 0x00004D, 0x26264D, 0x000026, 0x131326, // 170-179 + 0x4000FF, 0x9F80FF, 0x2900A6, 0x6853A6, 0x200080, 0x504080, 0x13004D, 0x30264D, 0x0A0026, 0x181326, // 180-189 + 0x8000FF, 0xBF80FF, 0x5300A6, 0x7C53A6, 0x400080, 0x604080, 0x26004D, 0x39264D, 0x130026, 0x1D1326, // 190-199 + 0xBF00FF, 0xDF80FF, 0x7C00A6, 0x9153A6, 0x600080, 0x704080, 0x39004D, 0x43264D, 0x1D0026, 0x211326, // 200-209 + 0xFF00FF, 0xFF80FF, 0xA600A6, 0xA653A6, 0x800080, 0x804080, 0x4D004D, 0x4D264D, 0x260026, 0x261326, // 210-219 + 0xFF00BF, 0xFF80DF, 0xA6007C, 0xA65391, 0x800060, 0x804070, 0x4D0039, 0x4D2643, 0x26001D, 0x261321, // 220-229 + 0xFF0080, 0xFF80BF, 0xA60053, 0xA6537C, 0x800040, 0x804060, 0x4D0026, 0x4D2639, 0x260013, 0x26131D, // 230-239 + 0xFF0040, 0xFF809F, 0xA60029, 0xA65368, 0x800020, 0x804050, 0x4D0013, 0x4D2630, 0x26000A, 0x261318, // 240-249 + 0x545454, 0x767676, 0x989898, 0xBBBBBB, 0xDDDDDD, 0xFFFFFF, // 250-255 = grays + ]; + + /// RGB of an AutoCAD Color Index; index 0 and 256 resolve to white (index 7). + public static (byte R, byte G, byte B) RgbOf(int index) + { + int stored = Rgb[index is > 0 and < 256 ? index : 7]; + return ((byte)(stored >> 16 & 0xFF), (byte)(stored >> 8 & 0xFF), (byte)(stored & 0xFF)); + } +} diff --git a/src/DwgIO.Scene/DwgIO.Scene.csproj b/src/DwgIO.Scene/DwgIO.Scene.csproj new file mode 100644 index 0000000..c333a16 --- /dev/null +++ b/src/DwgIO.Scene/DwgIO.Scene.csproj @@ -0,0 +1,37 @@ + + + + Turns an AutoCAD drawing read by DwgIO into an IOScene scene document: decoded model-space geometry as lines and points, drawing-unit scale, ACI entity colours and producer metadata. + dwg;autocad;autodesk;cad;ioscene;scene;bim + true + + $(NoWarn);NU5104 + + + + + + + + + + + + + + + + + + + + + + + <_Pinned Include="@(_ProjectReferencesWithVersions)">[%(_ProjectReferencesWithVersions.ProjectVersion)] + <_ProjectReferencesWithVersions Remove="@(_ProjectReferencesWithVersions)" /> + <_ProjectReferencesWithVersions Include="@(_Pinned)" /> + + + + diff --git a/src/DwgIO.Scene/DwgSceneExport.cs b/src/DwgIO.Scene/DwgSceneExport.cs new file mode 100644 index 0000000..a2b3db4 --- /dev/null +++ b/src/DwgIO.Scene/DwgSceneExport.cs @@ -0,0 +1,143 @@ +using System.Security.Cryptography; +using System.Text; +using DwgIO.Internal; +using IOScene; +using IOScene.Formats; + +namespace DwgIO.Scene; + +/// +/// Exports a drawing to the mesh and viewer formats the IOScene toolchain writes: Wavefront OBJ with an +/// adjacent MTL library and binary glTF (GLB). Both go through the IOScene scene document, so colors, line +/// and point topologies and instancing behave exactly as in the scene JSON export. +/// +public static class DwgSceneExport +{ + /// Converts the drawing and writes it to a Wavefront OBJ file with an adjacent MTL library + /// (<objPath> with .mtl instead of its extension). + /// The drawing, for example from . + /// Path to the OBJ file; the MTL library is written beside it. + /// Conversion options; null uses the defaults. + /// The conversion report. is the intermediate scene. + public static DwgSceneResult SaveObj(DwgDocument document, string objPath, DwgSceneOptions? options = null) + { + var result = DwgSceneReader.Read(document, OptionsFor(document, objPath, options)); + WriteObj(result.Document, objPath); + return result; + } + + /// Writes a scene to a Wavefront OBJ file with an adjacent MTL library + /// (<objPath> with .mtl instead of its extension). The pair is replaced so that a + /// failure at any step leaves the previous pair untouched: the old MTL is first renamed aside, the new + /// MTL moves in, and the OBJ — which names that MTL in its mtllib — moves in last, after which + /// the old MTL backup is dropped. + /// The scene to export. + /// Path to the OBJ file. + public static void WriteObj(SceneDocument scene, string objPath) + { + ArgumentNullException.ThrowIfNull(scene); + ArgumentException.ThrowIfNullOrEmpty(objPath); + string fullPath = Path.GetFullPath(objPath); + string directory = Path.GetDirectoryName(fullPath) ?? Directory.GetCurrentDirectory(); + if (Path.GetExtension(fullPath).Equals(".mtl", StringComparison.OrdinalIgnoreCase)) + { + throw new ArgumentException("The OBJ destination must differ from its material file.", nameof(objPath)); + } + + string objName = Path.GetFileName(fullPath); + string mtlName = Path.ChangeExtension(objName, ".mtl"); + if (mtlName.Any(c => char.IsWhiteSpace(c) || char.IsControl(c) || c is ':' or '#' or '\\')) + { + mtlName = $"materials-{Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(objName)))}.mtl"; + } + + string mtlPath = Path.Combine(directory, mtlName); + string? objTemp = null; + string? mtlTemp = null; + string? mtlBackup = null; + bool mtlReplaced = false; + try + { + objTemp = AtomicOutput.CreateTemporary(fullPath); + mtlTemp = AtomicOutput.CreateTemporary(mtlPath); + // Both temporary files are written first; the OBJ names the MTL by its stable name. + using (var objStream = new FileStream(objTemp, FileMode.Truncate, FileAccess.Write, FileShare.None)) + using (var objWriter = new StreamWriter(objStream, new System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: false))) + using (var mtlStream = new FileStream(mtlTemp, FileMode.Truncate, FileAccess.Write, FileShare.None)) + using (var mtlWriter = new StreamWriter(mtlStream, new System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: false))) + { + ObjSceneWriter.Write(scene, objWriter, mtlWriter, mtlName); + } + + // The old MTL steps aside first, so it can step back in when either move fails. + if (File.Exists(mtlPath)) + { + mtlBackup = Path.Combine(directory, $".dwgio-{Guid.NewGuid():N}.bak"); + File.Move(mtlPath, mtlBackup); + } + + File.Move(mtlTemp, mtlPath, overwrite: true); + mtlReplaced = true; + File.Move(objTemp, fullPath, overwrite: true); + if (mtlBackup is not null) + { + AtomicOutput.TryDelete(mtlBackup); + } + } + catch + { + // Restore the previous pair: the old MTL comes back, and a fresh export leaves no MTL behind. + if (mtlBackup is not null && File.Exists(mtlBackup)) + { + File.Move(mtlBackup, mtlPath, overwrite: true); + } + else if (mtlReplaced && File.Exists(mtlPath)) + { + File.Delete(mtlPath); + } + + throw; + } + finally + { + AtomicOutput.TryDelete(objTemp); + AtomicOutput.TryDelete(mtlTemp); + } + } + + /// Converts the drawing and writes it to a binary glTF (GLB) file. + /// The drawing, for example from . + /// Path to the GLB file. + /// Conversion options; null uses the defaults. + /// The conversion report. is the intermediate scene. + public static DwgSceneResult SaveGlb(DwgDocument document, string glbPath, DwgSceneOptions? options = null) + { + var result = DwgSceneReader.Read(document, OptionsFor(document, glbPath, options)); + WriteGlb(result.Document, glbPath); + return result; + } + + /// Writes a scene to a binary glTF (GLB) file. + /// The scene to export. + /// Path to the GLB file. + public static void WriteGlb(SceneDocument scene, string glbPath) + { + ArgumentNullException.ThrowIfNull(scene); + AtomicOutput.Write(glbPath, stream => GlbSceneWriter.Write(scene, stream)); + } + + private static DwgSceneOptions OptionsFor(DwgDocument document, string path, DwgSceneOptions? options) + { + if (options?.ModelKey is { Length: > 0 }) + { + return options; + } + + // The file name doubles as the model key; a document from memory falls back to the export file name. + return new DwgSceneOptions + { + LengthUnit = options?.LengthUnit ?? "m", + ModelKey = Path.GetFileName(path), + }; + } +} diff --git a/src/DwgIO.Scene/DwgSceneOptions.cs b/src/DwgIO.Scene/DwgSceneOptions.cs new file mode 100644 index 0000000..9a00f22 --- /dev/null +++ b/src/DwgIO.Scene/DwgSceneOptions.cs @@ -0,0 +1,21 @@ +namespace DwgIO.Scene; + +/// Options of the DWG → scene conversion. +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 . + /// + public string LengthUnit { get; set; } = "m"; + + /// + /// 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 + /// is read, which has no file name. + /// + public string? ModelKey { get; set; } +} diff --git a/src/DwgIO.Scene/DwgSceneReader.cs b/src/DwgIO.Scene/DwgSceneReader.cs new file mode 100644 index 0000000..01917f8 --- /dev/null +++ b/src/DwgIO.Scene/DwgSceneReader.cs @@ -0,0 +1,275 @@ +using System.Globalization; +using System.Reflection; +using DwgIO.Model; +using IOScene; +using Vector3d = IOScene.Vector3d; +using RgbaColor = IOScene.RgbaColor; + +namespace DwgIO.Scene; + +/// Converts an AutoCAD drawing, or a read by DwgIO, into a . +/// +/// The scene has one : Key and Name are , +/// else the file name; SourceFormat is dwg; Application is the producer from +/// AcDb:AppInfo; CreatedAt is the summary-info creation time in UTC. The drawing's entities become +/// flat scene elements with the handle as ; LINE, CIRCLE, ARC and POINT become +/// line and point geometries, tessellated for the round kinds. Every coordinate is scaled to metres by +/// ; the drawing itself names no unit, so the scene records the choice. +/// +public static class DwgSceneReader +{ + private static readonly string Producer = "DwgIO.Scene " + + typeof(DwgSceneReader).Assembly.GetCustomAttribute()!.InformationalVersion.Split('+')[0]; + + // A full circle tessellated into 64 segments (5.6 degrees); an arc gets one segment per 5 degrees, at least 8. + private const int CircleSegments = 64; + private const double ArcRadiansPerSegment = 5.0 * Math.PI / 180.0; + private const int MinArcSegments = 8; + + /// Reads the drawing at with and converts it. + /// The drawing file. + /// Conversion options; null uses the defaults. + /// The scene with a report of the conversion. + /// is empty. + public static DwgSceneResult Read(string path, DwgSceneOptions? options = null) + { + ArgumentException.ThrowIfNullOrEmpty(path); + return Convert(DwgDocument.Open(path), options?.ModelKey ?? Path.GetFileName(path), path, options ?? new DwgSceneOptions()); + } + + /// + /// Converts , which has no file name, so is + /// required. Give a document opened with the default ; a document read with + /// off has no entities, and the scene holds the drawing without geometry. + /// + /// The document. + /// Conversion options with . + /// The scene with a report of the conversion. + /// is null or empty. + public static DwgSceneResult Read(DwgDocument document, DwgSceneOptions options) + { + ArgumentNullException.ThrowIfNull(document); + ArgumentNullException.ThrowIfNull(options); + if (string.IsNullOrEmpty(options.ModelKey)) + { + throw new ArgumentException("DwgSceneOptions.ModelKey must not be empty; a document converted from memory has no file name.", nameof(options)); + } + + return Convert(document, options.ModelKey, null, options); + } + + private static DwgSceneResult Convert(DwgDocument document, string key, string? path, DwgSceneOptions options) + { + double metresPerUnit = MetresPerUnit(options.LengthUnit); + var scene = new SceneDocument { Title = key }; + var diagnostics = new List(); + + scene.Models.Add(new SceneModel + { + Id = 1, + Key = key, + Name = key, + Path = path, + SourceFormat = "dwg", + Producer = Producer, + SourceLengthUnit = options.LengthUnit, + Application = document.AppInfo is { Name.Length: > 0 } appInfo ? appInfo.Name : null, + CreatedAt = document.SummaryInfo?.CreatedUtc?.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture), + }); + + foreach (string message in document.Diagnostics) + { + // Findings from the read: the scene is usable but something in the drawing was skipped. + diagnostics.Add(new SceneDiagnostic(SceneSeverity.Warning, "document", $"{key}: {message}")); + } + + int elementCount = 0; + int elementsWithGeometry = 0; + var withoutGeometry = new SortedDictionary(StringComparer.Ordinal); + int nonFinite = 0; + int geometryId = 0; + + foreach (var entity in document.Entities) + { + elementCount++; + var element = new SceneElement + { + Id = elementCount, + ModelId = 1, + SourceId = entity.Handle.ToString("X", CultureInfo.InvariantCulture), + Name = $"{entity.TypeName} {entity.Handle:X}", + Category = entity.TypeName, + TypeName = entity.TypeName, + }; + scene.Elements.Add(element); + + if (entity.Geometry is { } coordinates && !coordinates.All(double.IsFinite)) + { + nonFinite++; + continue; + } + + Vector3d[]? vertices = entity.Kind switch + { + DwgEntityKind.Line when entity.Geometry is { Length: 6 } g => LineVertices(g, metresPerUnit), + DwgEntityKind.Circle when entity.Geometry is { Length: 4 } g => CircleVertices(g, metresPerUnit), + DwgEntityKind.Arc when entity.Geometry is { Length: 6 } g => ArcVertices(g, metresPerUnit), + DwgEntityKind.Point when entity.Geometry is { Length: 3 } g => PointVertices(g, metresPerUnit), + _ => null, + }; + if (vertices is null) + { + if (entity.Kind == DwgEntityKind.Unknown || entity.Geometry is null) + { + withoutGeometry[entity.TypeName] = withoutGeometry.TryGetValue(entity.TypeName, out int n) ? n + 1 : 1; + } + + continue; + } + + if (!vertices.All(IsFinite)) + { + // The IOScene contract forbids non-finite coordinates; the core JSON export writes them as null, + // the scene drops the geometry and reports it. + nonFinite++; + continue; + } + + elementsWithGeometry++; + geometryId++; + bool isPoint = entity.Kind == DwgEntityKind.Point; + // The contract wants whole pairs for non-indexed lines; polylines share their joints through indices. + IReadOnlyList indices = entity.Kind switch + { + DwgEntityKind.Circle => SharedIndices(CircleSegments, closed: true), + DwgEntityKind.Arc => SharedIndices(vertices!.Length, closed: false), + _ => [], + }; + var geometry = new SceneGeometry + { + Id = geometryId, + Topology = isPoint ? SceneTopology.Points : SceneTopology.Lines, + Vertices = vertices!, + Indices = indices, + }; + scene.Geometries.Add(geometry); + scene.Instances.Add(new SceneInstance + { + ElementId = element.Id, + GeometryId = geometry.Id, + Color = ColourOf(entity.ColorIndex), + }); + } + + if (withoutGeometry.Count > 0) + { + string kinds = string.Join(", ", withoutGeometry.Select(kvp => $"{kvp.Key} {kvp.Value}")); + diagnostics.Add(new SceneDiagnostic(SceneSeverity.Info, "entities-without-geometry", + $"{withoutGeometry.Values.Sum()} entities have no geometry the scene places yet ({kinds}).")); + } + + if (nonFinite > 0) + { + diagnostics.Add(new SceneDiagnostic(SceneSeverity.Warning, "non-finite-geometry", + $"{nonFinite} entities had non-finite coordinates and are placed without geometry.")); + } + + return new DwgSceneResult + { + Document = scene, + Diagnostics = diagnostics, + ElementCount = elementCount, + ElementsWithGeometry = elementsWithGeometry, + EntitiesWithoutGeometry = withoutGeometry.Values.Sum(), + LengthUnit = options.LengthUnit, + MetresPerUnit = metresPerUnit, + UnitAssumed = true, + }; + } + + /// Tells whether accepts . + public static bool IsSupportedUnit(string unit) => unit is "mm" or "cm" or "m" or "ft" or "in"; + + private static double MetresPerUnit(string unit) => unit switch + { + "mm" => 0.001, + "cm" => 0.01, + "m" => 1.0, + "ft" => 0.3048, + "in" => 0.0254, + _ => throw new ArgumentException($"DwgSceneOptions.LengthUnit '{unit}' is not supported; use mm, cm, m, ft or in.", nameof(unit)), + }; + + private static RgbaColor? ColourOf(int colorIndex) + { + if (colorIndex is <= 0 or >= 256) + { + // BYBLOCK (0) and BYLAYER (256) have no colour of their own; the scene leaves the choice to the + // consumer until layers and blocks are decoded. + return null; + } + + (byte r, byte g, byte b) = DwgAciPalette.RgbOf(colorIndex); + return new RgbaColor(r, g, b); + } + + private static Vector3d[] LineVertices(double[] g, double scale) => + [ + new(g[0] * scale, g[1] * scale, g[2] * scale), + new(g[3] * scale, g[4] * scale, g[5] * scale), + ]; + + private static Vector3d[] CircleVertices(double[] g, double scale) + { + double cx = g[0] * scale, cy = g[1] * scale, cz = g[2] * scale; + double radius = g[3] * scale; + var vertices = new Vector3d[CircleSegments]; + for (int i = 0; i < CircleSegments; i++) + { + double angle = 2.0 * Math.PI * i / CircleSegments; + vertices[i] = new Vector3d(cx + radius * Math.Cos(angle), cy + radius * Math.Sin(angle), cz); + } + + return vertices; + } + + private static Vector3d[] ArcVertices(double[] g, double scale) + { + double cx = g[0] * scale, cy = g[1] * scale, cz = g[2] * scale; + double radius = g[3] * scale; + var (start, span) = ArcAngles.Normalize(g[4], g[5]); + + int segments = Math.Clamp((int)Math.Ceiling(span / ArcRadiansPerSegment), MinArcSegments, CircleSegments * 4); + var vertices = new Vector3d[segments + 1]; + for (int i = 0; i <= segments; i++) + { + double angle = start + span * i / segments; + vertices[i] = new Vector3d(cx + radius * Math.Cos(angle), cy + radius * Math.Sin(angle), cz); + } + + return vertices; + } + + private static Vector3d[] PointVertices(double[] g, double scale) => [new(g[0] * scale, g[1] * scale, g[2] * scale)]; + + /// Line indices of a tessellated circle (closed ring) or arc (open chain), sharing the joints. + private static List SharedIndices(int vertexCount, bool closed) + { + var indices = new List((vertexCount - (closed ? 0 : 1)) * 2); + for (int i = 0; i < vertexCount - 1; i++) + { + indices.Add(i); + indices.Add(i + 1); + } + + if (closed) + { + indices.Add(vertexCount - 1); + indices.Add(0); + } + + return indices; + } + + private static bool IsFinite(Vector3d v) => double.IsFinite(v.X) && double.IsFinite(v.Y) && double.IsFinite(v.Z); +} diff --git a/src/DwgIO.Scene/DwgSceneResult.cs b/src/DwgIO.Scene/DwgSceneResult.cs new file mode 100644 index 0000000..c0e4e97 --- /dev/null +++ b/src/DwgIO.Scene/DwgSceneResult.cs @@ -0,0 +1,34 @@ +using IOScene; + +namespace DwgIO.Scene; + +/// +/// The scene of a drawing and the report of the conversion: what was converted, what was left out and why. +/// +public sealed class DwgSceneResult +{ + /// The scene document, with one model per drawing. + public required SceneDocument Document { get; init; } + + /// Findings of the conversion, in the order they were made. + public IReadOnlyList Diagnostics { get; init; } = []; + + /// Number of elements the scene holds. + public int ElementCount { get; init; } + + /// Number of elements that carry at least one geometry. + public int ElementsWithGeometry { get; init; } + + /// Number of entities the drawing decoded but the scene left out, because the record had no usable + /// geometry or a kind the conversion does not place yet. + public int EntitiesWithoutGeometry { get; init; } + + /// The length unit the conversion used, e.g. m. + public string? LengthUnit { get; init; } + + /// Metres per drawing unit the conversion used, or null when unknown. + public double? MetresPerUnit { get; init; } + + /// True when the unit came from the default instead of the drawing, which never names its unit. + public bool UnitAssumed { get; init; } +} diff --git a/src/DwgIO.Scene/DwgSvgExporter.cs b/src/DwgIO.Scene/DwgSvgExporter.cs new file mode 100644 index 0000000..a2807de --- /dev/null +++ b/src/DwgIO.Scene/DwgSvgExporter.cs @@ -0,0 +1,302 @@ +using System.Globalization; +using System.Xml; +using DwgIO.Internal; +using DwgIO.Model; + +namespace DwgIO.Scene; + +/// +/// Draws the model space of a drawing as SVG: LINE, CIRCLE, ARC and POINT entities in the top view, with the +/// drawing's X to the right and Y up, in the entities' ACI colours. The viewBox is the bounding box of +/// everything drawn plus a margin, in drawing units with y flipped, so the output contains every exported entity. +/// +/// +/// This is the first step of issue #32: polylines, curves and text join as the core decodes them. SVG is a 2D +/// format; the drawing's Z is dropped, so entities off the XY plane are drawn flattened onto it. +/// +public static class DwgSvgExporter +{ + /// Writes the model space of to a new SVG file at . + public static void WriteFile(DwgDocument document, string path, DwgSvgOptions? options = null) + { + AtomicOutput.Write(path, stream => Write(document, stream, options)); + } + + /// Writes the model space of to a stream. The stream stays open. + public static void Write(DwgDocument document, Stream output, DwgSvgOptions? options = null) + { + ArgumentNullException.ThrowIfNull(output); + using var writer = XmlWriter.Create(output, new XmlWriterSettings + { + Indent = true, + Encoding = new System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: false), + }); + Write(document, writer, options); + } + + /// Writes the model space of to an XML writer. + public static void Write(DwgDocument document, XmlWriter writer, DwgSvgOptions? options = null) + { + ArgumentNullException.ThrowIfNull(document); + ArgumentNullException.ThrowIfNull(writer); + options ??= new DwgSvgOptions(); + if (!double.IsFinite(options.Scale) || options.Scale <= 0) + { + throw new ArgumentException("DwgSvgOptions.Scale must be finite and positive.", nameof(options)); + } + + if (!double.IsFinite(options.StrokeWidth) || options.StrokeWidth <= 0) + { + throw new ArgumentException("DwgSvgOptions.StrokeWidth must be finite and positive.", nameof(options)); + } + + var shapes = Collect(document, options.Scale); + (double minX, double minY, double width, double height) = ViewBox(shapes); + // Margins and markers are pixel values: they stay fixed while the scale zooms the drawing. + double margin = Math.Max(0.02 * Math.Max(width, height), 8.0); + if (!IsUsable(minX - margin, minY - margin, width + 2 * margin, height + 2 * margin)) + { + throw new ArgumentException("Drawing extents at this scale exceed the SVG coordinate range.", nameof(options)); + } + + double markerRadius = Math.Max(0.015 * Math.Max(width, height), 3.0); + + writer.WriteStartDocument(); + writer.WriteStartElement("svg", "http://www.w3.org/2000/svg"); + writer.WriteAttributeString("viewBox", $"{Num(minX - margin)} {Num(minY - margin)} {Num(width + 2 * margin)} {Num(height + 2 * margin)}"); + writer.WriteAttributeString("width", Num(width + 2 * margin)); + writer.WriteAttributeString("height", Num(height + 2 * margin)); + + writer.WriteStartElement("rect"); + writer.WriteAttributeString("x", Num(minX - margin)); + writer.WriteAttributeString("y", Num(minY - margin)); + writer.WriteAttributeString("width", Num(width + 2 * margin)); + writer.WriteAttributeString("height", Num(height + 2 * margin)); + writer.WriteAttributeString("fill", options.Background); + writer.WriteEndElement(); + + writer.WriteStartElement("g"); + writer.WriteAttributeString("fill", "none"); + writer.WriteAttributeString("stroke", "#000000"); + writer.WriteAttributeString("stroke-width", Num(options.StrokeWidth)); + writer.WriteAttributeString("stroke-linecap", "round"); + + foreach (var shape in shapes) + { + string stroke = ColourOf(shape.ColorIndex); + switch (shape) + { + case SvgLine line: + writer.WriteStartElement("line"); + writer.WriteAttributeString("x1", Num(line.X1)); + writer.WriteAttributeString("y1", Num(line.Y1)); + writer.WriteAttributeString("x2", Num(line.X2)); + writer.WriteAttributeString("y2", Num(line.Y2)); + writer.WriteAttributeString("stroke", stroke); + writer.WriteEndElement(); + break; + case SvgCircle circle: + writer.WriteStartElement("circle"); + writer.WriteAttributeString("cx", Num(circle.Cx)); + writer.WriteAttributeString("cy", Num(circle.Cy)); + writer.WriteAttributeString("r", Num(circle.Radius)); + writer.WriteAttributeString("stroke", stroke); + writer.WriteEndElement(); + break; + case SvgArc arc: + (double x1, double y1, double x2, double y2) = ArcEndpoints(arc); + // The drawing's CCW arc becomes a CW trace in SVG's y-down space, hence sweep 0; the y flip + // is baked into the endpoints already. + writer.WriteStartElement("path"); + writer.WriteAttributeString( + "d", + FormattableString.Invariant( + $"M {Num(x1)} {Num(y1)} A {Num(arc.Radius)} {Num(arc.Radius)} 0 {(arc.Span > Math.PI ? 1 : 0):D} 0 {Num(x2)} {Num(y2)}")); + writer.WriteAttributeString("stroke", stroke); + writer.WriteEndElement(); + break; + case SvgPoint: + writer.WriteStartElement("circle"); + writer.WriteAttributeString("cx", Num(((SvgPoint)shape).X)); + writer.WriteAttributeString("cy", Num(((SvgPoint)shape).Y)); + writer.WriteAttributeString("r", Num(markerRadius)); + writer.WriteAttributeString("fill", stroke); + writer.WriteAttributeString("stroke", "none"); + writer.WriteEndElement(); + break; + } + } + + writer.WriteEndElement(); + writer.WriteEndElement(); + writer.WriteEndDocument(); + } + + private abstract record SvgShape(int ColorIndex); + + private sealed record SvgLine(double X1, double Y1, double X2, double Y2, int ColorIndex) : SvgShape(ColorIndex); + + private sealed record SvgCircle(double Cx, double Cy, double Radius, int ColorIndex) : SvgShape(ColorIndex); + + // Start and span are normalised (span > 0); the endpoints follow in SVG coordinates. + private sealed record SvgArc(double Cx, double Cy, double Radius, double Start, double Span, int ColorIndex) + : SvgShape(ColorIndex); + + private sealed record SvgPoint(double X, double Y, int ColorIndex) : SvgShape(ColorIndex); + + private static List Collect(DwgDocument document, double scale) + { + var shapes = new List(); + foreach (var entity in document.Entities) + { + if (!entity.IsModelSpace) + { + continue; + } + + switch (entity.Kind, entity.Geometry) + { + case (DwgEntityKind.Line, [var x1, var y1, var z1, var x2, var y2, var z2]): + if (IsUsable(x1 * scale, y1 * scale, x2 * scale, y2 * scale)) + { + shapes.Add(new SvgLine(x1 * scale, -y1 * scale, x2 * scale, -y2 * scale, entity.ColorIndex)); + } + else + { + Skip(document, entity, "non-finite coordinates"); + } + + break; + case (DwgEntityKind.Circle, [var cx, var cy, var cz, var r]): + if (IsUsable((Math.Abs(cx) + r) * scale, (Math.Abs(cy) + r) * scale) && r > 0) + { + shapes.Add(new SvgCircle(cx * scale, -cy * scale, r * scale, entity.ColorIndex)); + } + else + { + Skip(document, entity, "non-finite or non-positive radius"); + } + + break; + case (DwgEntityKind.Arc, [var cx, var cy, _, var r, var start, var end]): + if (IsUsable((Math.Abs(cx) + r) * scale, (Math.Abs(cy) + r) * scale, start, end) && r > 0) + { + var (arcStart, span) = ArcAngles.Normalize(start, end); + shapes.Add(span == Math.Tau + ? new SvgCircle(cx * scale, -cy * scale, r * scale, entity.ColorIndex) + : new SvgArc(cx * scale, -cy * scale, r * scale, arcStart, span, entity.ColorIndex)); + } + else + { + Skip(document, entity, "non-finite or non-positive radius"); + } + + break; + case (DwgEntityKind.Point, [var x, var y, _]): + if (IsUsable(x * scale, y * scale)) + { + shapes.Add(new SvgPoint(x * scale, -y * scale, entity.ColorIndex)); + } + else + { + Skip(document, entity, "non-finite coordinates"); + } + + break; + } + } + + return shapes; + } + + private static void Skip(DwgDocument document, DwgEntity entity, string reason) => + document.ReportDiagnostic($"svg: entity {entity.Handle:X} ({entity.TypeName}) skipped: {reason}"); + + private static bool IsUsable(params double[] values) => values.All(double.IsFinite); + + private static (double X1, double Y1, double X2, double Y2) ArcEndpoints(SvgArc arc) => + ( + arc.Cx + arc.Radius * Math.Cos(arc.Start), + arc.Cy - arc.Radius * Math.Sin(arc.Start), + arc.Cx + arc.Radius * Math.Cos(arc.Start + arc.Span), + arc.Cy - arc.Radius * Math.Sin(arc.Start + arc.Span) + ); + + private static (double MinX, double MinY, double Width, double Height) ViewBox(List shapes) + { + double minX = double.PositiveInfinity, minY = double.PositiveInfinity; + double maxX = double.NegativeInfinity, maxY = double.NegativeInfinity; + foreach (var shape in shapes) + { + switch (shape) + { + case SvgLine line: + Expand(line.X1, line.Y1); + Expand(line.X2, line.Y2); + break; + case SvgCircle circle: + Expand(circle.Cx - circle.Radius, circle.Cy - circle.Radius); + Expand(circle.Cx + circle.Radius, circle.Cy + circle.Radius); + break; + case SvgArc arc: + (double x1, double y1, double x2, double y2) = ArcEndpoints(arc); + Expand(x1, y1); + Expand(x2, y2); + // The extremes of the four cardinal directions lie inside the arc when their angle falls + // within its span; without them the view box could cut through the drawn curve. + for (int k = 0; k < 4; k++) + { + double angle = k * Math.PI / 2.0; + if (ArcAngles.PositiveAngle(angle - arc.Start) <= arc.Span) + { + Expand(arc.Cx + arc.Radius * Math.Cos(angle), -Math.Sin(angle) * arc.Radius + arc.Cy); + } + } + + break; + case SvgPoint point: + Expand(point.X, point.Y); + break; + } + } + + if (minX > maxX) + { + return (0, 0, 0, 0); + } + + return (minX, minY, maxX - minX, maxY - minY); + + void Expand(double x, double y) + { + minX = Math.Min(minX, x); + minY = Math.Min(minY, y); + maxX = Math.Max(maxX, x); + maxY = Math.Max(maxY, y); + } + } + + private static string ColourOf(int colorIndex) + { + // BYBLOCK (0) and BYLAYER (256) resolve to the default layer colour, which is 7; on a light background + // AutoCAD renders 7 (white) as black. + int resolved = colorIndex is > 0 and < 256 ? colorIndex : 7; + if (resolved == 7) + { + return "#000000"; + } + + (byte r, byte g, byte b) = DwgAciPalette.RgbOf(resolved); + return FormattableString.Invariant($"#{r:X2}{g:X2}{b:X2}"); + } + + private static string Num(double value) + { + if (value == 0.0) + { + value = 0.0; // normalise -0 + } + + return value.ToString("0.######", CultureInfo.InvariantCulture); + } +} diff --git a/src/DwgIO.Scene/DwgSvgOptions.cs b/src/DwgIO.Scene/DwgSvgOptions.cs new file mode 100644 index 0000000..ce403ce --- /dev/null +++ b/src/DwgIO.Scene/DwgSvgOptions.cs @@ -0,0 +1,19 @@ +namespace DwgIO.Scene; + +/// Options of the SVG export of model space. +public sealed class DwgSvgOptions +{ + /// + /// Pixels per drawing unit. The geometry is scaled by it, so the viewBox, width and + /// height grow together: the drawing keeps its aspect at every scale, and one viewBox unit is + /// one pixel. + /// + public double Scale { get; set; } = 1.0; + + /// Stroke width of the drawn entities, in pixels; it stays fixed while the scale zooms the drawing. + public double StrokeWidth { get; set; } = 1.0; + + /// Background colour, as CSS. AutoCAD renders on a dark background, but SVG files are usually + /// viewed on light ones, so the default is white and colour 7 (white/black) renders black. + public string Background { get; set; } = "white"; +} diff --git a/src/DwgIO.Scene/DwgViewerExport.cs b/src/DwgIO.Scene/DwgViewerExport.cs new file mode 100644 index 0000000..861a597 --- /dev/null +++ b/src/DwgIO.Scene/DwgViewerExport.cs @@ -0,0 +1,67 @@ +using IOViewer.Exporters; +using DwgIO.Internal; +using IOScene; + +namespace DwgIO.Scene; + +/// +/// Exports a drawing as a standalone interactive 3D HTML viewer: one self-contained file with the scene and the +/// WebGL viewer runtime embedded, no server and no external scripts. The viewer is generated by +/// IOViewer from the IOScene scene document, so the +/// drawing shows exactly what the scene JSON and the OBJ/GLB exports describe. +/// +public static class DwgViewerExport +{ + /// Converts the drawing and writes it to a standalone interactive HTML viewer file. + /// The drawing, for example from . + /// Path to the HTML file. + /// Scene conversion options; null uses the defaults. + /// Viewer options (title, initial mode, vertex budget); null uses the defaults. + /// The conversion report. is the scene the viewer embeds. + public static DwgSceneResult SaveViewer( + DwgDocument document, + string htmlPath, + DwgSceneOptions? options = null, + HtmlViewerOptions? viewerOptions = null) + { + var result = DwgSceneReader.Read(document, ViewerOptionsFor(document, htmlPath, options)); + WriteViewer(result.Document, htmlPath, viewerOptions); + return result; + } + + /// Writes a scene to a standalone interactive HTML viewer file. + /// The scene to embed. + /// Path to the HTML file. + /// Viewer options; null uses the defaults. + public static void WriteViewer(SceneDocument scene, string htmlPath, HtmlViewerOptions? viewerOptions = null) + { + ArgumentNullException.ThrowIfNull(scene); + ArgumentException.ThrowIfNullOrEmpty(htmlPath); + if (viewerOptions is null) + { + viewerOptions = new HtmlViewerOptions { Title = scene.Title }; + } + else if (string.IsNullOrEmpty(viewerOptions.Title)) + { + viewerOptions.Title = scene.Title; + } + + var drawableScene = ViewerMeshGeometry.Adapt(scene); + AtomicOutput.Write(htmlPath, stream => HtmlViewerExporter.Export(drawableScene, stream, viewerOptions)); + } + + private static DwgSceneOptions ViewerOptionsFor(DwgDocument document, string path, DwgSceneOptions? options) + { + if (options?.ModelKey is { Length: > 0 }) + { + return options; + } + + // The export file name doubles as the model key; a document from memory falls back to it. + return new DwgSceneOptions + { + LengthUnit = options?.LengthUnit ?? "m", + ModelKey = Path.GetFileName(path), + }; + } +} diff --git a/src/DwgIO.Scene/ViewerMeshGeometry.cs b/src/DwgIO.Scene/ViewerMeshGeometry.cs new file mode 100644 index 0000000..355ef95 --- /dev/null +++ b/src/DwgIO.Scene/ViewerMeshGeometry.cs @@ -0,0 +1,109 @@ +using IOScene; + +namespace DwgIO.Scene; + +internal static class ViewerMeshGeometry +{ + // shortcut: IOViewer 0.3.1 draws triangles only; use thin display meshes until it supports lines and points. + public static SceneDocument Adapt(SceneDocument scene) + { + if (!scene.Geometries.Any(g => g.Topology is SceneTopology.Lines or SceneTopology.Points)) + { + return scene; + } + + var bounds = scene.ComputeBounds(); + double extent = bounds.IsEmpty ? 0 : MaxComponent(bounds.Size); + double halfWidth = extent > 0 && double.IsFinite(extent) ? extent / 1500 : 0.001; + + return new SceneDocument + { + Title = scene.Title, + Models = scene.Models, + Materials = scene.Materials, + Textures = scene.Textures, + PropertySets = scene.PropertySets, + Levels = scene.Levels, + Elements = scene.Elements, + Instances = scene.Instances, + Grids = scene.Grids, + Viewpoints = scene.Viewpoints, + Schedules = scene.Schedules, + ClashTests = scene.ClashTests, + Geometries = scene.Geometries.ConvertAll(g => ToTriangles(g, halfWidth)), + }; + } + + private static SceneGeometry ToTriangles(SceneGeometry geometry, double halfWidth) + { + if (geometry.Topology is not (SceneTopology.Lines or SceneTopology.Points)) + { + return geometry; + } + + bool isLine = geometry.Topology == SceneTopology.Lines; + int count = geometry.Indices.Count == 0 ? geometry.Vertices.Count : geometry.Indices.Count; + int stride = isLine ? 2 : 1; + if (count % stride != 0) + { + throw new InvalidDataException($"Geometry {geometry.Id} has an incomplete line segment."); + } + + var vertices = new List(); + var indices = new List(); + for (int i = 0; i < count; i += stride) + { + Vector3d a = Vertex(i); + Vector3d b = isLine ? Vertex(i + 1) : a; + Vector3d delta = b - a; + double scale = MaxComponent(delta); + double radius = Math.Max(halfWidth, Math.Max(MaxComponent(a), MaxComponent(b)) * 1e-15); + if (scale == 0) + { + AddPoint(a, radius); + continue; + } + + Vector3d axis = (delta / scale).Normalized(); + Vector3d side = Vector3d.Cross(axis, Math.Abs(axis.Z) < 0.9 ? Vector3d.UnitZ : Vector3d.UnitX).Normalized(); + AddRibbon(a, b, side * radius); + AddRibbon(a, b, Vector3d.Cross(axis, side) * radius); + } + + return new SceneGeometry { Id = geometry.Id, Vertices = vertices, Indices = indices }; + + Vector3d Vertex(int i) + { + int index = geometry.Indices.Count == 0 ? i : geometry.Indices[i]; + if ((uint)index >= (uint)geometry.Vertices.Count) + { + throw new InvalidDataException($"Geometry {geometry.Id} references missing vertex {index}."); + } + + var vertex = geometry.Vertices[index]; + if (!double.IsFinite(MaxComponent(vertex))) + { + throw new InvalidDataException($"Geometry {geometry.Id} has a non-finite coordinate."); + } + + return vertex; + } + + void AddRibbon(Vector3d a, Vector3d b, Vector3d side) + { + int first = vertices.Count; + vertices.AddRange([a - side, b - side, b + side, a + side]); + indices.AddRange([first, first + 1, first + 2, first, first + 2, first + 3]); + } + + void AddPoint(Vector3d p, double radius) + { + AddRibbon(p - Vector3d.UnitX * radius, p + Vector3d.UnitX * radius, Vector3d.UnitY * radius); + AddRibbon(p - Vector3d.UnitX * radius, p + Vector3d.UnitX * radius, Vector3d.UnitZ * radius); + AddRibbon(p - Vector3d.UnitY * radius, p + Vector3d.UnitY * radius, Vector3d.UnitZ * radius); + } + } + + private static double MaxComponent(Vector3d vector) => + Math.Max(Math.Abs(vector.X), Math.Max(Math.Abs(vector.Y), Math.Abs(vector.Z))); +} diff --git a/src/DwgIO/DwgDocument.cs b/src/DwgIO/DwgDocument.cs index f6dd35b..49e5612 100644 --- a/src/DwgIO/DwgDocument.cs +++ b/src/DwgIO/DwgDocument.cs @@ -36,6 +36,10 @@ private DwgDocument(string path, byte[] fileBytes, DwgFileHeader fileHeader, R20 AppInfo = TryReadMetadata("AcDb:AppInfo", b => AppInfoParser.Parse(b, fileHeader.Codepage)); FileDepList = TryReadMetadata("AcDb:FileDepList", b => FileDepListParser.Parse(b, fileHeader.Codepage)); Preview = ReadOptionalPreview(); + AppInfoHistory = ReadAppInfoHistory(); + RevHistory = TryReadMetadata("AcDb:RevHistory", b => RevHistoryParser.Parse(b)); + AuxHeader = TryReadMetadata("AcDb:AuxHeader", b => AuxHeaderParser.Parse(b)); + Template = TryReadMetadata("AcDb:Template", b => TemplateParser.Parse(b, fileHeader.Codepage)); } if (options.ReadObjects) @@ -74,12 +78,26 @@ private DwgDocument(string path, byte[] fileBytes, DwgFileHeader fileHeader, R20 /// Producer information from AcDb:AppInfo, when present. public DwgAppInfo? AppInfo { get; } + /// The decompressed AcDb:AppInfoHistory payload when read. Its record layout is unknown. + public ReadOnlyMemory AppInfoHistory { get; } + + /// The save references of AcDb:RevHistory, when present. + public DwgRevHistory? RevHistory { get; } + + /// The auxiliary header of AcDb:AuxHeader, when present (save counters and drawing times). + public DwgAuxHeader? AuxHeader { get; } + + /// The template description of AcDb:Template, when present. + public DwgTemplate? Template { get; } + /// External file dependencies from AcDb:FileDepList, when present. public DwgFileDepList? FileDepList { get; } /// Embedded thumbnail from AcDb:Preview, when present. public DwgPreview? Preview { get; } + internal string? PreviewReadError { get; private set; } + /// Handle→offset index from AcDb:Handles (R2004-family files, ReadObjects on). public DwgHandleMap? HandleMap { get; } @@ -93,7 +111,8 @@ private DwgDocument(string path, byte[] fileBytes, DwgFileHeader fileHeader, R20 public IReadOnlyList Diagnostics { get; } = []; /// Creates an in-memory document over a file header and a fixed entity list (tests). - internal DwgDocument(string path, DwgFileHeader fileHeader, IReadOnlyList entities) + internal DwgDocument(string path, DwgFileHeader fileHeader, IReadOnlyList entities, + DwgPreview? preview = null, IReadOnlyList? objects = null) { Path = path; _fileBytes = []; @@ -102,6 +121,14 @@ internal DwgDocument(string path, DwgFileHeader fileHeader, IReadOnlyListCreates a document over a container built in the tests; reads follow . + internal DwgDocument(string path, R2004Container container, DwgFileHeader fileHeader, DwgReaderOptions options) + : this(path, [], fileHeader, container, options) + { } /// Records a non-fatal problem found after the document was opened (e.g. by an exporter). @@ -131,6 +158,50 @@ public static DwgDocument Open(string path, DwgReaderOptions? options = null) } } + /// + /// Opens and parses a DWG from a stream (a network handle, an archive entry, an already-open file). The + /// stream is read to the end into memory once, so the results are identical to + /// on the same bytes; names the document in , error + /// messages and exports (the default is "stream"). + /// + /// The stream cannot be read. + /// The file's container is not implemented yet (R13-R2000, R2007). + /// The file is corrupt or truncated. + public static DwgDocument Open(Stream stream, string? documentName = null, DwgReaderOptions? options = null) + { + ArgumentNullException.ThrowIfNull(stream); + if (!stream.CanRead) + { + throw new ArgumentException("The stream cannot be read.", nameof(stream)); + } + + options ??= DwgReaderOptions.Default; + string name = string.IsNullOrEmpty(documentName) ? "stream" : documentName; + long? expectedLength = stream.CanSeek ? stream.Length - stream.Position : null; + byte[] fileBytes; + try + { + using var buffer = expectedLength is long length and >= 0 + ? new MemoryStream((int)Math.Min(length, int.MaxValue)) + : new MemoryStream(); + stream.CopyTo(buffer); + fileBytes = buffer.ToArray(); + } + catch (Exception ex) when (ex is not DwgException && IsParseFailure(ex)) + { + throw Corrupt(ex); + } + + try + { + return Parse(name, fileBytes, options); + } + catch (Exception ex) when (ex is not DwgException && IsParseFailure(ex)) + { + throw Corrupt(ex); + } + } + private static DwgDocument Parse(string path, byte[] fileBytes, DwgReaderOptions options) { var fileHeader = DwgFileHeader.Parse(fileBytes); @@ -138,7 +209,7 @@ private static DwgDocument Parse(string path, byte[] fileBytes, DwgReaderOptions if (fileHeader.Version.Family != DwgContainerFamily.R2004Family) { throw new DwgUnsupportedVersionException( - $"{fileHeader.Version.Release} ({fileHeader.Version.Magic}) is not supported yet: " + + $"{path}: {fileHeader.Version.Release} ({fileHeader.Version.Magic}) is not supported yet: " + (fileHeader.Version.Family == DwgContainerFamily.R2007 ? "the R2007 container is planned." : "the R13-R2000 container is planned.")); @@ -176,8 +247,7 @@ private static DwgException Corrupt(Exception ex) => private DwgSummaryInfo? ReadOptionalSummaryInfo() { - var entry = _container!.SectionMap.FindByName("AcDb:SummaryInfo"); - if (entry is null || entry.Encryption == 1) + if (!TryGetReadableSection("AcDb:SummaryInfo", out var entry)) { return null; } @@ -185,17 +255,35 @@ private static DwgException Corrupt(Exception ex) => return TryParseMetadata("AcDb:SummaryInfo", static bytes => SummaryInfoParser.Parse(bytes), entry); } + /// Looks up a named section the reader is expected to parse: present and not encrypted. An + /// encrypted section is reported once, instead of the data simply going missing. + internal bool TryGetReadableSection(string name, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out SectionEntry? entry) + { + entry = _container!.SectionMap.FindByName(name); + if (entry is null) + { + return false; + } + + if (entry.Encryption == 1) + { + _diagnostics.Add($"{name}: the section is encrypted (encryption flag 1) and was skipped; decrypting it is not supported"); + return false; + } + + return true; + } + private DwgHandleMap? ReadOptionalHandleMap() { - var entry = _container!.SectionMap.FindByName("AcDb:Handles"); - if (entry is null || entry.Encryption == 1) + if (!TryGetReadableSection("AcDb:Handles", out var entry)) { return null; } try { - return DwgHandleMap.Parse(ReadSectionCore(entry)); + return DwgHandleMap.Parse(ReadSectionCore(entry), _diagnostics.Add); } catch (Exception ex) when (IsParseFailure(ex)) { @@ -206,8 +294,7 @@ private static DwgException Corrupt(Exception ex) => private IReadOnlyList ReadOptionalObjects() { - var entry = _container!.SectionMap.FindByName("AcDb:AcDbObjects"); - if (entry is null || entry.Encryption == 1) + if (!TryGetReadableSection("AcDb:AcDbObjects", out var entry)) { return []; } @@ -215,7 +302,22 @@ private IReadOnlyList ReadOptionalObjects() try { _objectStreamBytes = ReadSectionCore(entry); - return ObjectStreamWalker.Walk(_objectStreamBytes, r2010Plus: FileHeader.Version.Year >= 2010); + // Drive the walk by the handle map: after a gap it resumes at the next map offset, so records + // beyond the gap are still inventoried instead of silently lost. + var mapOffsets = HandleMap is null + ? null + : HandleMap.Entries.Select(e => e.Offset).Distinct().OrderBy(o => o).ToList(); + var objects = ObjectStreamWalker.Walk(_objectStreamBytes, r2010Plus: FileHeader.Version.Year >= 2010, mapOffsets, _diagnostics.Add); + if (HandleMap is { Count: > 0 } map) + { + int missing = CountUnreachedObjects(objects, map); + if (missing > 0) + { + _diagnostics.Add($"AcDb:AcDbObjects: inventory holds {objects.Count} records; {missing} of {map.Count} handle-map entries were unreached"); + } + } + + return objects; } catch (Exception ex) when (IsParseFailure(ex)) { @@ -224,6 +326,12 @@ private IReadOnlyList ReadOptionalObjects() } } + internal static int CountUnreachedObjects(IReadOnlyList objects, DwgHandleMap map) + { + var reached = objects.Select(o => (o.Handle, (ulong)o.StreamOffset)).ToHashSet(); + return map.Entries.Count(e => !reached.Contains((e.Handle, e.Offset))); + } + private List ReadOptionalEntities() { if (_objectStreamBytes is null) @@ -256,23 +364,45 @@ private List ReadOptionalEntities() return entities; } + private ReadOnlyMemory ReadAppInfoHistory() + { + if (!TryGetReadableSection("AcDb:AppInfoHistory", out var entry)) + { + return ReadOnlyMemory.Empty; + } + + try + { + return ReadSectionCore(entry); + } + catch (Exception ex) when (IsParseFailure(ex)) + { + _diagnostics.Add($"AcDb:AppInfoHistory: {ex.Message}"); + return ReadOnlyMemory.Empty; + } + } + private DwgPreview? ReadOptionalPreview() { - var entry = _container!.SectionMap.FindByName("AcDb:Preview"); - if (entry is null || entry.Encryption == 1) + if (!TryGetReadableSection("AcDb:Preview", out var entry)) { + if (entry is not null) + { + PreviewReadError = _diagnostics[^1]; + } return null; } try { var pageLayout = new List(); - var bytes = _container.ReadSection(_fileBytes, entry, _verifyChecksums, _diagnostics.Add, pageLayout); + var bytes = _container!.ReadSection(_fileBytes, entry, _verifyChecksums, _diagnostics.Add, pageLayout); return PreviewParser.Parse(bytes, pageLayout); } catch (Exception ex) when (IsParseFailure(ex)) { - _diagnostics.Add($"AcDb:Preview: {ex.Message}"); + PreviewReadError = $"AcDb:Preview: {ex.Message}"; + _diagnostics.Add(PreviewReadError); return null; } } @@ -280,8 +410,7 @@ private List ReadOptionalEntities() private T? TryReadMetadata(string sectionName, Func parse) where T : class { - var entry = _container!.SectionMap.FindByName(sectionName); - if (entry is null || entry.Encryption == 1) + if (!TryGetReadableSection(sectionName, out var entry)) { return null; } diff --git a/src/DwgIO/DwgIO.csproj b/src/DwgIO/DwgIO.csproj index 74dacaf..7d6db93 100644 --- a/src/DwgIO/DwgIO.csproj +++ b/src/DwgIO/DwgIO.csproj @@ -8,6 +8,8 @@ + + diff --git a/src/DwgIO/DwgReaderOptions.cs b/src/DwgIO/DwgReaderOptions.cs index 88095fb..62184c3 100644 --- a/src/DwgIO/DwgReaderOptions.cs +++ b/src/DwgIO/DwgReaderOptions.cs @@ -1,6 +1,6 @@ namespace DwgIO; -/// Options controlling what reads. +/// Options controlling what reads. public sealed class DwgReaderOptions { /// Options with every default value. diff --git a/src/DwgIO/Internal/AtomicOutput.cs b/src/DwgIO/Internal/AtomicOutput.cs new file mode 100644 index 0000000..61c1b98 --- /dev/null +++ b/src/DwgIO/Internal/AtomicOutput.cs @@ -0,0 +1,150 @@ +using System.Security.AccessControl; + +namespace DwgIO.Internal; + +internal static class AtomicOutput +{ + public static void Write(string path, Action write) + { + string fullPath = Path.GetFullPath(path); + string temporary = CreateTemporary(fullPath); + try + { + using (var stream = new FileStream(temporary, FileMode.Truncate, FileAccess.Write, FileShare.None)) + { + write(stream); + } + + File.Move(temporary, fullPath, overwrite: true); + } + finally + { + TryDelete(temporary); + } + } + + public static string CreateTemporary(string fullPath) + { + string directory = Path.GetDirectoryName(fullPath) ?? Directory.GetCurrentDirectory(); + string tempPath = Path.Combine(directory, $".dwgio-{Guid.NewGuid():N}.tmp"); + + // Preserve the destination's access rights across the atomic replace: a fresh + // temporary file inherits the directory ACL, which may be more permissive than + // the file being overwritten. Copy the existing rights onto the temporary file + // before any JSON bytes are written; the same-directory move preserves them. + // Reading or applying the rights is mandatory: failures abort the export + // before the destination is touched, instead of silently widening access. + FileSecurity? savedWindowsAcl = null; + UnixFileMode? savedUnixMode = null; + bool destinationExists = File.Exists(fullPath); + if (destinationExists) + { + if (OperatingSystem.IsWindows()) + { + try + { + savedWindowsAcl = new FileInfo(fullPath).GetAccessControl(); + } + catch (PlatformNotSupportedException) + { + savedWindowsAcl = null; + } + } + else if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) + { + try + { + savedUnixMode = File.GetUnixFileMode(fullPath); + } + catch (PlatformNotSupportedException) + { + savedUnixMode = null; + } + } + } + + try + { + using (var stream = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + } + + ApplyTempSecurity(tempPath, savedWindowsAcl, savedUnixMode, destinationExists); + return tempPath; + } + catch + { + TryDelete(tempPath); + throw; + } + } + + private static void ApplyTempSecurity( + string filePath, + FileSecurity? windowsAcl, + UnixFileMode? unixMode, + bool destinationExists) + { + if (!destinationExists) + { + return; + } + + if (OperatingSystem.IsWindows()) + { + if (windowsAcl is null) + { + return; + } + + // Copy only the DACL and its protection flag. Persisting the whole + // FileSecurity (owner/group/SACL) requires SeSecurityPrivilege and, + // when unmodified, persists nothing — the temporary file would keep + // the directory's inherited rules. + new FileInfo(filePath).SetAccessControl(CloneDacl(windowsAcl)); + return; + } + + if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) + { + if (unixMode.HasValue) + { + File.SetUnixFileMode(filePath, unixMode.Value); + } + } + } + + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + private static FileSecurity CloneDacl(FileSecurity source) + { + var clone = new FileSecurity(); + clone.SetAccessRuleProtection(source.AreAccessRulesProtected, preserveInheritance: false); + foreach (FileSystemAccessRule rule in source.GetAccessRules(includeExplicit: true, includeInherited: false, targetType: typeof(System.Security.Principal.SecurityIdentifier))) + { + clone.AddAccessRule(rule); + } + + return clone; + } + + public static void TryDelete(string? path) + { + if (path is null) + { + return; + } + + try + { + File.Delete(path); + } + catch (IOException) + { + // Best-effort cleanup: the original export failure is the error worth reporting. + } + catch (UnauthorizedAccessException) + { + // Best-effort cleanup: the original export failure is the error worth reporting. + } + } +} diff --git a/src/DwgIO/Internal/Container/ObjectStream.cs b/src/DwgIO/Internal/Container/ObjectStream.cs index bed9e13..89bb52f 100644 --- a/src/DwgIO/Internal/Container/ObjectStream.cs +++ b/src/DwgIO/Internal/Container/ObjectStream.cs @@ -14,73 +14,152 @@ internal static class ObjectStreamWalker { private const int MaxRecords = 1 << 21; - /// Walks the object records sequentially and returns their inventory. - public static IReadOnlyList Walk(byte[] data, bool r2010Plus) + /// + /// Walks the object records sequentially and returns their inventory. The walk assumes records follow each + /// other without gaps; when it stops at a broken record and names an offset + /// further on, it reports the gap and resumes at the next handle-map offset, so records after the gap are + /// still inventoried. + /// + /// The decompressed AcDb:AcDbObjects stream. + /// R2010 and later carry the handle-stream size in bits. + /// Handle-map offsets into the stream, ascending, or null when the map is absent. + /// Receives one message per early stop or gap that was skipped. + public static IReadOnlyList Walk( + byte[] data, + bool r2010Plus, + IReadOnlyList? mapOffsets = null, + Action? diagnostic = null) { var objects = new List(); int pos = StartOffset(data); while (pos + 2 < data.Length && objects.Count < MaxRecords) { - var (sizeBytes, prefixLength) = ReadSizePrefix(data, pos); - if (sizeBytes == 0) + var (end, failure, nextPos) = TryReadRecord(data, pos, r2010Plus, objects); + if (!end && failure is null) { - break; // zero-length record: trailing padding — stream end + pos = nextPos; + continue; } - int payloadStart = pos + prefixLength; - int handleBitsWidth = 0; - if (r2010Plus) + // A zero run (padding, or bytes erased in the file) and a broken record both end the sequential + // walk; a handle-map offset beyond the stop point resynchronises it. + int stop = pos; + string reason = end ? "zero run (padding or erased bytes)" : failure!; + int resumed = ResumeAfterGap(data, mapOffsets, stop); + if (resumed > stop) { - int? width = VarUIntWidth(data, payloadStart); - if (width is null) - { - break; // no terminating byte — not a record start - } - - handleBitsWidth = width.Value; + Report(diagnostic, $"object stream: gap at {stop}: {reason}; skipped {resumed - stop} bytes to the next handle-map offset and resumed"); + pos = resumed; + continue; } - long payloadEndLong = (long)payloadStart + sizeBytes + handleBitsWidth; - if (payloadEndLong + 2 > data.Length) + if (end) { - break; // malformed tail + break; // trailing padding: the stream ends here } - int payloadEnd = (int)payloadEndLong; - try + Report(diagnostic, $"object stream: stopped at {stop}: {reason}"); + break; + } + + return objects; + } + + /// + /// Tries to decode the record at ; on success appends it to . + /// Returns End true for a clean stream end (zero-length record) and Failure naming a broken + /// record that a gap resync may recover from. + /// + private static (bool End, string? Failure, int NextPos) TryReadRecord(byte[] data, int pos, bool r2010Plus, List objects) + { + int nextPos = pos; + var (sizeBytes, prefixLength) = ReadSizePrefix(data, pos); + if (sizeBytes == 0) + { + return (End: true, Failure: null, NextPos: nextPos); // zero-length record: trailing padding — stream end + } + + int payloadStart = pos + prefixLength; + int handleBitsWidth = 0; + if (r2010Plus) + { + int? width = VarUIntWidth(data, payloadStart); + if (width is null) { - // The bit-level payload starts right after the size prefix. - int bitsStart = payloadStart; - var reader = new BitReaderMsb(data[bitsStart..payloadEnd]); - if (r2010Plus) - { - reader.ReadVarUInt(); // handle-stream size in bits - } - - ushort typeCode = reader.ReadObjectType(r2010Plus); - var handle = reader.ReadHandle(); - objects.Add(new DwgObjectInfo - { - StreamOffset = pos, - SizeBytes = sizeBytes, - TypeCode = typeCode, - Handle = handle.Value, - StreamHandle = handle, - BitsStart = bitsStart, - BitsLength = payloadEnd - bitsStart, - }); + return (End: false, Failure: "no terminating byte in the handle-stream size", NextPos: nextPos); } - catch (DwgException) + + handleBitsWidth = width.Value; + } + + long payloadEndLong = (long)payloadStart + sizeBytes + handleBitsWidth; + if (payloadEndLong + 2 > data.Length) + { + return (End: false, Failure: $"record of {sizeBytes} bytes runs past the stream end", NextPos: nextPos); + } + + int payloadEnd = (int)payloadEndLong; + try + { + // The bit-level payload starts right after the size prefix. + int bitsStart = payloadStart; + var reader = new BitReaderMsb(data[bitsStart..payloadEnd]); + if (r2010Plus) { - break; // torn record body: keep the walk deterministic by stopping + reader.ReadVarUInt(); // handle-stream size in bits } - pos = payloadEnd + 2; + ushort typeCode = reader.ReadObjectType(r2010Plus); + var handle = reader.ReadHandle(); + objects.Add(new DwgObjectInfo + { + StreamOffset = pos, + SizeBytes = sizeBytes, + TypeCode = typeCode, + Handle = handle.Value, + StreamHandle = handle, + BitsStart = bitsStart, + BitsLength = payloadEnd - bitsStart, + }); + } + catch (DwgException ex) + { + return (End: false, Failure: $"torn record body ({ex.Message})", NextPos: nextPos); } - return objects; + return (End: false, Failure: null, NextPos: payloadEnd + 2); } + /// The first handle-map offset strictly after , or 0 when there is none. + private static int ResumeAfterGap(byte[] data, IReadOnlyList? mapOffsets, int stop) + { + if (mapOffsets is null) + { + return 0; + } + + int low = 0; + int high = mapOffsets.Count; + while (low < high) + { + int mid = low + (high - low) / 2; + if (mapOffsets[mid] <= (ulong)stop) + { + low = mid + 1; + } + else + { + high = mid; + } + } + + return low < mapOffsets.Count && mapOffsets[low] < (ulong)(data.Length - 2) + ? (int)mapOffsets[low] + : 0; + } + + private static void Report(Action? diagnostic, string message) => diagnostic?.Invoke(message); + /// The 0x0DCA stream prefix occupies 4 bytes; otherwise the stream starts at 0. private static int StartOffset(byte[] data) => data.Length >= 4 && data[0] == 0xCA && data[1] == 0x0D && data[2] == 0 && data[3] == 0 ? 4 : 0; diff --git a/src/DwgIO/Internal/Parsing/AppInfoParser.cs b/src/DwgIO/Internal/Parsing/AppInfoParser.cs index 3af9783..40dc693 100644 --- a/src/DwgIO/Internal/Parsing/AppInfoParser.cs +++ b/src/DwgIO/Internal/Parsing/AppInfoParser.cs @@ -1,5 +1,7 @@ using System.Buffers.Binary; using System.Text.RegularExpressions; +using System.Xml; +using System.Xml.Linq; using DwgIO.Model; namespace DwgIO.Internal.Parsing; @@ -24,26 +26,22 @@ internal static partial class AppInfoParser [GeneratedRegex("build_version=\\\\?\"([^\"\\\\]+)")] private static partial Regex BuildVersionRegex(); + [GeneratedRegex("""(?:^|\s)name\s*=\s*"(?[^"]*)"|(?:^|\s)name\s*=\s*'(?[^']*)'""")] + private static partial Regex ProductNameRegex(); + /// Parses an AppInfo payload; decodes 8-bit strings. public static DwgAppInfo Parse(byte[] data, int codepage) { - if (data.Length >= 4) + if (data.Length >= 4 && BinaryPrimitives.ReadUInt32LittleEndian(data) is 2 or 3 + && TryParseUnicode(data, codepage) is { } unicodeInfo) { - uint marker = BinaryPrimitives.ReadUInt32LittleEndian(data); - if (marker is 2 or 3) - { - var unicodeInfo = TryParseUnicode(data, codepage); - if (unicodeInfo is not null) - { - return unicodeInfo; - } - } + return unicodeInfo; } - return ParseAnsi(data, codepage); + return BuildAnsi(data, codepage); } - private static DwgAppInfo ParseAnsi(byte[] data, int codepage) + private static DwgAppInfo BuildAnsi(byte[] data, int codepage) { var cursor = new MetadataByteCursor(data, codepage); var name = cursor.ReadAnsiString16(); @@ -56,6 +54,7 @@ private static DwgAppInfo ParseAnsi(byte[] data, int codepage) Name = name, ProductXml = productXml, Version = version ?? string.Empty, + Product = ExtractProduct(productXml), }; } @@ -109,6 +108,7 @@ private static DwgAppInfo ParseAnsi(byte[] data, int codepage) Version = version, Comment = comment, ProductXml = productXml, + Product = ExtractProduct(productXml), }; } catch (DwgException) @@ -117,6 +117,38 @@ private static DwgAppInfo ParseAnsi(byte[] data, int codepage) } } + /// + /// The product the product XML names: its name attribute ("AutoCAD", "AutoCAD LT", "Teigha(R)", ...), + /// per libredwg's appinfo.spec. Empty when the XML has no readable name attribute. + /// + private static string ExtractProduct(string productXml) + { + if (productXml.Length == 0) + { + return string.Empty; + } + + try + { + using var input = new StringReader(productXml); + using var reader = XmlReader.Create(input, new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit }); + return XElement.Load(reader).Attribute("name")?.Value ?? string.Empty; + } + catch (XmlException) + { + if (productXml.Contains(" read) { try diff --git a/src/DwgIO/Internal/Parsing/AuxHeaderParser.cs b/src/DwgIO/Internal/Parsing/AuxHeaderParser.cs new file mode 100644 index 0000000..9111204 --- /dev/null +++ b/src/DwgIO/Internal/Parsing/AuxHeaderParser.cs @@ -0,0 +1,75 @@ +using System.Buffers.Binary; +using DwgIO.Model; + +namespace DwgIO.Internal.Parsing; + +/// +/// Parses the decompressed AcDb:AuxHeader payload: a fixed 123-byte little-endian layout (plus up +/// to three trailing words in R2018 files), per libredwg's auxheader.spec. AutoCAD's R2018 variant is +/// normalised to the ODA layout before the fields are read. +/// +internal static class AuxHeaderParser +{ + // Offsets into the normalised ODA layout. + private const int MinSize = 123; + + public static DwgAuxHeader Parse(byte[] data) + { + if (data.Length < MinSize) + { + throw new DwgException($"AuxHeader is {data.Length} bytes; the fixed layout needs {MinSize}."); + } + + var bytes = (byte[])data.Clone(); + NormaliseR2018(bytes, data.Length); + var created = ReadTime(bytes, 63); + var modified = ReadTime(bytes, 71); + return new DwgAuxHeader + { + Intro = [bytes[0], bytes[1], bytes[2]], + DwgVersion = ReadU16(bytes, 3), + MaintVersion = ReadU16(bytes, 5), + Numsaves = ReadU32(bytes, 7), + CreatedRaw = created, + ModifiedRaw = modified, + Handseed = ReadU64(bytes, 79), + CreatedUtc = ToUtc(created), + ModifiedUtc = ToUtc(modified), + }; + } + + /// AutoCAD's R2018 auxheader writes the maint_version as 32 bits and two extra words in the + /// version area; when the -1 marker sits at [13..17) instead of [11..15), compact it in place. + private static void NormaliseR2018(byte[] bytes, int length) + { + if (length < 129) + { + return; + } + + uint minusOneOda = ReadU32(bytes, 11); + uint minusOneAcad = ReadU32(bytes, 13); + if (minusOneAcad == 0xFFFFFFFF && minusOneOda != 0xFFFFFFFF) + { + // Compact out the RL-sized maint_version word and the two extra RS fields. + Buffer.BlockCopy(bytes, 9, bytes, 7, 18); // through dwg_version_1 + Buffer.BlockCopy(bytes, 27, bytes, 25, 2); // maint_version_1 + Buffer.BlockCopy(bytes, 31, bytes, 27, 4); // dwg/maint_version_2 + Buffer.BlockCopy(bytes, 37, bytes, 31, 92); // unknown words through zero_8 + Array.Clear(bytes, 123, 6); + } + } + + private static ushort ReadU16(byte[] b, int pos) => BinaryPrimitives.ReadUInt16LittleEndian(b.AsSpan(pos)); + + private static uint ReadU32(byte[] b, int pos) => BinaryPrimitives.ReadUInt32LittleEndian(b.AsSpan(pos)); + + private static ulong ReadU64(byte[] b, int pos) => BinaryPrimitives.ReadUInt64LittleEndian(b.AsSpan(pos)); + + private static (uint, uint) ReadTime(byte[] b, int pos) => (ReadU32(b, pos), ReadU32(b, pos + 4)); + + private static DateTime? ToUtc((uint JulianDay, uint Milliseconds) time) => + SummaryInfoParser.ToDateTimeUtc(time.JulianDay, time.Milliseconds) is long ticks + ? new DateTime(ticks, DateTimeKind.Utc) + : null; +} diff --git a/src/DwgIO/Internal/Parsing/EntityDecoder.cs b/src/DwgIO/Internal/Parsing/EntityDecoder.cs index 2bf276d..95a7376 100644 --- a/src/DwgIO/Internal/Parsing/EntityDecoder.cs +++ b/src/DwgIO/Internal/Parsing/EntityDecoder.cs @@ -10,56 +10,15 @@ namespace DwgIO.Internal.Parsing; /// internal static class EntityDecoder { - private const ushort DictionaryTypeCode = 0x2A; - - /// Well-known DWG type codes (subset covering the common ones). - private static readonly Dictionary TypeNames = new() - { - [0x01] = "TEXT", - [0x02] = "ATTRIB", - [0x03] = "ATTDEF", - [0x04] = "BLOCK", - [0x05] = "ENDBLK", - [0x06] = "SEQEND", - [0x07] = "INSERT", - [0x0B] = "VERTEX", - [0x0F] = "2DPOLYLINE", - [0x10] = "3DPOLYLINE", - [0x11] = "ARC", - [0x12] = "CIRCLE", - [0x13] = "LINE", - [0x1B] = "POINT", - [0x1C] = "3DFACE", - [0x21] = "ELLIPSE", - [0x22] = "VIEWPORT", - [0x24] = "SPLINE", - [0x26] = "3DSOLID", - [0x28] = "RAY", - [0x29] = "XLINE", - [DictionaryTypeCode] = "DICTIONARY", - [0x2C] = "MTEXT", - [0x2D] = "LEADER", - [0x31] = "BLOCK_RECORD", - [0x32] = "LAYER_TABLE", - [0x33] = "LAYER", - [0x34] = "STYLE_TABLE", - [0x35] = "STYLE", - [0x38] = "LTYPE_TABLE", - [0x39] = "LTYPE", - [0x4E] = "HATCH", - [0x4F] = "XRECORD", - }; - - /// Name for a DWG type code, or Object_XX when the code is not in the table. - public static string TypeName(ushort typeCode) => - TypeNames.TryGetValue(typeCode, out var name) ? name : $"Object_{typeCode:X}"; + /// + /// Name for a fixed type code, via . + /// + public static string TypeName(ushort typeCode) => DwgObjectTypes.Name(typeCode); /// - /// Entities are the drawable fixed codes 0x01..0x2F. DICTIONARY (0x2A) shares that range but is a - /// non-graphical object; codes above 0x2F are table, dictionary and control objects. + /// Tells whether a record of this code is a drawable entity; see . /// - public static bool IsEntityCode(ushort typeCode) => - typeCode is >= 0x01 and <= 0x2F and not DictionaryTypeCode; + public static bool IsEntityCode(ushort typeCode) => DwgObjectTypes.IsEntity(typeCode); /// /// Decodes an entity from the record payload (starting right after the size prefix). @@ -99,7 +58,7 @@ public static bool IsEntityCode(ushort typeCode) => reader.SkipBytes((int)graphicsSize); } - reader.ReadTwoBits(); // entity mode + bool isModelSpace = reader.ReadTwoBits() == 2; reader.ReadPackedInt(); // reactor count: back-reference handles consumed from the tail later reader.ReadBit(); // no extension dictionary flag (R2004+) if (year >= 2013) @@ -108,7 +67,10 @@ public static bool IsEntityCode(ushort typeCode) => } uint colorValue = reader.ReadPackedShort(); - int colorIndex = (int)(colorValue & 0xFF); + // The colour index takes the low 9 bits (0 BYBLOCK, 1-255 indexed, 256 BYLAYER); the upper byte holds + // the flag bits, whose bit 0 doubles as the "index 256" bit of a discrete colour (see libredwg's + // common_entity_data.spec, which keeps the same flag = raw >> 8 split). + int colorIndex = (int)(colorValue & 0x1FF); uint colorFlags = colorValue >> 8; if ((colorFlags & 0x40) == 0 && (colorFlags & 0x80) != 0) { @@ -164,6 +126,7 @@ public static bool IsEntityCode(ushort typeCode) => Geometry = body?.geometry, ColorIndex = colorIndex, LineTypeScale = lineTypeScale, + IsModelSpace = isModelSpace, }; } diff --git a/src/DwgIO/Internal/Parsing/RevHistoryParser.cs b/src/DwgIO/Internal/Parsing/RevHistoryParser.cs new file mode 100644 index 0000000..94a4693 --- /dev/null +++ b/src/DwgIO/Internal/Parsing/RevHistoryParser.cs @@ -0,0 +1,38 @@ +using DwgIO.Model; + +namespace DwgIO.Internal.Parsing; + +/// +/// Parses the decompressed AcDb:RevHistory payload: two version words, a count and that many +/// 32-bit values, one per recorded save (per libredwg's revhistory.spec). +/// +internal static class RevHistoryParser +{ + /// Maximum number of history entries accepted before the payload is considered malformed. + private const int MaxHistories = 1 << 20; + + public static DwgRevHistory Parse(byte[] data) + { + var cursor = new MetadataByteCursor(data, 0); + uint version = cursor.ReadU32(); + uint minor = cursor.ReadU32(); + uint count = cursor.ReadU32(); + if (count > MaxHistories) + { + throw new DwgException($"RevHistory declares {count} entries; the sanity cap is {MaxHistories}."); + } + + var histories = new uint[count]; + for (uint i = 0; i < count; i++) + { + histories[i] = cursor.ReadU32(); + } + + return new DwgRevHistory + { + ClassVersion = version, + ClassMinor = minor, + Histories = histories, + }; + } +} diff --git a/src/DwgIO/Internal/Parsing/TemplateParser.cs b/src/DwgIO/Internal/Parsing/TemplateParser.cs new file mode 100644 index 0000000..d7a6a32 --- /dev/null +++ b/src/DwgIO/Internal/Parsing/TemplateParser.cs @@ -0,0 +1,22 @@ +using DwgIO.Model; + +namespace DwgIO.Internal.Parsing; + +/// +/// Parses the decompressed AcDb:Template payload: a counted description string and the unit +/// system word (0 English, 1 metric), per libredwg's template.spec. +/// +internal static class TemplateParser +{ + public static DwgTemplate Parse(byte[] data, int codepage) + { + var cursor = new MetadataByteCursor(data, codepage); + string description = cursor.ReadAnsiString16(); + ushort measurement = cursor.ReadU16(); + return new DwgTemplate + { + Description = description, + Measurement = measurement, + }; + } +} diff --git a/src/DwgIO/Json/DwgJsonExporter.cs b/src/DwgIO/Json/DwgJsonExporter.cs index ca2ab32..48c7aab 100644 --- a/src/DwgIO/Json/DwgJsonExporter.cs +++ b/src/DwgIO/Json/DwgJsonExporter.cs @@ -1,4 +1,4 @@ -using System.Security.AccessControl; +using DwgIO.Internal; using System.Text.Json; namespace DwgIO.Json; @@ -88,6 +88,48 @@ public static void Write(DwgDocument document, Stream output, DwgJsonExportOptio writer.WriteEndObject(); } + if (!document.AppInfoHistory.IsEmpty) + { + writer.WriteStartObject("appInfoHistory"); + writer.WriteNumber("size", document.AppInfoHistory.Length); + writer.WriteEndObject(); + } + + if (document.RevHistory is { } revHistory) + { + writer.WriteStartObject("revHistory"); + writer.WriteNumber("classVersion", revHistory.ClassVersion); + writer.WriteNumber("classMinor", revHistory.ClassMinor); + writer.WriteStartArray("histories"); + foreach (uint history in revHistory.Histories) + { + writer.WriteNumberValue(history); + } + + writer.WriteEndArray(); + writer.WriteEndObject(); + } + + if (document.AuxHeader is { } auxHeader) + { + writer.WriteStartObject("auxHeader"); + writer.WriteNumber("dwgVersion", auxHeader.DwgVersion); + writer.WriteNumber("maintVersion", auxHeader.MaintVersion); + writer.WriteNumber("numsaves", auxHeader.Numsaves); + writer.WriteString("createdUtc", auxHeader.CreatedUtc?.ToString("O")); + writer.WriteString("modifiedUtc", auxHeader.ModifiedUtc?.ToString("O")); + writer.WriteNumber("handseed", auxHeader.Handseed); + writer.WriteEndObject(); + } + + if (document.Template is { } template) + { + writer.WriteStartObject("template"); + writer.WriteString("description", template.Description); + writer.WriteNumber("measurement", template.Measurement); + writer.WriteEndObject(); + } + if (document.Preview is { } preview) { writer.WriteStartObject("preview"); @@ -125,11 +167,19 @@ public static void Write(DwgDocument document, Stream output, DwgJsonExportOptio writer.WriteNumber("count", document.Objects.Count); writer.WriteNumber("handleMapEntries", document.HandleMap?.Count ?? 0); writer.WriteStartObject("byType"); - foreach (var group in document.Objects.GroupBy(o => o.TypeCode).OrderByDescending(g => g.Count())) + var typesByCode = document.Objects.GroupBy(o => o.TypeCode).OrderByDescending(g => g.Count()).ToArray(); + foreach (var group in typesByCode) { writer.WriteNumber(group.Key.ToString("X", System.Globalization.CultureInfo.InvariantCulture), group.Count()); } + writer.WriteEndObject(); + writer.WriteStartObject("byTypeName"); + foreach (var group in typesByCode) + { + writer.WriteNumber(DwgIO.Model.DwgObjectTypes.Name(group.Key), group.Count()); + } + writer.WriteEndObject(); writer.WriteEndObject(); @@ -166,11 +216,8 @@ public static void Write(DwgDocument document, Stream output, DwgJsonExportOptio } } - if (entity.ColorIndex != 0) - { - writer.WriteNumber("colorIndex", entity.ColorIndex); - } - + // Written always: 0 (BYBLOCK) and 256 (BYLAYER) must be distinguishable. + writer.WriteNumber("colorIndex", entity.ColorIndex); writer.WriteEndObject(); } @@ -211,131 +258,7 @@ public static void Write(DwgDocument document, Stream output, DwgJsonExportOptio /// Writes as JSON to a new file at . public static void WriteFile(DwgDocument document, string path, DwgJsonExportOptions options) { - var fullPath = Path.GetFullPath(path); - var directory = Path.GetDirectoryName(fullPath) ?? Directory.GetCurrentDirectory(); - var tempPath = Path.Combine(directory, $".dwgio-{Guid.NewGuid():N}.tmp"); - - // Preserve the destination's access rights across the atomic replace: a fresh - // temporary file inherits the directory ACL, which may be more permissive than - // the file being overwritten. Copy the existing rights onto the temporary file - // before any JSON bytes are written; the same-directory move preserves them. - // Reading or applying the rights is mandatory: failures abort the export - // before the destination is touched, instead of silently widening access. - FileSecurity? savedWindowsAcl = null; - UnixFileMode? savedUnixMode = null; - bool destinationExists = File.Exists(fullPath); - if (destinationExists) - { - if (OperatingSystem.IsWindows()) - { - try - { - savedWindowsAcl = new FileInfo(fullPath).GetAccessControl(); - } - catch (PlatformNotSupportedException) - { - savedWindowsAcl = null; - } - } - else if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) - { - try - { - savedUnixMode = File.GetUnixFileMode(fullPath); - } - catch (PlatformNotSupportedException) - { - savedUnixMode = null; - } - } - } - - try - { - // Create the temporary file empty first so its rights can be tightened - // before any document content hits the disk. - using (var _ = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) - { - } - - ApplyTempSecurity(tempPath, savedWindowsAcl, savedUnixMode, destinationExists); - - using (var stream = new FileStream(tempPath, FileMode.Truncate, FileAccess.Write, FileShare.None)) - { - Write(document, stream, options); - } - - File.Move(tempPath, fullPath, overwrite: true); - } - catch - { - TryDelete(tempPath); - throw; - } - } - - private static void ApplyTempSecurity( - string filePath, - FileSecurity? windowsAcl, - UnixFileMode? unixMode, - bool destinationExists) - { - if (!destinationExists) - { - return; - } - - if (OperatingSystem.IsWindows()) - { - if (windowsAcl is null) - { - return; - } - - // Copy only the DACL and its protection flag. Persisting the whole - // FileSecurity (owner/group/SACL) requires SeSecurityPrivilege and, - // when unmodified, persists nothing — the temporary file would keep - // the directory's inherited rules. - new FileInfo(filePath).SetAccessControl(CloneDacl(windowsAcl)); - return; - } - - if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) - { - if (unixMode.HasValue) - { - File.SetUnixFileMode(filePath, unixMode.Value); - } - } - } - - [System.Runtime.Versioning.SupportedOSPlatform("windows")] - private static FileSecurity CloneDacl(FileSecurity source) - { - var clone = new FileSecurity(); - clone.SetAccessRuleProtection(source.AreAccessRulesProtected, preserveInheritance: false); - foreach (FileSystemAccessRule rule in source.GetAccessRules(includeExplicit: true, includeInherited: false, targetType: typeof(System.Security.Principal.SecurityIdentifier))) - { - clone.AddAccessRule(rule); - } - - return clone; - } - - private static void TryDelete(string path) - { - try - { - File.Delete(path); - } - catch (IOException) - { - // Best-effort cleanup: the original export failure is the error worth reporting. - } - catch (UnauthorizedAccessException) - { - // Best-effort cleanup: the original export failure is the error worth reporting. - } + AtomicOutput.Write(path, stream => Write(document, stream, options)); } private static bool IsIncluded(DwgDocument document, string name, DwgJsonExportOptions options) => diff --git a/src/DwgIO/Model/DwgAppInfo.cs b/src/DwgIO/Model/DwgAppInfo.cs index 9d1489e..f339511 100644 --- a/src/DwgIO/Model/DwgAppInfo.cs +++ b/src/DwgIO/Model/DwgAppInfo.cs @@ -14,7 +14,8 @@ public sealed class DwgAppInfo /// Free-form comment string (AC1021+ files; usually a producer notice). public string Comment { get; init; } = string.Empty; - /// Free-form product string; not filled by the current parsers. + /// The product named by the product XML's name attribute (e.g. "AutoCAD", "AutoCAD LT", + /// "Teigha(R)"); empty when the XML is absent or carries no name. public string Product { get; init; } = string.Empty; /// XML product blob (ProductInformation element), present in both layouts. diff --git a/src/DwgIO/Model/DwgAuxHeader.cs b/src/DwgIO/Model/DwgAuxHeader.cs new file mode 100644 index 0000000..8ab55cf --- /dev/null +++ b/src/DwgIO/Model/DwgAuxHeader.cs @@ -0,0 +1,35 @@ +namespace DwgIO.Model; + +/// +/// The auxiliary file header of the AcDb:AuxHeader section (R2000 and later files): a fixed layout +/// that mirrors parts of the file header and keeps the save counters and the drawing times. +/// +public sealed class DwgAuxHeader +{ + /// The three intro bytes, FF 77 01 in the files observed. + public IReadOnlyList Intro { get; init; } = []; + + /// DWG version code (matches 's container value). + public ushort DwgVersion { get; init; } + + /// Maintenance version. + public ushort MaintVersion { get; init; } + + /// Number of times the drawing was saved. + public uint Numsaves { get; init; } + + /// Creation time of the drawing. + public DateTime? CreatedUtc { get; init; } + + /// Last update time of the drawing. + public DateTime? ModifiedUtc { get; init; } + + /// The next free handle at the last save. + public ulong Handseed { get; init; } + + /// Creation time as the section stores it: Julian day and milliseconds of the day. + public (uint JulianDay, uint Milliseconds) CreatedRaw { get; init; } + + /// Last update time as the section stores it. + public (uint JulianDay, uint Milliseconds) ModifiedRaw { get; init; } +} diff --git a/src/DwgIO/Model/DwgEntity.cs b/src/DwgIO/Model/DwgEntity.cs index 7503da8..b055ec8 100644 --- a/src/DwgIO/Model/DwgEntity.cs +++ b/src/DwgIO/Model/DwgEntity.cs @@ -42,7 +42,10 @@ public sealed class DwgEntity /// Point = [x,y,z]. Null for non-decoded kinds. public double[]? Geometry { get; init; } - /// DXF 62 colour index (low byte of the stored colour value) from the common preamble. + internal bool IsModelSpace { get; init; } = true; + + /// DXF 62 colour index from the common preamble: the low 9 bits of the stored colour value, + /// so 0 is BYBLOCK, 1 to 255 are indexed colours and 256 is BYLAYER. public int ColorIndex { get; init; } /// DXF 48 linetype scale from the common preamble. diff --git a/src/DwgIO/Model/DwgHandleMap.cs b/src/DwgIO/Model/DwgHandleMap.cs index b161162..3317d41 100644 --- a/src/DwgIO/Model/DwgHandleMap.cs +++ b/src/DwgIO/Model/DwgHandleMap.cs @@ -32,11 +32,13 @@ public sealed class DwgHandleMap return _byHandle.TryGetValue(handle, out var entry) ? entry : null; } - /// Parses the decompressed AcDb:Handles section. - internal static DwgHandleMap Parse(byte[] data) + /// Parses the decompressed AcDb:Handles section. Where the parse stops early, or an entry + /// is dropped, a message goes to instead of vanishing. + internal static DwgHandleMap Parse(byte[] data, Action? diagnostic = null) { var entries = new List(); int pos = 0; + int dropped = 0; while (pos + 2 <= data.Length) { int blockSize = (data[pos] << 8) | data[pos + 1]; @@ -50,6 +52,7 @@ internal static DwgHandleMap Parse(byte[] data) { // Real writers leave a truncated final block (or padding) past the last // well-formed one: treat it as the end of the map, not a hard error. + Report(diagnostic, $"handle map: block at {pos - 2} is truncated ({blockSize} declared, {data.Length - pos} present); the map ends here"); break; } @@ -67,13 +70,21 @@ internal static DwgHandleMap Parse(byte[] data) handleDelta = reader.ReadVarUInt(); offsetDelta = reader.ReadVarInt(); } - catch (DwgException) + catch (DwgException ex) { + Report(diagnostic, $"handle map: block at {pos - 2}: unreadable delta pair after {entries.Count} entries ({ex.Message}); the rest of the block is skipped"); break; } lastHandle += handleDelta; lastOffset += offsetDelta; + if (lastOffset < 0) + { + dropped++; + Report(diagnostic, $"handle map: entry {lastHandle} has the negative offset {lastOffset} and is dropped"); + continue; + } + if (entries.Count >= MaxEntries) { throw new DwgException("Handle map exceeds the entry cap; file is malformed."); @@ -85,6 +96,13 @@ internal static DwgHandleMap Parse(byte[] data) pos += blockSize; } + if (dropped > 0) + { + Report(diagnostic, $"handle map: {dropped} of {dropped + entries.Count} entries were dropped"); + } + return new DwgHandleMap { Entries = entries }; } + + private static void Report(Action? diagnostic, string message) => diagnostic?.Invoke(message); } diff --git a/src/DwgIO/Model/DwgObjectInfo.cs b/src/DwgIO/Model/DwgObjectInfo.cs index a4b886e..7febb2d 100644 --- a/src/DwgIO/Model/DwgObjectInfo.cs +++ b/src/DwgIO/Model/DwgObjectInfo.cs @@ -25,6 +25,10 @@ public sealed record DwgObjectInfo /// Object type code (e.g. LINE, LWPOLYLINE). public required ushort TypeCode { get; init; } + /// Name for : the AutoCAD or table name, or Object_XX/Class_XX + /// when the code is not in the fixed table (see ). + public string TypeName => DwgObjectTypes.Name(TypeCode); + /// Absolute object handle as read from the record (the value of ). public required ulong Handle { get; init; } diff --git a/src/DwgIO/Model/DwgObjectTypes.cs b/src/DwgIO/Model/DwgObjectTypes.cs new file mode 100644 index 0000000..0f82a66 --- /dev/null +++ b/src/DwgIO/Model/DwgObjectTypes.cs @@ -0,0 +1,114 @@ +namespace DwgIO.Model; + +/// +/// The fixed object type codes of the DWG format: the name and the entity-or-object flag of every fixed +/// code, per libredwg's include/dwg.h. Class-defined records (codes 500 and above) take their name from the +/// drawing's class list, which the reader does not decode yet, so they fall back to Class_XX. +/// +public static class DwgObjectTypes +{ + private const ushort ProxyEntityCode = 0x1F2; + private const ushort ProxyObjectCode = 0x1F3; + + private static readonly Dictionary FixedNames = new() + { + [0x01] = "TEXT", + [0x02] = "ATTRIB", + [0x03] = "ATTDEF", + [0x04] = "BLOCK", + [0x05] = "ENDBLK", + [0x06] = "SEQEND", + [0x07] = "INSERT", + [0x08] = "MINSERT", + [0x0A] = "VERTEX_2D", + [0x0B] = "VERTEX_3D", + [0x0C] = "VERTEX_MESH", + [0x0D] = "VERTEX_PFACE", + [0x0E] = "VERTEX_PFACE_FACE", + [0x0F] = "POLYLINE_2D", + [0x10] = "POLYLINE_3D", + [0x11] = "ARC", + [0x12] = "CIRCLE", + [0x13] = "LINE", + [0x14] = "DIMENSION_ORDINATE", + [0x15] = "DIMENSION_LINEAR", + [0x16] = "DIMENSION_ALIGNED", + [0x17] = "DIMENSION_ANG3PT", + [0x18] = "DIMENSION_ANG2LN", + [0x19] = "DIMENSION_RADIUS", + [0x1A] = "DIMENSION_DIAMETER", + [0x1B] = "POINT", + [0x1C] = "3DFACE", + [0x1D] = "POLYLINE_PFACE", + [0x1E] = "POLYLINE_MESH", + [0x1F] = "SOLID", + [0x20] = "TRACE", + [0x21] = "SHAPE", + [0x22] = "VIEWPORT", + [0x23] = "ELLIPSE", + [0x24] = "SPLINE", + [0x25] = "REGION", + [0x26] = "3DSOLID", + [0x27] = "BODY", + [0x28] = "RAY", + [0x29] = "XLINE", + [0x2A] = "DICTIONARY", + [0x2B] = "OLEFRAME", + [0x2C] = "MTEXT", + [0x2D] = "LEADER", + [0x2E] = "TOLERANCE", + [0x2F] = "MLINE", + [0x30] = "BLOCK_CONTROL", + [0x31] = "BLOCK_RECORD", + [0x32] = "LAYER_CONTROL", + [0x33] = "LAYER", + [0x34] = "STYLE_CONTROL", + [0x35] = "STYLE", + [0x38] = "LTYPE_CONTROL", + [0x39] = "LTYPE", + [0x3C] = "VIEW_CONTROL", + [0x3D] = "VIEW", + [0x3E] = "UCS_CONTROL", + [0x3F] = "UCS", + [0x40] = "VPORT_CONTROL", + [0x41] = "VPORT", + [0x42] = "APPID_CONTROL", + [0x43] = "APPID", + [0x44] = "DIMSTYLE_CONTROL", + [0x45] = "DIMSTYLE", + [0x46] = "VX_CONTROL", + [0x47] = "VX_TABLE_RECORD", + [0x48] = "GROUP", + [0x49] = "MLINESTYLE", + [0x4A] = "OLE2FRAME", + [0x4B] = "DUMMY", + [0x4C] = "LONG_TRANSACTION", + [0x4D] = "LWPOLYLINE", + [0x4E] = "HATCH", + [0x4F] = "XRECORD", + [0x50] = "PLACEHOLDER", + [0x51] = "VBA_PROJECT", + [0x52] = "LAYOUT", + [ProxyEntityCode] = "PROXY_ENTITY", + [ProxyObjectCode] = "PROXY_OBJECT", + }; + + /// Codes that are drawable entities outside the 0x01-0x2F range (per libredwg). + private static readonly HashSet ExtraEntities = [0x4A, 0x4D, 0x4E, ProxyEntityCode]; + + /// Name for a fixed type code: the AutoCAD or table name, Class_XX for the class-defined + /// codes and Object_XX for an unknown fixed code. + public static string Name(ushort typeCode) => + FixedNames.TryGetValue(typeCode, out var name) + ? name + : typeCode >= 500 ? $"Class_{typeCode}" : $"Object_{typeCode:X}"; + + /// Tells whether a record of this code is a drawable entity: the 0x01-0x2F range without + /// the reserved 0x09 and DICTIONARY (0x2A), plus LWPOLYLINE, HATCH, OLE2FRAME and PROXY_ENTITY. Class-defined codes + /// (500+) are entities when their class says so; without a decoded class list they are treated as objects. + public static bool IsEntity(ushort typeCode) => + (typeCode is >= 0x01 and <= 0x2F and not (0x09 or 0x2A)) || ExtraEntities.Contains(typeCode); + + /// Every fixed type name the table knows, for validating a filter list. + public static IReadOnlyCollection KnownNames => FixedNames.Values; +} diff --git a/src/DwgIO/Model/DwgRevHistory.cs b/src/DwgIO/Model/DwgRevHistory.cs new file mode 100644 index 0000000..65964f3 --- /dev/null +++ b/src/DwgIO/Model/DwgRevHistory.cs @@ -0,0 +1,17 @@ +namespace DwgIO.Model; + +/// +/// The revision history of the AcDb:RevHistory section: a version pair and the list of save +/// entries in file order. +/// +public sealed class DwgRevHistory +{ + /// Major version of the section layout. + public uint ClassVersion { get; init; } + + /// Minor version of the section layout. + public uint ClassMinor { get; init; } + + /// Stored revision values in file order. + public IReadOnlyList Histories { get; init; } = []; +} diff --git a/src/DwgIO/Model/DwgTemplate.cs b/src/DwgIO/Model/DwgTemplate.cs new file mode 100644 index 0000000..78453bf --- /dev/null +++ b/src/DwgIO/Model/DwgTemplate.cs @@ -0,0 +1,17 @@ +namespace DwgIO.Model; + +/// +/// The template description of the AcDb:Template section: the drawing template the file was +/// created from and its unit system. +/// +public sealed class DwgTemplate +{ + /// Description of the template (for example the original file name), or empty. + public string Description { get; init; } = string.Empty; + + /// Unit system: 0 = English (imperial), 1 = metric. + public int Measurement { get; init; } + + /// True when is 1 (metric). + public bool IsMetric => Measurement == 1; +} diff --git a/test-files/public/README.md b/test-files/public/README.md new file mode 100644 index 0000000..8a76c53 --- /dev/null +++ b/test-files/public/README.md @@ -0,0 +1,24 @@ +# Redistributable test drawings (#33) + +This folder is reserved for small DWG files whose licence allows redistribution, one per supported release +(AC1018, AC1024, AC1027, AC1032 — then AC1012 to AC1015 as the readers for those land). The fixture tests +run over every drawing in the fixture folders, so a drawing committed here turns its skipped tests into +real runs in CI on all three systems. + +## How a drawing qualifies + +Before committing a file, record here, next to the file name: + +1. **Origin** — where the drawing came from, and who produced it. +2. **Licence** — why it may be redistributed in this MIT-licensed repository (own drawing, written + permission of the author, a licence that allows redistribution, or a file created from scratch). +3. **Contents** — one line on what the drawing holds (entities, layers), so tests can be written against it. + +When the licence is in doubt, the file stays out. The private-folder mechanism (`DWGIO_TEST_FILES`, +see `docs/test-fixtures.md`) remains the place for larger local test sets. + +## The fixture search + +`TestFiles` looks for drawings in the folder named by `DWGIO_TEST_FILES`, in a `test_files` folder and in +this `test-files/public` folder; one level of subfolders is searched too. Nothing else about the search +changes: unsupported versions are skipped and counted, and a missing drawing never fails a test. diff --git a/tests/DwgIO.Tests/CliEntitiesTests.cs b/tests/DwgIO.Tests/CliEntitiesTests.cs new file mode 100644 index 0000000..5ca6f61 --- /dev/null +++ b/tests/DwgIO.Tests/CliEntitiesTests.cs @@ -0,0 +1,172 @@ +using System.Text.Json; +using DwgIO.Cli; +using DwgIO.Model; +using Xunit; + +namespace DwgIO.Tests; + +/// The --version/--help switches and the entities command (#18, #19). +public class CliEntitiesTests +{ + private static DwgDocument CreateDocument(params DwgEntity[] entities) => + new( + "synthetic.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1024", + Release = "R2010", + Family = DwgContainerFamily.R2004Family, + Year = 2010, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + entities); + + private static DwgDocument SampleDrawing() => CreateDocument( + new DwgEntity { Handle = 0x2A, TypeCode = 0x13, TypeName = "LINE", Kind = DwgEntityKind.Line, Geometry = [0, 0, 0, 1, 0, 0], ColorIndex = 1 }, + new DwgEntity { Handle = 0x2B, TypeCode = 0x12, TypeName = "CIRCLE", Kind = DwgEntityKind.Circle, Geometry = [5, 0, 0, 2], ColorIndex = 40 }, + new DwgEntity { Handle = 0x2C, TypeCode = 0x13, TypeName = "LINE", Kind = DwgEntityKind.Line, Geometry = [0, 0, 0, 3, 0, 0] }); + + [Fact] + public void Version_PrintsThePackageVersionAndExits0() + { + using var output = new StringWriter(); + + int exit = Program.Run(["--version"], output, new StringWriter()); + + Assert.Equal(0, exit); + Assert.Matches(@"^\d+\.\d+\.\d+", output.ToString().TrimEnd()); + } + + [Fact] + public void ShortVersion_PrintsTheVersion() + { + using var output = new StringWriter(); + + Assert.Equal(0, Program.Run(["-v"], output, new StringWriter())); + Assert.Matches(@"^\d+\.\d+\.\d+", output.ToString().TrimEnd()); + } + + [Theory] + [InlineData("--help")] + [InlineData("-h")] + public void Help_PrintsTheUsageAndExits0(string option) + { + using var output = new StringWriter(); + + int exit = Program.Run([option], output, new StringWriter()); + + Assert.Equal(0, exit); + Assert.Contains("Usage:", output.ToString(), StringComparison.Ordinal); + Assert.Contains("entities", output.ToString(), StringComparison.Ordinal); + } + + [Fact] + public void UnknownOption_Exits1WithTheOptionNamed() + { + using var output = new StringWriter(); + using var error = new StringWriter(); + + int exit = Program.Run(["--bogus"], output, error); + + Assert.Equal(1, exit); + Assert.Contains("--bogus", error.ToString(), StringComparison.Ordinal); + } + + [Fact] + public void EntitiesDocument_ListsOneLinePerEntity() + { + var document = SampleDrawing(); + using var output = new StringWriter(); + + int exit = Program.EntitiesDocument(document, json: false, filter: null, output); + + Assert.Equal(0, exit); + string[] lines = output.ToString().Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + Assert.Equal(3, lines.Length); + Assert.StartsWith("LINE 2A:", lines[0], StringComparison.Ordinal); + } + + [Fact] + public void EntitiesDocument_FiltersByType() + { + var document = SampleDrawing(); + using var output = new StringWriter(); + + int exit = Program.EntitiesDocument(document, json: false, filter: ["LINE"], output); + + Assert.Equal(0, exit); + string text = output.ToString(); + Assert.Equal(2, text.Split("LINE").Length - 1); + Assert.DoesNotContain("CIRCLE", text, StringComparison.Ordinal); + } + + [Fact] + public void EntitiesDocument_UnknownType_Exits1WithTheName() + { + using var error = new StringWriter(); + var types = new[] { "WEDGE" }; + + // The type validation happens while parsing the option list, before the document is read. + int exit = Program.Run(["entities", "--type", types[0]], new StringWriter(), error); + + Assert.Equal(1, exit); + Assert.Contains("unknown type 'WEDGE'", error.ToString(), StringComparison.Ordinal); + } + + [Theory] + [InlineData("--bogus")] + [InlineData("-z")] + public void Entities_UnknownOption_ReturnsUsage(string option) + { + using var output = new StringWriter(); + using var error = new StringWriter(); + + Assert.Equal(1, Program.Run(["entities", option], output, error)); + Assert.Contains("unknown option", error.ToString(), StringComparison.Ordinal); + } + + [Fact] + public void Entities_EmptyTypeFilter_ReturnsUsage() + { + using var output = new StringWriter(); + using var error = new StringWriter(); + + Assert.Equal(1, Program.Run(["entities", "drawing.dwg", "--type", ", "], output, error)); + Assert.Contains("at least one type", error.ToString(), StringComparison.Ordinal); + } + + [Fact] + public void EntitiesDocument_Json_WritesAnArrayOfEntities() + { + var document = SampleDrawing(); + using var output = new StringWriter(); + + int exit = Program.EntitiesDocument(document, json: true, filter: null, output); + + Assert.Equal(0, exit); + using var parsed = JsonDocument.Parse(output.ToString()); + Assert.Equal(3, parsed.RootElement.GetArrayLength()); + Assert.Equal("LINE", parsed.RootElement[0].GetProperty("type").GetString()); + Assert.Equal("2A", parsed.RootElement[0].GetProperty("handle").GetString()); + Assert.Equal(1, parsed.RootElement[0].GetProperty("colorIndex").GetInt32()); + } + + [Fact] + public void Export_Dash_WritesTheSameJsonToStandardOutputAsToFile() + { + var document = CreateDocument( + new DwgEntity { Handle = 0x2A, TypeCode = 0x13, TypeName = "LINE", Kind = DwgEntityKind.Line, Geometry = [0, 0, 0, 1, 0, 0] }); + + using var stdout = new StringWriter(); + Assert.Equal(0, Program.ExportDocument(document, "-", stdout, new StringWriter())); + + using var fileJson = new MemoryStream(); + DwgIO.Json.DwgJsonExporter.Write(document, fileJson, DwgIO.Json.DwgJsonExportOptions.Default); + Assert.Equal(System.Text.Encoding.UTF8.GetString(fileJson.ToArray()), stdout.ToString()); + } +} diff --git a/tests/DwgIO.Tests/CliOutputTests.cs b/tests/DwgIO.Tests/CliOutputTests.cs new file mode 100644 index 0000000..13b6fd4 --- /dev/null +++ b/tests/DwgIO.Tests/CliOutputTests.cs @@ -0,0 +1,121 @@ +using System.Globalization; +using DwgIO.Cli; +using DwgIO.Model; +using Xunit; + +namespace DwgIO.Tests; + +public class CliOutputTests +{ + [Fact] + public void Count_GroupsWithTheInvariantSeparator_UnderANonEnglishCulture() + { + var previous = CultureInfo.CurrentCulture; + try + { + // Turkish uses a dot as the thousands separator and, notably, different digits rules; the output + // must not follow it. + CultureInfo.CurrentCulture = new CultureInfo("tr-TR"); + + Assert.Equal("1,234,567", Program.Count(1_234_567)); + Assert.Equal("10", Program.Count(10)); + } + finally + { + CultureInfo.CurrentCulture = previous; + } + } + + [Fact] + public void Count_IsStableUnderTheDefaultCulture() + { + Assert.Equal("1,234,567", Program.Count(1_234_567)); + } + + [Fact] + public void Inspect_PrintsDiagnosticsWithoutDecodedEntities() + { + var document = new DwgDocument( + "synthetic.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1024", + Release = "R2010", + Family = DwgContainerFamily.R2004Family, + Year = 2010, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + []); + document.ReportDiagnostic("AcDb:Handles: unexpected end of stream"); + + using var output = new StringWriter(); + int exit = Program.InspectDocument(document, output); + + Assert.Equal(0, exit); + string text = output.ToString(); + Assert.Contains("Diagnostics: 1", text, StringComparison.Ordinal); + Assert.Contains("AcDb:Handles: unexpected end of stream", text, StringComparison.Ordinal); + Assert.DoesNotContain("Entities decoded", text, StringComparison.Ordinal); + } + + [Fact] + public void Inspect_PrintsTheDiagnosticTotal_Invariantly() + { + var document = new DwgDocument( + "synthetic.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1024", + Release = "R2010", + Family = DwgContainerFamily.R2004Family, + Year = 2010, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + []); + for (int i = 0; i < 1234; i++) + { + document.ReportDiagnostic($"problem {i}"); + } + + using var output = new StringWriter(); + Program.InspectDocument(document, output); + + Assert.Contains("Diagnostics: 1,234", output.ToString(), StringComparison.Ordinal); + } + + [Fact] + public void Inspect_DoesNotPrintTheDiagnosticBlockWithoutDiagnostics() + { + var document = new DwgDocument( + "synthetic.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1024", + Release = "R2010", + Family = DwgContainerFamily.R2004Family, + Year = 2010, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + []); + + using var output = new StringWriter(); + Program.InspectDocument(document, output); + + Assert.DoesNotContain("Diagnostics:", output.ToString(), StringComparison.Ordinal); + } +} diff --git a/tests/DwgIO.Tests/CliPreviewTests.cs b/tests/DwgIO.Tests/CliPreviewTests.cs new file mode 100644 index 0000000..2f3571c --- /dev/null +++ b/tests/DwgIO.Tests/CliPreviewTests.cs @@ -0,0 +1,119 @@ +using DwgIO.Cli; +using DwgIO.Model; +using Xunit; + +namespace DwgIO.Tests; + +/// The preview command: its own exit code for a missing thumbnail and the output extension (#14). +public class CliPreviewTests : IDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), "dwgio-tests-" + Guid.NewGuid().ToString("N")); + + public CliPreviewTests() + { + Directory.CreateDirectory(_directory); + } + + public void Dispose() + { + GC.SuppressFinalize(this); + try + { + Directory.Delete(_directory, recursive: true); + } + catch (DirectoryNotFoundException) + { + } + } + + private static DwgDocument CreateDocument(DwgPreview? preview) + { + var header = new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1024", + Release = "R2010", + Family = DwgContainerFamily.R2004Family, + Year = 2010, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }; + return preview is null + ? new DwgDocument("synthetic.dwg", header, []) + : new DwgDocument("synthetic.dwg", header, [], preview); + } + + [Fact] + public void PreviewDocument_WithoutThumbnail_ExitsWith5() + { + using var output = new StringWriter(); + using var error = new StringWriter(); + + int exit = Program.PreviewDocument(CreateDocument(null), Path.Combine(_directory, "thumb"), output, error); + + Assert.Equal(5, exit); + Assert.Contains("no thumbnail", error.ToString(), StringComparison.Ordinal); + Assert.Empty(Directory.EnumerateFiles(_directory)); + } + + [Fact] + public void PreviewDocument_WithoutImageBytes_ExitsWith5() + { + var preview = new DwgPreview { OverallSize = 0, ImageKind = DwgPreviewImageKind.None, ImageBytes = [] }; + using var output = new StringWriter(); + using var error = new StringWriter(); + + int exit = Program.PreviewDocument(CreateDocument(preview), Path.Combine(_directory, "thumb"), output, error); + + Assert.Equal(5, exit); + Assert.Empty(Directory.EnumerateFiles(_directory)); + } + + [Fact] + public void PreviewDocument_ExtensionIsAddedToMatchTheKind() + { + var preview = new DwgPreview { OverallSize = 4, ImageKind = DwgPreviewImageKind.Png, ImageBytes = [1, 2, 3, 4] }; + string requested = Path.Combine(_directory, "thumb"); + using var output = new StringWriter(); + using var error = new StringWriter(); + + int exit = Program.PreviewDocument(CreateDocument(preview), requested, output, error); + + Assert.Equal(0, exit); + Assert.True(File.Exists(Path.Combine(_directory, "thumb.png"))); + Assert.Null(Program.ResolvePreviewTarget(DwgPreviewImageKind.Png, requested).Warning); + } + + [Fact] + public void ResolvePreviewTarget_MismatchingExtension_IsReportedAndKept() + { + var (target, warning) = Program.ResolvePreviewTarget(DwgPreviewImageKind.Bmp, "drawing.png"); + + Assert.Equal("drawing.png", target); + Assert.NotNull(warning); + Assert.Contains("Bmp", warning, StringComparison.Ordinal); + Assert.Contains(".bmp", warning, StringComparison.Ordinal); + Assert.Contains(".png", warning, StringComparison.Ordinal); + } + + [Fact] + public void ResolvePreviewTarget_MatchingExtension_IsSilent() + { + var (target, warning) = Program.ResolvePreviewTarget(DwgPreviewImageKind.Png, "drawing.PNG"); + + Assert.Equal("drawing.PNG", target); + Assert.Null(warning); + } + + [Fact] + public void ResolvePreviewTarget_DirectoryRequest_GainsTheExtension() + { + var (target, warning) = Program.ResolvePreviewTarget(DwgPreviewImageKind.Wmf, "out" + Path.DirectorySeparatorChar); + + Assert.Equal("out" + Path.DirectorySeparatorChar + ".wmf", target); + Assert.Null(warning); + } +} diff --git a/tests/DwgIO.Tests/DwgFixtureTests.cs b/tests/DwgIO.Tests/DwgFixtureTests.cs index a9b8246..2e66a52 100644 --- a/tests/DwgIO.Tests/DwgFixtureTests.cs +++ b/tests/DwgIO.Tests/DwgFixtureTests.cs @@ -12,17 +12,23 @@ public class DwgFixtureTests { /// Runs on every fixture and fails with one line per failing file (name only, /// never the full path). The check returns false when a file legitimately lacks what it needs (an optional - /// section); when no file had it, the test is skipped rather than passed. - private static void CheckAll(Func check, string requirement) + /// section); when no file had it, the test is skipped rather than passed. Drawings of an unsupported version + /// are ignored and counted in the skip reason, so one AC1021 file in the folder does not fail every test. + internal static void CheckAll(Func check, string requirement) { var failures = new List(); int checkedFiles = 0; + int unsupported = 0; foreach (string path in TestFiles.DwgFiles()) { try { if (check(path)) checkedFiles++; } + catch (DwgUnsupportedVersionException) + { + unsupported++; + } catch (Exception ex) when (ex is not SkipException) { failures.Add($"{Path.GetFileName(path)}: {ex.GetType().Name}: {ex.Message}"); @@ -30,7 +36,12 @@ private static void CheckAll(Func check, string requirement) } Assert.True(failures.Count == 0, string.Join(Environment.NewLine, failures)); - if (checkedFiles == 0) throw new SkipException($"No private fixture has {requirement}."); + if (checkedFiles == 0) + { + throw new SkipException(unsupported > 0 + ? $"No private fixture has {requirement}; {unsupported} drawing(s) of an unsupported version were ignored." + : $"No private fixture has {requirement}."); + } } private static void CheckAll(Action check) => @@ -123,12 +134,33 @@ public void HandleMap_AndObjectInventory_AreConsistent() => CheckAll(path => int mapped = doc.Objects.Count(o => doc.HandleMap.Find(o.Handle) is not null); Assert.True(mapped >= doc.Objects.Count * 99 / 100, $"only {mapped}/{doc.Objects.Count} object handles resolved; diagnostics: {diagnostics}"); + int missing = DwgDocument.CountUnreachedObjects(doc.Objects, doc.HandleMap); + Assert.True(missing <= doc.HandleMap.Count / 100 + 64, + $"inventory missed {missing} of {doc.HandleMap.Count} handle-map entries; diagnostics: {diagnostics}"); + if (missing > 0) + { + Assert.Contains($"{missing} of {doc.HandleMap.Count} handle-map entries were unreached", diagnostics, StringComparison.Ordinal); + } + Assert.True(doc.Objects.Count <= doc.HandleMap.Count * 102 / 100 + 64, $"inventory {doc.Objects.Count} far exceeds handle map {doc.HandleMap.Count}"); Assert.All(doc.Objects, o => Assert.True(o.StreamOffset >= 0 && o.StreamOffset < acDbObjects.Size)); }); + [SkippableFact] + public void AppInfoHistory_PreservesTheRawSection() => CheckAll(path => + { + var doc = DwgDocument.Open(path, new DwgReaderOptions { ReadObjects = false }); + if (!HasReadableSection(doc, "AcDb:AppInfoHistory")) + { + return false; + } + + Assert.Equal(doc.ReadSection("AcDb:AppInfoHistory"), doc.AppInfoHistory.ToArray()); + return true; + }, "a readable AcDb:AppInfoHistory section"); + [SkippableFact] public void Preview_HasImageWhenSectionPresent() => CheckAll(path => { diff --git a/tests/DwgIO.Tests/DwgIO.Tests.csproj b/tests/DwgIO.Tests/DwgIO.Tests.csproj index 328f3a5..7c0fbb6 100644 --- a/tests/DwgIO.Tests/DwgIO.Tests.csproj +++ b/tests/DwgIO.Tests/DwgIO.Tests.csproj @@ -19,6 +19,8 @@ + + diff --git a/tests/DwgIO.Tests/DwgSceneExportTests.cs b/tests/DwgIO.Tests/DwgSceneExportTests.cs new file mode 100644 index 0000000..9402f1e --- /dev/null +++ b/tests/DwgIO.Tests/DwgSceneExportTests.cs @@ -0,0 +1,308 @@ +using DwgIO.Model; +using DwgIO.Scene; +using IOScene.Formats; +using Xunit; +using Vector3d = IOScene.Vector3d; + +namespace DwgIO.Tests; + +public class DwgSceneExportTests : IDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), "dwgio-tests-" + Guid.NewGuid().ToString("N")); + + public DwgSceneExportTests() + { + Directory.CreateDirectory(_directory); + } + + public void Dispose() + { + GC.SuppressFinalize(this); + try + { + Directory.Delete(_directory, recursive: true); + } + catch (DirectoryNotFoundException) + { + } + } + + private static DwgDocument CreateDocument(params DwgEntity[] entities) => + new( + "synthetic.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1024", + Release = "R2010", + Family = DwgContainerFamily.R2004Family, + Year = 2010, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + entities); + + private static DwgDocument SampleDrawing() => CreateDocument( + new DwgEntity + { + Handle = 0x2A, + TypeCode = 0x13, + TypeName = "LINE", + Kind = DwgEntityKind.Line, + Geometry = [1.0, 2.0, 0.0, 11.0, 2.0, 0.0], + ColorIndex = 1, + }, + new DwgEntity + { + Handle = 0x2B, + TypeCode = 0x12, + TypeName = "CIRCLE", + Kind = DwgEntityKind.Circle, + Geometry = [6.0, 2.0, 0.0, 5.0], + ColorIndex = 40, + }, + new DwgEntity + { + Handle = 0x2C, + TypeCode = 0x1B, + TypeName = "POINT", + Kind = DwgEntityKind.Point, + Geometry = [20.0, 2.0, 0.0], + }); + + [Fact] + public void SaveObj_WritesObjWithMtlLibrary() + { + string objPath = Path.Combine(_directory, "drawing.obj"); + + var result = DwgSceneExport.SaveObj(SampleDrawing(), objPath); + + Assert.Equal(3, result.ElementCount); + Assert.True(File.Exists(objPath)); + Assert.True(File.Exists(Path.Combine(_directory, "drawing.mtl"))); + string obj = File.ReadAllText(objPath); + Assert.Contains("mtllib drawing.mtl", obj, StringComparison.Ordinal); + Assert.Contains("usemtl material_1", obj, StringComparison.Ordinal); + Assert.Contains("v 1 2 0", obj, StringComparison.Ordinal); + Assert.Contains("l ", obj, StringComparison.Ordinal); + Assert.Contains("p ", obj, StringComparison.Ordinal); + string mtl = File.ReadAllText(Path.Combine(_directory, "drawing.mtl")); + Assert.Contains("newmtl material_1", mtl, StringComparison.Ordinal); + } + + [Fact] + public void SaveObj_WritesLineAndPointRecords() + { + string objPath = Path.Combine(_directory, "drawing.obj"); + + DwgSceneExport.SaveObj(SampleDrawing(), objPath); + + // The OBJ preview reader of IOScene.Formats reads faces only, so the line and point records are asserted + // on the text: one segment for the LINE, 64 for the tessellated CIRCLE, one point for the POINT. + string[] objLines = File.ReadAllLines(objPath); + Assert.Equal(65, objLines.Count(l => l.StartsWith("l ", StringComparison.Ordinal))); + Assert.Equal(1, objLines.Count(l => l.StartsWith("p ", StringComparison.Ordinal))); + Assert.Contains(objLines, l => l == "v 1 2 0"); + Assert.Contains(objLines, l => l == "v 20 2 0"); + } + + [Fact] + public void SaveObj_ReplacesExistingFiles() + { + string objPath = Path.Combine(_directory, "drawing.obj"); + File.WriteAllText(objPath, "stale"); + string mtlPath = Path.Combine(_directory, "drawing.mtl"); + File.WriteAllText(mtlPath, "stale"); + + DwgSceneExport.SaveObj(SampleDrawing(), objPath); + + Assert.DoesNotContain("stale", File.ReadAllText(objPath), StringComparison.Ordinal); + Assert.DoesNotContain("stale", File.ReadAllText(mtlPath), StringComparison.Ordinal); + Assert.Empty(Directory.EnumerateFiles(_directory, ".dwgio-*")); + } + + [SkippableFact] + public void SaveObj_SecondMoveFailure_KeepsTheOldPair() + { + if (!OperatingSystem.IsWindows()) + { + throw new SkipException("The failure injection relies on a Windows file lock; on Unix the rename succeeds regardless."); + } + + string objPath = Path.Combine(_directory, "drawing.obj"); + string mtlPath = Path.Combine(_directory, "drawing.mtl"); + File.WriteAllText(objPath, "old obj"); + File.WriteAllText(mtlPath, "old mtl"); + byte[] oldObj = File.ReadAllBytes(objPath); + byte[] oldMtl = File.ReadAllBytes(mtlPath); + + // The OBJ destination is held open exclusively, so the last step of the replace fails. + using (var lockStream = new FileStream(objPath, FileMode.Open, FileAccess.Read, FileShare.None)) + { + // The move failure surfaces as IOException or UnauthorizedAccessException depending on the obstacle. + var failure = Record.Exception(() => DwgSceneExport.SaveObj(SampleDrawing(), objPath)); + Assert.True(failure is IOException or UnauthorizedAccessException, $"unexpected {failure?.GetType().Name}"); + } + + // The old pair survives together: the old OBJ still names its own old MTL. + Assert.Equal(oldObj, File.ReadAllBytes(objPath)); + Assert.Equal(oldMtl, File.ReadAllBytes(mtlPath)); + Assert.Empty(Directory.EnumerateFiles(_directory, ".dwgio-*")); + } + + [SkippableFact] + public void SaveObj_FirstMoveFailure_KeepsTheOldPair() + { + if (!OperatingSystem.IsWindows()) + { + throw new SkipException("The failure injection relies on a Windows file lock; on Unix the rename succeeds regardless."); + } + + string objPath = Path.Combine(_directory, "drawing.obj"); + string mtlPath = Path.Combine(_directory, "drawing.mtl"); + File.WriteAllText(objPath, "old obj"); + File.WriteAllText(mtlPath, "old mtl"); + byte[] oldObj = File.ReadAllBytes(objPath); + byte[] oldMtl = File.ReadAllBytes(mtlPath); + + // The old MTL cannot step aside, so the export aborts before anything is replaced. + using (var lockStream = new FileStream(mtlPath, FileMode.Open, FileAccess.Read, FileShare.None)) + { + // The move failure surfaces as IOException or UnauthorizedAccessException depending on the obstacle. + var failure = Record.Exception(() => DwgSceneExport.SaveObj(SampleDrawing(), objPath)); + Assert.True(failure is IOException or UnauthorizedAccessException, $"unexpected {failure?.GetType().Name}"); + } + + Assert.Equal(oldObj, File.ReadAllBytes(objPath)); + Assert.Equal(oldMtl, File.ReadAllBytes(mtlPath)); + Assert.Empty(Directory.EnumerateFiles(_directory, ".dwgio-*")); + } + + [Fact] + public void SaveObj_FailedFreshExport_WritesNothing() + { + // The OBJ destination is a directory, so the final move fails on every platform. + string objPath = Path.Combine(_directory, "drawing.obj"); + Directory.CreateDirectory(objPath); + + // The move failure surfaces as IOException or UnauthorizedAccessException depending on the obstacle. + var failure = Record.Exception(() => DwgSceneExport.SaveObj(SampleDrawing(), objPath)); + Assert.True(failure is IOException or UnauthorizedAccessException, $"unexpected {failure?.GetType().Name}"); + + // A fresh export that fails leaves nothing: no half-written MTL beside the pair. + Assert.False(File.Exists(Path.Combine(_directory, "drawing.mtl"))); + Assert.Empty(Directory.EnumerateFiles(_directory, ".dwgio-*")); + } + + [Fact] + public void SaveObj_FileNameWithSpaces_WritesAnAdjacentLibrary() + { + string objPath = Path.Combine(_directory, "drawing with spaces.obj"); + + DwgSceneExport.SaveObj(SampleDrawing(), objPath); + + string reference = Assert.Single(File.ReadLines(objPath), line => line.StartsWith("mtllib ", StringComparison.Ordinal)); + Assert.True(File.Exists(Path.Combine(_directory, reference["mtllib ".Length..]))); + } + + [Fact] + public void SaveObj_MaterialExtension_RejectsTheOverlappingDestination() + { + string path = Path.Combine(_directory, "drawing.mtl"); + File.WriteAllText(path, "old material"); + + Assert.Throws(() => DwgSceneExport.SaveObj(SampleDrawing(), path)); + + Assert.Equal("old material", File.ReadAllText(path)); + } + + [Fact] + public void SaveObj_Overwrite_PreservesBothFilesAccessRules() + { + string[] paths = [Path.Combine(_directory, "drawing.obj"), Path.Combine(_directory, "drawing.mtl")]; + foreach (string path in paths) + { + File.WriteAllText(path, "old file"); + } + + const UnixFileMode ownerOnly = UnixFileMode.UserRead | UnixFileMode.UserWrite; + if (OperatingSystem.IsWindows()) + { + var user = System.Security.Principal.WindowsIdentity.GetCurrent().User!; + foreach (string path in paths) + { + var acl = new System.Security.AccessControl.FileSecurity(); + acl.SetAccessRuleProtection(true, preserveInheritance: false); + acl.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(user, + System.Security.AccessControl.FileSystemRights.FullControl, + System.Security.AccessControl.AccessControlType.Allow)); + new FileInfo(path).SetAccessControl(acl); + } + + string expected = new FileInfo(paths[0]).GetAccessControl().GetSecurityDescriptorSddlForm( + System.Security.AccessControl.AccessControlSections.Access); + DwgSceneExport.SaveObj(SampleDrawing(), paths[0]); + + foreach (string path in paths) + { + Assert.Equal(expected, new FileInfo(path).GetAccessControl().GetSecurityDescriptorSddlForm( + System.Security.AccessControl.AccessControlSections.Access)); + } + } + else if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) + { + foreach (string path in paths) + { + File.SetUnixFileMode(path, ownerOnly); + } + + DwgSceneExport.SaveObj(SampleDrawing(), paths[0]); + + foreach (string path in paths) + { + Assert.Equal(ownerOnly, File.GetUnixFileMode(path)); + } + } + } + + [Fact] + public void SaveGlb_RoundTripsThroughGlbSceneReader() + { + string glbPath = Path.Combine(_directory, "drawing.glb"); + + var result = DwgSceneExport.SaveGlb(SampleDrawing(), glbPath); + + Assert.Equal(3, result.ElementCount); + var loaded = GlbSceneReader.Load(glbPath); + Assert.Equal(3, loaded.Elements.Count); + Assert.Equal(3, loaded.Instances.Count); + // The GLB reader turns instance colours into materials: red for the LINE (ACI 1), gold for the CIRCLE (ACI 40). + Assert.Contains(loaded.Materials, m => m.Color.R == 255 && m.Color.G == 0 && m.Color.B == 0); + Assert.Contains(loaded.Materials, m => m.Color.R == 255 && m.Color.G == 191 && m.Color.B == 0); + var lineInstance = Assert.Single(loaded.Instances, i => loaded.Geometries.Single(g => g.Id == i.GeometryId).Topology == IOScene.SceneTopology.Lines && loaded.Geometries.Single(g => g.Id == i.GeometryId).Vertices.Count == 2); + Assert.NotNull(lineInstance); + } + + [Fact] + public void SaveGlb_ScalesByLengthUnit() + { + string glbPath = Path.Combine(_directory, "drawing.glb"); + var document = CreateDocument(new DwgEntity + { + Handle = 0x2A, + TypeCode = 0x13, + TypeName = "LINE", + Kind = DwgEntityKind.Line, + Geometry = [1000.0, 0.0, 0.0, 2000.0, 0.0, 0.0], + }); + + DwgSceneExport.SaveGlb(document, glbPath, new DwgSceneOptions { LengthUnit = "mm" }); + + var loaded = GlbSceneReader.Load(glbPath); + var geometry = Assert.Single(loaded.Geometries); + Assert.Equal(new Vector3d(1.0, 0.0, 0.0), geometry.Vertices[0]); + } +} diff --git a/tests/DwgIO.Tests/DwgSceneReaderTests.cs b/tests/DwgIO.Tests/DwgSceneReaderTests.cs new file mode 100644 index 0000000..3657f4c --- /dev/null +++ b/tests/DwgIO.Tests/DwgSceneReaderTests.cs @@ -0,0 +1,234 @@ +using DwgIO.Model; +using DwgIO.Scene; +using IOScene; +using Xunit; +using Vector3d = IOScene.Vector3d; + +namespace DwgIO.Tests; + +public class DwgSceneReaderTests +{ + private static DwgDocument CreateDocument(params DwgEntity[] entities) => + new( + "synthetic.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1024", + Release = "R2010", + Family = DwgContainerFamily.R2004Family, + Year = 2010, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + entities); + + private static DwgEntity Entity(ulong handle, DwgEntityKind kind, string typeName, double[] geometry, int colorIndex = 256) => + new() + { + Handle = handle, + TypeCode = 0x13, + TypeName = typeName, + Kind = kind, + Geometry = geometry, + ColorIndex = colorIndex, + }; + + [Fact] + public void Read_ConvertsLineAndPointToSceneGeometries() + { + var document = CreateDocument( + Entity(0x2A, DwgEntityKind.Line, "LINE", [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]), + Entity(0x2B, DwgEntityKind.Point, "POINT", [7.0, 8.0, 9.0])); + + var result = DwgSceneReader.Read(document, new DwgSceneOptions { ModelKey = "synthetic" }); + + var scene = result.Document; + var model = Assert.Single(scene.Models); + Assert.Equal("synthetic", model.Key); + Assert.Equal("dwg", model.SourceFormat); + Assert.Equal("m", model.SourceLengthUnit); + Assert.Equal(2, result.ElementCount); + Assert.Equal(2, result.ElementsWithGeometry); + + var line = scene.Elements[0]; + Assert.Equal("2A", line.SourceId); + Assert.Equal("LINE 2A", line.Name); + Assert.Equal("LINE", line.Category); + Assert.Equal(SceneNodeKind.Element, line.Kind); + + var lineInstance = Assert.Single(scene.Instances, i => i.ElementId == line.Id); + var lineGeometry = scene.Geometries.Single(g => g.Id == lineInstance.GeometryId); + Assert.Equal(SceneTopology.Lines, lineGeometry.Topology); + Assert.Equal(2, lineGeometry.Vertices.Count); + Assert.Equal(new Vector3d(1.0, 2.0, 3.0), lineGeometry.Vertices[0]); + Assert.Equal(new Vector3d(4.0, 5.0, 6.0), lineGeometry.Vertices[1]); + + var point = scene.Elements[1]; + var pointInstance = Assert.Single(scene.Instances, i => i.ElementId == point.Id); + var pointGeometry = scene.Geometries.Single(g => g.Id == pointInstance.GeometryId); + Assert.Equal(SceneTopology.Points, pointGeometry.Topology); + Assert.Equal(new Vector3d(7.0, 8.0, 9.0), Assert.Single(pointGeometry.Vertices)); + } + + [Fact] + public void Read_TessellatesCircleAndArc() + { + var document = CreateDocument( + Entity(0x31, DwgEntityKind.Circle, "CIRCLE", [10.0, 20.0, 0.0, 5.0]), + Entity(0x32, DwgEntityKind.Arc, "ARC", [10.0, 20.0, 0.0, 5.0, 0.0, Math.PI])); + + var result = DwgSceneReader.Read(document, new DwgSceneOptions { ModelKey = "synthetic" }); + + var circleGeometry = result.Document.Geometries[0]; + Assert.Equal(SceneTopology.Lines, circleGeometry.Topology); + Assert.Equal(64, circleGeometry.Vertices.Count); + // Vertex 0 sits at angle 0, so one radius to the right of the centre. + Assert.Equal(15.0, circleGeometry.Vertices[0].X, 9); + Assert.Equal(20.0, circleGeometry.Vertices[0].Y, 9); + + var arcGeometry = result.Document.Geometries[1]; + Assert.True(arcGeometry.Vertices.Count >= 9); + Assert.Equal(15.0, arcGeometry.Vertices[0].X, 9); + var last = arcGeometry.Vertices[^1]; + Assert.Equal(5.0, last.X, 9); // centre - radius at PI + Assert.Equal(20.0, last.Y, 9); + } + + [Fact] + public void Read_MapsAciColourOntoInstances() + { + var document = CreateDocument( + Entity(0x2A, DwgEntityKind.Line, "LINE", [0, 0, 0, 1, 0, 0], colorIndex: 1), + Entity(0x2B, DwgEntityKind.Line, "LINE", [0, 0, 0, 1, 0, 0], colorIndex: 256), + Entity(0x2C, DwgEntityKind.Line, "LINE", [0, 0, 0, 1, 0, 0], colorIndex: 0)); + + var result = DwgSceneReader.Read(document, new DwgSceneOptions { ModelKey = "synthetic" }); + + Assert.Equal(new RgbaColor(255, 0, 0), result.Document.Instances[0].Color); + // BYLAYER (256) and BYBLOCK (0) have no colour of their own until layers are decoded. + Assert.Null(result.Document.Instances[1].Color); + Assert.Null(result.Document.Instances[2].Color); + } + + [Fact] + public void Read_UnitOptionScalesCoordinates() + { + var document = CreateDocument(Entity(0x2A, DwgEntityKind.Line, "LINE", [1000.0, 0.0, 0.0, 2000.0, 0.0, 0.0])); + + var result = DwgSceneReader.Read(document, new DwgSceneOptions { ModelKey = "synthetic", LengthUnit = "mm" }); + + Assert.Equal("mm", result.LengthUnit); + Assert.Equal(0.001, result.MetresPerUnit); + Assert.Equal(1.0, result.Document.Geometries[0].Vertices[0].X, 9); + Assert.Equal(2.0, result.Document.Geometries[0].Vertices[1].X, 9); + } + + [Fact] + public void Read_UnknownUnit_Throws() + { + var document = CreateDocument(); + + Assert.Throws(() => DwgSceneReader.Read(document, new DwgSceneOptions { ModelKey = "synthetic", LengthUnit = "parsec" })); + Assert.False(DwgSceneReader.IsSupportedUnit("parsec")); + } + + [Fact] + public void Read_MemoryDocumentWithoutModelKey_Throws() + { + var document = CreateDocument(); + + Assert.Throws(() => DwgSceneReader.Read(document, new DwgSceneOptions())); + } + + [Fact] + public void Read_ForwardsDocumentDiagnostics() + { + var document = CreateDocument(); + document.ReportDiagnostic("AcDb:Handles: unexpected end"); + + var result = DwgSceneReader.Read(document, new DwgSceneOptions { ModelKey = "synthetic" }); + + var diagnostic = Assert.Single(result.Diagnostics); + Assert.Equal(SceneSeverity.Warning, diagnostic.Severity); + Assert.Equal("document", diagnostic.Code); + Assert.Contains("AcDb:Handles", diagnostic.Message); + } + + [Fact] + public void Read_EntityWithoutGeometry_CountsAndDiagnoses() + { + var document = CreateDocument( + Entity(0x2A, DwgEntityKind.Unknown, "TEXT", []), + Entity(0x2B, DwgEntityKind.Unknown, "TEXT", []), + Entity(0x2C, DwgEntityKind.Unknown, "INSERT", [])); + + var result = DwgSceneReader.Read(document, new DwgSceneOptions { ModelKey = "synthetic" }); + + Assert.Equal(3, result.ElementCount); + Assert.Equal(0, result.ElementsWithGeometry); + Assert.Equal(3, result.EntitiesWithoutGeometry); + var diagnostic = Assert.Single(result.Diagnostics, d => d.Code == "entities-without-geometry"); + Assert.Contains("TEXT 2", diagnostic.Message); + } + + [Fact] + public void Read_ArcWithInvalidAnglesReturnsWithoutGeometry() + { + var document = CreateDocument(Entity(1, DwgEntityKind.Arc, "ARC", [0, 0, 0, 5, double.PositiveInfinity, 0])); + + var result = DwgSceneReader.Read(document, new DwgSceneOptions { ModelKey = "synthetic" }); + + Assert.Empty(result.Document.Geometries); + Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Code == "non-finite-geometry"); + } + + [Fact] + public void Read_NonFiniteGeometry_DropsGeometryAndReports() + { + var document = CreateDocument(Entity(0x2A, DwgEntityKind.Line, "LINE", [0.0, 0.0, 0.0, double.NaN, 0.0, 0.0])); + + var result = DwgSceneReader.Read(document, new DwgSceneOptions { ModelKey = "synthetic" }); + + Assert.Empty(result.Document.Geometries); + Assert.Empty(result.Document.Instances); + Assert.Equal(1, result.ElementCount); + Assert.Equal(0, result.ElementsWithGeometry); + var diagnostic = Assert.Single(result.Diagnostics, d => d.Code == "non-finite-geometry"); + Assert.Equal(SceneSeverity.Warning, diagnostic.Severity); + } + + [Fact] + public void Read_ScenePassesTheIosceneContract() + { + var document = CreateDocument( + Entity(0x2A, DwgEntityKind.Line, "LINE", [1, 2, 3, 4, 5, 6], colorIndex: 1), + Entity(0x2B, DwgEntityKind.Arc, "ARC", [0, 0, 0, 2, 0.5, 1.5], colorIndex: 40), + Entity(0x2C, DwgEntityKind.Point, "POINT", [0, 0, 0])); + + var result = DwgSceneReader.Read(document, new DwgSceneOptions { ModelKey = "synthetic" }); + + Assert.DoesNotContain(result.Diagnostics, d => d.Severity == SceneSeverity.Error); + Assert.DoesNotContain(result.Document.Validate(), d => d.Severity == SceneSeverity.Error); + } + + [Fact] + public void Read_SerializedScene_IsAnIosceneDocument() + { + var document = CreateDocument(Entity(0x2A, DwgEntityKind.Line, "LINE", [1, 2, 3, 4, 5, 6])); + + var result = DwgSceneReader.Read(document, new DwgSceneOptions { ModelKey = "synthetic" }); + string json = SceneJson.Write(result.Document); + + using var parsed = System.Text.Json.JsonDocument.Parse(json); + Assert.Equal("ioscene", parsed.RootElement.GetProperty("Kind").GetString()); + Assert.Equal(1, parsed.RootElement.GetProperty("Format").GetInt32()); + + var roundTrip = SceneJson.Read(json); + Assert.Equal(result.Document.Models[0].Key, roundTrip.Models[0].Key); + Assert.Equal(result.Document.Instances.Count, roundTrip.Instances.Count); + } +} diff --git a/tests/DwgIO.Tests/DwgSvgExporterTests.cs b/tests/DwgIO.Tests/DwgSvgExporterTests.cs new file mode 100644 index 0000000..1867bb2 --- /dev/null +++ b/tests/DwgIO.Tests/DwgSvgExporterTests.cs @@ -0,0 +1,219 @@ +using System.Text; +using System.Xml; +using DwgIO.Model; +using DwgIO.Scene; +using Xunit; + +namespace DwgIO.Tests; + +public class DwgSvgExporterTests +{ + private static DwgDocument CreateDocument(params DwgEntity[] entities) => + new( + "synthetic.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1024", + Release = "R2010", + Family = DwgContainerFamily.R2004Family, + Year = 2010, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + entities); + + private static DwgEntity Entity(ulong handle, DwgEntityKind kind, string typeName, double[] geometry, int colorIndex = 256) => + new() + { + Handle = handle, + TypeCode = 0x13, + TypeName = typeName, + Kind = kind, + Geometry = geometry, + ColorIndex = colorIndex, + }; + + private static string WriteToString(DwgDocument document, DwgSvgOptions? options = null) + { + using var stream = new MemoryStream(); + DwgSvgExporter.Write(document, stream, options); + return Encoding.UTF8.GetString(stream.ToArray()); + } + + private static string SingleLineSvg() => WriteToString(CreateDocument( + Entity(0x2A, DwgEntityKind.Line, "LINE", [10.0, 20.0, 0.0, 30.0, 20.0, 0.0], colorIndex: 1))); + + [Fact] + public void Write_DrawsLineWithFlippedYAndAciColour() + { + string svg = SingleLineSvg(); + + // The Y flip puts the line at y = -20, and ACI 1 is pure red. + Assert.Contains("", svg, StringComparison.Ordinal); + } + + [Fact] + public void Write_ViewBoxContainsEveryEntity() + { + var document = CreateDocument( + Entity(0x2A, DwgEntityKind.Line, "LINE", [10.0, 20.0, 0.0, 30.0, 20.0, 0.0]), + Entity(0x2B, DwgEntityKind.Circle, "CIRCLE", [-50.0, 0.0, 0.0, 5.0]), + Entity(0x2C, DwgEntityKind.Arc, "ARC", [0.0, 0.0, 0.0, 40.0, 0.1, 1.7]), + Entity(0x2D, DwgEntityKind.Point, "POINT", [100.0, -60.0, 0.0])); + + string svg = WriteToString(document); + + string viewBox = Between(svg, "viewBox=\"", "\""); + string[] parts = viewBox.Split(' '); + double minX = Parse(parts[0]); + double minY = Parse(parts[1]); + double width = Parse(parts[2]); + double height = Parse(parts[3]); + // Every coordinate the entities occupy after the y flip: the circle's left edge (-55), the arc's top + // extreme at angle 90° (y -40), the point at x 100 (flipped to y 60). + Assert.True(minX <= -55); + Assert.True(minY <= -40); + Assert.True(minX + width >= 100); + Assert.True(minY + height >= 60); + } + + [Fact] + public void Write_ArcPathIsWellFormedAndContinuous() + { + // An arc through the top cardinal: from 10° to 170° around (0,0) with r 40 passes (0, 40). + var document = CreateDocument(Entity(0x2A, DwgEntityKind.Arc, "ARC", [0.0, 0.0, 0.0, 40.0, 10.0 * Math.PI / 180.0, 170.0 * Math.PI / 180.0])); + + string svg = WriteToString(document); + + string path = Between(svg, "(() => WriteToString(CreateDocument(), new DwgSvgOptions { Scale = scale })); + } + + [Fact] + public void Write_EmptyDrawing_ProducesValidSvg() + { + string svg = WriteToString(CreateDocument()); + + Assert.Contains("", svg, StringComparison.Ordinal); + Assert.Contains("stroke=\"#545454\" />", svg, StringComparison.Ordinal); + Assert.Equal(3, svg.Split("stroke=\"#000000\" />").Length - 1); + } + + [Fact] + public void Write_ScaleMultipliesWidthAndHeight() + { + string svg = WriteToString(CreateDocument(Entity(0x2A, DwgEntityKind.Line, "LINE", [0.0, 0.0, 0.0, 10.0, 0.0, 0.0])), new DwgSvgOptions { Scale = 2.5 }); + + // 10 units × 2.5 px/unit = 25 px, plus the 8 px margin on every side. + Assert.Equal("41", Between(svg, "width=\"", "\"")); + } + + [Fact] + public void WriteFile_IsAtomicAndLeavesNoTemporaryFile() + { + string directory = Path.Combine(Path.GetTempPath(), "dwgio-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + try + { + string path = Path.Combine(directory, "drawing.svg"); + DwgSvgExporter.WriteFile(SingleLineSvgDocument(), path, null); + + Assert.Contains(" CreateDocument( + Entity(0x2A, DwgEntityKind.Line, "LINE", [0.0, 0.0, 0.0, 10.0, 0.0, 0.0])); + + private static System.Xml.Linq.XName XName(string local) => System.Xml.Linq.XName.Get(local, "http://www.w3.org/2000/svg"); + + private static string Between(string text, string start, string end) + { + int from = text.IndexOf(start, StringComparison.Ordinal) + start.Length; + int to = text.IndexOf(end, from, StringComparison.Ordinal); + return text[from..to]; + } + + private static double Parse(string value) => + double.Parse(value, System.Globalization.CultureInfo.InvariantCulture); +} diff --git a/tests/DwgIO.Tests/DwgViewerExportTests.cs b/tests/DwgIO.Tests/DwgViewerExportTests.cs new file mode 100644 index 0000000..c8c9d03 --- /dev/null +++ b/tests/DwgIO.Tests/DwgViewerExportTests.cs @@ -0,0 +1,112 @@ +using System.Text.Json; +using DwgIO.Model; +using DwgIO.Scene; +using Xunit; + +namespace DwgIO.Tests; + +public class DwgViewerExportTests : IDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), "dwgio-tests-" + Guid.NewGuid().ToString("N")); + + public DwgViewerExportTests() + { + Directory.CreateDirectory(_directory); + } + + public void Dispose() + { + GC.SuppressFinalize(this); + try + { + Directory.Delete(_directory, recursive: true); + } + catch (DirectoryNotFoundException) + { + } + } + + private static DwgDocument CreateDocument(params DwgEntity[] entities) => + new( + "synthetic.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1024", + Release = "R2010", + Family = DwgContainerFamily.R2004Family, + Year = 2010, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + entities); + + private static DwgDocument SampleDrawing() => CreateDocument( + new DwgEntity + { + Handle = 0x2A, + TypeCode = 0x13, + TypeName = "LINE", + Kind = DwgEntityKind.Line, + Geometry = [0.0, 0.0, 0.0, 10.0, 0.0, 0.0], + ColorIndex = 1, + }, + new DwgEntity + { + Handle = 0x2B, + TypeCode = 0x12, + TypeName = "CIRCLE", + Kind = DwgEntityKind.Circle, + Geometry = [5.0, 0.0, 0.0, 5.0], + ColorIndex = 40, + }, + new DwgEntity + { + Handle = 0x2C, + TypeCode = 0x1B, + TypeName = "POINT", + Kind = DwgEntityKind.Point, + Geometry = [2.0, 3.0, 0.0], + }); + + [Fact] + public void SaveViewer_WritesSelfContainedHtml() + { + string htmlPath = Environment.GetEnvironmentVariable("DWGIO_VIEWER_DEBUG_PATH") is { Length: > 0 } debug + ? debug + : Path.Combine(_directory, "drawing.html"); + + var result = DwgViewerExport.SaveViewer(SampleDrawing(), htmlPath); + + Assert.Equal(3, result.ElementCount); + Assert.Contains(result.Document.Geometries, geometry => geometry.Topology == IOScene.SceneTopology.Lines); + Assert.Contains(result.Document.Geometries, geometry => geometry.Topology == IOScene.SceneTopology.Points); + string html = File.ReadAllText(htmlPath); + // A standalone viewer: the WebGL runtime is embedded, no external script or stylesheet is referenced. + Assert.Contains("", html, StringComparison.OrdinalIgnoreCase); + Assert.Contains("canvas", html, StringComparison.Ordinal); + Assert.DoesNotContain("", metaStart, StringComparison.Ordinal); + using var metadata = JsonDocument.Parse(html[metaStart..metaEnd]); + Assert.Equal(3, metadata.RootElement.GetProperty("geometries").GetArrayLength()); + Assert.Contains("id=\"ioviewer-bin\"", html, StringComparison.Ordinal); + } + + [Fact] + public void SaveViewer_TitleFollowsTheScene() + { + string htmlPath = Path.Combine(_directory, "drawing.html"); + + DwgViewerExport.SaveViewer(SampleDrawing(), htmlPath); + + string html = File.ReadAllText(htmlPath); + Assert.Contains("drawing.html", html, StringComparison.Ordinal); + } +} diff --git a/tests/DwgIO.Tests/EncryptedSectionTests.cs b/tests/DwgIO.Tests/EncryptedSectionTests.cs new file mode 100644 index 0000000..8dba824 --- /dev/null +++ b/tests/DwgIO.Tests/EncryptedSectionTests.cs @@ -0,0 +1,135 @@ +using DwgIO.Internal.Container; +using DwgIO.Model; +using Xunit; + +namespace DwgIO.Tests; + +/// A section map with an encrypted entry: the section is skipped with a diagnostic, not silently (#38). +public class EncryptedSectionTests +{ + private static DwgDocument CreateDocument(params SectionEntry[] entries) => CreateDocument(readMetadata: false, entries); + + private static DwgDocument CreateDocument(bool readMetadata, params SectionEntry[] entries) + { + var container = new R2004Container + { + Header = new DwgContainerHeader + { + FileHeader = new DwgFileHeader + { + Version = DwgVersionInfo.FromMagic("AC1024"u8.ToArray()), + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + SecurityFlags = 0, + SummaryInfoOffset = 0, + VbaProjectOffset = 0, + FileId = "AcFssFcAJMB", + LastPageNumber = 0, + LastPageEndOffset = 0, + BackupHeaderOffset = 0, + GapCount = 0, + PageCount = 0, + PageMapPageNumber = 0, + PageMapOffset = 0, + SectionMapPageNumber = 0, + PageTableLength = 0, + GapTableLength = 0, + StoredCrc32 = 0, + HeaderCrcValid = true, + }, + PageMap = new PageMap { Entries = [] }, + SectionMap = new SectionMap { Sections = entries }, + MaxDecompressedBytes = 1L << 30, + }; + + var document = new DwgDocument( + "synthetic.dwg", + container, + new DwgFileHeader + { + Version = DwgVersionInfo.FromMagic("AC1024"u8.ToArray()), + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + new DwgReaderOptions { ReadSummaryInfo = false, ReadMetadata = readMetadata, ReadObjects = false }); + return document; + } + + private static SectionEntry Section(string name, uint encryption) => new() + { + Name = name, + Size = 16, + PageCount = 1, + MaxPageSize = 16, + Compression = 2, + SectionId = 1, + Encryption = encryption, + Pages = [new PageRef { PageNumber = 1, DataSize = 0, StartOffset = 0 }], + }; + + + [Theory] + [InlineData(0u)] + [InlineData(1u)] + public void PreviewCommand_WhenSectionCannotBeRead_ReturnsParseError(uint encryption) + { + var document = CreateDocument(readMetadata: true, Section("AcDb:Preview", encryption)); + using var output = new StringWriter(); + using var error = new StringWriter(); + + Assert.Equal(4, Cli.Program.PreviewDocument(document, "unused", output, error)); + Assert.Contains("AcDb:Preview:", error.ToString(), StringComparison.Ordinal); + Assert.Empty(output.ToString()); + } + + [Fact] + public void TryGetReadableSection_EncryptedEntry_IsSkippedWithADiagnostic() + { + var document = CreateDocument(Section("AcDb:SummaryInfo", encryption: 1)); + + Assert.False(document.TryGetReadableSection("AcDb:SummaryInfo", out _)); + var diagnostic = Assert.Single(document.Diagnostics); + Assert.Contains("AcDb:SummaryInfo", diagnostic, StringComparison.Ordinal); + Assert.Contains("encrypted", diagnostic, StringComparison.Ordinal); + } + + [Fact] + public void TryGetReadableSection_PlainEntry_IsReadableWithoutDiagnostics() + { + var document = CreateDocument(Section("AcDb:SummaryInfo", encryption: 0)); + + Assert.True(document.TryGetReadableSection("AcDb:SummaryInfo", out var entry)); + Assert.NotNull(entry); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void TryGetReadableSection_MissingEntry_IsSilent() + { + var document = CreateDocument(Section("AcDb:SummaryInfo", encryption: 0)); + + Assert.False(document.TryGetReadableSection("AcDb:AppInfo", out _)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void TryGetReadableSection_EachEncryptedSection_IsReportedOnce() + { + var document = CreateDocument( + Section("AcDb:SummaryInfo", encryption: 1), + Section("AcDb:AppInfo", encryption: 1), + Section("AcDb:Handles", encryption: 1)); + + Assert.False(document.TryGetReadableSection("AcDb:SummaryInfo", out _)); + Assert.False(document.TryGetReadableSection("AcDb:AppInfo", out _)); + Assert.False(document.TryGetReadableSection("AcDb:Handles", out _)); + // Second look at the same section does not duplicate the message. + Assert.False(document.TryGetReadableSection("AcDb:SummaryInfo", out _)); + + Assert.Equal(4, document.Diagnostics.Count); + Assert.Contains(document.Diagnostics, d => d.Contains("AcDb:Handles", StringComparison.Ordinal)); + } +} diff --git a/tests/DwgIO.Tests/EntityColourTests.cs b/tests/DwgIO.Tests/EntityColourTests.cs new file mode 100644 index 0000000..d229f76 --- /dev/null +++ b/tests/DwgIO.Tests/EntityColourTests.cs @@ -0,0 +1,126 @@ +using System.Text.Json; +using DwgIO.Internal.Container; +using DwgIO.Internal.Parsing; +using DwgIO.Json; +using DwgIO.Model; +using Xunit; + +namespace DwgIO.Tests; + +/// Synthetic entity records, bit-built, exercising the common entity data (#40). +public class EntityColourTests +{ + [Fact] + public void ShortConstantColour256_DecodesAsByLayer() + { + var entity = DecodeLine(writer => writer.WritePackedShortTag3(), expectTransparency: false); + + Assert.Equal(256, entity.ColorIndex); + } + + [Fact] + public void FullWidthColour0x2100_DecodesAsByLayerWithTransparency() + { + var entity = DecodeLine(writer => writer.WritePackedShortRaw(0x2100), expectTransparency: true); + + // 0x2100 = index 256 in the low 9 bits, transparency flag in the upper byte. + Assert.Equal(256, entity.ColorIndex); + } + + [Fact] + public void FullWidthColourWithTransparencyKeepsTheIndexByte() + { + // 0x2005 = transparency flag (raw bit 13) plus index 5 in the low 9 bits. + var entity = DecodeLine(writer => writer.WritePackedShortRaw(0x2005), expectTransparency: true); + + Assert.Equal(5, entity.ColorIndex); + } + + [Fact] + public void JsonExport_TellsByBlockAndByLayerApart() + { + var document = new DwgDocument( + "synthetic.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1024", + Release = "R2010", + Family = DwgContainerFamily.R2004Family, + Year = 2010, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + [ + new DwgEntity { Handle = 0x2A, TypeCode = 0x13, TypeName = "LINE", Kind = DwgEntityKind.Line, Geometry = [0, 0, 0, 1, 0, 0], ColorIndex = 0 }, + new DwgEntity { Handle = 0x2B, TypeCode = 0x13, TypeName = "LINE", Kind = DwgEntityKind.Line, Geometry = [0, 0, 0, 2, 0, 0], ColorIndex = 256 }, + ]); + + using var stream = new MemoryStream(); + DwgJsonExporter.Write(document, stream, DwgJsonExportOptions.Default); + + using var json = JsonDocument.Parse(stream.ToArray()); + var entities = json.RootElement.GetProperty("entities"); + Assert.Equal(0, entities[0].GetProperty("colorIndex").GetInt32()); + Assert.Equal(256, entities[1].GetProperty("colorIndex").GetInt32()); + } + + private static DwgEntity DecodeLine(Action writeColour, bool expectTransparency) + { + var writer = new RecordBitWriter(); + writer.WriteRawByte(0x00); // R2010+ record-size VarUInt placeholder + writer.WriteTwoBits(0); // object type: tag 00 → next byte + writer.WriteRawByte(0x13); // LINE + writer.WriteHandle(code: 0, count: 0); // handle 0 + writer.WriteTwoBits(2); // extended data: packed short tag 10 → 0 (end) + writer.WriteBit(false); // no graphics preview + writer.WriteTwoBits(0); // entity mode + writer.WriteTwoBits(2); // reactors: packed int tag 10 → 0 + writer.WriteBit(false); // no extension dictionary + writer.WriteBit(false); // no AcDs data (R2013+) + writeColour(writer); + if (expectTransparency) + { + writer.WriteTwoBits(2); // transparency value: packed int tag 10 → 0 + } + + writer.WriteTwoBits(1); // linetype scale: packed double tag 01 → 1.0 + writer.WriteTwoBits(0); // linetype flags + writer.WriteTwoBits(0); // plot-style flags + writer.WriteTwoBits(0); // material flag (read for every release today, see #23) + writer.WriteRawByte(0); // shadow flags + writer.WriteBit(false); // full visual style (R2010+) + writer.WriteBit(false); // face visual style + writer.WriteBit(false); // edge visual style + writer.WriteTwoBits(2); // invisibility → 0 + writer.WriteRawByte(0); // lineweight + // LINE body + writer.WriteBit(true); // z is zero + writer.WriteRawDouble(1.0); + writer.WriteTwoBits(0); // end x = start x + writer.WriteRawDouble(2.0); + writer.WriteTwoBits(0); // end y = start y + writer.WriteBit(true); // thickness → 0.0 + writer.WriteBit(true); // extrusion → default + + var info = new DwgObjectInfo + { + StreamOffset = 0, + SizeBytes = 2, + TypeCode = 0x13, + Handle = 0x10, + StreamHandle = new DwgHandle(0, 1, 0x10), + BitsStart = 0, + BitsLength = (writer.BitsUsed + 7) / 8, + }; + + var entity = EntityDecoder.Decode(info, writer.ToArray(), 2018); + Assert.NotNull(entity); + Assert.Equal(DwgEntityKind.Line, entity.Kind); + return entity; + } + +} diff --git a/tests/DwgIO.Tests/EntityTypeTests.cs b/tests/DwgIO.Tests/EntityTypeTests.cs index f810475..69931f5 100644 --- a/tests/DwgIO.Tests/EntityTypeTests.cs +++ b/tests/DwgIO.Tests/EntityTypeTests.cs @@ -25,12 +25,84 @@ public void DrawableFixedCodes_AreEntities(ushort typeCode) [Theory] [InlineData(0x00)] // UNUSED + [InlineData(0x09)] // reserved in the supported versions [InlineData(0x30)] // BLOCK CONTROL OBJ public void ObjectsAndOutOfRangeCodes_AreNotEntities(ushort typeCode) { Assert.False(EntityDecoder.IsEntityCode(typeCode)); } + [Theory] + [InlineData(0x08, "MINSERT")] + [InlineData(0x0B, "VERTEX_3D")] + [InlineData(0x14, "DIMENSION_ORDINATE")] + [InlineData(0x1D, "POLYLINE_PFACE")] + [InlineData(0x1F, "SOLID")] + [InlineData(0x21, "SHAPE")] + [InlineData(0x23, "ELLIPSE")] + [InlineData(0x2E, "TOLERANCE")] + [InlineData(0x31, "BLOCK_RECORD")] + [InlineData(0x4A, "OLE2FRAME")] + [InlineData(0x4D, "LWPOLYLINE")] + [InlineData(0x50, "PLACEHOLDER")] + [InlineData(0x52, "LAYOUT")] + [InlineData(0x1F2, "PROXY_ENTITY")] + [InlineData(0x1F3, "PROXY_OBJECT")] + public void FixedCodes_HaveTheirLibredwgNames(ushort typeCode, string expected) + { + Assert.Equal(expected, EntityDecoder.TypeName(typeCode)); + Assert.Equal(expected, DwgObjectTypes.Name(typeCode)); + } + + [Theory] + [InlineData(0x4D)] // LWPOLYLINE + [InlineData(0x4E)] // HATCH + [InlineData(0x4A)] // OLE2FRAME + [InlineData(0x1F2)] // PROXY_ENTITY + public void DrawableCodesOutsideTheClassicRange_AreEntities(ushort typeCode) + { + Assert.True(EntityDecoder.IsEntityCode(typeCode)); + Assert.True(DwgObjectTypes.IsEntity(typeCode)); + } + + [Theory] + [InlineData(0x30)] // BLOCK_CONTROL + [InlineData(0x32)] // LAYER_CONTROL + [InlineData(0x39)] // LTYPE + [InlineData(0x48)] // GROUP + [InlineData(0x4F)] // XRECORD + [InlineData(0x51)] // VBA_PROJECT + [InlineData(0x52)] // LAYOUT + [InlineData(0x1F3)] // PROXY_OBJECT + public void TableAndControlObjects_AreNotEntities(ushort typeCode) + { + Assert.False(EntityDecoder.IsEntityCode(typeCode)); + Assert.False(DwgObjectTypes.IsEntity(typeCode)); + } + + [Fact] + public void EveryCodeInsideTheTableHasANameAndAFlag() + { + foreach (ushort code in new ushort[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x38, 0x39, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52 }) + { + string name = DwgObjectTypes.Name(code); + Assert.False(name.StartsWith("Object_", StringComparison.Ordinal), $"code 0x{code:X} has no name"); + // The flag exists by definition; the test pins the pairs that must agree. + Assert.Equal(code is >= 0x01 and <= 0x2F and not 0x2A || code is 0x4A or 0x4D or 0x4E, DwgObjectTypes.IsEntity(code)); + } + + Assert.Contains("TEXT", DwgObjectTypes.KnownNames); + Assert.Contains("HATCH", DwgObjectTypes.KnownNames); + } + + [Fact] + public void UnknownAndClassCodes_FallBack() + { + Assert.Equal("Object_53", DwgObjectTypes.Name(0x53)); + Assert.Equal("Class_502", DwgObjectTypes.Name(502)); + Assert.False(DwgObjectTypes.IsEntity(502)); // no decoded class list yet: treated as an object + } + [Fact] public void Dictionary_IsNotDecoded() { diff --git a/tests/DwgIO.Tests/HistorySectionsTests.cs b/tests/DwgIO.Tests/HistorySectionsTests.cs new file mode 100644 index 0000000..7c938ba --- /dev/null +++ b/tests/DwgIO.Tests/HistorySectionsTests.cs @@ -0,0 +1,135 @@ +using System.Buffers.Binary; +using DwgIO.Internal.Parsing; +using Xunit; + +namespace DwgIO.Tests; + +/// The AcDb:AppInfoHistory, AcDb:RevHistory, AcDb:AuxHeader and AcDb:Template sections (#36). +public class HistorySectionsTests +{ + // ------------------------------------------------------------------ RevHistory + + [Fact] + public void RevHistory_ParsesTheSaveList() + { + var data = new byte[20]; + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(0), 1); // class version + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(4), 2); // class minor + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(8), 2); // count + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(12), 5); + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(16), 7); + + var history = RevHistoryParser.Parse(data); + + Assert.Equal(1u, history.ClassVersion); + Assert.Equal(2u, history.ClassMinor); + Assert.Equal([5u, 7u], history.Histories); + } + + [Fact] + public void RevHistory_TruncatedCount_Throws() + { + // The count word promises 5 entries, the payload holds none. + var data = new byte[12]; + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(8), 5); + + Assert.Throws(() => RevHistoryParser.Parse(data)); + } + + // ------------------------------------------------------------------ Template + + [Fact] + public void Template_ParsesDescriptionAndMeasurement() + { + var data = new List(); + WriteAnsiString16(data, "standard.dwt"); + data.AddRange([0x01, 0x00]); // metric + + var template = TemplateParser.Parse([.. data], 1251); + + Assert.Equal("standard.dwt", template.Description); + Assert.Equal(1, template.Measurement); + Assert.True(template.IsMetric); + } + + [Fact] + public void Template_TruncatedDescription_Throws() + { + var data = new List(); + data.AddRange([0x20, 0x00]); // 32 bytes promised + data.AddRange([0x61, 0x62]); // "ab" + + Assert.Throws(() => TemplateParser.Parse([.. data], 1251)); + } + + // ------------------------------------------------------------------ AuxHeader + + [Fact] + public void AuxHeader_ParsesTheFixedLayout() + { + var data = new byte[123]; + data[0] = 0xFF; + data[1] = 0x77; + data[2] = 0x01; + BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan(3), 27); // dwg_version + BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan(5), 0); // maint_version + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(7), 3); // numsaves + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(11), 0xFFFFFFFF); // minus_1 + // TDCREATE at 63: Julian day 2460311, noon. + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(63), 2460311); + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(67), 43200000); + // TDUPDATE at 71. + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(71), 2460311); + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(75), 86400000 - 1); + // HANDSEED at 79. + BinaryPrimitives.WriteUInt64LittleEndian(data.AsSpan(79), 0x2B); + + var aux = AuxHeaderParser.Parse(data); + + Assert.Equal([0xFF, 0x77, 0x01], aux.Intro); + Assert.Equal(27, aux.DwgVersion); + Assert.Equal(0, aux.MaintVersion); + Assert.Equal(3u, aux.Numsaves); + Assert.Equal(0x2Bul, aux.Handseed); + Assert.Equal(2460311u, aux.CreatedRaw.JulianDay); + Assert.Equal(43200000u, aux.CreatedRaw.Milliseconds); + var midnight = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc); + Assert.Equal(midnight.AddHours(12), aux.CreatedUtc); + Assert.Equal(midnight.AddDays(1).AddMilliseconds(-1), aux.ModifiedUtc); + } + + [Fact] + public void AuxHeader_R2018AutoCADLayout_IsNormalised() + { + // In AutoCAD's R2018 variant the -1 marker sits at [13..17) and the maint_version takes 4 bytes. + var data = new byte[129]; + data[0] = 0xFF; + data[1] = 0x77; + data[2] = 0x01; + BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan(3), 32); // dwg_version + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(5), 42); // maint_version (RL) + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(9), 9); // numsaves + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(13), 0xFFFFFFFF); // minus_1 (Acad variant) + BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan(17), 7); // numsaves_1 + + var aux = AuxHeaderParser.Parse(data); + + Assert.Equal(9u, aux.Numsaves); + Assert.Equal(32, aux.DwgVersion); + Assert.Equal(42, aux.MaintVersion); + } + + [Fact] + public void AuxHeader_Truncated_Throws() + { + Assert.Throws(() => AuxHeaderParser.Parse(new byte[50])); + } + + private static void WriteAnsiString16(List data, string text) + { + var bytes = System.Text.Encoding.ASCII.GetBytes(text); + data.AddRange([(byte)(bytes.Length + 1), 0x00]); + data.AddRange(bytes); + data.Add(0); + } +} diff --git a/tests/DwgIO.Tests/JsonExporterTests.cs b/tests/DwgIO.Tests/JsonExporterTests.cs index 7ab59d9..11afcaa 100644 --- a/tests/DwgIO.Tests/JsonExporterTests.cs +++ b/tests/DwgIO.Tests/JsonExporterTests.cs @@ -35,6 +35,29 @@ private static DwgEntity CreateEntity(double[] geometry) => Geometry = geometry, }; + [Fact] + public void Write_LeavesObjectTypeCodesAndAddsNames() + { + var header = new DwgFileHeader + { + Version = DwgVersionInfo.FromMagic("AC1032"u8.ToArray()), + Codepage = 30, MaintenanceVersion = 0, PreviewOffset = 0, + }; + var item = new DwgObjectInfo + { + TypeCode = 0x13, Handle = 1, StreamHandle = new DwgHandle(0, 1, 1), + StreamOffset = 4, SizeBytes = 2, BitsStart = 6, BitsLength = 16, + }; + var document = new DwgDocument("synthetic.dwg", header, [], objects: [item]); + using var buffer = new MemoryStream(); + DwgJsonExporter.Write(document, buffer, DwgJsonExportOptions.Default); + using var json = JsonDocument.Parse(buffer.ToArray()); + var objects = json.RootElement.GetProperty("objects"); + + Assert.Equal(1, objects.GetProperty("byType").GetProperty("13").GetInt32()); + Assert.Equal(1, objects.GetProperty("byTypeName").GetProperty("LINE").GetInt32()); + } + [Fact] public void Write_NonFiniteGeometry_WritesNullAndRecordsDiagnostic() { diff --git a/tests/DwgIO.Tests/MetadataParserTests.cs b/tests/DwgIO.Tests/MetadataParserTests.cs index a626d9d..c957281 100644 --- a/tests/DwgIO.Tests/MetadataParserTests.cs +++ b/tests/DwgIO.Tests/MetadataParserTests.cs @@ -140,6 +140,44 @@ public void AppInfo_UnicodeLayout_ParsesVersionFromXml() Assert.Equal("Autodesk DWG. Trusted DWG notice.", appInfo.Comment); Assert.Contains("1.2.3.4", appInfo.Version); Assert.Contains("ProductInformation", appInfo.ProductXml); + // #35: the product XML's name attribute is the product. + Assert.Equal("Writer", appInfo.Product); + } + + [Fact] + public void AppInfo_Product_ComesFromTheXmlNameAttribute() + { + var data = BuildUnicodeAppInfo( + "AppInfoDataList", + (ProductXmlEntryId, "")); + + var appInfo = AppInfoParser.Parse(data, 1251); + + Assert.Equal("AutoCAD", appInfo.Product); + } + + [Theory] + [InlineData("", "AutoCAD")] + [InlineData("", "AutoCAD LT")] + [InlineData("", "A & B")] + [InlineData("", "Writer")] + public void AppInfo_Product_HandlesXmlAttributeForms(string xml, string expected) + { + var data = BuildUnicodeAppInfo("AppInfoDataList", (ProductXmlEntryId, xml)); + + Assert.Equal(expected, AppInfoParser.Parse(data, 30).Product); + } + + [Fact] + public void AppInfo_Product_IsEmptyWithoutANameAttribute() + { + var data = BuildUnicodeAppInfo( + "AppInfoDataList", + (ProductXmlEntryId, "")); + + var appInfo = AppInfoParser.Parse(data, 1251); + + Assert.Equal(string.Empty, appInfo.Product); } [Fact] diff --git a/tests/DwgIO.Tests/ObjectStreamGapTests.cs b/tests/DwgIO.Tests/ObjectStreamGapTests.cs new file mode 100644 index 0000000..cde7768 --- /dev/null +++ b/tests/DwgIO.Tests/ObjectStreamGapTests.cs @@ -0,0 +1,166 @@ +using DwgIO.Internal.Container; +using DwgIO.Model; +using Xunit; + +namespace DwgIO.Tests; + +/// Synthetic object streams and handle maps for the gap diagnostics (#13). +public class ObjectStreamGapTests +{ + [Fact] + public void Walk_WithoutMap_StopsAtTheGapSilently() + { + var stream = new RecordBitWriter(); + stream.WriteRawByte(0xCA); + stream.WriteRawByte(0x0D); + stream.WriteRawByte(0); + stream.WriteRawByte(0); + stream.WriteRecord(r => r.WriteLineRecord()); + stream.WriteZeros(9); // the gap: zero bytes are not a record + stream.WriteRecord(r => r.WriteLineRecord()); + + var objects = ObjectStreamWalker.Walk(stream.ToArray(), r2010Plus: true); + + // The pre-fix behaviour: the walk stops at the first bad size and drops the rest. + Assert.Single(objects); + } + + [Fact] + public void Walk_WithMap_ResumesAtTheNextMapOffsetAndReportsTheGap() + { + var stream = new RecordBitWriter(); + stream.WriteRawByte(0xCA); + stream.WriteRawByte(0x0D); + stream.WriteRawByte(0); + stream.WriteRawByte(0); + int recordAStart = stream.BytesUsed; + stream.WriteRecord(r => r.WriteLineRecord()); + stream.WriteZeros(9); // the gap + int recordBStart = stream.BytesUsed; + stream.WriteRecord(r => r.WriteLineRecord()); + + var mapOffsets = new List { (ulong)recordAStart, (ulong)recordBStart }; + var diagnostics = new List(); + var objects = ObjectStreamWalker.Walk(stream.ToArray(), r2010Plus: true, mapOffsets, diagnostics.Add); + + Assert.Equal(2, objects.Count); + Assert.Equal(recordAStart, objects[0].StreamOffset); + Assert.Equal(recordBStart, objects[1].StreamOffset); + var gap = Assert.Single(diagnostics, d => d.Contains("gap at", StringComparison.Ordinal)); + Assert.Contains("resumed", gap, StringComparison.Ordinal); + } + + [Fact] + public void Walk_ZeroGapWithoutMap_EndsCleanly() + { + // Zero padding is a normal stream end: the walk stops without a diagnostic. + var stream = new RecordBitWriter(); + stream.WriteRawByte(0xCA); + stream.WriteRawByte(0x0D); + stream.WriteRawByte(0); + stream.WriteRawByte(0); + stream.WriteRecord(r => r.WriteLineRecord()); + stream.WriteZeros(9); + stream.WriteRecord(r => r.WriteLineRecord()); + + var diagnostics = new List(); + var objects = ObjectStreamWalker.Walk(stream.ToArray(), r2010Plus: true, mapOffsets: [], diagnostics.Add); + + Assert.Single(objects); + Assert.Empty(diagnostics); + } + + [Fact] + public void CountUnreachedObjects_UsesBothHandleAndOffset() + { + var stream = new RecordBitWriter(); + stream.WriteRecord(r => r.WriteLineRecord()); + var objects = ObjectStreamWalker.Walk(stream.ToArray(), r2010Plus: true); + var item = Assert.Single(objects); + var map = new DwgHandleMap + { + Entries = [new DwgHandleMapEntry(item.Handle, (ulong)item.StreamOffset + 1)], + }; + + Assert.Equal(1, DwgDocument.CountUnreachedObjects(objects, map)); + } + + [Fact] + public void Walk_TruncatedTailWithoutRecovery_ReportsTheStop() + { + var stream = new RecordBitWriter(); + stream.WriteRawByte(0xCA); + stream.WriteRawByte(0x0D); + stream.WriteRawByte(0); + stream.WriteRawByte(0); + stream.WriteRecord(r => r.WriteLineRecord()); + // A record whose declared size runs past the stream end: no map offset to recover to. + stream.WriteRawByte(100 & 0xFF); + stream.WriteRawByte(0); + stream.WriteZeros(4); + + var diagnostics = new List(); + var objects = ObjectStreamWalker.Walk(stream.ToArray(), r2010Plus: true, mapOffsets: [], diagnostics.Add); + + Assert.Single(objects); + var stop = Assert.Single(diagnostics); + Assert.Contains("stopped at", stop, StringComparison.Ordinal); + Assert.Contains("past the stream end", stop, StringComparison.Ordinal); + } + + [Fact] + public void Walk_CleanStream_EndsWithoutDiagnostics() + { + var stream = new RecordBitWriter(); + stream.WriteRawByte(0xCA); + stream.WriteRawByte(0x0D); + stream.WriteRawByte(0); + stream.WriteRawByte(0); + stream.WriteRecord(r => r.WriteLineRecord()); + stream.WriteRecord(r => r.WriteLineRecord()); + + var diagnostics = new List(); + var objects = ObjectStreamWalker.Walk(stream.ToArray(), r2010Plus: true, mapOffsets: [], diagnostics.Add); + + Assert.Equal(2, objects.Count); + Assert.Empty(diagnostics); + } + + [Fact] + public void Parse_TruncatedBlock_ReportsAndKeepsThePreviousEntries() + { + // One well-formed block (handle 1 at offset 4), then a block whose declared size runs past the data. + var writer = new RecordBitWriter(); + writer.WriteRawByte(0); writer.WriteRawByte(4); // block: 2 delta bytes + 2 CRC bytes + writer.WriteRawByte(1); writer.WriteRawByte(4); // handle delta 1, offset delta 4 + writer.WriteRawByte(0); writer.WriteRawByte(0); // CRC placeholder + writer.WriteRawByte(0); writer.WriteRawByte(30); // declared 30 bytes — truncated + + var diagnostics = new List(); + var map = DwgHandleMap.Parse(writer.ToArray(), diagnostics.Add); + + Assert.Equal(1, map.Count); + Assert.Equal(4u, map.Entries[0].Offset); + Assert.Contains(diagnostics, d => d.Contains("truncated", StringComparison.Ordinal)); + } + + [Fact] + public void Parse_NegativeOffset_IsDroppedAndReported() + { + // handle delta 1, offset delta 4 → entry (1, 4); then handle delta 1, offset delta -10 → dropped. + var writer = new RecordBitWriter(); + writer.WriteRawByte(0); writer.WriteRawByte(6); // block: 4 delta bytes + 2 CRC bytes + writer.WriteRawByte(1); writer.WriteRawByte(4); // handle 1, offset +4 + writer.WriteRawByte(1); writer.WriteRawByte(0x46); // handle +1, offset delta -6 (VarInt: 0x40 | 6) + writer.WriteRawByte(0); writer.WriteRawByte(0); // CRC placeholder + + var diagnostics = new List(); + var map = DwgHandleMap.Parse(writer.ToArray(), diagnostics.Add); + + Assert.Equal(1, map.Count); + Assert.Equal(1u, map.Entries[0].Handle); + Assert.Equal(4u, map.Entries[0].Offset); + Assert.Contains(diagnostics, d => d.Contains("negative offset", StringComparison.Ordinal)); + Assert.Contains(diagnostics, d => d.Contains("dropped", StringComparison.Ordinal)); + } +} diff --git a/tests/DwgIO.Tests/OpenStreamTests.cs b/tests/DwgIO.Tests/OpenStreamTests.cs new file mode 100644 index 0000000..2a5272e --- /dev/null +++ b/tests/DwgIO.Tests/OpenStreamTests.cs @@ -0,0 +1,117 @@ +using System.Buffers.Binary; +using Xunit; + +namespace DwgIO.Tests; + +/// DwgDocument.Open(Stream): identical results to Open(path) on the same bytes (#37). +public class OpenStreamTests +{ + private static byte[] CraftedFile() + { + // The negative-page-map-offset file of InputHardeningTests: a parseable header that fails cleanly. + var bytes = new byte[0x100]; + "AC1018"u8.CopyTo(bytes); + var block = new byte[Internal.Cipher.DwgCipher.HeaderBlockLength]; + "AcFssFcAJMB"u8.CopyTo(block); + BinaryPrimitives.WriteUInt64LittleEndian(block.AsSpan(0x54), 0xFFFF_FFFF_7FFF_FF00); + Internal.Cipher.DwgCipher.XorHeaderBlock(block); + block.CopyTo(bytes, 0x80); + return bytes; + } + + [Fact] + public void Open_Stream_SameCleanFailureAsPath() + { + var bytes = CraftedFile(); + string path = Path.Combine(Path.GetTempPath(), $"dwgio-{Guid.NewGuid():N}.dwg"); + File.WriteAllBytes(path, bytes); + try + { + var pathException = Assert.Throws(() => DwgDocument.Open(path)); + + using var stream = new MemoryStream(bytes); + var streamException = Assert.Throws(() => DwgDocument.Open(stream, "crafted.dwg")); + + Assert.Equal(pathException.Message, streamException.Message); + } + finally + { + File.Delete(path); + } + } + + [Fact] + public void Open_Stream_UnsupportedVersion_SameFailureAsPath() + { + var bytes = new byte[0x80]; + "AC1021"u8.CopyTo(bytes); + string path = Path.Combine(Path.GetTempPath(), $"dwgio-{Guid.NewGuid():N}.dwg"); + File.WriteAllBytes(path, bytes); + try + { + var pathException = Assert.Throws(() => DwgDocument.Open(path)); + + using var stream = new MemoryStream(bytes); + var streamException = Assert.Throws(() => DwgDocument.Open(stream)); + + // The message names the source (the path or "stream"); the rest is identical. + Assert.Equal(Core(pathException.Message), Core(streamException.Message)); + + } + finally + { + File.Delete(path); + } + } + + private sealed class NonReadableStream(byte[] bytes) : MemoryStream(bytes) + { + public override bool CanRead => false; + } + + [Fact] + public void Open_Stream_NotReadable_Throws() + { + using var stream = new NonReadableStream([1, 2, 3]); + Assert.Throws(() => DwgDocument.Open(stream)); + } + + [Fact] + public void Open_Stream_Empty_ThrowsCleanly() + { + using var stream = new MemoryStream([]); + Assert.Throws(() => DwgDocument.Open(stream)); + } + + [Fact] + public void Open_Stream_DefaultName_IsStream() + { + // A header that parses far enough to name the document: the unsupported-version path reports the name. + var bytes = new byte[0x80]; + "AC1021"u8.CopyTo(bytes); + using var stream = new MemoryStream(bytes); + + var ex = Assert.Throws(() => DwgDocument.Open(stream)); + + Assert.Contains("stream", ex.Message, StringComparison.Ordinal); + } + + private static string Core(string message) => message[(message.IndexOf(": ", StringComparison.Ordinal) + 2)..]; + + [SkippableFact] + public void Open_Stream_MatchesPath_OnEveryAvailableDrawing() => DwgFixtureTests.CheckAll(path => + { + var fromPath = DwgDocument.Open(path); + using var stream = File.OpenRead(path); + var fromStream = DwgDocument.Open(stream, path); + using var fileJson = new MemoryStream(); + using var streamJson = new MemoryStream(); + Json.DwgJsonExporter.Write(fromPath, fileJson, Json.DwgJsonExportOptions.Default); + Json.DwgJsonExporter.Write(fromStream, streamJson, Json.DwgJsonExportOptions.Default); + + Assert.Equal(fromPath.Diagnostics, fromStream.Diagnostics); + Assert.True(fileJson.GetBuffer().AsSpan(0, (int)fileJson.Length) + .SequenceEqual(streamJson.GetBuffer().AsSpan(0, (int)streamJson.Length))); + return true; + }, "a readable container"); +} diff --git a/tests/DwgIO.Tests/RecordBitWriter.cs b/tests/DwgIO.Tests/RecordBitWriter.cs new file mode 100644 index 0000000..48ac811 --- /dev/null +++ b/tests/DwgIO.Tests/RecordBitWriter.cs @@ -0,0 +1,155 @@ +namespace DwgIO.Tests; + +/// +/// MSB-first bit writer mirroring 's consumption, for +/// synthetic object records and handle-map blocks in the tests. +/// +internal sealed class RecordBitWriter +{ + private readonly List _bytes = []; + private int _bitPos; + + /// Bits written so far; a partially filled trailing byte counts once. + public int BitsUsed => _bitPos == 0 ? _bytes.Count * 8 : (_bytes.Count - 1) * 8 + _bitPos; + + public int BytesUsed => _bytes.Count; + + public byte[] ToArray() => [.. _bytes]; + + public void WriteBit(bool bit) => WriteBits(bit ? 1ul : 0ul, 1); + + public void WriteTwoBits(uint value) => WriteBits(value, 2); + + public void WriteRawByte(byte value) => WriteBits(value, 8); + + public void WriteRawDouble(double value) + { + foreach (byte b in BitConverter.GetBytes(value)) + { + WriteRawByte(b); + } + } + + public void WriteHandle(byte code, byte count) + { + WriteBits(code, 4); + WriteBits(count, 4); + for (int i = 0; i < count; i++) + { + WriteRawByte(0); + } + } + + /// Packed short tag 11 → the constant 256 (BYLAYER in the short form). + public void WritePackedShortTag3() => WriteTwoBits(3); + + /// Packed short tag 00 followed by the two little-endian bytes of a full-width value. + public void WritePackedShortRaw(ushort value) + { + WriteTwoBits(0); + WriteRawByte((byte)(value & 0xFF)); + WriteRawByte((byte)(value >> 8)); + } + + /// Writes one object record: size prefix (15-bit words, little-endian), the bit-level payload + /// produced by and a two-byte CRC placeholder. Returns the record's start offset. + public int WriteRecord(Action fill) + { + int recordStart = BytesUsed; + var payload = new RecordBitWriter(); + fill(payload); + byte[] payloadBytes = payload.ToArray(); + // The R2010+ handle-stream size VarUInt (the payload's first byte here) is not counted by the prefix. + uint declared = (uint)(payloadBytes.Length - 1); + WriteSizePrefix(declared); + foreach (byte b in payloadBytes) + { + WriteRawByte(b); + } + + WriteRawByte(0); // CRC placeholder, low byte + WriteRawByte(0); // CRC placeholder, high byte + return recordStart; + } + + /// Writes a run of zero bytes (a gap between records). + public void WriteZeros(int count) + { + for (int i = 0; i < count; i++) + { + WriteRawByte(0); + } + } + + /// The standard LINE record body used by the synthetic tests, starting with the R2010+ VarUInt + /// handle-stream size placeholder. + public void WriteLineRecord() + { + WriteRawByte(0x00); // R2010+ record-size VarUInt placeholder + WriteTwoBits(0); // object type: tag 00 → next byte + WriteRawByte(0x13); // LINE + WriteHandle(code: 0, count: 0); // handle 0 + WriteTwoBits(2); // extended data: packed short tag 10 → 0 (end) + WriteBit(false); // no graphics preview + WriteTwoBits(0); // entity mode + WriteTwoBits(2); // reactors: packed int tag 10 → 0 + WriteBit(false); // no extension dictionary + WriteBit(false); // no AcDs data (R2013+) + WriteTwoBits(2); // colour: packed short tag 10 → 0 (BYBLOCK) + WriteTwoBits(1); // linetype scale: packed double tag 01 → 1.0 + WriteTwoBits(0); // linetype flags + WriteTwoBits(0); // plot-style flags + WriteTwoBits(0); // material flag + WriteRawByte(0); // shadow flags + WriteBit(false); // full visual style (R2010+) + WriteBit(false); // face visual style + WriteBit(false); // edge visual style + WriteTwoBits(2); // invisibility → 0 + WriteRawByte(0); // lineweight + WriteBit(true); // z is zero + WriteRawDouble(1.0); + WriteTwoBits(0); // end x = start x + WriteRawDouble(2.0); + WriteTwoBits(0); // end y = start y + WriteBit(true); // thickness → 0.0 + WriteBit(true); // extrusion → default + } + + private void WriteSizePrefix(uint value) + { + // 15-bit little-endian words, 0x8000 marks a following word. + while (true) + { + uint word = value & 0x7FFF; + value >>= 15; + if (value == 0) + { + WriteRawByte((byte)(word & 0xFF)); + WriteRawByte((byte)(word >> 8)); + return; + } + + WriteRawByte((byte)(word & 0xFF)); + WriteRawByte((byte)((word >> 8) | 0x80)); + } + } + + private void WriteBits(ulong value, int n) + { + for (int i = n - 1; i >= 0; i--) + { + if (_bitPos == 0) + { + _bytes.Add(0); + } + + int index = _bytes.Count - 1; + if ((value >> i & 1) != 0) + { + _bytes[index] |= (byte)(0x80 >> _bitPos); + } + + _bitPos = (_bitPos + 1) & 7; + } + } +} diff --git a/tests/DwgIO.Tests/TestFiles.cs b/tests/DwgIO.Tests/TestFiles.cs index 1a86252..62399a9 100644 --- a/tests/DwgIO.Tests/TestFiles.cs +++ b/tests/DwgIO.Tests/TestFiles.cs @@ -1,21 +1,25 @@ namespace DwgIO.Tests; -/// Where the tests find private DWG files that are not part of the repository. The folder is named by the environment -/// variable DWGIO_TEST_FILES; when it is not set, the folder test_files in the repository root (or in an ancestor of the test -/// binary) is used. Files may lie directly in the folder or in one level of subfolders. A test that needs a file which is not +/// Where the tests find DWG fixtures: the folder named by the environment variable DWGIO_TEST_FILES, the committed +/// redistributable drawings of test-files/public, and a test_files folder in the repository root (or in an ancestor of the test +/// binary). Files may lie directly in a folder or in one level of subfolders. A test that needs a file which is not /// there is reported as skipped with the reason, never passed. internal static class TestFiles { public const string EnvironmentVariable = "DWGIO_TEST_FILES"; - /// Folders searched for fixtures, the one named by the environment variable first. + /// Folders searched for fixtures: the one named by the environment variable first, then the + /// committed redistributable drawings of test-files/public, then a test_files folder in the repository + /// root (or in an ancestor of the test binary). public static IEnumerable Roots() { if (Environment.GetEnvironmentVariable(EnvironmentVariable) is { Length: > 0 } configured && Directory.Exists(configured)) yield return configured; for (var directory = AppContext.BaseDirectory; directory != null; directory = Path.GetDirectoryName(directory)) { - string candidate = Path.Combine(directory, "test_files"); + string candidate = Path.Combine(directory, "test-files", "public"); + if (Directory.Exists(candidate)) yield return candidate; + candidate = Path.Combine(directory, "test_files"); if (Directory.Exists(candidate)) yield return candidate; } }