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
- `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`,
`ReleaseSectionBuffers`, `Progress` (`IProgress<DwgReadProgress>`), and `DiagnosticOutput` (`TextWriter?`).
- `DwgDocument`: `SourcePath`, `OpenAsync` (path and stream overloads), `ReleaseSectionBuffers()`, `SaveJson` and `ToJson`.
Expand Down
5 changes: 3 additions & 2 deletions docs/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,9 @@ change in any release and is visible only to the test project through `Internals
| `DwgFileDepList`, `DwgFileDependency` | External files the drawing refers to (fonts, images, references). |
| `DwgPreview`, `DwgPreviewImageKind` | The embedded thumbnail and its format (BMP, PNG or WMF). `DwgDocument.PreviewReadError` provides the reason when the thumbnail section could not be read. |
| `DwgHandleMap`, `DwgHandleMapEntry` | The handle to offset index of the object stream; `Find(handle)` looks up one object. |
| `DwgObjectInfo`, `DwgHandle` | One record of the object stream: offset, size, type code (`TypeName` names it) and handle. |
| `DwgEntity`, `DwgEntityKind` | A decoded entity with its handle, type, colour, linetype scale, `IsModelSpace` flag and the `Geometry` decoded for LINE, CIRCLE, ARC and POINT. |
| `DwgObjectInfo`, `DwgHandle` | One record of the object stream: offset, size, type code (`TypeName` resolves fixed names and `AcDb:Classes` names) and handle. |
| `DwgClassInfo` | One class definition from `AcDb:Classes` (codes 500+): `ClassNumber`, `AppName`, `CppClassName`, `DxfName`, `ItemClassId`, `IsEntity`, `InstanceCount`. |
| `DwgEntity`, `DwgEntityKind` | A decoded entity with its handle, type, colour (`ColorIndex` and optional `TrueColorRgb`), linetype scale, `IsModelSpace` flag and decoded `Geometry` for LINE, CIRCLE, ARC, POINT, LWPOLYLINE, ELLIPSE, SOLID/TRACE, 3DFACE, RAY and XLINE. |
| `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. |
Expand Down
2 changes: 1 addition & 1 deletion src/DwgIO.Cli/DwgIO.Cli.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

<ItemGroup>
<PackageReference Include="IOViewer" />
<Compile Include="..\Shared\AtomicOutput.cs;..\Shared\ArcAngles.cs;..\Shared\DwgAciPalette.cs"
<Compile Include="..\Shared\AtomicOutput.cs;..\Shared\ArcAngles.cs;..\Shared\DwgAciPalette.cs;..\Shared\EllipseAxes.cs"
Link="Shared\%(Filename)%(Extension)" />
<InternalsVisibleTo Include="DwgIO.Tests" />
</ItemGroup>
Expand Down
218 changes: 213 additions & 5 deletions src/DwgIO.Cli/Export/DwgCadHtmlViewer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ private static string BuildPayloadJson(DwgDocument document, DwgViewerOptions op
continue;
}

if (!TryExpandBounds(entity, ref minX, ref minY, ref maxX, ref maxY))
if (!TryExpandBounds(entity, ref minX, ref minY, ref maxX, ref maxY, out var ellipseMinor))
{
continue;
}
Expand All @@ -100,10 +100,22 @@ private static string BuildPayloadJson(DwgDocument document, DwgViewerOptions op
w.WriteString("type", entity.TypeName);
w.WriteString("kind", entity.Kind.ToString().ToLowerInvariant());
w.WriteNumber("colorIndex", entity.ColorIndex);
w.WriteBoolean("isAdaptiveColor", IsAdaptiveColor(entity.ColorIndex));
w.WriteString("rgb", FormatFixedRgb(entity.ColorIndex));
bool adaptive = entity.TrueColorRgb is null && IsAdaptiveColor(entity.ColorIndex);
w.WriteBoolean("isAdaptiveColor", adaptive);
w.WriteString("rgb", FormatFixedRgb(entity.ColorIndex, entity.TrueColorRgb));
if (entity.TrueColorRgb is { } trueColor)
{
w.WriteString("trueColorRgb", string.Create(CultureInfo.InvariantCulture, $"#{trueColor:X6}"));
}

w.WriteNumber("lineTypeScale", double.IsFinite(entity.LineTypeScale) ? Math.Round(entity.LineTypeScale, 6) : 1.0);
w.WriteBoolean("modelSpace", entity.IsModelSpace);
if (ellipseMinor is { } minor)
{
w.WriteNumber("ellipseMinorX", minor.X);
w.WriteNumber("ellipseMinorY", minor.Y);
}

w.WriteStartArray("geom");
foreach (double v in entity.Geometry)
{
Expand Down Expand Up @@ -145,8 +157,13 @@ private static string BuildPayloadJson(DwgDocument document, DwgViewerOptions op

private static bool IsAdaptiveColor(int colorIndex) => colorIndex is <= 0 or 7 or >= 256;

private static string? FormatFixedRgb(int colorIndex)
private static string? FormatFixedRgb(int colorIndex, uint? trueColorRgb)
{
if (trueColorRgb is { } rgb)
{
return string.Create(CultureInfo.InvariantCulture, $"#{rgb:X6}");
}

if (IsAdaptiveColor(colorIndex))
{
return null;
Expand All @@ -156,8 +173,11 @@ private static string BuildPayloadJson(DwgDocument document, DwgViewerOptions op
return string.Create(CultureInfo.InvariantCulture, $"#{r:X2}{g:X2}{b:X2}");
}

private static bool TryExpandBounds(DwgEntity entity, ref double minX, ref double minY, ref double maxX, ref double maxY)
private static bool TryExpandBounds(
DwgEntity entity, ref double minX, ref double minY, ref double maxX, ref double maxY,
out (double X, double Y, double Z)? ellipseMinor)
{
ellipseMinor = null;
switch (entity.Kind, entity.Geometry)
{
case (DwgEntityKind.Line, [var x1, var y1, _, var x2, var y2, _]):
Expand Down Expand Up @@ -185,6 +205,36 @@ private static bool TryExpandBounds(DwgEntity entity, ref double minX, ref doubl
case (DwgEntityKind.Point, [var x, var y, _]):
Expand(x, y, ref minX, ref minY, ref maxX, ref maxY);
return true;
case (DwgEntityKind.Polyline, { Length: >= 5 } g):
int count = (g.Length - 2) / 3;
for (int i = 0; i < count; i++)
{
Expand(g[2 + i * 3], g[2 + i * 3 + 1], ref minX, ref minY, ref maxX, ref maxY);
}

return count > 0;
case (DwgEntityKind.Ellipse, { Length: 12 } g) when EllipseAxes.TryGetMinor(g, out var minor):
ellipseMinor = minor;
double centerX = g[0], centerY = g[1], mx = g[3], my = g[4];
var (eStart, eSpan) = ArcAngles.Normalize(g[7], g[8]);
for (int i = 0; i <= 32; i++)
{
double a = eStart + eSpan * i / 32;
Expand(centerX + mx * Math.Cos(a) + minor.X * Math.Sin(a), centerY + my * Math.Cos(a) + minor.Y * Math.Sin(a),
ref minX, ref minY, ref maxX, ref maxY);
}

return true;
case (DwgEntityKind.Solid or DwgEntityKind.Face3d, { Length: 12 } g):
for (int i = 0; i < 4; i++)
{
Expand(g[i * 3], g[i * 3 + 1], ref minX, ref minY, ref maxX, ref maxY);
}

return true;
case (DwgEntityKind.Ray or DwgEntityKind.XLine, [var rx, var ry, _, _, _, _]):
Expand(rx, ry, ref minX, ref minY, ref maxX, ref maxY);
return true;
default:
return false;
}
Expand Down Expand Up @@ -735,6 +785,30 @@ function entityBounds(e) {
const r = Math.max(g[3], 1);
return { minX: g[0] - r, minY: g[1] - r, maxX: g[0] + r, maxY: g[1] + r };
}
if (e.kind === 'polyline') {
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
const n = Math.floor((g.length - 2) / 3);
for (let i = 0; i < n; i++) {
minX = Math.min(minX, g[2 + i * 3]);
minY = Math.min(minY, g[2 + i * 3 + 1]);
maxX = Math.max(maxX, g[2 + i * 3]);
maxY = Math.max(maxY, g[2 + i * 3 + 1]);
}
return { minX, minY, maxX, maxY };
}
if (e.kind === 'ellipse') {
const rx = Math.hypot(g[3], e.ellipseMinorX);
const ry = Math.hypot(g[4], e.ellipseMinorY);
return { minX: g[0] - rx, minY: g[1] - ry, maxX: g[0] + rx, maxY: g[1] + ry };
}
if (e.kind === 'solid' || e.kind === 'face3d') {
return {
minX: Math.min(g[0], g[3], g[6], g[9]),
minY: Math.min(g[1], g[4], g[7], g[10]),
maxX: Math.max(g[0], g[3], g[6], g[9]),
maxY: Math.max(g[1], g[4], g[7], g[10]),
};
}
return { minX: g[0] - 1, minY: g[1] - 1, maxX: g[0] + 1, maxY: g[1] + 1 };
}

Expand Down Expand Up @@ -910,6 +984,83 @@ function drawEntity(entity, w, h, overrideColor, lineWidth) {
} else if (entity.kind === 'point') {
const [px, py] = worldToScreen(g[0], g[1], w, h);
drawPoint(px, py, color, !!overrideColor);
} else if (entity.kind === 'polyline') {
const count = Math.floor((g.length - 2) / 3);
if (count < 2) return;
const closed = g[0] !== 0;
const segs = closed ? count : count - 1;
ctx.beginPath();
const [sx0, sy0] = worldToScreen(g[2], g[3], w, h);
ctx.moveTo(sx0, sy0);
for (let i = 0; i < segs; i++) {
const next = (i + 1) % count;
const x1 = g[2 + i * 3], y1 = g[2 + i * 3 + 1], bulge = g[2 + i * 3 + 2];
const x2 = g[2 + next * 3], y2 = g[2 + next * 3 + 1];
if (Math.abs(bulge) < 1e-12) {
const [sx, sy] = worldToScreen(x2, y2, w, h);
ctx.lineTo(sx, sy);
} else {
const dx = x2 - x1, dy = y2 - y1;
const chord = Math.hypot(dx, dy);
if (chord <= 1e-12) continue;
const radius = chord * (1 + bulge * bulge) / (4 * Math.abs(bulge));
const hOff = chord * (1 - bulge * bulge) / (4 * bulge);
const cx = (x1 + x2) * 0.5 - hOff * (dy / chord);
const cy = (y1 + y2) * 0.5 + hOff * (dx / chord);
const [scx, scy] = worldToScreen(cx, cy, w, h);
const a1 = Math.atan2(y1 - cy, x1 - cx);
const a2 = Math.atan2(y2 - cy, x2 - cx);
ctx.arc(scx, scy, radius * cam.scale, -a1, -a2, bulge > 0);
}
}
ctx.stroke();
} else if (entity.kind === 'ellipse') {
const cx = g[0], cy = g[1], mx = g[3], my = g[4];
const nx = entity.ellipseMinorX, ny = entity.ellipseMinorY;
const [start, span] = arcSpan(g[7], g[8]);
const steps = Math.max(16, Math.min(256, Math.ceil(span / (5 * Math.PI / 180))));
ctx.beginPath();
for (let i = 0; i <= steps; i++) {
const a = start + (span * i) / steps;
const [sx, sy] = worldToScreen(cx + mx * Math.cos(a) + nx * Math.sin(a), cy + my * Math.cos(a) + ny * Math.sin(a), w, h);
if (i === 0) ctx.moveTo(sx, sy);
else ctx.lineTo(sx, sy);
}
ctx.stroke();
} else if (entity.kind === 'solid' || entity.kind === 'face3d') {
const order = entity.kind === 'solid' ? [0, 3, 9, 6] : [0, 3, 6, 9];
ctx.beginPath();
for (let i = 0; i < 4; i++) {
const idx = order[i];
const [sx, sy] = worldToScreen(g[idx], g[idx + 1], w, h);
if (i === 0) ctx.moveTo(sx, sy);
else ctx.lineTo(sx, sy);
}
ctx.closePath();
if (entity.kind === 'solid') {
ctx.save();
ctx.globalAlpha = 0.25;
ctx.fillStyle = color;
ctx.fill();
ctx.restore();
}
ctx.stroke();
} else if (entity.kind === 'ray' || entity.kind === 'xline') {
const len = Math.max(w, h) / cam.scale + Math.hypot(cam.x - g[0], cam.y - g[1]) + 100;
const dirLen = Math.hypot(g[3], g[4]);
if (dirLen <= 1e-12) return;
const ux = g[3] / dirLen, uy = g[4] / dirLen;
const [sx1, sy1] = entity.kind === 'ray'
? worldToScreen(g[0], g[1], w, h)
: worldToScreen(g[0] - ux * len, g[1] - uy * len, w, h);
const [sx2, sy2] = worldToScreen(g[0] + ux * len, g[1] + uy * len, w, h);
ctx.save();
ctx.setLineDash([6, 4]);
ctx.beginPath();
ctx.moveTo(sx1, sy1);
ctx.lineTo(sx2, sy2);
ctx.stroke();
ctx.restore();
}
}

Expand Down Expand Up @@ -990,6 +1141,45 @@ function hitTest(wx, wy) {
}
} else if (e.kind === 'point') {
d = Math.hypot(wx - g[0], wy - g[1]);
} else if (e.kind === 'polyline') {
const count = Math.floor((g.length - 2) / 3);
const closed = g[0] !== 0;
const segs = closed ? count : count - 1;
for (let k = 0; k < segs; k++) {
const next = (k + 1) % count;
d = Math.min(d, distanceToSegment(wx, wy, g[2 + k * 3], g[2 + k * 3 + 1], g[2 + next * 3], g[2 + next * 3 + 1]));
}
} else if (e.kind === 'ellipse') {
const cx = g[0], cy = g[1], mx = g[3], my = g[4];
const nx = e.ellipseMinorX, ny = e.ellipseMinorY;
const [start, span] = arcSpan(g[7], g[8]);
let prevX = cx + mx * Math.cos(start) + nx * Math.sin(start);
let prevY = cy + my * Math.cos(start) + ny * Math.sin(start);
for (let s = 1; s <= 32; s++) {
const a = start + (span * s) / 32;
const curX = cx + mx * Math.cos(a) + nx * Math.sin(a);
const curY = cy + my * Math.cos(a) + ny * Math.sin(a);
d = Math.min(d, distanceToSegment(wx, wy, prevX, prevY, curX, curY));
prevX = curX;
prevY = curY;
}
} else if (e.kind === 'solid' || e.kind === 'face3d') {
const order = e.kind === 'solid' ? [0, 3, 9, 6] : [0, 3, 6, 9];
for (let k = 0; k < 4; k++) {
const a = order[k], b = order[(k + 1) % 4];
d = Math.min(d, distanceToSegment(wx, wy, g[a], g[a + 1], g[b], g[b + 1]));
}
} else if (e.kind === 'ray' || e.kind === 'xline') {
const dirLen = Math.hypot(g[3], g[4]);
if (dirLen > 1e-12) {
const ux = g[3] / dirLen, uy = g[4] / dirLen;
const proj = (wx - g[0]) * ux + (wy - g[1]) * uy;
if (e.kind === 'xline' || proj >= 0) {
d = Math.hypot(wx - (g[0] + proj * ux), wy - (g[1] + proj * uy));
} else {
d = Math.hypot(wx - g[0], wy - g[1]);
}
}
}
if (d <= bestDist) {
bestDist = d;
Expand All @@ -1004,6 +1194,7 @@ function fmt(n) {
}

function colorLabel(e) {
if (e.trueColorRgb) return `RGB ${e.trueColorRgb}`;
if (e.colorIndex === 256) return `256 (${t('bylayer')})`;
if (e.colorIndex === 0) return `0 (${t('byblock')})`;
if (e.colorIndex === 7) return `7 (${t('white')})`;
Expand Down Expand Up @@ -1040,6 +1231,23 @@ function renderProps(e) {
rows.push([t('angles'), `${fmt(d1)}° .. ${fmt(d2)}°`]);
} else if (e.kind === 'point') {
rows.push([t('position'), `(${fmt(g[0])}, ${fmt(g[1])}, ${fmt(g[2])})`]);
} else if (e.kind === 'polyline') {
const count = Math.floor((g.length - 2) / 3);
rows.push(['Vertices', String(count)]);
rows.push(['Closed', g[0] !== 0 ? 'Yes' : 'No']);
rows.push(['Elevation', fmt(g[1])]);
} else if (e.kind === 'ellipse') {
rows.push([t('center'), `(${fmt(g[0])}, ${fmt(g[1])}, ${fmt(g[2])})`]);
rows.push(['Major Axis', `(${fmt(g[3])}, ${fmt(g[4])}, ${fmt(g[5])})`]);
rows.push(['Ratio', fmt(g[6])]);
} else if (e.kind === 'solid' || e.kind === 'face3d') {
rows.push(['P1', `(${fmt(g[0])}, ${fmt(g[1])}, ${fmt(g[2])})`]);
rows.push(['P2', `(${fmt(g[3])}, ${fmt(g[4])}, ${fmt(g[5])})`]);
rows.push(['P3', `(${fmt(g[6])}, ${fmt(g[7])}, ${fmt(g[8])})`]);
rows.push(['P4', `(${fmt(g[9])}, ${fmt(g[10])}, ${fmt(g[11])})`]);
} else if (e.kind === 'ray' || e.kind === 'xline') {
rows.push([t('position'), `(${fmt(g[0])}, ${fmt(g[1])}, ${fmt(g[2])})`]);
rows.push(['Direction', `(${fmt(g[3])}, ${fmt(g[4])}, ${fmt(g[5])})`]);
}

propsGrid.innerHTML = '';
Expand Down
10 changes: 10 additions & 0 deletions src/DwgIO.Cli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,11 @@ internal static int InspectDocument(DwgDocument doc, TextWriter output)
}
}

if (doc.Classes.Count > 0)
{
output.WriteLine($"Classes: {Count(doc.Classes.Count)}");
}

if (doc.Objects.Count > 0)
{
output.WriteLine($"Objects: {Count(doc.Objects.Count)} (handle map: {Count(doc.HandleMap?.Count ?? 0)})");
Expand Down Expand Up @@ -721,6 +726,11 @@ private static void WriteEntitiesJson(TextWriter output, IEnumerable<DwgEntity>
}

writer.WriteNumber("colorIndex", entity.ColorIndex);
if (entity.TrueColorRgb is { } trueColor)
{
writer.WriteString("trueColorRgb", $"#{trueColor:X6}");
}

writer.WriteEndObject();
}

Expand Down
2 changes: 1 addition & 1 deletion src/DwgIO.Scene.Adapter/DwgIO.Scene.Adapter.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<ItemGroup>
<ProjectReference Include="..\DwgIO\DwgIO.csproj" />
<PackageReference Include="IOScene" />
<Compile Include="..\Shared\ArcAngles.cs;..\Shared\DwgAciPalette.cs" Link="%(Filename)%(Extension)" />
<Compile Include="..\Shared\ArcAngles.cs;..\Shared\DwgAciPalette.cs;..\Shared\EllipseAxes.cs" Link="%(Filename)%(Extension)" />
</ItemGroup>

<!-- The shared pack metadata expects icon.png beside the project; the adapter ships the engine's icon. -->
Expand Down
Loading
Loading