Download studio.js from Chao-Yun/I-DevNet: direct link, hf CLI and curl.
- Browser
- Download file 104 kB
-
https://huggingface.co/spaces/Chao-Yun/I-DevNet/resolve/main/studio.js
- Command line
-
hf download hf://spaces/Chao-Yun/I-DevNet/studio.js
-
curl -L -o studio.js https://huggingface.co/spaces/Chao-Yun/I-DevNet/resolve/main/studio.js
104 kB
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.js";
const DEFAULT_CONFIG = {
assetsBase: "./assets/studio",
modelsBase: "./assets/models",
fallbackModelsBase: "https://huggingface.co/Chao-Yun/I-DevNet/resolve/main",
hasLocalBackend: false,
};
function getConfig() {
return { ...DEFAULT_CONFIG, ...(window.IDEVNET_STUDIO_CONFIG || {}) };
}
/* ---------- sRGB <-> Linear Conversion & Paper-Calibrated Colormaps ---------- */
function srgbToLinear(c) {
const x = Math.max(0, Math.min(1, c));
return x <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
}
function hexToLinearRGB(hex) {
let num = typeof hex === "number" ? hex : parseInt(String(hex).replace(/^#/, ""), 16);
const r = ((num >> 16) & 255) / 255.0;
const g = ((num >> 8) & 255) / 255.0;
const b = (num & 255) / 255.0;
return [srgbToLinear(r), srgbToLinear(g), srgbToLinear(b)];
}
function mixSrgbToLinear(c0, c1, t) {
const u = Math.max(0, Math.min(1, t));
return [
srgbToLinear(c0[0] + (c1[0] - c0[0]) * u),
srgbToLinear(c0[1] + (c1[1] - c0[1]) * u),
srgbToLinear(c0[2] + (c1[2] - c0[2]) * u),
];
}
const PATCH_PALETTE_HEX = [
"#5B8EC4",
"#6BB8A8",
"#C48ED4",
"#D8C85E",
"#96B83C",
"#E29B63",
"#DF6B55",
"#7DA3DF",
"#9CC27B",
"#A37286",
"#5FA7C4",
"#D48872",
];
const PATCH_PALETTE_LINEAR = PATCH_PALETTE_HEX.map(hexToLinearRGB);
const STEEL_LINEAR = hexToLinearRGB("#5F86B3");
const CLAY_LINEAR = hexToLinearRGB("#DCD9D2");
function computeAdaptiveMaxK(signedK, interiorMask, minVal = 0.006, maxVal = 0.06) {
if (!signedK || signedK.length === 0) return minVal;
const mags = [];
for (let i = 0; i < signedK.length; i++) {
if (!interiorMask || interiorMask[i] > 0) {
const a = Math.abs(signedK[i]);
if (Number.isFinite(a)) mags.push(a);
}
}
if (mags.length === 0) {
for (let i = 0; i < signedK.length; i++) {
const a = Math.abs(signedK[i]);
if (Number.isFinite(a)) mags.push(a);
}
}
if (mags.length === 0) return minVal;
mags.sort((a, b) => a - b);
const idx = Math.min(mags.length - 1, Math.floor(mags.length * 0.92));
return Math.max(minVal, Math.min(maxVal, mags[idx] || minVal));
}
function bwrCurvatureRGB(signedK, maxK = 0.02) {
// #1d56a8 (Saddle K<0) -> #e6e2da (Zero K~0) -> #cc362f (Dome K>0)
const mag = Math.min(1.0, Math.pow(Math.min(1.0, Math.abs(signedK) / Math.max(maxK, 1e-6)), 0.58));
const zero = [0.902, 0.886, 0.855];
if (signedK < 0) {
return mixSrgbToLinear(zero, [0.114, 0.337, 0.659], mag);
}
return mixSrgbToLinear(zero, [0.800, 0.212, 0.184], mag);
}
function hausdorffColorRGB(pct, maxPct = 1.4) {
// Paper Fig. 22-24 scale: #e2dfda (0%) -> #ef7a6d (45%) -> #d62424 (100%)
const t = Math.pow(Math.min(1.0, Math.max(0.0, pct) / Math.max(maxPct, 1e-4)), 0.68);
const c0 = [0.886, 0.875, 0.855];
const c1 = [0.937, 0.478, 0.427];
const c2 = [0.839, 0.141, 0.141];
if (t < 0.45) {
return mixSrgbToLinear(c0, c1, t / 0.45);
}
return mixSrgbToLinear(c1, c2, (t - 0.45) / 0.55);
}
function createZebraMaterial() {
return new THREE.ShaderMaterial({
side: THREE.DoubleSide,
polygonOffset: true,
polygonOffsetFactor: 1,
polygonOffsetUnits: 1,
uniforms: {
uLightDir: { value: new THREE.Vector3(0.42, 0.72, 0.55).normalize() },
uStripeAxis: { value: new THREE.Vector3(0.38, 0.76, 0.52).normalize() },
},
vertexShader: `
varying vec3 vViewNormal;
void main() {
vViewNormal = normalize(normalMatrix * normal);
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
uniform vec3 uLightDir;
uniform vec3 uStripeAxis;
varying vec3 vViewNormal;
void main() {
vec3 n = normalize(vViewNormal);
if (!gl_FrontFacing) n = -n;
float proj = dot(n, normalize(uStripeAxis));
float wave = sin(proj * 38.0);
float band = smoothstep(-0.18, 0.18, wave);
float diff = 0.56 + 0.44 * max(dot(n, normalize(uLightDir)), 0.0);
vec3 darkBand = vec3(0.045, 0.095, 0.195);
vec3 lightBand = vec3(0.76, 0.80, 0.86);
vec3 col = mix(darkBand, lightBand, band) * diff;
gl_FragColor = vec4(col, 1.0);
}
`,
});
}
function seededNoise(idx, seed) {
let x = (idx + 1) * 374761393 + (seed + 1) * 668265263;
x = (x ^ (x >> 13)) * 1274126177;
x = x ^ (x >> 16);
return (x & 0x7fffffff) / 0x3fffffff - 1.0;
}
function computeSignedGaussianCurvature(verts, faces, interiorMask) {
const nVerts = verts.length / 3;
const angleSums = new Float64Array(nVerts);
const nFaces = faces.length / 3;
const cornerAngle = (ax, ay, az, bx, by, bz, cx, cy, cz) => {
const ux = bx - ax, uy = by - ay, uz = bz - az;
const wx = cx - ax, wy = cy - ay, wz = cz - az;
const nu = Math.hypot(ux, uy, uz);
const nw = Math.hypot(wx, wy, wz);
const denom = Math.max(nu * nw, 1e-12);
const cosA = Math.min(1.0, Math.max(-1.0, (ux * wx + uy * wy + uz * wz) / denom));
return Math.acos(cosA);
};
for (let f = 0; f < nFaces; f++) {
const i0 = faces[f * 3], i1 = faces[f * 3 + 1], i2 = faces[f * 3 + 2];
const x0 = verts[i0 * 3], y0 = verts[i0 * 3 + 1], z0 = verts[i0 * 3 + 2];
const x1 = verts[i1 * 3], y1 = verts[i1 * 3 + 1], z1 = verts[i1 * 3 + 2];
const x2 = verts[i2 * 3], y2 = verts[i2 * 3 + 1], z2 = verts[i2 * 3 + 2];
angleSums[i0] += cornerAngle(x0, y0, z0, x1, y1, z1, x2, y2, z2);
angleSums[i1] += cornerAngle(x1, y1, z1, x2, y2, z2, x0, y0, z0);
angleSums[i2] += cornerAngle(x2, y2, z2, x0, y0, z0, x1, y1, z1);
}
const signedK = new Float64Array(nVerts);
let sumK = 0.0;
let maxK = 0.0;
let interiorCount = 0;
for (let v = 0; v < nVerts; v++) {
if (!interiorMask || interiorMask[v]) {
const d = 2.0 * Math.PI - angleSums[v];
signedK[v] = d;
const ad = Math.abs(d);
sumK += ad;
if (ad > maxK) maxK = ad;
interiorCount++;
}
}
return {
signedK,
kMean: interiorCount > 0 ? sumK / interiorCount : 0.0,
kMax: maxK,
};
}
function computeMeanVertexShiftPct(vertsA, vertsB) {
const n = Math.min(vertsA.length, vertsB.length) / 3;
if (n <= 0) return 0.0;
let minX = Infinity, minY = Infinity, minZ = Infinity;
let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;
let sumD = 0.0;
for (let i = 0; i < n; i++) {
const ax = vertsA[i * 3], ay = vertsA[i * 3 + 1], az = vertsA[i * 3 + 2];
if (ax < minX) minX = ax; if (ax > maxX) maxX = ax;
if (ay < minY) minY = ay; if (ay > maxY) maxY = ay;
if (az < minZ) minZ = az; if (az > maxZ) maxZ = az;
sumD += Math.hypot(vertsB[i * 3] - ax, vertsB[i * 3 + 1] - ay, vertsB[i * 3 + 2] - az);
}
const diag = Math.max(Math.hypot(maxX - minX, maxY - minY, maxZ - minZ), 1e-8);
return (sumD / n / diag) * 100.0;
}
function downloadObjText(filename, verts, faces) {
const nVerts = verts.length / 3;
const nFaces = faces.length / 3;
const lines = ["# Exported from I-DevNet Interactive 3D Studio"];
for (let i = 0; i < nVerts; i++) {
lines.push(`v ${verts[i * 3].toFixed(6)} ${verts[i * 3 + 1].toFixed(6)} ${verts[i * 3 + 2].toFixed(6)}`);
}
for (let f = 0; f < nFaces; f++) {
lines.push(`f ${faces[f * 3] + 1} ${faces[f * 3 + 1] + 1} ${faces[f * 3 + 2] + 1}`);
}
const blob = new Blob([lines.join("\n")], { type: "text/plain;charset=utf-8" });
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = filename;
a.click();
URL.revokeObjectURL(a.href);
}
let _cachedShadowTex = null;
function getSoftShadowTexture() {
if (_cachedShadowTex) return _cachedShadowTex;
const c = document.createElement("canvas");
c.width = 128;
c.height = 128;
const ctx = c.getContext("2d");
const g = ctx.createRadialGradient(64, 64, 6, 64, 64, 62);
g.addColorStop(0, "rgba(18, 23, 34, 0.24)");
g.addColorStop(0.52, "rgba(18, 23, 34, 0.08)");
g.addColorStop(1, "rgba(18, 23, 34, 0.0)");
ctx.fillStyle = g;
ctx.fillRect(0, 0, 128, 128);
_cachedShadowTex = new THREE.CanvasTexture(c);
return _cachedShadowTex;
}
/* ---------- 3x3 Symmetric Jacobi PCA & 3D FFD Lattice Control Cage ---------- */
function computePCAFrame(verts) {
const n = Math.floor(verts.length / 3);
if (n === 0) {
return {
center: [0, 0, 0],
eU: [1, 0, 0],
eV: [0, 1, 0],
eW: [0, 0, 1],
};
}
let cx = 0, cy = 0, cz = 0;
for (let i = 0; i < n; i++) {
cx += verts[i * 3];
cy += verts[i * 3 + 1];
cz += verts[i * 3 + 2];
}
cx /= n; cy /= n; cz /= n;
// Symmetric 3x3 covariance matrix A
const A = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
];
for (let i = 0; i < n; i++) {
const dx = verts[i * 3] - cx;
const dy = verts[i * 3 + 1] - cy;
const dz = verts[i * 3 + 2] - cz;
A[0][0] += dx * dx; A[0][1] += dx * dy; A[0][2] += dx * dz;
A[1][1] += dy * dy; A[1][2] += dy * dz; A[2][2] += dz * dz;
}
A[1][0] = A[0][1];
A[2][0] = A[0][2];
A[2][1] = A[1][2];
const V = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
];
// Classic Jacobi eigenvalue solver for 3x3 symmetric covariance
for (let iter = 0; iter < 24; iter++) {
let p = 0, q = 1;
let maxOff = Math.abs(A[0][1]);
if (Math.abs(A[0][2]) > maxOff) { p = 0; q = 2; maxOff = Math.abs(A[0][2]); }
if (Math.abs(A[1][2]) > maxOff) { p = 1; q = 2; maxOff = Math.abs(A[1][2]); }
if (maxOff < 1e-12) break;
const app = A[p][p], aqq = A[q][q], apq = A[p][q];
const tau = (aqq - app) / (2.0 * apq);
const t = tau >= 0 ? 1.0 / (tau + Math.sqrt(1.0 + tau * tau)) : -1.0 / (-tau + Math.sqrt(1.0 + tau * tau));
const c = 1.0 / Math.sqrt(1.0 + t * t);
const s = t * c;
A[p][p] = app - t * apq;
A[q][q] = aqq + t * apq;
A[p][q] = 0.0;
A[q][p] = 0.0;
for (let r = 0; r < 3; r++) {
if (r !== p && r !== q) {
const arp = A[r][p], arq = A[r][q];
A[r][p] = c * arp - s * arq;
A[p][r] = A[r][p];
A[r][q] = s * arp + c * arq;
A[q][r] = A[r][q];
}
}
for (let r = 0; r < 3; r++) {
const vrp = V[r][p], vrq = V[r][q];
V[r][p] = c * vrp - s * vrq;
V[r][q] = s * vrp + c * vrq;
}
}
const cols = [0, 1, 2].map((col) => ({
val: A[col][col],
vec: [V[0][col], V[1][col], V[2][col]],
}));
cols.sort((a, b) => b.val - a.val);
const norm3 = (v) => {
const l = Math.hypot(v[0], v[1], v[2]) || 1.0;
return [v[0] / l, v[1] / l, v[2] / l];
};
const cross3 = (a, b) => [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
];
let eU = norm3(cols[0].vec);
let eV = norm3(cols[1].vec);
let eW = norm3(cross3(eU, eV));
eV = norm3(cross3(eW, eU));
if (eW[1] < -0.15) {
eW = [-eW[0], -eW[1], -eW[2]];
eV = [-eV[0], -eV[1], -eV[2]];
}
return { center: [cx, cy, cz], eU, eV, eW };
}
function bernsteinBasis(nCount, t) {
const u = Math.max(0.0, Math.min(1.0, t));
if (nCount === 2) {
return [1.0 - u, u];
}
const omt = 1.0 - u;
return [omt * omt, 2.0 * u * omt, u * u];
}
class LatticeCage {
constructor(verts, nu = 2, nv = 2, nw = 2) {
this.nu = nu;
this.nv = nv;
this.nw = nw;
this.nVerts = Math.floor(verts.length / 3);
this.origVerts = new Float64Array(verts);
const { center, eU, eV, eW } = computePCAFrame(verts);
this.center = center;
this.eU = eU;
this.eV = eV;
this.eW = eW;
let uMin = Infinity, uMax = -Infinity;
let vMin = Infinity, vMax = -Infinity;
let wMin = Infinity, wMax = -Infinity;
const uvwProj = new Float64Array(this.nVerts * 3);
for (let i = 0; i < this.nVerts; i++) {
const dx = verts[i * 3] - center[0];
const dy = verts[i * 3 + 1] - center[1];
const dz = verts[i * 3 + 2] - center[2];
const pu = dx * eU[0] + dy * eU[1] + dz * eU[2];
const pv = dx * eV[0] + dy * eV[1] + dz * eV[2];
const pw = dx * eW[0] + dy * eW[1] + dz * eW[2];
uvwProj[i * 3] = pu;
uvwProj[i * 3 + 1] = pv;
uvwProj[i * 3 + 2] = pw;
if (pu < uMin) uMin = pu; if (pu > uMax) uMax = pu;
if (pv < vMin) vMin = pv; if (pv > vMax) vMax = pv;
if (pw < wMin) wMin = pw; if (pw > wMax) wMax = pw;
}
const spanU = Math.max(uMax - uMin, 1e-4);
const spanV = Math.max(vMax - vMin, 1e-4);
const spanW = Math.max(wMax - wMin, 0.0);
const maxSpan = Math.max(spanU, spanV, spanW, 0.25);
const pad = 0.08 * maxSpan;
const thickW = Math.max(spanW + 2.0 * pad, 0.36 * maxSpan);
const wMid = 0.5 * (wMin + wMax);
this.boxMin = [uMin - pad, vMin - pad, wMid - 0.5 * thickW];
this.boxMax = [uMax + pad, vMax + pad, wMid + 0.5 * thickW];
this.boxSpan = [
Math.max(this.boxMax[0] - this.boxMin[0], 1e-5),
Math.max(this.boxMax[1] - this.boxMin[1], 1e-5),
Math.max(this.boxMax[2] - this.boxMin[2], 1e-5),
];
this.uvw = new Float64Array(this.nVerts * 3);
this.bu = new Float64Array(this.nVerts * nu);
this.bv = new Float64Array(this.nVerts * nv);
this.bw = new Float64Array(this.nVerts * nw);
for (let v = 0; v < this.nVerts; v++) {
const tu = Math.max(0.0, Math.min(1.0, (uvwProj[v * 3] - this.boxMin[0]) / this.boxSpan[0]));
const tv = Math.max(0.0, Math.min(1.0, (uvwProj[v * 3 + 1] - this.boxMin[1]) / this.boxSpan[1]));
const tw = Math.max(0.0, Math.min(1.0, (uvwProj[v * 3 + 2] - this.boxMin[2]) / this.boxSpan[2]));
this.uvw[v * 3] = tu;
this.uvw[v * 3 + 1] = tv;
this.uvw[v * 3 + 2] = tw;
const Bu = bernsteinBasis(nu, tu);
const Bv = bernsteinBasis(nv, tv);
const Bw = bernsteinBasis(nw, tw);
for (let i = 0; i < nu; i++) this.bu[v * nu + i] = Bu[i];
for (let j = 0; j < nv; j++) this.bv[v * nv + j] = Bv[j];
for (let k = 0; k < nw; k++) this.bw[v * nw + k] = Bw[k];
}
this.nNodes = nu * nv * nw;
this.nodeParams = [];
this.restNodes = new Float64Array(this.nNodes * 3);
this.userOffsets = [];
for (let i = 0; i < nu; i++) {
const su = nu > 1 ? i / (nu - 1) : 0.5;
const pu = this.boxMin[0] + su * this.boxSpan[0];
for (let j = 0; j < nv; j++) {
const sv = nv > 1 ? j / (nv - 1) : 0.5;
const pv = this.boxMin[1] + sv * this.boxSpan[1];
for (let k = 0; k < nw; k++) {
const sw = nw > 1 ? k / (nw - 1) : 0.5;
const pw = this.boxMin[2] + sw * this.boxSpan[2];
const idx = this.nodeIndex(i, j, k);
this.nodeParams[idx] = [su, sv, sw, i, j, k];
this.restNodes[idx * 3] = center[0] + pu * eU[0] + pv * eV[0] + pw * eW[0];
this.restNodes[idx * 3 + 1] = center[1] + pu * eU[1] + pv * eV[1] + pw * eW[1];
this.restNodes[idx * 3 + 2] = center[2] + pu * eU[2] + pv * eV[2] + pw * eW[2];
this.userOffsets[idx] = [0.0, 0.0, 0.0];
}
}
}
// Build grid edges & corner u-bars
this.edges = [];
this.adjacentNodes = Array.from({ length: this.nNodes }, () => []);
for (let i = 0; i < nu; i++) {
for (let j = 0; j < nv; j++) {
for (let k = 0; k < nw; k++) {
const a = this.nodeIndex(i, j, k);
if (i + 1 < nu) {
const b = this.nodeIndex(i + 1, j, k);
this.edges.push([a, b, "u", i, j, k]);
this.adjacentNodes[a].push(b);
this.adjacentNodes[b].push(a);
}
if (j + 1 < nv) {
const b = this.nodeIndex(i, j + 1, k);
this.edges.push([a, b, "v", i, j, k]);
this.adjacentNodes[a].push(b);
this.adjacentNodes[b].push(a);
}
if (k + 1 < nw) {
const b = this.nodeIndex(i, j, k + 1);
this.edges.push([a, b, "w", i, j, k]);
this.adjacentNodes[a].push(b);
this.adjacentNodes[b].push(a);
}
}
}
}
}
nodeIndex(i, j, k) {
return (i * this.nv + j) * this.nw + k;
}
resetOffsets() {
for (let idx = 0; idx < this.nNodes; idx++) {
this.userOffsets[idx] = [0.0, 0.0, 0.0];
}
}
getNodeBaseAndFinal(idx, params) {
const [su, sv, _sw, i] = this.nodeParams[idx];
const rx = this.restNodes[idx * 3] - this.center[0];
const ry = this.restNodes[idx * 3 + 1] - this.center[1];
const rz = this.restNodes[idx * 3 + 2] - this.center[2];
const du = rx * this.eU[0] + ry * this.eU[1] + rz * this.eU[2];
let dv = rx * this.eV[0] + ry * this.eV[1] + rz * this.eV[2];
let dw = rx * this.eW[0] + ry * this.eW[1] + rz * this.eW[2];
if (params.twist !== 0) {
const ang = params.twist * 0.55 * (2.0 * su - 1.0);
const ca = Math.cos(ang), sa = Math.sin(ang);
const ndv = dv * ca - dw * sa;
const ndw = dv * sa + dw * ca;
dv = ndv;
dw = ndw;
}
if (params.saddle !== 0) {
dw += params.saddle * 0.34 * (2.0 * su - 1.0) * (2.0 * sv - 1.0);
}
if (this.nu === 3 && params.bend !== 0) {
dw += i === 1 ? params.bend * 0.36 : -params.bend * 0.14;
}
const bx = this.center[0] + du * this.eU[0] + dv * this.eV[0] + dw * this.eW[0];
const by = this.center[1] + du * this.eU[1] + dv * this.eV[1] + dw * this.eW[1];
const bz = this.center[2] + du * this.eU[2] + dv * this.eV[2] + dw * this.eW[2];
const off = this.userOffsets[idx];
return {
base: [bx, by, bz],
pos: [bx + off[0], by + off[1], bz + off[2]],
};
}
computeDeformedNodes(params) {
const out = new Float64Array(this.nNodes * 3);
for (let idx = 0; idx < this.nNodes; idx++) {
const { pos } = this.getNodeBaseAndFinal(idx, params);
out[idx * 3] = pos[0];
out[idx * 3 + 1] = pos[1];
out[idx * 3 + 2] = pos[2];
}
return out;
}
deformVertices(nodes, params) {
const out = new Float64Array(this.nVerts * 3);
const { nu, nv, nw } = this;
const hasArch = nu === 2 && Math.abs(params.bend) > 1e-6;
const noiseAmp = params.noise > 0 ? (params.noise / 100.0) * 0.35 : 0.0;
const eWx = this.eW[0], eWy = this.eW[1], eWz = this.eW[2];
for (let v = 0; v < this.nVerts; v++) {
let x = 0.0, y = 0.0, z = 0.0;
const uOff = v * nu;
const vOff = v * nv;
const wOff = v * nw;
for (let i = 0; i < nu; i++) {
const bui = this.bu[uOff + i];
for (let j = 0; j < nv; j++) {
const buv = bui * this.bv[vOff + j];
for (let k = 0; k < nw; k++) {
const w = buv * this.bw[wOff + k];
const nIdx = ((i * nv + j) * nw + k) * 3;
x += w * nodes[nIdx];
y += w * nodes[nIdx + 1];
z += w * nodes[nIdx + 2];
}
}
}
if (hasArch) {
const u = this.uvw[v * 3];
const s = 2.0 * u - 1.0;
const arch = params.bend * 0.30 * (1.0 - s * s);
x += arch * eWx;
y += arch * eWy;
z += arch * eWz;
}
if (noiseAmp > 0) {
x += 0.35 * noiseAmp * seededNoise(v, 19);
y += 0.35 * noiseAmp * seededNoise(v, 31);
z += noiseAmp * seededNoise(v, 7);
}
out[v * 3] = x;
out[v * 3 + 1] = y;
out[v * 3 + 2] = z;
}
return out;
}
getWireframeEdgeSegments(nodes, params, highlightNode = -1) {
const basePos = [];
const hiPos = [];
const bendArch = this.nu === 2 && Math.abs(params.bend) > 1e-6 ? params.bend * 0.30 : 0.0;
for (const [a, b, axis] of this.edges) {
const isHi = highlightNode >= 0 && (a === highlightNode || b === highlightNode);
const target = isHi ? hiPos : basePos;
const ax = nodes[a * 3], ay = nodes[a * 3 + 1], az = nodes[a * 3 + 2];
const bx = nodes[b * 3], by = nodes[b * 3 + 1], bz = nodes[b * 3 + 2];
if (axis === "u" && Math.abs(bendArch) > 1e-6) {
const segs = 10;
let px = ax, py = ay, pz = az;
for (let s = 1; s <= segs; s++) {
const t = s / segs;
const arch = bendArch * (1.0 - (2.0 * t - 1.0) ** 2);
const nx = ax + (bx - ax) * t + arch * this.eW[0];
const ny = ay + (by - ay) * t + arch * this.eW[1];
const nz = az + (bz - az) * t + arch * this.eW[2];
target.push(px, py, pz, nx, ny, nz);
px = nx; py = ny; pz = nz;
}
} else {
target.push(ax, ay, az, bx, by, bz);
}
}
const movedRays = [];
for (let idx = 0; idx < this.nNodes; idx++) {
const ox = this.restNodes[idx * 3], oy = this.restNodes[idx * 3 + 1], oz = this.restNodes[idx * 3 + 2];
const nx = nodes[idx * 3], ny = nodes[idx * 3 + 1], nz = nodes[idx * 3 + 2];
if (Math.hypot(nx - ox, ny - oy, nz - oz) > 0.015) {
movedRays.push(ox, oy, oz, nx, ny, nz);
}
}
return {
basePos: new Float32Array(basePos),
hiPos: new Float32Array(hiPos),
movedRays: new Float32Array(movedRays),
};
}
}
/* ---------- Custom OBJ Parser + Fast Planar UVGridMapping ---------- */
function parseCustomObjToPatch(text, fileName) {
const rawVerts = [];
const faces = [];
const lines = text.split(/\r?\n/);
for (const line of lines) {
const s = line.trim();
if (!s || s.startsWith("#")) continue;
const parts = s.split(/\s+/);
if (parts[0] === "v" && parts.length >= 4) {
rawVerts.push(parseFloat(parts[1]), parseFloat(parts[2]), parseFloat(parts[3]));
} else if (parts[0] === "f" && parts.length >= 4) {
const idx = parts.slice(1).map((tok) => {
const vi = parseInt(tok.split("/")[0], 10);
return vi < 0 ? rawVerts.length / 3 + vi : vi - 1;
});
for (let k = 1; k + 1 < idx.length; k++) {
faces.push(idx[0], idx[k], idx[k + 1]);
}
}
}
const nVerts = rawVerts.length / 3;
const nFaces = faces.length / 3;
if (nVerts < 4 || nFaces < 2) {
throw new Error("OBJ has too few vertices/faces to form a patch.");
}
const verts = new Float64Array(rawVerts);
let cx = 0, cy = 0, cz = 0;
for (let i = 0; i < nVerts; i++) {
cx += verts[i * 3]; cy += verts[i * 3 + 1]; cz += verts[i * 3 + 2];
}
cx /= nVerts; cy /= nVerts; cz /= nVerts;
let minX = Infinity, minY = Infinity, minZ = Infinity;
let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;
for (let i = 0; i < nVerts; i++) {
verts[i * 3] -= cx; verts[i * 3 + 1] -= cy; verts[i * 3 + 2] -= cz;
const x = verts[i * 3], y = verts[i * 3 + 1], z = verts[i * 3 + 2];
if (x < minX) minX = x; if (x > maxX) maxX = x;
if (y < minY) minY = y; if (y > maxY) maxY = y;
if (z < minZ) minZ = z; if (z > maxZ) maxZ = z;
}
const scale = 2.0 / Math.max(Math.hypot(maxX - minX, maxY - minY, maxZ - minZ), 1e-8);
for (let i = 0; i < verts.length; i++) verts[i] *= scale;
const edgeMap = new Map();
for (let f = 0; f < nFaces; f++) {
const tri = [faces[f * 3], faces[f * 3 + 1], faces[f * 3 + 2]];
for (let e = 0; e < 3; e++) {
const a = tri[e], b = tri[(e + 1) % 3];
const key = a < b ? `${a}_${b}` : `${b}_${a}`;
edgeMap.set(key, (edgeMap.get(key) || 0) + 1);
}
}
const interiorMask = new Uint8Array(nVerts).fill(1);
const bndEdges = [];
for (const [key, count] of edgeMap.entries()) {
if (count === 1) {
const [a, b] = key.split("_").map(Number);
interiorMask[a] = 0;
interiorMask[b] = 0;
bndEdges.push(a, b);
}
}
const pca = computePCAFrame(verts);
const e1 = pca.eU, e2 = pca.eV;
const uvs = new Float64Array(nVerts * 2);
let uMin = Infinity, uMax = -Infinity, vMin = Infinity, vMax = -Infinity;
for (let i = 0; i < nVerts; i++) {
const x = verts[i * 3], y = verts[i * 3 + 1], z = verts[i * 3 + 2];
const u = x * e1[0] + y * e1[1] + z * e1[2];
const v = x * e2[0] + y * e2[1] + z * e2[2];
uvs[i * 2] = u; uvs[i * 2 + 1] = v;
if (u < uMin) uMin = u; if (u > uMax) uMax = u;
if (v < vMin) vMin = v; if (v > vMax) vMax = v;
}
uMin -= 1e-5; vMin -= 1e-5; uMax += 1e-5; vMax += 1e-5;
const N = 64;
const mask = new Uint8Array(N * N);
const forwardTri = new Int32Array(N * N);
const forwardBary = new Float32Array(N * N * 3);
const du = (uMax - uMin) / (N - 1);
const dv = (vMax - vMin) / (N - 1);
const bary2D = (pu, pv, au, av, bu, bv, cu, cv) => {
const v0u = bu - au, v0v = bv - av;
const v1u = cu - au, v1v = cv - av;
const v2u = pu - au, v2v = pv - av;
const d00 = v0u * v0u + v0v * v0v;
const d01 = v0u * v1u + v0v * v1v;
const d11 = v1u * v1u + v1v * v1v;
const d20 = v2u * v0u + v2v * v0v;
const d21 = v2u * v1u + v2v * v1v;
const denom = d00 * d11 - d01 * d01;
if (Math.abs(denom) < 1e-12) return [1 / 3, 1 / 3, 1 / 3, false];
const beta = (d11 * d20 - d01 * d21) / denom;
const gamma = (d00 * d21 - d01 * d20) / denom;
const alpha = 1.0 - beta - gamma;
const inside = alpha >= -1e-4 && alpha <= 1.0001 && beta >= -1e-4 && beta <= 1.0001 && gamma >= -1e-4 && gamma <= 1.0001;
return [alpha, beta, gamma, inside];
};
for (let vi = 0; vi < N; vi++) {
const pv = vMin + vi * dv;
for (let ui = 0; ui < N; ui++) {
const pu = uMin + ui * du;
const gIdx = vi * N + ui;
let found = false;
let bestTri = 0;
let bestDist = Infinity;
for (let f = 0; f < nFaces; f++) {
const i0 = faces[f * 3], i1 = faces[f * 3 + 1], i2 = faces[f * 3 + 2];
const au = uvs[i0 * 2], av = uvs[i0 * 2 + 1];
const bu = uvs[i1 * 2], bv = uvs[i1 * 2 + 1];
const cu = uvs[i2 * 2], cv = uvs[i2 * 2 + 1];
const cuM = (au + bu + cu) / 3, cvM = (av + bv + cv) / 3;
const d2 = (pu - cuM) ** 2 + (pv - cvM) ** 2;
if (d2 < bestDist) { bestDist = d2; bestTri = f; }
if (
pu >= Math.min(au, bu, cu) - 1e-4 && pu <= Math.max(au, bu, cu) + 1e-4 &&
pv >= Math.min(av, bv, cv) - 1e-4 && pv <= Math.max(av, bv, cv) + 1e-4
) {
const [a, b, c, ok] = bary2D(pu, pv, au, av, bu, bv, cu, cv);
if (ok) {
mask[gIdx] = 1;
forwardTri[gIdx] = f;
forwardBary[gIdx * 3] = a; forwardBary[gIdx * 3 + 1] = b; forwardBary[gIdx * 3 + 2] = c;
found = true;
break;
}
}
}
if (!found) {
const i0 = faces[bestTri * 3], i1 = faces[bestTri * 3 + 1], i2 = faces[bestTri * 3 + 2];
const [a, b, c] = bary2D(pu, pv, uvs[i0 * 2], uvs[i0 * 2 + 1], uvs[i1 * 2], uvs[i1 * 2 + 1], uvs[i2 * 2], uvs[i2 * 2 + 1]);
forwardTri[gIdx] = bestTri;
forwardBary[gIdx * 3] = a; forwardBary[gIdx * 3 + 1] = b; forwardBary[gIdx * 3 + 2] = c;
}
}
}
const maskExt = new Uint8Array(mask);
for (let vi = 0; vi < N; vi++) {
for (let ui = 0; ui < N; ui++) {
if (mask[vi * N + ui]) continue;
for (let dvI = -1; dvI <= 1; dvI++) {
for (let duI = -1; duI <= 1; duI++) {
const nv = vi + dvI, nu = ui + duI;
if (nv >= 0 && nv < N && nu >= 0 && nu < N && mask[nv * N + nu]) {
maskExt[vi * N + ui] = 1;
}
}
}
}
}
const inverseTri = new Int32Array(nVerts * 3);
const inverseBary = new Float32Array(nVerts * 3);
for (let v = 0; v < nVerts; v++) {
const pu = uvs[v * 2], pv = uvs[v * 2 + 1];
const ui = Math.min(N - 2, Math.max(0, Math.floor((pu - uMin) / du)));
const vi = Math.min(N - 2, Math.max(0, Math.floor((pv - vMin) / dv)));
const p00 = vi * N + ui, p10 = vi * N + ui + 1, p01 = (vi + 1) * N + ui, p11 = (vi + 1) * N + ui + 1;
const fu = (pu - (uMin + ui * du)) / du;
const fv = (pv - (vMin + vi * dv)) / dv;
if (fu + fv <= 1.0) {
inverseTri[v * 3] = p00; inverseTri[v * 3 + 1] = p10; inverseTri[v * 3 + 2] = p01;
inverseBary[v * 3] = 1 - fu - fv; inverseBary[v * 3 + 1] = fu; inverseBary[v * 3 + 2] = fv;
} else {
inverseTri[v * 3] = p11; inverseTri[v * 3 + 1] = p01; inverseTri[v * 3 + 2] = p10;
inverseBary[v * 3] = fu + fv - 1; inverseBary[v * 3 + 1] = 1 - fu; inverseBary[v * 3 + 2] = 1 - fv;
}
}
return {
name: fileName.replace(/\.obj$/i, ""),
category: "custom",
label: `Custom: ${fileName}`,
sample_n: N,
num_vertices: nVerts,
num_faces: nFaces,
vertices: Array.from(verts),
faces,
boundary_edges: bndEdges,
interior_mask: Array.from(interiorMask),
control_indices: [],
mask: Array.from(maskExt),
forward_tri_idx: Array.from(forwardTri),
forward_bary: Array.from(forwardBary),
inverse_grid_tri: Array.from(inverseTri),
inverse_bary: Array.from(inverseBary),
default_camera: [1.85, 1.35, 2.15],
};
}
/* ---------- Neural Inference Engine (ONNX Runtime Web) ---------- */
class WebNeuralOptimizer {
constructor(modelsBase, fallbackModelsBase) {
this.modelsBase = modelsBase;
this.fallbackModelsBase = fallbackModelsBase;
this.coarseSession = null;
this.fineSession = null;
this.loadingPromise = null;
this.activeSourceLabel = "Local";
}
async _loadSessionWithFallback(fileName, opts, onStatus) {
const primaryUrl = `${this.modelsBase}/${fileName}`;
try {
if (onStatus) onStatus(`Loading ${fileName} (10.8 MB)...`);
return { session: await window.ort.InferenceSession.create(primaryUrl, opts), viaFallback: false };
} catch (primaryErr) {
if (this.fallbackModelsBase && this.fallbackModelsBase !== this.modelsBase) {
const fbUrl = `${this.fallbackModelsBase}/${fileName}`;
if (onStatus) onStatus(`Streaming ${fileName} from Hugging Face Hub...`);
return { session: await window.ort.InferenceSession.create(fbUrl, opts), viaFallback: true };
}
throw primaryErr;
}
}
async ensureLoaded(onStatus) {
if (this.coarseSession && this.fineSession) return true;
if (this.loadingPromise) return this.loadingPromise;
this.loadingPromise = (async () => {
if (typeof window.ort === "undefined") {
throw new Error("onnxruntime-web failed to load from CDN.");
}
window.ort.env.wasm.wasmPaths = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.20.1/dist/";
window.ort.env.wasm.numThreads = 1;
const opts = { executionProviders: ["wasm"], graphOptimizationLevel: "all" };
const c = await this._loadSessionWithFallback("coarse_model.onnx", opts, onStatus);
const f = await this._loadSessionWithFallback("fine_model.onnx", opts, onStatus);
this.coarseSession = c.session;
this.fineSession = f.session;
const usingHF = c.viaFallback || f.viaFallback || String(this.modelsBase).includes("huggingface.co");
this.activeSourceLabel = usingHF ? "HF Hub" : "Local";
if (onStatus) onStatus(`ONNX Neural Engine Ready (${this.activeSourceLabel})`);
return true;
})();
try {
return await this.loadingPromise;
} catch (err) {
this.loadingPromise = null;
throw err;
}
}
forwardDeformToGrid(patch, verts) {
const N = patch.sample_n;
const total = N * N;
const grid = new Float64Array(total * 3);
const triIdx = patch.forward_tri_idx;
const bary = patch.forward_bary;
const faces = patch.faces;
for (let g = 0; g < total; g++) {
const f = triIdx[g];
const i0 = faces[f * 3], i1 = faces[f * 3 + 1], i2 = faces[f * 3 + 2];
const a = bary[g * 3], b = bary[g * 3 + 1], c = bary[g * 3 + 2];
grid[g * 3] = a * verts[i0 * 3] + b * verts[i1 * 3] + c * verts[i2 * 3];
grid[g * 3 + 1] = a * verts[i0 * 3 + 1] + b * verts[i1 * 3 + 1] + c * verts[i2 * 3 + 1];
grid[g * 3 + 2] = a * verts[i0 * 3 + 2] + b * verts[i1 * 3 + 2] + c * verts[i2 * 3 + 2];
}
return grid;
}
inverseSampleToMesh(patch, grid) {
const nVerts = patch.num_vertices;
const out = new Float64Array(nVerts * 3);
const invTri = patch.inverse_grid_tri;
const invBary = patch.inverse_bary;
for (let v = 0; v < nVerts; v++) {
const g0 = invTri[v * 3], g1 = invTri[v * 3 + 1], g2 = invTri[v * 3 + 2];
const a = invBary[v * 3], b = invBary[v * 3 + 1], c = invBary[v * 3 + 2];
out[v * 3] = a * grid[g0 * 3] + b * grid[g1 * 3] + c * grid[g2 * 3];
out[v * 3 + 1] = a * grid[g0 * 3 + 1] + b * grid[g1 * 3 + 1] + c * grid[g2 * 3 + 1];
out[v * 3 + 2] = a * grid[g0 * 3 + 2] + b * grid[g1 * 3 + 2] + c * grid[g2 * 3 + 2];
}
return out;
}
normalizeMask(grid, mask, N) {
const total = N * N;
let cx = 0, cy = 0, cz = 0, count = 0;
for (let g = 0; g < total; g++) {
if (mask[g] > 0) {
cx += grid[g * 3]; cy += grid[g * 3 + 1]; cz += grid[g * 3 + 2];
count++;
}
}
if (count < 1) {
return { xBchw: new Float32Array(3 * total), scaleM: 1.0, centroid: [0, 0, 0] };
}
cx /= count; cy /= count; cz /= count;
let maxNorm = 1e-8;
for (let g = 0; g < total; g++) {
if (mask[g] > 0) {
const d = Math.hypot(grid[g * 3] - cx, grid[g * 3 + 1] - cy, grid[g * 3 + 2] - cz);
if (d > maxNorm) maxNorm = d;
}
}
const xBchw = new Float32Array(3 * total);
const invM = 1.0 / maxNorm;
for (let g = 0; g < total; g++) {
if (mask[g] > 0) {
xBchw[g] = (grid[g * 3] - cx) * invM;
xBchw[total + g] = (grid[g * 3 + 1] - cy) * invM;
xBchw[2 * total + g] = (grid[g * 3 + 2] - cz) * invM;
}
}
return { xBchw, scaleM: maxNorm, centroid: [cx, cy, cz] };
}
denormalizeMask(outBchw, scaleM, centroid, mask, N) {
const total = N * N;
const grid = new Float64Array(total * 3);
const [cx, cy, cz] = centroid;
for (let g = 0; g < total; g++) {
if (mask[g] > 0) {
grid[g * 3] = outBchw[g] * scaleM + cx;
grid[g * 3 + 1] = outBchw[total + g] * scaleM + cy;
grid[g * 3 + 2] = outBchw[2 * total + g] * scaleM + cz;
}
}
return grid;
}
async runStage(grid, mask, N, session) {
const { xBchw, scaleM, centroid } = this.normalizeMask(grid, mask, N);
const inputName = session.inputNames[0];
const tensor = new window.ort.Tensor("float32", xBchw, [1, 3, N, N]);
const results = await session.run({ [inputName]: tensor });
const outName = session.outputNames[0];
const outData = results[outName].data;
return {
grid: this.denormalizeMask(outData, scaleM, centroid, mask, N),
xInNorm: xBchw,
yOutNorm: outData,
};
}
async optimizePatch(patch, deformedVerts, passes) {
const N = patch.sample_n;
const mask = patch.mask;
const gridIn = this.forwardDeformToGrid(patch, deformedVerts);
const { xBchw: inputNorm } = this.normalizeMask(gridIn, mask, N);
if (passes <= 0) {
return { verts: new Float64Array(deformedVerts), ms: 0.0, inputNorm, outputNorm: inputNorm };
}
await this.ensureLoaded();
const t0 = performance.now();
const s1 = await this.runStage(gridIn, mask, N, this.coarseSession);
let curGrid = s1.grid;
let outNorm = s1.yOutNorm;
for (let p = 1; p < passes; p++) {
const s2 = await this.runStage(curGrid, mask, N, this.fineSession);
curGrid = s2.grid;
outNorm = s2.yOutNorm;
}
const vertsOpt = this.inverseSampleToMesh(patch, curGrid);
const ms = performance.now() - t0;
return { verts: vertsOpt, ms, inputNorm, outputNorm: outNorm };
}
}
/* ---------- Shared Dual-Viewport PBR Three.js Engine ---------- */
class DualStudioViewport {
constructor(canvasWrapEl, options = {}) {
this.wrap = canvasWrapEl;
this.splitView = options.splitView !== false;
this.autoRotate = false;
this.theme = "light"; // "light" | "dark"
this.isInViewport = true;
this.camTargetAnim = null;
this.controlsTargetAnim = null;
const w = this.wrap.clientWidth || 760;
const h = this.wrap.clientHeight || 550;
this.renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance",
preserveDrawingBuffer: true,
});
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
this.renderer.setSize(w, h);
this.renderer.outputColorSpace = THREE.SRGBColorSpace;
this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
this.renderer.toneMappingExposure = 0.96;
this.wrap.appendChild(this.renderer.domElement);
const pmrem = new THREE.PMREMGenerator(this.renderer);
this.envTex = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
pmrem.dispose();
this.sceneInput = this._buildSubScene();
this.sceneOutput = this._buildSubScene();
this.groupInput = new THREE.Group();
this.groupOutput = new THREE.Group();
this.sceneInput.add(this.groupInput);
this.sceneOutput.add(this.groupOutput);
this.camera = new THREE.PerspectiveCamera(36, (this.splitView ? w * 0.5 : w) / Math.max(h, 1), 0.05, 100);
this.camera.position.set(2.4, 1.5, 2.8);
this.controls = new OrbitControls(this.camera, this.renderer.domElement);
this.controls.enableDamping = true;
this.controls.dampingFactor = 0.08;
this.controls.minDistance = 0.6;
this.controls.maxDistance = 12.0;
this.applyTheme("light");
const ro = new ResizeObserver(() => {
const cw = this.wrap.clientWidth;
const ch = this.wrap.clientHeight;
if (cw > 0 && ch > 0) {
this.renderer.setSize(cw, ch);
this.renderNow();
}
});
ro.observe(this.wrap);
if ("IntersectionObserver" in window) {
const io = new IntersectionObserver((entries) => {
const nextVis = entries[0]?.isIntersecting ?? true;
const becameVis = !this.isInViewport && nextVis;
this.isInViewport = nextVis;
if (becameVis) this.renderNow();
}, { threshold: 0.02 });
io.observe(this.wrap);
}
this.renderNow = () => {
if (this.controlsTargetAnim) {
this.controls.target.lerp(this.controlsTargetAnim, 0.16);
if (this.controls.target.distanceTo(this.controlsTargetAnim) < 0.008) {
this.controls.target.copy(this.controlsTargetAnim);
this.controlsTargetAnim = null;
}
}
if (this.camTargetAnim) {
this.camera.position.lerp(this.camTargetAnim, 0.16);
if (this.camera.position.distanceTo(this.camTargetAnim) < 0.012) {
this.camera.position.copy(this.camTargetAnim);
this.camTargetAnim = null;
}
}
this.controls.autoRotate = this.autoRotate;
this.controls.autoRotateSpeed = 1.35;
this.controls.update();
// Orient any camera-facing billboard target rings
this.sceneInput.traverse((obj) => {
if (obj.userData && obj.userData.isBillboard) {
obj.quaternion.copy(this.camera.quaternion);
}
});
const cw = this.wrap.clientWidth || 760;
const ch = this.wrap.clientHeight || 550;
if (this.splitView) {
const halfW = Math.max(1, Math.floor(cw / 2));
const asp = halfW / Math.max(ch, 1);
if (Math.abs(this.camera.aspect - asp) > 1e-4) {
this.camera.aspect = asp;
this.camera.updateProjectionMatrix();
}
this.renderer.setScissorTest(true);
this.renderer.setViewport(0, 0, halfW, ch);
this.renderer.setScissor(0, 0, halfW, ch);
this.renderer.render(this.sceneInput, this.camera);
const rw = Math.max(1, cw - halfW);
this.renderer.setViewport(halfW, 0, rw, ch);
this.renderer.setScissor(halfW, 0, rw, ch);
this.renderer.render(this.sceneOutput, this.camera);
this.renderer.setScissorTest(false);
} else {
const asp = Math.max(cw, 1) / Math.max(ch, 1);
if (Math.abs(this.camera.aspect - asp) > 1e-4) {
this.camera.aspect = asp;
this.camera.updateProjectionMatrix();
}
this.renderer.setScissorTest(false);
this.renderer.setViewport(0, 0, cw, ch);
this.renderer.render(this.sceneOutput, this.camera);
}
};
const animate = () => {
requestAnimationFrame(animate);
if (!this.isInViewport) return;
this.renderNow();
};
animate();
}
_configureGrid(grid) {
const mats = Array.isArray(grid.material) ? grid.material : [grid.material];
mats.forEach((m) => {
m.transparent = true;
m.opacity = 0.26;
m.depthWrite = false;
});
}
_buildSubScene() {
const s = new THREE.Scene();
s.environment = this.envTex;
const hemi = new THREE.HemisphereLight(0xfffefb, 0x646e7d, 0.48);
s.add(hemi);
const key = new THREE.DirectionalLight(0xfffcf5, 1.42);
key.position.set(3.2, 4.8, 3.6);
s.add(key);
const rim = new THREE.DirectionalLight(0xc2d8f8, 0.48);
rim.position.set(-3.4, 2.2, -2.8);
s.add(rim);
const fill = new THREE.DirectionalLight(0xf6efe6, 0.28);
fill.position.set(-2.0, -1.5, 2.4);
s.add(fill);
const grid = new THREE.GridHelper(3.4, 17, 0xcec5b7, 0xded7cb);
this._configureGrid(grid);
grid.position.y = -0.87;
s.add(grid);
const shadowGeo = new THREE.PlaneGeometry(1, 1);
const shadowMat = new THREE.MeshBasicMaterial({
map: getSoftShadowTexture(),
transparent: true,
depthWrite: false,
});
const shadowMesh = new THREE.Mesh(shadowGeo, shadowMat);
shadowMesh.rotation.x = -Math.PI / 2;
shadowMesh.scale.set(2.5, 2.5, 1);
shadowMesh.position.y = -0.866;
s.add(shadowMesh);
s.userData = { hemi, key, rim, fill, grid, shadowMesh, floorY: -0.87 };
return s;
}
setFloorY(minY, span = 1.4) {
const floorY = minY - 0.05;
const scSize = Math.max(1.8, Math.min(3.6, span * 1.45));
[this.sceneInput, this.sceneOutput].forEach((sc) => {
sc.userData.floorY = floorY;
if (sc.userData.grid) {
sc.userData.grid.position.y = floorY;
}
if (sc.userData.shadowMesh) {
sc.userData.shadowMesh.position.y = floorY + 0.004;
sc.userData.shadowMesh.scale.set(scSize, scSize, 1);
}
});
}
applyTheme(theme) {
this.theme = theme;
const isDark = theme === "dark";
const bgHex = isDark ? 0x111622 : 0xeeece6;
const c1 = isDark ? 0x324059 : 0xcec5b7;
const c2 = isDark ? 0x1e2738 : 0xded7cb;
[this.sceneInput, this.sceneOutput].forEach((sc) => {
sc.background = new THREE.Color(bgHex);
const { grid, shadowMesh, hemi, key, floorY } = sc.userData;
if (grid) {
const oldIdx = sc.children.indexOf(grid);
if (oldIdx >= 0) {
sc.remove(grid);
grid.geometry.dispose();
const newGrid = new THREE.GridHelper(3.4, 17, c1, c2);
this._configureGrid(newGrid);
newGrid.position.y = typeof floorY === "number" ? floorY : -0.87;
sc.add(newGrid);
sc.userData.grid = newGrid;
}
}
if (shadowMesh) shadowMesh.visible = !isDark;
if (hemi) hemi.intensity = isDark ? 0.38 : 0.48;
if (key) key.intensity = isDark ? 1.52 : 1.42;
});
this.wrap.classList.toggle("is-dark", isDark);
}
fitCameraToBounds(pointsFlat, viewDirArr, padding = 1.32, instant = false) {
const n = Math.floor((pointsFlat?.length || 0) / 3);
if (n === 0) return;
let minX = Infinity, minY = Infinity, minZ = Infinity;
let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;
for (let i = 0; i < n; i++) {
const x = pointsFlat[i * 3], y = pointsFlat[i * 3 + 1], z = pointsFlat[i * 3 + 2];
if (x < minX) minX = x; if (x > maxX) maxX = x;
if (y < minY) minY = y; if (y > maxY) maxY = y;
if (z < minZ) minZ = z; if (z > maxZ) maxZ = z;
}
const center = new THREE.Vector3(0.5 * (minX + maxX), 0.5 * (minY + maxY), 0.5 * (minZ + maxZ));
this.setFloorY(minY, Math.max(maxX - minX, maxZ - minZ));
const dir = new THREE.Vector3(viewDirArr[0] || 0.45, viewDirArr[1] ?? 0.35, viewDirArr[2] || 0.82).normalize();
if (Math.abs(dir.y) > 0.93) {
dir.y = Math.sign(dir.y || 1) * 0.93;
dir.normalize();
}
const worldUp = new THREE.Vector3(0, 1, 0);
const right = new THREE.Vector3().crossVectors(worldUp, dir).normalize();
if (right.lengthSq() < 1e-6) right.set(1, 0, 0);
const camUp = new THREE.Vector3().crossVectors(dir, right).normalize();
const corners = [
[minX, minY, minZ], [minX, minY, maxZ], [minX, maxY, minZ], [minX, maxY, maxZ],
[maxX, minY, minZ], [maxX, minY, maxZ], [maxX, maxY, minZ], [maxX, maxY, maxZ],
];
let rx = 0.05, ry = 0.05, rz = 0.05;
for (const [x, y, z] of corners) {
const rel = new THREE.Vector3(x - center.x, y - center.y, z - center.z);
rx = Math.max(rx, Math.abs(rel.dot(right)));
ry = Math.max(ry, Math.abs(rel.dot(camUp)));
rz = Math.max(rz, Math.abs(rel.dot(dir)));
}
const cw = this.wrap.clientWidth || 760;
const ch = this.wrap.clientHeight || 550;
const asp = (this.splitView ? cw * 0.5 : cw) / Math.max(ch, 1);
const vFov = (this.camera.fov * Math.PI) / 180.0;
const tanV = Math.tan(vFov * 0.5);
const tanH = tanV * Math.max(asp, 0.25);
const dist = Math.max(ry / tanV, rx / tanH) * padding + rz;
const targetCamPos = center.clone().addScaledVector(dir, dist);
if (instant) {
this.camTargetAnim = null;
this.controlsTargetAnim = null;
this.controls.target.copy(center);
this.camera.position.copy(targetCamPos);
this.camera.lookAt(center);
this.controls.update();
} else {
this.controlsTargetAnim = center.clone();
this.camTargetAnim = targetCamPos;
}
}
clearGroup(group) {
while (group.children.length > 0) {
const c = group.children.pop();
c.traverse((node) => {
if (node.geometry) node.geometry.dispose();
if (node.material) {
if (Array.isArray(node.material)) node.material.forEach((m) => m.dispose());
else node.material.dispose();
}
});
}
}
}
/* ---------- Workbench 1: Live ONNX Patch Sculptor w/ 3D Lattice Cage ---------- */
class PatchStudioController {
constructor(rootEl, sharedEngine) {
this.root = rootEl;
this.config = getConfig();
this.engine = sharedEngine;
this.patchCache = new Map();
this.manifest = null;
this.activePatch = null;
this.cage = null;
this.cageMode = "2x2x2"; // "2x2x2" | "3x3x2"
this.activeNodes = null;
this.deformedVerts = null;
this.displayedVerts = null;
this.params = { bend: 0, twist: 0, saddle: 0, noise: 0 };
this.outputMode = "onnx2"; // "onnx2" | "onnx1" | "ref" | "raw"
this.patchShading = "steel"; // "steel" | "curvature" | "zebra" | "clay"
this.showWireframe = false;
this.showGhost = false;
this.showHandles = true;
this.demoPlaying = false;
this.demoPhase = 0;
this.inferRunning = false;
this.inferQueued = false;
this.lastOnnxMs = 0;
this.vp = new DualStudioViewport(this.root.querySelector("#patch-canvas-wrap"), { splitView: true });
this.cageGroup = new THREE.Group();
this.vp.sceneInput.add(this.cageGroup);
this.cageSpheres = [];
this.cageEdgeBase = null;
this.cageEdgeHi = null;
this.cageMovedRays = null;
this.hoveredNode = -1;
this.draggingNode = -1;
this.dragPlane = new THREE.Plane();
this.dragHitOffset = new THREE.Vector3();
this.pointer = new THREE.Vector2();
this.raycaster = new THREE.Raycaster();
this.ghostMesh = null;
this.geoCanvas = this.root.querySelector("#geo-image-canvas");
this.bindPointerDrag();
this.bindUI();
this.syncViewportChrome();
this.loadManifestAndInit();
}
async loadManifestAndInit() {
try {
const res = await fetch(`${this.config.assetsBase}/manifest.json`);
if (res.ok) {
this.manifest = await res.json();
this.renderGalleryCategories();
}
} catch (_) {}
await this.loadPresetPatch("patch_811v", false);
}
_getUprightViewDir(patch) {
const raw = patch?.default_camera || [0.695, 0.70, 2.133];
let x = raw[0], y = raw[1], z = raw[2];
if (y < -0.15) {
x = -x;
y = -y;
z = -z;
}
if (y < 0.22) y = 0.28;
const len = Math.hypot(x, y, z) || 1.0;
return [x / len, y / len, z / len];
}
_getCombinedFitPoints() {
if (!this.activePatch) return [];
const v = this.deformedVerts || this.activePatch.vertices;
if (!this.cage || !this.activeNodes) return v;
const arr = new Float64Array(v.length + this.activeNodes.length);
arr.set(v, 0);
arr.set(this.activeNodes, v.length);
return arr;
}
_updatePointerNDC(ev) {
const rect = this.vp.renderer.domElement.getBoundingClientRect();
if (this.vp.splitView) {
const halfW = rect.width * 0.5;
const inLeft = ev.clientX - rect.left <= halfW;
this.pointer.x = ((ev.clientX - rect.left) / halfW) * 2 - 1;
this.pointer.y = -((ev.clientY - rect.top) / rect.height) * 2 + 1;
return inLeft;
}
this.pointer.x = ((ev.clientX - rect.left) / rect.width) * 2 - 1;
this.pointer.y = -((ev.clientY - rect.top) / rect.height) * 2 + 1;
return true;
}
_syncCageNodeStyles() {
for (let i = 0; i < this.cageSpheres.length; i++) {
const m = this.cageSpheres[i];
const isActive = i === this.draggingNode || i === this.hoveredNode;
if (isActive) {
m.material.color.setHex(0xc83e37);
m.material.emissive.setHex(0x52120f);
m.scale.set(1.32, 1.32, 1.32);
if (m.userData.halo) m.userData.halo.visible = true;
} else {
m.material.color.setHex(0x1d4e89);
m.material.emissive.setHex(0x0b1f38);
m.scale.set(1.0, 1.0, 1.0);
if (m.userData.halo) m.userData.halo.visible = false;
}
}
}
bindPointerDrag() {
const dom = this.vp.renderer.domElement;
dom.addEventListener("pointerdown", (ev) => {
if (!this.showHandles || this.cageSpheres.length === 0 || !this.cage) return;
if (!this._updatePointerNDC(ev)) return;
this.raycaster.setFromCamera(this.pointer, this.vp.camera);
const hits = this.raycaster.intersectObjects(this.cageSpheres, false);
if (hits.length > 0) {
this.stopDemo();
this.vp.camTargetAnim = null;
this.vp.controlsTargetAnim = null;
this.draggingNode = hits[0].object.userData.nodeIdx;
this.vp.controls.enabled = false;
const camDir = new THREE.Vector3();
this.vp.camera.getWorldDirection(camDir);
this.dragPlane.setFromNormalAndCoplanarPoint(camDir, hits[0].object.position);
const planeHit = new THREE.Vector3();
this.raycaster.ray.intersectPlane(this.dragPlane, planeHit);
this.dragHitOffset.copy(hits[0].object.position).sub(planeHit);
this._syncCageNodeStyles();
this.updateCageVisuals();
dom.setPointerCapture(ev.pointerId);
dom.style.cursor = "grabbing";
}
});
dom.addEventListener("pointermove", (ev) => {
const inVp = this._updatePointerNDC(ev);
this.raycaster.setFromCamera(this.pointer, this.vp.camera);
if (this.draggingNode >= 0 && this.activePatch && this.cage) {
const planeHit = new THREE.Vector3();
if (this.raycaster.ray.intersectPlane(this.dragPlane, planeHit)) {
planeHit.add(this.dragHitOffset);
const { base } = this.cage.getNodeBaseAndFinal(this.draggingNode, this.params);
this.cage.userOffsets[this.draggingNode] = [
planeHit.x - base[0],
planeHit.y - base[1],
planeHit.z - base[2],
];
this.recomputeDeformationAndOptimize();
}
} else if (inVp && this.showHandles && this.cageSpheres.length > 0) {
const hits = this.raycaster.intersectObjects(this.cageSpheres, false);
const nextHover = hits.length > 0 ? hits[0].object.userData.nodeIdx : -1;
if (nextHover !== this.hoveredNode) {
this.hoveredNode = nextHover;
this._syncCageNodeStyles();
this.updateCageVisuals();
}
dom.style.cursor = nextHover >= 0 ? "grab" : "default";
} else {
if (this.hoveredNode !== -1) {
this.hoveredNode = -1;
this._syncCageNodeStyles();
this.updateCageVisuals();
}
dom.style.cursor = "default";
}
});
const endDrag = (ev) => {
if (this.draggingNode >= 0) {
this.draggingNode = -1;
this.vp.controls.enabled = true;
this._syncCageNodeStyles();
this.updateCageVisuals();
dom.style.cursor = this.hoveredNode >= 0 ? "grab" : "default";
try { dom.releasePointerCapture(ev.pointerId); } catch (_) {}
}
};
dom.addEventListener("pointerup", endDrag);
dom.addEventListener("pointercancel", endDrag);
this.vp.wrap.addEventListener("dragover", (e) => {
e.preventDefault();
this.vp.wrap.classList.add("is-dragover");
});
this.vp.wrap.addEventListener("dragleave", () => this.vp.wrap.classList.remove("is-dragover"));
this.vp.wrap.addEventListener("drop", async (e) => {
e.preventDefault();
this.vp.wrap.classList.remove("is-dragover");
const file = e.dataTransfer?.files?.[0];
if (file && file.name.toLowerCase().endsWith(".obj")) {
await this.loadCustomObjFile(file);
}
});
}
bindUI() {
const q = (s) => this.root.querySelector(s);
this.root.querySelectorAll("[data-patch-view]").forEach((btn) => {
btn.addEventListener("click", () => {
this.vp.splitView = btn.dataset.patchView === "split";
this.root.querySelectorAll("[data-patch-view]").forEach((b) => b.classList.toggle("active", b === btn));
this.syncViewportChrome();
if (this.activePatch) {
this.vp.fitCameraToBounds(this._getCombinedFitPoints(), this._getUprightViewDir(this.activePatch), 1.32, false);
}
});
});
const themeBtn = q("#btn-patch-theme");
if (themeBtn) {
themeBtn.addEventListener("click", () => {
const next = this.vp.theme === "light" ? "dark" : "light";
this.vp.applyTheme(next);
themeBtn.textContent = next === "dark" ? "Light Studio" : "Dark CAD";
themeBtn.classList.toggle("active", next === "dark");
this.updateCageVisuals();
this.renderPatchScene();
});
}
const autoBtn = q("#btn-patch-autorotate");
if (autoBtn) {
autoBtn.addEventListener("click", () => {
this.vp.autoRotate = !this.vp.autoRotate;
autoBtn.classList.toggle("active", this.vp.autoRotate);
});
}
const camBtn = q("#btn-patch-reset-cam");
if (camBtn) {
camBtn.addEventListener("click", () => {
if (!this.activePatch) return;
this.vp.fitCameraToBounds(this._getCombinedFitPoints(), this._getUprightViewDir(this.activePatch), 1.32, false);
});
}
const demoBtn = q("#btn-sculpt-demo");
if (demoBtn) {
demoBtn.addEventListener("click", () => {
if (this.demoPlaying) this.stopDemo();
else this.startDemo();
});
}
const patchSel = q("#studio-patch-select");
if (patchSel) {
patchSel.addEventListener("change", () => this.loadPresetPatch(patchSel.value));
}
const objUpload = q("#studio-obj-upload");
if (objUpload) {
objUpload.addEventListener("change", async (e) => {
const f = e.target.files?.[0];
if (f) await this.loadCustomObjFile(f);
e.target.value = "";
});
}
this.root.querySelectorAll("[data-cage-mode]").forEach((btn) => {
btn.addEventListener("click", () => {
this.stopDemo();
this.cageMode = btn.dataset.cageMode;
this.root.querySelectorAll("[data-cage-mode]").forEach((b) => b.classList.toggle("active", b === btn));
if (this.activePatch) {
this.resetDeformation();
}
});
});
this.root.querySelectorAll("[data-cage-pose]").forEach((btn) => {
btn.addEventListener("click", () => {
this.stopDemo();
this.applyPose(btn.dataset.cagePose);
});
});
this.root.querySelectorAll("[data-output-mode]").forEach((btn) => {
btn.addEventListener("click", () => {
if (btn.disabled) return;
this.outputMode = btn.dataset.outputMode;
this.root.querySelectorAll("[data-output-mode]").forEach((b) => b.classList.toggle("active", b === btn));
this.recomputeDeformationAndOptimize();
});
});
const sliderMap = [
["#slider-bend", "bend", "#val-bend", (v) => v.toFixed(2)],
["#slider-twist", "twist", "#val-twist", (v) => v.toFixed(2)],
["#slider-saddle", "saddle", "#val-saddle", (v) => v.toFixed(2)],
["#slider-noise", "noise", "#val-noise", (v) => `${v.toFixed(1)}%`],
];
sliderMap.forEach(([sel, key, valSel, fmt]) => {
const el = q(sel);
const valEl = q(valSel);
if (!el) return;
el.addEventListener("input", () => {
this.stopDemo();
this.params[key] = parseFloat(el.value);
if (valEl) valEl.textContent = fmt(this.params[key]);
if (this.outputMode === "ref") {
this.setOutputMode("onnx2");
}
this.recomputeDeformationAndOptimize();
});
});
this.root.querySelectorAll("[data-patch-shading]").forEach((btn) => {
btn.addEventListener("click", () => {
this.patchShading = btn.dataset.patchShading;
this.root.querySelectorAll("[data-patch-shading]").forEach((b) => b.classList.toggle("active", b === btn));
this.renderPatchScene();
});
});
const wireChk = q("#chk-patch-wire");
if (wireChk) {
wireChk.addEventListener("change", () => {
this.showWireframe = wireChk.checked;
this.renderPatchScene();
});
}
const ghostChk = q("#chk-ghost");
if (ghostChk) {
ghostChk.addEventListener("change", () => {
this.showGhost = ghostChk.checked;
if (this.ghostMesh) this.ghostMesh.visible = this.showGhost;
});
}
const handleChk = q("#chk-handles");
if (handleChk) {
handleChk.addEventListener("change", () => {
this.showHandles = handleChk.checked;
this.cageGroup.visible = this.showHandles;
});
}
const resetBtn = q("#btn-reset-patch");
if (resetBtn) {
resetBtn.addEventListener("click", () => {
this.stopDemo();
this.resetDeformation();
});
}
const exInBtn = q("#btn-export-input-obj");
if (exInBtn) exInBtn.addEventListener("click", () => this.exportCurrentObj("input"));
const exOutBtn = q("#btn-export-obj");
if (exOutBtn) exOutBtn.addEventListener("click", () => this.exportCurrentObj("output"));
const localBar = q("#studio-local-backend-bar");
if (localBar) localBar.classList.toggle("hidden", !this.config.hasLocalBackend);
const refineBtn = q("#btn-stage2-refine");
if (refineBtn) refineBtn.addEventListener("click", () => this.runLocalPostprocess());
const pdfBtn = q("#btn-export-pdf");
if (pdfBtn) pdfBtn.addEventListener("click", () => this.downloadPapercraftPdf());
}
setOutputMode(mode) {
this.outputMode = mode;
this.root.querySelectorAll("[data-output-mode]").forEach((b) =>
b.classList.toggle("active", b.dataset.outputMode === mode)
);
}
_syncSlidersUI() {
const q = (s) => this.root.querySelector(s);
const items = [
["#slider-bend", "#val-bend", this.params.bend, (v) => v.toFixed(2)],
["#slider-twist", "#val-twist", this.params.twist, (v) => v.toFixed(2)],
["#slider-saddle", "#val-saddle", this.params.saddle, (v) => v.toFixed(2)],
["#slider-noise", "#val-noise", this.params.noise, (v) => `${v.toFixed(1)}%`],
];
items.forEach(([s, v, val, fmt]) => {
if (q(s)) q(s).value = String(val);
if (q(v)) q(v).textContent = fmt(val);
});
}
applyPose(pose) {
if (!this.activePatch || !this.cage) return;
this.cage.resetOffsets();
this.params = { bend: 0, twist: 0, saddle: 0, noise: 0 };
if (this.outputMode === "ref" || this.outputMode === "raw") {
this.setOutputMode("onnx2");
}
const { nu, nv, nw, eU, eV, eW } = this.cage;
if (pose === "corner") {
const idxFront = this.cage.nodeIndex(nu - 1, nv - 1, nw - 1);
const idxOpposite = this.cage.nodeIndex(0, 0, nw - 1);
this.cage.userOffsets[idxFront] = [
0.34 * eU[0] + 0.22 * eV[0] + 0.36 * eW[0],
0.34 * eU[1] + 0.22 * eV[1] + 0.36 * eW[1],
0.34 * eU[2] + 0.22 * eV[2] + 0.36 * eW[2],
];
this.cage.userOffsets[idxOpposite] = [
-0.14 * eW[0],
-0.14 * eW[1],
-0.14 * eW[2],
];
} else if (pose === "saddle") {
this.params.saddle = 0.72;
} else if (pose === "twist") {
this.params.twist = 0.78;
}
this._syncSlidersUI();
this.recomputeDeformationAndOptimize();
}
async startDemo() {
if (!this.activePatch || !this.cage || this.demoPlaying) return;
this.demoPlaying = true;
const demoBtn = this.root.querySelector("#btn-sculpt-demo");
if (demoBtn) {
demoBtn.classList.add("active");
demoBtn.textContent = "Pause Demo";
}
if (this.outputMode === "ref" || this.outputMode === "raw") {
this.setOutputMode("onnx2");
}
const { nu, nv, nw } = this.cage;
const corners = [
this.cage.nodeIndex(nu - 1, nv - 1, nw - 1),
this.cage.nodeIndex(0, nv - 1, nw - 1),
this.cage.nodeIndex(0, 0, nw - 1),
this.cage.nodeIndex(nu - 1, 0, nw - 1),
];
try {
await this.engine.ensureLoaded((msg) => this.setStatus(msg));
while (this.demoPlaying) {
this.demoPhase += 0.22;
this.cage.resetOffsets();
const seg = Math.floor(this.demoPhase / Math.PI) % corners.length;
const localT = this.demoPhase % Math.PI;
const amp = Math.sin(localT);
const nodeIdx = corners[seg];
const [su, sv] = this.cage.nodeParams[nodeIdx];
const dirU = su > 0.5 ? 1.0 : -1.0;
const dirV = sv > 0.5 ? 1.0 : -1.0;
const { eU, eV, eW } = this.cage;
this.cage.userOffsets[nodeIdx] = [
amp * (0.30 * dirU * eU[0] + 0.22 * dirV * eV[0] + 0.34 * eW[0]),
amp * (0.30 * dirU * eU[1] + 0.22 * dirV * eV[1] + 0.34 * eW[1]),
amp * (0.30 * dirU * eU[2] + 0.22 * dirV * eV[2] + 0.34 * eW[2]),
];
this.activeNodes = this.cage.computeDeformedNodes(this.params);
this.deformedVerts = this.cage.deformVertices(this.activeNodes, this.params);
this.renderInputSide();
const passes = this.outputMode === "onnx1" ? 1 : 2;
const snapshot = new Float64Array(this.deformedVerts);
const { verts, ms, inputNorm, outputNorm } = await this.engine.optimizePatch(
this.activePatch,
snapshot,
passes
);
if (!this.demoPlaying) break;
this.displayedVerts = verts;
this.lastOnnxMs = ms;
this.drawGeometryImage(inputNorm, outputNorm, this.activePatch.mask, this.activePatch.sample_n);
this.renderOutputSide();
this.updatePatchHUD();
const tag = passes === 1 ? "Coarse ONNX" : "Coarse + Fine ONNX";
this.setStatus(`${this.activePatch.label} · Fig. 7 Cage Demo · ${tag} in ${ms.toFixed(1)} ms`);
// Always yield so UI click events (Pause Demo) respond instantaneously
await new Promise((r) => setTimeout(r, 45));
}
} catch (err) {
this.setStatus(`Demo paused: ${err.message}`, true);
this.stopDemo();
}
}
stopDemo() {
if (!this.demoPlaying) return;
this.demoPlaying = false;
const demoBtn = this.root.querySelector("#btn-sculpt-demo");
if (demoBtn) {
demoBtn.classList.remove("active");
demoBtn.textContent = "Fig. 7 Cage Demo";
}
}
syncViewportChrome() {
const q = (s) => this.root.querySelector(s);
const divider = q("#vp-divider");
const leftBadge = q("#vp-badge-left");
if (divider) divider.classList.toggle("hidden", !this.vp.splitView);
if (leftBadge) leftBadge.classList.toggle("hidden", !this.vp.splitView);
const targetParent = this.vp.splitView ? this.vp.sceneInput : this.vp.sceneOutput;
if (this.cageGroup.parent !== targetParent) targetParent.add(this.cageGroup);
this.cageGroup.visible = this.showHandles;
}
setStatus(msg, isError = false) {
const el = this.root.querySelector("#studio-status");
if (el) {
el.textContent = msg;
el.classList.toggle("is-error", isError);
}
}
async loadCustomObjFile(file) {
try {
this.stopDemo();
this.setStatus(`Parsing ${file.name}...`);
const text = await file.text();
const patch = parseCustomObjToPatch(text, file.name);
this.activatePatch(patch, true);
} catch (err) {
this.setStatus(`OBJ error: ${err.message}`, true);
}
}
async loadPresetPatch(name, animateCam = true) {
try {
this.stopDemo();
this.setStatus(`Loading patch "${name}"...`);
let patch = this.patchCache.get(name);
if (!patch) {
const res = await fetch(`${this.config.assetsBase}/patches/${name}.json`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
patch = await res.json();
this.patchCache.set(name, patch);
}
const sel = this.root.querySelector("#studio-patch-select");
if (sel && sel.querySelector(`option[value="${name}"]`)) {
sel.value = name;
}
document.querySelectorAll(".patch-gallery-card").forEach((c) =>
c.classList.toggle("active", c.dataset.patchCard === name)
);
this.activatePatch(patch, animateCam);
} catch (err) {
this.setStatus(`Failed loading patch: ${err.message}`, true);
}
}
activatePatch(patch, animateCam = true) {
this.activePatch = patch;
this.displayedVerts = null;
this.hoveredNode = -1;
this.draggingNode = -1;
const hasRef = Boolean(patch.ref_vertices && patch.ref_vertices.length > 0);
const refBtn = this.root.querySelector('[data-output-mode="ref"]');
if (refBtn) {
refBtn.disabled = !hasRef;
refBtn.classList.toggle("hidden", !hasRef);
if (!hasRef && this.outputMode === "ref") {
this.setOutputMode("onnx2");
}
}
this.resetDeformation();
this.vp.fitCameraToBounds(this._getCombinedFitPoints(), this._getUprightViewDir(patch), 1.32, !animateCam);
}
resetDeformation() {
if (!this.activePatch) return;
const isCurved = this.cageMode === "3x3x2";
this.cage = new LatticeCage(
this.activePatch.vertices,
isCurved ? 3 : 2,
isCurved ? 3 : 2,
2
);
this.params = { bend: 0, twist: 0, saddle: 0, noise: 0 };
this._syncSlidersUI();
this.rebuildCageObjects();
this.recomputeDeformationAndOptimize();
}
_isDeformationUntouched() {
if (!this.cage) return true;
const slidersZero =
this.params.bend === 0 &&
this.params.twist === 0 &&
this.params.saddle === 0 &&
this.params.noise === 0;
const offsetsZero = !this.cage.userOffsets.some(
(o) => Math.abs(o[0]) + Math.abs(o[1]) + Math.abs(o[2]) > 1e-6
);
return slidersZero && offsetsZero;
}
recomputeDeformationAndOptimize() {
if (!this.activePatch || !this.cage) return;
this.activeNodes = this.cage.computeDeformedNodes(this.params);
this.deformedVerts = this.cage.deformVertices(this.activeNodes, this.params);
// Immediate 60 FPS Input mesh + Outer Cage redraw BEFORE async ONNX finishes
this.renderInputSide();
const untouched = this._isDeformationUntouched();
if (this.outputMode === "ref" && this.activePatch.ref_vertices && untouched) {
this.displayedVerts = new Float64Array(this.activePatch.ref_vertices);
this.lastOnnxMs = 0;
const gIn = this.engine.forwardDeformToGrid(this.activePatch, this.deformedVerts);
const { xBchw: normIn } = this.engine.normalizeMask(gIn, this.activePatch.mask, this.activePatch.sample_n);
this.drawGeometryImage(normIn, normIn, this.activePatch.mask, this.activePatch.sample_n);
this.renderOutputSide();
this.updatePatchHUD();
this.setStatus(`Showing ${this.activePatch.label}: Published Stage 2 Developable Ref`);
return;
}
if (this.outputMode === "raw") {
this.displayedVerts = this.deformedVerts;
this.lastOnnxMs = 0;
const gIn = this.engine.forwardDeformToGrid(this.activePatch, this.deformedVerts);
const { xBchw: normIn } = this.engine.normalizeMask(gIn, this.activePatch.mask, this.activePatch.sample_n);
this.drawGeometryImage(normIn, normIn, this.activePatch.mask, this.activePatch.sample_n);
this.renderOutputSide();
this.updatePatchHUD();
this.setStatus("Showing Unoptimized Input Surface (0 passes)");
return;
}
if (!this.displayedVerts) {
this.displayedVerts = this.deformedVerts;
this.renderOutputSide();
this.updatePatchHUD();
}
this.scheduleOnnxOptimize();
}
async scheduleOnnxOptimize() {
if (!this.activePatch || !this.deformedVerts) return;
const passes = this.outputMode === "onnx1" ? 1 : this.outputMode === "raw" ? 0 : 2;
if (passes === 0) return;
if (this.inferRunning) {
this.inferQueued = true;
return;
}
this.inferRunning = true;
try {
await this.engine.ensureLoaded((msg) => this.setStatus(msg));
do {
this.inferQueued = false;
const snapshotDeformed = new Float64Array(this.deformedVerts);
const { verts, ms, inputNorm, outputNorm } = await this.engine.optimizePatch(
this.activePatch,
snapshotDeformed,
passes
);
this.displayedVerts = verts;
this.lastOnnxMs = ms;
this.drawGeometryImage(inputNorm, outputNorm, this.activePatch.mask, this.activePatch.sample_n);
this.renderPatchScene();
const tag = passes === 1 ? "Coarse ONNX" : "Coarse + Fine ONNX";
this.setStatus(`${this.activePatch.label} · ${tag} (${this.engine.activeSourceLabel}) in ${ms.toFixed(1)} ms`);
} while (this.inferQueued);
} catch (err) {
this.displayedVerts = this.deformedVerts;
this.renderPatchScene();
this.setStatus(`ONNX Engine fallback: ${err.message}`, true);
} finally {
this.inferRunning = false;
}
}
drawGeometryImage(inBchw, outBchw, mask, N) {
if (!this.geoCanvas || !inBchw || !outBchw) return;
const ctx = this.geoCanvas.getContext("2d");
const total = N * N;
const gap = 4;
if (this.geoCanvas.width !== N * 2 + gap || this.geoCanvas.height !== N) {
this.geoCanvas.width = N * 2 + gap;
this.geoCanvas.height = N;
}
ctx.fillStyle = "#171c23";
ctx.fillRect(0, 0, this.geoCanvas.width, N);
const drawGrid = (bchw, offsetX) => {
const img = ctx.createImageData(N, N);
for (let py = 0; py < N; py++) {
for (let px = 0; px < N; px++) {
const g = py * N + px;
const pIdx = (py * N + px) * 4;
if (mask[g] > 0) {
img.data[pIdx] = Math.max(0, Math.min(255, Math.round((bchw[g] + 1) * 127.5)));
img.data[pIdx + 1] = Math.max(0, Math.min(255, Math.round((bchw[total + g] + 1) * 127.5)));
img.data[pIdx + 2] = Math.max(0, Math.min(255, Math.round((bchw[2 * total + g] + 1) * 127.5)));
img.data[pIdx + 3] = 255;
} else {
img.data[pIdx] = 28;
img.data[pIdx + 1] = 35;
img.data[pIdx + 2] = 46;
img.data[pIdx + 3] = 255;
}
}
}
ctx.putImageData(img, offsetX, 0);
};
drawGrid(inBchw, 0);
drawGrid(outBchw, N + gap);
}
rebuildCageObjects() {
this.vp.clearGroup(this.cageGroup);
this.cageSpheres = [];
this.cageEdgeBase = null;
this.cageEdgeHi = null;
this.cageMovedRays = null;
if (!this.cage) return;
this.cageEdgeBase = new THREE.LineSegments(
new THREE.BufferGeometry(),
new THREE.LineBasicMaterial({ color: 0x64748b, transparent: true, opacity: 0.72 })
);
this.cageEdgeHi = new THREE.LineSegments(
new THREE.BufferGeometry(),
new THREE.LineBasicMaterial({ color: 0xc83e37, transparent: true, opacity: 0.96 })
);
this.cageMovedRays = new THREE.LineSegments(
new THREE.BufferGeometry(),
new THREE.LineBasicMaterial({ color: 0x94a3b8, transparent: true, opacity: 0.5 })
);
this.cageGroup.add(this.cageEdgeBase, this.cageEdgeHi, this.cageMovedRays);
const sphereGeo = new THREE.SphereGeometry(0.042, 18, 18);
const haloGeo = new THREE.RingGeometry(0.056, 0.072, 28);
for (let idx = 0; idx < this.cage.nNodes; idx++) {
const mat = new THREE.MeshStandardMaterial({
color: 0x1d4e89,
emissive: 0x0b1f38,
roughness: 0.24,
metalness: 0.14,
});
const sphere = new THREE.Mesh(sphereGeo.clone(), mat);
const halo = new THREE.Mesh(
haloGeo.clone(),
new THREE.MeshBasicMaterial({ color: 0xc83e37, side: THREE.DoubleSide, transparent: true, opacity: 0.92 })
);
halo.visible = false;
halo.userData.isBillboard = true;
sphere.add(halo);
sphere.userData.nodeIdx = idx;
sphere.userData.halo = halo;
this.cageGroup.add(sphere);
this.cageSpheres.push(sphere);
}
sphereGeo.dispose();
haloGeo.dispose();
this._syncCageNodeStyles();
this.syncViewportChrome();
}
updateCageVisuals() {
if (!this.cage || !this.activeNodes) return;
for (let i = 0; i < this.cageSpheres.length; i++) {
this.cageSpheres[i].position.set(
this.activeNodes[i * 3],
this.activeNodes[i * 3 + 1],
this.activeNodes[i * 3 + 2]
);
}
const activeIdx = this.draggingNode >= 0 ? this.draggingNode : this.hoveredNode;
const { basePos, hiPos, movedRays } = this.cage.getWireframeEdgeSegments(this.activeNodes, this.params, activeIdx);
const isDark = this.vp.theme === "dark";
if (this.cageEdgeBase) {
this.cageEdgeBase.geometry.dispose();
this.cageEdgeBase.geometry = new THREE.BufferGeometry();
this.cageEdgeBase.geometry.setAttribute("position", new THREE.BufferAttribute(basePos, 3));
this.cageEdgeBase.material.color.setHex(isDark ? 0x94a3b8 : 0x64748b);
}
if (this.cageEdgeHi) {
this.cageEdgeHi.geometry.dispose();
this.cageEdgeHi.geometry = new THREE.BufferGeometry();
this.cageEdgeHi.geometry.setAttribute("position", new THREE.BufferAttribute(hiPos, 3));
}
if (this.cageMovedRays) {
this.cageMovedRays.geometry.dispose();
this.cageMovedRays.geometry = new THREE.BufferGeometry();
this.cageMovedRays.geometry.setAttribute("position", new THREE.BufferAttribute(movedRays, 3));
}
}
_populatePatchGroup(group, verts, faces, signedK, maxK, boundaryEdges, ghostVerts, ghostFaces, isRight) {
const nVerts = verts.length / 3;
const geom = new THREE.BufferGeometry();
geom.setAttribute("position", new THREE.BufferAttribute(new Float32Array(verts), 3));
geom.setIndex(faces);
geom.computeVertexNormals();
let mat;
if (this.patchShading === "zebra") {
mat = createZebraMaterial();
} else {
const colors = new Float32Array(nVerts * 3);
if (this.patchShading === "curvature") {
for (let i = 0; i < nVerts; i++) {
const [r, g, b] = bwrCurvatureRGB(signedK[i], maxK);
colors[i * 3] = r; colors[i * 3 + 1] = g; colors[i * 3 + 2] = b;
}
} else if (this.patchShading === "steel") {
for (let i = 0; i < nVerts; i++) {
colors[i * 3] = STEEL_LINEAR[0]; colors[i * 3 + 1] = STEEL_LINEAR[1]; colors[i * 3 + 2] = STEEL_LINEAR[2];
}
} else {
for (let i = 0; i < nVerts; i++) {
colors[i * 3] = CLAY_LINEAR[0]; colors[i * 3 + 1] = CLAY_LINEAR[1]; colors[i * 3 + 2] = CLAY_LINEAR[2];
}
}
geom.setAttribute("color", new THREE.BufferAttribute(colors, 3));
mat = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: this.patchShading === "steel" ? 0.44 : 0.42,
metalness: this.patchShading === "steel" ? 0.08 : 0.04,
envMapIntensity: 0.42,
side: THREE.DoubleSide,
polygonOffset: true,
polygonOffsetFactor: 1,
polygonOffsetUnits: 1,
});
}
group.add(new THREE.Mesh(geom, mat));
const drawWire = this.showWireframe || this.patchShading === "steel";
if (drawWire) {
const wireOp = this.patchShading === "steel" ? (this.showWireframe ? 0.30 : 0.21) : 0.16;
const wireCol = this.patchShading === "steel"
? (this.vp.theme === "dark" ? 0x101c2d : 0x1b2c40)
: (this.vp.theme === "dark" ? 0x9eb8de : 0x243447);
group.add(new THREE.Mesh(geom.clone(), new THREE.MeshBasicMaterial({
color: wireCol,
wireframe: true,
transparent: true,
opacity: wireOp,
})));
}
if (boundaryEdges && boundaryEdges.length > 0) {
const bPos = new Float32Array(boundaryEdges.length * 3);
for (let k = 0; k < boundaryEdges.length; k++) {
const vi = boundaryEdges[k];
bPos[k * 3] = verts[vi * 3]; bPos[k * 3 + 1] = verts[vi * 3 + 1]; bPos[k * 3 + 2] = verts[vi * 3 + 2];
}
const bGeo = new THREE.BufferGeometry();
bGeo.setAttribute("position", new THREE.BufferAttribute(bPos, 3));
const bMat = new THREE.LineBasicMaterial({
color: this.vp.theme === "dark" ? 0x7cb0f5 : 0x163866,
transparent: true,
opacity: 0.88,
});
group.add(new THREE.LineSegments(bGeo, bMat));
}
if (isRight && ghostVerts && ghostFaces) {
const ghostGeo = new THREE.BufferGeometry();
ghostGeo.setAttribute("position", new THREE.BufferAttribute(new Float32Array(ghostVerts), 3));
ghostGeo.setIndex(ghostFaces);
const ghostMat = new THREE.MeshBasicMaterial({
color: 0x627080,
wireframe: true,
transparent: true,
opacity: 0.16,
});
this.ghostMesh = new THREE.Mesh(ghostGeo, ghostMat);
this.ghostMesh.visible = this.showGhost;
group.add(this.ghostMesh);
}
}
_getCurrentKStats() {
const patch = this.activePatch;
const defV = this.deformedVerts || patch.vertices;
const disp = this.displayedVerts || defV;
const kIn = computeSignedGaussianCurvature(defV, patch.faces, patch.interior_mask);
const maxK = computeAdaptiveMaxK(kIn.signedK, patch.interior_mask, 0.006, 0.06);
const usingRef = this.outputMode === "ref" && patch.ref_vertices && this._isDeformationUntouched();
const outFaces = usingRef && patch.ref_faces ? patch.ref_faces : patch.faces;
const outBnd = usingRef && patch.ref_boundary_edges ? patch.ref_boundary_edges : patch.boundary_edges;
const outInt = usingRef && patch.ref_interior_mask ? patch.ref_interior_mask : patch.interior_mask;
const kOut = computeSignedGaussianCurvature(disp, outFaces, outInt);
return { defV, disp, kIn, maxK, usingRef, outFaces, outBnd, kOut };
}
renderInputSide() {
if (!this.activePatch) return;
const patch = this.activePatch;
const defV = this.deformedVerts || patch.vertices;
this.vp.clearGroup(this.vp.groupInput);
const kIn = computeSignedGaussianCurvature(defV, patch.faces, patch.interior_mask);
const maxK = computeAdaptiveMaxK(kIn.signedK, patch.interior_mask, 0.006, 0.06);
this._populatePatchGroup(
this.vp.groupInput,
defV,
patch.faces,
kIn.signedK,
maxK,
patch.boundary_edges,
null,
null,
false
);
this.updateCageVisuals();
const el = this.root.querySelector("#vp-badge-left");
if (el) el.textContent = `INPUT · |K| ${kIn.kMean.toFixed(5)} rad`;
}
renderOutputSide() {
if (!this.activePatch || !this.displayedVerts) return;
const patch = this.activePatch;
const { defV, disp, maxK, outFaces, outBnd, kOut } = this._getCurrentKStats();
this.vp.clearGroup(this.vp.groupOutput);
this.ghostMesh = null;
this._populatePatchGroup(
this.vp.groupOutput,
disp,
outFaces,
kOut.signedK,
maxK,
outBnd,
defV,
patch.faces,
true
);
}
updatePatchHUD() {
if (!this.activePatch || !this.displayedVerts) return;
const patch = this.activePatch;
const { defV, disp, kIn, maxK, usingRef, kOut } = this._getCurrentKStats();
const dHa = usingRef && patch.ref_metrics ? patch.ref_metrics.d_Ha : computeMeanVertexShiftPct(defV, disp);
const pctDrop = kIn.kMean > 1e-8 ? ((kIn.kMean - kOut.kMean) / kIn.kMean) * 100.0 : 0.0;
const dropTxt = `${pctDrop >= 0 ? "-" : "+"}${Math.abs(pctDrop).toFixed(1)}%`;
const setTxt = (s, t) => { const el = this.root.querySelector(s); if (el) el.textContent = t; };
setTxt("#vp-badge-left", `INPUT · |K| ${kIn.kMean.toFixed(5)} rad`);
let rBadge = `ONNX OUTPUT · |K| ${kOut.kMean.toFixed(5)} (${dropTxt})`;
if (usingRef) rBadge = `STAGE 2 REF · |K| ${kOut.kMean.toFixed(5)} (${dropTxt})`;
else if (this.outputMode === "raw") rBadge = `RAW INPUT · |K| ${kOut.kMean.toFixed(5)}`;
setTxt("#vp-badge-right", rBadge);
setTxt("#hud-kmean", `${kIn.kMean.toFixed(5)} -> ${kOut.kMean.toFixed(5)} (${dropTxt})`);
setTxt("#hud-kmax", `${kOut.kMax.toFixed(5)} rad`);
setTxt("#hud-dha", `${dHa.toFixed(3)}%`);
setTxt("#hud-latency", usingRef ? "Paper Stage 2" : this.outputMode === "raw" ? "0.0 ms" : `${this.lastOnnxMs.toFixed(1)} ms (WASM)`);
const legEl = this.root.querySelector("#studio-legend-patch");
if (legEl) {
if (this.patchShading === "curvature") {
legEl.innerHTML = `<span class="legend-title">Signed K (bwr):</span><span>-${maxK.toFixed(3)} Saddle</span><span class="legend-bar legend-bwr"></span><span>0 (Developable)</span><span class="legend-title">+${maxK.toFixed(3)} Dome</span>`;
} else if (this.patchShading === "zebra") {
legEl.innerHTML = `<span class="legend-title">Zebra Rulings:</span><span>Straight parallel reflection bands highlight zero-Gaussian rulings</span>`;
} else if (this.patchShading === "steel") {
legEl.innerHTML = `<span class="legend-title">CAD Steel (Fig. 7):</span><span>Crisp wireframe mesh + Cobalt/Vermilion 3D Lattice Control Cage</span>`;
} else {
legEl.innerHTML = `<span class="legend-title">Material:</span><span>Smooth PBR Ceramic Clay + UV Boundary Outline</span>`;
}
}
}
renderPatchScene() {
if (!this.activePatch || !this.displayedVerts) return;
this.renderInputSide();
this.renderOutputSide();
this.updatePatchHUD();
if (this.vp.renderNow) this.vp.renderNow();
}
exportCurrentObj(side = "output") {
if (!this.activePatch) return;
const isRef = this.outputMode === "ref" && this.activePatch.ref_faces && this._isDeformationUntouched();
if (side === "input" && this.deformedVerts) {
downloadObjText(`${this.activePatch.name}_input.obj`, this.deformedVerts, this.activePatch.faces);
} else if (this.displayedVerts) {
downloadObjText(`${this.activePatch.name}_opt.obj`, this.displayedVerts, isRef ? this.activePatch.ref_faces : this.activePatch.faces);
}
}
async runLocalPostprocess() {
if (!this.config.hasLocalBackend || !this.activePatch || !this.displayedVerts) return;
try {
this.setStatus("Running Stage 2 SciPy interior optimization...");
const res = await fetch("/api/postprocess", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
vertices: Array.from(this.displayedVerts),
orig_vertices: Array.from(this.deformedVerts || this.displayedVerts),
faces: this.activePatch.faces,
}),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
this.displayedVerts = new Float64Array(data.vertices);
this.lastOnnxMs = data.ms;
this.renderPatchScene();
this.setStatus(`Stage 2 Interior Refine done in ${data.ms.toFixed(1)} ms`);
} catch (err) {
this.setStatus(`Local refine failed: ${err.message}`, true);
}
}
async downloadPapercraftPdf() {
if (!this.config.hasLocalBackend || !this.activePatch || !this.displayedVerts) return;
try {
this.setStatus("Generating A4 unfolded papercraft PDF...");
const res = await fetch("/api/papercraft_pdf", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: this.activePatch.name,
vertices: Array.from(this.displayedVerts),
faces: this.activePatch.faces,
}),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const blob = await res.blob();
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = `${this.activePatch.name}_papercraft_a4.pdf`;
a.click();
URL.revokeObjectURL(a.href);
this.setStatus("Downloaded A4 papercraft PDF");
} catch (err) {
this.setStatus(`PDF export failed: ${err.message}`, true);
}
}
/* ----- Dynamic 29-Patch Gallery Rendering ----- */
renderGalleryCategories() {
const tabsWrap = document.getElementById("patches-cat-tabs");
const gridWrap = document.getElementById("patches-gallery-grid");
if (!tabsWrap || !gridWrap || !this.manifest?.categories) return;
let activeCat = "fig09_model";
const renderCards = (catId) => {
activeCat = catId;
tabsWrap.querySelectorAll("button").forEach((b) =>
b.classList.toggle("active", b.dataset.cat === catId)
);
const items = this.manifest.patches.filter((p) => p.category === catId);
gridWrap.innerHTML = items.map((p) => {
const dropBadge = p.has_ref
? `<span class="pg-drop">-${p.ref_drop_pct.toFixed(1)}% |K|</span>`
: `<span class="pg-drop pg-core">ONNX Preset</span>`;
const subMeta = p.has_ref
? `d<sub>H-a</sub> ${p.ref_d_ha.toFixed(3)}% · ${p.num_vertices.toLocaleString()}v`
: `${p.num_vertices.toLocaleString()}v · ${p.num_faces.toLocaleString()}f`;
return `
<button type="button" class="card patch-gallery-card ${this.activePatch?.name === p.name ? "active" : ""}" data-patch-card="${p.name}">
<div class="pg-top"><strong>${p.label}</strong>${dropBadge}</div>
<div class="pg-meta">${subMeta}</div>
<div class="pg-cta">Inspect in Live 3D Studio ↑</div>
</button>`;
}).join("");
gridWrap.querySelectorAll(".patch-gallery-card").forEach((btn) => {
btn.addEventListener("click", async () => {
const pName = btn.dataset.patchCard;
await this.loadPresetPatch(pName, true);
this.root.scrollIntoView({ behavior: "smooth", block: "start" });
});
});
};
tabsWrap.innerHTML = this.manifest.categories.map((c) => {
const cnt = this.manifest.patches.filter((p) => p.category === c.id).length;
return `<button type="button" class="tab-btn ${c.id === activeCat ? "active" : ""}" data-cat="${c.id}">${c.label} (${cnt})</button>`;
}).join("");
tabsWrap.querySelectorAll("button").forEach((b) => {
b.addEventListener("click", () => renderCards(b.dataset.cat));
});
renderCards(activeCat);
}
}
/* ---------- Workbench 2: Full 3D Model & Pipeline Comparator ---------- */
const MODEL_VIEW_DIRS = {
bunny: [-0.36, 0.25, 0.90],
dog: [-0.32, 0.24, -0.92],
kitten: [-0.34, 0.22, 0.91],
};
class ModelExplorerController {
constructor(rootEl) {
this.root = rootEl;
this.config = getConfig();
this.modelCache = new Map();
this.activeModelName = "bunny";
this.activeModelAsset = null;
this.leftVariant = "input";
this.rightVariant = "ours_final";
this.modelShading = "patches"; // "patches" | "curvature" | "hausdorff" | "clay"
this.explodePct = 0;
this.showSeams = true;
this.showWireframe = false;
this._firstLoad = true;
this.vp = new DualStudioViewport(this.root.querySelector("#model-canvas-wrap"), { splitView: true });
this.bindUI();
this.bindTable1Rows();
this.loadModelAsset("bunny");
}
_curViewDir() {
return MODEL_VIEW_DIRS[this.activeModelName] || [-0.35, 0.24, 0.90];
}
bindUI() {
const q = (s) => this.root.querySelector(s);
this.root.querySelectorAll("[data-model-view]").forEach((btn) => {
btn.addEventListener("click", () => {
this.vp.splitView = btn.dataset.modelView === "split";
this.root.querySelectorAll("[data-model-view]").forEach((b) => b.classList.toggle("active", b === btn));
const div = q("#model-vp-divider");
const lBadge = q("#model-badge-left");
if (div) div.classList.toggle("hidden", !this.vp.splitView);
if (lBadge) lBadge.classList.toggle("hidden", !this.vp.splitView);
const lv = this.activeModelAsset?.variants?.[this.leftVariant] || this.activeModelAsset?.variants?.input;
if (lv) this.vp.fitCameraToBounds(lv.vertices, this._curViewDir(), 1.34, false);
});
});
const themeBtn = q("#btn-model-theme");
if (themeBtn) {
themeBtn.addEventListener("click", () => {
const next = this.vp.theme === "light" ? "dark" : "light";
this.vp.applyTheme(next);
themeBtn.textContent = next === "dark" ? "Light Studio" : "Dark CAD";
themeBtn.classList.toggle("active", next === "dark");
this.renderModelScene();
});
}
const autoBtn = q("#btn-model-autorotate");
if (autoBtn) {
autoBtn.addEventListener("click", () => {
this.vp.autoRotate = !this.vp.autoRotate;
autoBtn.classList.toggle("active", this.vp.autoRotate);
});
}
const camBtn = q("#btn-model-reset-cam");
if (camBtn) {
camBtn.addEventListener("click", () => {
const lv = this.activeModelAsset?.variants?.[this.leftVariant] || this.activeModelAsset?.variants?.input;
if (lv) this.vp.fitCameraToBounds(lv.vertices, this._curViewDir(), 1.34, false);
});
}
this.root.querySelectorAll("[data-model-name]").forEach((btn) => {
btn.addEventListener("click", () => {
this.loadModelAsset(btn.dataset.modelName);
});
});
this.root.querySelectorAll("[data-model-left]").forEach((btn) => {
btn.addEventListener("click", () => {
if (btn.disabled) return;
this.leftVariant = btn.dataset.modelLeft;
this._clearStageActive();
this._syncVariantButtons();
this.renderModelScene();
});
});
this.root.querySelectorAll("[data-model-right]").forEach((btn) => {
btn.addEventListener("click", () => {
if (btn.disabled) return;
this.rightVariant = btn.dataset.modelRight;
this._clearStageActive();
this._syncVariantButtons();
this.renderModelScene();
});
});
const STAGES = [
["input", "seg_input"],
["seg_input", "ours_before_merge"],
["ours_before_merge", "ours_final"],
["input", "ours_final"],
];
this.root.querySelectorAll("[data-stage-step]").forEach((btn) => {
btn.addEventListener("click", () => {
const idx = parseInt(btn.dataset.stageStep, 10);
const [lv, rv] = STAGES[idx] || STAGES[3];
this.leftVariant = lv;
this.rightVariant = rv;
this.root.querySelectorAll("[data-stage-step]").forEach((b) => b.classList.toggle("active", b === btn));
this._syncVariantButtons();
this.renderModelScene();
});
});
this.root.querySelectorAll("[data-model-shading]").forEach((btn) => {
btn.addEventListener("click", () => {
this.modelShading = btn.dataset.modelShading;
this.root.querySelectorAll("[data-model-shading]").forEach((b) => b.classList.toggle("active", b === btn));
this.renderModelScene();
});
});
const expSlider = q("#slider-explode");
const expVal = q("#val-explode");
if (expSlider) {
expSlider.addEventListener("input", () => {
this.explodePct = parseFloat(expSlider.value);
if (expVal) expVal.textContent = `${Math.round(this.explodePct)}%`;
this.renderModelScene();
});
}
const seamChk = q("#chk-seams");
if (seamChk) {
seamChk.addEventListener("change", () => {
this.showSeams = seamChk.checked;
this.renderModelScene();
});
}
const wireChk = q("#chk-model-wire");
if (wireChk) {
wireChk.addEventListener("change", () => {
this.showWireframe = wireChk.checked;
this.renderModelScene();
});
}
const exL = q("#btn-model-export-left");
if (exL) exL.addEventListener("click", () => this.exportVariantObj(this.leftVariant));
const exR = q("#btn-model-export-right");
if (exR) exR.addEventListener("click", () => this.exportVariantObj(this.rightVariant));
}
bindTable1Rows() {
document.querySelectorAll("#table1-interactive tbody tr[data-t1-model]").forEach((row) => {
row.addEventListener("click", async () => {
document.querySelectorAll("#table1-interactive tbody tr").forEach((r) => r.classList.remove("row-selected"));
row.classList.add("row-selected");
const model = row.dataset.t1Model;
const leftV = row.dataset.t1Left;
const rightV = row.dataset.t1Right || "ours_final";
this.leftVariant = leftV;
this.rightVariant = rightV;
this._clearStageActive();
await this.loadModelAsset(model);
this.root.scrollIntoView({ behavior: "smooth", block: "nearest" });
});
});
}
_clearStageActive() {
this.root.querySelectorAll("[data-stage-step]").forEach((b) => b.classList.remove("active"));
}
_syncVariantButtons() {
this.root.querySelectorAll("[data-model-name]").forEach((b) =>
b.classList.toggle("active", b.dataset.modelName === this.activeModelName)
);
const vars = this.activeModelAsset?.variants || {};
this.root.querySelectorAll("[data-model-left]").forEach((b) => {
const avail = Boolean(vars[b.dataset.modelLeft]);
b.disabled = !avail;
b.classList.toggle("hidden", !avail);
b.classList.toggle("active", b.dataset.modelLeft === this.leftVariant);
});
this.root.querySelectorAll("[data-model-right]").forEach((b) => {
const avail = Boolean(vars[b.dataset.modelRight]);
b.disabled = !avail;
b.classList.toggle("hidden", !avail);
b.classList.toggle("active", b.dataset.modelRight === this.rightVariant);
});
}
setStatus(msg, isError = false) {
const el = this.root.querySelector("#model-status");
if (el) {
el.textContent = msg;
el.classList.toggle("is-error", isError);
}
}
async loadModelAsset(name) {
try {
const changedModel = this.activeModelName !== name || this._firstLoad;
this.activeModelName = name;
this.setStatus(`Loading 3D model "${name}"...`);
let asset = this.modelCache.get(name);
if (!asset) {
const res = await fetch(`${this.config.assetsBase}/models/${name}.json`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
asset = await res.json();
this.modelCache.set(name, asset);
}
this.activeModelAsset = asset;
if (!asset.variants[this.leftVariant]) this.leftVariant = "input";
if (!asset.variants[this.rightVariant]) this.rightVariant = "ours_final";
this._syncVariantButtons();
const lv = asset.variants[this.leftVariant] || asset.variants.input;
if (lv && changedModel) {
this.vp.fitCameraToBounds(lv.vertices, this._curViewDir(), 1.34, true);
this._firstLoad = false;
}
this.renderModelScene();
if (this.vp.renderNow) this.vp.renderNow();
} catch (err) {
this.setStatus(`Model load failed: ${err.message}`, true);
}
}
_populateSmoothModelGroup(group, variant, variantKey, sharedMaxK) {
const verts = variant.vertices;
const faces = variant.faces;
const nVerts = variant.num_vertices;
const vPatch = variant.vertex_patch_ids || new Array(nVerts).fill(0);
const pDirs = variant.patch_dirs;
const gK = variant.gaussian_k;
const hV = variant.hausdorff_v;
const expScale = (this.explodePct / 100.0) * 0.42;
const posArr = new Float32Array(nVerts * 3);
const colArr = new Float32Array(nVerts * 3);
for (let v = 0; v < nVerts; v++) {
const pid = vPatch[v] || 0;
posArr[v * 3] = verts[v * 3] + pDirs[pid * 3] * expScale;
posArr[v * 3 + 1] = verts[v * 3 + 1] + pDirs[pid * 3 + 1] * expScale;
posArr[v * 3 + 2] = verts[v * 3 + 2] + pDirs[pid * 3 + 2] * expScale;
if (this.modelShading === "patches") {
const c = PATCH_PALETTE_LINEAR[pid % PATCH_PALETTE_LINEAR.length];
colArr[v * 3] = c[0]; colArr[v * 3 + 1] = c[1]; colArr[v * 3 + 2] = c[2];
} else if (this.modelShading === "curvature") {
const [r, g, b] = bwrCurvatureRGB(gK[v] || 0, sharedMaxK);
colArr[v * 3] = r; colArr[v * 3 + 1] = g; colArr[v * 3 + 2] = b;
} else if (this.modelShading === "hausdorff") {
const [r, g, b] = hausdorffColorRGB(hV[v] || 0, 1.4);
colArr[v * 3] = r; colArr[v * 3 + 1] = g; colArr[v * 3 + 2] = b;
} else {
colArr[v * 3] = CLAY_LINEAR[0]; colArr[v * 3 + 1] = CLAY_LINEAR[1]; colArr[v * 3 + 2] = CLAY_LINEAR[2];
}
}
const geom = new THREE.BufferGeometry();
geom.setAttribute("position", new THREE.BufferAttribute(posArr, 3));
geom.setAttribute("color", new THREE.BufferAttribute(colArr, 3));
geom.setIndex(faces);
geom.computeVertexNormals();
const mat = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.42,
metalness: 0.05,
envMapIntensity: 0.42,
side: THREE.DoubleSide,
polygonOffset: true,
polygonOffsetFactor: 1,
polygonOffsetUnits: 1,
});
group.add(new THREE.Mesh(geom, mat));
const drawWire = this.showWireframe || this.modelShading === "hausdorff";
if (drawWire) {
const wireCol = this.modelShading === "hausdorff"
? (this.vp.theme === "dark" ? 0x64748b : 0x263140)
: (this.vp.theme === "dark" ? 0x9eb8de : 0x243447);
group.add(new THREE.Mesh(geom.clone(), new THREE.MeshBasicMaterial({
color: wireCol,
wireframe: true,
transparent: true,
opacity: 0.14,
})));
}
if (this.showSeams && variant.seam_edges && variant.seam_edges.length > 0) {
const sPos = new Float32Array(variant.seam_edges.length * 3);
for (let s = 0; s < variant.seam_edges.length; s++) {
const vi = variant.seam_edges[s];
const pid = vPatch[vi] || 0;
sPos[s * 3] = verts[vi * 3] + pDirs[pid * 3] * expScale * 1.004;
sPos[s * 3 + 1] = verts[vi * 3 + 1] + pDirs[pid * 3 + 1] * expScale * 1.004;
sPos[s * 3 + 2] = verts[vi * 3 + 2] + pDirs[pid * 3 + 2] * expScale * 1.004;
}
const sGeo = new THREE.BufferGeometry();
sGeo.setAttribute("position", new THREE.BufferAttribute(sPos, 3));
const isSegInput = variantKey === "seg_input";
const seamCol = isSegInput
? (this.vp.theme === "dark" ? 0xf87171 : 0xb91c1c)
: (this.vp.theme === "dark" ? 0xe5edf8 : 0x171c23);
const sMat = new THREE.LineBasicMaterial({
color: seamCol,
transparent: true,
opacity: isSegInput ? 0.96 : 0.88,
});
group.add(new THREE.LineSegments(sGeo, sMat));
}
}
renderModelScene() {
if (!this.activeModelAsset) return;
const leftVar = this.activeModelAsset.variants[this.leftVariant] || this.activeModelAsset.variants.input;
const rightVar = this.activeModelAsset.variants[this.rightVariant] || this.activeModelAsset.variants.ours_final;
if (!leftVar || !rightVar) return;
this.vp.clearGroup(this.vp.groupInput);
this.vp.clearGroup(this.vp.groupOutput);
let sharedMaxK = 0.02;
if (this.modelShading === "curvature") {
const hasNonZeroLeft = leftVar.metrics.K_mean > 1e-4;
const refKVar = hasNonZeroLeft ? leftVar : (this.activeModelAsset.variants.input || leftVar);
sharedMaxK = computeAdaptiveMaxK(refKVar.gaussian_k, null, 0.008, 0.06);
}
this._populateSmoothModelGroup(this.vp.groupInput, leftVar, this.leftVariant, sharedMaxK);
this._populateSmoothModelGroup(this.vp.groupOutput, rightVar, this.rightVariant, sharedMaxK);
if (this.vp.renderNow) this.vp.renderNow();
const lm = leftVar.metrics;
const rm = rightVar.metrics;
const setTxt = (s, t) => { const el = this.root.querySelector(s); if (el) el.textContent = t; };
setTxt("#model-badge-left", `${leftVar.label.toUpperCase()} · ${lm.N_P}p | d_Ha ${lm.d_Ha.toFixed(3)}%`);
setTxt("#model-badge-right", `${rightVar.label.toUpperCase()} · ${rm.N_P}p | d_Ha ${rm.d_Ha.toFixed(3)}%`);
setTxt("#hud-model-np", `${lm.N_P}p -> ${rm.N_P}p`);
setTxt("#hud-model-kmean", `${lm.K_mean.toFixed(5)} -> ${rm.K_mean.toFixed(5)} rad`);
setTxt("#hud-model-kmax", `${rm.K_max.toFixed(5)} rad`);
setTxt("#hud-model-dha", `${rm.d_Ha.toFixed(3)}% (H99: ${rm.d_H99.toFixed(3)}%)`);
this.setStatus(`Comparing ${this.activeModelAsset.title}: ${leftVar.label} vs ${rightVar.label}`);
const leg = this.root.querySelector("#studio-legend-model");
if (leg) {
if (this.modelShading === "curvature") {
leg.innerHTML = `<span class="legend-title">Signed K (bwr):</span><span>-${sharedMaxK.toFixed(3)} Saddle</span><span class="legend-bar legend-bwr"></span><span>0 (Developable)</span><span>+${sharedMaxK.toFixed(3)} Dome</span>`;
} else if (this.modelShading === "hausdorff") {
leg.innerHTML = `<span class="legend-title">Hausdorff d_H:</span><span>0.0% (Exact)</span><span class="legend-bar legend-haus"></span><span>1.4%+ diag</span>`;
} else if (this.modelShading === "patches") {
leg.innerHTML = `<span class="legend-title">Smooth PBR Patches:</span><span>Calibrated paper-toned developable shells with sharp crease seams</span>`;
} else {
leg.innerHTML = `<span class="legend-title">Clay Material:</span><span>Warm alabaster PBR clay highlighting normal continuity & crease seams</span>`;
}
}
}
exportVariantObj(vKey) {
const v = this.activeModelAsset?.variants?.[vKey];
if (!v) return;
downloadObjText(`${this.activeModelAsset.name}_${vKey}.obj`, v.vertices, v.faces);
}
}
/* ---------- Bootstrapper ---------- */
document.addEventListener("DOMContentLoaded", () => {
const cfg = getConfig();
const sharedEngine = new WebNeuralOptimizer(cfg.modelsBase, cfg.fallbackModelsBase);
const patchRoot = document.getElementById("idevnet-patch-studio");
if (patchRoot) {
window.__idevnetPatchStudio = new PatchStudioController(patchRoot, sharedEngine);
}
const modelRoot = document.getElementById("idevnet-model-studio");
if (modelRoot) {
window.__idevnetModelStudio = new ModelExplorerController(modelRoot);
}
document.querySelectorAll("[data-cli-workbench]").forEach((btn) => {
btn.addEventListener("click", () => {
const target = btn.dataset.cliWorkbench;
document.querySelectorAll("[data-cli-workbench]").forEach((b) => b.classList.toggle("active", b === btn));
if (patchRoot) patchRoot.classList.toggle("hidden", target !== "patch");
if (modelRoot) modelRoot.classList.toggle("hidden", target !== "model");
});
});
});
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.js";
const DEFAULT_CONFIG = {
assetsBase: "./assets/studio",
modelsBase: "./assets/models",
fallbackModelsBase: "https://huggingface.co/Chao-Yun/I-DevNet/resolve/main",
hasLocalBackend: false,
};
function getConfig() {
return { ...DEFAULT_CONFIG, ...(window.IDEVNET_STUDIO_CONFIG || {}) };
}
/* ---------- sRGB <-> Linear Conversion & Paper-Calibrated Colormaps ---------- */
function srgbToLinear(c) {
const x = Math.max(0, Math.min(1, c));
return x <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
}
function hexToLinearRGB(hex) {
let num = typeof hex === "number" ? hex : parseInt(String(hex).replace(/^#/, ""), 16);
const r = ((num >> 16) & 255) / 255.0;
const g = ((num >> 8) & 255) / 255.0;
const b = (num & 255) / 255.0;
return [srgbToLinear(r), srgbToLinear(g), srgbToLinear(b)];
}
function mixSrgbToLinear(c0, c1, t) {
const u = Math.max(0, Math.min(1, t));
return [
srgbToLinear(c0[0] + (c1[0] - c0[0]) * u),
srgbToLinear(c0[1] + (c1[1] - c0[1]) * u),
srgbToLinear(c0[2] + (c1[2] - c0[2]) * u),
];
}
const PATCH_PALETTE_HEX = [
"#5B8EC4",
"#6BB8A8",
"#C48ED4",
"#D8C85E",
"#96B83C",
"#E29B63",
"#DF6B55",
"#7DA3DF",
"#9CC27B",
"#A37286",
"#5FA7C4",
"#D48872",
];
const PATCH_PALETTE_LINEAR = PATCH_PALETTE_HEX.map(hexToLinearRGB);
const STEEL_LINEAR = hexToLinearRGB("#5F86B3");
const CLAY_LINEAR = hexToLinearRGB("#DCD9D2");
function computeAdaptiveMaxK(signedK, interiorMask, minVal = 0.006, maxVal = 0.06) {
if (!signedK || signedK.length === 0) return minVal;
const mags = [];
for (let i = 0; i < signedK.length; i++) {
if (!interiorMask || interiorMask[i] > 0) {
const a = Math.abs(signedK[i]);
if (Number.isFinite(a)) mags.push(a);
}
}
if (mags.length === 0) {
for (let i = 0; i < signedK.length; i++) {
const a = Math.abs(signedK[i]);
if (Number.isFinite(a)) mags.push(a);
}
}
if (mags.length === 0) return minVal;
mags.sort((a, b) => a - b);
const idx = Math.min(mags.length - 1, Math.floor(mags.length * 0.92));
return Math.max(minVal, Math.min(maxVal, mags[idx] || minVal));
}
function bwrCurvatureRGB(signedK, maxK = 0.02) {
// #1d56a8 (Saddle K<0) -> #e6e2da (Zero K~0) -> #cc362f (Dome K>0)
const mag = Math.min(1.0, Math.pow(Math.min(1.0, Math.abs(signedK) / Math.max(maxK, 1e-6)), 0.58));
const zero = [0.902, 0.886, 0.855];
if (signedK < 0) {
return mixSrgbToLinear(zero, [0.114, 0.337, 0.659], mag);
}
return mixSrgbToLinear(zero, [0.800, 0.212, 0.184], mag);
}
function hausdorffColorRGB(pct, maxPct = 1.4) {
// Paper Fig. 22-24 scale: #e2dfda (0%) -> #ef7a6d (45%) -> #d62424 (100%)
const t = Math.pow(Math.min(1.0, Math.max(0.0, pct) / Math.max(maxPct, 1e-4)), 0.68);
const c0 = [0.886, 0.875, 0.855];
const c1 = [0.937, 0.478, 0.427];
const c2 = [0.839, 0.141, 0.141];
if (t < 0.45) {
return mixSrgbToLinear(c0, c1, t / 0.45);
}
return mixSrgbToLinear(c1, c2, (t - 0.45) / 0.55);
}