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
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "dwg-previewer",
"displayName": "AutoCAD DWG & DXF Previewer",
"description": "View AutoCAD DWG and DXF drawings inside VS Code — no AutoCAD needed. Open .dwg and .dxf files instantly with pan, zoom, layer control and SVG/PNG export.",
"version": "1.4.0",
"version": "1.4.1",
"publisher": "bumkom",
"license": "GPL-3.0-or-later",
"icon": "icon.png",
Expand Down
2 changes: 1 addition & 1 deletion src/ai/drawingStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import type { DiskCache } from './diskCache';
export type { DrawingKey };

/** Bump whenever parser output changes, so stale disk caches are ignored. */
export const CACHE_FORMAT = 3;
export const CACHE_FORMAT = 4;

export interface StoredDrawing {
key: DrawingKey;
Expand Down
49 changes: 47 additions & 2 deletions src/dwg/workerClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@ const WORKER_HEAP_MB = 3072;
*/
const JOB_TIMEOUT_MS = 300_000;

/**
* How long the worker may sit with no job before it is shut down. Its WASM heap
* (LibreDWG, ODA's output) stays allocated for as long as the thread lives, so an
* idle worker would hold that memory until VS Code closes. Restarting costs one
* WASM load, under a second, so this only needs to cover opening several drawings
* in a row.
*/
const IDLE_MS = 120_000;

interface Job {
request: WorkerRequest;
resolve: (parsed: ParsedDxf) => void;
Expand All @@ -28,27 +37,38 @@ interface Job {
export interface DrawingWorkerOptions {
/** Overrides JOB_TIMEOUT_MS. */
timeoutMs?: number;
/** Overrides IDLE_MS. */
idleMs?: number;
}

/**
* Runs drawing jobs on one long-lived worker thread, so the WASM converters
* load once. If the worker dies — out of memory, a crash in WASM — its jobs
* fail with a readable message and the next job starts a fresh worker. A job
* that runs too long fails alone: the worker is replaced and the jobs queued
* behind it are sent to the new one.
* behind it are sent to the new one. A worker left idle for IDLE_MS is shut
* down to give its memory back; the next job starts a new one.
*/
export class DrawingWorker {
private worker: Worker | null = null;
private readonly jobs = new Map<number, Job>();
private nextId = 1;
private readonly timeoutMs: number;
private readonly idleMs: number;
private idleTimer?: ReturnType<typeof setTimeout>;

constructor(
private readonly scriptPath: string,
private readonly log: (msg: string) => void = () => {},
options: DrawingWorkerOptions = {}
) {
this.timeoutMs = options.timeoutMs ?? JOB_TIMEOUT_MS;
this.idleMs = options.idleMs ?? IDLE_MS;
}

/** Whether a worker thread is alive (for tests and diagnostics). */
get running(): boolean {
return this.worker !== null;
}

run(bytes: Uint8Array, filePath: string, converterPath: string, progress: (stage: Stage) => void): Promise<ParsedDxf> {
Expand All @@ -61,13 +81,15 @@ export class DrawingWorker {
}

async dispose(): Promise<void> {
this.cancelIdle();
const worker = this.worker;
this.worker = null;
this.failAll(new Error('The drawing worker was shut down.'));
if (worker) await worker.terminate();
}

private send(request: WorkerRequest): void {
this.cancelIdle();
const worker = this.ensureWorker();
// Keep the process alive while a job is out; an idle worker must not.
worker.ref();
Expand Down Expand Up @@ -154,7 +176,30 @@ export class DrawingWorker {
private finish(id: number, job: Job): void {
if (job.timer) clearTimeout(job.timer);
this.jobs.delete(id);
if (this.jobs.size === 0) this.worker?.unref();
if (this.jobs.size === 0 && this.worker) {
this.worker.unref();
this.scheduleIdle();
}
}

private scheduleIdle(): void {
this.cancelIdle();
this.idleTimer = setTimeout(() => {
this.idleTimer = undefined;
// A job sent since then cancelled this timer; check anyway, a busy worker is never released.
if (this.jobs.size > 0 || !this.worker) return;
const idle = this.worker;
// Cleared first, so the exit it reports is ignored and the next job starts a new worker.
this.worker = null;
this.log(`Drawing worker idle for ${this.idleMs} ms; shutting it down to free its memory`);
void idle.terminate();
}, this.idleMs);
this.idleTimer.unref();
}

private cancelIdle(): void {
if (this.idleTimer) clearTimeout(this.idleTimer);
this.idleTimer = undefined;
}

private failAll(err: Error): void {
Expand Down
72 changes: 34 additions & 38 deletions src/dxf/hatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -229,13 +229,8 @@ function parseEdge(edgeType: number, body: Pair[]): Point2D[] {
const cy = at(20);
const radius = at(40);
if (cx === undefined || cy === undefined || radius === undefined) return [];
return sampleArc(
{ x: cx, y: cy },
radius,
((at(50) ?? 0) * Math.PI) / 180,
((at(51) ?? 360) * Math.PI) / 180,
at(73) !== 0
);
const { start, sweep } = edgeSweep(at(50) ?? 0, at(51) ?? 360, at(73) !== 0);
return sampleArc({ x: cx, y: cy }, radius, start, sweep);
}
case 3: {
// Elliptic arc: centre (10,20), major axis vector (11,21), ratio 40.
Expand All @@ -245,14 +240,8 @@ function parseEdge(edgeType: number, body: Pair[]): Point2D[] {
const my = at(21);
const ratio = at(40) ?? 1;
if ([cx, cy, mx, my].some((n) => n === undefined)) return [];
return sampleEllipse(
{ x: cx!, y: cy! },
{ x: mx!, y: my! },
ratio,
((at(50) ?? 0) * Math.PI) / 180,
((at(51) ?? 360) * Math.PI) / 180,
at(73) !== 0
);
const { start, sweep } = edgeSweep(at(50) ?? 0, at(51) ?? 360, at(73) !== 0, ratio);
return sampleEllipse({ x: cx!, y: cy! }, { x: mx!, y: my! }, ratio, start, sweep);
}
case 4: {
// Spline: degree 94, knots 40, control points 10/20.
Expand All @@ -269,20 +258,41 @@ function parseEdge(edgeType: number, body: Pair[]): Point2D[] {
}
}

function sampleArc(
center: Point2D,
radius: number,
startAngle: number,
endAngle: number,
counterClockwise: boolean
): Point2D[] {
let sweep = endAngle - startAngle;
/**
* Where a boundary arc starts and how far it turns, in radians (negative =
* clockwise). DXF stores a clockwise edge (73 = 0) with its angles mirrored:
* 0..120 clockwise runs from 0° to -120°, not the long way round from 0° to
* 120°. An elliptic edge's angles are geometric (the direction from the
* centre), so with a `ratio` they are turned into ellipse parameters.
*/
export function edgeSweep(
startDeg: number,
endDeg: number,
counterClockwise: boolean,
ratio?: number
): { start: number; sweep: number } {
const span = endDeg - startDeg;
const fullTurn = span !== 0 && Math.abs(span) % 360 === 0;
const sign = counterClockwise ? 1 : -1;
const toAngle = (deg: number) => {
const a = (sign * deg * Math.PI) / 180;
// On an ellipse, the parameter whose point lies in direction a from the centre
return ratio ? Math.atan2(Math.sin(a) / ratio, Math.cos(a)) : a;
};
const start = toAngle(startDeg);
if (fullTurn) return { start, sweep: sign * Math.PI * 2 };
let sweep = toAngle(endDeg) - start;
if (counterClockwise) {
while (sweep <= 0) sweep += Math.PI * 2;
while (sweep > Math.PI * 2) sweep -= Math.PI * 2;
} else {
while (sweep >= 0) sweep -= Math.PI * 2;
while (sweep < -Math.PI * 2) sweep += Math.PI * 2;
}
return { start, sweep };
}

function sampleArc(center: Point2D, radius: number, startAngle: number, sweep: number): Point2D[] {
const segments = Math.max(
2,
Math.ceil((Math.abs(sweep) / (Math.PI * 2)) * ARC_SEGMENTS_PER_TURN)
Expand All @@ -298,21 +308,7 @@ function sampleArc(
return points;
}

function sampleEllipse(
center: Point2D,
major: Point2D,
ratio: number,
startAngle: number,
endAngle: number,
counterClockwise: boolean
): Point2D[] {
let sweep = endAngle - startAngle;
if (counterClockwise) {
while (sweep <= 0) sweep += Math.PI * 2;
} else {
while (sweep >= 0) sweep -= Math.PI * 2;
}

function sampleEllipse(center: Point2D, major: Point2D, ratio: number, startAngle: number, sweep: number): Point2D[] {
const segments = Math.max(
4,
Math.ceil((Math.abs(sweep) / (Math.PI * 2)) * ARC_SEGMENTS_PER_TURN)
Expand Down
4 changes: 4 additions & 0 deletions src/dxf/parseDxf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,10 @@ function parseAttrib(
const code = lines[i].trim();
const value = lines[i + 1].trim();
if (code === '0') break;
// A multiline attribute ends with an Xrecord and an embedded MTEXT object that reuse
// the same group codes (10/20/40/1/8); they are not this attribute's fields. R12
// attributes have neither marker, so they still read to the end.
if (code === '101' || (code === '100' && value === 'AcDbXrecord')) break;

switch (code) {
case '8': layer = value; break;
Expand Down
79 changes: 79 additions & 0 deletions test/hatch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,3 +203,82 @@ test('a curved boundary is flattened into a polygon', () => {
assert.ok(Number.isFinite(point.x) && Number.isFinite(point.y));
}
});

/** One hatch whose single loop is the given edges (path type 0: edge-defined). */
function edgeHatch(...edges: string[][]): string {
return dxf(
'0', 'SECTION',
'2', 'ENTITIES',
'0', 'HATCH',
'8', '0',
'2', 'SOLID',
'70', '1',
'91', '1',
'92', '0',
'93', String(edges.length),
...edges.flat(),
'97', '0',
'0', 'ENDSEC'
);
}

const near = (actual: number, expected: number, label: string) =>
assert.ok(Math.abs(actual - expected) < 1e-6, `${label}: expected ${expected}, got ${actual}`);

/** Signed angle swept along a sampled arc around the origin, in degrees. */
function sweptDegrees(points: { x: number; y: number }[]): number {
let total = 0;
for (let i = 1; i < points.length; i++) {
const a = Math.atan2(points[i - 1].y, points[i - 1].x);
const b = Math.atan2(points[i].y, points[i].x);
let d = b - a;
while (d > Math.PI) d -= 2 * Math.PI;
while (d < -Math.PI) d += 2 * Math.PI;
total += d;
}
return (total * 180) / Math.PI;
}

test('a clockwise circular edge sweeps the arc its angles describe, not the rest of the circle (issue #4)', () => {
// DXF stores a clockwise edge's angles mirrored: 0..120 clockwise runs from 0° to -120°
const [hatch] = scanHatches(edgeHatch(['72', '2', '10', '0', '20', '0', '40', '10', '50', '0', '51', '120', '73', '0']));
const loop = hatch.loops[0];
near(sweptDegrees(loop), -120, 'sweep');
near(loop[0].x, 10, 'start x');
near(loop[0].y, 0, 'start y');
near(loop[loop.length - 1].x, 10 * Math.cos((-120 * Math.PI) / 180), 'end x');
near(loop[loop.length - 1].y, 10 * Math.sin((-120 * Math.PI) / 180), 'end y');
});

test('a counter-clockwise circular edge is unchanged', () => {
const [hatch] = scanHatches(edgeHatch(['72', '2', '10', '0', '20', '0', '40', '10', '50', '0', '51', '120', '73', '1']));
near(sweptDegrees(hatch.loops[0]), 120, 'sweep');
});

test('a full clockwise circle edge still makes a whole turn', () => {
const [hatch] = scanHatches(edgeHatch(['72', '2', '10', '0', '20', '0', '40', '10', '50', '0', '51', '360', '73', '0']));
near(Math.abs(sweptDegrees(hatch.loops[0])), 360, 'sweep');
});

test('a clockwise elliptic edge stays in the quadrant its angles describe (issue #4)', () => {
const [hatch] = scanHatches(
edgeHatch(['72', '3', '10', '0', '20', '0', '11', '10', '21', '0', '40', '0.5', '50', '0', '51', '90', '73', '0'])
);
const loop = hatch.loops[0];
near(loop[0].x, 10, 'start x');
near(loop[0].y, 0, 'start y');
near(loop[loop.length - 1].x, 0, 'end x');
near(loop[loop.length - 1].y, -5, 'end y');
assert.ok(loop.every((p) => p.x >= -1e-9 && p.y <= 1e-9), 'every point in the lower-right quadrant');
});

test('elliptic edge angles are geometric angles, turned into ellipse parameters', () => {
// 45° on an ellipse with axes 10 and 5 is where the ray at 45° meets it: x = y = 10*5/sqrt(10²+5²)
const [hatch] = scanHatches(
edgeHatch(['72', '3', '10', '0', '20', '0', '11', '10', '21', '0', '40', '0.5', '50', '0', '51', '45', '73', '1'])
);
const end = hatch.loops[0][hatch.loops[0].length - 1];
const r = (10 * 5) / Math.sqrt(10 * 10 + 5 * 5);
near(end.x, r, 'end x');
near(end.y, r, 'end y');
});
39 changes: 39 additions & 0 deletions test/parse-fixes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,45 @@ test('an invisible attribute is not drawn', () => {
assert.deepEqual(modelEntities(text).filter((e) => e.type === 'TEXT').map((e) => (e as TextEntity).text), ['SHOWN']);
});

test('an attribute keeps its own fields when an Xrecord and an embedded MTEXT object follow (issue #4)', () => {
const text = withLayers(
[layer('0', 7), layer('TEST', 7)],
...entities(
'0', 'INSERT', '8', '0', '66', '1', '2', 'NOPE', '10', '0', '20', '0', '30', '0',
'0', 'ATTRIB', '8', 'TEST',
'100', 'AcDbText', '10', '5', '20', '7', '30', '0', '40', '2.5', '1', 'LABEL',
'100', 'AcDbAttribute', '2', 'NAME', '70', '0',
'100', 'AcDbXrecord', '280', '1', '40', '1e307',
'101', 'Embedded Object', '10', '1e307', '20', '-1e307', '40', '1e307', '1', 'WRONG', '8', 'OTHER',
'0', 'SEQEND', '8', '0'
)
);

const attribs = modelEntities(text).filter((e): e is TextEntity => e.type === 'TEXT');
assert.equal(attribs.length, 1);
assert.equal(attribs[0].text, 'LABEL');
assert.deepEqual(attribs[0].position, { x: 5, y: 7 });
assert.equal(attribs[0].height, 2.5);
assert.equal(attribs[0].layer, 'TEST');
});

test('an R12 attribute without subclass markers still reads every field', () => {
const text = withLayers(
[layer('0', 7), layer('TEST', 7)],
...entities(
'0', 'INSERT', '8', '0', '66', '1', '2', 'NOPE', '10', '0', '20', '0', '30', '0',
'0', 'ATTRIB', '8', 'TEST', '10', '5', '20', '7', '30', '0', '40', '2.5', '1', 'LABEL', '2', 'NAME', '70', '0',
'0', 'SEQEND', '8', '0'
)
);

const [attrib] = modelEntities(text).filter((e): e is TextEntity => e.type === 'TEXT');
assert.equal(attrib.text, 'LABEL');
assert.deepEqual(attrib.position, { x: 5, y: 7 });
assert.equal(attrib.height, 2.5);
assert.equal(attrib.layer, 'TEST');
});

// ── OCS / extrusion ───────────────────────────────────────────────────────

test('a mirrored ARC (extrusion 0,0,-1) is drawn on the mirrored side', () => {
Expand Down
Loading
Loading