Files
vibemake/js/assembly-head.js

52 lines
2.2 KiB
JavaScript

import { Box3, Vector3 } from '../vendor/three/build/three.module.min.js';
const dims = ['x','y','z'];
const screw = /(?:^|[-_ ])(?:STP39(?:$|[.\-_ ])|BTS2(?:$|[.\-_ ]))|螺钉|螺丝|screw|bolt/i;
export const isAssemblyFastener = name => screw.test(name);
// Test both end bands, in the actual mesh-local coordinates. Reject ambiguous
// heads rather than choosing a side based on the robot's center or filename.
export function screwHead(local) {
const points = local.getAttribute('position');
local.computeBoundingBox();
const { min, max } = local.boundingBox;
const size = max.clone().sub(min);
const plausible = [];
for (const k of dims) {
const [u,v] = dims.filter(d => d !== k);
if (size[k] < Math.max(size[u],size[v]) * 0.8 || Math.min(size[u],size[v]) < Math.max(size[u],size[v]) * 0.88) continue;
const bands = [new Box3(),new Box3()];
const p = new Vector3();
for (let i = 0; i < points.count; i++) {
p.fromBufferAttribute(points,i);
if (p[k] <= min[k] + size[k] * 0.12) bands[0].expandByPoint(p);
if (p[k] >= max[k] - size[k] * 0.12) bands[1].expandByPoint(p);
}
const widths = bands.map(b => b.getSize(new Vector3()));
const [a,b] = widths.map(w => Math.sqrt(w[u]*w[v]));
const ratio = Math.max(a,b) / Math.min(a,b);
if (ratio >= 1.18 && Number.isFinite(ratio)) plausible.push({ k, sign: a>b?-1:1, ratio });
}
if (plausible.length !== 1) return null;
const {k,sign,ratio} = plausible[0];
return {vector: new Vector3().setComponent(dims.indexOf(k),sign), widthRatio:ratio};
}
// Legacy JSON lacks head metadata. Inspect a named fastener once, without
// cloning geometry or changing its pose/material. Ambiguous shapes stay null.
export function inferScrewHeadDirection(template) {
template.updateWorldMatrix(true, true);
const directions = [];
let ambiguous = false;
template.traverse(object => {
if (!object.isMesh) return;
const head = screwHead(object.geometry);
if (!head) { ambiguous = true; return; }
directions.push(head.vector.transformDirection(object.matrixWorld));
});
if (ambiguous || !directions.length || directions.some(v => v.dot(directions[0]) < .99)) return null;
return directions[0];
}