` : ''}`;
const devtg = el.querySelector('.devtg');
if (devtg) devtg.onclick = (e) => {
e.stopPropagation();
p.devOn = !p.devOn;
colorSurfaceGizmo(p);
renderPrims();
};
el.querySelector('.p-ck').onchange = (e) => { p.checked = e.target.checked; refreshConstructUI(); };
el.querySelector('.x').onclick = async () => {
const j = await post('/api/prim/delete', { id: p.id });
if (!j.ok) return;
removePrim(p);
await commit(`Delete ${p.kind} ${p.id}`);
};
el.addEventListener('click', (e) => {
if (e.target.closest('input,button')) return;
const ck = el.querySelector('.p-ck');
ck.checked = !ck.checked;
p.checked = ck.checked;
refreshConstructUI();
});
wrap.appendChild(el);
});
refreshConstructUI();
refreshDevLegend();
renderAlignSlots();
}
// Which construction the checked set supports — mirrors the server's rules so the
// buttons light up only for meaningful combinations.
function inferHow(kind, checked) {
const kinds = checked.map(p => p.kind);
const n = k => kinds.filter(x => x === k).length;
if (kind === 'line') {
if (checked.length === 2 && n('plane') === 2) return 'planes';
if (checked.length === 1 && (n('cylinder') === 1 || n('cone') === 1)) return 'axis';
if (checked.length === 2 && n('line') === 1 && n('plane') === 1) return 'project';
if (checked.length >= 2 && checked.every(p => p.kind === 'cylinder' || p.kind === 'line')) return 'average';
} else {
if (checked.length === 2 && n('line') === 1 && n('plane') === 1) return 'lineplane';
if (checked.length === 3 && n('plane') === 3) return 'threeplanes';
if ((checked.length === 2 && n('point') === 2) || (checked.length === 1 && n('line') === 1)) return 'midpoint';
if (checked.length === 1 && n('sphere') === 1) return 'center';
}
return null;
}
function refreshConstructUI() {
const checked = prims.filter(p => p.checked);
$('mkline').disabled = !inferHow('line', checked);
$('mkpoint').disabled = !inferHow('point', checked);
}
async function constructPrim(kind) {
const checked = prims.filter(p => p.checked);
const how = inferHow(kind, checked);
if (!how) return;
const j = await post('/api/prim/construct', { kind, how, ids: checked.map(p => p.id) });
if (!j.ok) { setHud('Construct failed: ' + (j.error || 'server')); return; }
prims.forEach(p => { p.checked = false; });
addPrim(j.prim);
setHud(`Reference ${kind} created (${how}).`);
await commit(`Ref ${kind} ${j.prim.id}`, how);
}
$('mkline').addEventListener('click', () => constructPrim('line'));
$('mkpoint').addEventListener('click', () => constructPrim('point'));
async function fitPrim(type) {
setHud(`Fitting ${type}…`);
const j = await post('/api/prim/fit', { type });
if (!j.ok) { setHud('Fit failed: ' + (j.error || 'server')); return; }
addPrim(j.prim);
setHud(`${type} fitted — rms ${j.prim.rms.toFixed(3)} mm over ${j.prim.npts.toLocaleString()} pts.`);
directive(`${type} ${j.prim.id} extracted (rms ${j.prim.rms.toFixed(3)} mm). ` +
'Select another region, or check primitives to construct reference geometry.', true);
await commit(`Fit ${type} ${j.prim.id}`, `rms ${j.prim.rms.toFixed(3)}`);
}
$('fitplane').addEventListener('click', () => fitPrim('plane'));
$('fitcyl').addEventListener('click', () => fitPrim('cylinder'));
$('fitcone').addEventListener('click', () => fitPrim('cone'));
$('fitsphere').addEventListener('click', () => fitPrim('sphere'));
// ---- free-form Fit Surface + deviation colormap --------------------------
// The fitted B-spline preview is coloured by signed deviation to the scan:
// green within ±tol, gradient out to ±5·tol, saturated beyond, neutral grey in
// the extended skirt where there is no scan data. Recolouring on a tolerance
// change is pure client-side — that's the "real-time" part.
function devColor(d, tol, out) {
if (d === null || d === undefined || Number.isNaN(d)) { out.setRGB(0.35, 0.37, 0.4); return; }
const a = Math.abs(d);
if (a <= tol) { out.setHex(0x3fb950); return; }
const t = Math.min((a - tol) / (4 * tol), 1);
if (d > 0) out.setHSL(0.33 * (1 - t), 0.85, 0.5 - 0.22 * t); // green → red → dark
else out.setHSL(0.33 + 0.33 * t, 0.85, 0.5 - 0.22 * t); // green → blue → dark
}
function surfTol() { return Math.max(parseFloat($('surfTol').value) || 0.05, 1e-4); }
function colorSurfaceGizmo(p) {
const mesh = p.gizmo && p.gizmo.userData.surfMesh;
if (!mesh || !p.preview) return;
const tol = surfTol();
const dev = p.preview.dev;
const colors = mesh.geometry.getAttribute('color');
const c = new THREE.Color();
for (let i = 0; i < dev.length; i++) {
devColor(p.devOn ? dev[i] : null, tol, c);
if (!p.devOn) c.setHex(primColor(p));
colors.setXYZ(i, c.r, c.g, c.b);
}
colors.needsUpdate = true;
mesh.material.opacity = p.devOn ? 0.95 : 0.35;
}
function drawSurfaceGizmo(p) {
const { nu, nv, pos } = p.preview;
const geo = new THREE.BufferGeometry();
geo.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
geo.setAttribute('color', new THREE.Float32BufferAttribute(new Float32Array(nu * nv * 3), 3));
const idx = [];
for (let i = 0; i < nu - 1; i++)
for (let j = 0; j < nv - 1; j++) {
const a = i * nv + j, b = a + nv;
idx.push(a, b, a + 1, b, b + 1, a + 1);
}
geo.setIndex(idx);
geo.computeVertexNormals();
const mesh = new THREE.Mesh(geo, new THREE.MeshBasicMaterial({
vertexColors: true, transparent: true, opacity: 0.95, side: THREE.DoubleSide }));
const g = new THREE.Group();
g.add(mesh);
g.userData.surfMesh = mesh;
primGizmos.add(g);
return g;
}
function refreshDevLegend() {
const anySurf = prims.some(p => p.kind === 'surface');
$('devlegend').style.display = anySurf ? '' : 'none';
if (anySurf) {
const t = surfTol();
$('devlo').textContent = `−${(5 * t).toFixed(2)}`;
$('devhi').textContent = `+${(5 * t).toFixed(2)}`;
}
}
$('surfTol').addEventListener('input', () => {
prims.forEach(p => { if (p.kind === 'surface') colorSurfaceGizmo(p); });
refreshDevLegend();
});
$('fitsurf').addEventListener('click', async () => {
const auto = $('surfAuto').checked;
const body = {
smooth: (parseFloat($('surfSmooth').value) || 0) / 100,
tol: surfTol(),
auto,
};
if (!auto) {
body.u = Math.min(50, Math.max(4, parseInt($('surfU').value, 10) || 10));
body.v = Math.min(50, Math.max(4, parseInt($('surfV').value, 10) || 10));
}
$('fitsurf').disabled = true;
setHud(auto ? 'Fitting surface (auto-growing the control net)…' : 'Fitting surface…');
try {
const j = await post('/api/surface/fit', body);
if (!j.ok) { setHud('Surface fit failed: ' + (j.error || 'server')); return; }
const p = { ...j.prim, preview: j.preview, devOn: true, checked: false };
p.gizmo = drawSurfaceGizmo(p);
prims.push(p);
colorSurfaceGizmo(p);
renderPrims();
$('surfU').value = j.prim.u; // show what auto-fit actually reached
$('surfV').value = j.prim.v;
$('surfinfo').innerHTML = `${j.prim.u}×${j.prim.v} control pts · ` +
`rms ${j.prim.rms.toFixed(3)} mm · max ${j.prim.max.toFixed(3)} · ` +
`${j.prim.pctWithin.toFixed(1)}% within ±${surfTol()} mm`;
setHud('');
directive(`Surface fitted — the colour map shows deviation (green = within ±${surfTol()} mm). ` +
'Tighten Tolerance to recolour live, raise Smoothness and refit to trade accuracy for fairness.', true);
await commit(`Fit surface ${j.prim.id}`, `${j.prim.u}×${j.prim.v}`);
} finally {
$('fitsurf').disabled = selCount === 0;
refreshDevLegend();
}
});
// ---- Align by Coordinate System (3-2-1 datum alignment) -------------------
// Up to three primitives map to world roles; the server builds the rigid
// transform and reports per-DOF lock state. The triad preview shows where the
// world frame will land on the part: locked axes in full colour, free ones grey.
const ALIGN_DIR_KINDS = ['plane', 'cylinder', 'cone', 'line'];
const ALIGN_PT_KINDS = ['point', 'sphere'];
const alignSlots = [
{ id: -1, target: 'Z', flip: false },
{ id: -1, target: 'X', flip: false },
{ id: -1, target: 'Y', flip: false },
];
let alignFrame = null; // last /api/align/frame response
let alignGizmo = null;
const SLOT_NAMES = ['Primary', 'Secondary', 'Tertiary'];
function renderAlignSlots() {
const wrap = $('alignslots');
wrap.innerHTML = '';
$('align321pick').style.display = alignMode === 'prims' ? 'none' : '';
if (alignMode === 'points') { renderAlign321(wrap); return; }
if (alignMode === 'faces') { renderFaces(wrap); return; }
const eligible = prims.filter(p => ALIGN_DIR_KINDS.includes(p.kind) || ALIGN_PT_KINDS.includes(p.kind));
alignSlots.forEach((slot, i) => {
if (slot.id >= 0 && !eligible.some(p => p.id === slot.id)) slot.id = -1; // deleted prim
const row = document.createElement('div');
row.className = 'grid3';
row.style.marginTop = '4px';
const opts = [''].concat(eligible.map(p =>
``));
const chosen = eligible.find(p => p.id === slot.id);
const isDir = chosen && ALIGN_DIR_KINDS.includes(chosen.kind);
const targetSel = !chosen ? ''
: isDir
? ``
: '→ origin';
row.innerHTML = `
`;
row.querySelector('.a-p').onchange = (e) => {
slot.id = parseInt(e.target.value, 10);
autoFlip(slot);
renderAlignSlots();
previewAlign();
};
const t = row.querySelector('.a-t');
if (t) t.onchange = (e) => { slot.target = e.target.value; previewAlign(); };
const f = row.querySelector('.a-f');
if (f) f.onchange = (e) => { slot.flip = e.target.checked !== !!slot.auto; previewAlign(); };
wrap.appendChild(row);
});
}
// Engineers draw from the part's corner outward: by default a datum plane's
// axis points into the part, so the part sits on the + side of every plane.
// (A fitted normal's sign is arbitrary, so 'flip' starts from this instead.)
function partCenter() {
const box = new THREE.Box3();
for (const t of meshTargets) { t.geometry.computeBoundingBox(); box.union(t.geometry.boundingBox); }
return box.isEmpty() ? null : box.getCenter(new THREE.Vector3());
}
// `slot.auto` is that into-the-part default; `slot.flip` (sent to the server)
// is relative to the fitted normal. The checkbox shows flip ≠ auto, so it
// starts unticked and ticking it points the axis away from the part.
function autoFlip(slot) {
slot.auto = false;
const p = prims.find(x => x.id === slot.id);
const c = partCenter();
if (p && p.kind === 'plane' && c) slot.auto = c.sub(v3(p.origin)).dot(v3(p.normal)) < 0;
slot.flip = slot.auto;
}
function primDir(p) {
return v3(p.kind === 'plane' ? p.normal : p.kind === 'line' ? p.d : p.axis).normalize();
}
// With three direction slots, the first two fix the rotation and the third axis
// follows from the right-hand rule. If the third's requested direction points
// the other way, say so and offer the swap that honours all three.
// The direction slots in precedence order, for either slot-based method.
function dirSlots() {
const list = alignMode === 'faces' ? orderedFaces() : alignMode === 'prims' ? alignSlots : [];
return list.map(sl => ({ sl, p: prims.find(x => x.id === sl.id) }))
.filter(o => o.sl.id >= 0 && o.p && ALIGN_DIR_KINDS.includes(o.p.kind));
}
function swapFirstTwo() {
const d = dirSlots();
const a = d[0].sl.target, b = d[1].sl.target;
if (alignMode === 'faces') {
[alignFaces[a], alignFaces[b]] = [alignFaces[b], alignFaces[a]];
alignFaces[a].target = a; alignFaces[b].target = b;
} else {
d[0].sl.target = b; d[1].sl.target = a;
}
renderAlignSlots();
return previewAlign().then(livePreview).then(() => commit(`Swap ${a} and ${b}`));
}
function handednessNote(j) {
const dirs = dirSlots();
if (dirs.length < 3) return '';
const third = dirs[2];
const want = primDir(third.p).multiplyScalar(third.sl.flip ? -1 : 1);
const got = v3(j.axes[third.sl.target.toLowerCase()]);
if (want.dot(got) >= 0) return '';
const a = dirs[0].sl.target, b = dirs[1].sl.target, c = third.sl.target;
return `
⚠ ${c} is set by ${a} and ${b} (right-hand rule), so it points the other way ` +
`from ${third.p.kind} ${third.p.id}. To put the part on the + side of all three, swap ${a} and ${b}.` +
`
`;
}
function alignBody() {
if (alignMode === 'points') return align321Body();
const slots = [];
for (const s of alignMode === 'faces' ? orderedFaces() : alignSlots) {
if (s.id < 0) continue;
const p = prims.find(x => x.id === s.id);
if (!p) continue;
const entry = { id: s.id, flip: !!s.flip };
if (ALIGN_DIR_KINDS.includes(p.kind)) entry.target = s.target;
slots.push(entry);
}
const translate = [parseFloat($('alignTx').value) || 0,
parseFloat($('alignTy').value) || 0, parseFloat($('alignTz').value) || 0];
return { slots, translate };
}
function drawAlignGizmo(j) {
if (alignGizmo) { scene.remove(alignGizmo); alignGizmo = null; }
if (!j) return;
const g = new THREE.Group();
const o = v3(j.origin);
const len = Math.max(modelScale * 0.28, 10);
const axes = [
{ d: j.axes.x, c: 0xf85149, rot: [1, 2] }, // rot about y,z lock the X direction
{ d: j.axes.y, c: 0x3fb950, rot: [0, 2] },
{ d: j.axes.z, c: 0x2f81f7, rot: [0, 1] },
];
axes.forEach((a, i) => {
const locked = j.rotLocked[a.rot[0]] && j.rotLocked[a.rot[1]];
const color = locked ? a.c : 0x59606a;
g.add(new THREE.ArrowHelper(v3(a.d).normalize(), o, len, color, len * 0.18, len * 0.07));
});
// Datum planes, once both their normal direction and their offset are locked:
// XY ⊥ Z, YZ ⊥ X, XZ ⊥ Y, tinted by the normal axis.
const dirLocked = [0, 1, 2].map(k => axes[k].rot.every(r => j.rotLocked[r]));
const AX = [j.axes.x, j.axes.y, j.axes.z].map(a => v3(a).normalize());
[0, 1, 2].forEach(k => {
if (!dirLocked[k] || !j.transLocked[k]) return;
const u = AX[(k + 1) % 3], w = AX[(k + 2) % 3];
const quad = new THREE.Mesh(new THREE.PlaneGeometry(len * 1.6, len * 1.6),
new THREE.MeshBasicMaterial({ color: axes[k].c, transparent: true, opacity: 0.13,
side: THREE.DoubleSide, depthWrite: false }));
quad.matrixAutoUpdate = false;
quad.matrix.makeBasis(u, w, AX[k]).setPosition(o);
g.add(quad);
const edge = new THREE.LineSegments(new THREE.EdgesGeometry(quad.geometry),
new THREE.LineBasicMaterial({ color: axes[k].c, transparent: true, opacity: 0.6 }));
edge.matrixAutoUpdate = false;
edge.matrix.copy(quad.matrix);
g.add(edge);
});
const dot = new THREE.Mesh(new THREE.SphereGeometry(len * 0.03, 12, 10),
new THREE.MeshBasicMaterial({ color: 0xffffff }));
dot.position.copy(o);
g.add(dot);
g.visible = (step === 3);
scene.add(g);
alignGizmo = g;
}
async function previewAlign() {
const body = alignBody();
if (body.points ? !body.points.length : !body.slots.length) {
alignFrame = null;
drawAlignGizmo(null);
drawDatumPlanes();
$('alignapply').disabled = true;
$('alignpreview').disabled = true;
exitPreview();
$('alignstat').textContent = 'free';
$('alignstat').className = 'pill off';
return;
}
const j = await post('/api/align/frame', body);
if (!j.ok) {
alignFrame = null;
drawAlignGizmo(null);
$('alignapply').disabled = true;
$('alignpreview').disabled = true;
exitPreview();
$('aligninfo').innerHTML = '⚠ ' + (j.error || 'frame failed');
return;
}
alignFrame = j;
drawAlignGizmo(j);
drawDatumPlanes();
$('alignapply').disabled = false;
$('alignpreview').disabled = false;
syncPreview();
const rot = j.rotLocked.filter(Boolean).length, tr = j.transLocked.filter(Boolean).length;
$('alignstat').textContent = j.fullyDefined ? 'defined' : `${rot}/3 rot · ${tr}/3 trans`;
$('alignstat').className = 'pill ' + (j.fullyDefined ? 'on' : 'off');
$('aligninfo').innerHTML = (j.fullyDefined
? 'Coordinate system fully defined — Apply moves the part into it.'
: 'Partially constrained — free DOF stay put. ' + (alignMode === 'faces' ? 'Pick the remaining faces to pin them.' : 'Add more slots to pin them.')) +
(j.overconstrained && j.overconstrained.length
? ` ⚠ ignored: ${j.overconstrained.join('; ')}` : '') + handednessNote(j);
const sw = $('handswap');
if (sw) sw.onclick = swapFirstTwo;
}
// ---- Faces: click the +X, +Y, +Z faces ------------------------------------
// One click per axis: magic-wand the face, fit a plane (it joins the primitives
// list), point that axis into the part, and move the part into the frame
// defined so far — so after X and Y you can see which face should be Z.
// Each pick is one history step; ✕ clears just that axis for a re-pick.
const FACE_AXES = ['X', 'Y', 'Z'];
const PRECEDENCE = ['primary', 'secondary', 'tertiary'];
function orderedFaces() {
return FACE_AXES.filter(a => alignFaces[a]).map(a => ({ ...alignFaces[a], target: a }))
.sort((u, v) => u.order - v.order);
}
function faceCount() { return FACE_AXES.filter(a => alignFaces[a]).length; }
function clearFaces() {
FACE_AXES.forEach(a => { alignFaces[a] = null; });
alignFaces.active = 'X';
alignFaces.seq = 1;
}
function renderFaces(wrap) {
FACE_AXES.forEach(a => { // a face plane deleted from the primitives list
if (alignFaces[a] && !prims.some(p => p.id === alignFaces[a].id)) alignFaces[a] = null;
});
const ord = orderedFaces();
const armed = pick.armed === 'alignface';
wrap.innerHTML = FACE_AXES.map(a => {
const f = alignFaces[a], act = armed && alignFaces.active === a;
const rank = f ? PRECEDENCE[ord.findIndex(o => o.target === a)] : '';
return `
${act ? '▶ ' : ''}+${a}${f ? `
` : ''}
`;
}).join('');
wrap.querySelectorAll('.a3pick').forEach(b => b.onclick = () => armFace(b.dataset.ax));
wrap.querySelectorAll('.f-f').forEach(c => c.onchange = async () => {
const f = alignFaces[c.dataset.ax];
f.flip = c.checked !== !!f.auto;
await previewAlign(); livePreview();
commit(`${c.checked ? 'Flip' : 'Unflip'} +${c.dataset.ax}`);
});
wrap.querySelectorAll('.faceopts .x').forEach(b => b.onclick = () => clearFace(b.dataset.ax));
const n = faceCount();
$('align321pick').textContent = armed ? `◎ Picking +${alignFaces.active}… (click to stop)`
: n === 0 ? '◎ Pick faces' : n < 3 ? `◎ Pick remaining faces (${n}/3)` : '◎ Re-pick a face…';
}
function faceDirective() {
if (pick.armed !== 'alignface') {
if (faceCount() === 3) directive('All three faces set — the preview shows the part in X/Y/Z. Apply when it looks right.', true);
return;
}
const a = alignFaces.active;
directive(`Click the face that will be +${a} — the part goes on its + side. ` +
(faceCount() ? 'The part has moved to show the frame so far.' : 'One click picks the whole face.'));
}
function armFace(a) {
disarm();
alignFaces.active = a;
pick.armed = 'alignface';
$('align321pick').classList.add('armed');
renderAlignSlots();
faceDirective();
}
async function deletePrimQuiet(id) {
const p = prims.find(x => x.id === id);
if (!p) return;
const j = await post('/api/prim/delete', { id });
if (j.ok) removePrim(p);
}
async function pickAlignFace(hit) {
const a = alignFaces.active;
const q = hit.object.worldToLocal(hit.point.clone()); // model coords, even mid-preview
setHud(`Fitting the +${a} face…`);
const angleDeg = parseFloat($('wandDeg').value) || 15;
const sel = await post('/api/prim/select', { mode: 'wand', seed: [q.x, q.y, q.z], angleDeg, add: false });
const fit = sel.ok && sel.nsel ? await post('/api/prim/fit', { type: 'plane' }) : null;
await post('/api/prim/select', { mode: 'clear' });
selCount = 0; drawSelection(null); refreshSelUI();
if (!fit || !fit.ok) { setHud(`Couldn't read a flat face there — try another spot on the +${a} face.`); return; }
const old = alignFaces[a];
if (old) await deletePrimQuiet(old.id); // re-pick replaces that axis's plane
addPrim(fit.prim);
const f = { id: fit.prim.id, order: old ? old.order : alignFaces.seq++ };
autoFlip(f);
alignFaces[a] = f;
const next = FACE_AXES.find(x => !alignFaces[x]);
if (next) alignFaces.active = next;
else { pick.armed = null; $('align321pick').classList.remove('armed'); }
renderAlignSlots();
await previewAlign();
livePreview();
faceDirective();
setHud(`+${a} face: plane ${fit.prim.id}, rms ${fit.prim.rms.toFixed(3)} mm.`);
await commit(`Pick +${a} face`, `plane ${fit.prim.id}`);
}
async function clearFace(a) {
const f = alignFaces[a];
if (!f) return;
alignFaces[a] = null;
await deletePrimQuiet(f.id);
armFace(a);
await previewAlign();
livePreview();
await commit(`Clear +${a} face`);
}
// Faces and 3-2-1 points preview live: after each pick the part moves into
// the frame defined so far. The first time it also turns to the iso view.
function livePreview() {
if (step !== 3 || alignMode === 'prims') return;
if (!alignFrame) { exitPreview(true); return; }
if (previewOn) { syncPreview(); fitView(); return; }
previewOn = true;
$('alignpreview').classList.add('armed');
$('alignpreview').textContent = '👁 Previewing — click to exit';
syncPreview();
setView('iso');
}
// ---- 3-2-1 points (ZEISS INSPECT style) -----------------------------------
// Rule "AAA-BB-C": three plane points set coordinate A (the plane is ⊥ A),
// two line points set B (the line runs along C), one point sets C. Each point
// has its own nominal value. Points live in fixed slots so any one can be
// re-picked or removed; the active slot (▶) takes the next click on the mesh.
// The server previews after 3 and 5 points and fully defines the frame at 6.
const A321_RULES = ['ZZZ-YY-X', 'ZZZ-XX-Y', 'XXX-YY-Z', 'XXX-ZZ-Y', 'YYY-XX-Z', 'YYY-ZZ-X'];
const AXIS_COLOR = { X: 0xf85149, Y: 0x3fb950, Z: 0x2f81f7 };
const AXIS_CSS = { X: '#ff7b72', Y: '#56d364', Z: '#58a6ff' };
function a321Axis(i) { const r = align321.rule; return i < 3 ? r[0] : i < 5 ? r[4] : r[7]; }
function a321Name(i) { return a321Axis(i) + (i < 3 ? i + 1 : i < 5 ? i - 2 : ''); }
function a321Count() { return align321.pts.filter(Boolean).length; }
function drawAlign321Points() {
if (align321Obj) { scene.remove(align321Obj); align321Obj = null; }
align321Labels.forEach(el => el.remove());
align321Labels = [];
const g = new THREE.Group();
align321.pts.forEach((p, i) => {
if (!p) return;
const mk = new THREE.Mesh(new THREE.SphereGeometry(1, 12, 10),
new THREE.MeshBasicMaterial({ color: AXIS_COLOR[a321Axis(i)], depthTest: false, transparent: true, opacity: 0.95 }));
mk.renderOrder = 998;
mk.position.copy(v3(p));
g.add(mk);
// ZEISS-style tag: leader line from the point to "✕ X1:" (✕ removes it)
const el = document.createElement('div');
el.className = 'ptag';
el.style.setProperty('--c', AXIS_CSS[a321Axis(i)]);
el.innerHTML = `✕${a321Name(i)}:`;
el.querySelector('.xbtn').addEventListener('click', (ev) => { ev.stopPropagation(); removeAlign321Point(i); });
el.userData = { p };
viewport.appendChild(el);
align321Labels.push(el);
});
g.visible = (step === 3 && alignMode === 'points');
scene.add(g);
align321Obj = g;
syncPreview();
}
const _tp = new THREE.Vector3();
function updateAlign321Labels() {
if (!align321Labels.length) return;
const show = step === 3 && alignMode === 'points';
const w = viewport.clientWidth, vh = viewport.clientHeight;
if (align321Obj) align321Obj.updateMatrixWorld();
for (const el of align321Labels) {
const p = el.userData.p;
_tp.set(p[0], p[1], p[2]);
if (align321Obj) _tp.applyMatrix4(align321Obj.matrixWorld); // follows the XYZ preview
_tp.project(camera);
if (!show || _tp.z > 1 || _tp.z < -1) { el.style.display = 'none'; continue; }
el.style.display = 'block';
el.style.left = ((_tp.x * 0.5 + 0.5) * w) + 'px';
el.style.top = ((-_tp.y * 0.5 + 0.5) * vh) + 'px';
}
}
function align321Directive() {
if (pick.armed !== 'align321') {
if (a321Count() === 6) directive('All 6 points set — 👁 Preview to check the part in X/Y/Z, then Apply.', true);
return;
}
const i = align321.active;
const where = i < 3 ? 'on the plane face — spread the three out'
: i < 5 ? `along the line face — +${align321.rule[7]} runs from ${a321Name(3)} to ${a321Name(4)}`
: `on the face that sets ${align321.rule[7]}`;
directive(`Click ${a321Name(i)} ${where}.`);
}
function renderAlign321(wrap) {
const r = align321.rule;
const row = (i) => {
const has = !!align321.pts[i], act = pick.armed === 'align321' && align321.active === i;
return `
${act ? '▶ ' : ''}${a321Name(i)}:
`;
};
wrap.innerHTML = `
Plane — ${r[0]}1–${r[0]}3 set ${r[0]} (plane ⊥ ${r[0]})
${row(0)}${row(1)}${row(2)}
Line — ${r[4]}1–${r[4]}2 set ${r[4]} (line along ${r[7]})
${row(3)}${row(4)}
Point — sets ${r[7]}
${row(5)}`;
wrap.querySelector('.a3-rule').onchange = (e) => { align321.rule = e.target.value; drawAlign321Points(); renderAlignSlots(); align321Directive(); previewAlign(); };
wrap.querySelector('.a3-pp').onchange = (e) => { align321.planePositive = e.target.checked; previewAlign(); };
wrap.querySelector('.a3-lp').onchange = (e) => { align321.linePositive = e.target.checked; previewAlign(); };
wrap.querySelectorAll('.a3pick').forEach(b => b.onclick = () => armAlign321(parseInt(b.dataset.i, 10)));
wrap.querySelectorAll('.a3val input').forEach(inp => inp.onchange = () => {
align321.values[parseInt(inp.dataset.i, 10)] = parseFloat(inp.value) || 0;
previewAlign();
});
const n = a321Count();
$('align321pick').textContent = pick.armed === 'align321' ? `◎ Picking ${a321Name(align321.active)}… (click to stop)`
: n === 0 ? '◎ Pick 3-2-1 points' : n < 6 ? `◎ Pick remaining (${n}/6)` : '◎ Re-pick all points';
}
function align321Body() {
// the server only takes complete stages: 3 (plane), 5 (+line), 6 (+point)
const p = align321.pts;
const usable = p.every(Boolean) ? 6 : p.slice(0, 5).every(Boolean) ? 5 : p.slice(0, 3).every(Boolean) ? 3 : 0;
const hint = align321.normals.slice(0, 3).filter(Boolean)
.reduce((s, n) => [s[0] + n[0], s[1] + n[1], s[2] + n[2]], [0, 0, 0]);
return {
points: p.slice(0, usable),
rule: align321.rule, values: align321.values.slice(),
flipPlane: !align321.planePositive, flipLine: !align321.linePositive,
planeHint: hint, // "plane positive" = out of the clicked face
};
}
function clearAlign321() {
align321.pts = Array(6).fill(null);
align321.normals = Array(6).fill(null);
align321.active = 0;
drawAlign321Points();
}
function armAlign321(i) {
disarm();
align321.active = i;
pick.armed = 'align321';
$('align321pick').classList.add('armed');
renderAlignSlots();
align321Directive();
}
async function removeAlign321Point(i) {
align321.pts[i] = null;
align321.normals[i] = null;
drawAlign321Points();
armAlign321(i);
await previewAlign();
livePreview();
await commit(`Remove point ${a321Name(i)}`);
}
async function addAlign321Point(hit) {
// geometry-local = model coordinates, so picking works mid-preview too
const n = hit.face ? hit.face.normal.clone() : new THREE.Vector3();
const q = hit.object.worldToLocal(hit.point.clone());
const i = align321.active;
align321.pts[i] = [q.x, q.y, q.z];
align321.normals[i] = [n.x, n.y, n.z];
// advance to the next empty slot after this one (wrapping); none left → done
const next = [1, 2, 3, 4, 5].map(k => (i + k) % 6).find(k => !align321.pts[k]);
if (next === undefined) { pick.armed = null; $('align321pick').classList.remove('armed'); }
else align321.active = next;
drawAlign321Points();
renderAlignSlots();
align321Directive();
await previewAlign();
livePreview();
await commit(`Pick point ${a321Name(i)}`);
}
$('alignmode').addEventListener('change', (e) => {
alignMode = e.target.value;
disarm();
$('aligninfo').innerHTML = ALIGN_INFO[alignMode];
$('aligndelta').style.display = alignMode === 'points' ? 'none' : ''; // per-point values replace Δ
if (align321Obj) align321Obj.visible = alignMode === 'points' && step === 3;
renderAlignSlots();
previewAlign();
});
const ALIGN_INFO = {
faces: 'Click the faces at the part\'s corner: the one for +X, +Y, then +Z. ' +
'The part moves into place after each pick, on the + side of every face.',
points: 'Pick points on the mesh like ZEISS 3-2-1: 3 on the plane face, 2 along the ' +
'line face, 1 for the last axis. Each point can carry a nominal value.',
prims: 'Map primitives to the world frame — a plane ⇒ Z puts OXY on it, a cylinder ⇒ X pins ' +
'that axis line, a point pins the origin.',
};
$('align321pick').addEventListener('click', () => {
if (alignMode === 'faces') {
if (pick.armed === 'alignface') { disarm(); faceDirective(); return; }
armFace(FACE_AXES.find(a => !alignFaces[a]) || 'X');
return;
}
if (pick.armed === 'align321') { disarm(); return; }
if (a321Count() === 6) clearAlign321();
armAlign321(align321.pts.findIndex(p => !p));
previewAlign();
});
// Rigidly move every piece of client-side state into the new frame so nothing
// staged (seat, holes, gizmos) has to be re-picked after an alignment.
function applyRT(a, R, t) {
return [R[0] * a[0] + R[1] * a[1] + R[2] * a[2] + t[0],
R[3] * a[0] + R[4] * a[1] + R[5] * a[2] + t[1],
R[6] * a[0] + R[7] * a[1] + R[8] * a[2] + t[2]];
}
function applyR(a, R) {
return [R[0] * a[0] + R[1] * a[1] + R[2] * a[2],
R[3] * a[0] + R[4] * a[1] + R[5] * a[2],
R[6] * a[0] + R[7] * a[1] + R[8] * a[2]];
}
// ---- XYZ preview: show the part where Apply will put it -------------------
// Everything drawn in model coordinates gets the pending transform as its object
// matrix, so the part (and its gizmos) sit in the world frame against the datum
// planes and grid. Nothing moves server-side until Apply. (`previewOn` is
// declared up top: handleClick and setStep read it.)
function previewTargets() {
return [meshObject, primGizmos, gizmos, selObj, align321Obj, cloudObj, patchObj, meshMarkers]
.filter(Boolean);
}
function syncPreview() {
if (!previewOn) return;
if (!alignFrame) { exitPreview(); return; }
const { R, t } = alignFrame;
const M = new THREE.Matrix4().set(R[0], R[1], R[2], t[0], R[3], R[4], R[5], t[1],
R[6], R[7], R[8], t[2], 0, 0, 0, 1);
for (const o of previewTargets()) { o.matrixAutoUpdate = false; o.matrix.copy(M); o.matrixWorldNeedsUpdate = true; }
if (alignGizmo) alignGizmo.visible = false; // the world datum planes show the same frame
drawDatumPlanes();
}
function enterPreview() {
if (!alignFrame) return;
disarm();
previewOn = true;
$('alignpreview').classList.add('armed');
$('alignpreview').textContent = '👁 Previewing — click to exit';
syncPreview();
setView('iso');
directive('Preview: the part as it will sit in X/Y/Z — Z up, the grid is the XY plane. ' +
'Flip axes to fix it, then Apply.', true);
}
function exitPreview(keepCamera) {
if (!previewOn) return;
previewOn = false;
for (const o of previewTargets()) { o.matrixAutoUpdate = true; o.updateMatrix(); o.matrixWorldNeedsUpdate = true; }
if (alignGizmo) alignGizmo.visible = (step === 3);
$('alignpreview').classList.remove('armed');
$('alignpreview').textContent = '👁 Preview in XYZ';
drawDatumPlanes();
if (!keepCamera) fitView();
}
$('alignpreview').addEventListener('click', () => (previewOn ? exitPreview() : enterPreview()));
// Commit a rigid transform server-side, then carry every piece of client state
// into the new frame. Used by alignment Apply and by the datum-plane moves.
async function applyRigid(body, R, t) {
setHud('Moving the part…');
const j = await post('/api/align/apply', body);
if (!j.ok) { setHud('Move failed: ' + (j.error || 'server')); return false; }
await reloadMeshFromServer();
// registry entries come back transformed; keep client-only fields, rebuild gizmos
const byId = new Map((j.prims || []).map(p => [p.id, p]));
prims.forEach(p => {
const np = byId.get(p.id);
if (np) Object.assign(p, np);
if (p.kind === 'surface' && p.preview) { // rigid ⇒ deviations unchanged, positions move
const pos = p.preview.pos;
for (let i = 0; i < pos.length; i += 3) {
const q = applyRT([pos[i], pos[i + 1], pos[i + 2]], R, t);
pos[i] = q[0]; pos[i + 1] = q[1]; pos[i + 2] = q[2];
}
}
if (p.gizmo) primGizmos.remove(p.gizmo);
p.gizmo = p.kind === 'surface' ? drawSurfaceGizmo(p) : drawPrimGizmo(p);
if (p.kind === 'surface') colorSurfaceGizmo(p);
});
// staged seat / holes / datum move with the part
if (seat) {
seat.origin = applyRT(seat.origin, R, t);
seat.normal = applyR(seat.normal, R);
if (seat.u) seat.u = applyR(seat.u, R);
if (seat.v) seat.v = applyR(seat.v, R);
drawSeatGizmo({ normal: seat.normal, origin: seat.origin, patch: null });
}
if (datum) {
datum.origin = applyRT(datum.origin, R, t);
datum.normal = applyR(datum.normal, R);
}
holes.forEach(h => {
h.center = applyRT(h.center, R, t);
h.axis = applyR(h.axis, R);
h.p1 = applyRT(h.p1, R, t);
h.p2 = applyRT(h.p2, R, t);
if (h.gizmo) gizmos.remove(h.gizmo);
h.gizmo = drawHoleGizmo({ p1: h.p1, p2: h.p2, axis: h.axis,
diameter: effectiveDiameter(h) }, h.color, h.locked);
});
surfacePicks = surfacePicks.map(p2 => applyRT(p2, R, t));
lastSeatQuery = null;
if (patchObj) { scene.remove(patchObj); patchObj = null; } // stale decimated patch
drawSelection(null); selCount = 0; refreshSelUI(); // selection indices are stale
if (cloudObj) await reloadCloudFromServer(j.moved ? j.moved.ncloud : 0); // server moved it with the part
meshStatus = null; // canUndo changed server-side
alignSlots.forEach(s => { s.id = -1; s.flip = false; s.auto = false; });
clearFaces();
clearAlign321();
['alignTx', 'alignTy', 'alignTz'].forEach(id => { $(id).value = 0; });
alignFrame = null;
drawAlignGizmo(null);
$('alignpreview').disabled = true;
renderPrims();
renderAlignSlots();
drawDatumPlanes();
setHud('');
return true;
}
$('alignapply').addEventListener('click', async () => {
if (!alignFrame) return;
exitPreview(true);
$('alignapply').disabled = true;
const how = alignMode === 'points' ? '3-2-1 points' : 'primitives';
const ok = await applyRigid(alignBody(), alignFrame.R, alignFrame.t);
if (!ok) { $('alignapply').disabled = false; return; }
setView('iso');
$('alignstat').textContent = 'applied ✓';
$('alignstat').className = 'pill on';
directive('Part aligned — Z up, the grid is the XY plane. Everything staged moved with it. ' +
'Only need the planes? Skip to export to move them or download.', true);
await commit('Apply alignment', how);
});
$('alignreset').addEventListener('click', () => {
alignSlots.forEach((s, i) => { s.id = -1; s.target = ['Z', 'X', 'Y'][i]; s.flip = false; s.auto = false; });
if (pick.armed === 'align321' || pick.armed === 'alignface') disarm();
exitPreview();
clearAlign321();
clearFaces();
Object.assign(align321, { rule: 'ZZZ-YY-X', values: [0, 0, 0, 0, 0, 0], planePositive: true, linePositive: true });
['alignTx', 'alignTy', 'alignTz'].forEach(id => { $(id).value = 0; });
alignFrame = null;
drawAlignGizmo(null);
renderAlignSlots();
$('alignapply').disabled = true;
$('alignstat').textContent = 'free';
$('alignstat').className = 'pill off';
});
['alignTx', 'alignTy', 'alignTz'].forEach(id => $(id).addEventListener('change', previewAlign));
function clearAllPrims() {
clearFaces();
prims.forEach(p => { if (p.gizmo) primGizmos.remove(p.gizmo); });
prims.length = 0;
selCount = 0;
drawSelection(null);
alignSlots.forEach((s, i) => { s.id = -1; s.target = ['Z', 'X', 'Y'][i]; s.flip = false; s.auto = false; });
alignFrame = null;
drawAlignGizmo(null);
renderPrims();
refreshSelUI();
}
// ---------------------------------------------------------------- click routing
// Drag = orbit, always. A clean click (little movement, quick) acts according to
// the step / armed tool. No mode buttons.
const ray = new THREE.Raycaster();
const ndc = new THREE.Vector2();
let downAt = null;
renderer.domElement.addEventListener('pointerdown', (ev) => {
if (ev.button === 0) downAt = { x: ev.clientX, y: ev.clientY, t: performance.now() };
});
renderer.domElement.addEventListener('pointerup', (ev) => {
if (ev.button !== 0 || !downAt) return;
const moved = Math.hypot(ev.clientX - downAt.x, ev.clientY - downAt.y);
const dt = performance.now() - downAt.t;
downAt = null;
if (panKey) return; // space-panning, not picking
if (moved > 6 || dt > 600) return; // that was an orbit drag
handleClick(ev);
});
function raycastEvent(ev) {
const rect = renderer.domElement.getBoundingClientRect();
ndc.x = ((ev.clientX - rect.left) / rect.width) * 2 - 1;
ndc.y = -((ev.clientY - rect.top) / rect.height) * 2 + 1;
ray.setFromCamera(ndc, camera);
return ray.intersectObjects(meshTargets, true)[0] || null;
}
// The hint for hole detection: prefer a mesh hit near the seat plane (clicked the
// face), else the ray∩plane point (clicked into the bore's void).
function holeHint(ev, hit) {
const plane = new THREE.Plane().setFromNormalAndCoplanarPoint(v3(seat.normal), v3(seat.origin));
const pp = ray.ray.intersectPlane(plane, new THREE.Vector3());
if (hit && Math.abs(plane.distanceToPoint(hit.point)) < 2.5)
return [hit.point.x, hit.point.y, hit.point.z];
return pp ? [pp.x, pp.y, pp.z] : null;
}
async function handleClick(ev) {
if (!meshObject) return;
// the rotation center is a world point, so it can be picked on the previewed part too
if (pick.armed === 'pivot') {
const hit = raycastEvent(ev);
disarm();
if (!hit) { setHud('No surface there — rotation stays around the part\'s center.'); return; }
setPivot(hit.point, `Rotating around the clicked point (${hit.point.x.toFixed(1)}, ${hit.point.y.toFixed(1)}, ${hit.point.z.toFixed(1)}). ` +
'Double-click empty space to go back to the origin.');
return;
}
// alignment picks work on the previewed part (hits map back to model coords)
if (pick.armed === 'align321' || pick.armed === 'alignface') {
const h = raycastEvent(ev);
if (!h) { setHud('No surface there — try again.'); return; }
await (pick.armed === 'alignface' ? pickAlignFace(h) : addAlign321Point(h));
return;
}
if (previewOn) { setHud('Previewing the aligned part — exit the preview to pick.'); return; }
if (isPaintMode()) return; // strokes (incl. single taps) are handled by the paint listeners
const hit = raycastEvent(ev);
if (pick.armed === 'origin') {
disarm();
if (!hit) { setHud('No surface there — try again.'); return; }
await setOrigin(hit.point);
return;
}
if (pick.armed === 'parallel') {
disarm();
if (!hit || !lastSeatQuery) { setHud('No surface there — try again.'); return; }
if (await fitSeat({ ...lastSeatQuery,
parallelTo: { point: [hit.point.x, hit.point.y, hit.point.z], radius: 0 } }))
await commit('Lock parallel');
return;
}
if (pick.armed === 'datum') {
disarm();
if (!hit) { setHud('No surface there — try again.'); return; }
await pickDatum(hit.point);
return;
}
if (pick.armed === 'refine') {
if (!hit) { setHud('No surface there — try again.'); return; }
surfacePicks.push([hit.point.x, hit.point.y, hit.point.z]);
addMarker(hit.point, SEAT_COLOR);
const left = 3 - surfacePicks.length;
if (left > 0) directive(`Refining — click ${left} more point${left === 1 ? '' : 's'} on the same surface.`);
else { pick.armed = null; $('refine').classList.remove('armed'); }
if (await fitSeat({ points: surfacePicks.slice() }))
await commit('Refine surface', `${surfacePicks.length} pts`);
return;
}
if (pick.armed === 'coplanar') {
// Open-ended: each click adds a surface to the SAME plane — one joint fit
// through every picked island. Stays armed until the user clicks the button
// again (or leaves the step), so any number of coplanar faces can join.
if (!hit) { setHud('No surface there — try again.'); return; }
surfacePicks.push([hit.point.x, hit.point.y, hit.point.z]);
addMarker(hit.point, SEAT_COLOR);
const ok = await fitSeat({ points: surfacePicks.slice() });
// Not coplanar within tolerance → the fitter silently ignored the new pick's
// seeds. Catch it by the pick's distance to the fitted plane and say so.
const off = ok ? Math.abs(hit.point.clone().sub(v3(seat.origin)).dot(v3(seat.normal))) : 0;
if (!ok || off > 1.0) {
surfacePicks.pop();
const mk = markers.pop();
if (mk) gizmos.remove(mk);
directive(ok
? `That surface sits ${off.toFixed(2)} mm off this plane — not coplanar, so it wasn't added. Use ∥ parallel instead if it's a different level.`
: 'That point didn\'t read as part of the same plane — try another spot on the surface.');
if (ok) await fitSeat({ points: surfacePicks.slice() }); // restore the plane without it
pick.armed = 'coplanar';
return;
}
pick.armed = 'coplanar'; // fitSeat rewrote the directive; re-assert the mode
directive(`One plane through ${surfacePicks.length} pick${surfacePicks.length === 1 ? '' : 's'} — ` +
`click more coplanar surfaces to add them, or press ⧉ again to finish.`);
await commit('Extend coplanar', `${surfacePicks.length} picks`);
return;
}
if (pick.armed === 'assist') {
const hint = seat ? holeHint(ev, hit) : null;
if (!hint) { setHud('Click inside the hole area.'); return; }
pick.pts.push(hint);
addMarker(new THREE.Vector3(...hint), PINK);
const left = 3 - pick.pts.length;
if (left > 0) { directive(`Got it — click ${left} more point${left === 1 ? '' : 's'} inside the hole.`); return; }
const pts = pick.pts.slice();
disarm();
directive('Solving the hole from your 3 points…');
const ok = await detectHole(null, 0, 'Hole', pts);
if (!ok) directive('Still no round gap there. Check the Ø bounds, or refine the surface and retry.', true);
else directive(`${holes.length} hole${holes.length === 1 ? '' : 's'} staged. Not seeing another? Click inside it.`);
return;
}
// step-default actions
if (step === 2) {
// Mesh edit: clicking a red gap ring fills that hole. raycastEvent above
// already aimed `ray`, so reuse it against the markers (their invisible
// centre discs give the ring a solid hit area).
const mh = ray.intersectObjects(meshMarkers.children, true)[0];
if (!mh) return;
let g = mh.object;
while (g && g.userData.holeId === undefined) g = g.parent;
if (!g) return;
const method = $('fillmethod').value;
const j = await meshOp('/api/mesh/fill_holes', { holes: [g.userData.holeId], method },
'Filling the hole…');
if (!j) return;
setHud(`Hole filled (${method}) — ${j.status.holes.length} remaining. ${keyLabel('mod+Z')} undoes it if that was a real bore.`);
if (j.filled) await commit('Fill hole', method);
} else if (step === 3) {
// Primitives: click = magic-wand select (Shift adds to the selection)
if (!hit) { setHud('Click on the model surface to select it.'); return; }
await wandSelect(hit.point, ev.shiftKey);
} else if (step === 4) {
if (!hit) { setHud('Click on the model surface.'); return; }
surfacePicks = [[hit.point.x, hit.point.y, hit.point.z]];
clearMarkers();
addMarker(hit.point, SEAT_COLOR);
if (await fitSeat({ points: surfacePicks.slice() })) await commit('Pick surface');
} else if (step === 5) {
if (!seat) return;
const hint = holeHint(ev, hit);
if (!hint) { setHud('Click the hole (or the surface near it).'); return; }
directive('Looking for a round gap there…');
if (await detectHole(hint, 0, 'Hole')) {
directive(`${holes.length} hole${holes.length === 1 ? '' : 's'} staged. Not seeing another? Click inside it.`);
return;
}
// gated wall-fit fallback (only when the bore itself scanned)
if (hit && await lockedWallFit(hit.point)) {
directive(`${holes.length} hole${holes.length === 1 ? '' : 's'} staged. Not seeing another? Click inside it.`);
return;
}
// escalate: ask the user for more evidence
pick.armed = 'assist';
pick.pts = [hint];
addMarker(new THREE.Vector3(...hint), PINK);
directive(`Couldn't confirm it from one point — click 2 more points inside the hole.`);
}
}
// ---------------------------------------------------------------- paint select
// Geomagic-style brush: while armed, dragging on the mesh paints a circular
// stamp trail; the seat plane is fitted from exactly the painted vertices
// (server rejects brushed-over walls/bores). Strokes accumulate — including on
// other coplanar surfaces — and every stroke release refits. Dragging from
// empty space still orbits, so you can turn the part between strokes.
const paint = { samples: [], radius: 0, active: false, dots: null };
let brushRing = null;
// The brush serves two masters: 'paint' fits the seat plane, 'primpaint' feeds
// the primitives selection. Same stroke mechanics, different release handler.
function isPaintMode() { return pick.armed === 'paint' || pick.armed === 'primpaint'; }
function brushR() { return paint.radius > 0 ? paint.radius : Math.max(modelScale * 0.012, 1.5); }
function ensureBrush() {
if (!brushRing) {
brushRing = new THREE.Mesh(
new THREE.TorusGeometry(1, 0.035, 10, 48),
new THREE.MeshBasicMaterial({ color: SEAT_COLOR, depthTest: false,
transparent: true, opacity: 0.9 }));
brushRing.renderOrder = 997;
scene.add(brushRing);
}
return brushRing;
}
function updateBrush(hit) {
const ring = ensureBrush();
ring.visible = !!hit;
if (!hit) return;
ring.position.copy(hit.point);
const n = hit.face
? hit.face.normal.clone().transformDirection(hit.object.matrixWorld)
: camera.getWorldDirection(new THREE.Vector3()).negate();
ring.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), n);
ring.scale.setScalar(brushR());
}
function paintDotsRefresh() {
if (paint.dots) { scene.remove(paint.dots); paint.dots = null; }
if (!paint.samples.length) return;
const geo = new THREE.BufferGeometry();
geo.setAttribute('position', new THREE.Float32BufferAttribute(paint.samples.flat(), 3));
paint.dots = new THREE.Points(geo, new THREE.PointsMaterial({
color: SEAT_COLOR, size: Math.max(modelScale * 0.004, 0.6), sizeAttenuation: true,
transparent: true, opacity: 0.9, depthTest: false }));
paint.dots.renderOrder = 996;
scene.add(paint.dots);
}
function endPaintMode() {
paint.active = false;
paint.samples = [];
controls.enabled = true;
if (brushRing) brushRing.visible = false;
if (paint.dots) { scene.remove(paint.dots); paint.dots = null; }
}
function addPaintSample(p) {
paint.samples.push([p.x, p.y, p.z]);
paintDotsRefresh();
}
async function fitPaintedSeat() {
const ok = await fitSeat({ paint: { centers: paint.samples.slice(), radius: brushR() } });
if (!ok) {
directive('Couldn\'t fit a plane to the painted area yet — keep painting on the surface.');
return;
}
surfacePicks = [paint.samples[0].slice()]; // seed for the step-3 hole scan
directive(`Painted plane locked from ${paint.samples.length} stamps. Keep painting to add area — ` +
`even on other coplanar surfaces — or press 🖌 again to finish. ` +
`[ and ] resize the brush.`);
await commit('Paint surface', `${paint.samples.length} stamps`);
}
renderer.domElement.addEventListener('pointerdown', (ev) => {
if (!isPaintMode() || ev.button !== 0 || panKey) return;
const hit = raycastEvent(ev);
if (!hit) return; // empty space: leave the drag to OrbitControls
paint.active = true;
controls.enabled = false; // this drag paints; it must not orbit
addPaintSample(hit.point);
});
let lastBrushCast = 0;
renderer.domElement.addEventListener('pointermove', (ev) => {
if (!isPaintMode() || panKey) return;
// Raycasts are O(tris); at move frequency on a multi-million-tri scan they'd
// freeze the UI. ~30 Hz is plenty for a brush.
const now = performance.now();
if (now - lastBrushCast < 33) return;
lastBrushCast = now;
const hit = raycastEvent(ev);
updateBrush(hit);
if (!paint.active || !hit) return;
const last = paint.samples[paint.samples.length - 1];
if (last && hit.point.distanceTo(new THREE.Vector3(last[0], last[1], last[2])) < brushR() * 0.45) return;
addPaintSample(hit.point);
});
renderer.domElement.addEventListener('pointerup', async (ev) => {
if (!isPaintMode() || !paint.active || ev.button !== 0) return;
paint.active = false;
controls.enabled = true;
if (!paint.samples.length) return;
if (pick.armed === 'primpaint') await primPaintSelect();
else await fitPaintedSeat();
});
$('paintsurf').addEventListener('click', () => {
if (!meshObject) { setHud('Load a mesh first.'); return; }
const arming = pick.armed !== 'paint';
disarm(); // also clears any previous paint session
if (arming) {
pick.armed = 'paint';
$('paintsurf').classList.add('armed');
ensureBrush();
directive('Drag across the surface to paint it — the plane is fitted from exactly ' +
'the painted points. Paint several coplanar surfaces to join them. ' +
'[ ] brush size · drag from empty space to orbit');
} else {
directive(seat ? 'Painted plane kept. Find holes when ready.' : 'Paint cancelled.', !!seat);
}
});
// double-click the model to set the orbit pivot at that point (rotation centre)
renderer.domElement.addEventListener('dblclick', (ev) => {
if (!meshObject) return;
const hit = raycastEvent(ev);
if (!hit) { setPivot(new THREE.Vector3(), 'Rotation center back on the origin. Double-click the part to rotate around a point on it.', 'origin'); return; }
setPivot(hit.point);
});
// fit-to-view: button + 'f' key
$('fitview').addEventListener('click', () => fitView());
window.addEventListener('keydown', (e) => {
if (e.key === 'f' && meshObject && e.target.tagName !== 'INPUT') fitView();
});
// ---- rotation center ------------------------------------------------------
// One click: rotate around the middle of the part's X/Y/Z bounding box (after
// alignment, the box squared to the datum planes). The button stays armed so
// the next click on the model can pick a point instead; Esc keeps the center.
$('setpivot').addEventListener('click', () => {
if (!meshObject) { setHud('Load a mesh first.'); return; }
if (pick.armed === 'pivot') { disarm(); setHud('Rotation center kept.'); return; }
const box = meshBox();
if (box.isEmpty()) return;
setPivot(box.getCenter(new THREE.Vector3()),
'Rotating around the center of the part. Click the model to rotate around a point instead.', 'center');
disarm();
pick.armed = 'pivot';
$('setpivot').classList.add('armed');
});
// ---- redefine the origin --------------------------------------------------
$('setorigin').addEventListener('click', () => {
if (!meshObject) { setHud('Load a mesh first.'); return; }
disarm();
pick.armed = 'origin';
$('setorigin').classList.add('armed');
setHud('Click a point on the model to set it as the origin (0,0,0).');
});
async function setOrigin(p) {
const off = p.clone();
const j = await post('/api/set_origin', { point: [off.x, off.y, off.z] });
if (!j || !j.ok) { setHud('Set origin failed: ' + ((j && j.error) || 'server')); return; }
// shift everything by -off; view is preserved because the camera moves too
for (const t of meshTargets) {
t.geometry.translate(-off.x, -off.y, -off.z);
t.geometry.computeBoundingBox();
}
gizmos.children.forEach(c => c.position.sub(off));
holes.forEach(h => { h.center = [h.center[0] - off.x, h.center[1] - off.y, h.center[2] - off.z]; });
if (datum) datum.origin = [datum.origin[0] - off.x, datum.origin[1] - off.y, datum.origin[2] - off.z];
if (seat) seat.origin = [seat.origin[0] - off.x, seat.origin[1] - off.y, seat.origin[2] - off.z];
surfacePicks = surfacePicks.map(p2 => [p2[0] - off.x, p2[1] - off.y, p2[2] - off.z]);
lastSeatQuery = null; // its coords are in the old frame
if (cloudObj) cloudObj.geometry.translate(-off.x, -off.y, -off.z);
if (patchObj) {
patchObj.geometry.translate(-off.x, -off.y, -off.z);
seatPatchId = cacheBlob(Array.from(patchObj.geometry.attributes.position.array));
}
frameShift.add(off);
camera.position.sub(off);
controls.target.sub(off);
controls.update();
showPivot();
drawDatumPlanes();
setHud('Origin moved to the clicked point. Exports and picks now use this frame.');
await commit('Set origin');
}
// ---------------------------------------------------------------- surface (02)
async function fitSeat(query) {
setHud('Analysing the surface…');
const vd = camera.getWorldDirection(new THREE.Vector3()).negate();
const body = { ...query, viewDir: [vd.x, vd.y, vd.z] };
const j = await post('/api/fit_seat', body);
if (!j.ok) {
setHud('');
directive('Couldn\'t read a flat surface there — try another point.', false);
$('seatinfo').textContent = 'Surface fit failed: ' + (j.error || '');
return false;
}
seat = { origin: j.origin, normal: j.normal, u: j.u, v: j.v };
seatPatchId = j.patch && j.patch.length >= 9 ? cacheBlob(j.patch) : null;
seatScanned = false; // new plane — step 3 will scan it
lastSeatQuery = query.paint ? { paint: query.paint }
: { points: query.points || lastSeatQuery?.points || surfacePicks.slice() };
drawSeatGizmo(j);
drawPatch(j.patch);
$('seatstat').textContent = j.parallel ? 'set ∥' : 'set';
$('seatstat').className = 'pill on';
$('parallelpick').disabled = false;
$('refine').disabled = false;
$('addcoplanar').disabled = false;
$('seatredo').disabled = false;
$('seatinfo').innerHTML =
`n = (${fmt(j.normal)}) rms ${j.rms.toFixed(3)} mm · ${j.npts.toLocaleString()} mesh pts` +
(j.ncloud ? ` + ${j.ncloud.toLocaleString()} cloud` : '') +
(j.npatch ? ` · patch ${j.npatch.toLocaleString()} verts` : '') +
(j.parallel ? ` ∥-locked to picked face (rms ${j.parallel.rms.toFixed(3)})` : '');
setHud('');
directive(`Surface locked — the highlighted patch is what I'll use (rms ${j.rms.toFixed(2)} mm). ` +
`Wrong patch? Click a different point, or refine. Otherwise find holes.`, true);
refreshStepper();
return true;
}
function drawPatch(flat) {
if (patchObj) { scene.remove(patchObj); patchObj = null; }
if (!flat || flat.length < 9) return;
const geo = new THREE.BufferGeometry();
geo.setAttribute('position', new THREE.Float32BufferAttribute(flat, 3));
patchObj = new THREE.Points(geo, new THREE.PointsMaterial({
color: SEAT_COLOR, size: Math.max(modelScale * 0.002, 0.3), sizeAttenuation: true,
transparent: true, opacity: 0.85, depthTest: true }));
scene.add(patchObj);
}
function drawSeatGizmo(j) {
if (seatGizmo) gizmos.remove(seatGizmo);
let r = Math.max(modelScale * 0.015, 2);
if (j.patch && j.patch.length >= 9) {
const g2 = new THREE.BufferGeometry();
g2.setAttribute('position', new THREE.Float32BufferAttribute(j.patch, 3));
g2.computeBoundingSphere();
if (g2.boundingSphere) r = Math.min(Math.max(g2.boundingSphere.radius * 0.4, 1.5), 60);
}
const g = new THREE.Group();
g.add(new THREE.ArrowHelper(v3(j.normal), v3(j.origin), r * 1.4, SEAT_COLOR, r * 0.35, r * 0.18));
seatGizmo = g;
gizmos.add(g);
}
function clearSeat() {
if (seatGizmo) { gizmos.remove(seatGizmo); seatGizmo = null; }
if (patchObj) { scene.remove(patchObj); patchObj = null; }
seat = null; lastSeatQuery = null; surfacePicks = []; seatPatchId = null;
clearMarkers();
$('seatstat').textContent = 'none'; $('seatstat').className = 'pill off';
$('parallelpick').disabled = true;
$('refine').disabled = true;
$('addcoplanar').disabled = true;
$('seatredo').disabled = true;
$('seatinfo').textContent = 'Rotate so you can see the face, then click once on it.';
refreshStepper();
}
$('seatredo').addEventListener('click', () => {
disarm(); // also tears down an in-progress paint session
if (!seat) return;
clearSeat();
directive('Click once on the surface the holes pass through.');
commit('Clear surface');
});
$('refine').addEventListener('click', () => {
if (!seat) return;
disarm();
pick.armed = 'refine';
$('refine').classList.add('armed');
directive('Refining — click 2 more points on the same surface.');
});
$('addcoplanar').addEventListener('click', () => {
if (!seat) return;
const arming = pick.armed !== 'coplanar';
disarm();
if (arming) {
pick.armed = 'coplanar';
$('addcoplanar').classList.add('armed');
directive('Click each surface that lies on this same plane — one plane is fitted ' +
'through all of them, and holes on any of them will share it. Press ⧉ again to finish.');
} else {
directive(`Plane locked across ${surfacePicks.length} pick${surfacePicks.length === 1 ? '' : 's'}. Find holes when ready.`, true);
}
});
$('parallelpick').addEventListener('click', () => {
if (!seat || !lastSeatQuery) return;
const arming = pick.armed !== 'parallel';
disarm();
if (arming) {
pick.armed = 'parallel';
$('parallelpick').classList.add('armed');
directive('Click the face this surface must be parallel to.');
}
});
// ---------------------------------------------------------------- holes (03)
function diaWindow() {
return { minDiameterMM: parseFloat($('minDia').value) || 0,
maxDiameterMM: parseFloat($('maxDia').value) || 0 };
}
async function autoScan() {
if (!seat || !surfacePicks.length) return;
seatScanned = true;
directive('Scanning this surface for round holes…');
const j = await post('/api/detect_holes_auto', {
seed: surfacePicks[0], origin: seat.origin, normal: seat.normal, ...diaWindow() });
if (!j.ok) { directive('Scan failed: ' + (j.error || 'server'), true); return; }
let added = 0;
for (const h of j.holes) if (mergeHole(h)) added++;
if (holes.length)
directive(`${holes.length} hole${holes.length === 1 ? '' : 's'} found on this surface. ` +
`Not seeing yours? Click inside it.`, false);
else
directive('No holes found automatically within the Ø bounds. Click inside the hole you can see.');
setHud(added ? `${added} hole${added === 1 ? '' : 's'} auto-detected.` : '');
refreshBuildEnabled();
if (added) await commit('Find holes', `${added} found`);
}
$('rescan').addEventListener('click', autoScan);
$('nextsurface').addEventListener('click', () => setStep(4));
// Detect a hole around `hint` (or from `insidePts`) as a circular data gap.
async function detectHole(hint, searchR, label, insidePts) {
if (!seat) return false;
const body = { origin: seat.origin, normal: seat.normal, ...diaWindow() };
if (insidePts) body.points = insidePts;
else { body.point = hint; body.radius = searchR || 0; }
const j = await post('/api/detect_hole', body);
if (!j.ok) return false;
if (!mergeHole(j)) { setHud('That hole is already staged.'); return true; }
setHud(`${label || 'Hole'}: Ø${j.diameter.toFixed(2)} mm, ${Math.round(j.coverage * 100)}% rim` +
(j.depthMeasured ? `, depth ${j.depth.toFixed(1)}` : ', depth unseen — set it if blind') +
'. Set caliper Ø / thread to refine.');
refreshBuildEnabled();
await commit(`Add hole ${holes.length}`, `Ø ${j.diameter.toFixed(2)}`);
return true;
}
// Gated fallback when the bore wall actually scanned: axis-locked cylinder fit,
// accepted only if clean and inside the Ø window — never invent a hole.
async function lockedWallFit(p) {
const j = await post('/api/fit_cylinder', { point: [p.x, p.y, p.z], radius: 0,
axisLock: seat.normal, axisOrigin: seat.origin });
if (!j.ok) return false;
const { minDiameterMM: minD, maxDiameterMM: maxD } = diaWindow();
if (j.rms > Math.max(0.25, 0.04 * j.diameter)) return false;
if (minD > 0 && j.diameter < minD * 0.85) return false;
if (maxD > 0 && j.diameter > maxD * 1.15) return false;
if (!mergeHole(j)) return true;
setHud(`Hole fitted from its wall: Ø${j.diameter.toFixed(2)} mm, rms ${j.rms.toFixed(3)} — axis locked.`);
refreshBuildEnabled();
await commit(`Add hole ${holes.length}`, `Ø ${j.diameter.toFixed(2)} wall fit`);
return true;
}
// Add a discovered hole unless one already exists at ~the same place.
function mergeHole(c) {
const nc = v3(c.center);
for (const h of holes) {
const d = nc.distanceTo(v3(h.center));
if (d < Math.max(c.diameter * 0.5, 1.5)) return false;
}
addHole(c);
return true;
}
let inFlight = 0; // requests still running — undo waits for the action to land
async function post(url, body) {
inFlight++;
try {
const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body) });
return await r.json();
} finally {
inFlight--;
}
}
// ---------------------------------------------------------------- undo / redo
// Whole-document history. After every action that changes the model the browser
// commits: the server snapshots its state (mesh, cloud, primitives, selection,
// frame) and stores this page's state (`docState`) beside it. Undo / redo / goto
// restore a snapshot on the server and hand the page state back to `restoreDoc`.
// View changes (camera, planes toggle, step tabs) are not history.
const isMac = /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent);
function keyLabel(k) {
return k.split('+').map(p => ({ mod: isMac ? '⌘' : 'Ctrl', shift: isMac ? '⇧' : 'Shift',
alt: isMac ? '⌥' : 'Alt' }[p] || p)).join(isMac ? '' : '+');
}
const STEP_NAMES = ['Scan', 'Mesh', 'Prims', 'Surface', 'Holes', 'Export'];
let hist = { cursor: -1, entries: [], canUndo: false, canRedo: false, dropped: 0 };
let histBusy = false;
// Large immutable arrays (the accepted surface patch) stay in the page and are
// referenced from snapshots by key, so history doesn't copy them per step.
const blobCache = new Map();
let blobSeq = 1;
function cacheBlob(v) { const k = blobSeq++; blobCache.set(k, v); return k; }
function docState() {
return {
step,
frameShift: frameShift.toArray(),
meshinfo: $('meshinfo').innerHTML, cloudinfo: $('cloudinfo').innerHTML,
decinfo: $('decinfo').innerHTML, surfinfo: $('surfinfo').innerHTML,
prims: Object.fromEntries(prims.map(p => [p.id, { checked: !!p.checked, devOn: !!p.devOn }])),
seat: seat ? {
...seat, picks: surfacePicks, query: lastSeatQuery, scanned: seatScanned, patchId: seatPatchId,
stat: $('seatstat').textContent, info: $('seatinfo').innerHTML,
} : null,
holes: holes.map(h => ({ id: h.id, center: h.center, axis: h.axis, diameterFit: h.diameterFit,
measured: h.measured, thread: h.thread, through: h.through, depth: h.depth, p1: h.p1, p2: h.p2,
locked: h.locked, bossDir: h.bossDir, color: h.color })),
nextId, selectedHole: selectedHole ? selectedHole.id : null,
datum: datum ? { ...datum, info: $('datuminfo').innerHTML } : null,
align: {
mode: alignMode, slots: alignSlots.map(x => ({ ...x })),
faces: JSON.parse(JSON.stringify(alignFaces)),
a321: { pts: align321.pts.slice(), normals: align321.normals.slice(), active: align321.active,
rule: align321.rule, values: align321.values.slice(),
planePositive: align321.planePositive, linePositive: align321.linePositive },
delta: ['alignTx', 'alignTy', 'alignTz'].map(id => $(id).value),
stat: $('alignstat').textContent, statClass: $('alignstat').className,
info: $('aligninfo').innerHTML,
},
};
}
async function commit(label, detail = '') {
if (restoring || !meshObject) return;
try {
const j = await post('/api/history/commit',
{ label, step: STEP_NAMES[step - 1], detail, ui: docState() });
if (j.ok) setHistory(j.history);
else console.warn('[scan2cad] history commit failed:', j.error);
} catch (err) {
console.warn('[scan2cad] history commit failed:', err);
}
}
function resetHistoryUI() {
setHistory({ cursor: -1, entries: [], canUndo: false, canRedo: false, dropped: 0 });
blobCache.clear();
seatPatchId = null;
}
function setHistory(h) {
hist = h;
const undoE = h.canUndo ? h.entries[h.cursor] : null;
const redoE = h.canRedo ? h.entries[h.cursor + 1] : null;
$('b-undo').disabled = !undoE; $('m-undo').disabled = !undoE;
$('b-redo').disabled = !redoE; $('m-redo').disabled = !redoE;
$('b-hist').disabled = !h.entries.length;
$('b-undo').title = undoE ? `Undo ${undoE.label} (${keyLabel('mod+Z')})` : 'Nothing to undo';
$('b-redo').title = redoE ? `Redo ${redoE.label} (${keyLabel('shift+mod+Z')})` : 'Nothing to redo';
$('b-hist').title = `History (${keyLabel('alt+mod+Z')})`;
$('m-undo').querySelector('.what').textContent = undoE ? undoE.label : '';
$('m-redo').querySelector('.what').textContent = redoE ? redoE.label : '';
const last = $('lastact');
last.textContent = '';
if (undoE) { last.append('Last: '); const b = document.createElement('b'); b.textContent = undoE.label; last.append(b); }
renderTape();
}
function renderTape() {
const list = $('tapelist');
list.innerHTML = '';
if (hist.dropped) {
const li = document.createElement('li');
li.className = 'ent dropped';
li.textContent = `${hist.dropped} older step${hist.dropped === 1 ? '' : 's'} dropped to stay under the memory limit`;
list.appendChild(li);
}
hist.entries.forEach((e, i) => {
const li = document.createElement('li');
li.className = 'ent' + (i === hist.cursor ? ' now' : i > hist.cursor ? ' future' : '');
li.tabIndex = 0;
for (const [cls, text] of [['stp', e.step], ['act', e.label], ['det', e.detail]]) {
const sp = document.createElement('span'); sp.className = cls; sp.textContent = text || '';
li.appendChild(sp);
}
li.title = i === hist.cursor ? 'Current state' : `Go ${i < hist.cursor ? 'back' : 'forward'} to here`;
li.onclick = () => { closeMenus(); travel('goto', i); };
li.onkeydown = (ev) => {
if (ev.key === 'Enter') { closeMenus(); travel('goto', i); }
else if (ev.key === 'ArrowDown' && li.nextElementSibling) { ev.preventDefault(); (li.nextElementSibling.classList.contains('cursorline') ? li.nextElementSibling.nextElementSibling : li.nextElementSibling)?.focus(); }
else if (ev.key === 'ArrowUp' && li.previousElementSibling) { ev.preventDefault(); (li.previousElementSibling.classList.contains('cursorline') ? li.previousElementSibling.previousElementSibling : li.previousElementSibling)?.focus(); }
};
list.appendChild(li);
if (i === hist.cursor && i < hist.entries.length - 1) {
const c = document.createElement('li'); c.className = 'cursorline'; c.setAttribute('aria-hidden', 'true');
list.appendChild(c);
}
});
const mb = (hist.bytes || 0) / 1048576, cap = (hist.budget || 0) / 1048576;
$('tapefoot').textContent = 'Redo steps are kept until you make a new change.' +
(cap ? ` History uses ${mb < 10 ? mb.toFixed(1) : Math.round(mb)} of ${Math.round(cap)} MB.` : '');
}
let toastTimer = null;
function toast(text, action) {
const t = $('toast');
t.textContent = '';
const sp = document.createElement('span'); sp.textContent = text; t.appendChild(sp);
if (action) {
const b = document.createElement('button');
b.textContent = action.label + ' ';
const k = document.createElement('kbd'); k.textContent = keyLabel(action.key); b.appendChild(k);
b.onclick = () => travel(action.kind);
t.appendChild(b);
}
t.classList.add('show');
clearTimeout(toastTimer);
toastTimer = setTimeout(() => t.classList.remove('show'), 3500);
}
function flashBtn(id) { const b = $(id); b.classList.remove('flash'); void b.offsetWidth; b.classList.add('flash'); }
// kind: 'undo' | 'redo' | 'goto' (index). One at a time: presses that arrive
// while a restore is running are dropped, not queued, so a held or doubled ⌘Z
// can never run past where the user meant to stop. Also refused while an
// action's request is still in flight (its commit hasn't landed yet).
function travel(kind, index) {
if (!meshObject || histBusy) return Promise.resolve();
if (inFlight > 0) { setHud('Still working on the last action…'); return Promise.resolve(); }
return travelNow(kind, index);
}
async function travelNow(kind, index) {
if (kind === 'undo' && !hist.canUndo) return;
if (kind === 'redo' && !hist.canRedo) return;
if (kind === 'goto' && (index === hist.cursor || index < 0 || index >= hist.entries.length)) return;
const from = hist.cursor;
histBusy = true;
['b-undo', 'b-redo', 'b-hist'].forEach(id => { $(id).disabled = true; }); // visibly busy
try {
const j = await post('/api/history/' + kind, kind === 'goto' ? { index } : {});
if (!j.ok) { setHud((kind === 'undo' ? 'Undo' : kind === 'redo' ? 'Redo' : 'History') + ' failed: ' + (j.error || 'server')); return; }
const to = j.history.cursor;
// the step whose change was undone / redone, so its controls are in view
const touched = kind === 'undo' ? hist.entries[from] : j.history.entries[to];
await restoreDoc(j, touched ? STEP_NAMES.indexOf(touched.step) + 1 : 0);
setHistory(j.history);
if (kind === 'undo') {
flashBtn('b-undo');
toast(`Undid ${touched.label}`, { label: 'Redo', key: 'shift+mod+Z', kind: 'redo' });
} else if (kind === 'redo') {
flashBtn('b-redo');
toast(`Redid ${touched.label}`, { label: 'Undo', key: 'mod+Z', kind: 'undo' });
} else {
const n = Math.abs(to - from);
toast(`Went ${to < from ? 'back' : 'forward'} ${n} step${n === 1 ? '' : 's'} to ${touched.label}`);
}
} catch (err) {
console.error('[scan2cad] history travel failed:', err);
setHud('History failed: ' + err.message);
} finally {
histBusy = false;
setHistory(hist); // re-enable the arrows for whatever state we ended in
}
}
async function reloadCloudFromServer(n) {
if (cloudObj) { scene.remove(cloudObj); cloudObj.geometry.dispose(); cloudObj = null; }
if (!n) return;
const r = await fetch('/api/cloud/current');
if (!r.ok) return;
const geo = new THREE.BufferGeometry();
geo.setAttribute('position', new THREE.Float32BufferAttribute(new Float32Array(await r.arrayBuffer()), 3));
cloudObj = new THREE.Points(geo, new THREE.PointsMaterial({
color: 0x39c5cf, size: Math.max(modelScale * 0.0012, 0.05), sizeAttenuation: true,
transparent: true, opacity: 0.5 }));
scene.add(cloudObj);
}
async function surfacePreview(id) {
try {
const r = await fetch('/api/surface/preview?id=' + id);
const j = await r.json();
return j.ok ? j.preview : null;
} catch { return null; }
}
// Put the page back exactly as it was when snapshot `j` was committed, then
// show `focusStep` (the step the undone/redone change belongs to).
async function restoreDoc(j, focusStep) {
const ui = j.ui || {};
restoring = true;
try {
exitPreview(true);
disarm();
setHud(''); // status lines describe the state we're leaving
if (j.meshChanged) await reloadMeshFromServer();
meshStatus = null;
drawMeshHoleMarkers();
frameShift.fromArray(ui.frameShift || [0, 0, 0]);
if (j.cloudChanged || !!cloudObj !== j.ncloud > 0) await reloadCloudFromServer(j.ncloud);
$('meshinfo').innerHTML = ui.meshinfo ?? '';
$('cloudinfo').innerHTML = ui.cloudinfo ?? '';
$('decinfo').innerHTML = ui.decinfo ?? '';
$('surfinfo').innerHTML = ui.surfinfo ?? '';
setDocName(null, j.ntris);
// primitives: the server registry is the truth; checkbox / dev-map state is ours
prims.forEach(p => { if (p.gizmo) primGizmos.remove(p.gizmo); });
prims.length = 0;
const ext = ui.prims || {};
for (const sp of j.prims || []) {
const e = ext[sp.id] || {};
const p = { ...sp, checked: !!e.checked, devOn: e.devOn ?? true };
if (p.kind === 'surface') {
p.preview = await surfacePreview(p.id);
if (p.preview) { p.gizmo = drawSurfaceGizmo(p); colorSurfaceGizmo(p); }
} else {
p.gizmo = drawPrimGizmo(p);
}
prims.push(p);
}
selCount = j.nsel || 0;
drawSelection(j.selPreview);
refreshSelUI();
// surface datum
if (seatGizmo) { gizmos.remove(seatGizmo); seatGizmo = null; }
if (patchObj) { scene.remove(patchObj); patchObj = null; }
clearMarkers();
const st = ui.seat;
if (!st) {
clearSeat();
seatScanned = false;
} else {
seat = { origin: st.origin, normal: st.normal, u: st.u, v: st.v };
surfacePicks = st.picks || [];
lastSeatQuery = st.query || null;
seatScanned = !!st.scanned;
seatPatchId = st.patchId && blobCache.has(st.patchId) ? st.patchId : null;
const patch = seatPatchId ? blobCache.get(seatPatchId) : null;
drawSeatGizmo({ normal: seat.normal, origin: seat.origin, patch });
drawPatch(patch);
$('seatstat').textContent = st.stat || 'set';
$('seatstat').className = 'pill on';
$('seatinfo').innerHTML = st.info || '';
['parallelpick', 'refine', 'addcoplanar', 'seatredo'].forEach(id => { $(id).disabled = false; });
}
// holes
holes.forEach(h => { if (h.gizmo) gizmos.remove(h.gizmo); if (h.labelEl) h.labelEl.remove(); });
holes.length = 0;
if (bossPreview) { gizmos.remove(bossPreview); bossPreview = null; }
for (const d of ui.holes || []) makeHole(d);
nextId = ui.nextId || holes.length + 1;
selectedHole = holes.find(h => h.id === ui.selectedHole) || null;
renderHoles();
// legacy plate datum
if (datumGizmo) { gizmos.remove(datumGizmo); datumGizmo = null; }
datum = null;
if (ui.datum) {
const { info, ...d } = ui.datum;
datum = d;
drawDatum(d, Math.max(modelScale * 0.02, 3));
$('datumstat').textContent = 'set'; $('datumstat').className = 'pill on';
$('datuminfo').innerHTML = info || '';
} else {
$('datumstat').textContent = 'none'; $('datumstat').className = 'pill off';
$('datuminfo').textContent = 'Needed only for the plate rebuild.';
}
// alignment setup
const al = ui.align;
if (al) {
alignMode = al.mode;
$('alignmode').value = al.mode;
$('aligndelta').style.display = alignMode === 'points' ? 'none' : '';
al.slots.forEach((x, i) => Object.assign(alignSlots[i], { auto: false }, x));
clearFaces();
if (al.faces) Object.assign(alignFaces, JSON.parse(JSON.stringify(al.faces)));
Object.assign(align321, { ...al.a321, pts: al.a321.pts.slice(), normals: al.a321.normals.slice(),
values: al.a321.values.slice() });
['alignTx', 'alignTy', 'alignTz'].forEach((id, i) => { $(id).value = al.delta[i]; });
$('alignstat').textContent = al.stat; $('alignstat').className = al.statClass;
$('aligninfo').innerHTML = al.info;
}
alignFrame = null;
drawAlignGizmo(null);
$('alignapply').disabled = true; $('alignpreview').disabled = true;
drawAlign321Points();
renderPrims(); // also re-renders the alignment slots
const pendingAlign = alignMode === 'points' ? align321.pts.some(Boolean)
: alignMode === 'faces' ? faceCount() > 0 : alignSlots.some(x => x.id >= 0);
if (pendingAlign) await previewAlign();
refreshBuildEnabled();
const target = focusStep && canEnter(focusStep) ? focusStep
: ui.step && canEnter(ui.step) ? ui.step : 1;
setStep(target);
if (step === 3 && alignFrame) livePreview(); // faces / 3-2-1 keep showing the frame
drawDatumPlanes();
} finally {
restoring = false;
}
}
function setDocName(name, ntris) {
if (name) $('docfile').textContent = name;
const t = $('doctris');
if (ntris != null) { t.textContent = ntris.toLocaleString() + ' tris'; t.hidden = false; }
}
// ---------------------------------------------------------------- menu bar
const menus = [...document.querySelectorAll('#menubar .menu')];
function closeMenus() {
menus.forEach(m => { m.classList.remove('open'); m.querySelector('.mtop').setAttribute('aria-expanded', 'false'); });
$('tape').classList.remove('open');
$('b-hist').setAttribute('aria-expanded', 'false');
}
function refreshMenuState() {
document.querySelectorAll('#menubar [data-needs="mesh"]').forEach(b => { b.disabled = !meshObject; });
$('m-clearsel').disabled = !(step === 3 && selCount > 0);
$('m-delhole').disabled = !(selectedHole && !selectedHole.locked);
document.querySelector('[data-cmd="planes"]').classList.toggle('on', showPlanes);
if (!hist.canUndo) $('m-undo').disabled = true;
if (!hist.canRedo) $('m-redo').disabled = true;
}
function openMenu(m) {
closeMenus();
refreshMenuState();
m.classList.add('open');
m.querySelector('.mtop').setAttribute('aria-expanded', 'true');
}
menus.forEach(m => {
const top = m.querySelector('.mtop');
top.addEventListener('click', (e) => {
e.stopPropagation();
m.classList.contains('open') ? closeMenus() : openMenu(m);
});
// once a menu is open, hovering the others slides between them
top.addEventListener('mouseenter', () => {
if (menus.some(o => o !== m && o.classList.contains('open'))) openMenu(m);
});
});
function openTape() {
if (!hist.entries.length) return;
closeMenus();
const qa = $('qa').getBoundingClientRect(), bar = $('menubar').getBoundingClientRect();
const tape = $('tape');
tape.style.left = Math.max(0, Math.min(qa.left - bar.left, bar.width - 388)) + 'px';
tape.classList.add('open');
$('b-hist').setAttribute('aria-expanded', 'true');
const now = tape.querySelector('.ent.now');
if (now) { now.scrollIntoView({ block: 'nearest' }); now.focus(); }
}
$('b-hist').addEventListener('click', (e) => {
e.stopPropagation();
$('tape').classList.contains('open') ? closeMenus() : openTape();
});
$('tape').addEventListener('click', (e) => e.stopPropagation());
document.addEventListener('click', closeMenus);
$('b-undo').addEventListener('click', () => travel('undo'));
$('b-redo').addEventListener('click', () => travel('redo'));
function showKeys(on) { $('keyhelp').hidden = !on; if (on) $('khclose').focus(); }
$('khclose').addEventListener('click', () => showKeys(false));
$('keyhelp').addEventListener('click', (e) => { if (e.target.id === 'keyhelp') showKeys(false); });
document.querySelectorAll('[data-k]').forEach(el => { el.textContent = keyLabel(el.dataset.k); });
function runCommand(cmd) {
if (cmd.startsWith('view:')) { if (meshObject) setView(cmd.slice(5)); return; }
switch (cmd) {
case 'open': $('file').click(); break;
case 'cloud': $('cloudfile').click(); break;
case 'dlmesh': {
const a = document.createElement('a');
a.href = '/api/mesh/current'; a.download = 'scan2cad_mesh.stl';
document.body.appendChild(a); a.click(); a.remove();
break;
}
case 'export': setStep(6); break;
case 'undo': travel('undo'); break;
case 'redo': travel('redo'); break;
case 'history': setTimeout(openTape, 0); break;
case 'clearsel': if (step === 3 && selCount > 0) clearSelection(); break;
case 'delhole': deleteHole(selectedHole); break;
case 'fit': fitView(); break;
case 'planes': $('planestoggle').click(); break;
case 'keys': showKeys(true); break;
}
}
document.querySelectorAll('#menubar .mi').forEach(b => b.addEventListener('click', (e) => {
e.stopPropagation();
closeMenus();
runCommand(b.dataset.cmd);
}));
window.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
if (!$('keyhelp').hidden) { showKeys(false); return; }
if ($('tape').classList.contains('open') || menus.some(m => m.classList.contains('open'))) { closeMenus(); return; }
if (pick.armed) {
const what = pick.armed;
disarm();
setHud(what === 'pivot' ? 'Rotating around the center of the part.' : 'Pick cancelled.');
}
return;
}
if (typingInField(e)) return; // text fields keep their own native undo
const mod = isMac ? e.metaKey : e.ctrlKey;
const k = e.key.toLowerCase();
if (mod && e.altKey && e.code === 'KeyZ') { e.preventDefault(); openTape(); return; }
if (mod && e.code === 'KeyZ') { e.preventDefault(); travel(e.shiftKey ? 'redo' : 'undo'); return; }
if (mod && !isMac && k === 'y') { e.preventDefault(); travel('redo'); return; }
if (mod && k === 'o') { e.preventDefault(); $('file').click(); return; }
if (mod || e.altKey) return;
if (k === '?') { showKeys($('keyhelp').hidden); return; }
if (!meshObject) return;
const views = { 1: 'iso', 2: 'top', 3: 'front', 4: 'right' };
if (views[e.key]) setView(views[e.key]);
else if (k === 'p') $('planestoggle').click();
else if ((e.key === 'Backspace' || e.key === 'Delete') && step === 5 && selectedHole) {
e.preventDefault();
deleteHole(selectedHole);
}
});
// ---------------------------------------------------------------- gizmos
function v3(a) { return new THREE.Vector3(a[0], a[1], a[2]); }
function fmt(a) { return a.map(x => x.toFixed(3)).join(', '); }
async function pickDatum(p) {
setHud('Fitting datum plane…');
const vd = camera.getWorldDirection(new THREE.Vector3()).negate();
const j = await post('/api/fit_plane', {
point: [p.x, p.y, p.z], radius: 0, viewDir: [vd.x, vd.y, vd.z],
});
if (!j.ok) { setHud('Plane fit failed: ' + j.error); return; }
datum = { origin: j.origin, normal: j.normal, u: j.u, v: j.v };
drawDatum(j, Math.max(modelScale * 0.02, 3));
$('datumstat').textContent = 'set'; $('datumstat').className = 'pill on';
$('datuminfo').innerHTML = `n = (${fmt(j.normal)}) · rms ${j.rms.toFixed(3)} mm · ${j.npts} pts`;
setHud('Datum set.');
refreshBuildEnabled();
await commit('Pick datum face');
}
$('datumpick').addEventListener('click', () => {
if (!meshObject) return;
disarm();
pick.armed = 'datum';
$('datumpick').classList.add('armed');
setHud('Click the flat mounting face.');
});
function drawDatum(j, radius) {
if (datumGizmo) gizmos.remove(datumGizmo);
const g = new THREE.Group();
const disk = new THREE.Mesh(
new THREE.CircleGeometry(radius, 48),
new THREE.MeshBasicMaterial({ color: 0x2f81f7, transparent: true, opacity: 0.28, side: THREE.DoubleSide }));
const q = new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 0, 1), v3(j.normal));
disk.quaternion.copy(q); disk.position.copy(v3(j.origin));
g.add(disk);
g.add(new THREE.ArrowHelper(v3(j.normal), v3(j.origin), radius * 0.9, 0x2f81f7, radius * 0.25, radius * 0.14));
datumGizmo = g; gizmos.add(g);
}
// The hole gizmo is a *barrel*: it runs the bore's depth AND sticks out above the
// opening, so the fitted cylinder is obvious against the surface. A bright ring
// marks exactly where the bore pierces the seat surface; a thin rim outlines the
// protruding top. Locked holes render green and more solid.
function drawHoleGizmo(j, color, locked) {
const p1 = v3(j.p1), p2 = v3(j.p2); // p2 = outer opening (on the surface)
const axis = v3(j.axis).normalize();
const r = j.diameter / 2;
const depth = Math.max(p1.distanceTo(p2), j.diameter * 0.6);
const stick = Math.max(j.diameter * 0.7, 3); // protrusion above the surface
const top = p2.clone().add(axis.clone().multiplyScalar(stick));
const bottom = p2.clone().sub(axis.clone().multiplyScalar(depth));
const len = depth + stick;
const mid = bottom.clone().add(top).multiplyScalar(0.5);
const ringColor = locked ? 0x43c06a : PINK;
const q = new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 1, 0), axis);
const g = new THREE.Group();
const cyl = new THREE.Mesh(
new THREE.CylinderGeometry(r, r, len, 32, 1, true),
new THREE.MeshBasicMaterial({ color, transparent: true,
opacity: locked ? 0.7 : 0.45, side: THREE.DoubleSide }));
cyl.quaternion.copy(q); cyl.position.copy(mid);
g.add(cyl);
// ring at the surface intersection (the opening), snug on the bore
const ring = new THREE.Mesh(
new THREE.TorusGeometry(r * 1.12, Math.max(r * 0.14, 0.3), 12, 48),
new THREE.MeshBasicMaterial({ color: ringColor }));
ring.quaternion.copy(new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 0, 1), axis));
ring.position.copy(p2);
g.add(ring);
// thin rim at the protruding top so the barrel reads in 3D
const rim = new THREE.Mesh(
new THREE.TorusGeometry(r, Math.max(r * 0.07, 0.15), 10, 40),
new THREE.MeshBasicMaterial({ color }));
rim.quaternion.copy(ring.quaternion);
rim.position.copy(top);
g.add(rim);
gizmos.add(g);
return g;
}
// Preview the mount bosses exactly as the export resolved them (seat, direction,
// size), so a wrong-way boss is visible before the STEP ever reaches SolidWorks.
function drawBossPreview(mounts) {
if (bossPreview) gizmos.remove(bossPreview);
bossPreview = new THREE.Group();
mounts.forEach((m, i) => {
const seat = v3(m.seat), axis = v3(m.axis).normalize();
const r = m.bossDiameter / 2, hgt = m.bossHeight;
const color = holes[i] ? holes[i].color : 0xd29922;
const cyl = new THREE.Mesh(
new THREE.CylinderGeometry(r, r, hgt, 32),
new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0.5 }));
cyl.quaternion.copy(new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 1, 0), axis));
cyl.position.copy(seat.clone().add(axis.clone().multiplyScalar(hgt / 2)));
bossPreview.add(cyl);
bossPreview.add(new THREE.ArrowHelper(axis, seat, hgt * 1.6, color, hgt * 0.4, r * 0.5));
});
gizmos.add(bossPreview);
}
// ---------------------------------------------------------------- holes UI
function addHole(j) {
const id = nextId++;
makeHole({
id, center: j.center, axis: j.axis, diameterFit: j.diameter,
measured: null, thread: '', through: true, depth: j.depth,
p1: j.p1, p2: j.p2, locked: false, bossDir: 0,
color: PALETTE[(id - 1) % PALETTE.length],
});
renderHoles();
}
// Build a hole (gizmo + floating label) from its plain data — new or restored.
function makeHole(d) {
const h = { ...d };
h.gizmo = drawHoleGizmo({ p1: h.p1, p2: h.p2, axis: h.axis, diameter: effectiveDiameter(h) },
h.color, h.locked);
const lab = document.createElement('div');
lab.className = 'holelabel' + (h.locked ? ' locked' : '');
lab.style.borderColor = '#' + h.color.toString(16).padStart(6, '0');
lab.onclick = () => { selectHole(h); flyToHole(h); };
viewport.appendChild(lab);
h.labelEl = lab;
holes.push(h);
return h;
}
function removeHole(h) {
if (h.gizmo) gizmos.remove(h.gizmo);
if (h.labelEl) h.labelEl.remove();
if (bossPreview) { gizmos.remove(bossPreview); bossPreview = null; } // stale after edits
const i = holes.indexOf(h);
if (i >= 0) holes.splice(i, 1);
if (selectedHole === h) selectedHole = null;
renderHoles();
refreshBuildEnabled();
}
// User-initiated delete (card ✕, ⌫): one history step.
function deleteHole(h) {
if (!h || h.locked) return;
const n = holes.indexOf(h) + 1;
removeHole(h);
commit(`Remove hole ${n}`);
}
function effectiveDiameter(h) { return h.measured != null ? h.measured : h.diameterFit; }
function renderHoles() {
$('holecount').textContent = holes.length;
const wrap = $('holes'); wrap.innerHTML = '';
holes.forEach((h, i) => {
if (h.labelEl) { h.labelEl.textContent = i + 1; h.labelEl.classList.toggle('sel', h === selectedHole); }
const el = document.createElement('div');
el.className = 'hole' + (h === selectedHole ? ' active' : '') + (h.locked ? ' locked' : '');
el.dataset.id = h.id;
const dis = h.locked ? 'disabled' : '';
const threadOpts = ['', ...Object.keys(THREADS)]
.map(t => ``).join('');
const [x, y, z] = h.center;
let spacing = '';
if (h === selectedHole && holes.length > 1) {
const others = holes.filter(o => o !== h)
.map(o => `#${holes.indexOf(o) + 1}: ${v3(h.center).distanceTo(v3(o.center)).toFixed(2)}`);
spacing = `