diff --git a/TODO.md b/TODO.md index 4d5b43e..40e53c1 100644 --- a/TODO.md +++ b/TODO.md @@ -303,7 +303,11 @@ falta migrar documentos ni preferencias guardadas. - [ ] **Import/export de biblioteca de materiales** para compartir presets #### P4 — Producción y posicionamiento -- [ ] **Nesting / auto-arrange** de piezas (empaquetado para aprovechar material) +- [x] **Nesting / auto-arrange** de piezas (Arrange → Nesting…): plancha, separación, margen, rotación libre o por pasos, espejo, retal en centro/esquina/lado, búsqueda en Web Workers con vista previa en vivo (ver `docs/ARCHITECTURE.md` §4b) + - [ ] **Corte en línea común** (piezas que comparten un corte recto): previsto en `NestOptions.commonLine` y `NestResult.sharedEdges`, sin UI hasta que un motor lo soporte + - [ ] **Nesting en retales irregulares** (`NestSheet.obstacles`) y **varias planchas / cantidades** (`NestPart.quantity` ya se expande en el motor, falta la UI y la duplicación al aplicar) + - [ ] Motor alternativo **"gravedad + sacudidas"**: se registra en `src/nesting/registry.ts` implementando `NestEngine` + - [x] e2e en Electron del flujo Nesting (`e2e/nesting.spec.ts`: workers, plancha, separación y undo) - [ ] **Repeat marking** mejorado: array por filas/columnas fuera del diseño - [ ] **Contorno de máquina (machine contour)** para previsualizar el área real de trabajo diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 6b9877d..ad60f76 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -147,6 +147,48 @@ GCode + estadísticas (tiempo, distancia, bounds) --- +## 4b. Nesting (auto-arrange) + +`src/nesting/` empaqueta piezas en una plancha para dejar el mayor retal +aprovechable. El núcleo **no conoce Fabric ni la UI**: solo polígonos en mm +(Y hacia abajo). + +``` +WorkspaceController.collectNestParts ── extract.ts (Fabric → NestPart) + │ +NestingDialog ── runner.ts ── N × nest.worker.ts ── registry.ts → NestEngine.run + │ (semilla y variante distintas por worker) +WorkspaceController.applyNestResult (una sola entrada de undo) +``` + +- **Pieza** (`NestPart`): cada objeto de primer nivel (normalmente un grupo). + La capa de corte es la del contorno cerrado más grande; sus contornos + interiores son agujeros donde caben otras piezas. Los cerrados de otras capas + (grabados) y los textos se rellenan; los abiertos solo reservan su trazo. La + geometría se lee directamente de Fabric (comandos de path, puntos, rect, + elipse) con `calcTransformMatrix()`, así que coincide con lo dibujado. +- **Colocación** (`Placement`): espejo opcional (x → −x), rotación horaria + `angle` y traslación, en coordenadas de escena. `applySceneTransform` la + compone con la transformación actual del objeto. +- **Motor `grid`** (`engines/grid.ts`): rasteriza cada orientación en una + rejilla (≥ 0,2 mm, ≤ 1200 celdas por lado) de forma conservadora y dilatada + media separación, de modo que dos máscaras que no se solapan respetan siempre + la separación. Pasada voraz (piezas grandes primero, 12 orientaciones) y + después *late acceptance hill climbing* sobre orden, ángulo (paso de 5° en + rotación libre) y espejo, reanudando desde puntos de control para no + recolocar el prefijo que no cambia. +- **Retal**: el motor siempre empaqueta hacia arriba-izquierda en un marco + interno; `frame.ts` elige la isometría (simetrías/transposición) que lleva el + retal al lado o esquina pedidos. Conjugar por una isometría nunca refleja una + pieza por sí sola. +- **Otro motor**: implementar `NestEngine` y registrarlo en `registry.ts`; el + diálogo muestra el selector de motor en cuanto hay más de uno. +- **V2 prevista**: `NestOptions.commonLine` / `NestResult.sharedEdges` (corte en + línea común) y `NestSheet.obstacles` (retales irregulares). Los motores + actuales los ignoran y la UI no los muestra. + +--- + ## 5. Comunicación con la máquina ``` diff --git a/e2e/nesting.spec.ts b/e2e/nesting.spec.ts new file mode 100644 index 0000000..90d6816 --- /dev/null +++ b/e2e/nesting.spec.ts @@ -0,0 +1,138 @@ +import path from 'node:path'; +import { + test, + expect, + _electron as electron, + type ElectronApplication, + type Page, +} from '@playwright/test'; +import { createTestProfile, dismissWelcome, launchEnv, removeTestProfile } from './helpers'; + +const repoRoot = path.resolve(__dirname, '..'); + +let app: ElectronApplication; +let page: Page; +const profile = createTestProfile(); +const workers: string[] = []; + +interface Box { + left: number; + top: number; + width: number; + height: number; +} + +type Ws = { + snapshotDocument: () => { canvas: { objects: unknown[] }; layers: { id: string }[] }; + applyRecoveredDocument: (doc: unknown, path: string | null) => Promise; + selectAll: () => void; + undo: () => void; + canvas: { + getObjects: () => { width: number; height: number; calcTransformMatrix: () => number[] }[]; + discardActiveObject: () => void; + }; +}; + +/** + * Geometric boxes of every rectangle, in scene mm (getBoundingRect would add + * the on-screen stroke width). + */ +function boxes(): Promise { + return page.evaluate(() => { + const ws = (window as unknown as { __openburn: Ws }).__openburn; + ws.canvas.discardActiveObject(); + return ws.canvas.getObjects().map((o) => { + const m = o.calcTransformMatrix(); + const w = o.width / 2; + const h = o.height / 2; + const pts = [ + [-w, -h], + [w, -h], + [w, h], + [-w, h], + ].map(([x, y]) => [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]]); + const xs = pts.map((p) => p[0]); + const ys = pts.map((p) => p[1]); + const left = Math.min(...xs); + const top = Math.min(...ys); + return { left, top, width: Math.max(...xs) - left, height: Math.max(...ys) - top }; + }); + }); +} + +test.beforeAll(async () => { + app = await electron.launch({ args: [repoRoot, '--no-sandbox'], env: launchEnv(profile) }); + page = await app.firstWindow(); + page.on('worker', (w) => workers.push(w.url())); + await page.waitForLoadState('domcontentloaded'); + await dismissWelcome(page); + await page.waitForFunction(() => !!(window as unknown as { __openburn?: unknown }).__openburn); +}); + +test.afterAll(async () => { + await app?.close(); + removeTestProfile(profile); +}); + +test('Arrange → Nesting packs the parts on the sheet in workers and undoes in one step', async () => { + // Six rectangles scattered over the bed, and a short search. + await page.evaluate(async () => { + localStorage.setItem( + 'openburn.nesting', + JSON.stringify({ sheetWidth: 100, sheetHeight: 100, spacing: 2, margin: 1, timeLimit: 2, leftover: 'side', side: 'right', freeRotation: false, rotationStep: 90 }), + ); + const ws = (window as unknown as { __openburn: Ws }).__openburn; + const doc = ws.snapshotDocument(); + const layerId = doc.layers[0].id; + doc.canvas.objects = Array.from({ length: 6 }, (_, i) => ({ + type: 'Rect', + version: '6.5.1', + left: 150 + i * 60, + top: 200 + (i % 3) * 70, + width: 20 + i * 4, + height: 15 + (i % 2) * 10, + fill: null, + stroke: '#ff0000', + strokeWidth: 0, + layerId, + })); + await ws.applyRecoveredDocument(doc, null); + }); + const before = await boxes(); + expect(before).toHaveLength(6); + await page.evaluate(() => (window as unknown as { __openburn: Ws }).__openburn.selectAll()); + + await page.getByRole('button', { name: 'Arrange', exact: true }).click(); + await page.getByRole('button', { name: 'Nesting…' }).click(); + const dialog = page.locator('.dialog'); + await dialog.getByRole('button', { name: 'Start', exact: true }).click(); + await expect(dialog.getByRole('button', { name: 'Restart' })).toBeVisible({ timeout: 30_000 }); + await expect(dialog.locator('.nest-summary')).toContainText('6/6 parts'); + expect(workers.some((u) => /nest\.worker/.test(u))).toBe(true); + + await dialog.getByRole('button', { name: 'Apply' }).click(); + await expect(page.locator('.dialog')).toHaveCount(0); + + const after = await boxes(); + for (const b of after) { + expect(b.left).toBeGreaterThanOrEqual(1 - 1e-6); + expect(b.top).toBeGreaterThanOrEqual(1 - 1e-6); + expect(b.left + b.width).toBeLessThanOrEqual(99 + 1e-6); + expect(b.top + b.height).toBeLessThanOrEqual(99 + 1e-6); + } + // Quarter turns only, so the boxes are the parts: they keep the 2 mm spacing. + for (let i = 0; i < after.length; i += 1) { + for (let j = i + 1; j < after.length; j += 1) { + const a = after[i]; + const b = after[j]; + const overlapX = Math.min(a.left + a.width, b.left + b.width) - Math.max(a.left, b.left); + const overlapY = Math.min(a.top + a.height, b.top + b.height) - Math.max(a.top, b.top); + expect(Math.min(-overlapX, -overlapY) >= 2 - 1e-6 || -overlapX >= 2 - 1e-6 || -overlapY >= 2 - 1e-6).toBe(true); + } + } + + await page.evaluate(() => (window as unknown as { __openburn: Ws }).__openburn.undo()); + await expect.poll(async () => (await boxes()).map((b) => Math.round(b.left))).toEqual( + before.map((b) => Math.round(b.left)), + ); +}); diff --git a/src/nesting/engines/grid.ts b/src/nesting/engines/grid.ts new file mode 100644 index 0000000..29cdb71 --- /dev/null +++ b/src/nesting/engines/grid.ts @@ -0,0 +1,575 @@ +/** + * "Grid" nesting engine. + * + * 1. Every part orientation is rasterised (see raster.ts) on a fine grid. + * 2. A greedy pass places the parts one by one, largest first, trying a coarse + * set of orientations and keeping the position with the best key for the + * requested offcut (pack left, keep a corner square free, stay compact). + * 3. A late-acceptance hill climbing then permutes the order and nudges + * orientations (fine rotation step, mirror) until the time budget runs out. + * + * Holes are handled for free: a ring part leaves its inside cells empty, so + * small parts placed later can drop into them. + */ +import { frameFor, type Frame } from '../frame'; +import { + evenOddArea, + extendBounds, + emptyBounds, + multiply, + orientationMatrix, + placementFromMatrix, + simplify, + transformRing, + type Affine, +} from '../geometry'; +import { Board, rasterize, type RasterPart } from '../raster'; +import { createRng, type Rng } from '../rng'; +import type { + LeftoverMode, + NestEngine, + NestOptions, + NestPart, + NestResult, + NestSheet, + Placement, + Pt, +} from '../types'; + +interface PreparedPart { + /** Placement id (part id, or `${id}#n` for extra copies). */ + id: string; + rings: Pt[][]; + solids: Pt[][]; + lines: Pt[][]; + /** Internal frame geometry is centred on the origin: scene → base. */ + baseMatrix: Affine; + canMirror: boolean; + area: number; + extent: number; +} + +interface Orientation { + angleIndex: number; + mirrored: boolean; +} + +interface Gene extends Orientation {} + +interface PlacedPart { + part: number; + o: Orientation; + x: number; + y: number; +} + +/** Everything evaluate() accumulates while placing parts in order. */ +interface PrefixState { + cluster: ClusterBox; + placed: PlacedPart[]; + unplaced: number[]; + keySum: number; +} + +/** Board and state just before placing order[index]. */ +interface Checkpoint { + index: number; + occ: Uint8Array; + rowMaxX: Int32Array; + state: PrefixState; +} + +interface Evaluated { + score: number; + placed: PlacedPart[]; + unplaced: number[]; + genes: Gene[]; + board: Board; + checkpoints: Checkpoint[]; +} + +/** Checkpoints kept per evaluated solution (each costs one byte per cell). */ +const MAX_CHECKPOINTS = 6; + +function cloneState(s: PrefixState): PrefixState { + return { cluster: { ...s.cluster }, placed: s.placed.slice(), unplaced: s.unplaced.slice(), keySum: s.keySum }; +} + +function latestCheckpoint(list: Checkpoint[], from: number): Checkpoint | null { + let best: Checkpoint | null = null; + for (const c of list) if (c.index <= from && (!best || c.index > best.index)) best = c; + return best; +} + +const MAX_CELLS_PER_SIDE = 1200; +/** Separates the primary and secondary terms of a position key (cells < 1e5). */ +const KEY_BIG = 1e6; +/** Orientations tried per part by the greedy pass (before mirroring). */ +const GREEDY_ANGLES = 12; +const MIN_RES = 0.2; + +/** Cell size used for a sheet, in mm. */ +export function gridResolution(sheet: NestSheet): number { + return Math.max(MIN_RES, Math.max(sheet.width, sheet.height) / MAX_CELLS_PER_SIDE); +} + +export class GridSearch { + readonly res: number; + readonly frame: Frame; + readonly W: number; + readonly H: number; + /** Internal mm coordinates of the board's cell (0, 0) corner. */ + readonly gx: number; + readonly gy: number; + readonly parts: PreparedPart[]; + readonly angles: number[]; + readonly coarse: number[]; + private readonly cache = new Map(); + private readonly dilate: number; + + constructor( + input: NestPart[], + readonly sheet: NestSheet, + readonly options: NestOptions, + ) { + this.res = gridResolution(sheet); + this.frame = frameFor(sheet, options.leftover); + this.dilate = Math.max(0, options.spacing) / 2; + // The grid covers the usable area grown by the dilation halo so a part can + // sit exactly `margin` from the edge. + const inset = Math.max(0, options.margin) - this.dilate; + this.gx = inset; + this.gy = inset; + this.W = Math.max(0, Math.floor((this.frame.width - 2 * inset) / this.res)); + this.H = Math.max(0, Math.floor((this.frame.height - 2 * inset) / this.res)); + + const step = options.rotationStep > 0 ? options.rotationStep : 360; + this.angles = []; + for (let a = 0; a < 360 - 1e-9; a += step) this.angles.push(a); + const k = Math.max(1, Math.round(this.angles.length / GREEDY_ANGLES)); + this.coarse = this.angles.map((_, i) => i).filter((i) => i % k === 0); + + this.parts = []; + const tolerance = this.res / 4; + for (const part of input) { + const copies = Math.max(1, Math.floor(part.quantity || 1)); + const rings = part.rings.map((r) => simplify(transformRing(r, this.frame.toInternal), tolerance)); + const solids = part.solids.map((r) => simplify(transformRing(r, this.frame.toInternal), tolerance)); + const lines = part.lines.map((l) => simplify(transformRing(l, this.frame.toInternal), tolerance)); + const b = emptyBounds(); + [...rings, ...solids, ...lines].forEach((p) => extendBounds(b, p)); + if (!Number.isFinite(b.minX)) continue; + const cx = (b.minX + b.maxX) / 2; + const cy = (b.minY + b.maxY) / 2; + const center: Affine = [1, 0, 0, 1, -cx, -cy]; + const centred = (list: Pt[][]) => list.map((p) => transformRing(p, center)); + const area = + rings.length > 0 + ? evenOddArea(rings) + solids.reduce((s, r) => s + evenOddArea([r]), 0) + : solids.reduce((s, r) => s + evenOddArea([r]), 0); + for (let c = 0; c < copies; c += 1) { + this.parts.push({ + id: c === 0 ? part.id : `${part.id}#${c}`, + rings: centred(rings), + solids: centred(solids), + lines: centred(lines), + baseMatrix: multiply(center, this.frame.toInternal), + canMirror: part.canMirror && options.allowMirror, + area: area > 0 ? area : (b.maxX - b.minX) * (b.maxY - b.minY), + extent: Math.max(b.maxX - b.minX, b.maxY - b.minY), + }); + } + } + } + + orientationsFor(part: number, angleIndices: number[]): Orientation[] { + const out: Orientation[] = []; + for (const angleIndex of angleIndices) { + out.push({ angleIndex, mirrored: false }); + if (this.parts[part].canMirror) out.push({ angleIndex, mirrored: true }); + } + return out; + } + + raster(part: number, o: Orientation): RasterPart | null { + const key = `${part}|${o.angleIndex}|${o.mirrored ? 1 : 0}`; + if (this.cache.has(key)) return this.cache.get(key)!; + const p = this.parts[part]; + const m = orientationMatrix(this.angles[o.angleIndex], o.mirrored); + const rp = rasterize( + { + rings: p.rings.map((r) => transformRing(r, m)), + solids: p.solids.map((r) => transformRing(r, m)), + lines: p.lines.map((l) => transformRing(l, m)), + }, + this.res, + this.dilate, + ); + this.cache.set(key, rp); + return rp; + } + + /** + * Best position of one orientation on the board for the current mode, if + * one beats `bound`. Each row only needs its leftmost fit (every key grows + * with x), and rows are cut short as soon as a position can no longer beat + * the best key found so far, across orientations too. + */ + bestPosition( + board: Board, + rp: RasterPart, + cluster: ClusterBox, + bound = Infinity, + ): { x: number; y: number; key: number } | null { + const { mask } = rp; + const { w, h } = mask; + const mode = this.options.leftover.kind; + let best: { x: number; y: number; key: number } | null = null; + let limit = bound; + const clusterW = cluster.maxX > cluster.minX ? cluster.maxX - cluster.minX : 0; + for (let y = 0; y + h <= this.H; y += 1) { + let xMax = Infinity; + if (Number.isFinite(limit)) { + if (mode === 'side') { + xMax = Math.floor(limit / KEY_BIG) - w; + } else if (mode === 'corner') { + const allowed = -Math.floor(limit / KEY_BIG); + if (this.H - y - h < allowed) xMax = this.W - w - allowed; + } else if (Number.isFinite(cluster.minX)) { + const rowH = Math.max(cluster.maxY, y + h) - Math.min(cluster.minY, y); + const widthCap = limit / (10 * rowH); + if (Math.max(clusterW, w) > widthCap) continue; + xMax = Math.max(cluster.minX, Math.floor(cluster.minX + widthCap - w)); + } + if (xMax < 0) continue; + } + const x = board.leftmostFit(mask, y, 0, xMax); + if (x < 0) continue; + const key = this.positionKey(mode, x, y, w, h, cluster); + if (key < limit) { + best = { x, y, key }; + limit = key; + } + } + return best; + } + + private positionKey( + mode: LeftoverMode['kind'], + x: number, + y: number, + w: number, + h: number, + c: ClusterBox, + ): number { + if (mode === 'side') return (x + w) * KEY_BIG + y; + if (mode === 'corner') { + const allowed = Math.max(this.W - (x + w), this.H - (y + h)); + return -allowed * KEY_BIG + x + y; + } + const minX = Math.min(c.minX, x); + const minY = Math.min(c.minY, y); + const maxX = Math.max(c.maxX, x + w); + const maxY = Math.max(c.maxY, y + h); + const span = Math.max(maxX - minX, maxY - minY); + return ((maxX - minX) * (maxY - minY) + span * span * 0.25) * 10 + x + y; + } + + /** + * Place the parts in `order`, each with its gene, repairing genes that do + * not fit. With `base`, the parts before `from` are known to be identical + * to `base`'s, so placement resumes from its last checkpoint before `from`. + */ + evaluate(order: number[], genes: Gene[], greedy: boolean, base?: Evaluated, from = 0): Evaluated { + let start = 0; + let board: Board; + let state: PrefixState; + const checkpoints: Checkpoint[] = []; + const resume = base ? latestCheckpoint(base.checkpoints, from) : null; + if (resume) { + start = resume.index; + board = Board.fromOccupancy(this.W, this.H, resume.occ, resume.rowMaxX); + state = cloneState(resume.state); + for (const c of base!.checkpoints) if (c.index <= start) checkpoints.push(c); + } else { + board = new Board(this.W, this.H); + state = { + cluster: { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity }, + placed: [], + unplaced: [], + keySum: 0, + }; + } + const out = genes.slice(); + const every = Math.max(4, Math.ceil(order.length / MAX_CHECKPOINTS)); + for (let index = start; index < order.length; index += 1) { + if (index > start && index % every === 0) { + checkpoints.push({ + index, + occ: board.occ.slice(), + rowMaxX: board.rowMaxX.slice(), + state: cloneState(state), + }); + } + const part = order[index]; + const tries = greedy + ? this.orientationsFor(part, this.coarse) + : [out[part], ...this.orientationsFor(part, this.coarse)]; + let chosen: { o: Orientation; x: number; y: number; key: number; rp: RasterPart } | null = null; + for (let i = 0; i < tries.length; i += 1) { + const o = tries[i]; + const rp = this.raster(part, o); + if (!rp) continue; + const pos = this.bestPosition(board, rp, state.cluster, chosen ? chosen.key : Infinity); + if (pos) chosen = { o, rp, ...pos }; + // In search mode the gene wins whenever it fits; the coarse set is a repair. + if (!greedy && i === 0 && chosen) break; + } + if (!chosen) { + state.unplaced.push(part); + continue; + } + board.place(chosen.rp.mask, chosen.x, chosen.y); + const c = state.cluster; + c.minX = Math.min(c.minX, chosen.x); + c.minY = Math.min(c.minY, chosen.y); + c.maxX = Math.max(c.maxX, chosen.x + chosen.rp.mask.w); + c.maxY = Math.max(c.maxY, chosen.y + chosen.rp.mask.h); + out[part] = chosen.o; + state.keySum += chosen.x + chosen.y; + state.placed.push({ part, o: chosen.o, x: chosen.x, y: chosen.y }); + } + return { + score: this.score(board, state.cluster, state.unplaced, state.placed.length, state.keySum), + placed: state.placed, + unplaced: state.unplaced, + genes: out, + board, + checkpoints, + }; + } + + private score( + board: Board, + cluster: ClusterBox, + unplaced: number[], + count: number, + keySum: number, + ): number { + const missing = unplaced.reduce((s, p) => s + this.parts[p].area, 0) / (this.res * this.res); + const compact = count > 0 ? keySum / (count * (this.W + this.H)) : 0; + let primary: number; + switch (this.options.leftover.kind) { + case 'side': + primary = board.usedWidth(); + break; + case 'corner': + primary = -board.bottomRightSquare(); + break; + default: { + const w = Math.max(0, cluster.maxX - cluster.minX); + const h = Math.max(0, cluster.maxY - cluster.minY); + primary = Math.sqrt(w * h + Math.max(w, h) ** 2 * 0.25); + } + } + return missing * 1e6 + primary * 10 + compact; + } + + /** Scene-space result of an evaluation. */ + toResult(ev: Evaluated, evaluations: number, elapsedMs: number): NestResult { + let shiftX = 0; + let shiftY = 0; + if (this.options.leftover.kind === 'center' && ev.placed.length > 0) { + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const p of ev.placed) { + const m = this.raster(p.part, p.o)!.mask; + minX = Math.min(minX, p.x); + minY = Math.min(minY, p.y); + maxX = Math.max(maxX, p.x + m.w); + maxY = Math.max(maxY, p.y + m.h); + } + shiftX = ((this.W - (maxX - minX)) / 2 - minX) * this.res; + shiftY = ((this.H - (maxY - minY)) / 2 - minY) * this.res; + } + + const placements: Placement[] = ev.placed.map((p) => { + const part = this.parts[p.part]; + const rp = this.raster(p.part, p.o)!; + const tx = this.gx + p.x * this.res - rp.originX + shiftX; + const ty = this.gy + p.y * this.res - rp.originY + shiftY; + const orient = orientationMatrix(this.angles[p.o.angleIndex], p.o.mirrored); + const internal: Affine = [orient[0], orient[1], orient[2], orient[3], tx, ty]; + const m = multiply(this.frame.toScene, multiply(internal, part.baseMatrix)); + return placementFromMatrix(part.id, m); + }); + + const placedArea = ev.placed.reduce((s, p) => s + this.parts[p.part].area, 0); + const sheetArea = this.sheet.width * this.sheet.height; + let leftover: NestResult['leftover'] = null; + if (this.options.leftover.kind !== 'center' && this.W > 0 && this.H > 0) { + const r = ev.board.largestEmptyRect(); + // A rectangle touching the grid border extends to the sheet edge. + const x0 = r.x === 0 ? 0 : this.gx + r.x * this.res; + const y0 = r.y === 0 ? 0 : this.gy + r.y * this.res; + const x1 = r.x + r.w >= this.W ? this.frame.width : this.gx + (r.x + r.w) * this.res; + const y1 = r.y + r.h >= this.H ? this.frame.height : this.gy + (r.y + r.h) * this.res; + const a = applyToScene(this.frame, x0, y0); + const b = applyToScene(this.frame, x1, y1); + leftover = { + x: Math.min(a.x, b.x), + y: Math.min(a.y, b.y), + width: Math.abs(b.x - a.x), + height: Math.abs(b.y - a.y), + }; + } + return { + placements, + unplaced: ev.unplaced.map((p) => this.parts[p].id), + utilization: sheetArea > 0 ? placedArea / sheetArea : 0, + score: ev.score, + leftover, + sharedEdges: [], + evaluations, + elapsedMs, + }; + } + + initialOrder(variant: number, rng: Rng): number[] { + const idx = this.parts.map((_, i) => i); + const p = this.parts; + switch (variant % 4) { + case 1: + return idx.sort((a, b) => p[b].extent - p[a].extent || p[b].area - p[a].area); + case 2: + return idx.sort((a, b) => p[b].area * p[b].extent - p[a].area * p[a].extent); + case 3: { + // Area order with a little noise. + const noisy = idx.map((i) => ({ i, k: p[i].area * (0.7 + 0.6 * rng.next()) })); + return noisy.sort((a, b) => b.k - a.k).map((n) => n.i); + } + default: + return idx.sort((a, b) => p[b].area - p[a].area || p[b].extent - p[a].extent); + } + } +} + +interface ClusterBox { + minX: number; + minY: number; + maxX: number; + maxY: number; +} + +function applyToScene(frame: Frame, x: number, y: number): Pt { + const m = frame.toScene; + return { x: m[0] * x + m[2] * y + m[4], y: m[1] * x + m[3] * y + m[5] }; +} + +function yieldToEvents(): Promise { + return new Promise((resolve) => setTimeout(resolve, 0)); +} + +function now(): number { + return typeof performance !== 'undefined' ? performance.now() : Date.now(); +} + +/** Late-acceptance history length. */ +const LAHC_LENGTH = 30; + +export const gridEngine: NestEngine = { + id: 'grid', + label: 'Grid search', + async run(parts, sheet, options, onProgress, signal) { + const start = now(); + const search = new GridSearch(parts, sheet, options); + const rng = createRng(options.seed); + const n = search.parts.length; + const emptyGenes: Gene[] = search.parts.map(() => ({ angleIndex: 0, mirrored: false })); + + let order = search.initialOrder(options.variant, rng); + let current = search.evaluate(order, emptyGenes, true); + let best = current; + let evaluations = 1; + const elapsed = () => now() - start; + onProgress(search.toResult(best, evaluations, elapsed())); + + if (n < 2 && search.angles.length < 2 && !search.parts.some((p) => p.canMirror)) { + return search.toResult(best, evaluations, elapsed()); + } + + const history = new Array(LAHC_LENGTH).fill(current.score); + let lastReport = elapsed(); + let pendingReport = false; + const budget = Math.max(0, options.timeLimit) * 1000; + + while (!signal.aborted && elapsed() < budget) { + await yieldToEvents(); + if (signal.aborted) break; + const candidateOrder = order.slice(); + const genes = current.genes.slice(); + const from = mutate(candidateOrder, genes, search, rng); + const candidate = search.evaluate(candidateOrder, genes, false, current, from); + evaluations += 1; + const slot = evaluations % LAHC_LENGTH; + if (candidate.score <= current.score || candidate.score <= history[slot]) { + current = candidate; + order = candidateOrder; + } + history[slot] = current.score; + if (current.score < best.score - 1e-9) { + best = current; + pendingReport = true; + } + if (pendingReport && elapsed() - lastReport > 200) { + onProgress(search.toResult(best, evaluations, elapsed())); + lastReport = elapsed(); + pendingReport = false; + } + } + const result = search.toResult(best, evaluations, elapsed()); + onProgress(result); + return result; + }, +}; + +/** Apply one random move; returns the first order index it changed. */ +function mutate(order: number[], genes: Gene[], search: GridSearch, rng: Rng): number { + const n = order.length; + const roll = rng.next(); + const nAngles = search.angles.length; + if (n >= 2 && roll < 0.4) { + // Swap with a nearby part: small, local moves are accepted more often. + const i = rng.int(n); + const j = Math.min(n - 1, Math.max(0, i + (rng.next() < 0.5 ? -1 : 1) * (1 + rng.int(4)))); + [order[i], order[j]] = [order[j], order[i]]; + return Math.min(i, j); + } + if (n >= 2 && roll < 0.55) { + const i = rng.int(n); + const [item] = order.splice(i, 1); + const k = rng.int(n); + order.splice(k, 0, item); + return Math.min(i, k); + } + const index = rng.int(n); + const part = order[index]; + const g = { ...genes[part] }; + const r = rng.next(); + if (search.parts[part].canMirror && r < 0.2) { + g.mirrored = !g.mirrored; + } else if (nAngles > 1 && r < 0.6) { + const delta = 1 + rng.int(Math.max(1, Math.min(3, nAngles - 1))); + g.angleIndex = (g.angleIndex + (rng.next() < 0.5 ? -delta : delta) + nAngles) % nAngles; + } else if (nAngles > 1) { + g.angleIndex = rng.int(nAngles); + } else if (n >= 2) { + const j = rng.int(n); + [order[index], order[j]] = [order[j], order[index]]; + return Math.min(index, j); + } + genes[part] = g; + return index; +} diff --git a/src/nesting/extract.test.ts b/src/nesting/extract.test.ts new file mode 100644 index 0000000..5db140a --- /dev/null +++ b/src/nesting/extract.test.ts @@ -0,0 +1,78 @@ +// @vitest-environment jsdom +import { describe, expect, it } from 'vitest'; +import { Group, Path, Polygon, Rect } from 'fabric'; +import { applySceneTransform, partFromObject } from './extract'; +import { evenOddArea, placementMatrix } from './geometry'; +import type { Pt } from './types'; + +function bounds(polys: Pt[][]) { + const xs = polys.flat().map((p) => p.x); + const ys = polys.flat().map((p) => p.y); + return { minX: Math.min(...xs), minY: Math.min(...ys), maxX: Math.max(...xs), maxY: Math.max(...ys) }; +} + +const OPTS = { keepTextUnmirrored: true }; + +describe('nesting/extract', () => { + it('reads a rect in scene coordinates', () => { + const rect = new Rect({ left: 10, top: 20, width: 30, height: 15, strokeWidth: 0 }); + const part = partFromObject(rect, 'r', OPTS)!; + expect(part.rings).toHaveLength(1); + const b = bounds(part.rings); + expect(b.minX).toBeCloseTo(10, 6); + expect(b.minY).toBeCloseTo(20, 6); + expect(b.maxX).toBeCloseTo(40, 6); + expect(b.maxY).toBeCloseTo(35, 6); + }); + + it('keeps holes on the cut layer and fills engravings on other layers', () => { + const outer = new Path('M 0 0 L 40 0 L 40 40 L 0 40 Z', { strokeWidth: 0 }); + const hole = new Path('M 10 10 L 30 10 L 30 30 L 10 30 Z', { strokeWidth: 0 }); + const engraving = new Polygon( + [ + { x: 2, y: 2 }, + { x: 6, y: 2 }, + { x: 6, y: 6 }, + ], + { strokeWidth: 0 }, + ); + (outer as unknown as { layerId: string }).layerId = 'cut'; + (hole as unknown as { layerId: string }).layerId = 'cut'; + (engraving as unknown as { layerId: string }).layerId = 'engrave'; + const group = new Group([outer, hole, engraving]); + const part = partFromObject(group, 'g', OPTS)!; + expect(part.rings).toHaveLength(2); + expect(part.solids).toHaveLength(1); + expect(evenOddArea(part.rings)).toBeCloseTo(1600 - 400, 3); + expect(part.canMirror).toBe(true); + }); + + it('flattens curves and follows the group transform', () => { + const curve = new Path('M 0 0 C 10 -10 20 10 30 0 L 30 20 L 0 20 Z', { strokeWidth: 0 }); + const group = new Group([curve], { left: 100, top: 50, angle: 90, strokeWidth: 0 }); + const part = partFromObject(group, 'c', OPTS)!; + expect(part.rings[0].length).toBeGreaterThan(8); + const b = bounds(part.rings); + const br = group.getBoundingRect(); + expect(b.maxX - b.minX).toBeCloseTo(br.width, 0); + expect(b.maxY - b.minY).toBeCloseTo(br.height, 0); + }); + + it('moves an object exactly like the placement transforms its geometry', () => { + const rect = new Rect({ left: 5, top: 5, width: 20, height: 10, strokeWidth: 0 }); + const before = partFromObject(rect, 'r', OPTS)!; + const m = placementMatrix({ angle: 30, mirrored: true, x: 50, y: 40 }); + const expected = before.rings[0].map((p) => ({ + x: m[0] * p.x + m[2] * p.y + m[4], + y: m[1] * p.x + m[3] * p.y + m[5], + })); + applySceneTransform(rect, m); + const after = partFromObject(rect, 'r', OPTS)!; + const eb = bounds([expected]); + const ab = bounds(after.rings); + expect(ab.minX).toBeCloseTo(eb.minX, 6); + expect(ab.minY).toBeCloseTo(eb.minY, 6); + expect(ab.maxX).toBeCloseTo(eb.maxX, 6); + expect(ab.maxY).toBeCloseTo(eb.maxY, 6); + }); +}); diff --git a/src/nesting/extract.ts b/src/nesting/extract.ts new file mode 100644 index 0000000..ade7a92 --- /dev/null +++ b/src/nesting/extract.ts @@ -0,0 +1,295 @@ +/** + * Fabric objects → nesting parts. + * + * Each top-level object (usually a group) is one rigid part. Its leaves are + * read straight from Fabric's own geometry (path commands, polygon points, + * rect/ellipse sizes) with their absolute transform, and curves are flattened + * in scene millimetres. + * + * The cut silhouette is the set of closed contours on the part's cut layer, + * taken as the layer of its largest closed contour. Inner contours on that + * layer are through holes (other parts may nest inside); closed shapes on any + * other layer (engravings) are filled solid so nothing is ever placed on them. + */ +import type { FabricObject, TMat2D } from 'fabric'; +import { util } from 'fabric'; +import { signedArea } from './geometry'; +import type { NestPart, Pt, Ring } from './types'; + +/** Max chord deviation when flattening curves, mm. */ +const FLATTEN_TOLERANCE = 0.05; + +interface Leaf { + layerId: string | undefined; + closed: Ring[]; + open: Pt[][]; + text: boolean; +} + +export interface ExtractOptions { + /** Parts holding text are never mirrored (readable text stays readable). */ + keepTextUnmirrored: boolean; +} + +type AnyObject = FabricObject & { + layerId?: string; + path?: (string | number)[][]; + points?: Pt[]; + pathOffset?: Pt; + rx?: number; + ry?: number; + radius?: number; + x1?: number; + y1?: number; + x2?: number; + y2?: number; + calcLinePoints?: () => { x1: number; y1: number; x2: number; y2: number }; + getObjects?: () => FabricObject[]; +}; + +function isGroup(obj: AnyObject): boolean { + return typeof obj.getObjects === 'function' && /group|activeselection/i.test(obj.type ?? ''); +} + +function isText(obj: AnyObject): boolean { + return /text/i.test(obj.type ?? ''); +} + +function transform(m: TMat2D, p: Pt): Pt { + return { x: m[0] * p.x + m[2] * p.y + m[4], y: m[1] * p.x + m[3] * p.y + m[5] }; +} + +function curveSteps(points: Pt[]): number { + let len = 0; + for (let i = 1; i < points.length; i += 1) { + len += Math.hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y); + } + // A chord of length s on radius r deviates s²/8r; this keeps it tiny for + // the radii found in laser parts without exploding the vertex count. + return Math.max(2, Math.min(64, Math.ceil(Math.sqrt(len / FLATTEN_TOLERANCE)))); +} + +function cubic(p0: Pt, p1: Pt, p2: Pt, p3: Pt, out: Pt[]): void { + const n = curveSteps([p0, p1, p2, p3]); + for (let i = 1; i <= n; i += 1) { + const t = i / n; + const u = 1 - t; + out.push({ + x: u * u * u * p0.x + 3 * u * u * t * p1.x + 3 * u * t * t * p2.x + t * t * t * p3.x, + y: u * u * u * p0.y + 3 * u * u * t * p1.y + 3 * u * t * t * p2.y + t * t * t * p3.y, + }); + } +} + +function quadratic(p0: Pt, p1: Pt, p2: Pt, out: Pt[]): void { + const n = curveSteps([p0, p1, p2]); + for (let i = 1; i <= n; i += 1) { + const t = i / n; + const u = 1 - t; + out.push({ + x: u * u * p0.x + 2 * u * t * p1.x + t * t * p2.x, + y: u * u * p0.y + 2 * u * t * p1.y + t * t * p2.y, + }); + } +} + +function samePoint(a: Pt, b: Pt): boolean { + return Math.abs(a.x - b.x) < 1e-6 && Math.abs(a.y - b.y) < 1e-6; +} + +function pushPolyline(leaf: Leaf, points: Pt[], closed: boolean): void { + if (points.length === 0) return; + if (closed || (points.length > 2 && samePoint(points[0], points[points.length - 1]))) { + const ring = samePoint(points[0], points[points.length - 1]) ? points.slice(0, -1) : points; + if (ring.length >= 3) { + leaf.closed.push(ring); + return; + } + } + leaf.open.push(points); +} + +function pathLeaf(obj: AnyObject, m: TMat2D, leaf: Leaf): void { + const off = obj.pathOffset ?? { x: 0, y: 0 }; + const at = (x: number, y: number) => transform(m, { x: x - off.x, y: y - off.y }); + let current: Pt[] = []; + let pen: Pt = { x: 0, y: 0 }; + let start: Pt = pen; + for (const cmd of obj.path ?? []) { + const op = String(cmd[0]); + const n = cmd.slice(1).map(Number); + switch (op) { + case 'M': + pushPolyline(leaf, current, false); + pen = at(n[0], n[1]); + start = pen; + current = [pen]; + break; + case 'L': + pen = at(n[0], n[1]); + current.push(pen); + break; + case 'C': { + const p3 = at(n[4], n[5]); + cubic(pen, at(n[0], n[1]), at(n[2], n[3]), p3, current); + pen = p3; + break; + } + case 'Q': { + const p2 = at(n[2], n[3]); + quadratic(pen, at(n[0], n[1]), p2, current); + pen = p2; + break; + } + case 'Z': + case 'z': + pushPolyline(leaf, current, true); + current = []; + pen = start; + break; + default: + break; + } + } + pushPolyline(leaf, current, false); +} + +function ellipseRing(m: TMat2D, rx: number, ry: number): Ring { + const pts: Ring = []; + const n = 64; + for (let i = 0; i < n; i += 1) { + const a = (2 * Math.PI * i) / n; + pts.push(transform(m, { x: rx * Math.cos(a), y: ry * Math.sin(a) })); + } + return pts; +} + +/** Scene-space corners of the object's own (untransformed) box. */ +function boxRing(obj: AnyObject, m: TMat2D): Ring { + const w = (obj.width ?? 0) / 2; + const h = (obj.height ?? 0) / 2; + return [ + transform(m, { x: -w, y: -h }), + transform(m, { x: w, y: -h }), + transform(m, { x: w, y: h }), + transform(m, { x: -w, y: h }), + ]; +} + +type TextLike = AnyObject & { + textLines?: unknown[]; + getLineWidth?: (i: number) => number; + getHeightOfLine?: (i: number) => number; + _getLineLeftOffset?: (i: number) => number; +}; + +/** + * Scene-space box around the text actually drawn: a text box is often much + * wider than its glyphs (a single "A" in a 10 mm wide box). + */ +function textRing(obj: TextLike, m: TMat2D): Ring { + try { + const lines = obj.textLines?.length ?? 0; + if (lines > 0 && obj.getLineWidth && obj.getHeightOfLine && obj._getLineLeftOffset) { + const w = obj.width ?? 0; + const h = obj.height ?? 0; + let minX = Infinity; + let maxX = -Infinity; + let textH = 0; + for (let i = 0; i < lines; i += 1) { + const left = -w / 2 + obj._getLineLeftOffset(i); + const lw = obj.getLineWidth(i); + if (lw > 0) { + minX = Math.min(minX, left); + maxX = Math.max(maxX, left + lw); + } + textH += obj.getHeightOfLine(i); + } + if (Number.isFinite(minX) && maxX > minX) { + const top = -h / 2; + const bottom = top + Math.min(h, textH); + return [ + transform(m, { x: minX, y: top }), + transform(m, { x: maxX, y: top }), + transform(m, { x: maxX, y: bottom }), + transform(m, { x: minX, y: bottom }), + ]; + } + } + } catch { + /* fall back to the whole box */ + } + return boxRing(obj, m); +} + +function collectLeaves(obj: AnyObject, inheritedLayer: string | undefined, out: Leaf[]): void { + const layerId = obj.layerId ?? inheritedLayer; + if (isGroup(obj)) { + for (const child of obj.getObjects!()) collectLeaves(child as AnyObject, layerId, out); + return; + } + const m = obj.calcTransformMatrix(); + const leaf: Leaf = { layerId, closed: [], open: [], text: isText(obj) }; + const type = (obj.type ?? '').toLowerCase(); + if (leaf.text) { + leaf.closed.push(textRing(obj as TextLike, m)); + } else if (Array.isArray(obj.path)) { + pathLeaf(obj, m, leaf); + } else if (Array.isArray(obj.points) && (type === 'polygon' || type === 'polyline')) { + const off = obj.pathOffset ?? { x: 0, y: 0 }; + const pts = obj.points.map((p) => transform(m, { x: p.x - off.x, y: p.y - off.y })); + pushPolyline(leaf, pts, type === 'polygon'); + } else if (type === 'line' && obj.calcLinePoints) { + const l = obj.calcLinePoints(); + leaf.open.push([transform(m, { x: l.x1, y: l.y1 }), transform(m, { x: l.x2, y: l.y2 })]); + } else if (type === 'circle') { + leaf.closed.push(ellipseRing(m, obj.radius ?? 0, obj.radius ?? 0)); + } else if (type === 'ellipse') { + leaf.closed.push(ellipseRing(m, obj.rx ?? 0, obj.ry ?? 0)); + } else { + // Rect, image and anything else: its box. + leaf.closed.push(boxRing(obj, m)); + } + out.push(leaf); +} + +/** Build one nesting part from a top-level canvas object. */ +export function partFromObject(obj: FabricObject, id: string, options: ExtractOptions): NestPart | null { + const leaves: Leaf[] = []; + collectLeaves(obj as AnyObject, undefined, leaves); + + let cutLayer: string | undefined; + let bestArea = 0; + for (const leaf of leaves) { + if (leaf.text) continue; + for (const ring of leaf.closed) { + const a = Math.abs(signedArea(ring)); + if (a > bestArea) { + bestArea = a; + cutLayer = leaf.layerId; + } + } + } + + const part: NestPart = { id, rings: [], solids: [], lines: [], canMirror: true, quantity: 1 }; + let hasText = false; + for (const leaf of leaves) { + if (leaf.text) hasText = true; + const isCut = bestArea > 0 && !leaf.text && leaf.layerId === cutLayer; + for (const ring of leaf.closed) (isCut ? part.rings : part.solids).push(ring); + part.lines.push(...leaf.open); + } + if (part.rings.length === 0 && part.solids.length === 0 && part.lines.length === 0) return null; + part.canMirror = !(hasText && options.keepTextUnmirrored); + return part; +} + +/** + * Apply a rigid scene-space transform (mirror/rotation + translation) to a + * top-level object, on top of its current transform. + */ +export function applySceneTransform(obj: FabricObject, m: TMat2D): void { + const next = util.multiplyTransformMatrices(m, obj.calcTransformMatrix()); + util.applyTransformToObject(obj, next); + obj.setCoords(); +} diff --git a/src/nesting/frame.ts b/src/nesting/frame.ts new file mode 100644 index 0000000..b2571bd --- /dev/null +++ b/src/nesting/frame.ts @@ -0,0 +1,62 @@ +import { multiply, type Affine } from './geometry'; +import type { LeftoverMode, NestSheet } from './types'; + +/** + * Engines pack toward the top-left of an internal frame and keep the offcut at + * the right (side mode) or bottom-right (corner mode). The frame is an + * isometry of the real sheet (flips and/or a transpose) chosen so that the + * requested offcut lands where the user asked. + * + * A part transformed in the internal frame by P maps back to the scene as + * F⁻¹ · P · F. Conjugating by an isometry never mirrors a part on its own. + */ +export interface Frame { + /** Scene → internal (mm, sheet top-left at 0,0). */ + toInternal: Affine; + /** Internal → scene. */ + toScene: Affine; + /** Internal sheet size (swapped when transposed). */ + width: number; + height: number; +} + +export function frameFor(sheet: NestSheet, leftover: LeftoverMode): Frame { + let flipX = false; + let flipY = false; + let transpose = false; + if (leftover.kind === 'side') { + // Internal offcut is on the right. + if (leftover.side === 'left') flipX = true; + else if (leftover.side === 'bottom') transpose = true; + else if (leftover.side === 'top') { + flipY = true; + transpose = true; + } + } else if (leftover.kind === 'corner') { + // Internal offcut is bottom-right. + flipX = leftover.corner === 'topLeft' || leftover.corner === 'bottomLeft'; + flipY = leftover.corner === 'topLeft' || leftover.corner === 'topRight'; + } + + // Scene → sheet-relative, then flips (in sheet size), then transpose. + let m: Affine = [1, 0, 0, 1, -sheet.x, -sheet.y]; + if (flipX) m = multiply([-1, 0, 0, 1, sheet.width, 0], m); + if (flipY) m = multiply([1, 0, 0, -1, 0, sheet.height], m); + if (transpose) m = multiply([0, 1, 1, 0, 0, 0], m); + + return { + toInternal: m, + toScene: invert(m), + width: transpose ? sheet.height : sheet.width, + height: transpose ? sheet.width : sheet.height, + }; +} + +export function invert(m: Affine): Affine { + const det = m[0] * m[3] - m[1] * m[2]; + const a = m[3] / det; + const b = -m[1] / det; + const c = -m[2] / det; + const d = m[0] / det; + return [a, b, c, d, -(a * m[4] + c * m[5]), -(b * m[4] + d * m[5])]; +} diff --git a/src/nesting/geometry.ts b/src/nesting/geometry.ts new file mode 100644 index 0000000..726cbd9 --- /dev/null +++ b/src/nesting/geometry.ts @@ -0,0 +1,151 @@ +import type { Placement, Pt, Ring } from './types'; + +/** 2D affine matrix in Fabric order: [a, b, c, d, e, f] → x' = a·x + c·y + e. */ +export type Affine = [number, number, number, number, number, number]; + +export const IDENTITY: Affine = [1, 0, 0, 1, 0, 0]; + +export function multiply(m: Affine, n: Affine): Affine { + return [ + m[0] * n[0] + m[2] * n[1], + m[1] * n[0] + m[3] * n[1], + m[0] * n[2] + m[2] * n[3], + m[1] * n[2] + m[3] * n[3], + m[0] * n[4] + m[2] * n[5] + m[4], + m[1] * n[4] + m[3] * n[5] + m[5], + ]; +} + +export function applyAffine(m: Affine, p: Pt): Pt { + return { x: m[0] * p.x + m[2] * p.y + m[4], y: m[1] * p.x + m[3] * p.y + m[5] }; +} + +/** Mirror (x → -x) when asked, then rotate clockwise (Y down) by `angle` degrees. */ +export function orientationMatrix(angle: number, mirrored: boolean): Affine { + const rad = (angle * Math.PI) / 180; + const cos = Math.cos(rad); + const sin = Math.sin(rad); + const rot: Affine = [cos, sin, -sin, cos, 0, 0]; + return mirrored ? multiply(rot, [-1, 0, 0, 1, 0, 0]) : rot; +} + +export function placementMatrix(p: Pick): Affine { + const m = orientationMatrix(p.angle, p.mirrored); + m[4] = p.x; + m[5] = p.y; + return m; +} + +/** Inverse of {@link placementMatrix} for rigid (rotation ± mirror) matrices. */ +export function placementFromMatrix(partId: string, m: Affine): Placement { + const det = m[0] * m[3] - m[1] * m[2]; + const mirrored = det < 0; + // With a mirror the first column is (-cos, -sin); without it is (cos, sin). + const cos = mirrored ? -m[0] : m[0]; + const sin = mirrored ? -m[1] : m[1]; + let angle = (Math.atan2(sin, cos) * 180) / Math.PI; + angle = ((angle % 360) + 360) % 360; + if (Math.abs(angle - 360) < 1e-9) angle = 0; + return { partId, angle, mirrored, x: m[4], y: m[5] }; +} + +export function transformRing(ring: Ring, m: Affine): Ring { + return ring.map((p) => applyAffine(m, p)); +} + +export interface Bounds { + minX: number; + minY: number; + maxX: number; + maxY: number; +} + +export function emptyBounds(): Bounds { + return { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity }; +} + +export function extendBounds(b: Bounds, points: Pt[]): Bounds { + for (const p of points) { + if (p.x < b.minX) b.minX = p.x; + if (p.y < b.minY) b.minY = p.y; + if (p.x > b.maxX) b.maxX = p.x; + if (p.y > b.maxY) b.maxY = p.y; + } + return b; +} + +export function signedArea(ring: Ring): number { + let a = 0; + for (let i = 0, j = ring.length - 1; i < ring.length; j = i, i += 1) { + a += (ring[j].x + ring[i].x) * (ring[j].y - ring[i].y); + } + return a / 2; +} + +export function pointInRing(p: Pt, ring: Ring): boolean { + let inside = false; + for (let i = 0, j = ring.length - 1; i < ring.length; j = i, i += 1) { + const a = ring[i]; + const b = ring[j]; + if (a.y > p.y !== b.y > p.y && p.x < ((b.x - a.x) * (p.y - a.y)) / (b.y - a.y) + a.x) { + inside = !inside; + } + } + return inside; +} + +/** Area of a set of rings filled with the even-odd rule (holes subtracted). */ +export function evenOddArea(rings: Ring[]): number { + let total = 0; + for (let i = 0; i < rings.length; i += 1) { + const ring = rings[i]; + if (ring.length < 3) continue; + let depth = 0; + for (let j = 0; j < rings.length; j += 1) { + if (i !== j && rings[j].length >= 3 && pointInRing(ring[0], rings[j])) depth += 1; + } + const a = Math.abs(signedArea(ring)); + total += depth % 2 === 0 ? a : -a; + } + return Math.max(0, total); +} + +/** Ramer–Douglas–Peucker simplification; keeps the first and last points. */ +export function simplify(points: Pt[], tolerance: number): Pt[] { + if (points.length <= 3 || tolerance <= 0) return points.slice(); + const keep = new Uint8Array(points.length); + keep[0] = 1; + keep[points.length - 1] = 1; + const stack: [number, number][] = [[0, points.length - 1]]; + const tol2 = tolerance * tolerance; + while (stack.length) { + const [s, e] = stack.pop()!; + let maxD = -1; + let idx = -1; + for (let i = s + 1; i < e; i += 1) { + const d = segmentDistance2(points[i], points[s], points[e]); + if (d > maxD) { + maxD = d; + idx = i; + } + } + if (idx >= 0 && maxD > tol2) { + keep[idx] = 1; + stack.push([s, idx], [idx, e]); + } + } + return points.filter((_, i) => keep[i] === 1); +} + +/** Squared distance from `p` to segment [a, b]. */ +export function segmentDistance2(p: Pt, a: Pt, b: Pt): number { + const dx = b.x - a.x; + const dy = b.y - a.y; + const len2 = dx * dx + dy * dy; + let t = len2 > 0 ? ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2 : 0; + if (t < 0) t = 0; + else if (t > 1) t = 1; + const qx = a.x + t * dx - p.x; + const qy = a.y + t * dy - p.y; + return qx * qx + qy * qy; +} diff --git a/src/nesting/nest.worker.ts b/src/nesting/nest.worker.ts new file mode 100644 index 0000000..a872521 --- /dev/null +++ b/src/nesting/nest.worker.ts @@ -0,0 +1,33 @@ +/// +/** + * Runs one nesting engine off the UI thread. Messages: + * in: { type: 'run', engine, parts, sheet, options } | { type: 'stop' } + * out: { type: 'progress', result } | { type: 'done', result } | { type: 'error', message } + */ +import { getNestEngine } from './registry'; +import type { NestOptions, NestPart, NestSheet } from './types'; + +interface RunMessage { + type: 'run'; + engine: string; + parts: NestPart[]; + sheet: NestSheet; + options: NestOptions; +} + +const ctx = self as unknown as DedicatedWorkerGlobalScope; +let controller: AbortController | null = null; + +ctx.onmessage = (event: MessageEvent) => { + const msg = event.data; + if (msg.type === 'stop') { + controller?.abort(); + return; + } + if (msg.type !== 'run') return; + controller = new AbortController(); + getNestEngine(msg.engine) + .run(msg.parts, msg.sheet, msg.options, (result) => ctx.postMessage({ type: 'progress', result }), controller.signal) + .then((result) => ctx.postMessage({ type: 'done', result })) + .catch((err: unknown) => ctx.postMessage({ type: 'error', message: String(err) })); +}; diff --git a/src/nesting/nesting.test.ts b/src/nesting/nesting.test.ts new file mode 100644 index 0000000..df18a42 --- /dev/null +++ b/src/nesting/nesting.test.ts @@ -0,0 +1,279 @@ +// @vitest-environment node +import { describe, expect, it } from 'vitest'; +import { gridEngine, GridSearch } from './engines/grid'; +import { frameFor } from './frame'; +import { + applyAffine, + evenOddArea, + multiply, + placementFromMatrix, + placementMatrix, + pointInRing, +} from './geometry'; +import { Board, rasterize } from './raster'; +import type { NestOptions, NestPart, NestResult, NestSheet, Pt, Ring } from './types'; + +const rect = (x: number, y: number, w: number, h: number): Ring => [ + { x, y }, + { x: x + w, y }, + { x: x + w, y: y + h }, + { x, y: y + h }, +]; + +const circle = (cx: number, cy: number, r: number, n = 48): Ring => + Array.from({ length: n }, (_, i) => ({ + x: cx + r * Math.cos((2 * Math.PI * i) / n), + y: cy + r * Math.sin((2 * Math.PI * i) / n), + })); + +const part = (id: string, rings: Ring[], extra: Partial = {}): NestPart => ({ + id, + rings, + solids: [], + lines: [], + canMirror: true, + quantity: 1, + ...extra, +}); + +const OPTIONS: NestOptions = { + spacing: 1, + margin: 0, + rotationStep: 90, + allowMirror: false, + leftover: { kind: 'side', side: 'right' }, + commonLine: false, + timeLimit: 0, + seed: 1, + variant: 0, +}; + +const SHEET: NestSheet = { x: 0, y: 0, width: 100, height: 100 }; + +function run(parts: NestPart[], options: Partial = {}, sheet = SHEET): Promise { + return gridEngine.run(parts, sheet, { ...OPTIONS, ...options }, () => {}, new AbortController().signal); +} + +/** Part rings moved to their placement. */ +function placedRings(parts: NestPart[], result: NestResult): Map { + const out = new Map(); + for (const pl of result.placements) { + const p = parts.find((q) => q.id === pl.partId)!; + const m = placementMatrix(pl); + out.set( + pl.partId, + p.rings.map((r) => r.map((pt) => applyAffine(m, pt))), + ); + } + return out; +} + +function segDist(p: Pt, a: Pt, b: Pt): number { + const dx = b.x - a.x; + const dy = b.y - a.y; + const t = Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / (dx * dx + dy * dy))); + return Math.hypot(a.x + t * dx - p.x, a.y + t * dy - p.y); +} + +/** Smallest distance between the outlines of two polygons (0 if they cross or nest). */ +function ringDistance(a: Ring, b: Ring): number { + if (pointInRing(a[0], b) || pointInRing(b[0], a)) return 0; + let d = Infinity; + for (const p of a) for (let i = 0; i < b.length; i += 1) d = Math.min(d, segDist(p, b[i], b[(i + 1) % b.length])); + for (const p of b) for (let i = 0; i < a.length; i += 1) d = Math.min(d, segDist(p, a[i], a[(i + 1) % a.length])); + return d; +} + +describe('nesting/geometry', () => { + it('round-trips placements through matrices', () => { + for (const mirrored of [false, true]) { + for (const angle of [0, 33, 90, 270]) { + const p = placementFromMatrix('a', placementMatrix({ angle, mirrored, x: 5, y: -2 })); + expect(p.mirrored).toBe(mirrored); + expect(p.angle).toBeCloseTo(angle, 9); + expect(p.x).toBe(5); + expect(p.y).toBe(-2); + } + } + }); + + it('subtracts holes with the even-odd rule', () => { + expect(evenOddArea([rect(0, 0, 10, 10), rect(2, 2, 4, 4)])).toBeCloseTo(84, 9); + }); + + it('maps every leftover frame back to the scene without mirroring', () => { + const sheet = { x: 10, y: 20, width: 300, height: 200 }; + const modes = [ + { kind: 'side', side: 'left' }, + { kind: 'side', side: 'top' }, + { kind: 'side', side: 'bottom' }, + { kind: 'corner', corner: 'topLeft' }, + ] as const; + for (const mode of modes) { + const f = frameFor(sheet, mode); + const back = multiply(f.toScene, f.toInternal); + const p = applyAffine(back, { x: 42, y: 7 }); + expect(p.x).toBeCloseTo(42, 9); + expect(p.y).toBeCloseTo(7, 9); + // The internal frame covers exactly the sheet. + const corner = applyAffine(f.toInternal, { x: sheet.x, y: sheet.y }); + expect([0, f.width]).toContainEqual(Math.round(corner.x)); + expect([0, f.height]).toContainEqual(Math.round(corner.y)); + } + }); +}); + +describe('nesting/raster', () => { + it('covers the shape conservatively and keeps holes empty', () => { + const rp = rasterize({ rings: [rect(0, 0, 10, 10), rect(3, 3, 4, 4)], solids: [], lines: [] }, 0.5, 0)!; + expect(rp.mask.w).toBeGreaterThanOrEqual(20); + expect(rp.mask.w).toBeLessThanOrEqual(23); + // Some cells inside the hole are free. + const board = new Board(rp.mask.w, rp.mask.h); + board.place(rp.mask, 0, 0); + const cx = Math.floor((5 - rp.originX) / 0.5); + const cy = Math.floor((5 - rp.originY) / 0.5); + expect(board.occ[cy * board.W + cx]).toBe(0); + expect(rp.mask.cells).toBeGreaterThan(84 / 0.25); + }); + + it('finds the leftmost fit and jumps over obstacles', () => { + const board = new Board(20, 5); + const block = rasterize({ rings: [rect(0, 0, 2, 2)], solids: [], lines: [] }, 1, 0)!.mask; + board.place(block, 0, 0); + const x = board.leftmostFit(block, 0); + expect(x).toBe(block.w); + expect(board.fits(block, 0, 0)).toBe(false); + expect(board.largestEmptyRect().w * board.largestEmptyRect().h).toBeGreaterThan(0); + }); +}); + +describe('nesting/grid engine', () => { + it('places rectangles without overlap and keeps the spacing', async () => { + const parts = [ + part('a', [rect(0, 0, 40, 20)]), + part('b', [rect(0, 0, 30, 30)]), + part('c', [rect(0, 0, 20, 45)]), + part('d', [rect(0, 0, 25, 15)]), + ]; + const result = await run(parts, { spacing: 2 }); + expect(result.unplaced).toEqual([]); + const rings = placedRings(parts, result); + const ids = [...rings.keys()]; + for (let i = 0; i < ids.length; i += 1) { + for (let j = i + 1; j < ids.length; j += 1) { + expect(ringDistance(rings.get(ids[i])![0], rings.get(ids[j])![0])).toBeGreaterThanOrEqual(2 - 1e-6); + } + } + // Everything stays on the sheet. + for (const r of rings.values()) { + for (const p of r[0]) { + expect(p.x).toBeGreaterThanOrEqual(-1e-6); + expect(p.y).toBeGreaterThanOrEqual(-1e-6); + expect(p.x).toBeLessThanOrEqual(100 + 1e-6); + expect(p.y).toBeLessThanOrEqual(100 + 1e-6); + } + } + }); + + it('respects the margin', async () => { + const parts = [part('a', [rect(50, 50, 10, 10)])]; + const result = await run(parts, { margin: 5 }); + const r = placedRings(parts, result).get('a')![0]; + for (const p of r) { + expect(p.x).toBeGreaterThanOrEqual(5 - 1e-6); + expect(p.y).toBeGreaterThanOrEqual(5 - 1e-6); + } + }); + + it('reports parts that do not fit', async () => { + const result = await run([part('big', [rect(0, 0, 150, 10)]), part('ok', [rect(0, 0, 10, 10)])], { + rotationStep: 0, + }); + expect(result.unplaced).toEqual(['big']); + expect(result.placements.map((p) => p.partId)).toEqual(['ok']); + }); + + it('rotates a part that only fits sideways', async () => { + const sheet = { x: 0, y: 0, width: 100, height: 30 }; + const result = await run([part('tall', [rect(0, 0, 10, 80)])], { rotationStep: 90 }, sheet); + expect(result.unplaced).toEqual([]); + expect(Math.round(result.placements[0].angle) % 180).toBe(90); + }); + + it('nests a small part inside the hole of a ring', async () => { + const sheet = { x: 0, y: 0, width: 62, height: 62 }; + const ring = part('ring', [circle(30, 30, 30), circle(30, 30, 20)]); + const disc = part('disc', [circle(0, 0, 12)]); + const result = await run([ring, disc], { rotationStep: 0, spacing: 1 }, sheet); + expect(result.unplaced).toEqual([]); + const d = result.placements.find((p) => p.partId === 'disc')!; + const centre = applyAffine(placementMatrix(d), { x: 0, y: 0 }); + const r = result.placements.find((p) => p.partId === 'ring')!; + const ringCentre = applyAffine(placementMatrix(r), { x: 30, y: 30 }); + expect(Math.hypot(centre.x - ringCentre.x, centre.y - ringCentre.y)).toBeLessThan(8); + }); + + it('keeps the offcut on the requested side', async () => { + const parts = Array.from({ length: 6 }, (_, i) => part(`p${i}`, [rect(0, 0, 20, 15)])); + for (const side of ['left', 'right', 'top', 'bottom'] as const) { + const result = await run(parts, { leftover: { kind: 'side', side } }); + const lo = result.leftover!; + if (side === 'right') expect(lo.x + lo.width).toBeCloseTo(100, 5); + if (side === 'left') expect(lo.x).toBeCloseTo(0, 5); + if (side === 'top') expect(lo.y).toBeCloseTo(0, 5); + if (side === 'bottom') expect(lo.y + lo.height).toBeCloseTo(100, 5); + expect(Math.min(lo.width, lo.height)).toBeGreaterThan(40); + expect(Math.max(lo.width, lo.height)).toBeCloseTo(100, 5); + } + }); + + it('keeps a square free in the requested corner', async () => { + const parts = Array.from({ length: 6 }, (_, i) => part(`p${i}`, [rect(0, 0, 20, 15)])); + const result = await run(parts, { leftover: { kind: 'corner', corner: 'topRight' } }); + const rings = [...placedRings(parts, result).values()].map((r) => r[0]); + // Nothing intrudes a 50 mm square in the top-right corner. + for (const r of rings) { + const intrudes = r.some((p) => p.x > 50 + 1e-6 && p.y < 50 - 1e-6); + expect(intrudes).toBe(false); + } + }); + + it('never mirrors a part that must not be mirrored', async () => { + const parts = Array.from({ length: 5 }, (_, i) => + part(`p${i}`, [[{ x: 0, y: 0 }, { x: 30, y: 0 }, { x: 0, y: 12 }]], { canMirror: i % 2 === 0 }), + ); + const result = await run(parts, { allowMirror: true, rotationStep: 45, timeLimit: 0.3 }); + for (const pl of result.placements) { + const p = parts.find((q) => q.id === pl.partId)!; + if (!p.canMirror) expect(pl.mirrored).toBe(false); + } + }); + + it('improves or keeps the greedy score while searching and stops on abort', async () => { + const parts = Array.from({ length: 8 }, (_, i) => + part(`p${i}`, [[{ x: 0, y: 0 }, { x: 20 + i * 3, y: 0 }, { x: 0, y: 10 + i * 2 }]]), + ); + const scores: number[] = []; + const ctrl = new AbortController(); + const result = await gridEngine.run( + parts, + SHEET, + { ...OPTIONS, rotationStep: 15, allowMirror: true, timeLimit: 5 }, + (r) => { + scores.push(r.score); + if (scores.length === 1) setTimeout(() => ctrl.abort(), 300); + }, + ctrl.signal, + ); + expect(result.elapsedMs).toBeLessThan(4000); + expect(result.score).toBeLessThanOrEqual(scores[0]); + for (let i = 1; i < scores.length; i += 1) expect(scores[i]).toBeLessThanOrEqual(scores[i - 1]); + }); + + it('expands quantities into numbered copies', () => { + const search = new GridSearch([part('a', [rect(0, 0, 5, 5)], { quantity: 3 })], SHEET, OPTIONS); + expect(search.parts.map((p) => p.id)).toEqual(['a', 'a#1', 'a#2']); + }); +}); + diff --git a/src/nesting/raster.ts b/src/nesting/raster.ts new file mode 100644 index 0000000..161f82e --- /dev/null +++ b/src/nesting/raster.ts @@ -0,0 +1,350 @@ +/** + * Raster toolkit for nesting: parts and the sheet become occupancy grids. + * + * Working on cells instead of exact polygons makes concave parts, holes + * (small parts nested inside a ring), free rotation and "largest offcut" + * measures trivial and robust. The rasterisation is conservative: a cell is + * marked whenever the part dilated by half the spacing may touch it, so two + * parts whose masks do not overlap are always at least `spacing` apart. + */ +import { segmentDistance2 } from './geometry'; +import type { Pt, Ring } from './types'; + +/** A part orientation as rows of horizontal runs of occupied cells. */ +export interface Mask { + w: number; + h: number; + /** runs of row r are runs[rowStart[r] .. rowStart[r + 1]) as (start, length) pairs. */ + rowStart: Int32Array; + runs: Int32Array; + cells: number; +} + +export interface RasterPart { + mask: Mask; + /** Geometry coordinates of the mask's top-left cell corner. */ + originX: number; + originY: number; +} + +export interface RasterInput { + rings: Ring[]; + solids: Ring[]; + lines: Pt[][]; +} + +/** + * Rasterise geometry at `res` mm per cell, dilated by `dilate` mm. + * Returns null when the geometry is empty. + */ +export function rasterize(input: RasterInput, res: number, dilate: number): RasterPart | null { + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + const all = [...input.rings, ...input.solids, ...input.lines]; + for (const poly of all) { + for (const p of poly) { + if (p.x < minX) minX = p.x; + if (p.y < minY) minY = p.y; + if (p.x > maxX) maxX = p.x; + if (p.y > maxY) maxY = p.y; + } + } + if (!Number.isFinite(minX)) return null; + + // Halo: a cell is marked when its centre is within this distance of an edge. + const halo = dilate + res * Math.SQRT1_2; + const pad = halo + res; + const ox = minX - pad; + const oy = minY - pad; + const w = Math.ceil((maxX - minX + 2 * pad) / res) + 1; + const h = Math.ceil((maxY - minY + 2 * pad) / res) + 1; + const grid = new Uint8Array(w * h); + + fillEvenOdd(grid, w, h, ox, oy, res, input.rings); + for (const solid of input.solids) fillEvenOdd(grid, w, h, ox, oy, res, [solid]); + + const halo2 = halo * halo; + const strokeEdges = (poly: Pt[], closed: boolean) => { + const n = poly.length; + if (n === 1) markSegment(grid, w, h, ox, oy, res, poly[0], poly[0], halo, halo2); + const last = closed ? n : n - 1; + for (let i = 0; i < last; i += 1) { + markSegment(grid, w, h, ox, oy, res, poly[i], poly[(i + 1) % n], halo, halo2); + } + }; + input.rings.forEach((r) => strokeEdges(r, true)); + input.solids.forEach((r) => strokeEdges(r, true)); + input.lines.forEach((l) => strokeEdges(l, false)); + + return trimToMask(grid, w, h, ox, oy, res); +} + +function fillEvenOdd( + grid: Uint8Array, + w: number, + h: number, + ox: number, + oy: number, + res: number, + rings: Ring[], +): void { + const rows: number[][] = Array.from({ length: h }, () => []); + let any = false; + for (const ring of rings) { + const n = ring.length; + if (n < 3) continue; + for (let i = 0, j = n - 1; i < n; j = i, i += 1) { + const a = ring[j]; + const b = ring[i]; + if (a.y === b.y) continue; + const y0 = Math.min(a.y, b.y); + const y1 = Math.max(a.y, b.y); + // Row centres yc = oy + (r + 0.5)·res with y0 <= yc < y1. + const r0 = Math.max(0, Math.ceil((y0 - oy) / res - 0.5)); + const r1 = Math.min(h - 1, Math.ceil((y1 - oy) / res - 0.5) - 1); + for (let r = r0; r <= r1; r += 1) { + const yc = oy + (r + 0.5) * res; + rows[r].push(a.x + ((yc - a.y) * (b.x - a.x)) / (b.y - a.y)); + any = true; + } + } + } + if (!any) return; + for (let r = 0; r < h; r += 1) { + const xs = rows[r]; + if (xs.length < 2) continue; + xs.sort((p, q) => p - q); + for (let k = 0; k + 1 < xs.length; k += 2) { + const c0 = Math.max(0, Math.ceil((xs[k] - ox) / res - 0.5)); + const c1 = Math.min(w - 1, Math.floor((xs[k + 1] - ox) / res - 0.5)); + const base = r * w; + for (let c = c0; c <= c1; c += 1) grid[base + c] = 1; + } + } +} + +function markSegment( + grid: Uint8Array, + w: number, + h: number, + ox: number, + oy: number, + res: number, + a: Pt, + b: Pt, + halo: number, + halo2: number, +): void { + const c0 = Math.max(0, Math.floor((Math.min(a.x, b.x) - halo - ox) / res - 0.5)); + const c1 = Math.min(w - 1, Math.ceil((Math.max(a.x, b.x) + halo - ox) / res - 0.5)); + const r0 = Math.max(0, Math.floor((Math.min(a.y, b.y) - halo - oy) / res - 0.5)); + const r1 = Math.min(h - 1, Math.ceil((Math.max(a.y, b.y) + halo - oy) / res - 0.5)); + const p = { x: 0, y: 0 }; + for (let r = r0; r <= r1; r += 1) { + p.y = oy + (r + 0.5) * res; + const base = r * w; + for (let c = c0; c <= c1; c += 1) { + if (grid[base + c]) continue; + p.x = ox + (c + 0.5) * res; + if (segmentDistance2(p, a, b) <= halo2) grid[base + c] = 1; + } + } +} + +function trimToMask( + grid: Uint8Array, + w: number, + h: number, + ox: number, + oy: number, + res: number, +): RasterPart | null { + let minC = w; + let maxC = -1; + let minR = h; + let maxR = -1; + for (let r = 0; r < h; r += 1) { + const base = r * w; + for (let c = 0; c < w; c += 1) { + if (!grid[base + c]) continue; + if (c < minC) minC = c; + if (c > maxC) maxC = c; + if (r < minR) minR = r; + if (r > maxR) maxR = r; + } + } + if (maxC < 0) return null; + const mw = maxC - minC + 1; + const mh = maxR - minR + 1; + const rowStart = new Int32Array(mh + 1); + const runs: number[] = []; + let cells = 0; + for (let r = 0; r < mh; r += 1) { + rowStart[r] = runs.length; + const base = (r + minR) * w + minC; + let c = 0; + while (c < mw) { + if (!grid[base + c]) { + c += 1; + continue; + } + const start = c; + while (c < mw && grid[base + c]) c += 1; + runs.push(start, c - start); + cells += c - start; + } + } + rowStart[mh] = runs.length; + return { + mask: { w: mw, h: mh, rowStart, runs: Int32Array.from(runs), cells }, + originX: ox + minC * res, + originY: oy + minR * res, + }; +} + +/** + * The sheet as an occupancy grid. `free[y·W + x]` is the number of free cells + * from x to the right on row y, which lets the search jump over obstacles. + */ +export class Board { + readonly occ: Uint8Array; + readonly free: Int32Array; + /** Rightmost occupied column per row, -1 when the row is empty. */ + readonly rowMaxX: Int32Array; + + constructor( + readonly W: number, + readonly H: number, + init = true, + ) { + this.occ = new Uint8Array(W * H); + this.free = new Int32Array(W * H); + this.rowMaxX = new Int32Array(H).fill(-1); + if (init) for (let y = 0; y < H; y += 1) this.recomputeRow(y); + } + + /** A board restored from a saved occupancy grid. */ + static fromOccupancy(W: number, H: number, occ: Uint8Array, rowMaxX: Int32Array): Board { + const b = new Board(W, H, false); + b.occ.set(occ); + b.rowMaxX.set(rowMaxX); + for (let y = 0; y < H; y += 1) b.recomputeRow(y); + return b; + } + + private recomputeRow(y: number): void { + const W = this.W; + const base = y * W; + let run = 0; + for (let x = W - 1; x >= 0; x -= 1) { + run = this.occ[base + x] ? 0 : run + 1; + this.free[base + x] = run; + } + } + + /** + * Leftmost x in [x0, xMax] where `mask` fits with its top row on board row + * y, or -1. + */ + leftmostFit(mask: Mask, y: number, x0 = 0, xMax = Infinity): number { + const { W } = this; + const { h, rowStart, runs } = mask; + if (y < 0 || y + h > this.H) return -1; + const maxX = Math.min(W - mask.w, xMax); + let x = x0; + let first = 0; + outer: while (x <= maxX) { + for (let k = 0; k < h; k += 1) { + const r = first + k < h ? first + k : first + k - h; + const base = (y + r) * W + x; + for (let i = rowStart[r]; i < rowStart[r + 1]; i += 2) { + const d = this.free[base + runs[i]]; + if (d < runs[i + 1]) { + x += d + 1; + first = r; + continue outer; + } + } + } + return x; + } + return -1; + } + + fits(mask: Mask, x: number, y: number): boolean { + return x >= 0 && this.leftmostFit(mask, y, x) === x; + } + + place(mask: Mask, x: number, y: number): void { + const { W } = this; + const { h, rowStart, runs } = mask; + for (let r = 0; r < h; r += 1) { + const row = y + r; + const base = row * W + x; + let touched = false; + for (let i = rowStart[r]; i < rowStart[r + 1]; i += 2) { + const s = runs[i]; + const len = runs[i + 1]; + this.occ.fill(1, base + s, base + s + len); + const end = x + s + len - 1; + if (end > this.rowMaxX[row]) this.rowMaxX[row] = end; + touched = true; + } + if (touched) this.recomputeRow(row); + } + } + + /** + * Side of the largest empty square anchored at the bottom-right corner, + * in cells. + */ + bottomRightSquare(): number { + let s = Math.min(this.W, this.H); + for (let y = 0; y < this.H; y += 1) { + const mx = this.rowMaxX[y]; + if (mx < 0) continue; + const allowed = Math.max(this.W - 1 - mx, this.H - 1 - y); + if (allowed < s) s = allowed; + } + return s; + } + + /** Columns used from the left edge (rightmost occupied column + 1). */ + usedWidth(): number { + let m = -1; + for (let y = 0; y < this.H; y += 1) if (this.rowMaxX[y] > m) m = this.rowMaxX[y]; + return m + 1; + } + + /** Largest empty axis-aligned rectangle (histogram method), in cells. */ + largestEmptyRect(): { x: number; y: number; w: number; h: number } { + const { W, H, occ } = this; + const heights = new Int32Array(W); + const stack = new Int32Array(W + 1); + let best = { x: 0, y: 0, w: 0, h: 0 }; + let bestArea = 0; + for (let y = 0; y < H; y += 1) { + const base = y * W; + for (let x = 0; x < W; x += 1) heights[x] = occ[base + x] ? 0 : heights[x] + 1; + let top = 0; + for (let x = 0; x <= W; x += 1) { + const hx = x < W ? heights[x] : 0; + while (top > 0 && heights[stack[top - 1]] >= hx) { + const hh = heights[stack[top - 1]]; + top -= 1; + const left = top > 0 ? stack[top - 1] + 1 : 0; + const area = hh * (x - left); + if (area > bestArea) { + bestArea = area; + best = { x: left, y: y - hh + 1, w: x - left, h: hh }; + } + } + stack[top] = x; + top += 1; + } + } + return best; + } +} diff --git a/src/nesting/registry.ts b/src/nesting/registry.ts new file mode 100644 index 0000000..28e8989 --- /dev/null +++ b/src/nesting/registry.ts @@ -0,0 +1,23 @@ +import { gridEngine } from './engines/grid'; +import type { NestEngine } from './types'; + +/** + * Available nesting engines. Register a new engine here (or at runtime with + * {@link registerNestEngine}) and it shows up in the Nesting dialog; the + * dialog only shows the engine picker when there is more than one. + */ +const engines = new Map([[gridEngine.id, gridEngine]]); + +export const DEFAULT_NEST_ENGINE = gridEngine.id; + +export function registerNestEngine(engine: NestEngine): void { + engines.set(engine.id, engine); +} + +export function getNestEngine(id: string): NestEngine { + return engines.get(id) ?? engines.get(DEFAULT_NEST_ENGINE)!; +} + +export function listNestEngines(): { id: string; label: string }[] { + return [...engines.values()].map((e) => ({ id: e.id, label: e.label })); +} diff --git a/src/nesting/rng.ts b/src/nesting/rng.ts new file mode 100644 index 0000000..1088600 --- /dev/null +++ b/src/nesting/rng.ts @@ -0,0 +1,19 @@ +/** Small seeded PRNG (mulberry32) so nesting runs are reproducible. */ +export interface Rng { + /** Uniform float in [0, 1). */ + next(): number; + /** Uniform integer in [0, n). */ + int(n: number): number; +} + +export function createRng(seed: number): Rng { + let s = seed >>> 0 || 0x9e3779b9; + const next = () => { + s = (s + 0x6d2b79f5) >>> 0; + let t = s; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; + return { next, int: (n) => Math.floor(next() * n) }; +} diff --git a/src/nesting/runner.ts b/src/nesting/runner.ts new file mode 100644 index 0000000..7379627 --- /dev/null +++ b/src/nesting/runner.ts @@ -0,0 +1,114 @@ +/** + * Runs a nesting engine in several Web Workers at once (each with its own + * seed and strategy variant) and keeps the best result. Falls back to the UI + * thread when workers are unavailable; engines yield regularly so the app + * stays responsive either way. + */ +import { getNestEngine } from './registry'; +import type { NestOptions, NestPart, NestResult, NestSheet } from './types'; + +export interface NestProgress { + best: NestResult; + /** Evaluations summed over all workers. */ + evaluations: number; +} + +export interface NestRun { + /** Resolves with the best result once every worker has finished. */ + done: Promise; + /** Ask every worker to stop; `done` then resolves with the best so far. */ + stop(): void; +} + +export interface StartOptions { + engine: string; + parts: NestPart[]; + sheet: NestSheet; + options: NestOptions; + onProgress: (progress: NestProgress) => void; + /** Number of parallel workers (default: cores − 1, at most 4). */ + workers?: number; +} + +function defaultWorkers(): number { + const cores = typeof navigator !== 'undefined' ? navigator.hardwareConcurrency || 2 : 2; + return Math.max(1, Math.min(4, cores - 1)); +} + +function createWorker(): Worker | null { + try { + if (typeof Worker === 'undefined') return null; + return new Worker(new URL('./nest.worker.ts', import.meta.url), { type: 'module' }); + } catch { + return null; + } +} + +export function startNesting(start: StartOptions): NestRun { + const count = Math.max(1, start.workers ?? defaultWorkers()); + let best: NestResult | null = null; + const evaluations = new Array(count).fill(0); + const stoppers: (() => void)[] = []; + + const offer = (index: number, result: NestResult) => { + evaluations[index] = result.evaluations; + if (!best || result.score < best.score) best = result; + start.onProgress({ best, evaluations: evaluations.reduce((a, b) => a + b, 0) }); + }; + + const runInThread = (index: number, options: NestOptions): Promise => { + const ctrl = new AbortController(); + stoppers[index] = () => ctrl.abort(); + return getNestEngine(start.engine) + .run(start.parts, start.sheet, options, (r) => offer(index, r), ctrl.signal) + .then((r) => offer(index, r)); + }; + + const runOne = (index: number): Promise => { + const options: NestOptions = { + ...start.options, + seed: (start.options.seed + index * 7919) >>> 0, + variant: start.options.variant + index, + }; + const worker = createWorker(); + if (!worker) return runInThread(index, options); + return new Promise((resolve) => { + let started = false; + let stopped = false; + stoppers[index] = () => { + stopped = true; + worker.postMessage({ type: 'stop' }); + }; + worker.onmessage = (event: MessageEvent<{ type: string; result?: NestResult; message?: string }>) => { + const msg = event.data; + started = true; + if (msg.result) offer(index, msg.result); + if (msg.type === 'done' || msg.type === 'error') { + if (msg.type === 'error') console.error('[nesting] worker failed:', msg.message); + worker.terminate(); + resolve(); + } + }; + worker.onerror = (event) => { + event.preventDefault(); + worker.terminate(); + // A worker that never started (blocked by the platform) runs in-thread instead. + if (!started && !stopped) void runInThread(index, options).then(resolve, resolve); + else resolve(); + }; + worker.postMessage({ + type: 'run', + engine: start.engine, + parts: start.parts, + sheet: start.sheet, + options, + }); + }); + }; + + const done = Promise.all(Array.from({ length: count }, (_, i) => runOne(i))).then(() => best); + return { + done, + stop: () => stoppers.forEach((s) => s?.()), + }; +} diff --git a/src/nesting/settings.test.ts b/src/nesting/settings.test.ts new file mode 100644 index 0000000..49299db --- /dev/null +++ b/src/nesting/settings.test.ts @@ -0,0 +1,57 @@ +// @vitest-environment node +import { describe, expect, it } from 'vitest'; +import { + DEFAULT_NEST_SETTINGS, + FREE_ROTATION_STEP, + loadNestSettings, + nestOptions, + NEST_SETTINGS_KEY, + normalizeNestSettings, + saveNestSettings, +} from './settings'; + +function memoryStorage(): Storage { + const data = new Map(); + return { + get length() { + return data.size; + }, + clear: () => data.clear(), + getItem: (k) => data.get(k) ?? null, + key: (i) => [...data.keys()][i] ?? null, + removeItem: (k) => void data.delete(k), + setItem: (k, v) => void data.set(k, v), + }; +} + +describe('nesting/settings', () => { + it('falls back to defaults field by field', () => { + const s = normalizeNestSettings({ sheetWidth: 450, spacing: -3, leftover: 'nope', corner: 'topLeft' }); + expect(s.sheetWidth).toBe(450); + expect(s.spacing).toBe(0); + expect(s.leftover).toBe(DEFAULT_NEST_SETTINGS.leftover); + expect(s.corner).toBe('topLeft'); + expect(s.sheetHeight).toBe(DEFAULT_NEST_SETTINGS.sheetHeight); + }); + + it('round-trips through storage and survives garbage', () => { + const storage = memoryStorage(); + saveNestSettings({ ...DEFAULT_NEST_SETTINGS, sheetWidth: 123 }, storage); + expect(loadNestSettings(storage).sheetWidth).toBe(123); + storage.setItem(NEST_SETTINGS_KEY, '{not json'); + expect(loadNestSettings(storage)).toEqual(DEFAULT_NEST_SETTINGS); + }); + + it('builds engine options from the dialog settings', () => { + const free = nestOptions({ ...DEFAULT_NEST_SETTINGS, freeRotation: true }); + expect(free.rotationStep).toBe(FREE_ROTATION_STEP); + expect(free.commonLine).toBe(false); + const stepped = nestOptions({ ...DEFAULT_NEST_SETTINGS, freeRotation: false, rotationStep: 90 }); + expect(stepped.rotationStep).toBe(90); + expect(nestOptions({ ...DEFAULT_NEST_SETTINGS, leftover: 'corner', corner: 'topRight' }).leftover).toEqual({ + kind: 'corner', + corner: 'topRight', + }); + expect(nestOptions({ ...DEFAULT_NEST_SETTINGS, leftover: 'center' }).leftover).toEqual({ kind: 'center' }); + }); +}); diff --git a/src/nesting/settings.ts b/src/nesting/settings.ts new file mode 100644 index 0000000..d94a115 --- /dev/null +++ b/src/nesting/settings.ts @@ -0,0 +1,138 @@ +import type { Corner, LeftoverMode, NestOptions, Side } from './types'; +import { DEFAULT_NEST_ENGINE } from './registry'; + +/** + * Persisted Nesting dialog settings (versioned, like `openburn.snap`). + * Lengths are millimetres. + */ +export interface NestSettings { + version: 1; + sheetWidth: number; + sheetHeight: number; + sheetX: number; + sheetY: number; + spacing: number; + margin: number; + /** Free rotation uses {@link FREE_ROTATION_STEP}; otherwise `rotationStep`. */ + freeRotation: boolean; + rotationStep: number; + allowMirror: boolean; + keepTextUnmirrored: boolean; + leftover: 'center' | 'corner' | 'side'; + corner: Corner; + side: Side; + selectionOnly: boolean; + timeLimit: number; + engine: string; +} + +export const NEST_SETTINGS_KEY = 'openburn.nesting'; + +/** Angular step used for "free" rotation, degrees. */ +export const FREE_ROTATION_STEP = 5; + +export const DEFAULT_NEST_SETTINGS: NestSettings = { + version: 1, + sheetWidth: 300, + sheetHeight: 300, + sheetX: 0, + sheetY: 0, + spacing: 1, + margin: 2, + freeRotation: true, + rotationStep: 90, + allowMirror: false, + keepTextUnmirrored: true, + leftover: 'side', + corner: 'bottomRight', + side: 'right', + selectionOnly: true, + timeLimit: 30, + engine: DEFAULT_NEST_ENGINE, +}; + +const CORNERS: Corner[] = ['topLeft', 'topRight', 'bottomLeft', 'bottomRight']; +const SIDES: Side[] = ['top', 'bottom', 'left', 'right']; + +function num(v: unknown, fallback: number, min: number, max: number): number { + const n = typeof v === 'number' && Number.isFinite(v) ? v : fallback; + return Math.min(max, Math.max(min, n)); +} + +function bool(v: unknown, fallback: boolean): boolean { + return typeof v === 'boolean' ? v : fallback; +} + +function oneOf(v: unknown, list: readonly T[], fallback: T): T { + return list.includes(v as T) ? (v as T) : fallback; +} + +export function normalizeNestSettings(stored: unknown): NestSettings { + const s = (stored && typeof stored === 'object' ? stored : {}) as Partial; + const d = DEFAULT_NEST_SETTINGS; + return { + version: 1, + sheetWidth: num(s.sheetWidth, d.sheetWidth, 1, 10000), + sheetHeight: num(s.sheetHeight, d.sheetHeight, 1, 10000), + sheetX: num(s.sheetX, d.sheetX, -10000, 10000), + sheetY: num(s.sheetY, d.sheetY, -10000, 10000), + spacing: num(s.spacing, d.spacing, 0, 100), + margin: num(s.margin, d.margin, 0, 1000), + freeRotation: bool(s.freeRotation, d.freeRotation), + rotationStep: num(s.rotationStep, d.rotationStep, 0, 360), + allowMirror: bool(s.allowMirror, d.allowMirror), + keepTextUnmirrored: bool(s.keepTextUnmirrored, d.keepTextUnmirrored), + leftover: oneOf(s.leftover, ['center', 'corner', 'side'] as const, d.leftover), + corner: oneOf(s.corner, CORNERS, d.corner), + side: oneOf(s.side, SIDES, d.side), + selectionOnly: bool(s.selectionOnly, d.selectionOnly), + timeLimit: num(s.timeLimit, d.timeLimit, 1, 3600), + engine: typeof s.engine === 'string' && s.engine ? s.engine : d.engine, + }; +} + +function storage(): Storage | null { + try { + return typeof localStorage !== 'undefined' ? localStorage : null; + } catch { + return null; + } +} + +export function loadNestSettings(store: Storage | null = storage()): NestSettings { + try { + const raw = store?.getItem(NEST_SETTINGS_KEY); + return normalizeNestSettings(raw ? JSON.parse(raw) : null); + } catch { + return { ...DEFAULT_NEST_SETTINGS }; + } +} + +export function saveNestSettings(settings: NestSettings, store: Storage | null = storage()): void { + try { + store?.setItem(NEST_SETTINGS_KEY, JSON.stringify(settings)); + } catch { + /* storage full or blocked: settings simply are not remembered */ + } +} + +export function leftoverMode(s: NestSettings): LeftoverMode { + if (s.leftover === 'corner') return { kind: 'corner', corner: s.corner }; + if (s.leftover === 'side') return { kind: 'side', side: s.side }; + return { kind: 'center' }; +} + +/** Engine options for a run (seed and variant are filled in per worker). */ +export function nestOptions(s: NestSettings): NestOptions { + return { + spacing: s.spacing, + margin: s.margin, + rotationStep: s.freeRotation ? FREE_ROTATION_STEP : s.rotationStep, + allowMirror: s.allowMirror, + leftover: leftoverMode(s), + commonLine: false, + timeLimit: s.timeLimit, + seed: 1, + variant: 0, + }; +} diff --git a/src/nesting/types.ts b/src/nesting/types.ts new file mode 100644 index 0000000..cb41fa7 --- /dev/null +++ b/src/nesting/types.ts @@ -0,0 +1,138 @@ +/** + * Nesting (auto-arrange) data model. + * + * The engines only see plain polygons in millimetres: they know nothing about + * Fabric, Paper or the UI. That keeps them testable in Node and lets several + * engines (the raster engine shipped today, a physics "gravity + shake" engine + * later…) plug into the same dialog through {@link NestEngine}. + * + * Coordinates are scene coordinates: millimetres, Y pointing down. + */ + +export interface Pt { + x: number; + y: number; +} + +/** A closed polygon (the closing edge last → first is implicit). */ +export type Ring = Pt[]; + +/** + * One rigid piece to place. All sub-shapes move together. + * + * - `rings` is the cut silhouette, filled with the even-odd rule, so inner + * rings are through holes other parts may be nested into. + * - `solids` are closed shapes filled on their own (engravings, text boxes): + * they never create holes. + * - `lines` are open polylines (scores, engraved strokes) that must stay clear + * of other parts but enclose nothing. + */ +export interface NestPart { + id: string; + rings: Ring[]; + solids: Ring[]; + lines: Pt[][]; + /** False when the part must never be mirrored (it holds readable text…). */ + canMirror: boolean; + /** Copies to place. The placement ids are `${id}#${copyIndex}` beyond 1. */ + quantity: number; +} + +/** The board the parts are nested into, in scene coordinates. */ +export interface NestSheet { + x: number; + y: number; + width: number; + height: number; + /** Reserved for scrap nesting (V2): zones already used on the board. */ + obstacles?: Ring[]; +} + +export type Corner = 'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight'; +export type Side = 'top' | 'bottom' | 'left' | 'right'; + +/** Where the reusable offcut should end up. */ +export type LeftoverMode = + | { kind: 'center' } + | { kind: 'corner'; corner: Corner } + | { kind: 'side'; side: Side }; + +export interface NestOptions { + /** Minimum distance between two parts, mm. */ + spacing: number; + /** Minimum distance between a part and the sheet edge, mm. */ + margin: number; + /** Rotation step in degrees. 0 = never rotate; free rotation uses a fine step. */ + rotationStep: number; + allowMirror: boolean; + leftover: LeftoverMode; + /** + * Common-line cutting (V2): parts may share a straight cut. Not exposed in + * the UI yet; engines must ignore it until they support it. + */ + commonLine: boolean; + /** Search budget in seconds; the engine returns its best result after it. */ + timeLimit: number; + /** Seed for the engine's pseudo-random generator (reproducible runs). */ + seed: number; + /** Variant index so parallel workers explore different strategies. */ + variant: number; +} + +/** + * Final position of one part: mirror (x → -x) first, then rotate clockwise by + * `angle` degrees around the scene origin, then translate by (x, y). + */ +export interface Placement { + partId: string; + angle: number; + mirrored: boolean; + x: number; + y: number; +} + +/** Two parts sharing a straight cut (V2, common-line cutting). */ +export interface SharedEdge { + a: string; + b: string; + from: Pt; + to: Pt; +} + +export interface LeftoverInfo { + /** Largest empty axis-aligned rectangle on the sheet, mm. */ + width: number; + height: number; + x: number; + y: number; +} + +export interface NestResult { + placements: Placement[]; + /** Part ids that did not fit on the sheet. */ + unplaced: string[]; + /** Part area / sheet area, 0..1. */ + utilization: number; + /** Lower is better; only comparable between runs with the same inputs. */ + score: number; + leftover: LeftoverInfo | null; + sharedEdges: SharedEdge[]; + evaluations: number; + elapsedMs: number; +} + +export interface NestEngine { + id: string; + label: string; + /** + * Search placements. Must call `onProgress` with every improved result, stop + * quickly when `signal` aborts and resolve with the best result found. + */ + run( + parts: NestPart[], + sheet: NestSheet, + options: NestOptions, + onProgress: (best: NestResult) => void, + signal: AbortSignal, + ): Promise; +} diff --git a/src/state/store.ts b/src/state/store.ts index d220889..28937c6 100644 --- a/src/state/store.ts +++ b/src/state/store.ts @@ -11,6 +11,8 @@ import { import { DEFAULT_DEVICE, DEFAULT_OPTIMIZATION, type DeviceConfig, type JobPlan, type OptimizationSettings } from '@/gcode/types'; import { isBedOrigin } from '@/gcode/origin'; import type { TraceOptions } from '@/image/trace'; +import type { ExtractOptions } from '@/nesting/extract'; +import type { NestPart, NestResult } from '@/nesting/types'; import type { LiveMeasure } from '@/workspace/measure'; import type { SnapKind } from '@/workspace/snap'; import { DEFAULT_SNAP_SETTINGS, loadSnapSettings, saveSnapSettings, type SnapSettings } from './snapSettings'; @@ -476,6 +478,10 @@ export interface WorkspaceApi { traceSelectedImage(options: TraceOptions): Promise; applyMaskToImage(): Promise; addTabs(tabWidth: number, spacing: number): void; + /** Nesting: rigid parts from the selection (or every object) in scene mm. */ + collectNestParts(selectionOnly: boolean, options: ExtractOptions): { parts: NestPart[]; skipped: number }; + /** Nesting: move the collected objects to a result's placements (one undo step). */ + applyNestResult(result: NestResult, sheet: { x: number; y: number; width: number }): void; updateCursor(x: number, y: number): void; setStatus(text: string): void; } diff --git a/src/styles/global.css b/src/styles/global.css index d05e7d6..3171a99 100644 --- a/src/styles/global.css +++ b/src/styles/global.css @@ -1383,3 +1383,120 @@ input[type='color'].layer-swatch::-webkit-color-swatch { font-size: 12.5px; color: var(--text); } + +/* ---------------------------------------------------------------- nesting */ + +.nest-layout { + display: flex; + gap: 14px; + align-items: flex-start; +} + +.nest-settings { + flex: 0 0 330px; + min-width: 0; +} + +.nest-heading { + margin: 10px 0 5px; + font-size: 11px; + color: var(--text-dim); + text-transform: uppercase; + letter-spacing: 0.04em; +} + +.nest-heading:first-child { + margin-top: 0; +} + +.nest-label { + min-width: 92px; +} + +.nest-indent { + margin-left: 18px; +} + +.checkbox.disabled { + opacity: 0.5; +} + +.nest-gap { + margin-top: 6px; +} + +.nest-preview-col { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + gap: 8px; +} + +.nest-preview { + width: 100%; + aspect-ratio: 1; + background: var(--bg-input); + border: 1px solid var(--border); + border-radius: 2px; +} + +.nest-sheet { + fill: #3a352c; + stroke: var(--text-faint); + stroke-width: 1; + vector-effect: non-scaling-stroke; +} + +.nest-offcut { + fill: var(--green); + fill-opacity: 0.18; + stroke: var(--green); + stroke-dasharray: 4 3; + stroke-width: 1; + vector-effect: non-scaling-stroke; +} + +.nest-part { + fill: var(--accent); + fill-opacity: 0.35; + stroke: var(--accent-soft); + stroke-width: 1; + vector-effect: non-scaling-stroke; +} + +.nest-summary p { + margin: 0 0 4px; + font-size: 11.5px; +} + +.nest-warning { + color: var(--yellow); +} + +@media (max-width: 760px) { + .nest-layout { + flex-direction: column; + } + .nest-settings { + flex-basis: auto; + width: 100%; + } +} + +.nest-settings .checkbox { + display: flex; + margin-bottom: 4px; +} + +.nest-settings .seg-control button { + white-space: nowrap; +} + +.nest-settings .field-row .seg-control { + flex: 1; +} + +.nest-settings .seg-control button { + padding: 0 8px; +} diff --git a/src/ui/MenuBar.tsx b/src/ui/MenuBar.tsx index 9de99c0..c94de71 100644 --- a/src/ui/MenuBar.tsx +++ b/src/ui/MenuBar.tsx @@ -5,6 +5,7 @@ import { useRecentFiles, clearRecentFiles } from '@/state/recentStore'; import { Icon } from './icons'; import { Modal, NumberField, useUnits, useWorkspace } from './common'; import { ImageAdjustDialog, TabsDialog, TraceDialog } from './ImageToolsDialogs'; +import { NestingDialog } from './panels/NestingDialog'; import { MATERIALS_UPDATED_EVENT, loadMaterials, @@ -22,7 +23,8 @@ type DialogKind = | 'kerf' | 'image-adjust' | 'trace' - | 'tabs'; + | 'tabs' + | 'nesting'; interface MenuEntry { label?: string; @@ -142,6 +144,8 @@ const MENUS: MenuDef[] = [ { label: 'Distribute Horizontally', action: () => ws?.distribute('h'), disabled: selectionCount < 3 }, { label: 'Distribute Vertically', action: () => ws?.distribute('v'), disabled: selectionCount < 3 }, { separator: true }, + { label: 'Nesting…', dialog: 'nesting' }, + { separator: true }, { label: 'Bring to Front', action: () => ws?.bringToFront(), disabled: !hasSelection }, { label: 'Send to Back', action: () => ws?.sendToBack(), disabled: !hasSelection }, ], @@ -876,6 +880,7 @@ export function MenuBar() { {dialog === 'image-adjust' && setDialog(null)} />} {dialog === 'trace' && setDialog(null)} />} {dialog === 'tabs' && setDialog(null)} />} + {dialog === 'nesting' && setDialog(null)} />} {dialog === 'about' && ( setDialog(null)} width={420}> diff --git a/src/ui/panels/NestingDialog.test.tsx b/src/ui/panels/NestingDialog.test.tsx new file mode 100644 index 0000000..216e802 --- /dev/null +++ b/src/ui/panels/NestingDialog.test.tsx @@ -0,0 +1,111 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { render, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { NEST_SETTINGS_KEY } from '@/nesting/settings'; +import type { NestPart, NestResult } from '@/nesting/types'; +import { NestingDialog } from './NestingDialog'; + +const PART: NestPart = { + id: 'part-0', + rings: [ + [ + { x: 0, y: 0 }, + { x: 10, y: 0 }, + { x: 10, y: 10 }, + { x: 0, y: 10 }, + ], + ], + solids: [], + lines: [], + canMirror: true, + quantity: 1, +}; + +const RESULT: NestResult = { + placements: [{ partId: 'part-0', angle: 0, mirrored: false, x: 2, y: 2 }], + unplaced: [], + utilization: 0.25, + score: 1, + leftover: { x: 20, y: 0, width: 280, height: 300 }, + sharedEdges: [], + evaluations: 42, + elapsedMs: 10, +}; + +const mocks = vi.hoisted(() => ({ + collectNestParts: vi.fn(), + applyNestResult: vi.fn(), + startNesting: vi.fn(), +})); + +vi.mock('@/ui/common', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + useWorkspace: () => ({ + collectNestParts: mocks.collectNestParts, + applyNestResult: mocks.applyNestResult, + }), + }; +}); + +vi.mock('@/nesting/runner', () => ({ startNesting: mocks.startNesting })); + +beforeEach(() => { + localStorage.clear(); + mocks.collectNestParts.mockReset(); + mocks.applyNestResult.mockReset(); + mocks.startNesting.mockReset(); + mocks.startNesting.mockImplementation(({ onProgress }) => { + onProgress({ best: RESULT, evaluations: 42 }); + return { done: Promise.resolve(RESULT), stop: vi.fn() }; + }); +}); + +describe('NestingDialog', () => { + it('asks for a selection when there is nothing to nest', async () => { + mocks.collectNestParts.mockReturnValue({ parts: [], skipped: 0 }); + render(); + await userEvent.click(screen.getByRole('button', { name: 'Start' })); + expect(screen.getByText(/Select the parts to nest first/)).toBeInTheDocument(); + expect(mocks.startNesting).not.toHaveBeenCalled(); + expect(screen.getByRole('button', { name: 'Apply' })).toBeDisabled(); + }); + + it('runs the search with the dialog settings and applies the result', async () => { + mocks.collectNestParts.mockReturnValue({ parts: [PART], skipped: 0 }); + const onClose = vi.fn(); + render(); + await userEvent.click(screen.getByRole('button', { name: 'Corner' })); + await userEvent.click(screen.getByRole('button', { name: 'Start' })); + + expect(mocks.collectNestParts).toHaveBeenCalledWith(true, { keepTextUnmirrored: true }); + const call = mocks.startNesting.mock.calls[0][0]; + expect(call.sheet).toEqual({ x: 0, y: 0, width: 300, height: 300 }); + expect(call.options.leftover).toEqual({ kind: 'corner', corner: 'bottomRight' }); + expect(call.options.commonLine).toBe(false); + + const summary = () => document.querySelector('.nest-summary')?.textContent ?? ''; + await waitFor(() => expect(summary()).toMatch(/25% of the sheet used · 1\/1 parts/)); + expect(screen.getByText(/Largest offcut: 280 × 300 mm/)).toBeInTheDocument(); + await waitFor(() => expect(screen.getByRole('button', { name: 'Restart' })).toBeInTheDocument()); + + await userEvent.click(screen.getByRole('button', { name: 'Apply' })); + expect(mocks.applyNestResult).toHaveBeenCalledWith(RESULT, call.sheet); + expect(onClose).toHaveBeenCalled(); + }); + + it('remembers the settings and hides options that do not apply', async () => { + render(); + expect(screen.queryByText('Engine')).not.toBeInTheDocument(); + expect(screen.queryByText('Rotation step')).not.toBeInTheDocument(); + await userEvent.click(screen.getByRole('checkbox', { name: 'Free rotation' })); + expect(screen.getByText('Rotation step')).toBeInTheDocument(); + expect(screen.getByRole('checkbox', { name: 'Never mirror parts with text' })).toBeDisabled(); + await userEvent.click(screen.getByRole('checkbox', { name: 'Allow mirrored parts' })); + expect(screen.getByRole('checkbox', { name: 'Never mirror parts with text' })).toBeEnabled(); + const stored = JSON.parse(localStorage.getItem(NEST_SETTINGS_KEY)!); + expect(stored.freeRotation).toBe(false); + expect(stored.allowMirror).toBe(true); + }); +}); diff --git a/src/ui/panels/NestingDialog.tsx b/src/ui/panels/NestingDialog.tsx new file mode 100644 index 0000000..0a34319 --- /dev/null +++ b/src/ui/panels/NestingDialog.tsx @@ -0,0 +1,423 @@ +import { useEffect, useMemo, useRef, useState } from 'react'; +import { applyAffine, placementMatrix, simplify } from '@/nesting/geometry'; +import { listNestEngines } from '@/nesting/registry'; +import { startNesting, type NestRun } from '@/nesting/runner'; +import { + loadNestSettings, + nestOptions, + saveNestSettings, + type NestSettings, +} from '@/nesting/settings'; +import type { Corner, NestPart, NestResult, NestSheet, Side } from '@/nesting/types'; +import { Modal, NumberField, SegControl, useUnits, useWorkspace } from '../common'; + +const CORNER_LABEL: Record = { + topLeft: 'Top left', + topRight: 'Top right', + bottomLeft: 'Bottom left', + bottomRight: 'Bottom right', +}; + +const SIDE_LABEL: Record = { + top: 'Top', + bottom: 'Bottom', + left: 'Left', + right: 'Right', +}; + +const ROTATION_STEPS = [0, 90, 45, 30, 15, 10]; + +interface RunState { + parts: NestPart[]; + sheet: NestSheet; + result: NestResult | null; + evaluations: number; + running: boolean; +} + +/** + * Nesting (auto-arrange): pack the selected parts on a board so the offcut is + * as large and as reusable as possible. The search runs in Web Workers and + * the best layout so far is previewed live; nothing moves until Apply. + */ +export function NestingDialog({ onClose }: { onClose: () => void }) { + const ws = useWorkspace(); + const units = useUnits(); + const [settings, setSettings] = useState(() => loadNestSettings()); + const [run, setRun] = useState(null); + const [message, setMessage] = useState(null); + const runRef = useRef(null); + const engines = useMemo(() => listNestEngines(), []); + + const update = (patch: Partial) => { + const next = { ...settings, ...patch }; + setSettings(next); + saveNestSettings(next); + // A finished layout no longer matches the new settings. + if (!run?.running) setRun(null); + }; + + useEffect(() => () => runRef.current?.stop(), []); + + const start = () => { + if (!ws) return; + const { parts, skipped } = ws.collectNestParts(settings.selectionOnly, { + keepTextUnmirrored: settings.keepTextUnmirrored, + }); + if (parts.length === 0) { + setMessage( + settings.selectionOnly + ? 'Select the parts to nest first, or choose “All objects”.' + : 'There is nothing to nest on the canvas.', + ); + return; + } + setMessage(skipped > 0 ? `${skipped} object(s) without geometry were left out.` : null); + const sheet: NestSheet = { + x: settings.sheetX, + y: settings.sheetY, + width: settings.sheetWidth, + height: settings.sheetHeight, + }; + setRun({ parts, sheet, result: null, evaluations: 0, running: true }); + const handle = startNesting({ + engine: settings.engine, + parts, + sheet, + options: nestOptions(settings), + onProgress: ({ best, evaluations }) => + setRun((r) => (r ? { ...r, result: best, evaluations } : r)), + }); + runRef.current = handle; + void handle.done.then((best) => { + if (runRef.current !== handle) return; + runRef.current = null; + setRun((r) => (r ? { ...r, result: best ?? r.result, running: false } : r)); + }); + }; + + const stop = () => runRef.current?.stop(); + + const apply = () => { + if (!ws || !run?.result) return; + ws.applyNestResult(run.result, run.sheet); + onClose(); + }; + + const close = () => { + runRef.current?.stop(); + onClose(); + }; + + const result = run?.result ?? null; + const running = run?.running ?? false; + const numberRow = (label: string, key: keyof NestSettings, title?: string) => ( +
+ {label} + update({ [key]: Math.max(0, v) } as Partial)} + units={units} + /> + {units} +
+ ); + + return ( + + + {running ? ( + + ) : ( + + )} + + + } + > +
+
+

Sheet

+
+ Size + update({ sheetWidth: Math.max(1, v) })} units={units} /> + × + update({ sheetHeight: Math.max(1, v) })} units={units} /> + {units} +
+
+ Position + update({ sheetX: v })} units={units} /> + , + update({ sheetY: v })} units={units} /> + {units} +
+ +

Spacing

+ {numberRow('Between parts', 'spacing', 'Minimum distance between two parts')} + {numberRow('Sheet margin', 'margin', 'Minimum distance between a part and the sheet edge')} + +

Parts

+
+ Nest + update({ selectionOnly: v === 'selection' })} + /> +
+ + {!settings.freeRotation && ( +
+ Rotation step + +
+ )} + + + +

Offcut

+ update({ leftover: v })} + /> + {settings.leftover === 'corner' && ( +
+ Free corner + +
+ )} + {settings.leftover === 'side' && ( +
+ Free side + +
+ )} + +

Search

+
+ Time limit + update({ timeLimit: Math.max(1, Number(e.target.value) || 1) })} + /> + s +
+ {engines.length > 1 && ( +
+ Engine + +
+ )} +
+ +
+ + +
+
+
+ ); +} + +function NestSummary({ run, message }: { run: RunState | null; message: string | null }) { + const result = run?.result ?? null; + return ( +
+ {message &&

{message}

} + {!run && !message &&

Press Start to search for a layout.

} + {run && !result &&

Preparing {run.parts.length} parts…

} + {result && ( + <> +

+ {Math.round(result.utilization * 1000) / 10}% of the sheet used ·{' '} + {result.placements.length}/{run!.parts.length} parts + {run!.running ? ` · ${run!.evaluations} layouts tried…` : ` · ${run!.evaluations} layouts tried`} +

+ {result.leftover && ( +

+ Largest offcut: {Math.floor(result.leftover.width)} × {Math.floor(result.leftover.height)} mm +

+ )} + {result.unplaced.length > 0 && ( +

+ {result.unplaced.length} part(s) do not fit; they will be placed next to the sheet. +

+ )} + + )} +
+ ); +} + +/** Live SVG preview of the sheet, the parts' cut outlines and the offcut. */ +function NestPreview({ + parts, + sheet, + result, +}: { + parts: NestPart[] | null; + sheet: NestSheet; + result: NestResult | null; +}) { + // Lightweight outlines for the preview (the engine keeps full precision). + const outlines = useMemo(() => { + const map = new Map(); + for (const p of parts ?? []) { + const rings = p.rings.length > 0 ? p.rings : p.solids; + map.set( + p.id, + rings.map((r) => simplify(r, 0.2)), + ); + } + return map; + }, [parts]); + + const paths = useMemo(() => { + if (!result) return []; + return result.placements.map((pl) => { + const m = placementMatrix(pl); + const rings = outlines.get(pl.partId.split('#')[0]) ?? []; + const d = rings + .map( + (r) => + 'M' + + r + .map((p) => { + const q = applyAffine(m, p); + return `${(q.x - sheet.x).toFixed(2)} ${(q.y - sheet.y).toFixed(2)}`; + }) + .join('L') + + 'Z', + ) + .join(''); + return { id: pl.partId, d }; + }); + }, [result, outlines, sheet.x, sheet.y]); + + const pad = Math.max(sheet.width, sheet.height) * 0.02; + return ( + + + {result?.leftover && ( + + )} + {paths.map((p) => ( + + ))} + + ); +} diff --git a/src/workspace/WorkspaceController.ts b/src/workspace/WorkspaceController.ts index 189ea53..1690194 100644 --- a/src/workspace/WorkspaceController.ts +++ b/src/workspace/WorkspaceController.ts @@ -45,6 +45,9 @@ import { requestDiscardConfirmation } from '@/state/discardGuard'; import { booleanObjects, isConvertible, objectToPathData } from '@/geometry/paperOps'; import { offsetPathData } from '@/geometry/offset'; import { objectContours } from '@/gcode/geometry'; +import { applySceneTransform, partFromObject, type ExtractOptions } from '@/nesting/extract'; +import { placementMatrix } from '@/nesting/geometry'; +import type { NestPart, NestResult } from '@/nesting/types'; import { parseDxf } from '@/core/dxf'; import { prepareSvgForImport, applySvgPhysicalSize } from '@/io/svg'; import { findImageLayer } from './layers'; @@ -2339,6 +2342,73 @@ export class WorkspaceController implements WorkspaceApi { this.reselect(objs); } + // ------------------------------------------------------------------------- + // Nesting (auto-arrange) + // ------------------------------------------------------------------------- + + /** Objects behind the parts handed to the nesting dialog, by part id. */ + private nestObjects = new Map(); + + collectNestParts( + selectionOnly: boolean, + options: ExtractOptions, + ): { parts: NestPart[]; skipped: number } { + const source = selectionOnly + ? this.canvas.getActiveObjects() + : this.canvas.getObjects().filter((o) => !this.isNodeHandle(o) && !o.excludeFromExport); + this.nestObjects = new Map(); + const parts: NestPart[] = []; + let skipped = 0; + source.forEach((obj, i) => { + const id = `part-${i}`; + const part = partFromObject(obj, id, options); + if (!part) { + skipped += 1; + return; + } + this.nestObjects.set(id, obj); + parts.push(part); + }); + return { parts, skipped }; + } + + /** + * Move the collected objects to their nested positions in one undo step. + * Parts that did not fit are lined up to the right of the sheet. + */ + applyNestResult(result: NestResult, sheet: { x: number; y: number; width: number }): void { + const moved: FabricObject[] = []; + this.canvas.discardActiveObject(); + for (const placement of result.placements) { + const obj = this.nestObjects.get(placement.partId); + if (!obj) continue; + applySceneTransform(obj, placementMatrix(placement)); + moved.push(obj); + } + let cursorY = sheet.y; + for (const id of result.unplaced) { + const obj = this.nestObjects.get(id); + if (!obj) continue; + const r = obj.getBoundingRect(); + obj.set({ + left: (obj.left ?? 0) + sheet.x + sheet.width + 10 - r.left, + top: (obj.top ?? 0) + cursorY - r.top, + }); + obj.setCoords(); + cursorY += r.height + 5; + moved.push(obj); + } + if (moved.length === 0) return; + this.reselect(moved); + this.afterChange(); + const pct = Math.round(result.utilization * 100); + this.setStatus( + result.unplaced.length > 0 + ? `Nested ${result.placements.length} parts (${pct}% of the sheet), ${result.unplaced.length} did not fit` + : `Nested ${result.placements.length} parts (${pct}% of the sheet)`, + ); + } + /** Ctrl+Shift+I — select everything that is not currently selected. */ invertSelection(): void { const selected = new Set(this.canvas.getActiveObjects()); diff --git a/vite.config.ts b/vite.config.ts index 192366d..b7c3ff2 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -11,6 +11,8 @@ const pkg = JSON.parse( export default defineConfig({ plugins: [react()], + // The nesting worker is an ES module (`new Worker(url, { type: 'module' })`). + worker: { format: 'es' }, base: './', define: { __APP_VERSION__: JSON.stringify(pkg.version),