Ply Cutter

The Divider Designer starts with a grid. This tool starts with a model: import a closed solid or an STL made from flat panels, add finger joints, and lay the pieces out for a laser cutter.

The idea comes from Tuomas Lukka's Plycutter. This is an independent browser implementation for flat panels, including sloped faces and angled joints. Choose Closed solid → panels for a cube, box, or other model with planar faces: its outer faces become boards, with your chosen thickness growing inward. A solid cube becomes six boards with twelve finger-jointed edges, keeping its outside dimensions and gaining a hollow interior. The whole model can be rotated in space.

Choose Existing sheet panels when the STL already contains material at its final thickness. This mode detects those boards instead of creating a shell. The laser paths use square cuts through the sheet. Angled joints use wider relief slots, so seams have visible gaps rather than bevelled edges. Internal crossings need a different assembly strategy. This tool does not approximate curved surfaces or slice sculptures into stacked layers.

Everything happens on your device. The STL is not uploaded. Start with Load solid cube or Load panel corner, then import your own model. Confirm the displayed dimensions: STL files do not store units. Use the model scale factor to correct the size before generating; a cube shown as 2 × 2 × 2 mm becomes 100 × 100 × 100 mm at a factor of 50. Measure your plywood and enter its actual thickness.

Repair on import removes collapsed or tiny invalid facets and repeated triangles with the same winding, without moving any vertices. The report lists their original facet numbers and checks the remaining edges. A mesh can look normal in Blender while containing zero-area triangles, duplicate surfaces, or internal faces. Open boundaries, edges shared by more than two faces, and winding conflicts remain visible in the report and block conversion. Overlapping parts may need a Boolean Union in the source model. A cleaned STL download is available only when these checks pass; it uses the displayed millimetre dimensions.

From model to cutting file

Export a closed, consistently wound STL. In Closed solid mode, coplanar triangles merge into panel faces, which are thickened inward. Buried material is added around concave corners so the boards can meet. The tool checks that thickness leaves room for an interior and that the shell stays inside the source solid. Narrow features may need a thinner material or a larger model. Panels stay within the original envelope within the geometry tolerance; the original solid interior is replaced with a hollow panel assembly. Square-cut angled edges are trimmed inward and can leave gaps at seams. Very shallow angles may not leave enough material for fingers.

Holes already modeled in the STL remain inner cutting contours, including round and rectangular openings. In solid mode, connected tunnel walls between hole mouths are omitted: a round hole does not become a ring of tiny boards. Blind pockets are rejected because a 2D laser path would cut them all the way through. Keep openings inside panel faces and away from finger joints; an opening that divides a panel is rejected. Openings close to a seam can weaken or remove fingers, so inspect the preview before cutting. This version imports holes; it does not draw new holes in the interface.

In Existing sheet panels mode, model the connected boards at their actual thickness. The tool pairs opposing planar faces, reconstructs the boards, compares their union volume with the original mesh, and checks sampled points on every input face against those boards. Substantial pockets or mixed thicknesses are rejected in this mode.

Floating-point geometry needs a tolerance: volume differences below 0.1% of model volume (or 0.05 cubic mm for very small models) can pass. Solid mode aligns nominally perpendicular face coordinates within at most 0.005 mm and welds projected endpoints within 0.001 mm. These checks can miss very small features; they are not a proof that a complicated assembly can be put together. A fully closed box may require a specific assembly order, glue, or a separately designed removable lid.

Red paths are cuts. Optional blue part names are engraving paths, drawn as strokes so the SVG and DXF need no fonts. SVG files have explicit millimetre dimensions; DXF files declare millimetres. Import at 1:1, assign the two colours/layers to your laser's cut and engrave operations, and set power and speed in your laser software. Files contain geometry, not machine instructions.

Kerf is the full measured cut width. The tool offsets cutting paths outward by half that value, including shrinking hole paths. Leave kerf at zero if your laser software compensates it. At angled joints, slot width accounts for the projected overlap across the full sheet thickness. Small detached corner offcuts, each no larger than a material-thickness square, are removed from the finished part and reported. Joint subtraction includes 0.004 mm of numerical clearance; this is separate from kerf compensation. Test a small joint in scrap material first. Parts must fit wholly on a bed; the layout adds sheets rather than scaling or splitting parts. Preview and export use the same contours. Part names are omitted where there is no clear engraving area; the parts table reports this.

Set Finger segments per joint to an odd count (3, 5, 7…) for an exact pattern, or leave it at 0 to derive the count from Target finger width. The count describes alternating segments along the shared edge: five segments give two fingers on one piece and three on its mate. The tool reports the actual width and rejects fingers narrower than the material.

After generation, select a piece from the colour legend, 3D assembly, cutting layout, or parts table. Piece IDs such as P1 match the optional engraved IDs. Show piece IDs controls the preview overlays separately from engraving. The panel detail view enlarges that piece and marks its shared joints as J1, J2, and so on; select a marked joint or its dropdown entry to edit it, or apply a setting to all joints touching the selected piece.

Joint overrides belong to the shared edge. Editing a count or width from either mating panel updates both sides together. A neighboring panel shows that same override; it cannot silently acquire a conflicting pattern. Kerf and inclusion of the piece's engraved ID are local to each panel. Thickness remains global because this version uses one sheet material. Apply records a change; Generate panels recomputes the geometry. Pending edits keep the previous preview marked as out of date and disable cutting downloads. A new source, units, scale, input mode, import-repair setting, or thickness clears local overrides so they cannot transfer to a different piece accidentally. Settings are kept for the current page session.

This first version runs calculations on the browser's main thread. Large meshes can pause the interface. Input is limited to 10 MiB, 10,000 triangles, 256 face planes, and 32 panels; small, simple models work best.

An Org library

The named ply-cutter-core block has no DOM or file-picker dependency. It accepts triangle arrays in millimetres and returns panel contours, joint information, and bed layouts. Use createPanels(triangles, settings, { mode: 'solid' }) to create a shell, or omit the third argument to detect existing panels. That is the boundary for a future JSCAD pipeline; the upload interface is only one caller. The JSCAD integration itself is for later.

Reusable panel conversion and export library
import modeling from '@jscad/modeling';

const { booleans, geometries, primitives, measurements, extrusions, transforms, expansions } = modeling;
type Shape2 = ReturnType<typeof primitives.polygon>;
export type V2 = [number, number];
export type V3 = [number, number, number];
export type Triangle = [V3, V3, V3];
export type InputMode = 'panels' | 'solid';
export type JointSettings = { fingerCount?: number; fingerWidth?: number };
export type PanelSettings = { kerf?: number; engrave?: boolean };
export type ConversionOptions = {
  mode?: InputMode; holeWalls?: 'open' | 'panels';
  jointSettings?: Record<string, JointSettings>; panelSettings?: Record<string, PanelSettings>;
};
export type Settings = {
  thickness: number; fingerWidth: number; kerf: number;
  fingerCount?: number;
  bedWidth: number; bedHeight: number; margin: number; gap: number;
};
export const defaults: Settings = {
  thickness: 3, fingerWidth: 10, kerf: 0,
  bedWidth: 500, bedHeight: 300, margin: 5, gap: 5,
};
export type Panel = {
  id: string; normal: V3; u: V3; v: V3; distance: number;
  outward?: V3; kerf?: number; engrave?: boolean;
  outlines: V2[][]; cutOutlines: V2[][];
};
export type Joint = { id: string; key: string; a: string; b: string; fingers: number; length: number; pitch: number; segment: [V3,V3] };
export type Placement = { panel: number; x: number; y: number; width: number; height: number; rotated: boolean; min: V2 };
export type Sheet = { placements: Placement[] };
export type Result = { panels: Panel[]; joints: Joint[]; sheets: Sheet[]; settings: Settings; warnings: string[]; mode: InputMode };

const add = (a: V3, b: V3): V3 => [a[0]+b[0], a[1]+b[1], a[2]+b[2]];
const mul = (a: V3, n: number): V3 => [a[0]*n, a[1]*n, a[2]*n];
const sub = (a: V3, b: V3): V3 => add(a, mul(b, -1));
const dot = (a: V3, b: V3) => a[0]*b[0]+a[1]*b[1]+a[2]*b[2];
const cross = (a: V3, b: V3): V3 => [a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]];
const length = (a: V3) => Math.hypot(...a);
const unit = (a: V3) => mul(a, 1/length(a));
const area = (s: Shape2) => Math.abs(measurements.measureArea(s));
const EPS = 1e-5;
const fail = (message: string): never => { throw new Error(message); };
const signedArea = (p: V2[]) => p.reduce((s, a, i) => { const b=p[(i+1)%p.length]; return s+a[0]*b[1]-b[0]*a[1]; }, 0)/2;
const polygon = (p: V2[]): Shape2 => primitives.polygon({ points: signedArea(p) < 0 ? [...p].reverse() : p });
const union2 = (shapes: Shape2[]): Shape2 => shapes.length === 1 ? shapes[0] : booleans.union(...shapes) as Shape2;
const bounds = (outlines: V2[][]): { min: V2; width: number; height: number } => {
  const points=outlines.flat();
  if (!points.length) return fail('A panel disappeared. Reduce kerf or check the model.');
  let x=Infinity,y=Infinity,X=-Infinity,Y=-Infinity;
  for (const p of points) { x=Math.min(x,p[0]); y=Math.min(y,p[1]); X=Math.max(X,p[0]); Y=Math.max(Y,p[1]); }
  return { min:[x,y], width:X-x, height:Y-y };
};
const outlines = (s: Shape2): V2[][] => geometries.geom2.toOutlines(s).map(loop => loop.map(p => [p[0],p[1]]));
function components(s: Shape2): Shape2[] {
  const loops=outlines(s), holes=loops.filter(l=>signedArea(l)<0);
  return loops.filter(l=>signedArea(l)>0).map(outer=>{
    const shell=polygon(outer),cuts=holes.filter(h=>inside(h[0],[outer])).map(polygon);
    return cuts.length?booleans.subtract(shell,...cuts) as Shape2:shell;
  });
}

export function validateSettings(s: Settings): void {
  for (const key of Object.keys(defaults) as (keyof Settings)[]) if (!Number.isFinite(s[key])) fail(`${key} must be a finite number.`);
  if (s.thickness < 0.2 || s.thickness > 50) fail('Thickness must be between 0.2 and 50 mm.');
  validateFingerCount(s.fingerCount??0);
  if (s.fingerWidth < ((s.fingerCount??0)>0?0.2:s.thickness) || s.fingerWidth > 500) fail('Finger width must be at least the material thickness and at most 500 mm.');
  if (s.kerf < 0 || s.kerf >= s.thickness/2) fail('Kerf must be non-negative and less than half the thickness.');
  if (s.bedWidth < 10 || s.bedHeight < 10 || s.bedWidth > 5000 || s.bedHeight > 5000) fail('Bed dimensions must be between 10 and 5000 mm.');
  if (s.margin < 0 || s.gap < Math.max(1,s.kerf*2) || s.margin*2 >= Math.min(s.bedWidth,s.bedHeight)) fail('Use a non-negative margin and a gap of at least 1 mm (and twice the kerf).');
}

function validateFingerCount(count:number):void {
  if(!Number.isInteger(count)||(count!==0&&(count<3||count>999||count%2===0)))fail('Finger count must be 0 for automatic width, or an odd integer from 3 to 999.');
}
/** Settings belong to the shared joint, regardless of which panel edits it. */
export const jointKey=(a:string,b:string):string=>[a,b].sort((x,y)=>Number(x.slice(1))-Number(y.slice(1))).join(':');

/** Binary or ASCII STL. Input units are explicit; geometry downstream is mm. */
function readSTL(data: ArrayBuffer, units: 'mm' | 'in' = 'mm', scale=1): Triangle[] {
  if (units !== 'mm' && units !== 'in') return fail('Choose mm or inches for the STL units.');
  if(!Number.isFinite(scale)||scale<=0||scale>1000000)return fail('Scale factor must be positive and at most 1,000,000.');
  if (!data.byteLength || data.byteLength > 10*1024*1024) return fail('Choose an STL smaller than 10 MiB.');
  const view = new DataView(data), triangles: Triangle[] = [];
  if (data.byteLength >= 84 && 84+view.getUint32(80,true)*50 === data.byteLength) {
    const count=view.getUint32(80,true);
    if (count > 10000) return fail('This version accepts at most 10,000 triangles. Export a simpler STL.');
    for (let i=0; i<count; i++) {
      const vertices: V3[]=[];
      for (let j=0; j<3; j++) {
        const offset=84+i*50+12+j*12;
        vertices.push([view.getFloat32(offset,true),view.getFloat32(offset+4,true),view.getFloat32(offset+8,true)]);
      }
      triangles.push(vertices as Triangle);
    }
  } else {
    const text=new TextDecoder('utf-8',{fatal:true}).decode(data);
    if (!/^\s*solid(?:\s|$)/i.test(text) || !/endsolid/i.test(text)) return fail('The file is not a complete binary or ASCII STL.');
    const facets=[...text.matchAll(/facet\s+normal[\s\S]*?endfacet/gi)];
    if (facets.length > 10000) return fail('This version accepts at most 10,000 triangles.');
    for (const facet of facets) {
      const vertices=[...facet[0].matchAll(/\bvertex\s+(\S+)\s+(\S+)\s+(\S+)/gi)].map(m => [Number(m[1]),Number(m[2]),Number(m[3])] as V3);
      if (vertices.length !== 3) return fail('An STL facet does not have three vertices.');
      triangles.push(vertices as Triangle);
    }
    const allVertices=[...text.matchAll(/\bvertex\s/gi)].length;
    if (allVertices !== triangles.length*3) return fail('The ASCII STL contains incomplete facets.');
  }
  const factor=(units === 'in' ? 25.4 : 1)*scale;
  return triangles.map(t => t.map(p => mul(p,factor)) as Triangle);
}

export type MeshReport = {
  inputTriangles: number; outputTriangles: number;
  removedDegenerate: number[]; removedDuplicates: number[];
  boundaryEdges: number; nonManifoldEdges: number; inconsistentEdges: number;
  valid: boolean; message: string;
};
export type RepairedSTL = { triangles: Triangle[]; report: MeshReport };
const vertexKey=(p:V3)=>p.map(n=>n===0?0:n).join(',');
const twiceArea=(t:Triangle)=>length(cross(sub(t[1],t[0]),sub(t[2],t[0])));
function checkCoordinates(triangles:Triangle[]):void {
  if(!triangles.length||triangles.length>10000)fail('Expected 1–10,000 triangles.');
  for(const t of triangles)if(t.length!==3||t.some(p=>p.length!==3||p.some(n=>!Number.isFinite(n)||Math.abs(n)>100000)))fail('Invalid or excessive model coordinates.');
}
function topology(triangles:Triangle[]) {
  const edges=new Map<string,{count:number;balance:number}>();
  for(const t of triangles){const keys=t.map(vertexKey);for(let i=0;i<3;i++){
    const a=keys[i],b=keys[(i+1)%3],key=a<b?`${a}|${b}`:`${b}|${a}`;
    const edge=edges.get(key)??{count:0,balance:0};edge.count++;edge.balance+=a<b?1:-1;edges.set(key,edge);
  }}
  return {
    boundaryEdges:[...edges.values()].filter(e=>e.count===1).length,
    nonManifoldEdges:[...edges.values()].filter(e=>e.count>2).length,
    inconsistentEdges:[...edges.values()].filter(e=>e.count===2&&e.balance!==0).length,
  };
}
/** Remove invalid tiny/collapsed facets and repeated facets with the same winding. No vertex is moved. */
export function repairMesh(input:Triangle[]):RepairedSTL {
  checkCoordinates(input);
  const triangles:Triangle[]=[],removedDegenerate:number[]=[],removedDuplicates:number[]=[],seen=new Set<string>();
  input.forEach((t,index)=>{
    if(twiceArea(t)<EPS*EPS){removedDegenerate.push(index+1);return;}
    const keys=t.map(vertexKey),cyclic=[keys.join('|'),[keys[1],keys[2],keys[0]].join('|'),[keys[2],keys[0],keys[1]].join('|')].sort()[0];
    if(seen.has(cyclic)){removedDuplicates.push(index+1);return;}
    seen.add(cyclic);triangles.push(t.map(p=>[...p] as V3) as Triangle);
  });
  const counts=topology(triangles),valid=triangles.length>0&&!counts.boundaryEdges&&!counts.nonManifoldEdges&&!counts.inconsistentEdges;
  const changes=`Removed ${removedDegenerate.length} collapsed/zero-area triangles and ${removedDuplicates.length} duplicate triangles. No vertices were moved.`;
  const problem=!triangles.length?'No usable triangles remain.':`${counts.boundaryEdges} open edges, ${counts.nonManifoldEdges} non-manifold edges, ${counts.inconsistentEdges} winding conflicts remain. Union overlapping parts or fix these boundaries in the source model.`;
  return {triangles,report:{inputTriangles:input.length,outputTriangles:triangles.length,removedDegenerate,removedDuplicates,...counts,valid,message:`${changes} ${valid?'The remaining mesh is closed and consistently wound.':problem}`}};
}
export function repairSTL(data:ArrayBuffer,units:'mm'|'in'='mm',scale=1):RepairedSTL {
  return repairMesh(readSTL(data,units,scale));
}
/** Strict parser remains available for callers who want rejection instead of cleanup. */
export function parseSTL(data:ArrayBuffer,units:'mm'|'in'='mm',scale=1):Triangle[] {
  const triangles=readSTL(data,units,scale);validateMesh(triangles);return triangles;
}
/** ASCII preserves the cleaned coordinates without another float32 rounding step. Units are mm. */
export function exportSTL(triangles:Triangle[]):string {
  validateMesh(triangles);
  return `solid ply_cutter_cleaned_mm\n${triangles.map(t=>{
    const n=unit(cross(sub(t[1],t[0]),sub(t[2],t[0])));
    return `facet normal ${n.join(' ')}\nouter loop\n${t.map(p=>`vertex ${p.join(' ')}`).join('\n')}\nendloop\nendfacet`;
  }).join('\n')}\nendsolid ply_cutter_cleaned_mm\n`;
}

/** Accepts triangles directly, independently of the STL parser or the DOM. */
function validateMesh(triangles: Triangle[]): void {
  checkCoordinates(triangles);
  const bad=triangles.flatMap((t,i)=>twiceArea(t)<EPS*EPS?[i+1]:[]);
  if(bad.length)fail(`The mesh contains ${bad.length} degenerate triangles (facets ${bad.slice(0,8).join(', ')}). Enable repair on import to remove collapsed facets.`);
  const counts=topology(triangles);
  if(counts.boundaryEdges||counts.nonManifoldEdges||counts.inconsistentEdges)fail(`The STL must be closed and consistently wound: ${counts.boundaryEdges} open edges, ${counts.nonManifoldEdges} non-manifold edges, ${counts.inconsistentEdges} winding conflicts. Repair or union overlapping parts before exporting.`);
}

type Board = { panel: Panel; shape: Shape2; original: Shape2 };
type Face = { n: V3; d: number; triangles: Triangle[] };
function facePlanes(triangles: Triangle[], thickness: number): Face[] {
  const faces: Face[]=[],tolerance=Math.max(EPS*10,Math.min(0.005,thickness*0.001));
  // Large facets provide more stable normals than skinny STL triangles.
  for (const t of [...triangles].sort((a,b)=>twiceArea(b)-twiceArea(a))) {
    const n=unit(cross(sub(t[1],t[0]),sub(t[2],t[0]))),d=dot(n,t[0]);
    const face=faces.find(f=>dot(f.n,n)>1-1e-8&&t.every(p=>Math.abs(dot(f.n,p)-f.d)<tolerance));
    if (face) face.triangles.push(t); else faces.push({n,d,triangles:[t]});
    if (faces.length>256) fail('Too many face planes. Use flat panels and simplify curved edges.');
  }
  return faces;
}
function canonical(n: V3): V3 {
  const axis=n.reduce((best,x,i)=>Math.abs(x)>Math.abs(n[best])?i:best,0);
  return n[axis]<0?mul(n,-1):n;
}
function sortBoards(boards: Board[]): Board[] {
  if (!boards.length) fail('No usable panels found. Check the model dimensions and material thickness.');
  if (boards.length>32) fail('This version supports up to 32 panels.');
  boards.sort((a,b)=>{
    const x=[...a.panel.normal,a.panel.distance,...bounds(a.panel.outlines).min];
    const y=[...b.panel.normal,b.panel.distance,...bounds(b.panel.outlines).min];
    for (let i=0;i<x.length;i++) if (Math.abs(x[i]-y[i])>EPS) return x[i]-y[i];
    return 0;
  });
  boards.forEach((b,i)=>{b.panel.id=`P${i+1}`;});
  return boards;
}
function basis(n: V3): { u: V3; v: V3 } {
  const reference: V3=Math.abs(n[2])<0.8 ? [0,0,1] : [0,1,0];
  const u=unit(cross(reference,n)); return {u,v:cross(n,u)};
}
const project = (p: V3, panel: Pick<Panel,'u'|'v'>): V2 => [dot(p,panel.u),dot(p,panel.v)];
export const panelPoint = (panel: Panel, p: V2): V3 => add(mul(panel.normal,panel.distance),add(mul(panel.u,p[0]),mul(panel.v,p[1])));
function boardSolid(board: Board, thickness: number) {
  const p=board.panel, o=mul(p.normal,p.distance-thickness/2);
  const matrix: Parameters<typeof transforms.transform>[0]=[...p.u,0,...p.v,0,...p.normal,0,...o,1];
  return transforms.transform(matrix,extrusions.extrudeLinear({height:thickness},board.original));
}
function onBoard(point: V3, board: Board, thickness: number): boolean {
  if (Math.abs(dot(point,board.panel.normal)-board.panel.distance)>thickness/2+0.005) return false;
  const p=project(point,board.panel),loops=board.panel.outlines;
  if (inside(p,loops)) return true;
  for (const loop of loops) for (let i=0;i<loop.length;i++) {
    const a=loop[i],b=loop[(i+1)%loop.length],dx=b[0]-a[0],dy=b[1]-a[1];
    const t=Math.max(0,Math.min(1,((p[0]-a[0])*dx+(p[1]-a[1])*dy)/(dx*dx+dy*dy||1)));
    if (Math.hypot(p[0]-a[0]-t*dx,p[1]-a[1]-t*dy)<0.005) return true;
  }
  return false;
}

function detectBoards(triangles: Triangle[], thickness: number): Board[] {
  const faces=facePlanes(triangles,thickness);
  const tolerance=Math.max(EPS*10,thickness*0.0001);
  const boards: Board[]=[];
  for (let i=0;i<faces.length;i++) for (let j=i+1;j<faces.length;j++) {
    const a=faces[i],b=faces[j];
    if (dot(a.n,b.n)>-1+1e-9 || Math.abs(Math.abs(a.d+b.d)-thickness)>tolerance) continue;
    // Give every panel a canonical basis, independent of STL facet order.
    let normal=a.n;
    const first=normal.find(n => Math.abs(n)>EPS)!;
    if (first<0) normal=mul(normal,-1);
    const distance=(dot(normal,a.triangles[0][0])+dot(normal,b.triangles[0][0]))/2;
    const axes=basis(normal);
    const faceShape=(f: Face) => union2(f.triangles.map(t => polygon(t.map(p => project(p,axes)))));
    const sa=faceShape(a), sb=faceShape(b);
    if (area(booleans.intersect(sa,sb) as Shape2)<thickness*thickness) continue;
    const shape=union2([sa,sb]), loops=outlines(shape), box=bounds(loops);
    if (Math.min(box.width,box.height)<thickness*1.5) continue;
    // Each disconnected footprint is a separate board, with its holes retained.
    for (const component of components(shape)) {
      boards.push({panel:{id:'',normal,u:axes.u,v:axes.v,distance,outlines:outlines(component),cutOutlines:[]},shape:component,original:component});
    }
  }
  if (!boards.length) fail('No panels found at this thickness. Check STL units and measured sheet thickness.');
  sortBoards(boards);
  // A unioned T joint hides the end of its upright inside the other sheet.
  // Recover only material within another board's slab. The shell checks below
  // verify volume and surface coverage within the documented numerical tolerance.
  for (let i=0;i<boards.length;i++) for (let j=0;j<boards.length;j++) {
    if (i===j) continue;
    const a=boards[i],b=boards[j],n=a.panel.normal,m=b.panel.normal;
    if (Math.abs(dot(n,m))>1e-6) continue;
    const dir=unit(cross(n,m));
    const origin=add(mul(n,a.panel.distance),mul(m,b.panel.distance));
    if (intervals(a,origin,dir).length) continue;
    const ranges=intervals(b,origin,dir);
    const reach=expansions.offset({delta:thickness*0.51,corners:'edge'},a.original) as Shape2;
    const extensions=ranges.map(([start,end])=>booleans.intersect(reach,strip(a,origin,dir,start,end,thickness+0.004)) as Shape2).filter(s=>area(s)>EPS);
    if (extensions.length) {
      a.original=union2([a.original,...extensions]);a.shape=a.original;a.panel.outlines=outlines(a.original);
    }
  }
  // Rebuilding the shell catches solids, pockets, and false opposing-face pairs.
  const solids=boards.map(b => boardSolid(b,thickness));
  const reconstructed=solids.length===1?solids[0]:booleans.union(...solids);
  let original=geometries.geom3.fromPoints(triangles);
  if (measurements.measureVolume(original)<0) original=geometries.geom3.fromPoints(triangles.map(t=>[t[2],t[1],t[0]]));
  const volume=Math.abs(measurements.measureVolume(original));
  const rebuiltVolume=Math.abs(measurements.measureVolume(reconstructed));
  const covered=triangles.every(t=>{
    const samples=[...t,mul(add(add(t[0],t[1]),t[2]),1/3),mul(add(t[0],t[1]),0.5),mul(add(t[1],t[2]),0.5),mul(add(t[2],t[0]),0.5)];
    return samples.every(p=>boards.some(b=>onBoard(p,b,thickness)));
  });
  if (!covered || volume<EPS || Math.abs(rebuiltVolume-volume)>Math.max(0.05,volume*0.001)) fail('The mesh cannot be reconstructed as uniform flat panels. Check thickness, pockets, bevels, or overlapping/unjoined solids.');
  return boards;
}

type SolidFrame = { triangles: Triangle[]; center: V3; axes: [V3,V3,V3] };
/** Align orthogonal source faces for stable booleans, without requiring world-axis alignment. */
function solidFrame(input: Triangle[], thickness: number): SolidFrame {
  const signedVolume=measurements.measureVolume(geometries.geom3.fromPoints(input));
  if (Math.abs(signedVolume)<EPS) fail('The closed solid has no measurable volume. Check its scale and winding.');
  const triangles=signedVolume<0?input.map(t=>[t[2],t[1],t[0]] as Triangle):input;
  const faces=facePlanes(triangles,thickness),directions: V3[]=[];
  // Keep the stable orthogonal path; general planar models retain their own frame.
  const general=():SolidFrame=>({triangles,center:[0,0,0],axes:[[1,0,0],[0,1,0],[0,0,1]]});
  for (const face of faces) {
    const n=canonical(face.n);
    if (directions.some(d=>Math.abs(dot(d,n))>1-1e-8)) continue;
    if (directions.some(d=>Math.abs(dot(d,n))>1e-4)) return general();
    directions.push(n);
  }
  if (directions.length!==3) return general();
  directions.sort((a,b)=>{for(let i=0;i<3;i++)if(Math.abs(a[i]-b[i])>EPS)return a[i]-b[i];return 0;});
  const u=directions[0],w=unit(cross(u,directions[1])),v=unit(cross(w,u));
  const axes: [V3,V3,V3]=[u,v,w],lo:V3=[Infinity,Infinity,Infinity],hi:V3=[-Infinity,-Infinity,-Infinity];
  for(const t of triangles)for(const p of t)for(let i=0;i<3;i++){lo[i]=Math.min(lo[i],p[i]);hi[i]=Math.max(hi[i],p[i]);}
  const center=mul(add(lo,hi),0.5),local=triangles.map(t=>t.map(p=>axes.map(axis=>dot(sub(p,center),axis)) as V3) as Triangle);
  // STL floats can put a nominally planar coordinate a few microns apart.
  // Cluster only within the existing plane tolerance, before shell operations.
  const tolerance=Math.max(EPS*10,Math.min(0.005,thickness*0.001));
  for(let axis=0;axis<3;axis++) {
    const coordinates=[...new Set(local.flat().map(p=>p[axis]))].sort((a,b)=>a-b),groups:number[][]=[];
    for(const value of coordinates){const last=groups.at(-1);if(last&&value-last[0]<=tolerance)last.push(value);else groups.push([value]);}
    const values=new Map<number,number>();
    for(const group of groups){const mean=group.reduce((a,b)=>a+b,0)/group.length;for(const value of group)values.set(value,mean);}
    for(const t of local)for(const p of t)p[axis]=values.get(p[axis])!;
  }
  validateMesh(local);
  if(facePlanes(local,thickness).some(f=>Math.max(...f.n.map(Math.abs))<1-1e-12)) fail('The solid faces deviate from common perpendicular planes beyond the STL tolerance. Re-export flat faces at a larger scale or higher precision.');
  return {triangles:local,center,axes};
}
function restorePanel(panel: Panel, frame: SolidFrame): Panel {
  const vector=(p: V3):V3=>add(add(mul(frame.axes[0],p[0]),mul(frame.axes[1],p[1])),mul(frame.axes[2],p[2]));
  const normal=vector(panel.normal),u=vector(panel.u),v=vector(panel.v),x=dot(u,frame.center),y=dot(v,frame.center);
  const restore=(loops:V2[][]):V2[][]=>loops.map(loop=>loop.map(p=>[p[0]+x,p[1]+y]));
  return {...panel,normal,u,v,outward:panel.outward?vector(panel.outward):undefined,distance:panel.distance+dot(normal,frame.center),outlines:restore(panel.outlines),cutOutlines:restore(panel.cutOutlines)};
}

/** Recognize tunnel walls by mesh adjacency between inner face boundaries.
 * A round drilled opening remains a hole, rather than many tiny wall boards.
 * A blind pocket has one mouth and is rejected instead of becoming a through cut.
 */
function surfacePanels(triangles:Triangle[],thickness:number,holeWalls:'open'|'panels'):Face[] {
  const faces=facePlanes(triangles,thickness);
  if(holeWalls==='panels')return faces;
  const mouths=new Map<number,{axes:ReturnType<typeof basis>;holes:V2[][]}>();
  faces.forEach((f,i)=>{
    const axes=basis(canonical(f.n)),shape=weldShape(union2(f.triangles.map(t=>polygon(t.map(p=>project(p,axes))))));
    const holes=outlines(shape).filter(loop=>signedArea(loop)<0);
    if(holes.length)mouths.set(i,{axes,holes});
  });
  if(!mouths.size)return faces;
  const edges=new Map<string,{a:V3;b:V3;faces:Set<number>}>();
  faces.forEach((f,i)=>f.triangles.forEach(t=>t.forEach((a,k)=>{
    const b=t[(k+1)%3],x=vertexKey(a),y=vertexKey(b),key=x<y?`${x}|${y}`:`${y}|${x}`;
    const edge=edges.get(key)??{a,b,faces:new Set<number>()};edge.faces.add(i);edges.set(key,edge);
  })));
  const neighbors=faces.map(()=>new Set<number>()),contacts=faces.map(()=>new Set<string>()),seeds=new Set<number>();
  for(const edge of edges.values()) {
    if(edge.faces.size!==2)continue;
    const [a,b]=[...edge.faces];neighbors[a].add(b);neighbors[b].add(a);
    for(const [mouth,wall] of [[a,b],[b,a]]) {
      const entry=mouths.get(mouth);if(!entry||mouths.has(wall))continue;
      const point=project(mul(add(edge.a,edge.b),0.5),entry.axes);
      entry.holes.forEach((loop,h)=>{
        if(loop.some((p,k)=>{const q=loop[(k+1)%loop.length],dx=q[0]-p[0],dy=q[1]-p[1],t=Math.max(0,Math.min(1,((point[0]-p[0])*dx+(point[1]-p[1])*dy)/(dx*dx+dy*dy||1)));return Math.hypot(point[0]-p[0]-t*dx,point[1]-p[1]-t*dy)<0.001;})) {
          contacts[wall].add(`${mouth}:${h}`);seeds.add(wall);
        }
      });
    }
  }
  const removed=new Set<number>();
  for(const seed of seeds) {
    if(removed.has(seed))continue;
    const region=new Set<number>(),ends=new Set<string>(),queue=[seed];
    while(queue.length) {
      const i=queue.pop()!;if(region.has(i))continue;region.add(i);
      for(const end of contacts[i])ends.add(end);
      for(const j of neighbors[i])if(!mouths.has(j)&&!region.has(j))queue.push(j);
    }
    if(ends.size<2)fail('A blind pocket or opening across a panel edge was found. Use through-holes contained within panel faces; pockets cannot be exported as 2D through cuts.');
    for(const i of region)removed.add(i);
  }
  return faces.filter((_,i)=>!removed.has(i));
}

/** Use exterior surfaces as boards and grow their thickness inward. */
function solidBoards(triangles: Triangle[], thickness: number, holeWalls:'open'|'panels'='open'): Board[] {
  const faces=surfacePanels(triangles,thickness,holeWalls),solid=geometries.geom3.fromPoints(triangles),boards: Board[]=[];
  const convex=faces.every(f=>triangles.every(t=>t.every(p=>dot(f.n,p)<=f.d+Math.max(0.001,Math.min(0.005,thickness*0.001)))));
  if(faces.length>32)fail('More than 32 planar faces remain. Simplify or facet curved surfaces into fewer panels.');
  for (const face of faces) {
    const normal=canonical(face.n),axes=basis(normal),distance=dot(normal,face.triangles[0][0])-dot(normal,face.n)*thickness/2;
    const faceShape=weldShape(union2(face.triangles.map(t=>polygon(t.map(p=>project(p,axes))))));
    for (const component of components(faceShape)) {
      const panel:Panel={id:'',normal,...axes,outward:face.n,distance,outlines:outlines(component),cutOutlines:[]};
      // Convex boundaries clip back to the original silhouette. Concave edges
      // gain the buried material needed for two boards to meet and form fingers.
      const expanded=expansions.offset({delta:thickness+0.005,corners:'edge'},component) as Shape2;
      const candidate:Board={panel,shape:expanded,original:expanded};
      const clipped=convex?null:booleans.intersect(boardSolid(candidate,thickness),solid);
      const caps=clipped===null?[component]:geometries.geom3.toPolygons(clipped).filter(p=>{
        const n=unit(cross(sub(p.vertices[1] as V3,p.vertices[0] as V3),sub(p.vertices[2] as V3,p.vertices[0] as V3)));
        return Math.abs(dot(n,normal))>1-1e-8&&Math.abs(dot(face.n,p.vertices[0] as V3)-face.d)<Math.max(0.001,thickness*0.0001);
      }).map(p=>polygon(p.vertices.map(v=>project(v as V3,axes))));
      if (!caps.length) fail('Material thickness does not fit this solid. Increase model scale or reduce thickness.');
      let shape=weldShape(union2(caps));
      // Laser edges are square to the sheet. Remove the projection of every
      // out-of-solid piece across the full thickness, rather than assuming
      // a bevelled edge can be cut by a 2D laser path.
      const oblique=faces.filter(f=>{const d=Math.abs(dot(f.n,normal));return d>1e-6&&d<1-1e-8;});
      const tolerance=Math.max(0.001,Math.min(0.005,thickness*0.001));
      if(oblique.length&&oblique.every(f=>triangles.every(t=>t.every(p=>dot(f.n,p)<=f.d+tolerance)))) {
        // Convex support planes give a stable 2D half-plane intersection. The
        // allowance covers the whole stock thickness, including its back edge.
        for(const other of oblique) {
          const A=dot(other.n,axes.u),B=dot(other.n,axes.v);
          const limit=other.d-dot(other.n,normal)*distance-thickness/2*Math.abs(dot(other.n,normal));
          const box=bounds(outlines(shape)),extent=Math.max(box.width,box.height,thickness)*4;
          let clip:V2[]=[[box.min[0]-extent,box.min[1]-extent],[box.min[0]+box.width+extent,box.min[1]-extent],[box.min[0]+box.width+extent,box.min[1]+box.height+extent],[box.min[0]-extent,box.min[1]+box.height+extent]];
          const output:V2[]=[];
          for(let k=0;k<clip.length;k++) {
            const a=clip[k],b=clip[(k+1)%clip.length],da=A*a[0]+B*a[1]-limit,db=A*b[0]+B*b[1]-limit;
            if(da<=0)output.push(a);
            if((da<=0)!==(db<=0)){const t=da/(da-db);output.push([a[0]+t*(b[0]-a[0]),a[1]+t*(b[1]-a[1])]);}
          }
          clip=output;
          if(clip.length<3)fail('An angled face disappears at this thickness. Reduce thickness or increase model scale.');
          shape=weldShape(booleans.intersect(shape,polygon(clip)) as Shape2);
        }
      } else if(oblique.length) {
        const stock:Board={panel,shape,original:shape};
        const outside=booleans.subtract(boardSolid(stock,thickness),solid);
        const shadows=geometries.geom3.toPolygons(outside).flatMap(p=>{
          const points=p.vertices.map(v=>project(v as V3,axes));
          return Math.abs(signedArea(points))>EPS?[polygon(points)]:[];
        });
        if(shadows.length)shape=weldShape(booleans.subtract(shape,union2(shadows)) as Shape2);
      }
      if (components(shape).length!==1 || area(shape)<thickness**2) fail('A face is too small or splits at this thickness. Increase model scale or reduce thickness.');
      panel.outlines=outlines(shape);
      boards.push({panel,shape,original:shape});
      if(boards.length>32)fail('This version supports up to 32 panels.');
    }
  }
  sortBoards(boards);
  for(let i=0;i<boards.length;i++)for(let j=i+1;j<boards.length;j++) {
    const a=boards[i],b=boards[j];
    if(Math.abs(dot(a.panel.normal,b.panel.normal))<1-1e-8)continue;
    if(Math.abs(a.panel.distance-dot(a.panel.normal,b.panel.normal)*b.panel.distance)>thickness+0.005)continue;
    if(area(booleans.intersect(a.original,b.original) as Shape2)>EPS) fail('Thickness leaves no hollow interior between opposing faces. Increase model scale or reduce material thickness.');
  }
  const solids=boards.map(b=>boardSolid(b,thickness)),shell=booleans.union(...solids);
  const volume=Math.abs(measurements.measureVolume(solid)),shellVolume=Math.abs(measurements.measureVolume(shell));
  // Check each stock separately: coplanar seams can destabilize a union/subtract chain.
  const outsideVolume=solids.reduce((sum,stock)=>sum+Math.abs(measurements.measureVolume(booleans.subtract(stock,solid))),0);
  if(shellVolume>=volume-Math.max(0.05,volume*0.001) || outsideVolume>Math.max(0.05,volume*0.001)) fail('The selected thickness cannot form a hollow shell inside this solid. Increase model scale, reduce thickness, or simplify narrow features.');
  return boards;
}

// Join sub-millimetre endpoint differences left by projection through 3D booleans.
function weldShape(shape: Shape2): Shape2 {
  const tolerance=0.001,buckets=new Map<string,V2[]>();
  const weld=(point:V2):V2=>{
    const x=Math.floor(point[0]/tolerance),y=Math.floor(point[1]/tolerance);
    for(let dx=-1;dx<=1;dx++)for(let dy=-1;dy<=1;dy++)for(const p of buckets.get(`${x+dx},${y+dy}`)??[])if(Math.hypot(point[0]-p[0],point[1]-p[1])<=tolerance)return p;
    const key=`${x},${y}`,bucket=buckets.get(key)??[],p:V2=[...point];bucket.push(p);buckets.set(key,bucket);return p;
  };
  const sides=geometries.geom2.toSides(shape).map(([a,b])=>[weld(a as V2),weld(b as V2)] as [V2,V2]).filter(([a,b])=>a!==b);
  const unique=new Map<string,[V2,V2]>();
  for(const [a,b] of sides){const key=`${a.join(',')}|${b.join(',')}`,reverse=`${b.join(',')}|${a.join(',')}`;if(unique.has(reverse))unique.delete(reverse);else if(!unique.has(key))unique.set(key,[a,b]);}
  return geometries.geom2.create([...unique.values()]);
}

// Intersect a panel outline with a line, preserving holes and disconnected intervals.
function intervals(board: Board, origin: V3, direction: V3): [number,number][] {
  const p=project(origin,board.panel), d: V2=[dot(direction,board.panel.u),dot(direction,board.panel.v)];
  const side=(v: V2) => d[0]*(v[1]-p[1])-d[1]*(v[0]-p[0]);
  const values: number[]=[];
  for (const loop of board.panel.outlines) for (let i=0;i<loop.length;i++) {
    const a=loop[i],b=loop[(i+1)%loop.length], sa=side(a),sb=side(b);
    // Half-open crossing rule avoids double-counting vertices.
    if ((sa<=0&&sb>0)||(sb<=0&&sa>0)) {
      const r=sa/(sa-sb), x=a[0]+r*(b[0]-a[0]), y=a[1]+r*(b[1]-a[1]);
      values.push((x-p[0])*d[0]+(y-p[1])*d[1]);
    }
  }
  values.sort((a,b)=>a-b);
  if (values.length%2) fail('Ambiguous panel intersection. Move the joint away from a polygon vertex.');
  const result: [number,number][]=[];
  for (let i=0;i<values.length;i+=2) if (values[i+1]-values[i]>EPS) result.push([values[i],values[i+1]]);
  return result;
}
function strip(board: Board, origin: V3, dir: V3, start: number, end: number, width: number): Shape2 {
  const side=unit(cross(board.panel.normal,dir));
  return polygon([[start,-width/2],[end,-width/2],[end,width/2],[start,width/2]].map(([along,across])=>project(add(origin,add(mul(dir,along),mul(side,across))),board.panel)));
}
function crosses(board: Board, line: V3, dir: V3, middle: number, thickness: number): boolean {
  const side=unit(cross(board.panel.normal,dir));
  const near=(sign:number) => {
    const center=add(add(line,mul(dir,middle)),mul(side,sign*thickness*0.6));
    return area(booleans.intersect(board.original,strip(board,center,dir,-thickness/10,thickness/10,thickness/10)) as Shape2)>EPS;
  };
  return near(-1)&&near(1);
}

export function createPanels(triangles: Triangle[], input: Settings = defaults, options: ConversionOptions = {}): Result {
  const settings={...input}; validateSettings(settings); validateMesh(triangles);
  const mode=options.mode??'panels';
  if(mode!=='panels'&&mode!=='solid')fail('Choose existing panels or closed solid mode.');
  if(options.holeWalls!==undefined&&options.holeWalls!=='open'&&options.holeWalls!=='panels')fail('Choose open holes or panel-lined tunnels.');
  const frame=mode==='solid'?solidFrame(triangles,settings.thickness):null;
  const boards=frame?solidBoards(frame.triangles,settings.thickness,options.holeWalls):detectBoards(triangles,settings.thickness),joints: Joint[]=[];
  const panelOptions=options.panelSettings??{},jointOptions=options.jointSettings??{},ids=new Set(boards.map(b=>b.panel.id));
  for(const [id,value] of Object.entries(panelOptions)) {
    if(!ids.has(id))fail(`Unknown panel ${id}. Clear overrides after changing the source model.`);
    if(!value||typeof value!=='object')fail(`Invalid settings for ${id}.`);
    if(value.kerf!==undefined&&(!Number.isFinite(value.kerf)||value.kerf<0||value.kerf>=settings.thickness/2))fail(`Kerf for ${id} must be non-negative and less than half the thickness.`);
    if(value.engrave!==undefined&&typeof value.engrave!=='boolean')fail(`Engraving for ${id} must be on or off.`);
  }
  for(const [key,value] of Object.entries(jointOptions)) {
    const [a,b,...extra]=key.split(':');
    if(extra.length||!ids.has(a)||!ids.has(b)||a===b||jointKey(a,b)!==key)fail(`Use a shared joint key such as P1:P2; ${key} is not valid for this model.`);
    if(!value||typeof value!=='object')fail(`Invalid settings for joint ${key}.`);
    validateFingerCount(value.fingerCount??0);
    if(value.fingerWidth!==undefined&&(!Number.isFinite(value.fingerWidth)||value.fingerWidth<settings.thickness||value.fingerWidth>500))fail(`Finger width for ${key} must be at least the material thickness and at most 500 mm.`);
  }
  for(const board of boards) {
    const local=panelOptions[board.panel.id];
    board.panel.kerf=local?.kerf??settings.kerf;board.panel.engrave=local?.engrave??true;
  }
  if(settings.gap<Math.max(...boards.map(b=>2*b.panel.kerf!)))fail('Part gap must be at least twice the largest panel kerf.');
  const usedJointKeys=new Set<string>();
  const removals=boards.map(()=>[] as Shape2[]);
  let cornerOffcuts=0;
  for (let i=0;i<boards.length;i++) for (let j=i+1;j<boards.length;j++) {
    const a=boards[i],b=boards[j], n=a.panel.normal,m=b.panel.normal, angle=dot(n,m);
    if (Math.abs(angle)>1-1e-8) continue;
    const raw=cross(n,m), dir=unit(raw), denominator=dot(raw,raw);
    const origin=mul(add(mul(cross(m,raw),a.panel.distance),mul(cross(raw,n),b.panel.distance)),1/denominator);
    const ia=intervals(a,origin,dir),ib=intervals(b,origin,dir);
    for (const x of ia) for (const y of ib) {
      const start=Math.max(x[0],y[0]),end=Math.min(x[1],y[1]),span=end-start;
      if (span<settings.thickness) continue;
      // Project the other sheet's entire slab across this sheet's thickness.
      // At an oblique joint this envelope is wider than the material itself.
      const jointWidth=settings.thickness*(1+Math.abs(angle))/Math.sqrt(denominator);
      if(jointWidth>settings.thickness*8)fail(`${a.panel.id} and ${b.panel.id} meet too shallowly for square-cut finger joints. Change the angle or use thinner material.`);
      if (crosses(a,origin,dir,(start+end)/2,jointWidth)&&crosses(b,origin,dir,(start+end)/2,jointWidth)) fail(`${a.panel.id} and ${b.panel.id} cross internally. Use an edge joint; crossing panels need a different assembly strategy.`);
      const key=jointKey(a.panel.id,b.panel.id),local=jointOptions[key];
      const requested=local?(local.fingerCount??0):(settings.fingerCount??0);
      let count=requested||Math.floor((span+0.005)/(local?.fingerWidth??settings.fingerWidth));
      if (!requested&&count%2===0) count--;
      if (count<3) fail(`The joint between ${a.panel.id} and ${b.panel.id} is too short. Use a smaller finger width (at least three fingers must fit).`);
      const pitch=span/count;
      if(pitch<settings.thickness-EPS)fail(`${count} finger segments on ${key} would be narrower than the material thickness. Reduce the count.`);
      for (let k=0;k<count;k++) {
        const index=k%2===0?i:j,board=boards[index];
        removals[index].push(strip(board,origin,dir,start+k*pitch-0.002,end-(count-k-1)*pitch+0.002,jointWidth+0.004));
      }
      usedJointKeys.add(key);
      joints.push({id:`J${joints.length+1}`,key,a:a.panel.id,b:b.panel.id,fingers:count,length:span,pitch,segment:[add(origin,mul(dir,start)),add(origin,mul(dir,end))]});
    }
  }
  for(const key of Object.keys(jointOptions))if(!usedJointKeys.has(key))fail(`No touching joint exists at ${key}. Clear this override.`);
  for (let i=0;i<boards.length;i++) {
    const b=boards[i];
    if (removals[i].length) b.shape=booleans.subtract(b.original,union2(removals[i])) as Shape2;
    const pieces=components(b.shape);
    if(removals[i].length&&pieces.length>1) {
      const main=pieces.filter(p=>area(p)>settings.thickness**2);
      if(main.length===1){cornerOffcuts+=pieces.length-1;b.shape=main[0];}
    }
    if (area(b.shape)<settings.thickness**2 || components(b.shape).length!==1) fail(`Finger joints split or erase ${b.panel.id}. Change finger width or the model.`);
    b.panel.outlines=outlines(b.shape);
    const kerf=b.panel.kerf??settings.kerf;
    const cut=kerf?expansions.offset({delta:kerf/2,corners:'edge'},b.shape) as Shape2:b.shape;
    const cutLoops=outlines(cut);
    if (cutLoops.length!==b.panel.outlines.length || components(cut).length!==1) fail(`Kerf compensation destroys a feature in ${b.panel.id}. Reduce kerf.`);
    b.panel.cutOutlines=cutLoops;
  }
  if(frame)for(const joint of joints)joint.segment=joint.segment.map(p=>add(frame.center,add(add(mul(frame.axes[0],p[0]),mul(frame.axes[1],p[1])),mul(frame.axes[2],p[2])))) as [V3,V3];
  const panels=boards.map(b=>frame?restorePanel(b.panel,frame):b.panel), sheets=layoutPanels(panels,settings);
  const warnings=joints.length?['Check assembly order before cutting; closed assemblies may need glue or a removable final panel.']:['No touching panel edges were found; these parts have no finger joints.'];
  if(cornerOffcuts)warnings.push(`${cornerOffcuts} small corner offcuts (each at most one material-thickness square) fall away during cutting.`);
  if(joints.some(j=>{const a=panels.find(p=>p.id===j.a)!,b=panels.find(p=>p.id===j.b)!;return Math.abs(dot(a.normal,b.normal))>1e-6;}))warnings.push('Angled joints use relieved square-cut fingers, with visible gaps at the seam. No bevel cuts are included. Test the fit in scrap material.');
  if(mode==='solid')warnings.unshift(`Material grows inward from the exterior faces; the interior becomes hollow. ${options.holeWalls==='panels'?'Tunnel walls become panels.':'Through-hole walls stay open.'}`);
  return {panels,joints,sheets,settings,warnings,mode};
}

/** Deterministic shelf layout with quarter-turn rotation and multiple beds. */
export function layoutPanels(panels: Panel[], s: Settings): Sheet[] {
  validateSettings(s);
  type Shelf = { y:number; height:number; x:number };
  const bins: {sheet:Sheet;shelves:Shelf[]}[]=[];
  const usableWidth=s.bedWidth-2*s.margin,usableHeight=s.bedHeight-2*s.margin;
  const sorted=panels.map((panel,index)=>({index,...bounds(panel.cutOutlines)})).sort((a,b)=>b.width*b.height-a.width*a.height||a.index-b.index);
  for (const box of sorted) {
    const orientations=[{w:box.width,h:box.height,r:false},{w:box.height,h:box.width,r:true}];
    if (!orientations.some(o=>o.w<=usableWidth+EPS&&o.h<=usableHeight+EPS)) fail(`${panels[box.index].id} exceeds the bed, including margins. Use a larger bed or change the model.`);
    let placed=false;
    const put=(bin:typeof bins[number], shelf:Shelf, o:typeof orientations[number]) => {
      bin.sheet.placements.push({panel:box.index,x:s.margin+shelf.x,y:s.margin+shelf.y,width:o.w,height:o.h,rotated:o.r,min:box.min});
      shelf.x+=o.w+s.gap; placed=true;
    };
    for (const bin of bins) {
      for (const shelf of bin.shelves) {
        const o=orientations.find(o=>o.h<=shelf.height+EPS&&shelf.x+o.w<=usableWidth+EPS);
        if (o) {put(bin,shelf,o);break;}
      }
      if (placed) break;
      const last=bin.shelves.at(-1),y=last?last.y+last.height+s.gap:0;
      const o=orientations.filter(o=>o.w<=usableWidth+EPS&&y+o.h<=usableHeight+EPS).sort((a,b)=>a.h-b.h)[0];
      if (o) {const shelf={x:0,y,height:o.h};bin.shelves.push(shelf);put(bin,shelf,o);break;}
    }
    if (!placed) {
      const o=orientations.filter(o=>o.w<=usableWidth+EPS&&o.h<=usableHeight+EPS).sort((a,b)=>a.h-b.h)[0];
      const shelf={x:0,y:0,height:o.h}, bin={sheet:{placements:[]} as Sheet,shelves:[shelf]};
      bins.push(bin);put(bin,shelf,o);
    }
  }
  return bins.map(b=>b.sheet);
}

export function placedContours(panel: Panel, place: Placement): V2[][] {
  const box=bounds(panel.cutOutlines);
  return panel.cutOutlines.map(loop=>loop.map(p=>{
    const x=p[0]-place.min[0],y=p[1]-place.min[1];
    return place.rotated?[place.x+box.height-y,place.y+x]:[place.x+x,place.y+y];
  }));
}

// Stroke lettering is portable to both SVG and DXF and never becomes a cut.
const glyphs: Record<string,number[][]> = {
  P:[[0,0,0,2],[0,0,1,0],[1,0,1,1],[1,1,0,1]],
  '0':[[0,0,1,0],[1,0,1,2],[1,2,0,2],[0,2,0,0]],
  '1':[[0.5,0,0.5,2]], '2':[[0,0,1,0],[1,0,1,1],[1,1,0,1],[0,1,0,2],[0,2,1,2]],
  '3':[[0,0,1,0],[1,0,1,2],[0,1,1,1],[0,2,1,2]],
  '4':[[0,0,0,1],[0,1,1,1],[1,0,1,2]],
  '5':[[1,0,0,0],[0,0,0,1],[0,1,1,1],[1,1,1,2],[1,2,0,2]],
  '6':[[1,0,0,0],[0,0,0,2],[0,2,1,2],[1,2,1,1],[1,1,0,1]],
  '7':[[0,0,1,0],[1,0,0,2]],
  '8':[[0,0,1,0],[1,0,1,2],[1,2,0,2],[0,2,0,0],[0,1,1,1]],
  '9':[[1,2,1,0],[1,0,0,0],[0,0,0,1],[0,1,1,1]],
};
function inside(p: V2, loops: V2[][]): boolean {
  let yes=false;
  for (const loop of loops) for (let i=0,j=loop.length-1;i<loop.length;j=i++) {
    const a=loop[i],b=loop[j];
    if ((a[1]>p[1])!==(b[1]>p[1])&&p[0]<(b[0]-a[0])*(p[1]-a[1])/(b[1]-a[1])+a[0]) yes=!yes;
  }
  return yes;
}
export function labelStrokes(panel: Panel, place: Placement): V2[][] {
  if(panel.engrave===false)return [];
  const contours=placedContours(panel,place), width=panel.id.length*2.8, height=4;
  // Search for a clear patch of material; omit a label rather than engrave a hole.
  for (let row=1;row<=9;row++) for (let col=1;col<=9;col++) {
    const x=place.x+place.width*col/10-width/2,y=place.y+place.height*row/10-height/2;
    let clear=true;
    for (let xx=-0.5;xx<=width+0.5;xx+=0.5) for (let yy=-0.5;yy<=height+0.5;yy+=0.5) if (!inside([x+xx,y+yy],contours)) clear=false;
    if (!clear) continue;
    // Reject even very small holes or boundary segments passing through the patch.
    for (const loop of contours) for (let i=0;i<loop.length;i++) {
      const a=loop[i],b=loop[(i+1)%loop.length];
      if (Math.max(a[0],b[0])>=x-0.5&&Math.min(a[0],b[0])<=x+width+0.5&&Math.max(a[1],b[1])>=y-0.5&&Math.min(a[1],b[1])<=y+height+0.5) clear=false;
    }
    if (!clear) continue;
    return [...panel.id].flatMap((char,index)=>glyphs[char].map(([a,b,c,d])=>[[x+index*2.8+a*2,y+b*2],[x+index*2.8+c*2,y+d*2]] as V2[]));
  }
  return [];
}
const num=(n:number)=>String(Number(n.toFixed(5)));
const path=(loop:V2[],closed:boolean)=>loop.map((p,i)=>`${i?'L':'M'}${num(p[0])},${num(p[1])}`).join(' ')+(closed?' Z':'');
function selectedSheet(result:Result,index:number) {return result.sheets[index]??fail('Choose an existing sheet.');}
const xmlText=(value:string)=>value.replace(/[&<>"']/g,char=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&apos;'}[char]!));
export function exportSVG(result: Result, index=0, labels=true): string {
  const sheet=selectedSheet(result,index),s=result.settings;
  const cuts=sheet.placements.map(p=>{
    const panel=result.panels[p.panel];
    return `<g data-panel="${xmlText(panel.id)}"><title>${xmlText(panel.id)}</title>${placedContours(panel,p).map(loop=>`<path d="${path(loop,true)}"/>`).join('\n')}</g>`;
  }).join('\n');
  const engrave=labels?sheet.placements.flatMap(p=>labelStrokes(result.panels[p.panel],p)).map(stroke=>`<path d="${path(stroke,false)}"/>`).join('\n'):'';
  return `<?xml version="1.0" encoding="UTF-8"?>\n<svg xmlns="http://www.w3.org/2000/svg" width="${num(s.bedWidth)}mm" height="${num(s.bedHeight)}mm" viewBox="0 0 ${num(s.bedWidth)} ${num(s.bedHeight)}"><title>Ply Cutter sheet ${index+1}</title><g id="CUT" fill="none" stroke="#ff0000" stroke-width="0.1">${cuts}</g><g id="ENGRAVE" fill="none" stroke="#0000ff" stroke-width="0.1">${engrave}</g></svg>`;
}
export function exportDXF(result: Result, index=0, labels=true): string {
  const sheet=selectedSheet(result,index),s=result.settings;
  const entities: string[]=[];
  const emit=(points:V2[],closed:boolean,layer:string)=>{
    entities.push(`0\nLWPOLYLINE\n100\nAcDbEntity\n8\n${layer}\n100\nAcDbPolyline\n90\n${points.length}\n70\n${closed?1:0}\n${points.map(p=>`10\n${num(p[0])}\n20\n${num(s.bedHeight-p[1])}`).join('\n')}`);
  };
  for (const p of sheet.placements) {
    const panel=result.panels[p.panel];
    placedContours(panel,p).forEach(loop=>emit(loop,true,'CUT'));
    if (labels) labelStrokes(panel,p).forEach(stroke=>emit(stroke,false,'ENGRAVE'));
  }
  return `0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n9\n$INSUNITS\n70\n4\n9\n$MEASUREMENT\n70\n1\n0\nENDSEC\n0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLTYPE\n70\n1\n0\nLTYPE\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n2\nCONTINUOUS\n70\n0\n3\nSolid line\n72\n65\n73\n0\n40\n0\n0\nENDTAB\n0\nTABLE\n2\nLAYER\n70\n2\n0\nLAYER\n100\nAcDbSymbolTableRecord\n100\nAcDbLayerTableRecord\n2\nCUT\n70\n0\n62\n1\n6\nCONTINUOUS\n0\nLAYER\n100\nAcDbSymbolTableRecord\n100\nAcDbLayerTableRecord\n2\nENGRAVE\n70\n0\n62\n5\n6\nCONTINUOUS\n0\nENDTAB\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n${entities.join('\n')}\n0\nENDSEC\n0\nEOF\n`;
}

/** Small watertight L corner, useful without an uploaded file. */
export function exampleCorner(thickness=3): Triangle[] {
  const footprint=primitives.polygon({points:[[0,0],[90,0],[90,thickness],[thickness,thickness],[thickness,70],[0,70]]});
  const solid=extrusions.extrudeLinear({height:60},footprint);
  // Extrusion produces convex faces, so each face can be triangulated as a fan.
  return geometries.geom3.toPolygons(solid).flatMap(p=>{
    const vertices=p.vertices.map(v=>[v[0],v[1],v[2]] as V3),triangles:Triangle[]=[];
    for (let i=1;i<vertices.length-1;i++) triangles.push([vertices[0],vertices[i],vertices[i+1]]);
    return triangles;
  });
}

/** A closed 100 mm cube: six exterior faces, with no modelled wall thickness. */
export function exampleSolid(): Triangle[] {
  return geometries.geom3.toPolygons(primitives.cuboid({size:[100,100,100]})).flatMap(p=>{
    const vertices=p.vertices.map(v=>[v[0],v[1],v[2]] as V3),triangles:Triangle[]=[];
    for(let i=1;i<vertices.length-1;i++)triangles.push([vertices[0],vertices[i],vertices[i+1]]);
    return triangles;
  });
}
Article interface and preview
import {
  validateSettings, parseSTL, repairSTL, exportSTL, createPanels, exampleCorner, exampleSolid, panelPoint,
  exportSVG, exportDXF, labelStrokes,
} from './ply-cutter.org?name=ply-cutter-core';
import type { Settings, Triangle, V2, V3, Result, InputMode, MeshReport, JointSettings, PanelSettings } from './ply-cutter.org?name=ply-cutter-core';

export function mountPlyCutter(): HTMLElement {
  const root=document.createElement('section');
  root.className='ply-tool';
  root.innerHTML=`
    <style>
      .ply-tool { --ply-line:#b6c1c6; --ply-ink:#172d34; --ply-accent:#075e54; background:#f4f8f8; color:var(--ply-ink); border:1px solid var(--ply-line); border-radius:10px; padding:20px; margin:24px 0; font:1rem/1.5 system-ui,sans-serif; }
      .ply-tool * { box-sizing:border-box; }
      .ply-tool h2,.ply-tool h3 { color:inherit; margin:0 0 12px; }
      .ply-tool h2 { font-size:1.5rem; }
      .ply-tool h3 { font-size:1.1rem; }
      .ply-tool p { margin:8px 0; }
      .ply-toolbar,.ply-actions { display:flex; flex-wrap:wrap; align-items:center; gap:10px; margin:12px 0; }
      .ply-tool button,.ply-tool input,.ply-tool select { font:inherit; color:inherit; }
      .ply-tool button { border:1px solid var(--ply-accent); background:white; border-radius:5px; padding:8px 12px; cursor:pointer; }
      .ply-tool button.ply-primary { background:var(--ply-accent); color:white; }
      .ply-tool button:disabled { opacity:.45; cursor:default; }
      .ply-tool :focus-visible { outline:3px solid #1683d2; outline-offset:3px; }
      .ply-fields { display:grid; grid-template-columns:repeat(auto-fit,minmax(145px,1fr)); gap:12px; margin:16px 0; }
      .ply-fields label { display:flex; flex-direction:column; gap:4px; font-size:.9rem; }
      .ply-fields input,.ply-fields select { width:100%; min-height:40px; border:1px solid var(--ply-line); border-radius:4px; padding:6px 8px; background:white; }
      .ply-tool select { appearance:none; padding-right:28px; background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8'%3E%3Cpath d='m1 1 5 5 5-5' fill='none' stroke='%23172d34' stroke-width='2'/%3E%3C/svg%3E"); background-repeat:no-repeat; background-position:right 10px center; }
      .ply-status { padding:10px 12px; border-left:4px solid var(--ply-accent); background:#e0eeea; overflow-wrap:anywhere; }
      .ply-status[data-error=true] { border-color:#a12c2c; background:#ffe9e5; }
      .ply-previews { display:grid; grid-template-columns:repeat(auto-fit,minmax(min(100%,310px),1fr)); gap:18px; margin-top:20px; }
      .ply-tool figure { margin:0; min-width:0; }
      .ply-tool canvas { display:block; width:100%; height:340px; background:#edf1f2; border:1px solid var(--ply-line); border-radius:6px; touch-action:none; cursor:grab; }
      .ply-tool canvas:active { cursor:grabbing; }
      .ply-bed { display:flex; align-items:center; justify-content:center; min-height:260px; border:1px solid var(--ply-line); border-radius:6px; background:#e5ecee; padding:12px; overflow:hidden; }
      .ply-bed svg { display:block; width:100%; max-height:340px; background:white; box-shadow:0 1px 5px #172d3433; }
      .ply-bed svg path { vector-effect:non-scaling-stroke; stroke-width:1.25px; }
      .ply-tool figcaption,.ply-help { font-size:.9rem; color:#43585f; }
      .ply-check { display:flex; align-items:center; gap:8px; }
      .ply-tool table { width:100%; border-collapse:collapse; margin-top:12px; font-size:.9rem; }
      .ply-tool th,.ply-tool td { border-bottom:1px solid var(--ply-line); padding:6px; text-align:left; }
      .ply-table { max-height:250px; overflow:auto; }
      .ply-downloads { display:flex; flex-wrap:wrap; align-items:center; gap:10px; }
      .ply-file { max-width:100%; }
      .ply-legend { display:flex; flex-wrap:wrap; gap:8px; margin:16px 0; }
      .ply-legend button[aria-pressed=true] { outline:3px solid #2866aa; outline-offset:1px; }
      .ply-swatch { display:inline-block; width:14px; height:14px; border:1px solid #172d3488; border-radius:3px; vertical-align:middle; margin-right:6px; }
      .ply-inspector { border:1px solid var(--ply-line); padding:16px; border-radius:6px; margin-top:18px; }
      .ply-inspector .ply-fields { grid-template-columns:repeat(auto-fit,minmax(min(100%,180px),1fr)); }
      .ply-inspector summary { cursor:pointer; font-weight:600; }
      .ply-detail-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(min(100%,280px),1fr)); gap:20px; margin-top:12px; }
      .ply-detail-svg { width:100%; height:280px; background:white; border:1px solid var(--ply-line); }
      .ply-detail-svg [data-joint] { cursor:pointer; }
      .ply-pending { padding:10px; background:#fff3d6; border-left:4px solid #9a6b00; }
      .ply-tool [hidden] { display:none !important; }
      .ply-bed [data-panel] { cursor:pointer; }
      .ply-bed [data-selected=true] > path { stroke:#075e54; stroke-width:2px; }
      .ply-piece-badge { font:6px system-ui; fill:#172d34; paint-order:stroke; stroke:white; stroke-width:1.5px; }
      @media(max-width:480px) { .ply-tool {padding:12px;} .ply-tool canvas {height:280px;} }
    </style>
    <h2>STL to finger-jointed panels</h2>
    <p>Flat panels with right-angle or sloped joints. Round and rectangular STL holes are preserved. Files stay on your device.</p>
    <div class="ply-toolbar">
      <label>STL file <input class="ply-file" type="file" accept=".stl,model/stl,application/sla" aria-label="Import STL file"></label>
      <button type="button" data-action="solid-example">Load solid cube</button>
      <button type="button" data-action="example">Load panel corner</button>
    </div>
    <div class="ply-toolbar"><label class="ply-check"><input type="checkbox" data-action="repair" checked>Repair collapsed and duplicate facets on import</label><button type="button" data-action="cleaned-stl" disabled>Download cleaned STL</button></div>
    <p class="ply-help">Repair removes invalid facets without moving vertices. Overlapping parts may still need a Boolean Union. Cleaned STL downloads use the displayed millimetre dimensions.</p>
    <details data-import-report hidden><summary>Import repair report</summary><p data-import-summary></p><p class="ply-help" data-import-facets></p></details>
    <div class="ply-fields">
      <label>Input shape<select data-action="mode"><option value="solid">Closed solid → panels</option><option value="panels">Existing sheet panels</option></select></label>
      <label>STL units<select data-setting="units"><option value="mm">Millimetres</option><option value="in">Inches</option></select></label>
      <label>Model scale factor<input type="number" data-action="scale" value="1" min="0.000001" max="1000000" step="any"></label>
      <label>Thickness (mm)<input type="number" data-setting="thickness" value="3" min="0.2" max="50" step="0.1"></label>
      <label>Target finger width (mm)<input type="number" data-setting="fingerWidth" value="10" min="0.2" max="500" step="0.5"></label>
      <label>Finger segments per joint<input type="number" data-setting="fingerCount" value="0" min="0" max="999" step="1" aria-describedby="ply-count-help"></label>
      <label>Full kerf (mm)<input type="number" data-setting="kerf" value="0" min="0" step="0.01"></label>
      <label>Bed width (mm)<input type="number" data-setting="bedWidth" value="500" min="10" max="5000" step="1"></label>
      <label>Bed height (mm)<input type="number" data-setting="bedHeight" value="300" min="10" max="5000" step="1"></label>
      <label>Bed margin (mm)<input type="number" data-setting="margin" value="5" min="0" step="1"></label>
      <label>Part gap (mm)<input type="number" data-setting="gap" value="5" min="1" step="1"></label>
    </div>
    <p class="ply-help" data-mode-help>Closed solid: outer faces become boards with thickness growing inward. Through-holes stay open; angled seams use square-cut relief, with visible gaps.</p>
    <p class="ply-help" id="ply-count-help">Count 0 uses target width. Set an odd count (3, 5, 7…) for an exact pattern on every joint. Five segments means two fingers on one piece and three on its mate. Counts that make fingers thinner than the material are rejected.</p>
    <p class="ply-help">Check the dimensions below. If a cube shows 2 × 2 × 2 mm and you want 100 mm, set the model scale factor to 50. Generate first, then select a piece to inspect its joints and local settings.</p>
    <div class="ply-actions"><button type="button" class="ply-primary" data-action="generate">Generate panels</button><label class="ply-check"><input type="checkbox" data-action="labels" checked>Engrave part names</label></div>
    <p class="ply-status" role="status" aria-live="polite">Loading example…</p>
    <p class="ply-dimensions"></p>
    <p class="ply-pending" data-pending hidden>Preview shows the last generated panels. Generate panels to apply the pending settings; cutting downloads are disabled.</p>
    <div class="ply-legend" data-legend role="group" aria-label="Piece legend"></div>
    <div class="ply-previews">
      <figure>
        <h3>Assembly preview</h3>
        <div class="ply-toolbar"><label>View <select data-action="view"><option value="panels">Finger-jointed panels</option><option value="source">Original STL</option></select></label><button type="button" data-action="reset">Reset view</button><label class="ply-check"><input type="checkbox" data-action="piece-ids" checked>Show piece IDs</label></div>
        <canvas aria-label="3D model preview. Drag to orbit; use sliders to adjust the view." role="img"></canvas>
        <div class="ply-fields">
          <label>Orbit<input type="range" data-view="orbit" min="-180" max="180" value="35"></label>
          <label>Tilt<input type="range" data-view="tilt" min="-80" max="80" value="25"></label>
          <label>Explode panels<input type="range" data-view="explode" min="0" max="50" value="0"></label>
          <label>Zoom<input type="range" data-view="zoom" min="50" max="200" value="100"></label>
        </div>
        <figcaption>A visual assembly check. Closed assemblies can require a specific assembly order.</figcaption>
      </figure>
      <figure>
        <h3>Cutting layout</h3>
        <div class="ply-toolbar"><label>Sheet <select data-action="sheet" disabled><option>No layout yet</option></select></label></div>
        <div class="ply-bed"><p>Generate panels to preview the cutting paths.</p></div>
        <p class="ply-help"><span style="color:#a80000">Red: cut</span> · <span style="color:#0000b0">Blue: engrave</span> · All dimensions in mm.</p>
        <div class="ply-downloads"><button type="button" data-action="svg" disabled>Export SVG</button><button type="button" data-action="dxf" disabled>Export DXF</button></div>
        <figcaption>Each export contains the selected sheet at 1:1 scale. Download each sheet separately.</figcaption>
      </figure>
    </div>
    <details class="ply-inspector" data-inspector hidden open>
      <summary>Panel details — <span data-piece-name></span></summary>
      <div class="ply-detail-grid">
        <div><svg class="ply-detail-svg" data-piece-preview role="img" aria-label="Selected panel and its shared joints"></svg><p class="ply-help">Select a marked joint to edit it. Both mating pieces update together.</p><div data-neighbors class="ply-toolbar"></div></div>
        <div>
          <div class="ply-fields">
            <label>Shared joint<select data-action="joint-select"></select></label>
            <label>Joint pattern<select data-action="joint-mode"><option value="inherit">Use global settings</option><option value="count">Exact segment count</option><option value="width">Target finger width</option><option value="mixed" disabled>Mixed — choose a pattern</option></select></label>
            <label><span data-joint-value-label>Segment count</span><input data-action="joint-value" type="number" min="3" max="999" step="1" value="5"></label>
          </div>
          <button type="button" data-action="apply-joint">Apply to shared joints</button>
          <p class="ply-help" data-joint-summary></p>
          <div class="ply-fields"><label>Kerf for this piece (mm)<input data-action="panel-kerf" type="number" min="0" step="0.01" placeholder="Use global kerf"></label></div>
          <label class="ply-check"><input type="checkbox" data-action="panel-engrave" checked>Include this piece's ID in engraving</label>
          <div class="ply-toolbar"><button type="button" data-action="apply-panel">Apply piece settings</button><button type="button" data-action="reset-panel">Reset this piece and its shared joints</button></div>
          <p class="ply-help">Blank kerf inherits the global value. Thickness is shared by the whole material. Changing the source, units, scale, input mode or thickness clears local settings.</p>
        </div>
      </div>
    </details>
    <div class="ply-table"></div>
  `;
  const q=<T extends Element=HTMLElement>(selector:string)=>root.querySelector<T>(selector)!;
  const settingsInputs=[...root.querySelectorAll<HTMLInputElement>('.ply-fields input[data-setting]')];
  const status=q<HTMLParagraphElement>('.ply-status'),dimensions=q<HTMLParagraphElement>('.ply-dimensions');
  const file=q<HTMLInputElement>('input[type=file]'),units=q<HTMLSelectElement>('[data-setting=units]');
  const mode=q<HTMLSelectElement>('[data-action=mode]'),modelScale=q<HTMLInputElement>('[data-action=scale]');
  const repair=q<HTMLInputElement>('[data-action=repair]'),cleaned=q<HTMLButtonElement>('[data-action=cleaned-stl]');
  const importDetails=q<HTMLDetailsElement>('[data-import-report]');
  const generate=q<HTMLButtonElement>('[data-action=generate]'),sheet=q<HTMLSelectElement>('[data-action=sheet]');
  const svgButton=q<HTMLButtonElement>('[data-action=svg]'),dxfButton=q<HTMLButtonElement>('[data-action=dxf]');
  const labels=q<HTMLInputElement>('[data-action=labels]'),view=q<HTMLSelectElement>('[data-action=view]');
  const canvas=q<HTMLCanvasElement>('canvas'),bed=q<HTMLDivElement>('.ply-bed'),table=q<HTMLDivElement>('.ply-table');
  const inspector=q<HTMLDetailsElement>('[data-inspector]'),legend=q('[data-legend]'),pieceIds=q<HTMLInputElement>('[data-action=piece-ids]');
  const jointSelect=q<HTMLSelectElement>('[data-action=joint-select]'),jointMode=q<HTMLSelectElement>('[data-action=joint-mode]'),jointValue=q<HTMLInputElement>('[data-action=joint-value]');
  const panelKerf=q<HTMLInputElement>('[data-action=panel-kerf]'),panelEngrave=q<HTMLInputElement>('[data-action=panel-engrave]');
  let triangles: Triangle[]=[],result: Result|null=null, source: ArrayBuffer|null=null,usingExample=true,revision=0;
  let importReport:MeshReport|null=null,importValid=false;
  let inspection:Result|null=null,selectedId:string|null=null,selectedJoint='*';
  let jointOverrides:Record<string,JointSettings>={},panelOverrides:Record<string,PanelSettings>={};
  let hitRegions:{id:string;loops:V2[][]}[]=[];
  let yaw=35,pitch=25,explode=0,zoom=1,drag: {x:number;y:number;id:number;startX:number;startY:number;moved:boolean}|null=null;
  const say=(message:string,error=false)=>{status.textContent=message;status.dataset.error=String(error);};
  const scaleFactor=()=>{
    const value=modelScale.value===''?NaN:Number(modelScale.value);
    if(!Number.isFinite(value)||value<=0||value>1000000)throw new Error('Scale factor must be positive and at most 1,000,000.');
    return value;
  };
  const settings=():Settings=>Object.fromEntries(settingsInputs.map(input=>[input.dataset.setting,input.value===''?NaN:Number(input.value)])) as Settings;
  const setExports=(enabled:boolean)=>{svgButton.disabled=dxfButton.disabled=sheet.disabled=!enabled;};
  function invalidate(message='Settings changed. Generate panels to update the preview and exports.',keepPanels=true) {
    revision++;result=null;setExports(false);
    if(!keepPanels){inspection=null;selectedId=null;table.replaceChildren();legend.replaceChildren();inspector.hidden=true;bed.innerHTML='<p>Generate panels to update the cutting layout.</p>';}
    q('[data-pending]').hidden=!inspection;
    if(inspection){renderTable();renderBed();}
    say(message);draw();
  }
  function describe(name:string) {
    let lo=[Infinity,Infinity,Infinity],hi=[-Infinity,-Infinity,-Infinity];
    for (const t of triangles) for (const p of t) for (let i=0;i<3;i++) {lo[i]=Math.min(lo[i],p[i]);hi[i]=Math.max(hi[i],p[i]);}
    dimensions.textContent=triangles.length?`${name} · ${triangles.length} triangles · ${hi.map((n,i)=>(n-lo[i]).toFixed(2)).join(' × ')} mm`:'';
  }
  function refreshModel() {
    importValid=false;importReport=null;importDetails.hidden=true;cleaned.disabled=true;
    try {
      const factor=scaleFactor();
      if(usingExample){const mesh=mode.value==='solid'?exampleSolid():exampleCorner(settings().thickness);triangles=mesh.map(t=>t.map(p=>p.map(n=>n*factor) as V3) as Triangle);describe(mode.value==='solid'?'Solid cube':'Panel corner');}
      else if(source){
        if(repair.checked){const imported=repairSTL(source,units.value as 'mm'|'in',factor);triangles=imported.triangles;importReport=imported.report;importValid=importReport.valid;
          importDetails.hidden=false;importDetails.open=!importValid||!!importReport.removedDegenerate.length||!!importReport.removedDuplicates.length;
          q('[data-import-summary]').textContent=importReport.message;
          const ids=(values:number[])=>values.slice(0,100).join(', ')+(values.length>100?'…':'');
          q('[data-import-facets]').textContent=`Source facet numbers (starting at 1). Collapsed: ${ids(importReport.removedDegenerate)||'none'}. Duplicates: ${ids(importReport.removedDuplicates)||'none'}.`;
        }else{triangles=parseSTL(source,units.value as 'mm'|'in',factor);importValid=true;}
        cleaned.disabled=!importValid;describe(file.files?.[0]?.name??'STL');if(!importValid)say(importReport!.message,true);
      }
      generate.disabled=!usingExample&&!importValid;
      draw();
    } catch(error){triangles=[];generate.disabled=!usingExample;describe('');draw();say(error instanceof Error?error.message:String(error),true);}
  }
  function renderBed() {
    const model=current();if (!model) return;
    const index=Number(sheet.value), svg=exportSVG(model,index,labels.checked);
    const doc=new DOMParser().parseFromString(svg,'image/svg+xml');
    const element=document.importNode(doc.documentElement,true);
    element.setAttribute('aria-label',`Cutting layout, sheet ${index+1}`);element.setAttribute('role','img');
    for(const group of element.querySelectorAll<SVGGElement>('g[data-panel]')) {
      const id=group.dataset.panel!,panelIndex=model.panels.findIndex(p=>p.id===id);
      group.dataset.selected=String(id===selectedId);group.setAttribute('tabindex','0');group.setAttribute('role','button');group.setAttribute('aria-label',`Inspect ${id}`);
      const select=()=>selectPanel(id);group.addEventListener('click',select);group.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();select();}});
      if(pieceIds.checked) {
        const place=model.sheets[index].placements.find(p=>p.panel===panelIndex)!;
        const text=document.createElementNS('http://www.w3.org/2000/svg','text');text.textContent=id;text.setAttribute('x',String(place.x+place.width/2));text.setAttribute('y',String(place.y+place.height/2));text.setAttribute('text-anchor','middle');text.setAttribute('class','ply-piece-badge');group.append(text);
      }
    }
    bed.replaceChildren(element);
    svgButton.textContent=`Export SVG · sheet ${index+1}`;dxfButton.textContent=`Export DXF · sheet ${index+1}`;
  }
  const color=(index:number)=>`hsl(${(index*137.508+38)%360} 35% 65%)`;
  const current=()=>result??inspection;
  function resetLocalSettings() {jointOverrides={};panelOverrides={};selectedId=null;selectedJoint='*';}
  function panelBounds(loops:V2[][]) {
    const p=loops.flat(),xs=p.map(v=>v[0]),ys=p.map(v=>v[1]);
    const x=Math.min(...xs),y=Math.min(...ys),X=Math.max(...xs),Y=Math.max(...ys);
    return {x,y,width:X-x,height:Y-y};
  }
  function pointInside(point:V2,loops:V2[][]):boolean {
    let inside=false;
    for(const loop of loops)for(let i=0,j=loop.length-1;i<loop.length;j=i++) {
      const a=loop[i],b=loop[j];
      if((a[1]>point[1])!==(b[1]>point[1])&&point[0]<(b[0]-a[0])*(point[1]-a[1])/(b[1]-a[1])+a[0])inside=!inside;
    }
    return inside;
  }
  function selectPanel(id:string,joint?:string) {
    const model=current();if(!model?.panels.some(p=>p.id===id))return;
    selectedId=id;
    if(joint)selectedJoint=joint;
    if(selectedJoint!=='*'&&!model.joints.some(j=>j.key===selectedJoint&&(j.a===id||j.b===id)))selectedJoint='*';
    const index=model.panels.findIndex(p=>p.id===id),si=model.sheets.findIndex(s=>s.placements.some(p=>p.panel===index));
    if(si>=0)sheet.value=String(si);
    view.value='panels';renderBed();renderTable();draw();
  }
  function renderInspector() {
    const model=current(),panel=model?.panels.find(p=>p.id===selectedId);
    inspector.hidden=!panel;if(!model||!panel)return;
    q('[data-piece-name]').textContent=panel.id;
    const connected=model.joints.filter(j=>j.a===panel.id||j.b===panel.id),unique=[...new Map(connected.map(j=>[j.key,j])).values()];
    jointSelect.replaceChildren();
    const all=document.createElement('option');all.value='*';all.textContent=`All ${unique.length} shared joints on ${panel.id}`;jointSelect.append(all);
    for(const joint of unique){const opt=document.createElement('option');opt.value=joint.key;opt.textContent=`${joint.id}: ${joint.a} ↔ ${joint.b}`;jointSelect.append(opt);}
    if(selectedJoint!=='*'&&!unique.some(j=>j.key===selectedJoint))selectedJoint='*';jointSelect.value=selectedJoint;
    const targets=connected.filter(j=>selectedJoint==='*'||j.key===selectedJoint);
    const signatures=targets.map(j=>JSON.stringify(jointOverrides[j.key]??null));
    const same=signatures.every(s=>s===signatures[0]),local=targets.length?jointOverrides[targets[0].key]:undefined;
    jointMode.value=!same?'mixed':!local?'inherit':(local.fingerCount??0)>0?'count':'width';
    jointValue.value=String(local?.fingerCount||local?.fingerWidth||((jointMode.value==='count')?5:settings().fingerWidth));
    updateJointInput();
    q('[data-joint-summary]').textContent=connected.length?`${targets.map(j=>`${j.id} (${j.a} ↔ ${j.b}): ${j.fingers} segments, ${j.pitch.toFixed(2)} mm wide${jointOverrides[j.key]?' · shared override':''}`).join('; ')}. ${result?'Generated values.':'Last generated values; settings are pending.'}`:'This piece has no touching joints.';
    q<HTMLButtonElement>('[data-action=apply-joint]').disabled=!targets.length||jointMode.value==='mixed';
    panelKerf.value=panelOverrides[panel.id]?.kerf===undefined?'':String(panelOverrides[panel.id].kerf);
    panelEngrave.checked=panelOverrides[panel.id]?.engrave??true;
    const neighbors=q('[data-neighbors]');neighbors.replaceChildren();
    for(const joint of unique){const id=joint.a===panel.id?joint.b:joint.a,button=document.createElement('button');button.type='button';button.textContent=`${joint.id} → ${id}`;button.addEventListener('click',()=>selectPanel(id,joint.key));neighbors.append(button);}
    const box=panelBounds(panel.cutOutlines),pad=Math.max(box.width,box.height)*.09;
    const svg=q<SVGSVGElement>('[data-piece-preview]');
    svg.setAttribute('viewBox',`${box.x-pad} ${-box.y-box.height-pad} ${box.width+2*pad} ${box.height+2*pad}`);
    svg.replaceChildren();
    const ns='http://www.w3.org/2000/svg',outline=document.createElementNS(ns,'path');
    outline.setAttribute('d',panel.cutOutlines.map(l=>l.map((p,i)=>`${i?'L':'M'}${p[0]},${-p[1]}`).join(' ')+'Z').join(' '));
    outline.setAttribute('fill',color(model.panels.indexOf(panel)));outline.setAttribute('fill-opacity','.18');outline.setAttribute('fill-rule','evenodd');outline.setAttribute('stroke','#a80000');outline.setAttribute('vector-effect','non-scaling-stroke');svg.append(outline);
    const project=(p:V3):V2=>[p.reduce((s,n,i)=>s+n*panel.u[i],0),-p.reduce((s,n,i)=>s+n*panel.v[i],0)];
    for(const joint of connected) {
      const [a,b]=joint.segment.map(project),group=document.createElementNS(ns,'g'),line=document.createElementNS(ns,'line'),text=document.createElementNS(ns,'text');
      group.dataset.joint=joint.key;group.setAttribute('role','button');group.setAttribute('tabindex','0');group.setAttribute('aria-label',`Edit ${joint.id}: ${joint.a} and ${joint.b}`);
      for(const [key,value] of Object.entries({x1:a[0],y1:a[1],x2:b[0],y2:b[1]}))line.setAttribute(key,String(value));
      line.setAttribute('stroke',selectedJoint===joint.key?'#075e54':'#2866aa');line.setAttribute('stroke-width','3');line.setAttribute('vector-effect','non-scaling-stroke');line.setAttribute('stroke-dasharray','5 3');
      text.setAttribute('x',String((a[0]+b[0])/2));text.setAttribute('y',String((a[1]+b[1])/2));text.setAttribute('text-anchor','middle');text.setAttribute('font-size',String(Math.max(box.width,box.height)*.045));text.setAttribute('fill','#172d34');text.setAttribute('stroke','white');text.setAttribute('stroke-width','1');text.setAttribute('paint-order','stroke');text.textContent=joint.id;
      const choose=()=>{selectedJoint=joint.key;renderInspector();};group.addEventListener('click',choose);group.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();choose();}});group.append(line,text);svg.append(group);
    }
  }
  function updateJointInput() {
    const mode=jointMode.value,isCount=mode==='count';
    q('[data-joint-value-label]').textContent=isCount?'Finger segments (odd count)':'Target finger width (mm)';
    jointValue.disabled=mode==='inherit'||mode==='mixed';jointValue.min=isCount?'3':String(settings().thickness);jointValue.max=isCount?'999':'500';jointValue.step=isCount?'1':'0.5';
    q<HTMLButtonElement>('[data-action=apply-joint]').disabled=mode==='mixed'||!current()?.joints.some(j=>j.a===selectedId||j.b===selectedId);
  }
  function applyJointSettings() {
    try {
      const model=current();if(!model||!selectedId)return;
      const targets=model.joints.filter(j=>(j.a===selectedId||j.b===selectedId)&&(selectedJoint==='*'||j.key===selectedJoint));
      const choice=jointMode.value,value=jointValue.value===''?NaN:Number(jointValue.value);
      if(choice==='mixed')return;
      if(choice==='count') {
        if(value<3)throw new Error('Choose an odd count of at least 3, or use global settings.');
        validateSettings({...settings(),fingerCount:value});
        for(const joint of targets)if(joint.length/value<settings().thickness-1e-5)throw new Error(`${joint.id}: reduce the count so each finger is at least the material thickness.`);
      } else if(choice==='width')validateSettings({...settings(),fingerCount:0,fingerWidth:value});
      for(const joint of targets) {
        if(choice==='inherit')delete jointOverrides[joint.key];
        else jointOverrides[joint.key]=choice==='count'?{fingerCount:value}:{fingerWidth:value};
      }
      invalidate('Shared joint settings changed on both mating pieces. Generate panels to apply.');
    }catch(error){say(error instanceof Error?error.message:String(error),true);}
  }
  function renderTable() {
    const model=current();if(!model)return;
    if(!model.panels.some(p=>p.id===selectedId))selectedId=model.panels[0]?.id??null;
    legend.replaceChildren();
    const el=document.createElement('table');
    el.innerHTML='<thead><tr><th>Piece</th><th>Cut bounds (mm)</th><th>Sheet</th><th>Engraving</th><th>Shared joints</th></tr></thead>';
    const body=document.createElement('tbody');
    for(let index=0;index<model.panels.length;index++) {
      const panel=model.panels[index],si=model.sheets.findIndex(s=>s.placements.some(p=>p.panel===index)),place=model.sheets[si].placements.find(p=>p.panel===index)!;
      const button=document.createElement('button');button.type='button';button.setAttribute('aria-label',`Inspect ${panel.id}`);button.setAttribute('aria-pressed',String(selectedId===panel.id));
      const swatch=document.createElement('span');swatch.className='ply-swatch';swatch.style.background=color(index);swatch.setAttribute('aria-hidden','true');button.append(swatch,document.createTextNode(panel.id));button.addEventListener('click',()=>selectPanel(panel.id));legend.append(button);
      const row=document.createElement('tr'),name=document.createElement('td'),inspect=document.createElement('button');inspect.type='button';inspect.textContent=panel.id;inspect.addEventListener('click',()=>selectPanel(panel.id));name.append(inspect);row.append(name);
      for(const text of [`${place.width.toFixed(2)} × ${place.height.toFixed(2)}`,String(si+1),!labels.checked||panel.engrave===false?'Off':labelStrokes(panel,place).length?'On':'Omitted: no clear area',model.joints.filter(j=>j.a===panel.id||j.b===panel.id).map(j=>`${j.id}: ${j.fingers}`).join(', ')||'None']) {const td=document.createElement('td');td.textContent=text;row.append(td);}
      body.append(row);
    }
    el.append(body);table.replaceChildren(el);renderInspector();
  }
  async function run() {
    invalidate('Generating panels… Small models work best; this calculation runs in your browser.');
    const version=revision; generate.disabled=true; root.setAttribute('aria-busy','true');
    // Give the browser a frame to display the busy state before geometry work.
    await new Promise(resolve=>setTimeout(resolve,40));
    try {
      if (version!==revision) return;
      const s=settings();
      validateSettings(s);
      scaleFactor();
      if (usingExample) {refreshModel();}
      if(!usingExample&&!importValid)throw new Error(importReport?.message??'The imported mesh is not valid. Check the repair report.');
      if (!triangles.length) throw new Error('Import an STL or load the example first.');
      const converted=createPanels(triangles,s,{mode:mode.value as InputMode,jointSettings:jointOverrides,panelSettings:panelOverrides});
      if (version!==revision) return;
      result=converted;inspection=converted;q('[data-pending]').hidden=true;
      sheet.replaceChildren(...result.sheets.map((_,i)=>{const opt=document.createElement('option');opt.value=String(i);opt.textContent=`${i+1} of ${result!.sheets.length}`;return opt;}));
      setExports(true);renderTable();renderBed();draw();
      say(`${result.panels.length} panels · ${result.joints.length} joints · ${result.sheets.length} sheets. ${result.warnings.join(' ')}`);
    } catch(error) {
      result=null;setExports(false);say(error instanceof Error?error.message:String(error),true);draw();
    } finally {generate.disabled=!usingExample&&!importValid;root.removeAttribute('aria-busy');}
  }
  async function loadFile() {
    const selected=file.files?.[0];if (!selected) return;
    resetLocalSettings();invalidate('Reading STL…',false);const version=revision;
    triangles=[];source=null;usingExample=false;importValid=false;importReport=null;importDetails.hidden=true;cleaned.disabled=true;generate.disabled=true;describe('');draw();
    try {
      if (selected.size>10*1024*1024) throw new Error('Choose an STL smaller than 10 MiB.');
      const data=await selected.arrayBuffer();
      if (version!==revision) return;
      source=data;refreshModel();
      if(importValid)say('Model imported. Check dimensions and thickness, then generate panels.');
    } catch(error) {if (version===revision) say(error instanceof Error?error.message:String(error),true);}
  }
  function download(format:'svg'|'dxf') {
    if (!result) return;
    const index=Number(sheet.value),text=format==='svg'?exportSVG(result,index,labels.checked):exportDXF(result,index,labels.checked);
    const url=URL.createObjectURL(new Blob([text],{type:format==='svg'?'image/svg+xml':'application/dxf'}));
    const a=document.createElement('a');a.href=url;a.download=`ply-cutter-sheet-${index+1}.${format}`;a.click();
    setTimeout(()=>URL.revokeObjectURL(url),1000);
  }
  function draw() {
    const model=current();hitRegions=[];
    const rect=canvas.getBoundingClientRect(),w=rect.width||400,h=rect.height||340,dpr=Math.min(window.devicePixelRatio||1,2);
    canvas.width=Math.round(w*dpr);canvas.height=Math.round(h*dpr);
    const ctx=canvas.getContext('2d');if (!ctx) return;
    ctx.scale(dpr,dpr);ctx.fillStyle='#edf1f2';ctx.fillRect(0,0,w,h);
    if (!triangles.length) {ctx.fillStyle='#43585f';ctx.font='16px system-ui';ctx.fillText('Import an STL to preview it.',20,h/2);return;}
    const lo:V3=[Infinity,Infinity,Infinity],hi:V3=[-Infinity,-Infinity,-Infinity];
    for (const t of triangles) for (const p of t) for (let i=0;i<3;i++) {lo[i]=Math.min(lo[i],p[i]);hi[i]=Math.max(hi[i],p[i]);}
    const center=lo.map((n,i)=>(n+hi[i])/2),scale=zoom*Math.min(w,h)*0.7/(Math.hypot(...hi.map((n,i)=>n-lo[i]))+explode*2||1);
    const a=yaw*Math.PI/180,b=pitch*Math.PI/180;
    const project=(p:V3):[number,number,number]=>{
      const x=p[0]-center[0],y=p[1]-center[1],z=p[2]-center[2];
      const X=x*Math.cos(a)-y*Math.sin(a),Y=x*Math.sin(a)+y*Math.cos(a);
      return [w/2+X*scale,h/2-(z*Math.cos(b)-Y*Math.sin(b))*scale,Y*Math.cos(b)+z*Math.sin(b)];
    };
    type Face={loops:V3[][];color:string;depth:number;id?:string};const faces:Face[]=[];
    const badges=new Map<string,[number,number,number]>();
    if (!model||view.value==='source') {
      for (const t of triangles) faces.push({loops:[t],color:'#b9a17b',depth:t.reduce((v,p)=>v+project(p)[2],0)/3});
    } else for (let i=0;i<model.panels.length;i++) {
      const panel=model.panels[i],t=model.settings.thickness/2;
      const world=(p:V2,side:number):V3=>{
        const v=panelPoint(panel,p),direction=panel.outward??panel.normal;return v.map((n,j)=>n+panel.normal[j]*side*t+direction[j]*explode) as V3;
      };
      for (const side of [-1,1]) {
        const loops=panel.outlines.map(l=>l.map(p=>world(p,side)));
        faces.push({loops,id:panel.id,color:color(i),depth:loops[0].reduce((v,p)=>v+project(p)[2],0)/loops[0].length});
        if(pieceIds.checked) {
          const box=panelBounds(panel.outlines),points:V2[]=[[box.x+box.width/2,box.y+box.height/2]];
          for(let y=1;y<=9;y++)for(let x=1;x<=9;x++)points.push([box.x+box.width*x/10,box.y+box.height*y/10]);
          const anchor=points.find(p=>pointInside(p,panel.outlines));
          if(anchor){const point=project(world(anchor,side)),previous=badges.get(panel.id);if(!previous||point[2]>previous[2])badges.set(panel.id,point);}
        }
      }
      for (const loop of panel.outlines) for (let k=0;k<loop.length;k++) {
        const next=loop[(k+1)%loop.length],points=[world(loop[k],-1),world(next,-1),world(next,1),world(loop[k],1)];
        faces.push({loops:[points],id:panel.id,color:'#8f7857',depth:points.reduce((v,p)=>v+project(p)[2],0)/4});
      }
    }
    faces.sort((a,b)=>a.depth-b.depth);
    for (const face of faces) {
      ctx.beginPath();
      for (const loop of face.loops) {loop.forEach((p,i)=>{const [x,y]=project(p);if(i)ctx.lineTo(x,y);else ctx.moveTo(x,y);});ctx.closePath();}
      ctx.fillStyle=face.color;ctx.fill('evenodd');ctx.lineWidth=face.id===selectedId?2:0.7;ctx.strokeStyle=face.id===selectedId?'#154a8a':'#263b4188';ctx.stroke();
      if(face.id)hitRegions.push({id:face.id,loops:face.loops.map(loop=>loop.map(p=>{const [x,y]=project(p);return [x,y] as V2;}))});
    }
    for(const [id,[x,y]] of badges) {
      if([...hitRegions].reverse().find(hit=>pointInside([x,y],hit.loops))?.id!==id)continue;
      ctx.font='bold 13px system-ui';const width=ctx.measureText(id).width+10;ctx.fillStyle='#fffffff0';ctx.fillRect(x-width/2,y-11,width,20);ctx.fillStyle=id===selectedId?'#154a8a':'#172d34';ctx.textAlign='center';ctx.fillText(id,x,y+4);ctx.textAlign='start';
    }
    ctx.fillStyle='#43585f';ctx.font='14px system-ui';ctx.fillText(!model||view.value==='source'?'Original STL':result?'Finger-jointed panels':'Previous panels — generate to update',12,h-12);
  }
  pieceIds.addEventListener('change',()=>{renderBed();draw();});
  jointSelect.addEventListener('change',()=>{selectedJoint=jointSelect.value;renderInspector();});
  jointMode.addEventListener('change',()=>{
    if(jointMode.value==='count'&&(!Number.isInteger(Number(jointValue.value))||Number(jointValue.value)<3||Number(jointValue.value)%2===0))jointValue.value='5';
    if(jointMode.value==='width')jointValue.value=String(settings().fingerWidth);
    updateJointInput();
  });
  q('[data-action=apply-joint]').addEventListener('click',applyJointSettings);
  q('[data-action=apply-panel]').addEventListener('click',()=>{
    try {
      if(!selectedId)return;
      const kerf=panelKerf.value===''?undefined:Number(panelKerf.value);
      validateSettings({...settings(),kerf:kerf??settings().kerf});
      panelOverrides[selectedId]={...(kerf===undefined?{}:{kerf}),engrave:panelEngrave.checked};
      invalidate('Piece settings changed. Generate panels to apply.');
    }catch(error){say(error instanceof Error?error.message:String(error),true);}
  });
  q('[data-action=reset-panel]').addEventListener('click',()=>{
    if(!selectedId)return;delete panelOverrides[selectedId];
    for(const joint of current()?.joints??[])if(joint.a===selectedId||joint.b===selectedId)delete jointOverrides[joint.key];
    invalidate('Piece settings and its shared joints now inherit global values. Generate panels to apply.');
  });
  file.addEventListener('change',()=>void loadFile());
  repair.addEventListener('change',()=>{resetLocalSettings();invalidate('Repair setting changed. Local settings cleared.',false);if(source)refreshModel();});
  cleaned.addEventListener('click',()=>{
    if(!source||!importValid)return;
    const url=URL.createObjectURL(new Blob([exportSTL(triangles)],{type:'model/stl'})),a=document.createElement('a');a.href=url;a.download='ply-cutter-cleaned.stl';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);
  });
  const loadExample=(kind:InputMode)=>{resetLocalSettings();invalidate('Loading example…',false);usingExample=true;source=null;file.value='';units.value='mm';modelScale.value='1';mode.value=kind;updateModeHelp();void run();};
  q<HTMLButtonElement>('[data-action=example]').addEventListener('click',()=>loadExample('panels'));
  q<HTMLButtonElement>('[data-action=solid-example]').addEventListener('click',()=>loadExample('solid'));
  function updateModeHelp(){q('[data-mode-help]').textContent=mode.value==='solid'?'Closed solid: outer faces become boards with thickness growing inward. Through-holes stay open; angled seams use square-cut relief, with visible gaps.':'Existing panels: the STL must already model boards at the selected material thickness.';}
  mode.addEventListener('change',()=>{resetLocalSettings();invalidate('Input mode changed. Local settings cleared.',false);updateModeHelp();if(usingExample){modelScale.value='1';refreshModel();}});
  modelScale.addEventListener('input',()=>{resetLocalSettings();invalidate('Scale changed. Local settings cleared.',false);refreshModel();});
  for (const input of settingsInputs) input.addEventListener('input',()=>{
    if(input.dataset.setting==='thickness'){resetLocalSettings();invalidate('Thickness changed. Local settings cleared.',false);}
    else invalidate();
    q<HTMLInputElement>('[data-setting=fingerWidth]').disabled=Number(q<HTMLInputElement>('[data-setting=fingerCount]').value)>0;
  });
  units.addEventListener('change',()=>{
    resetLocalSettings();invalidate('Units changed. Local settings cleared.',false);
    if (usingExample) {units.value='mm';say('The example uses millimetres.');return;}
    if (source)refreshModel();
  });
  generate.addEventListener('click',()=>void run());
  sheet.addEventListener('change',renderBed);labels.addEventListener('change',()=>{renderBed();renderTable();});
  svgButton.addEventListener('click',()=>download('svg'));dxfButton.addEventListener('click',()=>download('dxf'));
  view.addEventListener('change',draw);
  const range=(name:string)=>q<HTMLInputElement>(`[data-view=${name}]`);
  function updateView() {yaw=Number(range('orbit').value);pitch=Number(range('tilt').value);explode=Number(range('explode').value);zoom=Number(range('zoom').value)/100;draw();}
  for (const input of root.querySelectorAll<HTMLInputElement>('[data-view]')) input.addEventListener('input',updateView);
  q<HTMLButtonElement>('[data-action=reset]').addEventListener('click',()=>{
    for (const [name,value] of Object.entries({orbit:35,tilt:25,explode:0,zoom:100})) range(name).value=String(value);
    updateView();
  });
  canvas.addEventListener('pointerdown',e=>{drag={x:e.clientX,y:e.clientY,id:e.pointerId,startX:e.clientX,startY:e.clientY,moved:false};canvas.setPointerCapture(e.pointerId);});
  canvas.addEventListener('pointermove',e=>{
    if (!drag||drag.id!==e.pointerId) return;
    if(Math.hypot(e.clientX-drag.startX,e.clientY-drag.startY)>5)drag.moved=true;
    yaw=((yaw+(e.clientX-drag.x)*0.5+540)%360)-180;pitch=Math.max(-80,Math.min(80,pitch+(e.clientY-drag.y)*0.5));
    drag.x=e.clientX;drag.y=e.clientY;range('orbit').value=String(yaw);range('tilt').value=String(pitch);draw();
  });
  canvas.addEventListener('pointerup',e=>{
    if(drag&&!drag.moved&&Math.hypot(e.clientX-drag.startX,e.clientY-drag.startY)<=5){const rect=canvas.getBoundingClientRect(),point:V2=[e.clientX-rect.left,e.clientY-rect.top];const hit=[...hitRegions].reverse().find(region=>pointInside(point,region.loops));if(hit)selectPanel(hit.id);}
    drag=null;
  });canvas.addEventListener('pointercancel',()=>{drag=null;});
  // The library stays independent; the interface follows the host element lifecycle.
  const observer=new ResizeObserver(()=>{if(root.isConnected)draw();else observer.disconnect();});
  observer.observe(canvas);
  void run();
  return root;
}