Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ API between minor releases.
## [Unreleased]

### Added
- `--unit auto` reads a supported `$INSUNITS` for scene, OBJ, GLB and HTML exports. These commands default to metres.
- `AcDb:Header` parsing (`DwgHeaderVariables`, `DwgInsUnits`, `DwgPoint2D`, `DwgPoint3D`, `DwgDocument.HeaderVariables`, `DwgReaderOptions.ReadHeader`) exposing `$INSUNITS`, `$MEASUREMENT`, extents/limits, units formatting, point style (`$PDMODE`/`$PDSIZE`), linetype/text/dim scales, timestamps, `$HANDSEED`, and GUIDs in JSON export, `dwgio inspect`, `DwgSceneOptions.UseDrawingUnits` and the 2D HTML viewer.
- `AcDb:Classes` parsing (`DwgClassInfo`, `DwgDocument.Classes`, `DwgReaderOptions.ReadClasses`) resolving class names (codes 500+) and `IsEntity` flags in `DwgObjectInfo`, JSON export and `dwgio inspect`.
- Entity geometry decoding for `LWPOLYLINE` (including bulges and elevation), `ELLIPSE`, `SOLID`/`TRACE`, `3DFACE`, `RAY`, `XLINE` and 24-bit `TrueColorRgb` across `DwgIO`, `DwgIO.Scene`, SVG and the 2D AutoCAD HTML viewer.
- `DwgReaderOptions`: `Strict`, `MaxFileBytes`, `MaxSectionBytes`, `MaxDecompressedBytes`, `MaxObjectCount`,
Expand Down
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,15 @@ Save the embedded thumbnail preview. Without an extension, `.png`, `.wmf` or `.b
dwgio preview drawing.dwg thumbnail
```

Export a neutral IOScene scene document (geometry in metres, ACI colours, one element per decoded entity). `--unit` names the drawing unit the coordinates are scaled from — one of `mm`, `cm`, `m` (default), `ft`, `in`:
Export a neutral IOScene scene document (geometry in metres, ACI colours, one element per decoded entity). Use
`--unit mm|cm|m|ft|in` to set the drawing unit. With `--unit auto`, a supported `$INSUNITS` provides the unit.
The default and the fallback for missing or unsupported drawing units are both metres.

```sh
dwgio scene drawing.dwg drawing.scene.json --unit mm
```

The plain export command writes OBJ, GLB and HTML by output extension (with `--unit mm|cm|m|ft|in`):
The plain export command writes OBJ, GLB and HTML by output extension and accepts the same `--unit` values:

```sh
dwgio drawing.dwg drawing.obj --unit mm # Wavefront OBJ + drawing.mtl with the ACI colours
Expand Down
8 changes: 5 additions & 3 deletions docs/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ change in any release and is visible only to the test project through `Internals

| Type | Use |
|---|---|
| `DwgDocument` | Opens a drawing (`Open` / `OpenAsync` from path or stream) and gives `SourcePath` (null for streams), `Path`, `Version`, file and container headers, section catalog, metadata, handle map, object inventory, entities and `Diagnostics`. `ReadSection(name)` returns decompressed section bytes; `ReleaseSectionBuffers()` drops retained raw buffers; `SaveJson` / `ToJson` write JSON. |
| `DwgReaderOptions` | What `Open` reads and enforces: `ReadSectionMap`, `ReadSummaryInfo`, `ReadMetadata`, `ReadObjects`, `ReadEntities`, `VerifyChecksums`, `Strict` (throws on diagnostics), `ReleaseSectionBuffers`, `MaxFileBytes`, `MaxSectionBytes`, `MaxDecompressedBytes`, `MaxObjectCount`, `Progress` and `DiagnosticOutput`. |
| `DwgDocument` | Opens a drawing (`Open` / `OpenAsync` from path or stream) and gives `SourcePath` (null for streams), `Path`, `Version`, file and container headers, header variables (`HeaderVariables`), section catalog, metadata, handle map, object inventory, entities and `Diagnostics`. `ReadSection(name)` returns decompressed section bytes; `ReleaseSectionBuffers()` drops retained raw buffers; `SaveJson` / `ToJson` write JSON. |
| `DwgReaderOptions` | What `Open` reads and enforces: `ReadSectionMap`, `ReadSummaryInfo`, `ReadMetadata`, `ReadHeader`, `ReadClasses`, `ReadObjects`, `ReadEntities`, `VerifyChecksums`, `Strict` (throws on diagnostics), `ReleaseSectionBuffers`, `MaxFileBytes`, `MaxSectionBytes`, `MaxDecompressedBytes`, `MaxObjectCount`, `Progress` and `DiagnosticOutput`. |
| `DwgReadProgress` | Synchronous phase updates (`Phase`, `Completed`, `Total`) delivered via `DwgReaderOptions.Progress`. |
| `DwgExitCodes` | Standard CLI exit codes (`Ok = 0`, `Usage = 1`, `FileNotFound = 2`, `UnsupportedVersion = 3`, `ParseError = 4`, `NoPreview = 5`). |
| `DwgException` | Thrown for a damaged or truncated file, exceeded reader limits, `Strict` diagnostic failures, and by `ReadSection` when buffers were released or a section is missing. |
Expand Down Expand Up @@ -41,6 +41,7 @@ change in any release and is visible only to the test project through `Internals
| `DwgDocument.AppInfoHistory` | Decompressed bytes of `AcDb:AppInfoHistory` when available. The record layout is unknown. |
| `DwgRevHistory` | The save references of `AcDb:RevHistory`: layout version pair and one value per recorded save. |
| `DwgAuxHeader` | The auxiliary header of `AcDb:AuxHeader`: version pair, save counter, creation and last-update times, next handle. |
| `DwgHeaderVariables`, `DwgInsUnits`, `DwgPoint2D`, `DwgPoint3D` | Drawing system variables from `AcDb:Header`: `$INSUNITS` (`TryGetSceneUnit`), `$MEASUREMENT`, `$EXTMIN`/`$EXTMAX`, `$LIMMIN`/`$LIMMAX`, `$LUNITS`/`$LUPREC`, `$AUNITS`/`$AUPREC`, `$PDMODE`/`$PDSIZE`, `$LTSCALE`/`$CELTSCALE`/`$DIMSCALE`, `$CELWEIGHT`, `$TDCREATE`/`$TDUPDATE`, `$HANDSEED`, `$FINGERPRINTGUID` and `$VERSIONGUID`. |
| `DwgTemplate` | The template description of `AcDb:Template`: description and unit system (English/metric). |

## JSON export (`DwgIO.Json`)
Expand Down Expand Up @@ -73,7 +74,7 @@ line and point geometry in metres, ACI colours on placements and a report in `Dw
| Type | Use |
|---|---|
| `DwgSceneReader` | `Read(path, options?)` opens and converts a drawing file (releasing raw section buffers automatically); `Read(stream, documentName?, options?)` converts a drawing from a stream; `Read(document, options)` converts an already opened `DwgDocument` (which needs `ModelKey`). |
| `DwgSceneOptions` | `LengthUnit` (`mm`, `cm`, `m`, `ft`, `in`; default `m`), `ModelKey`, and `ReadProgress` (`IProgress<DwgReadProgress>?`). |
| `DwgSceneOptions` | `LengthUnit` (`mm`, `cm`, `m`, `ft`, `in`; default `m`), `UseDrawingUnits` (prefers `$INSUNITS` when supported), `ModelKey`, and `ReadProgress` (`IProgress<DwgReadProgress>?`). |
| `DwgSceneResult` | The `Document` (an `IOScene.SceneDocument`), `Diagnostics`, element and geometry counters, the applied `MetresPerUnit` and `UnitAssumed`. |

```csharp
Expand All @@ -94,6 +95,7 @@ The CLI uses these exporters and adds a 2D HTML viewer:
- `dwgio drawing.dwg drawing.html` exports the interactive 3D WebGL viewer via [IOViewer](https://github.com/IOExtend/IOViewer). You can also pass `--mode 3d`.
- `dwgio drawing.dwg drawing.html --mode 2d` exports an AutoCAD-style top view. Use `--bg black|slate|light` to set its background.
- `dwgio drawing.dwg out.obj --unit mm` and `dwgio drawing.dwg out.glb --unit mm` pass `--unit` to the scene converter.
- The scene, OBJ, GLB and HTML commands use metres by default. Pass `--unit auto` to use a supported `$INSUNITS`.

## Diagnostics

Expand Down
16 changes: 15 additions & 1 deletion src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,13 @@ private static string BuildPayloadJson(DwgDocument document, DwgViewerOptions op
w.WriteString("title", title);
w.WriteString("version", document.Version.ToString());
w.WriteString("unit", lengthUnit);
if (document.HeaderVariables is { } header)
{
w.WriteNumber("pdmode", header.PdMode);
w.WriteNumber("pdsize", double.IsFinite(header.PdSize) ? header.PdSize : 0.0);
w.WriteString("insunits", header.InsUnits.ToString());
}

w.WriteString("theme", options.Theme switch
{
DwgCadTheme.Slate => "slate",
Expand Down Expand Up @@ -682,7 +689,13 @@ private static void Expand(double x, double y, ref double minX, ref double minY,
let theme = data.theme || 'black';
let showGrid = true;
let showCrosshair = true;
let pointStyle = 'target';
let pointStyle = (() => {
const pm = typeof data.pdmode === 'number' ? data.pdmode : 0;
if ((pm & 0x20) !== 0 || (pm & 0x0F) === 3) return 'target';
if (pm === 1) return 'dot';
if (pm === 0 || (pm & 0x0F) === 2) return 'target';
return 'target';
})();
let activeType = 'ALL';
let searchQuery = '';
let selectedIndex = -1;
Expand Down Expand Up @@ -1433,6 +1446,7 @@ function renderList() {
});

new ResizeObserver(resizeCanvas).observe(canvas);
selPoint.value = pointStyle;
applyTexts();
applyTheme(theme);
requestAnimationFrame(() => {
Expand Down
3 changes: 2 additions & 1 deletion src/DwgIO.Cli/Export/DwgViewerExport.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public static DwgSceneResult SaveViewer(
}
else
{
AtomicOutput.Write(htmlPath, stream => DwgCadHtmlViewer.Export(document, stream, viewerOptions, sceneOptions.LengthUnit));
AtomicOutput.Write(htmlPath, stream => DwgCadHtmlViewer.Export(document, stream, viewerOptions, result.LengthUnit ?? sceneOptions.LengthUnit));
}

return result;
Expand All @@ -69,6 +69,7 @@ private static DwgSceneOptions ViewerOptionsFor(string path, DwgSceneOptions? op
return new DwgSceneOptions
{
LengthUnit = options?.LengthUnit ?? "m",
UseDrawingUnits = options?.UseDrawingUnits ?? false,
ModelKey = Path.GetFileName(path),
ReadProgress = options?.ReadProgress,
};
Expand Down
38 changes: 22 additions & 16 deletions src/DwgIO.Cli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ or the scene to OBJ (.obj), GLB (.glb) or a standalone
dwgio extract <file.dwg> <section> <out> Write a named section's decompressed bytes
dwgio preview <file.dwg> <out> Write the embedded thumbnail image
dwgio scene <file.dwg> <out.json> [--unit u] Export a neutral IOScene scene document
(u: mm, cm, m (default), ft or in)
(u: mm, cm, m (default), ft, in or auto)
dwgio svg <file.dwg> <out.svg> [--scale s] Draw model space to SVG (s: px per unit, default 1)
dwgio entities <file.dwg> [--type LINE,CIRCLE] [--json]
List decoded entities, one line each or as JSON
Expand Down Expand Up @@ -181,6 +181,12 @@ internal static int InspectDocument(DwgDocument doc, TextWriter output)
output.WriteLine($"Template: \"{Truncate(template.Description, 60)}\" units={units}");
}

if (doc.HeaderVariables is { } hv)
{
output.WriteLine(
$"Header: insunits={hv.InsUnits} lunits={hv.LUnits} pdmode={hv.PdMode} ltscale={Plain(hv.LtScale)} handseed={hv.Handseed:X}");
}

if (doc.Preview is { } preview)
{
output.WriteLine($"Preview: {preview.ImageKind} {Count(preview.ImageBytes.Length)} bytes");
Expand Down Expand Up @@ -265,14 +271,14 @@ private static int Export(string[] args, TextWriter output, TextWriter error)
case "--unit":
if (i + 1 >= args.Length)
{
error.WriteLine("error: --unit needs a value (mm, cm, m, ft or in).");
error.WriteLine("error: --unit needs a value (mm, cm, m, ft, in or auto).");
return DwgExitCodes.Usage;
}

unit = args[++i];
if (!DwgSceneReader.IsSupportedUnit(unit))
if (!IsAutoUnit(unit) && !DwgSceneReader.IsSupportedUnit(unit))
{
error.WriteLine($"error: unknown length unit '{unit}'. Use mm, cm, m, ft or in.");
error.WriteLine($"error: unknown length unit '{unit}'. Use mm, cm, m, ft, in or auto.");
return DwgExitCodes.Usage;
}

Expand Down Expand Up @@ -356,7 +362,7 @@ internal static int ExportDocument(
return DwgExitCodes.Usage;
}

var sceneOptions = unit is null ? null : new DwgSceneOptions { LengthUnit = unit };
var sceneOptions = SceneOptionsFor(unit);

if (Path.GetExtension(target).Equals(".obj", StringComparison.OrdinalIgnoreCase))
{
Expand Down Expand Up @@ -466,7 +472,7 @@ private static int Scene(string[] args, TextWriter output, TextWriter error)
{
if (i + 1 >= args.Length)
{
error.WriteLine("error: --unit needs a value (mm, cm, m, ft or in).");
error.WriteLine("error: --unit needs a value (mm, cm, m, ft, in or auto).");
return DwgExitCodes.Usage;
}

Expand All @@ -493,19 +499,13 @@ private static int Scene(string[] args, TextWriter output, TextWriter error)
return DwgExitCodes.Usage;
}

var options = new DwgSceneOptions();
if (unit is not null)
if (unit is not null && !IsAutoUnit(unit) && !DwgSceneReader.IsSupportedUnit(unit))
{
if (!DwgSceneReader.IsSupportedUnit(unit))
{
error.WriteLine($"error: unknown length unit '{unit}'. Use mm, cm, m, ft or in.");
return DwgExitCodes.Usage;
}

options.LengthUnit = unit;
error.WriteLine($"error: unknown length unit '{unit}'. Use mm, cm, m, ft, in or auto.");
return DwgExitCodes.Usage;
}

var result = DwgSceneReader.Read(positional[0], options);
var result = DwgSceneReader.Read(positional[0], SceneOptionsFor(unit));
AtomicOutput.Write(positional[1], stream => SceneJson.Write(result.Document, stream));
output.WriteLine(
$"{result.Document.Title}: {Count(result.ElementCount)} elements ({Count(result.ElementsWithGeometry)} with geometry) -> {positional[1]}");
Expand All @@ -522,6 +522,12 @@ private static int Scene(string[] args, TextWriter output, TextWriter error)
return DwgExitCodes.Ok;
}

private static bool IsAutoUnit(string? unit) => string.Equals(unit, "auto", StringComparison.OrdinalIgnoreCase);

private static DwgSceneOptions SceneOptionsFor(string? unit) => IsAutoUnit(unit)
? new DwgSceneOptions { UseDrawingUnits = true }
: new DwgSceneOptions { LengthUnit = unit ?? "m" };

private static int Preview(string[] args, TextWriter output, TextWriter error)
{
if (args.Length != 3)
Expand Down
13 changes: 10 additions & 3 deletions src/DwgIO.Scene.Adapter/DwgSceneOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,19 @@ public sealed class DwgSceneOptions
/// <summary>
/// Length unit of the drawing's coordinates and the scale the conversion applies, as one value:
/// <c>mm</c>, <c>cm</c>, <c>m</c> (the default, one drawing unit = one metre), <c>ft</c> or <c>in</c>.
/// 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 <see cref="IOScene.SceneModel.SourceLengthUnit"/>
/// and reports it in <see cref="DwgSceneResult.UnitAssumed"/>.
/// Used when <see cref="UseDrawingUnits"/> is <see langword="false"/>, or as the fallback when
/// <c>$INSUNITS</c> is unitless or not mapped to a scene unit. The scene records the choice in
/// <see cref="IOScene.SceneModel.SourceLengthUnit"/> and reports it in <see cref="DwgSceneResult.UnitAssumed"/>.
/// </summary>
public string LengthUnit { get; set; } = "m";

/// <summary>
/// When <see langword="true"/>, prefers <c>$INSUNITS</c> from <see cref="DwgDocument.HeaderVariables"/>
/// whenever it maps to a supported scene unit (<c>mm</c>, <c>cm</c>, <c>m</c>, <c>ft</c>, or <c>in</c>),
/// and sets <see cref="DwgSceneResult.UnitAssumed"/> to <see langword="false"/>. Defaults to <see langword="false"/>.
/// </summary>
public bool UseDrawingUnits { get; set; }

/// <summary>
/// Key of the scene model: stable, unique and non-empty, written to <see cref="IOScene.SceneModel.Key"/>. The
/// default is the source file name without directory. A key must be given when a document converted from memory
Expand Down
18 changes: 14 additions & 4 deletions src/DwgIO.Scene.Adapter/DwgSceneReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,17 @@ public static DwgSceneResult Read(DwgDocument document, DwgSceneOptions options)

private static DwgSceneResult Convert(DwgDocument document, string key, string? path, DwgSceneOptions options)
{
double metresPerUnit = MetresPerUnit(options.LengthUnit);
string effectiveUnit = options.LengthUnit;
bool unitAssumed = true;
if (options.UseDrawingUnits &&
document.HeaderVariables is { } header &&
header.TryGetSceneUnit(out string headerUnit))
{
effectiveUnit = headerUnit;
unitAssumed = false;
}

double metresPerUnit = MetresPerUnit(effectiveUnit);
var scene = new SceneDocument { Title = key };
var diagnostics = new List<SceneDiagnostic>();

Expand All @@ -107,7 +117,7 @@ private static DwgSceneResult Convert(DwgDocument document, string key, string?
Path = path,
SourceFormat = "dwg",
Producer = Producer,
SourceLengthUnit = options.LengthUnit,
SourceLengthUnit = effectiveUnit,
Application = document.AppInfo is { Name.Length: > 0 } appInfo ? appInfo.Name : null,
CreatedAt = document.SummaryInfo?.CreatedUtc?.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture),
});
Expand Down Expand Up @@ -220,9 +230,9 @@ private static DwgSceneResult Convert(DwgDocument document, string key, string?
ElementCount = elementCount,
ElementsWithGeometry = elementsWithGeometry,
EntitiesWithoutGeometry = withoutGeometry.Values.Sum(),
LengthUnit = options.LengthUnit,
LengthUnit = effectiveUnit,
MetresPerUnit = metresPerUnit,
UnitAssumed = true,
UnitAssumed = unitAssumed,
};
}

Expand Down
1 change: 1 addition & 0 deletions src/DwgIO.Scene/Compatibility/DwgSceneExport.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ private static DwgSceneOptions OptionsFor(string path, DwgSceneOptions? options)
return new DwgSceneOptions
{
LengthUnit = options?.LengthUnit ?? "m",
UseDrawingUnits = options?.UseDrawingUnits ?? false,
ModelKey = Path.GetFileName(path),
ReadProgress = options?.ReadProgress,
};
Expand Down
1 change: 1 addition & 0 deletions src/DwgIO.Scene/Compatibility/DwgViewerExport.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ private static DwgSceneOptions ViewerOptionsFor(DwgDocument document, string pat
return new DwgSceneOptions
{
LengthUnit = options?.LengthUnit ?? "m",
UseDrawingUnits = options?.UseDrawingUnits ?? false,
ModelKey = Path.GetFileName(path),
};
}
Expand Down
Loading
Loading