const canvas = document.getElementById('mainCanvas'); const ctx = canvas.getContext('2d'); const inputs = { materialThickness: document.getElementById('materialThickness'), kerf: document.getElementById('kerf'), clearance: document.getElementById('clearance'), fingerWidth: document.getElementById('fingerWidth'), sheetWidth: document.getElementById('sheetWidth'), sheetHeight: document.getElementById('sheetHeight'), partGap: document.getElementById('partGap'), partName: document.getElementById('partName'), partWidth: document.getElementById('partWidth'), partHeight: document.getElementById('partHeight'), polySides: document.getElementById('polySides'), polyRadius: document.getElementById('polyRadius'), edgePreset: document.getElementById('edgePreset'), holeType: document.getElementById('holeType'), holeX: document.getElementById('holeX'), holeY: document.getElementById('holeY'), holeDiameter: document.getElementById('holeDiameter'), holeWidth: document.getElementById('holeWidth'), holeHeight: document.getElementById('holeHeight'), posX: document.getElementById('posX'), posY: document.getElementById('posY'), posZ: document.getElementById('posZ'), rotX: document.getElementById('rotX'), rotY: document.getElementById('rotY'), rotZ: document.getElementById('rotZ'), showGrid: document.getElementById('showGrid'), showJoints: document.getElementById('showJoints'), zoomSlider: document.getElementById('zoomSlider'), boxWidth: document.getElementById('boxWidth'), boxDepth: document.getElementById('boxDepth'), boxHeight: document.getElementById('boxHeight'), boxRef: document.getElementById('boxRef') }; const buttons = { addRect: document.getElementById('addRectBtn'), addPoly: document.getElementById('addPolyBtn'), box: document.getElementById('boxBtn'), duplicate: document.getElementById('duplicateBtn'), delete: document.getElementById('deleteBtn'), addHole: document.getElementById('addHoleBtn'), export: document.getElementById('exportBtn'), saveProject: document.getElementById('saveProjectBtn'), loadProject: document.getElementById('loadProjectBtn'), viewModel: document.getElementById('viewModelBtn'), viewSolid: document.getElementById('viewSolidBtn'), viewLayout: document.getElementById('viewLayoutBtn'), tabPart: document.getElementById('tabPartBtn'), tabBox: document.getElementById('tabBoxBtn'), tabSetup: document.getElementById('tabSetupBtn'), buildBox: document.getElementById('buildBoxBtn') }; const panes = { part: document.getElementById('tabPart'), box: document.getElementById('tabBox'), setup: document.getElementById('tabSetup') }; const boxSummary = document.getElementById('boxSummary'); function setConfigTab(tab) { panes.part.hidden = tab !== 'part'; panes.box.hidden = tab !== 'box'; panes.setup.hidden = tab !== 'setup'; buttons.tabPart.classList.toggle('active', tab === 'part'); buttons.tabBox.classList.toggle('active', tab === 'box'); buttons.tabSetup.classList.toggle('active', tab === 'setup'); if (tab === 'box') updateBoxSummary(); } const partsList = document.getElementById('partsList'); const holesList = document.getElementById('holesList'); const statusText = document.getElementById('statusText'); const state = { settings: { materialThickness: 3, kerf: 0.12, clearance: 0.08, fingerWidth: 14, sheetWidth: 600, sheetHeight: 400, partGap: 8 }, box: { width: 140, depth: 90, height: 70, reference: 'outer' }, viewMode: 'model', showGrid: true, showJoints: true, zoom: 1, camera: { yaw: Math.PI / 4, pitch: Math.PI / 3, panX: 0, panY: 0 }, parts: [], selectedId: null, selectedHoleId: null, hoverResizeEdge: null, hoverHoleHandle: null, drag: null }; let nextId = 1; let nextHoleId = 1; const SNAP_DISTANCE = 6; const CONTACT_TOLERANCE = 1.2; const MIN_PANEL_SIZE = 5; const RESIZE_HIT_DISTANCE = 11; const RESIZE_VECTOR_LENGTH = 40; function mm(value, fallback = 0) { const parsed = Number(value); return Number.isFinite(parsed) ? parsed : fallback; } function clamp(value, min, max) { return Math.min(max, Math.max(min, value)); } function rad(degrees) { return (degrees * Math.PI) / 180; } function round(value) { return Math.round(value * 1000) / 1000; } function setStatus(text) { statusText.textContent = text; } function jointBehavior(part) { return part.edgePreset === 'alternate' ? 'auto' : part.edgePreset || 'auto'; } function selectedPart() { return state.parts.find((part) => part.id === state.selectedId) || null; } function selectedHole() { const part = selectedPart(); return part?.holes?.find((hole) => hole.id === state.selectedHoleId) || null; } function createRectanglePart(overrides = {}) { const id = nextId++; return { id, type: 'rect', name: overrides.name || `Panel ${id}`, width: overrides.width ?? 100, height: overrides.height ?? 70, sides: 4, radius: 45, x: overrides.x ?? 0, y: overrides.y ?? 0, z: overrides.z ?? 0, rx: overrides.rx ?? 0, ry: overrides.ry ?? 0, rz: overrides.rz ?? 0, edgePreset: overrides.edgePreset || 'auto', edgeModes: overrides.edgeModes || ['tabs', 'slots', 'tabs', 'slots'], holes: overrides.holes ? structuredClone(overrides.holes) : [], color: overrides.color || colorForId(id) }; } function createPolygonPart(overrides = {}) { const id = nextId++; const sides = overrides.sides ?? 6; const radius = overrides.radius ?? 42; return { id, type: 'poly', name: overrides.name || `Polygon ${id}`, width: radius * 2, height: radius * 2, sides, radius, x: overrides.x ?? 0, y: overrides.y ?? 0, z: overrides.z ?? 0, rx: overrides.rx ?? 0, ry: overrides.ry ?? 0, rz: overrides.rz ?? 0, edgePreset: overrides.edgePreset || 'auto', edgeModes: edgeModesForPreset(overrides.edgePreset || 'auto', sides), holes: overrides.holes ? structuredClone(overrides.holes) : [], color: overrides.color || colorForId(id) }; } function colorForId(id) { const palette = ['#0f766e', '#9a3412', '#2563eb', '#7c2d12', '#2f855a', '#8a3ffc', '#b45309', '#be123c']; return palette[(id - 1) % palette.length]; } function edgeModesForPreset(preset, count) { if (preset === 'tabs') return Array(count).fill('tabs'); if (preset === 'slots') return Array(count).fill('slots'); if (preset === 'alternate') { return Array.from({ length: count }, (_value, index) => (index % 2 === 0 ? 'tabs' : 'slots')); } return Array(count).fill('none'); } function localVertices(part) { if (part.type === 'rect') { const w = part.width / 2; const h = part.height / 2; return [ { x: -w, y: -h }, { x: w, y: -h }, { x: w, y: h }, { x: -w, y: h } ]; } const sides = clamp(Math.round(part.sides || 3), 3, 16); const radius = part.radius || 40; return Array.from({ length: sides }, (_value, index) => { const angle = -Math.PI / 2 + (index * Math.PI * 2) / sides; return { x: Math.cos(angle) * radius, y: Math.sin(angle) * radius }; }); } function applyPartGeometry(part, updates) { Object.assign(part, updates); const edgeCount = localVertices(part).length; part.edgeModes = edgeModesForPreset(part.edgePreset, edgeCount); if (part.type === 'poly') { part.width = part.radius * 2; part.height = part.radius * 2; } } function seedScene() { state.parts = [ createRectanglePart({ name: 'Base', width: 140, height: 90, y: 0, edgePreset: 'auto' }), createRectanglePart({ name: 'Front', width: 140, height: 70, y: -45, z: 35, rx: 90, edgePreset: 'auto' }), createRectanglePart({ name: 'Right', width: 90, height: 70, x: 70, z: 35, ry: 90, edgePreset: 'auto' }) ]; state.selectedId = state.parts[0].id; } function syncInputsFromState() { inputs.materialThickness.value = state.settings.materialThickness; inputs.kerf.value = state.settings.kerf; inputs.clearance.value = state.settings.clearance; inputs.fingerWidth.value = state.settings.fingerWidth; inputs.sheetWidth.value = state.settings.sheetWidth; inputs.sheetHeight.value = state.settings.sheetHeight; inputs.partGap.value = state.settings.partGap; inputs.showGrid.checked = state.showGrid; inputs.showJoints.checked = state.showJoints; inputs.zoomSlider.value = state.zoom; inputs.boxWidth.value = state.box.width; inputs.boxDepth.value = state.box.depth; inputs.boxHeight.value = state.box.height; inputs.boxRef.value = state.box.reference; inputs.holeType.value = 'circle'; inputs.holeX.value = 0; inputs.holeY.value = 0; inputs.holeDiameter.value = 12; inputs.holeWidth.value = 20; inputs.holeHeight.value = 10; syncInspector(); } function syncInspector() { const part = selectedPart(); const disabled = !part; [ inputs.partName, inputs.partWidth, inputs.partHeight, inputs.polySides, inputs.polyRadius, inputs.edgePreset, inputs.holeType, inputs.holeX, inputs.holeY, inputs.holeDiameter, inputs.holeWidth, inputs.holeHeight, inputs.posX, inputs.posY, inputs.posZ, inputs.rotX, inputs.rotY, inputs.rotZ ].forEach((input) => { input.disabled = disabled; }); buttons.addHole.disabled = disabled; if (!part) { inputs.partName.value = ''; inputs.partWidth.value = ''; inputs.partHeight.value = ''; inputs.polySides.value = ''; inputs.polyRadius.value = ''; inputs.edgePreset.value = 'none'; holesList.innerHTML = ''; inputs.posX.value = ''; inputs.posY.value = ''; inputs.posZ.value = ''; inputs.rotX.value = ''; inputs.rotY.value = ''; inputs.rotZ.value = ''; return; } inputs.partName.value = part.name; inputs.partWidth.value = round(part.width); inputs.partHeight.value = round(part.height); inputs.polySides.value = part.sides; inputs.polyRadius.value = round(part.radius); inputs.edgePreset.value = part.edgePreset; if (!inputs.edgePreset.value) inputs.edgePreset.value = jointBehavior(part); inputs.posX.value = round(part.x); inputs.posY.value = round(part.y); inputs.posZ.value = round(part.z); inputs.rotX.value = round(part.rx); inputs.rotY.value = round(part.ry); inputs.rotZ.value = round(part.rz); inputs.partWidth.disabled = disabled || part.type !== 'rect'; inputs.partHeight.disabled = disabled || part.type !== 'rect'; inputs.polySides.disabled = disabled || part.type !== 'poly'; inputs.polyRadius.disabled = disabled || part.type !== 'poly'; renderHolesList(); } const CONFIG_VERSION = 1; function serializeConfig() { return { type: 'dxfdesign-config', version: CONFIG_VERSION, settings: state.settings, box: state.box, view: { viewMode: state.viewMode, showGrid: state.showGrid, showJoints: state.showJoints, zoom: state.zoom, camera: state.camera }, parts: state.parts, selectedId: state.selectedId, selectedHoleId: state.selectedHoleId }; } function applyConfig(config) { if (!config || config.type !== 'dxfdesign-config' || !Array.isArray(config.parts)) { throw new Error('Unrecognized configuration file'); } Object.assign(state.settings, config.settings || {}); Object.assign(state.box, config.box || {}); const view = config.view || {}; if (view.viewMode) state.viewMode = view.viewMode; if (typeof view.showGrid === 'boolean') state.showGrid = view.showGrid; if (typeof view.showJoints === 'boolean') state.showJoints = view.showJoints; if (Number.isFinite(view.zoom)) state.zoom = view.zoom; if (view.camera) Object.assign(state.camera, view.camera); state.parts = structuredClone(config.parts); state.drag = null; state.hoverResizeEdge = null; state.hoverHoleHandle = null; // Push id counters past anything imported so new pieces never collide. let maxPartId = 0; let maxHoleId = 0; state.parts.forEach((part) => { maxPartId = Math.max(maxPartId, part.id || 0); (part.holes || []).forEach((hole) => { maxHoleId = Math.max(maxHoleId, hole.id || 0); }); }); nextId = maxPartId + 1; nextHoleId = maxHoleId + 1; const partIds = new Set(state.parts.map((part) => part.id)); state.selectedId = partIds.has(config.selectedId) ? config.selectedId : (state.parts[0]?.id ?? null); const holeIds = new Set((selectedPart()?.holes || []).map((hole) => hole.id)); state.selectedHoleId = holeIds.has(config.selectedHoleId) ? config.selectedHoleId : null; setView(state.viewMode); syncInputsFromState(); renderPartsList(); updateBoxSummary(); draw(); } function renderPartsList() { partsList.innerHTML = ''; state.parts.forEach((part) => { const item = document.createElement('div'); item.className = `part-item${part.id === state.selectedId ? ' selected' : ''}`; item.tabIndex = 0; item.dataset.id = part.id; const title = document.createElement('div'); const badge = document.createElement('div'); const removeButton = document.createElement('button'); title.innerHTML = `
`; title.querySelector('.part-title').textContent = part.name; title.querySelector('.part-meta').textContent = `${part.type === 'rect' ? `${round(part.width)} x ${round(part.height)}` : `${part.sides} sides`} mm`; badge.className = 'part-badge'; badge.textContent = jointBehavior(part); removeButton.className = 'part-remove'; removeButton.type = 'button'; removeButton.title = `Remove ${part.name}`; removeButton.setAttribute('aria-label', `Remove ${part.name}`); removeButton.textContent = 'x'; removeButton.addEventListener('click', (event) => { event.stopPropagation(); deletePart(part.id); }); item.append(title, badge, removeButton); item.addEventListener('click', () => selectPart(part.id)); item.addEventListener('keydown', (event) => { if (event.key === 'Enter' || event.key === ' ') selectPart(part.id); if (event.key === 'Delete' || event.key === 'Backspace') deletePart(part.id); }); partsList.append(item); }); } function selectPart(id) { state.selectedId = id; state.selectedHoleId = null; state.hoverResizeEdge = null; state.hoverHoleHandle = null; syncInspector(); renderPartsList(); draw(); } function selectHole(id) { state.selectedHoleId = id; syncHoleInputs(); renderHolesList(); draw(); } function syncHoleInputs() { const hole = selectedHole(); if (!hole) return; inputs.holeType.value = hole.type; inputs.holeX.value = round(hole.x); inputs.holeY.value = round(hole.y); inputs.holeDiameter.value = round(hole.diameter || 12); inputs.holeWidth.value = round(hole.width || 20); inputs.holeHeight.value = round(hole.height || 10); } function renderHolesList() { const part = selectedPart(); holesList.innerHTML = ''; if (!part) return; const holes = part.holes || []; if (holes.length === 0) { const empty = document.createElement('div'); empty.className = 'empty-note'; empty.textContent = 'No holes'; holesList.append(empty); return; } holes.forEach((hole) => { const item = document.createElement('div'); item.className = `hole-item${hole.id === state.selectedHoleId ? ' selected' : ''}`; item.tabIndex = 0; const label = document.createElement('div'); const removeButton = document.createElement('button'); label.innerHTML = `
`; label.querySelector('.hole-title').textContent = hole.type === 'circle' ? 'Circle hole' : 'Rectangle hole'; label.querySelector('.hole-meta').textContent = hole.type === 'circle' ? `dia ${round(hole.diameter)} at ${round(hole.x)}, ${round(hole.y)}` : `${round(hole.width)} x ${round(hole.height)} at ${round(hole.x)}, ${round(hole.y)}`; removeButton.className = 'part-remove'; removeButton.type = 'button'; removeButton.title = 'Remove hole'; removeButton.setAttribute('aria-label', 'Remove hole'); removeButton.textContent = 'x'; removeButton.addEventListener('click', (event) => { event.stopPropagation(); removeHole(hole.id); }); item.append(label, removeButton); item.addEventListener('click', () => selectHole(hole.id)); item.addEventListener('keydown', (event) => { if (event.key === 'Enter' || event.key === ' ') selectHole(hole.id); if (event.key === 'Delete' || event.key === 'Backspace') removeHole(hole.id); }); holesList.append(item); }); } function resizeCanvas() { const rect = canvas.getBoundingClientRect(); const scale = window.devicePixelRatio || 1; canvas.width = Math.max(1, Math.floor(rect.width * scale)); canvas.height = Math.max(1, Math.floor(rect.height * scale)); ctx.setTransform(scale, 0, 0, scale, 0, 0); draw(); } function rotate3(point, part) { let { x, y, z } = point; const rx = rad(part.rx); const ry = rad(part.ry); const rz = rad(part.rz); let cy = Math.cos(rx); let sy = Math.sin(rx); [y, z] = [y * cy - z * sy, y * sy + z * cy]; cy = Math.cos(ry); sy = Math.sin(ry); [x, z] = [x * cy + z * sy, -x * sy + z * cy]; cy = Math.cos(rz); sy = Math.sin(rz); [x, y] = [x * cy - y * sy, x * sy + y * cy]; return { x: x + part.x, y: y + part.y, z: z + part.z }; } function rotateLocal(point, part) { const rotated = rotate3({ ...point }, { ...part, x: 0, y: 0, z: 0 }); return rotated; } function inverseRotate(point, part) { let { x, y, z } = point; let angle = -rad(part.rz); let c = Math.cos(angle); let s = Math.sin(angle); [x, y] = [x * c - y * s, x * s + y * c]; angle = -rad(part.ry); c = Math.cos(angle); s = Math.sin(angle); [x, z] = [x * c + z * s, -x * s + z * c]; angle = -rad(part.rx); c = Math.cos(angle); s = Math.sin(angle); [y, z] = [y * c - z * s, y * s + z * c]; return { x, y, z }; } function worldToLocal(point, part) { return inverseRotate({ x: point.x - part.x, y: point.y - part.y, z: point.z - part.z }, part); } function partNormal(part) { return normalize(rotateLocal({ x: 0, y: 0, z: 1 }, part)); } function dot(a, b) { return a.x * b.x + a.y * b.y + a.z * b.z; } function normalize(vector) { const length = Math.hypot(vector.x, vector.y, vector.z); if (length <= 0.0001) return { x: 0, y: 0, z: 0 }; return { x: vector.x / length, y: vector.y / length, z: vector.z / length }; } function project(point, width, height) { const scale = state.zoom * 2.2; const camera = worldToCamera(point); return { x: width / 2 + state.camera.panX + camera.x * scale, y: height / 2 + state.camera.panY + camera.y * scale }; } function screenToWorldAtZ(clientX, clientY, z) { const rect = canvas.getBoundingClientRect(); const scale = state.zoom * 2.2; const screenX = clientX - rect.left - canvas.clientWidth / 2 - state.camera.panX; const screenY = clientY - rect.top - canvas.clientHeight / 2 - state.camera.panY; const u = screenX / scale; const v = screenY / scale + z * Math.sin(state.camera.pitch); const groundY = v / Math.cos(state.camera.pitch); const yawCos = Math.cos(state.camera.yaw); const yawSin = Math.sin(state.camera.yaw); return { x: u * yawCos + groundY * yawSin, y: -u * yawSin + groundY * yawCos, z }; } function worldToCamera(point) { const yawCos = Math.cos(state.camera.yaw); const yawSin = Math.sin(state.camera.yaw); const pitchCos = Math.cos(state.camera.pitch); const pitchSin = Math.sin(state.camera.pitch); const x = point.x * yawCos - point.y * yawSin; const y = point.x * yawSin + point.y * yawCos; return { x, y: y * pitchCos - point.z * pitchSin, z: y * pitchSin + point.z * pitchCos }; } function cameraToWorld(point) { const yawCos = Math.cos(state.camera.yaw); const yawSin = Math.sin(state.camera.yaw); const pitchCos = Math.cos(state.camera.pitch); const pitchSin = Math.sin(state.camera.pitch); const y = point.y * pitchCos + point.z * pitchSin; const z = -point.y * pitchSin + point.z * pitchCos; return { x: point.x * yawCos + y * yawSin, y: -point.x * yawSin + y * yawCos, z }; } function screenToLocalOnPart(clientX, clientY, part) { const rect = canvas.getBoundingClientRect(); const scale = state.zoom * 2.2; const cameraX = (clientX - rect.left - canvas.clientWidth / 2 - state.camera.panX) / scale; const cameraY = (clientY - rect.top - canvas.clientHeight / 2 - state.camera.panY) / scale; const rayStart = cameraToWorld({ x: cameraX, y: cameraY, z: 0 }); const rayEnd = cameraToWorld({ x: cameraX, y: cameraY, z: 1 }); const rayDirection = { x: rayEnd.x - rayStart.x, y: rayEnd.y - rayStart.y, z: rayEnd.z - rayStart.z }; const normal = partNormal(part); const denominator = dot(rayDirection, normal); if (Math.abs(denominator) <= 0.0001) return null; const planePoint = { x: part.x, y: part.y, z: part.z }; const t = dot({ x: planePoint.x - rayStart.x, y: planePoint.y - rayStart.y, z: planePoint.z - rayStart.z }, normal) / denominator; return worldToLocal({ x: rayStart.x + rayDirection.x * t, y: rayStart.y + rayDirection.y * t, z: rayStart.z + rayDirection.z * t }, part); } function partWorldPolygon(part) { return localVertices(part).map((vertex) => rotate3({ x: vertex.x, y: vertex.y, z: 0 }, part)); } function gizmoAxes(part, width, height) { const originWorld = { x: part.x, y: part.y, z: part.z }; const origin = project(originWorld, width, height); const length = 44 / Math.max(0.35, state.zoom); return [ { axis: 'x', label: 'X', color: '#dc2626', origin, end: project({ x: originWorld.x + length, y: originWorld.y, z: originWorld.z }, width, height) }, { axis: 'y', label: 'Y', color: '#16a34a', origin, end: project({ x: originWorld.x, y: originWorld.y + length, z: originWorld.z }, width, height) }, { axis: 'z', label: 'Z', color: '#2563eb', origin, end: project({ x: originWorld.x, y: originWorld.y, z: originWorld.z + length }, width, height) } ]; } function resizeHandles(part, width, height) { if (!part || part.type !== 'rect') return []; const halfW = part.width / 2; const halfH = part.height / 2; const definitions = [ { edge: 'top', axis: 'height', normal: { x: 0, y: -1 }, start: { x: -halfW, y: -halfH }, end: { x: halfW, y: -halfH } }, { edge: 'right', axis: 'width', normal: { x: 1, y: 0 }, start: { x: halfW, y: -halfH }, end: { x: halfW, y: halfH } }, { edge: 'bottom', axis: 'height', normal: { x: 0, y: 1 }, start: { x: halfW, y: halfH }, end: { x: -halfW, y: halfH } }, { edge: 'left', axis: 'width', normal: { x: -1, y: 0 }, start: { x: -halfW, y: halfH }, end: { x: -halfW, y: -halfH } } ]; return definitions.map((definition) => { const midpoint = { x: (definition.start.x + definition.end.x) / 2, y: (definition.start.y + definition.end.y) / 2 }; const vectorEnd = { x: midpoint.x + definition.normal.x * RESIZE_VECTOR_LENGTH, y: midpoint.y + definition.normal.y * RESIZE_VECTOR_LENGTH }; return { ...definition, startScreen: project(localPointToWorld(part, definition.start, 0.5), width, height), endScreen: project(localPointToWorld(part, definition.end, 0.5), width, height), midpointScreen: project(localPointToWorld(part, midpoint, 0.5), width, height), vectorEndScreen: project(localPointToWorld(part, vectorEnd, 0.5), width, height) }; }); } function rectEdgeLocalPoints(width, height, edge) { const halfW = width / 2; const halfH = height / 2; if (edge === 'top') return [{ x: -halfW, y: -halfH }, { x: halfW, y: -halfH }]; if (edge === 'right') return [{ x: halfW, y: -halfH }, { x: halfW, y: halfH }]; if (edge === 'bottom') return [{ x: halfW, y: halfH }, { x: -halfW, y: halfH }]; return [{ x: -halfW, y: halfH }, { x: -halfW, y: -halfH }]; } function drawResizeHandles(width, height) { const part = selectedPart(); if (!part || part.type !== 'rect') return; const activeEdge = state.drag?.mode === 'resizePart' ? state.drag.resizeEdge : state.hoverResizeEdge; if (!activeEdge) return; ctx.save(); resizeHandles(part, width, height).forEach((handle) => { const active = handle.edge === activeEdge; ctx.strokeStyle = active ? '#111111' : 'rgba(17, 17, 17, 0.36)'; ctx.fillStyle = active ? '#f59e0b' : '#ffffff'; ctx.lineWidth = active ? 2 : 1.3; ctx.beginPath(); ctx.moveTo(handle.startScreen.x, handle.startScreen.y); ctx.lineTo(handle.endScreen.x, handle.endScreen.y); ctx.stroke(); const size = active ? 10 : 8; ctx.beginPath(); ctx.rect(handle.midpointScreen.x - size / 2, handle.midpointScreen.y - size / 2, size, size); ctx.fill(); ctx.stroke(); }); ctx.restore(); } function drawGizmo(width, height) { const part = selectedPart(); if (!part) return; ctx.save(); ctx.lineWidth = 3; ctx.font = '800 11px Inter, sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; gizmoAxes(part, width, height).forEach((axis) => { const dx = axis.end.x - axis.origin.x; const dy = axis.end.y - axis.origin.y; const length = Math.hypot(dx, dy); if (length < 0.001) return; const ux = dx / length; const uy = dy / length; const head = 9; const wing = 5; ctx.strokeStyle = axis.color; ctx.fillStyle = axis.color; ctx.beginPath(); ctx.moveTo(axis.origin.x, axis.origin.y); ctx.lineTo(axis.end.x, axis.end.y); ctx.stroke(); ctx.beginPath(); ctx.moveTo(axis.end.x, axis.end.y); ctx.lineTo(axis.end.x - ux * head - uy * wing, axis.end.y - uy * head + ux * wing); ctx.lineTo(axis.end.x - ux * head + uy * wing, axis.end.y - uy * head - ux * wing); ctx.closePath(); ctx.fill(); ctx.fillText(axis.label, axis.end.x + ux * 13, axis.end.y + uy * 13); }); const origin = project({ x: part.x, y: part.y, z: part.z }, width, height); ctx.fillStyle = '#ffffff'; ctx.strokeStyle = '#111111'; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.arc(origin.x, origin.y, 5, 0, Math.PI * 2); ctx.fill(); ctx.stroke(); ctx.restore(); } function localPointToWorld(part, point, zOffset = 0) { return rotate3({ x: point.x, y: point.y, z: zOffset }, part); } function drawWorldPolyline(points, color, width = 2, close = false) { if (points.length < 2) return; ctx.strokeStyle = color; ctx.lineWidth = width; ctx.beginPath(); points.forEach((point, index) => { const projected = project(point, canvas.clientWidth, canvas.clientHeight); if (index === 0) ctx.moveTo(projected.x, projected.y); else ctx.lineTo(projected.x, projected.y); }); if (close) ctx.closePath(); ctx.stroke(); } function drawJointOverlays(width, height) { if (!state.showJoints) return; const features = buildFabricationFeatures(); const surfaceOffset = 0.35; ctx.save(); ctx.lineCap = 'round'; ctx.lineJoin = 'round'; state.parts.forEach((part) => { const feature = features.get(part.id); if (!feature) return; if (feature.edgeJoints.some((joints) => joints.length > 0) || feature.edgeCutouts.some((cutouts) => cutouts.length > 0)) { drawWorldPolyline( generateProfile(part, feature).map((point) => localPointToWorld(part, point, surfaceOffset)), '#e11d48', part.id === state.selectedId ? 3.2 : 2.3, true ); } feature.internalCuts.forEach((cut) => { const color = cut.type === 'slit' ? '#7c3aed' : cut.type === 'hole' ? '#f59e0b' : '#0ea5e9'; drawWorldPolyline(cut.points.map((point) => localPointToWorld(part, point, surfaceOffset)), color, part.id === state.selectedId ? 2.8 : 2, true); }); }); ctx.restore(); } function holeHandlePoints(hole) { if (hole.type === 'rect') { const halfW = Math.max(1, hole.width) / 2; const halfH = Math.max(1, hole.height) / 2; return [ { edge: 'left', x: hole.x - halfW, y: hole.y }, { edge: 'right', x: hole.x + halfW, y: hole.y }, { edge: 'top', x: hole.x, y: hole.y - halfH }, { edge: 'bottom', x: hole.x, y: hole.y + halfH } ]; } return [{ edge: 'radius', x: hole.x + Math.max(1, hole.diameter) / 2, y: hole.y }]; } function drawHoleControls(width, height) { const part = selectedPart(); if (!part) return; const surfaceOffset = 0.75; ctx.save(); ctx.lineJoin = 'round'; (part.holes || []).forEach((hole) => { const selected = hole.id === state.selectedHoleId; const points = holeToCut(hole).points.map((point) => localPointToWorld(part, point, surfaceOffset)); drawWorldPolyline(points, selected ? '#111111' : '#f59e0b', selected ? 3 : 1.8, true); if (!selected) return; ctx.fillStyle = '#ffffff'; ctx.strokeStyle = '#111111'; ctx.lineWidth = 1.4; holeHandlePoints(hole).forEach((handle) => { const projected = project(localPointToWorld(part, handle, surfaceOffset), width, height); ctx.beginPath(); ctx.rect(projected.x - 4.5, projected.y - 4.5, 9, 9); ctx.fill(); ctx.stroke(); }); }); ctx.restore(); } function draw() { const width = canvas.clientWidth; const height = canvas.clientHeight; ctx.clearRect(0, 0, width, height); if (state.viewMode === 'layout') { drawLayout(width, height); } else if (state.viewMode === 'solid') { drawSolid(width, height); } else { drawModel(width, height); } } function cross(a, b) { return { x: a.y * b.z - a.z * b.y, y: a.z * b.x - a.x * b.z, z: a.x * b.y - a.y * b.x }; } // Extrude side walls along a local 2D ring; one quad face per edge. // The raw cross-product normal points toward the ring interior, so outwardSign // flips it outward: -1 for an outer perimeter (solid inside), +1 for a hole (empty inside). function pushSolidWalls(faces, ring, toWorld, half, outwardSign) { for (let i = 0; i < ring.length; i += 1) { const a = ring[i]; const b = ring[(i + 1) % ring.length]; const quad = [toWorld(a, half), toWorld(b, half), toWorld(b, -half), toWorld(a, -half)]; const e1 = { x: quad[1].x - quad[0].x, y: quad[1].y - quad[0].y, z: quad[1].z - quad[0].z }; const e2 = { x: quad[3].x - quad[0].x, y: quad[3].y - quad[0].y, z: quad[3].z - quad[0].z }; const n = normalize(cross(e1, e2)); faces.push({ rings: [quad], normal: { x: n.x * outwardSign, y: n.y * outwardSign, z: n.z * outwardSign } }); } } // Faces for one extruded panel: caps (with holes punched), outer walls, hole walls. function partSolidFaces(part, feature) { const thickness = Math.max(0.2, state.settings.materialThickness || 3); const half = thickness / 2; const profile = generateProfile(part, feature); const cuts = (feature?.internalCuts || []) .map((cut) => cut.points) .filter((points) => points && points.length >= 3); const toWorld = (pt, z) => rotate3({ x: pt.x, y: pt.y, z }, part); const ringWorld = (ring, z) => ring.map((pt) => toWorld(pt, z)); const topNormal = partNormal(part); const bottomNormal = { x: -topNormal.x, y: -topNormal.y, z: -topNormal.z }; const faces = []; // Top + bottom caps, each carrying the hole rings so they render punched. faces.push({ rings: [ringWorld(profile, half), ...cuts.map((c) => ringWorld(c, half))], normal: topNormal }); faces.push({ rings: [ringWorld(profile, -half), ...cuts.map((c) => ringWorld(c, -half))], normal: bottomNormal }); // Outer perimeter walls (carries finger/tab/cutout detail) and bored hole walls. pushSolidWalls(faces, profile, toWorld, half, -1); cuts.forEach((ring) => pushSolidWalls(faces, ring, toWorld, half, 1)); return faces; } function shadeRGB(hex, factor) { const clean = hex.replace('#', ''); return [0, 2, 4].map((offset) => clamp(Math.round(parseInt(clean.slice(offset, offset + 2), 16) * factor), 0, 255)); } // Camera-z as an affine function of device screen (x, y). Valid because the // projection is orthographic, so any planar face has z = A*x + B*y + C. function solveDepthPlane(samples) { for (let i = 0; i < samples.length - 2; i += 1) { const p1 = samples[i]; const p2 = samples[i + 1]; const p3 = samples[i + 2]; const det = p1.x * (p2.y - p3.y) + p2.x * (p3.y - p1.y) + p3.x * (p1.y - p2.y); if (Math.abs(det) < 1e-6) continue; return { a: (p1.z * (p2.y - p3.y) + p2.z * (p3.y - p1.y) + p3.z * (p1.y - p2.y)) / det, b: (p1.x * (p2.z - p3.z) + p2.x * (p3.z - p1.z) + p3.x * (p1.z - p2.z)) / det, c: (p1.x * (p2.y * p3.z - p3.y * p2.z) + p2.x * (p3.y * p1.z - p1.y * p3.z) + p3.x * (p1.y * p2.z - p2.y * p1.z)) / det }; } return { a: 0, b: 0, c: samples[0]?.z || 0 }; } // Even-odd scanline fill of a polygon-with-holes, with per-pixel depth test. function rasterFace(buffer, rings, plane, rgb) { const { data, depth, w, h } = buffer; let minY = Infinity; let maxY = -Infinity; rings.forEach((ring) => ring.forEach((p) => { if (p.y < minY) minY = p.y; if (p.y > maxY) maxY = p.y; })); const y0 = Math.max(0, Math.ceil(minY)); const y1 = Math.min(h - 1, Math.floor(maxY)); const xs = []; for (let y = y0; y <= y1; y += 1) { xs.length = 0; rings.forEach((ring) => { for (let i = 0; i < ring.length; i += 1) { const a = ring[i]; const b = ring[(i + 1) % ring.length]; if ((a.y <= y && b.y > y) || (b.y <= y && a.y > y)) { xs.push(a.x + ((y - a.y) / (b.y - a.y)) * (b.x - a.x)); } } }); if (xs.length < 2) continue; xs.sort((p, q) => p - q); for (let k = 0; k + 1 < xs.length; k += 2) { const xa = Math.max(0, Math.ceil(xs[k])); const xb = Math.min(w - 1, Math.floor(xs[k + 1])); for (let x = xa; x <= xb; x += 1) { const idx = y * w + x; const d = plane.a * x + plane.b * y + plane.c; if (d > depth[idx]) { depth[idx] = d; const o = idx * 4; data[o] = rgb[0]; data[o + 1] = rgb[1]; data[o + 2] = rgb[2]; data[o + 3] = 255; } } } } } // Draw a face edge only where that face is the nearest surface (hidden-line removal). function rasterEdge(buffer, a, b, plane, rgb, eps) { const { data, depth, w, h } = buffer; let x0 = Math.round(a.x); let y0 = Math.round(a.y); const x1 = Math.round(b.x); const y1 = Math.round(b.y); const dx = Math.abs(x1 - x0); const dy = -Math.abs(y1 - y0); const sx = x0 < x1 ? 1 : -1; const sy = y0 < y1 ? 1 : -1; let err = dx + dy; for (;;) { if (x0 >= 0 && x0 < w && y0 >= 0 && y0 < h) { const idx = y0 * w + x0; if (plane.a * x0 + plane.b * y0 + plane.c >= depth[idx] - eps) { const o = idx * 4; data[o] = rgb[0]; data[o + 1] = rgb[1]; data[o + 2] = rgb[2]; data[o + 3] = 255; } } if (x0 === x1 && y0 === y1) break; const e2 = 2 * err; if (e2 >= dy) { err += dy; x0 += sx; } if (e2 <= dx) { err += dx; y0 += sy; } } } function drawSolid(width, height) { ctx.fillStyle = '#f1f3f5'; ctx.fillRect(0, 0, width, height); if (state.showGrid) drawGrid(width, height); const w = canvas.width; const h = canvas.height; const dpr = w / Math.max(1, width); // Seed from the canvas (grid + background) so untouched pixels keep showing it. const image = ctx.getImageData(0, 0, w, h); const depth = new Float32Array(w * h).fill(-Infinity); const buffer = { data: image.data, depth, w, h }; const light = normalize({ x: -0.35, y: -0.55, z: 0.9 }); const features = buildFabricationFeatures(); const collected = []; state.parts.forEach((part) => { const selected = part.id === state.selectedId; partSolidFaces(part, features.get(part.id)).forEach((face) => { // Backface cull: drop faces whose outward normal points away from the viewer. if (worldToCamera(face.normal).z <= 0.0001) return; const screenRings = face.rings.map((ring) => ring.map((p) => { const s = project(p, width, height); return { x: s.x * dpr, y: s.y * dpr }; })); const samples = face.rings[0].map((p, i) => ({ x: screenRings[0][i].x, y: screenRings[0][i].y, z: worldToCamera(p).z })); const plane = solveDepthPlane(samples); const factor = 0.5 + 0.5 * Math.abs(dot(face.normal, light)); collected.push({ screenRings, plane, fill: shadeRGB(part.color, selected ? Math.min(1, factor + 0.12) : factor), edge: selected ? [17, 17, 17] : shadeRGB(part.color, factor * 0.45) }); }); }); // Pass 1: fill every face with per-pixel depth testing (true z-buffer occlusion). collected.forEach((face) => rasterFace(buffer, face.screenRings, face.plane, face.fill)); // Pass 2: draw edges where their own face won the depth test. const eps = 0.6; collected.forEach((face) => { face.screenRings.forEach((ring) => { for (let i = 0; i < ring.length; i += 1) { rasterEdge(buffer, ring[i], ring[(i + 1) % ring.length], face.plane, face.edge, eps); } }); }); ctx.putImageData(image, 0, 0); } function drawModel(width, height) { ctx.fillStyle = '#f1f3f5'; ctx.fillRect(0, 0, width, height); if (state.showGrid) drawGrid(width, height); const projected = state.parts .map((part) => { const world = partWorldPolygon(part); return { part, depth: world.reduce((sum, point) => sum + worldToCamera(point).z, 0) / world.length, points: world.map((point) => project(point, width, height)) }; }) .sort((a, b) => a.depth - b.depth); projected.forEach(({ part, points }) => { ctx.beginPath(); points.forEach((point, index) => { if (index === 0) ctx.moveTo(point.x, point.y); else ctx.lineTo(point.x, point.y); }); ctx.closePath(); ctx.fillStyle = part.id === state.selectedId ? tint(part.color, 0.78) : tint(part.color, 0.88); ctx.strokeStyle = part.id === state.selectedId ? '#111111' : part.color; ctx.lineWidth = part.id === state.selectedId ? 2.4 : 1.4; ctx.fill(); ctx.stroke(); const center = points.reduce((acc, point) => ({ x: acc.x + point.x / points.length, y: acc.y + point.y / points.length }), { x: 0, y: 0 }); ctx.fillStyle = '#202018'; ctx.font = '700 12px Inter, sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText(part.name, center.x, center.y); }); drawJointOverlays(width, height); drawHoleControls(width, height); drawResizeHandles(width, height); drawGizmo(width, height); } function drawGrid(width, height) { const origin = project({ x: 0, y: 0, z: 0 }, width, height); const step = 25; const extent = 500; ctx.lineWidth = 1; ctx.strokeStyle = '#dce1e8'; for (let i = -extent; i <= extent; i += step) { const a = project({ x: i, y: -extent, z: 0 }, width, height); const b = project({ x: i, y: extent, z: 0 }, width, height); const c = project({ x: -extent, y: i, z: 0 }, width, height); const d = project({ x: extent, y: i, z: 0 }, width, height); ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.moveTo(c.x, c.y); ctx.lineTo(d.x, d.y); ctx.stroke(); } ctx.strokeStyle = '#aab2c0'; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.moveTo(origin.x - 9, origin.y); ctx.lineTo(origin.x + 9, origin.y); ctx.moveTo(origin.x, origin.y - 9); ctx.lineTo(origin.x, origin.y + 9); ctx.stroke(); } function drawLayout(width, height) { ctx.fillStyle = '#f1f3f5'; ctx.fillRect(0, 0, width, height); const layout = arrangeParts(); const margin = 28; const availableW = Math.max(1, width - margin * 2); const availableH = Math.max(1, height - margin * 2); const scale = Math.min(availableW / state.settings.sheetWidth, availableH / state.settings.sheetHeight) * state.zoom; const originX = width / 2 - (state.settings.sheetWidth * scale) / 2; const originY = height / 2 - (state.settings.sheetHeight * scale) / 2; ctx.fillStyle = '#ffffff'; ctx.strokeStyle = '#c4ccd6'; ctx.lineWidth = 1; ctx.fillRect(originX, originY, state.settings.sheetWidth * scale, state.settings.sheetHeight * scale); ctx.strokeRect(originX, originY, state.settings.sheetWidth * scale, state.settings.sheetHeight * scale); layout.forEach((entry) => { const points = entry.profile.map((point) => ({ x: originX + (point.x + entry.x) * scale, y: originY + (point.y + entry.y) * scale })); ctx.beginPath(); points.forEach((point, index) => { if (index === 0) ctx.moveTo(point.x, point.y); else ctx.lineTo(point.x, point.y); }); ctx.closePath(); ctx.fillStyle = entry.part.id === state.selectedId ? tint(entry.part.color, 0.82) : 'rgba(15, 118, 110, 0.08)'; ctx.strokeStyle = entry.part.id === state.selectedId ? '#111111' : '#0f766e'; ctx.lineWidth = entry.part.id === state.selectedId ? 2 : 1.2; ctx.fill(); ctx.stroke(); ctx.fillStyle = '#23241f'; ctx.font = '700 11px Inter, sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText(entry.part.name, originX + (entry.x + entry.center.x) * scale, originY + (entry.y + entry.center.y) * scale); ctx.strokeStyle = '#be123c'; ctx.lineWidth = 1.1; entry.internalCuts.forEach((cut) => { const cutPoints = cut.points.map((point) => ({ x: originX + (point.x + entry.x) * scale, y: originY + (point.y + entry.y) * scale })); ctx.beginPath(); cutPoints.forEach((point, index) => { if (index === 0) ctx.moveTo(point.x, point.y); else ctx.lineTo(point.x, point.y); }); ctx.closePath(); ctx.stroke(); }); }); } function tint(hex, amount) { const clean = hex.replace('#', ''); const rgb = [0, 2, 4].map((offset) => parseInt(clean.slice(offset, offset + 2), 16)); const blended = rgb.map((value) => Math.round(value + (255 - value) * amount)); return `rgb(${blended[0]}, ${blended[1]}, ${blended[2]})`; } function pointInPolygon(point, polygon) { let inside = false; for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { const xi = polygon[i].x; const yi = polygon[i].y; const xj = polygon[j].x; const yj = polygon[j].y; const intersects = yi > point.y !== yj > point.y && point.x < ((xj - xi) * (point.y - yi)) / (yj - yi) + xi; if (intersects) inside = !inside; } return inside; } function pointOnSegment(point, start, end, tolerance = CONTACT_TOLERANCE) { return distanceToSegment(point, start, end) <= tolerance; } function pointInOrOnPolygon(point, polygon, tolerance = CONTACT_TOLERANCE) { if (pointInPolygon(point, polygon)) return true; return polygon.some((start, index) => pointOnSegment(point, start, polygon[(index + 1) % polygon.length], tolerance)); } function distanceToSegment(point, start, end) { const dx = end.x - start.x; const dy = end.y - start.y; const lengthSquared = dx * dx + dy * dy; if (lengthSquared <= 0.001) return Math.hypot(point.x - start.x, point.y - start.y); const t = clamp(((point.x - start.x) * dx + (point.y - start.y) * dy) / lengthSquared, 0, 1); const x = start.x + dx * t; const y = start.y + dy * t; return Math.hypot(point.x - x, point.y - y); } function hitTestGizmo(clientX, clientY) { const part = selectedPart(); if (!part) return null; const rect = canvas.getBoundingClientRect(); const point = { x: clientX - rect.left, y: clientY - rect.top }; const width = canvas.clientWidth; const height = canvas.clientHeight; return gizmoAxes(part, width, height).find((axis) => { return distanceToSegment(point, axis.origin, axis.end) <= 9 || Math.hypot(point.x - axis.end.x, point.y - axis.end.y) <= 14; }) || null; } function hitTestResizeHandle(clientX, clientY) { const part = selectedPart(); if (!part || part.type !== 'rect') return null; const rect = canvas.getBoundingClientRect(); const point = { x: clientX - rect.left, y: clientY - rect.top }; const width = canvas.clientWidth; const height = canvas.clientHeight; let best = null; resizeHandles(part, width, height).forEach((handle) => { const edgeDistance = distanceToSegment(point, handle.startScreen, handle.endScreen); const handleDistance = Math.hypot(point.x - handle.midpointScreen.x, point.y - handle.midpointScreen.y); const distance = Math.min(edgeDistance, handleDistance); if (distance <= RESIZE_HIT_DISTANCE && (!best || distance < best.distance)) { best = { ...handle, distance }; } }); return best; } function hitTestHoleHandle(clientX, clientY) { const part = selectedPart(); const hole = selectedHole(); if (!part || !hole) return null; const rect = canvas.getBoundingClientRect(); const point = { x: clientX - rect.left, y: clientY - rect.top }; const width = canvas.clientWidth; const height = canvas.clientHeight; let best = null; holeHandlePoints(hole).forEach((handle) => { const projected = project(localPointToWorld(part, handle, 0.75), width, height); const distance = Math.hypot(point.x - projected.x, point.y - projected.y); if (distance <= 10 && (!best || distance < best.distance)) { best = { hole, edge: handle.edge, distance }; } }); return best; } function hitTestHole(clientX, clientY) { const part = selectedPart(); if (!part) return null; const rect = canvas.getBoundingClientRect(); const point = { x: clientX - rect.left, y: clientY - rect.top }; const width = canvas.clientWidth; const height = canvas.clientHeight; const holes = part.holes || []; for (let i = holes.length - 1; i >= 0; i--) { const hole = holes[i]; const screenPoints = holeToCut(hole).points.map((cutPoint) => project(localPointToWorld(part, cutPoint, 0.75), width, height)); const onOutline = screenPoints.some((start, index) => distanceToSegment(point, start, screenPoints[(index + 1) % screenPoints.length]) <= 8); if (pointInPolygon(point, screenPoints) || onOutline) return hole; } return null; } function hitTest(clientX, clientY) { const rect = canvas.getBoundingClientRect(); const point = { x: clientX - rect.left, y: clientY - rect.top }; const width = canvas.clientWidth; const height = canvas.clientHeight; for (let i = state.parts.length - 1; i >= 0; i--) { const part = state.parts[i]; const polygon = partWorldPolygon(part).map((worldPoint) => project(worldPoint, width, height)); if (pointInPolygon(point, polygon)) return part; } return null; } function updateCanvasCursor(event) { if (state.viewMode !== 'model') { canvas.style.cursor = state.viewMode === 'solid' ? 'grab' : 'default'; return; } const holeHandle = event ? hitTestHoleHandle(event.clientX, event.clientY) : null; const hole = event ? hitTestHole(event.clientX, event.clientY) : null; state.hoverHoleHandle = holeHandle?.edge || null; if (holeHandle) { state.hoverResizeEdge = null; canvas.style.cursor = 'nwse-resize'; draw(); return; } if (hole) { state.hoverResizeEdge = null; canvas.style.cursor = 'move'; draw(); return; } const resizeHandle = event ? hitTestResizeHandle(event.clientX, event.clientY) : null; state.hoverResizeEdge = resizeHandle?.edge || null; state.hoverHoleHandle = null; if (resizeHandle) { canvas.style.cursor = 'ew-resize'; draw(); return; } if (event && hitTestGizmo(event.clientX, event.clientY)) { canvas.style.cursor = 'move'; draw(); return; } canvas.style.cursor = 'grab'; draw(); } function worldBoundsForPart(part, position = {}) { const placedPart = { ...part, ...position }; const bounds = partWorldPolygon(placedPart).reduce( (acc, point) => ({ minX: Math.min(acc.minX, point.x), maxX: Math.max(acc.maxX, point.x), minY: Math.min(acc.minY, point.y), maxY: Math.max(acc.maxY, point.y), minZ: Math.min(acc.minZ, point.z), maxZ: Math.max(acc.maxZ, point.z) }), { minX: Infinity, maxX: -Infinity, minY: Infinity, maxY: -Infinity, minZ: Infinity, maxZ: -Infinity } ); return { x: { min: bounds.minX, center: (bounds.minX + bounds.maxX) / 2, max: bounds.maxX }, y: { min: bounds.minY, center: (bounds.minY + bounds.maxY) / 2, max: bounds.maxY }, z: { min: bounds.minZ, center: (bounds.minZ + bounds.maxZ) / 2, max: bounds.maxZ } }; } function snapPartPosition(part, position, axes) { const snapped = { ...position }; axes.forEach((axis) => { const movingBounds = worldBoundsForPart(part, snapped)[axis]; let bestSnap = null; state.parts.forEach((otherPart) => { if (otherPart.id === part.id) return; const otherBounds = worldBoundsForPart(otherPart)[axis]; const candidates = [ [movingBounds.min, otherBounds.min], [movingBounds.min, otherBounds.max], [movingBounds.max, otherBounds.min], [movingBounds.max, otherBounds.max], [movingBounds.center, otherBounds.center] ]; candidates.forEach(([movingMark, otherMark]) => { const delta = otherMark - movingMark; const distance = Math.abs(delta); if (distance <= SNAP_DISTANCE && (!bestSnap || distance < bestSnap.distance)) { bestSnap = { delta, distance }; } }); }); if (bestSnap) { snapped[axis] += bestSnap.delta; } }); return snapped; } function projectionRange(points, direction) { return points.reduce( (range, point) => { const projection = dot(point, direction); return { min: Math.min(range.min, projection), max: Math.max(range.max, projection) }; }, { min: Infinity, max: -Infinity } ); } function rangesOverlap(a, b, tolerance = 0) { return a.min <= b.max + tolerance && b.min <= a.max + tolerance; } function resizeCandidate(part, drag, size) { const actualDelta = size - (drag.resizeAxis === 'width' ? drag.partWidth : drag.partHeight); const centerMove = rotateLocal( { x: drag.resizeNormal.x * actualDelta / 2, y: drag.resizeNormal.y * actualDelta / 2, z: 0 }, part ); return { ...part, x: drag.partX + centerMove.x, y: drag.partY + centerMove.y, z: drag.partZ + centerMove.z, width: drag.resizeAxis === 'width' ? size : drag.partWidth, height: drag.resizeAxis === 'height' ? size : drag.partHeight }; } function snapResizeSize(part, drag, size) { const direction = normalize(rotateLocal({ x: drag.resizeNormal.x, y: drag.resizeNormal.y, z: 0 }, part)); const tangent = normalize(rotateLocal({ x: -drag.resizeNormal.y, y: drag.resizeNormal.x, z: 0 }, part)); if (Math.hypot(direction.x, direction.y, direction.z) <= 0.0001 || Math.hypot(tangent.x, tangent.y, tangent.z) <= 0.0001) { return size; } const candidate = resizeCandidate(part, drag, size); const [edgeStartLocal, edgeEndLocal] = rectEdgeLocalPoints(candidate.width, candidate.height, drag.resizeEdge); const edgePoints = [localPointToWorld(candidate, edgeStartLocal), localPointToWorld(candidate, edgeEndLocal)]; const edgeProjection = (dot(edgePoints[0], direction) + dot(edgePoints[1], direction)) / 2; const edgeTangentRange = projectionRange(edgePoints, tangent); let bestSnap = null; state.parts.forEach((otherPart) => { if (otherPart.id === part.id) return; const otherPoints = partWorldPolygon(otherPart); const otherTangentRange = projectionRange(otherPoints, tangent); if (!rangesOverlap(edgeTangentRange, otherTangentRange, SNAP_DISTANCE)) return; const otherDirectionRange = projectionRange(otherPoints, direction); const targets = [ otherDirectionRange.min, (otherDirectionRange.min + otherDirectionRange.max) / 2, otherDirectionRange.max ]; targets.forEach((target) => { const delta = target - edgeProjection; const distance = Math.abs(delta); if (distance <= SNAP_DISTANCE && (!bestSnap || distance < bestSnap.distance)) { bestSnap = { delta, distance }; } }); }); return bestSnap ? Math.max(MIN_PANEL_SIZE, size + bestSnap.delta) : size; } function partArea(part) { const vertices = localVertices(part); let area = 0; vertices.forEach((point, index) => { const next = vertices[(index + 1) % vertices.length]; area += point.x * next.y - next.x * point.y; }); return Math.abs(area) / 2; } function segmentKey(start, end) { const pack = (point) => `${Math.round(point.x / 2)},${Math.round(point.y / 2)},${Math.round(point.z / 2)}`; const a = pack(start); const b = pack(end); return a < b ? `${a}|${b}` : `${b}|${a}`; } function lerpPoint(start, end, t) { return { x: start.x + (end.x - start.x) * t, y: start.y + (end.y - start.y) * t }; } function segmentProjectionT(point, start, end) { const dx = end.x - start.x; const dy = end.y - start.y; const lengthSquared = dx * dx + dy * dy; if (lengthSquared <= 0.0001) return 0; return ((point.x - start.x) * dx + (point.y - start.y) * dy) / lengthSquared; } function segmentIntersectionT(start, end, edgeStart, edgeEnd) { const dx = end.x - start.x; const dy = end.y - start.y; const ex = edgeEnd.x - edgeStart.x; const ey = edgeEnd.y - edgeStart.y; const denominator = dx * ey - dy * ex; if (Math.abs(denominator) <= 0.0001) return null; const qx = edgeStart.x - start.x; const qy = edgeStart.y - start.y; const t = (qx * ey - qy * ex) / denominator; const u = (qx * dy - qy * dx) / denominator; if (t >= -0.001 && t <= 1.001 && u >= -0.001 && u <= 1.001) { return clamp(t, 0, 1); } return null; } function segmentPolygonIntervals(start, end, polygon) { const candidates = [0, 1]; polygon.forEach((edgeStart, index) => { const edgeEnd = polygon[(index + 1) % polygon.length]; const t = segmentIntersectionT(start, end, edgeStart, edgeEnd); if (t !== null) candidates.push(t); [edgeStart, edgeEnd].forEach((point) => { const projection = segmentProjectionT(point, start, end); if (projection >= -0.001 && projection <= 1.001 && distanceToSegment(point, start, end) <= CONTACT_TOLERANCE) { candidates.push(clamp(projection, 0, 1)); } }); }); const sorted = [...new Set(candidates.map((value) => Math.round(value * 10000) / 10000))].sort((a, b) => a - b); const intervals = []; for (let i = 0; i < sorted.length - 1; i++) { const t0 = sorted[i]; const t1 = sorted[i + 1]; if (t1 - t0 <= 0.001) continue; const midpoint = lerpPoint(start, end, (t0 + t1) / 2); if (pointInOrOnPolygon(midpoint, polygon)) intervals.push({ t0, t1 }); } if (intervals.length === 0) { const midpoint = lerpPoint(start, end, 0.5); if (pointInOrOnPolygon(midpoint, polygon)) intervals.push({ t0: 0, t1: 1 }); } return intervals; } function fingerIntervals(start, end) { const dx = end.x - start.x; const dy = end.y - start.y; const length = Math.hypot(dx, dy); if (length <= 0.001) return []; let count = Math.max(3, Math.floor(length / Math.max(1, state.settings.fingerWidth))); if (count % 2 === 0) count -= 1; const segment = length / count; const unit = { x: dx / length, y: dy / length }; const intervals = []; for (let i = 0; i < count; i += 2) { const t0 = i * segment; const t1 = (i + 1) * segment; intervals.push({ start: { x: start.x + unit.x * t0, y: start.y + unit.y * t0 }, end: { x: start.x + unit.x * t1, y: start.y + unit.y * t1 } }); } return intervals; } // Split a world-space segment into finger bands (each tagged with its index), so a // shared corner edge yields the same banding for both panels regardless of how each // traverses it. Callers cut complementary bands (even vs odd) to interlock cleanly. function worldFingerBands(start, end) { const length = Math.hypot(end.x - start.x, end.y - start.y, end.z - start.z); if (length <= 0.001) return []; let count = Math.max(3, Math.floor(length / Math.max(1, state.settings.fingerWidth))); if (count % 2 === 0) count -= 1; const lerp3 = (t) => ({ x: start.x + (end.x - start.x) * t, y: start.y + (end.y - start.y) * t, z: start.z + (end.z - start.z) * t }); return Array.from({ length: count }, (_value, index) => ({ index, a: lerp3(index / count), b: lerp3((index + 1) / count) })); } function slotRectangle(start, end, width, lengthPadding = 0) { const dx = end.x - start.x; const dy = end.y - start.y; const length = Math.hypot(dx, dy); if (length <= 0.001) return null; const unit = { x: dx / length, y: dy / length }; const normal = { x: -unit.y, y: unit.x }; const halfWidth = width / 2; const a = { x: start.x - unit.x * lengthPadding, y: start.y - unit.y * lengthPadding }; const b = { x: end.x + unit.x * lengthPadding, y: end.y + unit.y * lengthPadding }; return [ { x: a.x + normal.x * halfWidth, y: a.y + normal.y * halfWidth }, { x: b.x + normal.x * halfWidth, y: b.y + normal.y * halfWidth }, { x: b.x - normal.x * halfWidth, y: b.y - normal.y * halfWidth }, { x: a.x - normal.x * halfWidth, y: a.y - normal.y * halfWidth } ]; } function holeToCut(hole) { if (hole.type === 'rect') { const halfW = Math.max(1, hole.width) / 2; const halfH = Math.max(1, hole.height) / 2; return { type: 'hole', points: [ { x: hole.x - halfW, y: hole.y - halfH }, { x: hole.x + halfW, y: hole.y - halfH }, { x: hole.x + halfW, y: hole.y + halfH }, { x: hole.x - halfW, y: hole.y + halfH } ] }; } const radius = Math.max(1, hole.diameter) / 2; const segments = 40; return { type: 'hole', points: Array.from({ length: segments }, (_value, index) => { const angle = (index / segments) * Math.PI * 2; return { x: hole.x + Math.cos(angle) * radius, y: hole.y + Math.sin(angle) * radius }; }) }; } function boundaryEdgeForSegment(part, segmentStart, segmentEnd) { const vertices = localVertices(part); for (let index = 0; index < vertices.length; index++) { const edgeStart = vertices[index]; const edgeEnd = vertices[(index + 1) % vertices.length]; const startT = segmentProjectionT(segmentStart, edgeStart, edgeEnd); const endT = segmentProjectionT(segmentEnd, edgeStart, edgeEnd); const onEdge = distanceToSegment(segmentStart, edgeStart, edgeEnd) <= CONTACT_TOLERANCE && distanceToSegment(segmentEnd, edgeStart, edgeEnd) <= CONTACT_TOLERANCE && startT >= -0.001 && startT <= 1.001 && endT >= -0.001 && endT <= 1.001; if (onEdge) return index; } return null; } function edgeFaceContacts(edgePart, facePart) { if (Math.abs(dot(partNormal(edgePart), partNormal(facePart))) > 0.35) return []; const edgeVertices = localVertices(edgePart); const faceVertices = localVertices(facePart); const contacts = []; edgeVertices.forEach((localStart, edgeIndex) => { const localEnd = edgeVertices[(edgeIndex + 1) % edgeVertices.length]; const worldStart = rotate3({ x: localStart.x, y: localStart.y, z: 0 }, edgePart); const worldEnd = rotate3({ x: localEnd.x, y: localEnd.y, z: 0 }, edgePart); const faceStart = worldToLocal(worldStart, facePart); const faceEnd = worldToLocal(worldEnd, facePart); if (Math.abs(faceStart.z) > CONTACT_TOLERANCE || Math.abs(faceEnd.z) > CONTACT_TOLERANCE) return; const intervals = segmentPolygonIntervals( { x: faceStart.x, y: faceStart.y }, { x: faceEnd.x, y: faceEnd.y }, faceVertices ); intervals.forEach((interval) => { const localEdgeStart = lerpPoint(localStart, localEnd, interval.t0); const localEdgeEnd = lerpPoint(localStart, localEnd, interval.t1); const clippedWorldStart = rotate3({ x: localEdgeStart.x, y: localEdgeStart.y, z: 0 }, edgePart); const clippedWorldEnd = rotate3({ x: localEdgeEnd.x, y: localEdgeEnd.y, z: 0 }, edgePart); const clippedFaceStart = lerpPoint({ x: faceStart.x, y: faceStart.y }, { x: faceEnd.x, y: faceEnd.y }, interval.t0); const clippedFaceEnd = lerpPoint({ x: faceStart.x, y: faceStart.y }, { x: faceEnd.x, y: faceEnd.y }, interval.t1); contacts.push({ key: segmentKey(clippedWorldStart, clippedWorldEnd), edgePart, facePart, edgeIndex, localEdgeStart, localEdgeEnd, worldStart: clippedWorldStart, worldEnd: clippedWorldEnd, faceStart: clippedFaceStart, faceEnd: clippedFaceEnd, score: Math.abs(partNormal(edgePart).z) - Math.abs(partNormal(facePart).z) + partArea(facePart) / 1000000 }); }); }); return contacts; } function contactPreferenceScore(contact) { const edgeBehavior = jointBehavior(contact.edgePart); const faceBehavior = jointBehavior(contact.facePart); if (edgeBehavior === 'none' || faceBehavior === 'none') return Infinity; let score = contact.score; if (edgeBehavior === 'tabs') score -= 10; if (edgeBehavior === 'slots') score += 10; if (faceBehavior === 'slots') score -= 10; if (faceBehavior === 'tabs') score += 10; return score; } function linePolygonSegment(part, otherPart) { const otherNormal = partNormal(otherPart); const localNormal = inverseRotate(otherNormal, part); const otherCenter = worldToLocal({ x: otherPart.x, y: otherPart.y, z: otherPart.z }, part); const a = localNormal.x; const b = localNormal.y; const c = -(localNormal.x * otherCenter.x + localNormal.y * otherCenter.y + localNormal.z * otherCenter.z); if (Math.hypot(a, b) <= 0.0001) return null; const vertices = localVertices(part); const points = []; const addPoint = (point) => { if (!points.some((existing) => Math.hypot(existing.x - point.x, existing.y - point.y) < 0.01)) { points.push(point); } }; vertices.forEach((start, index) => { const end = vertices[(index + 1) % vertices.length]; const ds = a * start.x + b * start.y + c; const de = a * end.x + b * end.y + c; if (Math.abs(ds) <= CONTACT_TOLERANCE) addPoint({ ...start }); if (ds * de < 0) { const t = ds / (ds - de); addPoint({ x: start.x + (end.x - start.x) * t, y: start.y + (end.y - start.y) * t }); } if (Math.abs(de) <= CONTACT_TOLERANCE) addPoint({ ...end }); }); if (points.length < 2) return null; let best = null; points.forEach((start, index) => { points.slice(index + 1).forEach((end) => { const length = Math.hypot(end.x - start.x, end.y - start.y); if (!best || length > best.length) best = { start, end, length }; }); }); return best; } function distanceToPolygonEdges(point, polygon) { return polygon.reduce((distance, start, index) => { return Math.min(distance, distanceToSegment(point, start, polygon[(index + 1) % polygon.length])); }, Infinity); } function slitCutForSegment(segment, useFirstEnd) { const mid = { x: (segment.start.x + segment.end.x) / 2, y: (segment.start.y + segment.end.y) / 2 }; const edge = useFirstEnd ? segment.start : segment.end; const width = state.settings.materialThickness + state.settings.kerf + state.settings.clearance; return slotRectangle(edge, mid, width, state.settings.kerf / 2); } function addThroughSlits(features, partA, partB) { if (jointBehavior(partA) === 'none' || jointBehavior(partB) === 'none') return; if (Math.abs(dot(partNormal(partA), partNormal(partB))) > 0.35) return; const segmentA = linePolygonSegment(partA, partB); const segmentB = linePolygonSegment(partB, partA); if (!segmentA || !segmentB) return; const minLength = state.settings.materialThickness * 2.5; if (segmentA.length < minLength || segmentB.length < minLength) return; const midA = { x: (segmentA.start.x + segmentA.end.x) / 2, y: (segmentA.start.y + segmentA.end.y) / 2 }; const midB = { x: (segmentB.start.x + segmentB.end.x) / 2, y: (segmentB.start.y + segmentB.end.y) / 2 }; const edgeClearance = Math.max(state.settings.materialThickness, CONTACT_TOLERANCE); if (distanceToPolygonEdges(midA, localVertices(partA)) <= edgeClearance) return; if (distanceToPolygonEdges(midB, localVertices(partB)) <= edgeClearance) return; const cutA = slitCutForSegment(segmentA, partA.id < partB.id); const cutB = slitCutForSegment(segmentB, partA.id >= partB.id); if (cutA) features.get(partA.id).internalCuts.push({ type: 'slit', points: cutA }); if (cutB) features.get(partB.id).internalCuts.push({ type: 'slit', points: cutB }); } function buildFabricationFeatures() { const features = new Map(); state.parts.forEach((part) => { const edgeCount = localVertices(part).length; features.set(part.id, { edgeModes: Array(edgeCount).fill('none'), edgeJoints: Array.from({ length: edgeCount }, () => []), edgeCutouts: Array.from({ length: edgeCount }, () => []), internalCuts: (part.holes || []).map(holeToCut) }); }); for (let i = 0; i < state.parts.length; i++) { for (let j = i + 1; j < state.parts.length; j++) { const partA = state.parts[i]; const partB = state.parts[j]; const contacts = [...edgeFaceContacts(partA, partB), ...edgeFaceContacts(partB, partA)]; const bySegment = new Map(); contacts.forEach((contact) => { const score = contactPreferenceScore(contact); if (!Number.isFinite(score)) return; const existing = bySegment.get(contact.key); if (!existing || score < existing.score) bySegment.set(contact.key, { ...contact, score }); }); if (bySegment.size === 0) { addThroughSlits(features, partA, partB); continue; } bySegment.forEach((contact) => { const edgeFeature = features.get(contact.edgePart.id); const faceFeature = features.get(contact.facePart.id); const faceEdgeIndex = boundaryEdgeForSegment(contact.facePart, contact.faceStart, contact.faceEnd); if (faceEdgeIndex !== null) { // Edge-to-edge corner: both panels meet along a shared boundary edge. Cut // complementary finger bands inward (no outward protrusion) so exactly one // panel keeps material in each band — the box joint interlocks flush. const depth = state.settings.materialThickness + state.settings.clearance; edgeFeature.edgeModes[contact.edgeIndex] = 'tabs'; faceFeature.edgeModes[faceEdgeIndex] = 'slots'; worldFingerBands(contact.worldStart, contact.worldEnd).forEach((band) => { const cutPart = band.index % 2 === 1 ? contact.edgePart : contact.facePart; const cutFeature = band.index % 2 === 1 ? edgeFeature : faceFeature; const cutEdgeIndex = band.index % 2 === 1 ? contact.edgeIndex : faceEdgeIndex; const a = worldToLocal(band.a, cutPart); const b = worldToLocal(band.b, cutPart); cutFeature.edgeCutouts[cutEdgeIndex].push({ start: { x: a.x, y: a.y }, end: { x: b.x, y: b.y }, depth }); }); return; } // Edge-to-face mounting (panel edge lands in the middle of another's face). // The tenons must NOT protrude past the edge panel's outline — that would add // material sticking out the far side of the hit panel. Instead, cut the gaps // inward (subtractive) so the edge panel keeps its nominal size, and slot the // face panel at the tenon bands. Bands come from the shared world segment so // the edge notches and face slots stay aligned. const depth = state.settings.materialThickness + state.settings.clearance; const slotWidth = state.settings.materialThickness + state.settings.kerf + state.settings.clearance; const padding = (state.settings.kerf + state.settings.clearance) / 2; edgeFeature.edgeModes[contact.edgeIndex] = 'slots'; worldFingerBands(contact.worldStart, contact.worldEnd).forEach((band) => { if (band.index % 2 === 1) { const a = worldToLocal(band.a, contact.edgePart); const b = worldToLocal(band.b, contact.edgePart); edgeFeature.edgeCutouts[contact.edgeIndex].push({ start: { x: a.x, y: a.y }, end: { x: b.x, y: b.y }, depth }); } else { const a = worldToLocal(band.a, contact.facePart); const b = worldToLocal(band.b, contact.facePart); const rectangle = slotRectangle({ x: a.x, y: a.y }, { x: b.x, y: b.y }, slotWidth, padding); if (rectangle) faceFeature.internalCuts.push({ type: 'mortise', points: rectangle }); } }); }); } } return features; } function generateProfile(part, feature = null) { const vertices = localVertices(part); const edgeJoints = feature?.edgeJoints || Array.from({ length: vertices.length }, () => []); const edgeCutouts = feature?.edgeCutouts || Array.from({ length: vertices.length }, () => []); const profile = []; vertices.forEach((start, index) => { const end = vertices[(index + 1) % vertices.length]; appendEdgeWithFeatures(profile, start, end, edgeJoints[index] || [], edgeCutouts[index] || []); }); return simplifyProfile(profile); } function edgeParameter(point, start, end) { return clamp(segmentProjectionT(point, start, end), 0, 1); } function appendEdgeWithFeatures(profile, start, end, joints, cutouts) { if (joints.length === 0 && cutouts.length === 0) { appendFingeredEdge(profile, start, end, 'none'); return; } const intervals = [ ...joints.map((joint) => ({ type: 'tabs', start: joint.start, end: joint.end })), ...cutouts.map((cutout) => ({ type: 'cutout', start: cutout.start, end: cutout.end, depth: cutout.depth })) ] .map((joint) => { const t0 = edgeParameter(joint.start, start, end); const t1 = edgeParameter(joint.end, start, end); return { ...joint, t0: Math.min(t0, t1), t1: Math.max(t0, t1) }; }) .filter((interval) => interval.t1 - interval.t0 > 0.001) .sort((a, b) => a.t0 - b.t0); let cursor = 0; intervals.forEach((interval) => { const t0 = Math.max(cursor, interval.t0); const t1 = Math.max(t0, interval.t1); if (t0 - cursor > 0.001) { appendFingeredEdge(profile, lerpPoint(start, end, cursor), lerpPoint(start, end, t0), 'none'); } if (t1 - t0 > 0.001) { if (interval.type === 'cutout') { appendEdgeCutout(profile, lerpPoint(start, end, t0), lerpPoint(start, end, t1), interval.depth); } else { appendFingeredEdge(profile, lerpPoint(start, end, t0), lerpPoint(start, end, t1), 'tabs'); } } cursor = Math.max(cursor, t1); }); if (1 - cursor > 0.001) { appendFingeredEdge(profile, lerpPoint(start, end, cursor), end, 'none'); } } function appendEdgeCutout(profile, start, end, depth) { const dx = end.x - start.x; const dy = end.y - start.y; const length = Math.hypot(dx, dy); if (length <= 0.001) return; const unit = { x: dx / length, y: dy / length }; const inward = { x: -dy / length, y: dx / length }; // Inverse of the tab kerf comp (appendFingeredEdge): a cutout is a recess, so the // cutter eats kerf/2 into each wall and shrinks the tenons left between cutouts. // Narrow the gap by kerf/2 per side so those tenons land on nominal after the cut. const kerfHalf = Math.max(0, state.settings.kerf) / 2; const p0 = { x: start.x + unit.x * kerfHalf, y: start.y + unit.y * kerfHalf }; const p1 = { x: end.x - unit.x * kerfHalf, y: end.y - unit.y * kerfHalf }; profile.push({ ...p0 }); profile.push({ x: p0.x + inward.x * depth, y: p0.y + inward.y * depth }); profile.push({ x: p1.x + inward.x * depth, y: p1.y + inward.y * depth }); profile.push({ ...p1 }); } function appendFingeredEdge(profile, start, end, mode) { const dx = end.x - start.x; const dy = end.y - start.y; const length = Math.hypot(dx, dy); if (length <= 0.001) return; const unit = { x: dx / length, y: dy / length }; const outward = { x: dy / length, y: -dx / length }; const depthDirection = mode === 'slots' ? -1 : 1; const kerf = Math.max(0, state.settings.kerf); // Match the t-joint slot formula (materialThickness + kerf + clearance) so both // joint types compensate for kerf identically. const depth = Math.max(0, state.settings.materialThickness + kerf + state.settings.clearance); // Cutter removes kerf/2 from the part side of each wall, so widen every tab by // kerf/2 per side; the complementary recess narrows by the same amount and both // land on nominal after the cut. const kerfHalf = kerf / 2; if (profile.length === 0) profile.push({ ...start }); const intervals = fingerIntervals(start, end); if (mode === 'none' || depth <= 0.001 || intervals.length === 0 || length < state.settings.fingerWidth * 1.6) { profile.push({ ...end }); return; } intervals.forEach((interval, index) => { const p0 = { x: interval.start.x - unit.x * kerfHalf, y: interval.start.y - unit.y * kerfHalf }; const p1 = { x: interval.end.x + unit.x * kerfHalf, y: interval.end.y + unit.y * kerfHalf }; if (index > 0) profile.push(p0); const offset = { x: outward.x * depth * depthDirection, y: outward.y * depth * depthDirection }; profile.push({ x: p0.x + offset.x, y: p0.y + offset.y }); profile.push({ x: p1.x + offset.x, y: p1.y + offset.y }); profile.push(p1); }); profile.push({ ...end }); } function simplifyProfile(profile) { const deduped = []; profile.forEach((point) => { const previous = deduped[deduped.length - 1]; if (!previous || Math.hypot(previous.x - point.x, previous.y - point.y) > 0.01) { deduped.push({ x: round(point.x), y: round(point.y) }); } }); return deduped; } function boundsFor(points) { return points.reduce( (bounds, point) => ({ minX: Math.min(bounds.minX, point.x), maxX: Math.max(bounds.maxX, point.x), minY: Math.min(bounds.minY, point.y), maxY: Math.max(bounds.maxY, point.y) }), { minX: Infinity, maxX: -Infinity, minY: Infinity, maxY: -Infinity } ); } function arrangeParts() { const gap = state.settings.partGap; const sheetW = state.settings.sheetWidth; const fabricationFeatures = buildFabricationFeatures(); let cursorX = gap; let cursorY = gap; let rowHeight = 0; return state.parts.map((part) => { const feature = fabricationFeatures.get(part.id); const profile = generateProfile(part, feature); const bounds = boundsFor(profile); const width = bounds.maxX - bounds.minX; const height = bounds.maxY - bounds.minY; if (cursorX + width + gap > sheetW && cursorX > gap) { cursorX = gap; cursorY += rowHeight + gap; rowHeight = 0; } const entry = { part, profile, internalCuts: feature?.internalCuts || [], x: cursorX - bounds.minX, y: cursorY - bounds.minY, center: { x: (bounds.minX + bounds.maxX) / 2, y: (bounds.minY + bounds.maxY) / 2 }, bounds: { width, height } }; cursorX += width + gap; rowHeight = Math.max(rowHeight, height); return entry; }); } function generateDxf() { const layout = arrangeParts(); const lines = [ '0', 'SECTION', '2', 'HEADER', '9', '$INSUNITS', '70', '4', '0', 'ENDSEC', '0', 'SECTION', '2', 'TABLES', '0', 'TABLE', '2', 'LAYER', '70', '3', layer('CUT', 1), layer('LABEL', 7), layer('SHEET', 8), '0', 'ENDTAB', '0', 'ENDSEC', '0', 'SECTION', '2', 'ENTITIES' ]; addPolyline(lines, 'SHEET', [ { x: 0, y: 0 }, { x: state.settings.sheetWidth, y: 0 }, { x: state.settings.sheetWidth, y: state.settings.sheetHeight }, { x: 0, y: state.settings.sheetHeight } ]); layout.forEach((entry) => { const points = entry.profile.map((point) => ({ x: point.x + entry.x, y: state.settings.sheetHeight - (point.y + entry.y) })); addPolyline(lines, 'CUT', points); entry.internalCuts.forEach((cut) => { addPolyline(lines, 'CUT', cut.points.map((point) => ({ x: point.x + entry.x, y: state.settings.sheetHeight - (point.y + entry.y) }))); }); addText(lines, 'LABEL', entry.part.name, entry.x + entry.center.x, state.settings.sheetHeight - (entry.y + entry.center.y), 5); }); lines.push('0', 'ENDSEC', '0', 'EOF'); return lines.join('\n'); } function layer(name, color) { return ['0', 'LAYER', '2', name, '70', '0', '62', String(color), '6', 'CONTINUOUS'].join('\n'); } function addPolyline(lines, layerName, points) { lines.push('0', 'POLYLINE', '8', layerName, '66', '1', '70', '1'); points.forEach((point) => { lines.push('0', 'VERTEX', '8', layerName, '10', String(round(point.x)), '20', String(round(point.y)), '30', '0'); }); lines.push('0', 'SEQEND'); } function addText(lines, layerName, text, x, y, height) { lines.push('0', 'TEXT', '8', layerName, '10', String(round(x)), '20', String(round(y)), '30', '0', '40', String(height), '1', text, '50', '0', '72', '1', '11', String(round(x)), '21', String(round(y)), '31', '0'); } function addRectangle() { const part = createRectanglePart({ x: state.parts.length * 12, y: state.parts.length * 8 }); state.parts.push(part); selectPart(part.id); setStatus('Rectangle added'); } function addPolygon() { const part = createPolygonPart({ x: state.parts.length * 12, y: state.parts.length * 8 }); state.parts.push(part); selectPart(part.id); setStatus('Polygon added'); } function addHole() { const part = selectedPart(); if (!part) return; const hole = { id: nextHoleId++, type: inputs.holeType.value, x: mm(inputs.holeX.value, 0), y: mm(inputs.holeY.value, 0), diameter: Math.max(1, mm(inputs.holeDiameter.value, 12)), width: Math.max(1, mm(inputs.holeWidth.value, 20)), height: Math.max(1, mm(inputs.holeHeight.value, 10)) }; part.holes = part.holes || []; part.holes.push(hole); state.selectedHoleId = hole.id; syncHoleInputs(); renderHolesList(); draw(); setStatus('Hole added'); } function removeHole(id) { const part = selectedPart(); if (!part) return; part.holes = (part.holes || []).filter((hole) => hole.id !== id); if (state.selectedHoleId === id) state.selectedHoleId = null; renderHolesList(); draw(); setStatus('Hole removed'); } function duplicateSelected() { const part = selectedPart(); if (!part) return; const copy = structuredClone(part); copy.id = nextId++; copy.holes = (copy.holes || []).map((hole) => ({ ...hole, id: nextHoleId++ })); copy.name = `${part.name} copy`; copy.x += 12; copy.y += 12; copy.color = colorForId(copy.id); state.parts.push(copy); selectPart(copy.id); setStatus('Piece duplicated'); } function deleteSelected() { if (state.selectedHoleId !== null) { removeHole(state.selectedHoleId); return; } const part = selectedPart(); if (!part) return; deletePart(part.id); } function deletePart(id) { const part = state.parts.find((item) => item.id === id); if (!part) return; state.parts = state.parts.filter((item) => item.id !== id); state.selectedId = state.parts[0]?.id || null; state.selectedHoleId = null; syncInspector(); renderPartsList(); draw(); setStatus('Piece deleted'); } // Resolve the entered X/Y/Z into the nominal panel layout dims (w, d, h) — the // mid-plane edge box the joint engine works on. Panels each protrude half a // thickness past their shared mid-plane, so the finished outer box is nominal + t // per axis and the inner cavity is nominal - t. We shift the nominal dims to hit // the requested outer or inner target, rather than insetting panels (which would // break the edge-on-plane contacts the joint generator relies on). function boxDimensions() { const t = state.settings.materialThickness; const ex = state.box.width; const ey = state.box.depth; const ez = state.box.height; const offset = state.box.reference === 'inner' ? t : -t; const w = Math.max(t, ex + offset); const d = Math.max(t, ey + offset); const h = Math.max(t, ez + offset); return { t, w, d, h, outer: { x: w + t, y: d + t, z: h + t }, inner: { x: w - t, y: d - t, z: h - t } }; } function updateBoxSummary() { if (!boxSummary) return; const { t, outer, inner } = boxDimensions(); const outerText = `${round(outer.x)} × ${round(outer.y)} × ${round(outer.z)} mm`; const innerText = `${round(inner.x)} × ${round(inner.y)} × ${round(inner.z)} mm`; boxSummary.textContent = `Outer ${outerText} · cavity ${innerText} · material ${round(t)} mm`; } // Six finger-jointed panels. Mid-planes meet at the nominal box edges; walls run // full height so every corner is an edge-to-face contact the joint engine turns // into matching tabs and mortises. Left/right panel sizing accounts for the ry=90 // rotation (local width -> world Z, local height -> world Y). function createFingerBox() { const { outer, w, d, h } = boxDimensions(); const boxParts = [ createRectanglePart({ name: 'Bottom', width: w, height: d, z: 0, edgePreset: 'slots', color: '#0f766e' }), createRectanglePart({ name: 'Lid', width: w, height: d, z: h, edgePreset: 'slots', color: '#2f855a' }), createRectanglePart({ name: 'Front', width: w, height: h, y: -d / 2, z: h / 2, rx: 90, edgePreset: 'tabs', color: '#9a3412' }), createRectanglePart({ name: 'Back', width: w, height: h, y: d / 2, z: h / 2, rx: 90, edgePreset: 'tabs', color: '#9a3412' }), createRectanglePart({ name: 'Left', width: h, height: d, x: -w / 2, z: h / 2, ry: 90, edgePreset: 'tabs', color: '#2563eb' }), createRectanglePart({ name: 'Right', width: h, height: d, x: w / 2, z: h / 2, ry: 90, edgePreset: 'tabs', color: '#2563eb' }) ]; state.parts = boxParts; state.selectedId = boxParts[0].id; syncInspector(); renderPartsList(); updateBoxSummary(); draw(); setStatus(`Box ${round(outer.x)} × ${round(outer.y)} × ${round(outer.z)} mm generated`); } function setView(mode) { state.viewMode = mode; state.hoverResizeEdge = null; buttons.viewModel.classList.toggle('active', mode === 'model'); buttons.viewSolid.classList.toggle('active', mode === 'solid'); buttons.viewLayout.classList.toggle('active', mode === 'layout'); canvas.style.cursor = mode === 'model' || mode === 'solid' ? 'grab' : 'default'; draw(); } function bindEvents() { buttons.addRect.addEventListener('click', addRectangle); buttons.addPoly.addEventListener('click', addPolygon); buttons.box.addEventListener('click', createFingerBox); buttons.duplicate.addEventListener('click', duplicateSelected); buttons.delete.addEventListener('click', deleteSelected); buttons.addHole.addEventListener('click', addHole); buttons.viewModel.addEventListener('click', () => setView('model')); buttons.viewSolid.addEventListener('click', () => setView('solid')); buttons.viewLayout.addEventListener('click', () => setView('layout')); buttons.tabPart.addEventListener('click', () => setConfigTab('part')); buttons.tabBox.addEventListener('click', () => setConfigTab('box')); buttons.tabSetup.addEventListener('click', () => setConfigTab('setup')); buttons.buildBox.addEventListener('click', createFingerBox); inputs.boxRef.addEventListener('change', () => { state.box.reference = inputs.boxRef.value; updateBoxSummary(); }); window.addEventListener('keydown', (event) => { const tagName = event.target?.tagName; const isTyping = event.target?.isContentEditable || tagName === 'INPUT' || tagName === 'SELECT' || tagName === 'TEXTAREA'; if (isTyping) return; if (event.key === 'Delete' || event.key === 'Backspace') { event.preventDefault(); if (state.selectedHoleId !== null) { removeHole(state.selectedHoleId); return; } deleteSelected(); } }); buttons.export.addEventListener('click', async () => { const contents = generateDxf(); const result = await window.dxfdesign.saveDxf({ contents, defaultName: 'sheet-parts.dxf' }); if (!result.canceled) setStatus(`Exported ${result.filePath}`); }); buttons.saveProject.addEventListener('click', async () => { const contents = JSON.stringify(serializeConfig(), null, 2); const result = await window.dxfdesign.saveProject({ contents, defaultName: 'dxfdesign-project.json' }); if (!result.canceled) setStatus(`Saved project ${result.filePath}`); }); buttons.loadProject.addEventListener('click', async () => { const result = await window.dxfdesign.loadProject(); if (result.canceled) return; try { applyConfig(JSON.parse(result.contents)); setStatus(`Loaded project ${result.filePath}`); } catch (error) { setStatus(`Load failed: ${error.message}`); } }); ['materialThickness', 'kerf', 'clearance', 'fingerWidth', 'sheetWidth', 'sheetHeight', 'partGap'].forEach((key) => { inputs[key].addEventListener('input', () => { state.settings[key] = mm(inputs[key].value, state.settings[key]); if (key === 'materialThickness') updateBoxSummary(); draw(); }); }); inputs.showGrid.addEventListener('change', () => { state.showGrid = inputs.showGrid.checked; draw(); }); inputs.showJoints.addEventListener('change', () => { state.showJoints = inputs.showJoints.checked; draw(); }); inputs.zoomSlider.addEventListener('input', () => { state.zoom = mm(inputs.zoomSlider.value, 1); draw(); }); canvas.addEventListener('wheel', (event) => { event.preventDefault(); const zoomFactor = event.deltaY < 0 ? 1.08 : 1 / 1.08; state.zoom = clamp(state.zoom * zoomFactor, mm(inputs.zoomSlider.min, 0.4), mm(inputs.zoomSlider.max, 2.2)); inputs.zoomSlider.value = round(state.zoom); draw(); }, { passive: false }); ['boxWidth', 'boxDepth', 'boxHeight'].forEach((key) => { inputs[key].addEventListener('input', () => { const field = key.replace('box', '').toLowerCase(); state.box[field] = mm(inputs[key].value, state.box[field]); updateBoxSummary(); }); }); inputs.partName.addEventListener('input', () => { const part = selectedPart(); if (!part) return; part.name = inputs.partName.value || part.name; renderPartsList(); draw(); }); inputs.partWidth.addEventListener('input', () => updateSelected({ width: Math.max(1, mm(inputs.partWidth.value, 1)) })); inputs.partHeight.addEventListener('input', () => updateSelected({ height: Math.max(1, mm(inputs.partHeight.value, 1)) })); inputs.polySides.addEventListener('input', () => updateSelected({ sides: clamp(Math.round(mm(inputs.polySides.value, 3)), 3, 16) })); inputs.polyRadius.addEventListener('input', () => updateSelected({ radius: Math.max(1, mm(inputs.polyRadius.value, 1)) })); inputs.edgePreset.addEventListener('change', () => updateSelected({ edgePreset: inputs.edgePreset.value })); inputs.posX.addEventListener('input', () => updateSelected({ x: mm(inputs.posX.value, 0) }, false)); inputs.posY.addEventListener('input', () => updateSelected({ y: mm(inputs.posY.value, 0) }, false)); inputs.posZ.addEventListener('input', () => updateSelected({ z: mm(inputs.posZ.value, 0) }, false)); inputs.rotX.addEventListener('input', () => updateSelected({ rx: mm(inputs.rotX.value, 0) }, false)); inputs.rotY.addEventListener('input', () => updateSelected({ ry: mm(inputs.rotY.value, 0) }, false)); inputs.rotZ.addEventListener('input', () => updateSelected({ rz: mm(inputs.rotZ.value, 0) }, false)); inputs.holeType.addEventListener('change', () => updateSelectedHole({ type: inputs.holeType.value })); inputs.holeX.addEventListener('input', () => updateSelectedHole({ x: mm(inputs.holeX.value, 0) })); inputs.holeY.addEventListener('input', () => updateSelectedHole({ y: mm(inputs.holeY.value, 0) })); inputs.holeDiameter.addEventListener('input', () => updateSelectedHole({ diameter: Math.max(1, mm(inputs.holeDiameter.value, 1)) })); inputs.holeWidth.addEventListener('input', () => updateSelectedHole({ width: Math.max(1, mm(inputs.holeWidth.value, 1)) })); inputs.holeHeight.addEventListener('input', () => updateSelectedHole({ height: Math.max(1, mm(inputs.holeHeight.value, 1)) })); canvas.addEventListener('contextmenu', (event) => { if (state.viewMode === 'model' || state.viewMode === 'solid') event.preventDefault(); }); canvas.addEventListener('pointerdown', (event) => { if (state.viewMode === 'solid') { if (event.button !== 0 && event.button !== 2) return; state.drag = { mode: event.button === 2 ? 'pan' : 'rotate', startX: event.clientX, startY: event.clientY, yaw: state.camera.yaw, pitch: state.camera.pitch, panX: state.camera.panX, panY: state.camera.panY, moved: false, hitPartId: null }; canvas.setPointerCapture(event.pointerId); return; } if (state.viewMode !== 'model' || (event.button !== 0 && event.button !== 2)) return; const holeHandle = event.button === 0 ? hitTestHoleHandle(event.clientX, event.clientY) : null; const hole = event.button === 0 ? hitTestHole(event.clientX, event.clientY) : null; const resizeHandle = event.button === 0 ? hitTestResizeHandle(event.clientX, event.clientY) : null; const gizmo = event.button === 0 ? hitTestGizmo(event.clientX, event.clientY) : null; const part = event.button === 0 ? hitTest(event.clientX, event.clientY) : null; const selected = selectedPart(); const activePart = holeHandle || hole ? selected : resizeHandle ? selected : gizmo ? selected : part; const movePart = event.button === 0 && event.shiftKey && part; const dragPoint = movePart ? screenToWorldAtZ(event.clientX, event.clientY, part.z) : null; const holeDragPoint = activePart && (holeHandle || hole) ? screenToLocalOnPart(event.clientX, event.clientY, activePart) : null; const activeHole = holeHandle?.hole || hole || null; if (activeHole) selectHole(activeHole.id); if (movePart) selectPart(part.id); state.hoverResizeEdge = resizeHandle?.edge || null; state.drag = { mode: event.button === 2 ? 'pan' : holeHandle ? 'resizeHole' : hole ? 'moveHole' : resizeHandle ? 'resizePart' : gizmo ? 'axisMove' : movePart ? 'movePart' : 'rotate', startX: event.clientX, startY: event.clientY, yaw: state.camera.yaw, pitch: state.camera.pitch, panX: state.camera.panX, panY: state.camera.panY, axis: gizmo?.axis || null, axisStart: gizmo?.origin || null, axisEnd: gizmo?.end || null, resizeEdge: resizeHandle?.edge || null, resizeAxis: resizeHandle?.axis || null, resizeNormal: resizeHandle?.normal || null, resizeMidpoint: resizeHandle?.midpointScreen || null, resizeVectorEnd: resizeHandle?.vectorEndScreen || null, partX: activePart?.x || 0, partY: activePart?.y || 0, partZ: activePart?.z || 0, partWidth: activePart?.width || 0, partHeight: activePart?.height || 0, dragWorldX: dragPoint?.x || 0, dragWorldY: dragPoint?.y || 0, dragLocalX: holeDragPoint?.x || 0, dragLocalY: holeDragPoint?.y || 0, holeId: activeHole?.id || null, holeEdge: holeHandle?.edge || null, holeX: activeHole?.x || 0, holeY: activeHole?.y || 0, holeDiameter: activeHole?.diameter || 0, holeWidth: activeHole?.width || 0, holeHeight: activeHole?.height || 0, hitPartId: part?.id || null, moved: false }; canvas.setPointerCapture(event.pointerId); }); canvas.addEventListener('pointermove', (event) => { if (!state.drag) { updateCanvasCursor(event); return; } canvas.style.cursor = state.drag.mode === 'resizePart' || state.drag.mode === 'resizeHole' ? 'nwse-resize' : state.drag.mode === 'axisMove' || state.drag.mode === 'movePart' || state.drag.mode === 'moveHole' ? 'move' : 'grabbing'; const dx = event.clientX - state.drag.startX; const dy = event.clientY - state.drag.startY; if (Math.hypot(dx, dy) > 3) state.drag.moved = true; if (state.drag.mode === 'rotate') { state.camera.yaw = state.drag.yaw + dx * 0.01; state.camera.pitch = clamp(state.drag.pitch + dy * 0.008, 0.15, 1.45); } else if (state.drag.mode === 'moveHole') { const part = selectedPart(); const hole = selectedHole(); const point = part ? screenToLocalOnPart(event.clientX, event.clientY, part) : null; if (!part || !hole || !point) return; hole.x = state.drag.holeX + point.x - state.drag.dragLocalX; hole.y = state.drag.holeY + point.y - state.drag.dragLocalY; syncHoleInputs(); renderHolesList(); } else if (state.drag.mode === 'resizeHole') { const part = selectedPart(); const hole = selectedHole(); const point = part ? screenToLocalOnPart(event.clientX, event.clientY, part) : null; if (!part || !hole || !point) return; if (hole.type === 'circle') { hole.diameter = Math.max(1, Math.hypot(point.x - state.drag.holeX, point.y - state.drag.holeY) * 2); } else { const deltaX = point.x - state.drag.dragLocalX; const deltaY = point.y - state.drag.dragLocalY; const left = state.drag.holeX - state.drag.holeWidth / 2; const right = state.drag.holeX + state.drag.holeWidth / 2; const top = state.drag.holeY - state.drag.holeHeight / 2; const bottom = state.drag.holeY + state.drag.holeHeight / 2; if (state.drag.holeEdge === 'right') { hole.width = Math.max(1, state.drag.holeWidth + deltaX); hole.x = left + hole.width / 2; } else if (state.drag.holeEdge === 'left') { hole.width = Math.max(1, state.drag.holeWidth - deltaX); hole.x = right - hole.width / 2; } else if (state.drag.holeEdge === 'bottom') { hole.height = Math.max(1, state.drag.holeHeight + deltaY); hole.y = top + hole.height / 2; } else if (state.drag.holeEdge === 'top') { hole.height = Math.max(1, state.drag.holeHeight - deltaY); hole.y = bottom - hole.height / 2; } } syncHoleInputs(); renderHolesList(); } else if (state.drag.mode === 'resizePart') { const part = selectedPart(); if (!part || !state.drag.resizeAxis || !state.drag.resizeNormal || !state.drag.resizeMidpoint || !state.drag.resizeVectorEnd) return; const vectorDx = state.drag.resizeVectorEnd.x - state.drag.resizeMidpoint.x; const vectorDy = state.drag.resizeVectorEnd.y - state.drag.resizeMidpoint.y; const vectorLengthSquared = vectorDx * vectorDx + vectorDy * vectorDy; if (vectorLengthSquared <= 0.001) return; const outwardDelta = (dx * vectorDx + dy * vectorDy) / vectorLengthSquared * RESIZE_VECTOR_LENGTH; const currentSize = state.drag.resizeAxis === 'width' ? state.drag.partWidth : state.drag.partHeight; const rawSize = Math.max(MIN_PANEL_SIZE, currentSize + outwardDelta); const snappedSize = snapResizeSize(part, state.drag, rawSize); const candidate = resizeCandidate(part, state.drag, snappedSize); applyPartGeometry(part, { x: candidate.x, y: candidate.y, z: candidate.z, width: candidate.width, height: candidate.height }); syncInspector(); renderPartsList(); } else if (state.drag.mode === 'axisMove') { const part = selectedPart(); if (!part || !state.drag.axisStart || !state.drag.axisEnd) return; const axisDx = state.drag.axisEnd.x - state.drag.axisStart.x; const axisDy = state.drag.axisEnd.y - state.drag.axisStart.y; const axisLengthSquared = axisDx * axisDx + axisDy * axisDy; if (axisLengthSquared <= 0.001) return; const worldDelta = (dx * axisDx + dy * axisDy) / axisLengthSquared * (44 / Math.max(0.35, state.zoom)); const candidate = { x: state.drag.partX, y: state.drag.partY, z: state.drag.partZ }; candidate[state.drag.axis] = state.drag[`part${state.drag.axis.toUpperCase()}`] + worldDelta; const snapped = snapPartPosition(part, candidate, [state.drag.axis]); part.x = snapped.x; part.y = snapped.y; part.z = snapped.z; inputs.posX.value = round(part.x); inputs.posY.value = round(part.y); inputs.posZ.value = round(part.z); } else if (state.drag.mode === 'movePart') { const part = selectedPart(); if (!part) return; const point = screenToWorldAtZ(event.clientX, event.clientY, part.z); const snapped = snapPartPosition( part, { x: state.drag.partX + point.x - state.drag.dragWorldX, y: state.drag.partY + point.y - state.drag.dragWorldY, z: state.drag.partZ }, ['x', 'y'] ); part.x = snapped.x; part.y = snapped.y; part.z = snapped.z; inputs.posX.value = round(part.x); inputs.posY.value = round(part.y); inputs.posZ.value = round(part.z); } else { state.camera.panX = state.drag.panX + dx; state.camera.panY = state.drag.panY + dy; } draw(); }); canvas.addEventListener('pointerup', (event) => { const drag = state.drag; if (canvas.hasPointerCapture(event.pointerId)) { canvas.releasePointerCapture(event.pointerId); } if (drag?.mode === 'rotate' && !drag.moved && drag.hitPartId) { selectPart(drag.hitPartId); } state.drag = null; updateCanvasCursor(event); }); canvas.addEventListener('pointercancel', (event) => { if (canvas.hasPointerCapture(event.pointerId)) { canvas.releasePointerCapture(event.pointerId); } state.drag = null; updateCanvasCursor(event); }); canvas.addEventListener('pointerleave', () => { if (!state.drag) updateCanvasCursor(); }); window.addEventListener('resize', resizeCanvas); } function updateSelected(updates, rebuildList = true) { const part = selectedPart(); if (!part) return; applyPartGeometry(part, updates); syncInspector(); if (rebuildList) renderPartsList(); draw(); } function updateSelectedHole(updates) { const hole = selectedHole(); if (!hole) return; Object.assign(hole, updates); renderHolesList(); draw(); } seedScene(); bindEvents(); syncInputsFromState(); renderPartsList(); resizeCanvas();