From 120f861efd875f9e3a3e73b399fe131b83728041 Mon Sep 17 00:00:00 2001 From: inzuno Date: Sat, 5 Dec 2026 09:53:15 +0000 Subject: [PATCH] fix(gcode): cut rotated shapes where they are drawn MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The scene geometry used for cuts, fills and offset fills was imported from the object's own SVG (which already carries its full transform) and then translated so its top-left matched getBoundingRect(). That box includes the stroke and, for a rotated object, is the axis-aligned hull of the rotated box, so it is larger than the shape itself: rotated parts were cut several millimetres away from where the canvas draws them (about 7 mm for a 34 mm disc at 45°, up to 15 mm for larger parts), and unrotated ones by half the stroke width. Drop the re-alignment. Measured against Fabric's own geometry (each leaf's points through its absolute matrix), rects, ellipses, circles, polygons, curved paths, groups and nested groups now match within 0.03 mm at any angle, scale or mirror. The origin tests used a rect with Fabric's default 1 mm stroke, whose outline really is half the stroke inside left/top; they now use no stroke so the expected coordinates stay the same. Co-Authored-By: Claude Opus 5.5 --- src/gcode/job.test.ts | 5 ++- src/geometry/paperOps.test.ts | 79 +++++++++++++++++++++++++++++++++++ src/geometry/paperOps.ts | 36 ++++------------ 3 files changed, 91 insertions(+), 29 deletions(-) create mode 100644 src/geometry/paperOps.test.ts diff --git a/src/gcode/job.test.ts b/src/gcode/job.test.ts index 657ce32..6817a80 100644 --- a/src/gcode/job.test.ts +++ b/src/gcode/job.test.ts @@ -179,10 +179,11 @@ describe('buildJob images', () => { describe('buildJob device origin', () => { // A 10x10 square on a 100x80 bed: its top-left corner is (20, 10) and the - // bottom-right corner is (30, 20) in document coordinates. + // bottom-right corner is (30, 20) in document coordinates. No stroke, so + // left/top are the drawn outline itself (a stroke would push it inwards). async function planFor(origin: (typeof DEFAULT_DEVICE)['origin']) { const layer = layerWithMode('line'); - const rect = new Rect({ left: 20, top: 10, width: 10, height: 10 }); + const rect = new Rect({ left: 20, top: 10, width: 10, height: 10, strokeWidth: 0 }); rect.set('layerId', layer.id); return buildJob({ objects: [rect], diff --git a/src/geometry/paperOps.test.ts b/src/geometry/paperOps.test.ts new file mode 100644 index 0000000..69b6fa7 --- /dev/null +++ b/src/geometry/paperOps.test.ts @@ -0,0 +1,79 @@ +// @vitest-environment jsdom +import { describe, expect, it } from 'vitest'; +import { Group, Path, Rect, type FabricObject } from 'fabric'; +import { objectContours } from '@/gcode/geometry'; +import paper from 'paper'; +import { ensurePaper } from './paperSetup'; +import { objectToSceneCompoundPathData, objectToScenePathData } from './paperOps'; + +type P = { x: number; y: number }; + +function bounds(points: P[]) { + const xs = points.map((p) => p.x); + const ys = points.map((p) => p.y); + return { minX: Math.min(...xs), minY: Math.min(...ys), maxX: Math.max(...xs), maxY: Math.max(...ys) }; +} + +/** Where Fabric draws a rect's corners: its own box through its absolute matrix. */ +function drawnCorners(rect: Rect): P[] { + const m = rect.calcTransformMatrix(); + const w = rect.width / 2; + const h = rect.height / 2; + return [ + [-w, -h], + [w, -h], + [w, h], + [-w, h], + ].map(([x, y]) => ({ x: m[0] * x + m[2] * y + m[4], y: m[1] * x + m[3] * y + m[5] })); +} + +function dataBounds(data: string | null) { + ensurePaper(); + const item = new paper.CompoundPath(data ?? ''); + const b = item.bounds; + item.remove(); + return { minX: b.x, minY: b.y, maxX: b.x + b.width, maxY: b.y + b.height }; +} + +/** Within 0.005 mm: toSVG() rounds coordinates to 4 decimals before Paper reads them. */ +function expectSameBox(a: ReturnType, b: ReturnType) { + expect(a.minX).toBeCloseTo(b.minX, 2); + expect(a.minY).toBeCloseTo(b.minY, 2); + expect(a.maxX).toBeCloseTo(b.maxX, 2); + expect(a.maxY).toBeCloseTo(b.maxY, 2); +} + +describe('geometry/paperOps scene geometry', () => { + // The cut used to be re-aligned to getBoundingRect(), which includes the + // stroke and, for a rotated object, the rotated box's hull: rotated parts + // were cut millimetres away from where they are drawn. + for (const angle of [0, 30, 45, 90, 137]) { + it(`cuts a rect rotated ${angle}° where it is drawn`, () => { + const rect = new Rect({ left: 50, top: 40, width: 60, height: 20, angle, strokeWidth: 2, stroke: '#f00', fill: '' }); + const expected = bounds(drawnCorners(rect)); + expectSameBox(bounds(objectContours(rect).flatMap((c) => c.points)), expected); + expectSameBox(dataBounds(objectToSceneCompoundPathData(rect)), expected); + expectSameBox(dataBounds(objectToScenePathData(rect)), expected); + }); + } + + it('cuts a rotated, scaled group where its shapes are drawn', () => { + const inner = new Rect({ left: 0, top: 0, width: 20, height: 10, strokeWidth: 1, stroke: '#f00', fill: '' }); + const tri = new Path('M 30 0 L 50 20 L 30 25 Z', { strokeWidth: 1, stroke: '#f00', fill: '' }); + const group = new Group([inner, tri], { left: 100, top: 60, angle: 33, scaleX: 1.5, scaleY: 1.5 }); + const cut = bounds(objectContours(group as FabricObject).flatMap((c) => c.points)); + const rectBox = bounds(drawnCorners(inner)); + // The rect is entirely inside the cut's bounds and touches its extremes + // on the sides it reaches. + expect(cut.minX).toBeLessThanOrEqual(rectBox.minX + 1e-3); + expect(cut.minY).toBeLessThanOrEqual(rectBox.minY + 1e-3); + const m = tri.calcTransformMatrix(); + const off = tri.pathOffset; + const triPts = [ + [30, 0], + [50, 20], + [30, 25], + ].map(([x, y]) => ({ x: m[0] * (x - off.x) + m[2] * (y - off.y) + m[4], y: m[1] * (x - off.x) + m[3] * (y - off.y) + m[5] })); + expectSameBox(cut, bounds([...drawnCorners(inner), ...triPts])); + }); +}); diff --git a/src/geometry/paperOps.ts b/src/geometry/paperOps.ts index 03a92fc..e4b724b 100644 --- a/src/geometry/paperOps.ts +++ b/src/geometry/paperOps.ts @@ -88,24 +88,15 @@ export function objectToPathData(obj: FabricObject): string | null { } /** - * Scene-space path data. Paper normalises imported SVG coordinates to the - * origin, so we re-align the result to the source object's bounding box. + * Scene-space path data. `toSVG()` carries the object's full transform, so the + * imported geometry is already where the canvas draws it. + * + * It used to be re-aligned to `getBoundingRect()`, but that box includes the + * stroke and, for a rotated object, is the rotated box's axis-aligned hull: + * the cut drifted by up to several millimetres from what was drawn. */ export function objectToScenePathData(obj: FabricObject): string | null { - const data = objectToPathData(obj); - if (!data) return null; - try { - ensurePaper(); - const item = new paper.CompoundPath(data); - const bounds = item.bounds; - const target = obj.getBoundingRect(); - item.translate(new paper.Point(target.left - bounds.x, target.top - bounds.y)); - const out = item.pathData; - item.remove(); - return out ?? null; - } catch { - return null; - } + return objectToPathData(obj); } /** Import a Fabric object's geometry as scene-space Paper items (holes kept). */ @@ -118,10 +109,7 @@ export function objectToScenePathItems(obj: FabricObject): paper.PathItem[] { const paths: paper.PathItem[] = []; collectPaths(imported, paths); if (paths.length === 0) return []; - const bounds = imported.bounds; - const target = obj.getBoundingRect(); - const dx = target.left - bounds.x; - const dy = target.top - bounds.y; + // No re-alignment: see objectToScenePathData. const out: paper.PathItem[] = []; for (const p of paths) { p.fillColor = new paper.Color('black'); @@ -131,7 +119,6 @@ export function objectToScenePathItems(obj: FabricObject): paper.PathItem[] { p.fillRule = 'evenodd'; const cloned = p.clone({ insert: false }) as paper.PathItem; cloned.fillRule = 'evenodd'; - cloned.translate(new paper.Point(dx, dy)); out.push(cloned); } imported.remove(); @@ -156,11 +143,7 @@ export function objectToSceneCompoundPathData(obj: FabricObject): string | null collectPaths(imported, paths); if (paths.length === 0) return null; - const bounds = imported.bounds; - const target = obj.getBoundingRect(); - const dx = target.left - bounds.x; - const dy = target.top - bounds.y; - + // No re-alignment: see objectToScenePathData. const data = paths .map((p) => (p as unknown as { pathData?: string }).pathData ?? '') .filter(Boolean) @@ -169,7 +152,6 @@ export function objectToSceneCompoundPathData(obj: FabricObject): string | null const item = new paper.CompoundPath(data); item.fillRule = 'evenodd'; - item.translate(new paper.Point(dx, dy)); const out = item.pathData ?? null; item.remove(); return out;