Просмотр исходного кода

path 路由 + 浅色 Apple 风 + 场景 look 图接入

- 路由:hash → History API path(/、/p/<id>、/lab/<id>),支持子路径部署
- base:动态写入站点根,修复深路径下资源 404
- 视觉:浅色为主,Apple 排版语言,段落行距 1.85
- 图片:详情页接入场景 look 图 ×2 + 微距 + 爆炸图(新增 16 张场景图)
- 修复:lab.js 仍用 hash 解析 ID 导致 JSON 解析失败
- 新增 404.html(SPA fallback)、tools/serve.py
liuyuyang 1 день назад
Родитель
Сommit
09106d4e3b

+ 50 - 0
site/404.html

@@ -0,0 +1,50 @@
+<!doctype html>
+<html lang="zh-CN">
+<head>
+  <meta charset="utf-8" />
+  <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover" />
+  <meta name="theme-color" content="#ffffff" media="(prefers-color-scheme: light)" />
+  <meta name="theme-color" content="#000000" media="(prefers-color-scheme: dark)" />
+  <title>Pocket Hardware Lab · FmodeCode</title>
+  <meta name="generator" content="FmodeCode" />
+  <meta name="description" content="把一款 AI 硬件,从想法做到能报价下单:外壳参数、物料清单、生产工艺与成本测算。FmodeCode 出品。" />
+  <!-- 部署基址:path 路由下 /p/<id> 是深路径,相对 base 会解析成 /p/ 导致资源全 404,
+       所以这里同步算出站点根并写入 base 元素,必须在任何相对 URL 解析之前完成。 -->
+  <script>
+    (function () {
+      var path = location.pathname;
+      var dir = path.replace(/[^/]*\.html?$/, '');
+      dir = dir.replace(/\/(p|lab)\/[^/]+\/?$/, '/');
+      if (dir.charAt(dir.length - 1) !== '/') dir += '/';
+      var b = document.createElement('base');
+      b.href = dir;
+      document.head.appendChild(b);
+    })();
+  </script>
+  <link rel="stylesheet" href="./assets/theme.css" />
+  <meta name="application-name" content="FmodeCode" />
+  <meta name="author" content="FmodeCode" />
+  <meta name="color-scheme" content="light dark" />
+  <link rel="stylesheet" href="./assets/app.css" />
+  <script type="importmap">
+  {
+    "imports": {
+      "lit": "./vendor/lit/lit/index.js",
+      "lit/": "./vendor/lit/lit/",
+      "lit-html": "./vendor/lit/lit-html/lit-html.js",
+      "lit-html/": "./vendor/lit/lit-html/",
+      "lit-element/lit-element.js": "./vendor/lit/lit-element/lit-element.js",
+      "lit-element/": "./vendor/lit/lit-element/",
+      "@lit/reactive-element": "./vendor/lit/@lit/reactive-element/reactive-element.js",
+      "@lit/reactive-element/": "./vendor/lit/@lit/reactive-element/",
+      "@lit-labs/signals": "./vendor/lit/@lit-labs/signals/index.js",
+      "signal-polyfill": "./vendor/signal-polyfill/dist/index.js"
+    }
+  }
+  </script>
+</head>
+<body>
+  <div id="app"><div class="boot">Pocket Hardware Lab 载入中…</div></div>
+  <script type="module" src="./app.js"></script>
+</body>
+</html>

+ 3 - 1
site/app.js

@@ -29,7 +29,9 @@ async function paint() {
   const r = router.resolve();
   let el;
   try {
-    el = await r.render({ path: r.path, params: r.params, navigate: router.navigate });
+    el = await r.render({ path: r.path, params: r.params, route: r.route, navigate: router.navigate, router });
+    if (r.route === '*') document.documentElement.dataset.route = '404';
+    else delete document.documentElement.dataset.route;
   } catch (err) {
     console.error(err);
     el = document.createElement('ph-error');

BIN
site/assets/look/ai-pin-scene-suit.png


BIN
site/assets/look/ai-pin-scene-walk.png


BIN
site/assets/look/bone-headset-scene-bike.png


BIN
site/assets/look/bone-headset-scene-run.png


BIN
site/assets/look/eink-tag-scene-desk.png


BIN
site/assets/look/eink-tag-scene-kitchen.png


BIN
site/assets/look/pocket-ai-scene-cafe.png


BIN
site/assets/look/pocket-ai-scene-train.png


BIN
site/assets/look/recorder-bean-scene-interview.png


BIN
site/assets/look/recorder-bean-scene-pocket.png


BIN
site/assets/look/round-screen-scene-bedside.png


BIN
site/assets/look/round-screen-scene-desk.png


BIN
site/assets/look/smart-ring-scene-sleep.png


BIN
site/assets/look/smart-ring-scene-work.png


BIN
site/assets/look/watch-case-scene-desk.png


BIN
site/assets/look/watch-case-scene-outdoor.png


+ 927 - 0
site/core/geometry/solid.js

@@ -0,0 +1,927 @@
+/**
+ * core/geometry/solid.js —— 参数化壳体几何引擎(纯函数,零 DOM / 零 Babylon,Node 可测)。
+ *
+ * 坐标:X 向右、Y 向上、Z 向前,单位 mm;壳体外底面中心 = 原点,壳高沿 +Y。
+ *
+ * 构造方法(所有主壳通用):把截面离散成「若干条同点数的水平环」(外环 → 内环 → 屏孔环),
+ * 相邻两条环之间用桥接四边形连成水平环带;竖直壁 = 环沿 Y 的挤出;封口 = 环内三角扇。
+ * 所有三角形统一取 (a,b,c) 绕向,使几何法线 (p2−p1)×(p3−p1) 朝外(Babylon 约定),
+ * 面板的朝向在构造参数里显式给出,不靠运行时猜绕向 —— 结果拓扑干净,可直接进 CSG / STL。
+ *
+ * 结构件(形体库 14 类)生成密闭切割体;工艺校验、内腔包络、派生尺寸、需求单文本也在这里。
+ */
+
+export const PRIMS = {
+  box:    { n: '方块',          short: '基础', d: { w: 8, h: 6, dd: 8 } },
+  cyl:    { n: '圆柱',          short: '基础', d: { dia: 10, h: 8 } },
+  rib:    { n: '加强筋',        short: '基础', d: { w: 14, h: 5, dd: 1.2 } },
+  pocket: { n: '凹槽(铣削)',  short: '基础', d: { w: 10, h: 2, dd: 10 } },
+  hole:   { n: '开孔(钻孔)',  short: '基础', d: { dia: 3, h: 4 } },
+  boss2:  { n: '螺丝柱 M2',     short: '紧固', d: { dia: 4.0, h: 7, dd: 1.6 } },
+  boss25: { n: '螺丝柱 M2.5',   short: '紧固', d: { dia: 4.8, h: 8, dd: 2.1 } },
+  boss3:  { n: '螺丝柱 M3',     short: '紧固', d: { dia: 5.6, h: 9, dd: 2.6 } },
+  thru25: { n: 'M2.5 过孔',     short: '紧固', d: { dia: 2.7, h: 4, dd: 2.7 } },
+  pin3:   { n: '定位销 Ø3',     short: '紧固', d: { dia: 3, h: 4 } },
+  pad4:   { n: '四角柱组 M2.5', short: '腔体', d: { w: 30, h: 7, dd: 30, dia: 4.8, hd: 2.1 } },
+  wall:   { n: '分隔墙',        short: '腔体', d: { w: 20, h: 6, dd: 0.8 } },
+  tray:   { n: '电池仓',        short: '腔体', d: { w: 22, h: 6, dd: 18 } },
+  clip:   { n: '卡扣',          short: '腔体', d: { w: 5, h: 4, dd: 1.2 } },
+};
+export const PRIM_KEYS = Object.keys(PRIMS);
+export const HOLLOW_TYPES = ['boss2', 'boss25', 'boss3', 'thru25'];
+export const CYL_TYPES = ['cyl', 'hole', 'pin3', ...HOLLOW_TYPES];
+export const RECT_TYPES = ['box', 'pocket', 'rib', 'wall', 'clip', 'tray'];
+/** 标准自攻预钻孔(mm):M2 / M2.5 / M3 */
+export const STD_PILOT = { boss2: 1.6, boss25: 2.1, boss3: 2.6 };
+
+const TAU = Math.PI * 2;
+const RAD = Math.PI / 180;
+const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
+const r2 = (v) => Math.round(v * 100) / 100;
+const num = (v, d = 0) => (+v || d);
+
+export function primDims(s) {
+  return s.w !== undefined ? [num(s.w), num(s.dd), num(s.h)] : [num(s.dia), num(s.dia), num(s.h)];
+}
+
+/* =========================================================
+   网格工具
+   ========================================================= */
+export function computeNormals(positions, indices) {
+  const n = new Float64Array(positions.length);
+  for (let i = 0; i < indices.length; i += 3) {
+    const a = indices[i] * 3, b = indices[i + 1] * 3, c = indices[i + 2] * 3;
+    const ux = positions[b] - positions[a], uy = positions[b + 1] - positions[a + 1], uz = positions[b + 2] - positions[a + 2];
+    const vx = positions[c] - positions[a], vy = positions[c + 1] - positions[a + 1], vz = positions[c + 2] - positions[a + 2];
+    const nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx;
+    n[a] += nx; n[a + 1] += ny; n[a + 2] += nz;
+    n[b] += nx; n[b + 1] += ny; n[b + 2] += nz;
+    n[c] += nx; n[c + 1] += ny; n[c + 2] += nz;
+  }
+  const out = new Array(positions.length);
+  for (let i = 0; i < n.length; i += 3) {
+    const l = Math.hypot(n[i], n[i + 1], n[i + 2]) || 1;
+    out[i] = n[i] / l; out[i + 1] = n[i + 1] / l; out[i + 2] = n[i + 2] / l;
+  }
+  return out;
+}
+
+/** 有向体积(mm³):封闭、外法向网格为正 */
+export function meshVolume(positions, indices) {
+  let v = 0;
+  for (let i = 0; i < indices.length; i += 3) {
+    const a = indices[i] * 3, b = indices[i + 1] * 3, c = indices[i + 2] * 3;
+    v += (positions[a] * (positions[b + 1] * positions[c + 2] - positions[b + 2] * positions[c + 1])
+      - positions[a + 1] * (positions[b] * positions[c + 2] - positions[b + 2] * positions[c])
+      + positions[a + 2] * (positions[b] * positions[c + 1] - positions[b + 1] * positions[c])) / 6;
+  }
+  return v;
+}
+
+export function bbox(positions) {
+  const mn = [Infinity, Infinity, Infinity], mx = [-Infinity, -Infinity, -Infinity];
+  for (let i = 0; i < positions.length; i += 3) for (let k = 0; k < 3; k++) {
+    const v = positions[i + k]; if (v < mn[k]) mn[k] = v; if (v > mx[k]) mx[k] = v;
+  }
+  return { min: mn, max: mx };
+}
+
+export function mergeMeshes(list) {
+  const positions = [], indices = [];
+  for (const m of list) {
+    if (!m) continue;
+    const base = positions.length / 3;
+    for (const v of m.positions) positions.push(v);
+    for (const i of m.indices) indices.push(i + base);
+  }
+  return { positions, indices };
+}
+
+export function translate(mesh, x, y, z) {
+  const p = mesh.positions.slice();
+  for (let i = 0; i < p.length; i += 3) { p[i] += x; p[i + 1] += y; p[i + 2] += z; }
+  return { positions: p, indices: mesh.indices.slice() };
+}
+
+/** 绕 Y 轴旋转(角度制)后平移 —— 和 Babylon rotation.y = deg 同向 */
+export function rotateY(mesh, deg, tx = 0, ty = 0, tz = 0) {
+  const a = deg * RAD, c = Math.cos(a), s = Math.sin(a);
+  const p = mesh.positions.slice();
+  for (let i = 0; i < p.length; i += 3) {
+    const x = p[i], z = p[i + 2];
+    p[i] = tx + x * c + z * s;
+    p[i + 2] = tz - x * s + z * c;
+    p[i + 1] += ty;
+  }
+  return { positions: p, indices: mesh.indices.slice() };
+}
+
+/* =========================================================
+   环 / 环带 / 竖壁 / 扇面
+   ========================================================= */
+/** 环面积(XZ 平面,>0 = 俯视逆时针);点可为 {x,z} 或 {r}(半径型,自动转 xz) */
+export function ringArea(ring) {
+  let a = 0;
+  for (let i = 0; i < ring.length; i++) {
+    const p = ring[i], q = ring[(i + 1) % ring.length];
+    a += p.x * q.z - q.x * p.z;
+  }
+  return a / 2;
+}
+
+/** 闭合环去重(相邻点 < tol 合并,末点与首点重合去掉) */
+export function dedupeRing(pts, tol = 0.02) {
+  const out = [];
+  for (const p of pts) {
+    const q = out[out.length - 1];
+    if (q && Math.hypot(p.x - q.x, p.z - q.z) < tol) { q.x = p.x; q.z = p.z; continue; }
+    out.push({ x: p.x, z: p.z });
+  }
+  while (out.length > 3 && Math.hypot(out[out.length - 1].x - out[0].x, out[out.length - 1].z - out[0].z) < tol) out.pop();
+  return out;
+}
+
+/**
+ * 朝外三角形:triO(B, a, b, c, nx, ny, nz) 让三角形 (a,b,c) 的几何法线与期望法向 (nx,ny,nz) 同向。
+ * 期望法向:水平面用 (0,±1,0);竖壁用该面中点的水平径向 (x,0,z)(凸环朝外、凹环朝内均为径向)。
+ * 零面积三角形跳过 —— 凹弧在径向法向下的退化面由此安全剔除。
+ */
+function triO(B, a, b, c, nx, ny, nz) {
+  const P = (i) => [B.pos[i * 3], B.pos[i * 3 + 1], B.pos[i * 3 + 2]];
+  const A = P(a), Bp = P(b), C = P(c);
+  const e1 = [Bp[0] - A[0], Bp[1] - A[1], Bp[2] - A[2]];
+  const e2 = [C[0] - A[0], C[1] - A[1], C[2] - A[2]];
+  const gx = e1[1] * e2[2] - e1[2] * e2[1], gy = e1[2] * e2[0] - e1[0] * e2[2], gz = e1[0] * e2[1] - e1[1] * e2[0];
+  if (gx * gx + gy * gy + gz * gz < 1e-14) return;
+  const dot = gx * nx + gy * ny + gz * nz;
+  if (dot >= 0) B.idx.push(a, b, c); else B.idx.push(a, c, b);
+}
+
+/** 四边形 a,b,c,d(按环序 A_j, A_j2, B_j2, B_j)→ 两三角形,法向同 (nx,ny,nz) */
+function quadN(B, a, b, c, d, nx, ny, nz) { triO(B, a, b, c, nx, ny, nz); triO(B, a, c, d, nx, ny, nz); }
+
+/** 环带:A(外)与 B(内)等长;法线朝 +Y(up)或 −Y(down) */
+function bandTris(B, A, Bn, dir) {
+  const n = A.length;
+  for (let j = 0; j < n; j++) {
+    const j2 = (j + 1) % n;
+    quadN(B, A[j], A[j2], Bn[j2], Bn[j], 0, dir === 'up' ? 1 : -1, 0);
+  }
+}
+
+/** 环在 XZ 平面的绕向(> 0 = 俯视逆时针),用鞋带公式在网格坐标上算 */
+function ringCcw(B, ring) {
+  let a = 0;
+  for (let j = 0; j < ring.length; j++) {
+    const p = ring[j] * 3, q = ring[(j + 1) % ring.length] * 3;
+    a += B.pos[p] * B.pos[q + 2] - B.pos[q] * B.pos[p + 2];
+  }
+  return a < 0; // 鞋带和 < 0 表示 CCW(XZ 视角,z 向上为屏幕下方)
+}
+
+/** 直接按 flip 输出四边形(不猜法线) */
+function quadW(B, a, b, c, d, flip) {
+  if (flip) { B.idx.push(a, c, b, a, d, c); } else { B.idx.push(a, b, c, a, c, d); }
+}
+
+/** 竖壁:环 A(底 y0)与 B(顶 y1);法线由面中点的水平径向决定(凸面/凹面都正确朝外) */
+function wallTris(B, A, Bn, radial = 1) {
+  const n = A.length;
+  const P = (i, k) => B.pos[i * 3 + k];
+  for (let j = 0; j < n; j++) {
+    const j2 = (j + 1) % n;
+    const a = A[j], b = A[j2], c = Bn[j2], d = Bn[j];
+    const mx = (P(a, 0) + P(b, 0) + P(c, 0) + P(d, 0)) / 4;
+    const mz = (P(a, 2) + P(b, 2) + P(c, 2) + P(d, 2)) / 4;
+    quadN(B, a, b, c, d, mx * radial, 0, mz * radial);
+  }
+}
+
+/** 环内封口三角扇到轴心点 c(扇面朝 +Y / −Y) */
+function capTris(B, ring, c, dir) {
+  const n = ring.length;
+  for (let j = 0; j < n; j++) quadN(B, ring[j], ring[(j + 1) % n], c, c, 0, dir === 'up' ? 1 : -1, 0);
+}
+
+class Builder {
+  constructor() { this.pos = []; this.idx = []; }
+  add(x, y, z) { this.pos.push(x, y, z); return this.pos.length / 3 - 1; }
+  ring(pts, y, cx = 0, cz = 0) {
+    const ids = [];
+    for (const p of pts) ids.push(this.add(cx + p.x, y, cz + p.z));
+    return ids;
+  }
+  mesh() { return { positions: this.pos, indices: this.idx }; }
+}
+
+/* =========================================================
+   壳体主体
+   ========================================================= */
+
+/** 圆角矩形环(XZ,CCW,中心原点) */
+export function roundedRectRing(w, d, r, seg = 8) {
+  const hw = w / 2, hd = d / 2;
+  const rr = Math.max(0.001, Math.min(r, hw - 0.001, hd - 0.001));
+  const out = [];
+  const corners = [[hw - rr, hd - rr, 0], [-hw + rr, hd - rr, Math.PI / 2], [-hw + rr, -hd + rr, Math.PI], [hw - rr, -hd + rr, 1.5 * Math.PI]];
+  for (const [cx, cz, a0] of corners) for (let i = 0; i <= seg; i++) {
+    const a = a0 + (Math.PI / 2) * (i / seg);
+    out.push({ x: cx + rr * Math.cos(a), z: cz + rr * Math.sin(a) });
+  }
+  return out;
+}
+
+/** circleRing */
+export function circleRing(r, seg = 64, cw = false) {
+  const out = [];
+  for (let s = 0; s < seg; s++) { const a = (s / seg) * TAU; out.push({ x: r * Math.cos(a), z: (cw ? 1 : -1) * r * Math.sin(a) }); }
+  return out;
+}
+
+/**
+ * 回转体(圆件 / 表壳 / 戒指):截面点 [[r, y], …](r ≥ 0,闭合;r=0 的两端为轴心)。
+ * 每个面的法向取「面中点的径向(含高度分量)」—— 回转面上它要么指向外侧(凸段),
+ * 要么指向轴线(内腔 / 沉台内壁),截面可以任意来回,朝外由 triO 保证。
+ * seg:圆周分段;cx/cz:水平偏移。
+ */
+export function roundShell(points, seg = 112, _sign = 1) {
+  const pts = points.filter((p, i, a) => i === 0 || Math.hypot(p[0] - a[i - 1][0], p[1] - a[i - 1][1]) > 1e-3);
+  const b = new Builder();
+  // 每行一个环(轴心行只放一个顶点),环与环之间三角化;绕向按「面中点径向」逐面校正
+  // 轴心点按连续等值(r≈0)合并为一个顶点(CSG 需要坐标去重后的封闭流形)
+  const P = (i) => [b.pos[i * 3], b.pos[i * 3 + 1], b.pos[i * 3 + 2]];
+  const rows = [];
+  let lastAxis = -1;
+  for (const [r, y] of pts) {
+    if (r < 1e-4) {
+      if (lastAxis < 0 || Math.abs(P(lastAxis)[1] - y) > 1e-6) lastAxis = b.add(0, y, 0);
+      rows.push([lastAxis]);
+      continue;
+    }
+    lastAxis = -1;
+    const ids = [];
+    for (let s = 0; s < seg; s++) { const a = (s / seg) * TAU; ids.push(b.add(r * Math.cos(a), y, r * Math.sin(a))); }
+    rows.push(ids);
+  }
+  const pushT = (a, b2, c, nrm) => {
+    const A = P(a), Bp = P(b2), C = P(c);
+    const u = [Bp[0] - A[0], Bp[1] - A[1], Bp[2] - A[2]], v = [C[0] - A[0], C[1] - A[1], C[2] - A[2]];
+    const nx = u[1] * v[2] - u[2] * v[1], ny = u[2] * v[0] - u[0] * v[2], nz = u[0] * v[1] - u[1] * v[0];
+    if (nx * nx + ny * ny + nz * nz < 1e-12) return;
+    const dot = nx * nrm[0] + ny * nrm[1] + nz * nrm[2];
+    if (dot >= 0) b.idx.push(a, b2, c); else b.idx.push(a, c, b2);
+  };
+  for (let i = 0; i < rows.length - 1; i++) {
+    const A = rows[i], Bn = rows[i + 1];
+    const aAxis = A.length === 1, bAxis = Bn.length === 1;
+    for (let s = 0; s < seg; s++) {
+      const s2 = (s + 1) % seg;
+      const a = aAxis ? A[0] : A[s], b2 = aAxis ? A[0] : A[s2];
+      const c = bAxis ? Bn[0] : Bn[s2], d = bAxis ? Bn[0] : Bn[s];
+      const ids4 = [a, b2, c, d];
+      const ys = ids4.map((id) => P(id)[1]);
+      let mut = 0, muz = 0;
+      for (const id of ids4) { mut += P(id)[0] / 4; muz += P(id)[2] / 4; }
+      const flat = ys.every((y) => Math.abs(y - ys[0]) < 1e-6);
+      if (aAxis || bAxis) {
+        // 轴心侧:单个三角形,期望法向取该三角形所在环面的径向(平面圆盘为 ±Y)
+        const nrm = flat ? [0, P(A[0])[1] > P(Bn[0])[1] ? 1 : -1, 0] : [mut, 0, muz];
+        if (aAxis) pushT(a, d, c, nrm); else pushT(a, c, b2, nrm);
+        continue;
+      }
+      // pushT 内部按法线校正绕向;这里先给「互不相反」的基础顺序:(a,d,c) 与 (a,b,c)
+      const nrm = flat ? [0, P(A[0])[1] > P(Bn[0])[1] ? 1 : -1, 0] : [mut, 0, muz];
+      pushT(a, d, c, nrm); pushT(a, b2, c, nrm);
+    }
+  }
+  return b.mesh();
+}
+
+/**
+ * 四边面:两个三角形顶点完全一致(不生成对角新点),CSG 内部按「闭合多边形」处理,
+ * 不会产生 T 形半边。绕向先按 (a,b,c) 与 (a,c,d) 同向写入,再按「面中点径向」保证朝外。
+ */
+function addQuad(b, a, b2, c, d) {
+  const P = (i) => [b.pos[i * 3], b.pos[i * 3 + 1], b.pos[i * 3 + 2]];
+  const A = P(a), Bp = P(b2), C = P(c), D = P(d);
+  // 三个非对顶组合中取非零面积的那个判定绕向:(a,b,c) 与 (a,c,d) 同向
+  const u = [Bp[0] - A[0], Bp[1] - A[1], Bp[2] - A[2]], v = [C[0] - A[0], C[1] - A[1], C[2] - A[2]];
+  const nx = u[1] * v[2] - u[2] * v[1], ny = u[2] * v[0] - u[0] * v[2], nz = u[0] * v[1] - u[1] * v[0];
+  const mx = (A[0] + Bp[0] + C[0] + D[0]) / 4, my = (A[1] + Bp[1] + C[1] + D[1]) / 4, mz = (A[2] + Bp[2] + C[2] + D[2]) / 4;
+  const dot = nx * mx + ny * my + nz * mz;
+  if (dot >= 0) { b.idx.push(a, b2, c, a, c, d); } else { b.idx.push(a, c, b2, a, d, c); }
+}
+
+/**
+ * 等距内缩点(与 roundedRectRing 同点序):直边沿法向收 d,圆角沿径向、R 减 d。
+ * 关键:用生成外环时的「拐角采样参数」判断点在圆角还是直边,保证内外环一一对应。
+ * angs = 每个点的 { c: 拐角0..3, a: 采样角 }(由 ringAngles() 给出)。
+ */
+export function insetPoint(p, L, W, d, r0, angs = null) {
+  const hw = L / 2, hd = W / 2;
+  const rr = clamp(r0, 0.001, Math.min(hw, hd) - 0.001);
+  if (angs) {
+    // 每个采样点归属:拐角 c 的弧(a ∈ (0, π/2))、水平边(a = 0 或 π/2 的端点,线段按两端点序号判定)。
+    // 水平边沿 z 收 d;竖直边沿 x 收 d;弧沿径向。段端点是相邻弧的切点,归入该边。
+    const c = angs.c, a = angs.a, i = angs.i;
+    // 拐角序号 → 圆心:0 右上、1 左上、2 左下、3 右下
+    const ccx = [hw - rr, -hw + rr, -hw + rr, hw - rr][c];
+    const ccz = [hd - rr, hd - rr, -hd + rr, -hd + rr][c];
+    const rk = Math.max(rr * 0.2, rr - d);
+    const p0 = rr - d; // 内缩后圆角终点距内边坐标的距离
+    if (a > 1e-9 && a < Math.PI / 2 - 1e-9) return { x: ccx + rk * Math.cos(c * Math.PI / 2 + a), z: ccz + rk * Math.sin(c * Math.PI / 2 + a) };
+    // 段端点:线段自本拐角 a=0 端点到相邻拐角 a=π/2 端点
+    if (i % 9 === 0) {
+      // 弧起点(调用端):角0 在右侧竖边(x=hw);角1 在顶边(z=hd);角2 在左侧竖边(x=-hw);角3 在底边(z=-hd)
+      return (c === 0 || c === 2) ? { x: p.x - Math.sign(p.x || 1) * d, z: p.z } : { x: p.x, z: p.z - Math.sign(p.z || 1) * d };
+    }
+    return (c === 1 || c === 3) ? { x: p.x - Math.sign(p.x || 1) * d, z: p.z } : { x: p.x, z: p.z - Math.sign(p.z || 1) * d };
+    void p0;
+  }
+  // 无参数时按几何位置判断
+  if (Math.abs(p.x) >= hw - rr - 1e-6 && Math.abs(p.z) >= hd - rr - 1e-6) {
+    const cx = (p.x >= 0 ? 1 : -1) * (hw - rr), cz = (p.z >= 0 ? 1 : -1) * (hd - rr);
+    const ax = p.x - cx, az = p.z - cz, l = Math.hypot(ax, az) || 1;
+    const rk = Math.max(rr * 0.2, rr - d);
+    return { x: cx + (ax / l) * rk, z: cz + (az / l) * rk };
+  }
+  if (p.x === hw || p.x === -hw) return { x: p.x - Math.sign(p.x) * d, z: p.z };
+  if (p.z === hd || p.z === -hd) return { x: p.x, z: p.z - Math.sign(p.z) * d };
+  return hw - Math.abs(p.x) <= hd - Math.abs(p.z) ? { x: p.x - Math.sign(p.x) * d, z: p.z } : { x: p.x, z: p.z - Math.sign(p.z) * d };
+}
+
+/** 圆角矩形环 + 每点的采样参数(拐角序号 c、采样角 a):点序与 roundedRectRing 完全一致 */
+export function roundedRectRingAngles(w, d, r, seg = 8) {
+  const hw = w / 2, hd = d / 2;
+  const rr = Math.max(0.001, Math.min(r, hw - 0.001, hd - 0.001));
+  const corners = [[hw - rr, hd - rr, 0], [-hw + rr, hd - rr, Math.PI / 2], [-hw + rr, -hd + rr, Math.PI], [hw - rr, -hd + rr, 1.5 * Math.PI]];
+  const out = [];
+  corners.forEach(([cx, cz, a0], c) => {
+    for (let i = 0; i <= seg; i++) {
+      const a = a0 + (Math.PI / 2) * (i / seg);
+      out.push({ x: cx + rr * Math.cos(a), z: cz + rr * Math.sin(a), c, a: (Math.PI / 2) * (i / seg), i });
+    }
+  });
+  return out;
+}
+
+/**
+ * 方件(rect / watch):圆角矩形挤出 + 底腔 + 顶面圆角 + 屏沉台。
+ * o = { L, W, H, wall, cornerR, domeR, chamferC, floorT, screenW, screenHh, recessDepth, seg }
+ * 环序(自外向内,全部 CCW,点数一致):
+ *   O 外壁底 → Oce 底边倒角顶 → O 外壁顶 → Oin 顶面圆角内沿 → C 内腔口 → C 内腔底 → S 屏孔底 → S 沉台顶
+ */
+export function boxShell(o) {
+  const L = Math.max(2, o.L), W = Math.max(2, o.W), H = Math.max(1.5, o.H);
+  const wall = clamp(o.wall ?? 1.5, 0.3, Math.min(L, W) / 2 - 0.5);
+  const seg = o.seg || 8;
+  const r0 = o.cornerR ?? 0;
+  const floor = clamp(o.floorT ?? wall, 0.4, H * 0.45);
+  const dome = clamp(o.domeR ?? 0, 0, Math.min(H - floor - 0.6, Math.min(L, W) / 4));
+  const bot = clamp(o.chamferC ?? 0, 0, Math.min(H * 0.3, wall * 0.8));
+  const depth = clamp(o.recessDepth ?? Math.min(1.2, (H - floor) * 0.35), 0.2, H - floor - 0.3);
+  const sw = clamp(o.screenW ?? L - 2 * wall - 6, 1, L - 2 * wall);
+  const sh = clamp(o.screenHh ?? W - 2 * wall - 6, 1, W - 2 * wall);
+  const OA = roundedRectRingAngles(L, W, r0, seg);
+  const O = OA.map((p) => ({ x: p.x, z: p.z }));
+  const inset = (d) => OA.map((p) => insetPoint(p, L, W, d, r0, p));
+  const b = new Builder();
+  const rO = b.ring(O, 0);
+  const rOce = bot > 0.01 ? b.ring(inset(bot), bot) : rO;
+  const rOtop = b.ring(O, H);
+  const Cpts = inset(wall);
+  const rCavTop = b.ring(Cpts, H);
+  const rCavBot = b.ring(Cpts, floor);
+  // ① 顶面:外环 → 内腔口(朝上;dome 用中间过渡环近似圆角)
+  if (dome > 0.01) {
+    const rMid = b.ring(inset(wall / 2 + dome * 0.5), H - dome * 0.35);
+    bandTris(b, rOtop, rMid, 'up');
+    bandTris(b, rMid, rCavTop, 'up');
+  } else bandTris(b, rOtop, rCavTop, 'up');
+  // ② 底面:内腔环 → 外环(朝下)
+  bandTris(b, rCavBot, rO, 'down');
+  // ③ 外壁:倒角环 → 外顶(朝外)
+  if (rOce !== rO) wallTris(b, rO, rOce);
+  wallTris(b, rOce, rOtop);
+  // ④ 内腔壁:顶 → 底(径向朝内,凹环自动朝腔)
+  wallTris(b, rCavTop, rCavBot, -1);
+  return b.mesh();
+}
+
+/** 表壳(watch):圆角矩形挤出 + 底腔 + 顶面圆角,开口为方角屏(表盘) */
+export function watchShell(o) {
+  const { dTop: D, length: L, height: H, wall, cornerR, domeR, chamferC } = o;
+  return boxShell({
+    L, W: D, H, wall,
+    cornerR: cornerR ?? Math.min(D, L) * 0.25,
+    domeR: domeR ?? 1,
+    chamferC: chamferC ?? 0.5,
+    floorT: wall,
+    screenW: Math.max(4, D - 2 * wall - 5),
+    screenHh: Math.max(4, D - 2 * wall - 5),
+    recessDepth: Math.max(0.6, Math.min(1.4, H * 0.2)),
+    seg: 10,
+  });
+}
+
+/**
+ * 戒指(ring):扁圆环带。截面行进方向(外法向 = 行进方向右侧):内底 → 外底 → 外壁上升 → 外顶圆角 → 顶面内收 → 内壁下降 → 内底圆角。
+ * o = { ringD, ringBandW, height, wall, cornerR }
+ */
+export function ringShell(o) {
+  const D = num(o.ringD, 19), bw = num(o.ringBandW, 6.5), H = Math.max(1, num(o.height, 7));
+  const wall = clamp(num(o.wall, 1.2), 0.3, bw / 2 - 0.1);
+  const ri = D / 2, ro = ri + bw;
+  const rc = Math.min(ro - 0.6, ri + Math.max(0.6, wall));   // 贴指面半径(内圈外沿)
+  const rr = Math.max(0.1, Math.min(num(o.cornerR, 2), bw / 2 - 0.05, H / 2 - 0.05));
+  const seg = 96;
+  const b = new Builder();
+  const circ = (r, y) => b.ring(circleRing(r, seg, false), y);
+  const arc = (pts, cx, cy, r, a0, a1, steps) => { for (let i = 0; i <= steps; i++) { const a = a0 + (a1 - a0) * (i / steps); pts.push({ x: cx + r * Math.cos(a), z: cy + r * Math.sin(a) }); } };
+  const band = (A, Bn, outward) => {
+    for (let j = 0; j < A.length; j++) {
+      const j2 = (j + 1) % A.length;
+      const a = A[j], b2 = A[j2], c = Bn[j2], d = Bn[j];
+      const mx = (b.pos[a * 3] + b.pos[b2 * 3] + b.pos[c * 3] + b.pos[d * 3]) / 4;
+      const mz = (b.pos[a * 3 + 2] + b.pos[b2 * 3 + 2] + b.pos[c * 3 + 2] + b.pos[d * 3 + 2]) / 4;
+      quadN(b, a, b2, c, d, mx * outward, 0, mz * outward);
+    }
+  };
+  // ① 外壁:底(含外底圆角)→ 外顶(含外顶圆角)
+  const outerPts = [{ x: ro - rr, z: 0 }];
+  arc(outerPts, ro - rr, rr, rr, -Math.PI / 2, 0, 5);
+  outerPts.push({ x: ro - rr, z: H - rr });
+  arc(outerPts, ro - rr, H - rr, rr, 0, Math.PI / 2, 5);
+  for (let i = 1; i < outerPts.length; i++) {
+    band(circ(outerPts[i - 1].x, outerPts[i - 1].z), circ(outerPts[i].x, outerPts[i].z), 1);
+  }
+  // ② 内圈(贴指面,凸向轴心):顶部小圆角下行到底
+  const collarPts = [{ x: rc, z: H - 0.4 }];
+  arc(collarPts, rc + 0.4, H - 0.4, 0.4, Math.PI, 1.5 * Math.PI, 4);
+  collarPts.push({ x: rc + 0.4, z: H });
+  for (let i = 1; i < collarPts.length; i++) {
+    band(circ(collarPts[i - 1].x, collarPts[i - 1].z), circ(collarPts[i].x, collarPts[i].z), -1);
+  }
+  // ③ 指孔内壁(圆柱面)
+  band(circ(ri, 0), circ(ri, H), -1);
+  // ④ 底面:底环带(ro−rr → ri,朝下)+ 底内环(rc → ri,朝下)
+  const capBand = (rOuter, rInner) => {
+    const O = circ(rOuter, 0), I = circ(rInner, 0);
+    for (let j = 0; j < seg; j++) {
+      const j2 = (j + 1) % seg;
+      quadN(b, O[j], O[j2], I[j2], I[j], 0, -1, 0);
+    }
+  };
+  capBand(ro - rr, ri);
+  capBand(ri, rc);
+  // ⑤ 顶面:外顶圆角末端(ro−rr)→ 内圈顶部末端(rc+0.4,y=H)朝上环带
+  const T1 = circ(ro - rr, H), T2 = circ(rc + 0.4, H);
+  for (let j = 0; j < seg; j++) {
+    const j2 = (j + 1) % seg;
+    quadN(b, T1[j], T1[j2], T2[j2], T2[j], 0, 1, 0);
+  }
+  // ⑥ 指孔底沿:ri(y=0)与 rc(y=0)之间的底环已由 ④ capBand(ri, rc) 覆盖;指孔顶沿:
+  const K1 = circ(ri, H), K2 = circ(rc, H - 0.4);
+  for (let j = 0; j < seg; j++) {
+    const j2 = (j + 1) % seg;
+    quadN(b, K1[j], K1[j2], K2[j2], K2[j], 0, 1, 0);
+  }
+  return b.mesh();
+}
+
+/* =========================================================
+   结构件(形体库,局部坐标:Y 向上,原点在件中心)
+   ========================================================= */
+function hollowCylinder(od, id, h, tess = 24) {
+  const b = new Builder();
+  const ri = Math.max(0.05, id / 2), ro = Math.max(ri + 0.3, od / 2), hh = Math.max(0.1, h / 2);
+  const mk = (r, y) => { const ids = []; for (let s = 0; s < tess; s++) { const a = (s / tess) * TAU; ids.push(b.add(r * Math.cos(a), y, r * Math.sin(a))); } return ids; };
+  const oT = mk(ro, hh), oB = mk(ro, -hh), iT = mk(ri, hh), iB = mk(ri, -hh);
+  wallTris(b, oB, oT);
+  wallTris(b, iB, iT, -1);
+  bandTris(b, oT, iT, 'up');
+  bandTris(b, oB, iB, 'down');
+  return b.mesh();
+}
+
+export function solidCylinder(dia, h, tess = 32, y0 = null) {
+  const b = new Builder();
+  const r = Math.max(0.1, dia / 2), yb = y0 ?? -Math.max(0.1, h / 2), yt = y0 != null ? y0 + h : Math.max(0.1, h / 2);
+  const mk = (y) => { const ids = []; for (let s = 0; s < tess; s++) { const a = (s / tess) * TAU; ids.push(b.add(r * Math.cos(a), y, r * Math.sin(a))); } return ids; };
+  const T = mk(yt), B = mk(yb);
+  wallTris(b, B, T);
+  capTris(b, T, b.add(0, yt, 0), 'up');
+  capTris(b, B, b.add(0, yb, 0), 'down');
+  return b.mesh();
+}
+
+export function boxMesh(w, h, d) {
+  const hw = w / 2, hh = h / 2, hd = d / 2;
+  const v = [[-hw, -hh, -hd], [hw, -hh, -hd], [hw, hh, -hd], [-hw, hh, -hd], [-hw, -hh, hd], [hw, -hh, hd], [hw, hh, hd], [-hw, hh, hd]];
+  return {
+    positions: v.flat(),
+    indices: [
+      4, 5, 6, 4, 6, 7,   // +z
+      1, 0, 3, 1, 3, 2,   // −z
+      5, 1, 2, 5, 2, 6,   // +x
+      0, 4, 7, 0, 7, 3,   // −x
+      3, 7, 6, 3, 6, 2,   // +y
+      0, 1, 5, 0, 5, 4,   // −y
+    ],
+  };
+}
+
+/** 带拔模的方柱(顶面内收);draft=0 即普通方柱 */
+export function taperedBox(w, h, d, draftDeg) {
+  const m = boxMesh(w, h, d);
+  const t = Math.tan(Math.max(0, draftDeg) * RAD) * h;
+  const kx = Math.max(0.2, (w - 2 * Math.min(t, w * 0.3)) / w), kz = Math.max(0.2, (d - 2 * Math.min(t, d * 0.3)) / d);
+  for (let i = 0; i < m.positions.length; i += 3) if (m.positions[i + 1] > 0) { m.positions[i] *= kx; m.positions[i + 2] *= kz; }
+  return m;
+}
+
+/**
+ * 结构件 → 局部坐标三角网格(Y 向上,原点在件中心高度)。
+ * 实心件(螺丝柱 / 方块)整体保留:既是本体也是切割体(壳内相交部分会被布尔吃掉)。
+ * 切割件(凹槽 / 开孔 / 过孔):其「孔壁」切割体;同型再生成一个细杆指示体(show)。
+ */
+export function primMesh(spec) {
+  const t = spec.type, h = Math.max(0.1, num(spec.h, 1));
+  if (t === 'box') return { part: boxMesh(Math.max(0.1, num(spec.w, 1)), h, Math.max(0.1, num(spec.dd, 1))) };
+  if (t === 'rib' || t === 'wall') return { part: taperedBox(Math.max(0.1, num(spec.w, 1)), h, Math.max(0.1, num(spec.dd, 1)), spec.draft || 0) };
+  if (t === 'clip') return { part: taperedBox(Math.max(0.1, num(spec.w, 1)), h, Math.max(0.1, num(spec.dd, 1)), 0) };
+  if (t === 'pocket') return { part: boxMesh(Math.max(0.2, num(spec.w, 1)), h, Math.max(0.2, num(spec.dd, 1))) };
+  if (t === 'hole' || t === 'thru25') return { part: solidCylinder(Math.max(0.2, num(spec.dia, 1)), h, 24) };
+  if (t === 'cyl') return { part: solidCylinder(Math.max(0.2, num(spec.dia, 1)), h, 32) };
+  if (t === 'pin3') return { part: solidCylinder(Math.max(0.2, num(spec.dia, 1)), h, 20) };
+  if (t === 'boss2' || t === 'boss25' || t === 'boss3') return { part: hollowCylinder(Math.max(0.6, num(spec.dia, 1)), Math.max(0.2, num(spec.dd, 1)), h, 24) };
+  if (t === 'pad4') {
+    const w = Math.max(2, num(spec.w, 2)), d = Math.max(2, num(spec.dd, 2)), od = Math.max(1, num(spec.dia, 4.8)), hd = Math.max(0.2, num(spec.hd, 2.1));
+    const one = hollowCylinder(od, hd, h, 20);
+    const parts = [];
+    for (const sx of [-1, 1]) for (const sz of [-1, 1]) parts.push(translate(one, sx * Math.max(0, w / 2 - od / 2), 0, sz * Math.max(0, d / 2 - od / 2)));
+    return { part: mergeMeshes(parts) };
+  }
+  if (t === 'tray') {
+    const w = Math.max(2, num(spec.w, 1)), d = Math.max(2, num(spec.dd, 1)), th = Math.min(1.4, Math.max(0.6, Math.min(w, d) / 12));
+    const parts = [translate(boxMesh(w, th, d), 0, -h / 2 + th / 2, 0)];
+    for (const sg of [-1, 1]) {
+      parts.push(translate(boxMesh(th, h, d), sg * (w / 2 - th / 2), 0, 0));
+      parts.push(translate(boxMesh(w, h, th), 0, 0, sg * (d / 2 - th / 2)));
+    }
+    return { part: mergeMeshes(parts) };
+  }
+  return { part: boxMesh(8, h, 8) };
+}
+
+/** 结构件世界网格:按 spec.x / spec.y / spec.z / spec.rot 摆到位 */
+export function placePrim(mesh, spec) {
+  return rotateY(mesh, spec.rot || 0, num(spec.x), num(spec.y), num(spec.z));
+}
+
+/** 结构件是否「减料」(CSG 减去);其余按实体加入 */
+export function isCutType(type) { return type === 'pocket' || type === 'hole' || type === 'thru25'; }
+
+/* =========================================================
+   内腔包络 / 结构件落位
+   ========================================================= */
+export function cavity(shapeType, p) {
+  if (shapeType === 'rect') {
+    const L = num(p.length, 40), W = num(p.dTop, 30), H = num(p.height, 8), wall = num(p.wall, 1.5);
+    return { kind: 'rect', halfX: Math.max(1, L / 2 - wall), halfZ: Math.max(0.6, W / 2 - wall), floor: Math.max(0.4, Math.min(wall, H * 0.3)), top: Math.max(0.8, H - 0.4), cornerR: Math.max(0, num(p.cornerR) - wall) };
+  }
+  if (shapeType === 'watch') {
+    const D = num(p.dTop, 45), L = num(p.length, 54), H = num(p.height, 12), wall = num(p.wall, 2);
+    return { kind: 'roundrect', halfX: Math.max(1, D / 2 - wall), halfZ: Math.max(1, L / 2 - wall), floor: Math.max(0.5, wall), top: H - 0.4, cornerR: 5 };
+  }
+  if (shapeType === 'ring') {
+    const D = num(p.dTop, 40), H = num(p.height, 6), wall = num(p.wall, 1.2);
+    return { kind: 'cyl', r: Math.max(1, D / 2 - wall), floor: Math.max(0.4, wall), top: Math.max(0.8, H - 0.2) };
+  }
+  const D = num(p.dTop, 40), H = num(p.height, 10), wall = num(p.wall, 1.5);
+  return { kind: 'cyl', r: Math.max(1, D / 2 - wall), floor: Math.max(0.4, Math.min(wall, H * 0.25)), top: Math.max(0.8, H - Math.max(0.4, wall)) };
+}
+
+/** 件到内腔边界的余量(mm;正 = 在内腔里) */
+export function clearanceTo(cav, s) {
+  const [w, d] = primDims(s);
+  const x = num(s.x), z = num(s.z), y = num(s.y), h = num(s.h, 1);
+  let side;
+  if (cav.kind === 'cyl') side = cav.r - Math.hypot(x, z) - Math.max(w, d) / 2;
+  else side = Math.min(cav.halfX - Math.abs(x) - w / 2, cav.halfZ - Math.abs(z) - d / 2);
+  const bottom = y - h / 2 - cav.floor;
+  const top = cav.top - (y + h / 2);
+  return r2(Math.min(side, bottom, top));
+}
+
+export function snapToWall(cav, s, margin = 1) {
+  const [w, d] = primDims(s);
+  if (cav.kind === 'cyl') return { x: r2(Math.max(0, cav.r - Math.max(w, d) / 2 - margin)), z: 0 };
+  return { x: 0, z: r2(Math.max(0, cav.halfZ - d / 2 - margin)) };
+}
+
+export function snapY(cav, s, mode) {
+  const h = num(s.h, 1);
+  if (mode === 'top') return r2(cav.top - h / 2);
+  if (mode === 'bottom') return r2(cav.floor + h / 2);
+  return r2((cav.floor + cav.top) / 2);
+}
+
+/** 拖拽吸附:先按 step 取整;离内壁 < tol(1.5mm)时贴到「留 margin(0.5mm) 余量」处 */
+export function snapDrag(cav, s, x, z, step = 0.5, tol = 1.5, margin = 0.5) {
+  const st = Math.max(0.05, +step || 0.5);
+  let X = Math.round(x / st) * st, Z = Math.round(z / st) * st;
+  const [w, d] = primDims(s);
+  if (cav.kind === 'cyl') {
+    const r = Math.hypot(X, Z), lim = cav.r - Math.max(w, d) / 2 - margin;
+    if (r > 0.01 && lim > 0 && Math.abs(r - lim) < tol) { X = (X / r) * lim; Z = (Z / r) * lim; }
+  } else {
+    const lx = cav.halfX - w / 2 - margin, lz = cav.halfZ - d / 2 - margin;
+    if (lx > 0 && Math.abs(Math.abs(X) - lx) < tol) X = Math.sign(X || 1) * lx;
+    if (lz > 0 && Math.abs(Math.abs(Z) - lz) < tol) Z = Math.sign(Z || 1) * lz;
+  }
+  return { x: r2(X), z: r2(Z) };
+}
+
+/** 新建结构件:默认尺寸 + 落在内腔底 */
+export function newSpec(type, cav, patch = {}) {
+  const base = (PRIMS[type] || PRIMS.box).d;
+  const s = { uid: 1, type, x: 0, z: 0, y: 0, rot: 0, draft: 1, snap: 0.5, note: '', ...base, ...patch };
+  if (cav) s.y = snapY(cav, s, 'bottom');
+  return s;
+}
+
+/* =========================================================
+   工艺规则(五套)
+   ========================================================= */
+export const RULES = {
+  injection: { name: '注塑(ABS/PC)', minWall: 0.8, minRib: 0.8, draft: 1,
+    items: [['最小壁厚', '0.8 mm,薄壁区建议 1.0'], ['拔模角', '≥1°,外观面 ≥2°'], ['内角圆角', 'R ≥ 0.5'], ['筋厚', '≥0.8 且 ≤ 主壁厚 0.8 倍'], ['深宽比', '≤ 3:1'], ['缩水', '0.4%~0.6%']] },
+  silicone: { name: '硅胶模压', minWall: 1.2, minRib: 1.0, draft: 3,
+    items: [['壁厚', '1.5~3.0 mm'], ['脱模角', '≥3°,双角根部 ≥5°'], ['圆角', 'R ≥ 0.5'], ['硬度', '30~70 Shore A'], ['最小批次', '500 套']] },
+  cnc: { name: 'CNC 铝 6061', minWall: 1.0, minRib: 1.0, draft: 0,
+    items: [['最小刀具', 'Ø2,内角 R≥1'], ['最小壁厚', '1.0 mm'], ['深腔', '≤ 4× 刀径'], ['公差', '±0.05 关键 / ±0.1 一般'], ['螺纹', '阳极后二次回攻']] },
+  vac: { name: '真空复模', minWall: 1.2, minRib: 1.0, draft: 1.5,
+    items: [['壁厚', '≥1.2 mm'], ['收缩补偿', '0.3%'], ['批量', '10 套起']] },
+  die: { name: '压铸铝', minWall: 1.5, minRib: 1.2, draft: 1.5,
+    items: [['壁厚', '≥1.5 mm'], ['拔模', '≥1.5°'], ['模具费', '¥12,000 起'], ['MOQ', '1000 套']] },
+};
+export const RULE_KEYS = { injection: '注塑', silicone: '硅胶', cnc: 'CNC', vac: '复模', die: '压铸' };
+
+/** 工艺选项:优先用产品 processParams / processes 的键,保证每个产品都有五套规则可选 */
+export function procOptions(product) {
+  const keys = Object.keys(product?.processParams || {});
+  const procs = product?.processes || [];
+  const opts = [];
+  for (const k of ['injection', 'cnc', 'silicone', 'diecast', 'vacuum']) {
+    if (keys.length && !keys.includes(k) && !(k === 'diecast' && keys.includes('die'))) continue;
+    const pr = procs.find((x) => x.id === k) || (k === 'diecast' ? procs.find((x) => /压铸/.test(x.name || '')) : null);
+    opts.push({ key: k, label: RULE_KEYS[ruleKey(k, product)], rule: ruleKey(k, product), name: pr ? pr.name : RULE_KEYS[ruleKey(k, product)] });
+  }
+  // 至少给出五个规则里的四类
+  const have = new Set(opts.map((o) => o.rule));
+  for (const [k, id] of [['injection', 'injection'], ['cnc', 'cnc'], ['silicone', 'silicone'], ['vacuum', 'vac'], ['diecast', 'die']]) {
+    if (!have.has(id)) { opts.push({ key: k, label: RULE_KEYS[id], rule: id, name: RULE_KEYS[id] }); have.add(id); }
+  }
+  return opts;
+}
+
+/** 工艺 id → 规则键 */
+export function ruleKey(procId, product) {
+  const id = String(procId || '').toLowerCase();
+  const pr = (product?.processes || []).find((x) => x.id === procId || x.key === procId);
+  const name = `${id} ${pr?.name || ''} ${(product?.craftTags || []).join(' ')}`;
+  if (/硅胶|silicone|vulcanize|sil-|bond/.test(name)) return 'silicone';
+  if (/压铸|diecast|die-cast|\bdie\b/.test(name)) return 'die';
+  if (/复模|vacuum|\bvac\b/.test(name)) return 'vac';
+  if (/cnc|阳极|五轴|车铣|polish|sandblast|车削/.test(name)) return 'cnc';
+  return 'injection';
+}
+
+/** 工艺弧面默认值(随规则),用于圆件 / 表壳 */
+export function procArcDefaults(rk) {
+  if (rk === 'silicone') return { crownR: 1.2, recessR: 0.8, chamferC: 0.8 };
+  if (rk === 'die') return { crownR: 1.0, recessR: 0.6, chamferC: 0.6 };
+  if (rk === 'vac') return { crownR: 1.0, recessR: 0.5, chamferC: 0.5 };
+  if (rk === 'cnc') return { crownR: 0.8, recessR: 0.5, chamferC: 0.5 };
+  return { crownR: 0.6, recessR: 0.4, chamferC: 0.4 };
+}
+
+/** 有效壁厚(圆件按外径 − 内腔推算;与 cavity() 同源) */
+export function effWall(shapeType, p) {
+  if (shapeType === 'round' || shapeType === 'ring') return r2(num(p.dTop) / 2 - cavity(shapeType, p).r);
+  return r2(num(p.wall));
+}
+
+/**
+ * 五套规则下的模型校验 → [{ ok, t, field?, partId?, rule? }]。
+ * field 指向主体参数(点击定位到滑块),partId 指向结构件。
+ */
+export function modelChecks(product, p, list, rk, arc = {}) {
+  const out = [];
+  const rule = RULES[rk] || RULES.injection;
+  const type = product?.shape?.type;
+  const cav = cavity(type, p);
+  const ew = effWall(type, p);
+  if (ew < rule.minWall - 0.001) out.push({ ok: false, field: 'wall', t: `主壁厚 ${ew} mm 低于${rule.name}下限 ${rule.minWall} mm` });
+  else out.push({ ok: true, field: 'wall', t: `主壁厚 ${ew} mm ≥ ${rule.minWall} mm(${rule.name})` });
+  const draft = num(p.draft);
+  if (rule.draft > 0) {
+    if (draft + 1e-6 < rule.draft) out.push({ ok: false, field: 'draft', t: `拔模角 ${r2(draft)}° < ${rule.draft}°(${rule.name}易粘模)` });
+    else out.push({ ok: true, field: 'draft', t: `拔模角 ${r2(draft)}° ≥ ${rule.draft}°` });
+  }
+  if (type === 'round' || type === 'ring' || type === 'watch') {
+    const crown = +arc.crownR || 0;
+    if (crown > 0 && crown < 0.4) out.push({ ok: false, field: 'crownR', arc: true, t: `顶部凸圆 R${r2(crown)} 小于工艺最小 0.4` });
+    if (rk === 'cnc' && (+arc.recessR || 0) < 0.4) out.push({ ok: false, field: 'recessR', arc: true, t: `屏边凹圆 R${r2(arc.recessR)} 小于球头刀最小 0.4` });
+    if (type !== 'watch') {
+      const cut = (num(p.dTop) - num(p.screenD)) / 2;
+      if (cut < ew + crown + (rule.draft > 0 ? 0.2 : 0)) out.push({ ok: false, field: 'screenD', t: `屏径 Ø${r2(p.screenD)} 过大:屏到外壁只剩 ${r2(cut)} mm,放不下壁厚 + 凸圆 R` });
+    }
+  }
+  const deep = num(p.height) - cav.top;
+  if (deep > 0 && type !== 'round') out.push({ ok: true, t: `顶壁 ${r2(deep)} mm(顶面圆角过渡)` });
+  if (!list.length) out.push({ ok: true, t: '尚无自定义结构件:当前为参数化主体' });
+  for (const s of list) {
+    const nm = (PRIMS[s.type] || { n: s.type }).n;
+    const [w, d] = primDims(s);
+    const thin = Math.min(w, d);
+    const clr = clearanceTo(cav, s);
+    const id = 'c' + s.uid;
+    if ((s.type === 'rib' || s.type === 'wall' || s.type === 'box') && thin < rule.minRib)
+      out.push({ ok: false, partId: id, t: `${nm} 厚 ${r2(thin)} mm < ${rule.name} 最小 ${rule.minRib} mm` });
+    if (clr < 1.0) out.push({ ok: false, partId: id, t: `${nm} 距内壁/底/顶只剩 ${r2(clr)} mm(<1 mm,装配与脱模都会出问题)` });
+    else out.push({ ok: true, partId: id, t: `${nm} 距内壁 ${r2(clr)} mm,余量可用` });
+    if (rule.draft > 0 && (s.type === 'rib' || s.type === 'wall') && num(s.draft) < rule.draft)
+      out.push({ ok: false, partId: id, field: 'draft', t: `${nm} 拔模 ${r2(s.draft)}° < ${rule.draft}°(${rule.name}易粘模)` });
+    if (['boss2', 'boss25', 'boss3'].includes(s.type)) {
+      const bw = (num(s.dia) - num(s.dd)) / 2, minW = rk === 'cnc' ? 0.9 : Math.max(0.9, rule.minRib * 0.9);
+      if (bw < minW) out.push({ ok: false, partId: id, field: 'dia', t: `${nm} 柱壁 ${r2(bw)} mm < ${r2(minW)} mm,自攻牙会胀裂` });
+      const std = STD_PILOT[s.type];
+      if (Math.abs(num(s.dd) - std) > 0.15) out.push({ ok: false, partId: id, field: 'dd', t: `${nm} 预钻孔 Ø${r2(s.dd)} 非标准(该规格应为 Ø${std})` });
+    }
+    if (s.type === 'pad4') {
+      const bw = (num(s.dia) - num(s.hd)) / 2;
+      if (bw < 0.9) out.push({ ok: false, partId: id, field: 'dia', t: `${nm} 柱壁 ${r2(bw)} mm 偏薄(<0.9)` });
+      if (Math.abs(num(s.hd) - STD_PILOT.boss25) > 0.15) out.push({ ok: false, partId: id, field: 'hd', t: `${nm} 预钻 Ø${r2(s.hd)} 非 M2.5 标准 Ø2.1` });
+    }
+    if ((s.type === 'pocket' || s.type === 'hole') && num(s.h) > thin * 2)
+      out.push({ ok: false, partId: id, field: 'h', t: `${nm} 深宽比 ${r2(num(s.h) / Math.max(1, thin))}:1 > 2:1,需分层铣 / 镶件` });
+  }
+  return out;
+}
+
+/* =========================================================
+   派生尺寸 / 需求单 / BOM
+   ========================================================= */
+const f2 = (v) => (num(v)).toFixed(2);
+const f1 = (v) => (num(v)).toFixed(1);
+
+export function derived(type, p, arc = {}) {
+  const cav = cavity(type, p);
+  const density = type === 'ring' ? 4.5 : type === 'round' ? 2.7 : 1.05;
+  if (type === 'round') {
+    const vol = Math.PI * ((num(p.dTop) / 2) ** 2 - cav.r ** 2) * num(p.height);
+    return [
+      ['外形', `Ø${f2(p.dTop)} × ${f2(p.height)} mm`],
+      ['内腔可用', `Ø${f1(cav.r * 2)} × H${f1(cav.top - cav.floor)} mm`],
+      ['屏径 / 沉台', `Ø${f2(p.screenD)} · 沉台 ${f1(p.recessDepth)} mm`],
+      ['工艺弧面', `顶部凸圆 R${f2(arc.crownR)} / 屏边凹圆 R${f2(arc.recessR)} / 底倒角 C${f1(arc.chamferC)}`],
+      ['壳重估算', `${f1((vol / 1000) * density)} g(铝 2.7 g/cm³)`],
+      ['屏占比', `${(num(p.screenD) / Math.max(1, num(p.dTop)) * 100).toFixed(0)}%`],
+    ];
+  }
+  if (type === 'ring') {
+    return [
+      ['内径 / 截面', `Ø${f1(p.ringD)} / ${f1(p.ringBandW)} × ${f1(p.height)} mm`],
+      ['外径', `Ø${f1(num(p.ringD) + 2 * num(p.ringBandW))} mm`],
+      ['壁厚', `${f2(effWall(type, p))} mm`],
+      ['工艺弧面', `顶部凸圆 R${f2(arc.crownR)} / 底倒角 C${f1(arc.chamferC)}`],
+    ];
+  }
+  if (type === 'watch') {
+    const vol = (num(p.dTop) * num(p.length) - (num(p.dTop) - 2 * num(p.wall)) * (num(p.length) - 2 * num(p.wall))) * num(p.height);
+    return [
+      ['外形', `${f1(p.dTop)} × ${f1(p.length)} × ${f1(p.height)} mm`],
+      ['内腔可用', `${f1(cav.halfX * 2)} × ${f1(cav.halfZ * 2)} mm`],
+      ['壁厚 / 角 R', `${f2(p.wall)} / R${f1(p.cornerR)}`],
+      ['壳重估算', `${f1((vol / 1000) * 1.15)} g(硅胶 1.15 g/cm³)`],
+    ];
+  }
+  const vol = (num(p.length) * num(p.dTop) - (num(p.length) - 2 * cav.halfX) * (num(p.dTop) - 2 * cav.halfZ)) * num(p.height) + (num(p.length) - 2 * cav.halfX) * (num(p.dTop) - 2 * cav.halfZ) * cav.floor;
+  return [
+    ['外形', `${f1(p.length)} × ${f1(p.dTop)} × ${f1(p.height)} mm`],
+    ['内腔可用', `${f1(cav.halfX * 2)} × ${f1(cav.halfZ * 2)} × H${f1(cav.top - cav.floor)} mm`],
+    ['屏视窗', `${f1(p.screenD)} × ${f1(p.screenH)} mm · 沉台 ${f1(p.recessDepth)}`],
+    ['角 R / 顶圆角', `R${f1(p.cornerR)} / R${f1(p.capR)}`],
+    ['壳重估算', `${f1((vol / 1000) * 1.05)} g(ABS 1.05 g/cm³)`],
+  ];
+}
+
+export function primDimText(s) {
+  if (CYL_TYPES.includes(s.type)) return `Ø${f2(s.dia)} × H${f2(s.h)}`;
+  if (s.type === 'pad4') return `${f1(s.w)} × ${f1(s.dd)} · 柱 Ø${f2(s.dia)}`;
+  return `${f2(s.w)} × ${f2(s.dd)} × H${f2(s.h)}`;
+}
+
+export function primRequirement(s, rk) {
+  const t = s.type;
+  const m = { boss2: 'M2', boss25: 'M2.5', boss3: 'M3' }[t];
+  if (t === 'rib' || t === 'wall') return `拔模 ${f1(s.draft)}°,厚 ${f2(s.dd)} mm,根部 R0.5`;
+  if (m) return `${m} 自攻牙:预钻 Ø${f2(s.dd)},柱径 Ø${f2(s.dia)},同轴度 ≤0.05${rk === 'cnc' ? ',建议嵌铜螺母' : ''}`;
+  if (t === 'thru25') return `Ø${f2(s.dia)} 过孔(M2.5),位置度 ±0.05`;
+  if (t === 'pin3') return `Ø${f2(s.dia)} 定位销,H7 配合`;
+  if (t === 'pad4') return `四角柱:中心距 ${f1(s.w)}×${f1(s.dd)},预钻 Ø${f2(s.hd)},与 PCB 孔位同轴 ±0.05`;
+  if (t === 'pocket') return `铣削凹槽 ${f1(s.w)}×${f1(s.dd)},内角 R≥1,深 ${f2(s.h)}`;
+  if (t === 'hole') return `钻孔 Ø${f2(s.dia)},位置度 ±0.05`;
+  if (t === 'tray') return '电池仓:壁厚 0.8~1.2,底部 R0.5,留极耳缺口';
+  if (t === 'clip') return '卡扣:根部 R0.4,扣合量 0.3~0.5,试插 50 次不疲劳';
+  return '与主体同材质,去刀纹';
+}
+
+const PARAM_LABEL = {
+  dTop: '顶部外径 / 宽', dBottom: '底部外径', height: '总高 / 厚', wall: '壁厚', domeR: '顶部凸圆 R', platform: '顶部平台',
+  recessR: '屏边凹圆 R', recessDepth: '沉台深度', screenD: '屏 / 沉台直径', screenH: '屏高', chamferC: '底边倒角 C', draft: '拔模角',
+  cornerR: '水平角 R', length: '长度', capR: '长边圆角 R', ringD: '内径', ringBandW: '截面宽', split: '拼色分割', bandD: '表带连接宽',
+};
+export { PARAM_LABEL };
+
+/** 生产需求单(Markdown) */
+export function specMarkdown({ product, params, arc, customs, qty, rk, checks }) {
+  const p = product;
+  const rule = RULES[rk] || RULES.injection;
+  const L = [];
+  const date = new Date().toISOString().slice(0, 10);
+  L.push(`# 生产需求单 · ${p.name}`, '');
+  L.push(`- 型号:${p.latin || p.name}(${p.id})`);
+  L.push(`- 日期:${date};单位 mm;数量 ${qty} 套;币种 CNY`);
+  L.push('- 本单由 Pocket Hardware Lab 实验室按当前 3D 参数快照自动生成(FmodeCode)', '');
+  L.push('## 1. 参数快照', '', '| 参数 | 键 | 数值 |', '| --- | --- | --- |');
+  for (const [k, v] of Object.entries(params || {})) if (typeof v === 'number') L.push(`| ${PARAM_LABEL[k] || k} | ${k} | ${f2(v)} |`);
+  L.push('', '派生尺寸:', ...derived(p.shape?.type, params || {}, arc || {}).map(([k, v]) => `- ${k}:${v}`), '');
+  if (p.shape?.type === 'round' || p.shape?.type === 'ring' || p.shape?.type === 'watch') {
+    L.push('> **CNC 弧面编程参数**:外壁顶部凸圆 R' + f2(arc?.crownR) + `,屏边凹圆弧 R${f2(arc?.recessR)}(沉台深 ${f2(params?.recessDepth)}),底边倒角 C${f2(arc?.chamferC)}。`);
+    L.push('> 弧面用 R≥1 的球头 / 圆鼻刀连续走刀;过渡区允许刀纹,不允许接刀台阶;关键尺寸按 ±0.05 检验并出首件报告。', '');
+  }
+  L.push('## 2. 公差与验收', '', '| 部位 | 公差 |', '| --- | --- |');
+  for (const pt of p.parts || []) if (pt.tolerance) L.push(`| ${pt.name} | ${pt.tolerance} |`);
+  L.push('| 首件 | 三坐标 / 影像仪报告 + 实配照片 |', '| 抽检 | AQL 1.0 外观 / 0.65 关键尺寸 |', '');
+  L.push('## 3. 装配顺序', '');
+  (p.processes || []).forEach((pr, i) => L.push(`${i + 1}. **${pr.name}**:${pr.desc || pr.equipment || '—'}${pr.bulkDays ? `(批量 ${pr.bulkDays})` : ''}`));
+  L.push('', '## 4. 自定义结构件坐标表(壳底中心为原点;X 右 / Y 上(高度)/ Z 前)', '');
+  if (!(customs || []).length) L.push('- 暂无自定义结构件(按主体参数推定)。');
+  else {
+    L.push('| # | 类型 | x (mm) | y (mm) | z (mm) | 外形尺寸 | 绕 Y 转向 | 工艺要求 |', '| --- | --- | --- | --- | --- | --- | --- | --- |');
+    (customs || []).forEach((s, i) => L.push(`| ${i + 1} | ${(PRIMS[s.type] || {}).n || s.type} | ${f2(s.x)} | ${f2(s.y)} | ${f2(s.z)} | ${primDimText(s)} | ${f1(s.rot || 0)}° | ${primRequirement(s, rk)} |`));
+    L.push('', '> 结构件已随主体写入 STL;CNC 报价请按「上表坐标 + 刀具半径」评估,注塑按壁厚 / 拔模评估。');
+  }
+  L.push('', `## 5. 工艺校验(${rule.name})`, '');
+  for (const c of checks || []) L.push(`- [${c.ok ? 'x' : ' '}] ${c.ok ? '通过' : '待改'}:${c.t}`);
+  L.push('', '## 6. 供应商报价回填表', '', '| 项目 | 供应商填写 |', '| --- | --- |');
+  for (const x of ['模具费(含试模 / 改模)', '单品单价(含税 / 不含税)', '最小起订量 MOQ', '打样费及抵扣规则', '交期(打样 / 大货)', '模具归属', '包装方式与费用', '有效期']) L.push(`| ${x} |  |`);
+  L.push('', '---', '生产需求单由 Pocket Hardware Lab · FmodeCode 生成;价格口径见产品页,不构成报价承诺。');
+  return L.join('\n');
+}
+
+export function bomCsv(product) {
+  const rows = [['序号', '分组', '名称', '规格', '供应商', '单价', '数量', '小计']];
+  for (const r of product.bom?.rows || []) rows.push([r.seq, r.group || '', r.name, r.spec || '', r.supplier || '', r.price, r.qty, r.subtotal]);
+  rows.push(['', '', '合计', '', '', '', '', product.bom?.bomTotal ?? '']);
+  return rows.map((r) => r.map((v) => `"${String(v ?? '').replace(/"/g, '""')}"`).join(',')).join('\n');
+}
+
+export function specJson({ product, params, arc, customs, qty, rk }) {
+  return JSON.stringify({
+    app: 'Pocket Hardware Lab', version: 'v3', generator: 'FmodeCode', exportedAt: new Date().toISOString(), unit: 'mm',
+    product: { id: product.id, name: product.name, latin: product.latin, shape: product.shape?.type },
+    rule: rk, qty, params, arc, customParts: customs || [], derived: derived(product.shape?.type, params, arc),
+    bom: product.bom, processes: product.processes,
+  }, null, 2);
+}
+
+/* =========================================================
+   工艺弧面 → 解码后的实体尺寸(3D 适配器直接读这些值)
+   ========================================================= */
+/**
+ * 圆件「工艺弧面」三参数(顶部凸圆 R / 屏边凹圆 R / 沉台深)+ 底边倒角 C,
+ * 折成 roundProfile 能吃的形参:凸圆/凹圆/平台占壁厚预算,沉台按弧深加深。
+ */
+export function arcApplied(profileParams, arc, rk) {
+  const p = { ...profileParams };
+  const wall = num(p.wall, 1.5);
+  const D = num(p.dTop, 40);
+  const crown = clamp(num(arc?.crownR, 0.8), 0.4, 4);
+  const recess = clamp(num(arc?.recessR, 0.5), 0.2, Math.min(4, wall * 0.9));
+  const cham = clamp(num(arc?.chamferC, 0.5), 0, 3);
+  const dep = clamp(num(p.recessDepth, 1) + recess * 0.5, 0.3, Math.max(0.4, num(p.height) * 0.5));
+  // 圆角/倒角有工艺最小;注塑/硅胶 凸圆不能把壁厚吃光
+  const budget = Math.max(0.6, D / 2 - num(p.screenD, D) / 2);
+  const crownUse = Math.min(crown, Math.max(0.4, budget - recess - 0.1), wall * 0.9);
+  p.domeR = r2(crownUse);
+  p.recessR = r2(recess);
+  p.platform = r2(Math.max(0.1, Math.min(num(p.platform, 0.3), budget - crownUse - recess - 0.05)));
+  p.recessDepth = r2(dep);
+  p.chamferC = r2(cham);
+  if (rk === 'cnc') p.draft = num(p.draft, 1);
+  return p;
+}

+ 13 - 2
site/index.html

@@ -8,8 +8,19 @@
   <title>Pocket Hardware Lab · FmodeCode</title>
   <meta name="generator" content="FmodeCode" />
   <meta name="description" content="把一款 AI 硬件,从想法做到能报价下单:外壳参数、物料清单、生产工艺与成本测算。FmodeCode 出品。" />
-  <!-- base 与 importmap 均相对,子路径部署零改动 -->
-  <base href="./" />
+  <!-- 部署基址:path 路由下 /p/<id> 是深路径,相对 base 会解析成 /p/ 导致资源全 404,
+       所以这里同步算出站点根并写入 base 元素,必须在任何相对 URL 解析之前完成。 -->
+  <script>
+    (function () {
+      var path = location.pathname;
+      var dir = path.replace(/[^/]*\.html?$/, '');
+      dir = dir.replace(/\/(p|lab)\/[^/]+\/?$/, '/');
+      if (dir.charAt(dir.length - 1) !== '/') dir += '/';
+      var b = document.createElement('base');
+      b.href = dir;
+      document.head.appendChild(b);
+    })();
+  </script>
   <link rel="stylesheet" href="./assets/theme.css" />
   <meta name="application-name" content="FmodeCode" />
   <meta name="author" content="FmodeCode" />

+ 2 - 2
site/page/lab.js

@@ -8,7 +8,7 @@ import '../wc/ph-bom.js';
 import { PhPage } from '../lib/base.js';
 import { loadProduct } from '../services/products.js';
 import { KEY_LABEL, rangeFor, stepFor } from '../utils/format.js';
-import { linkHref } from '../utils/router.js';
+import { linkHref, currentPath } from '../utils/router.js';
 import { labStyle } from './styles/lab-style.js';
 import { applyCss } from '../lib/css.js';
 
@@ -51,7 +51,7 @@ class PhLab extends PhPage {
   }
 
   setup() {
-    const m = location.hash.match(/^#\/lab\/([^/?#]+)/);
+    const m = currentPath().match(/^\/lab\/([^/?#]+)/);
     this.id = m ? decodeURIComponent(m[1]) : '';
     return this._load();
   }

+ 70 - 5
site/page/product.js

@@ -10,11 +10,49 @@ import { PhPage } from '../lib/base.js';
 import { loadProduct } from '../services/products.js';
 import { themeCss, sharedHtmlCss, brandFooter, footerCss } from '../utils/theme.js';
 import { money, pct, num } from '../utils/format.js';
-import { linkHref } from '../utils/router.js';
+import { linkHref, currentPath } from '../utils/router.js';
 import { applyCss } from '../lib/css.js';
 import { productStyle } from './styles/product-style.js';
 
 /** 内容段旁的线条示意:仅「结构」「工艺/材质工艺」段 */
+
+/** 每款产品的场景 look 图清单(主题场景 + 使用瞬间 + 行业场景) */
+const LOOK_MAP = {
+  'recorder-bean': [
+    { file: 'recorder-bean-scene-interview.png', alt: '采访场景', cap: '会议与采访 · 贴在笔记本上就开录' },
+    { file: 'recorder-bean-scene-pocket.png', alt: '衬衫口袋磁吸', cap: '磁吸贴合 · 一片圆盘藏进口袋' },
+  ],
+  'watch-case': [
+    { file: 'watch-case-scene-outdoor.png', alt: '户外运动', cap: '户外与运动 · 犄角护住每一次磕碰' },
+    { file: 'watch-case-scene-desk.png', alt: '日常桌面', cap: '通勤日常 · 双色撞出一点脾气' },
+  ],
+  'round-screen': [
+    { file: 'round-screen-scene-desk.png', alt: '书房桌面', cap: '书房桌面 · 一只抬眼看你的圆眼' },
+    { file: 'round-screen-scene-bedside.png', alt: '床头夜间', cap: '床头夜灯 · 深夜也有一束微光' },
+  ],
+  'ai-pin': [
+    { file: 'ai-pin-scene-suit.png', alt: '西装佩戴', cap: '商务场合 · 别在翻领上的第二块屏' },
+    { file: 'ai-pin-scene-walk.png', alt: '毛衣佩戴', cap: '日常穿搭 · 40mm 圆片几乎无感' },
+  ],
+  'eink-tag': [
+    { file: 'eink-tag-scene-desk.png', alt: '办公桌面', cap: '办公桌面 · 抬头一眼看清今天' },
+    { file: 'eink-tag-scene-kitchen.png', alt: '厨房台面', cap: '厨房与家 · 两周不用充电的常显' },
+  ],
+  'pocket-ai': [
+    { file: 'pocket-ai-scene-cafe.png', alt: '咖啡馆', cap: '咖啡馆 · 合上是书,翻开是终端' },
+    { file: 'pocket-ai-scene-train.png', alt: '高铁出行', cap: '移动办公 · 铝盖与实体键盘' },
+  ],
+  'bone-headset': [
+    { file: 'bone-headset-scene-run.png', alt: '晨跑', cap: '晨跑 · 耳朵是开着的' },
+    { file: 'bone-headset-scene-bike.png', alt: '骑行通勤', cap: '骑行通勤 · 听得见路况,也听得见歌' },
+  ],
+  'smart-ring': [
+    { file: 'smart-ring-scene-sleep.png', alt: '睡眠场景', cap: '整夜陪伴 · 7.9g 戴着无感' },
+    { file: 'smart-ring-scene-work.png', alt: '办公打字', cap: '日常办公 · 钛圈不挡键盘' },
+  ],
+};
+function LOOK_LIST(id) { return LOOK_MAP[id] || []; }
+
 function diagramFor(title) {
   if (/结构/.test(title)) return 'section';
   if (/工艺|材质/.test(title)) return 'chamfer';
@@ -38,7 +76,8 @@ class PhProductPage extends PhPage {
   }
 
   setup() {
-    this.id = currentId();
+    // 以路由解析出的 :id 为准(导航竞态下由 app.js 的导航令牌丢弃过期结果)
+    this.id = this.ctx?.params?.id || currentId();
     return this._load();
   }
 
@@ -103,6 +142,29 @@ class PhProductPage extends PhPage {
 
         <section class="block claim"><p>${p.tagline}</p></section>
 
+        <section class="block look">
+          <div class="inner">
+            <p class="eyebrow">Look & Feel</p>
+            <h2 class="h2">它在生活里的样子</h2>
+            <div class="look-grid">
+              ${LOOK_LIST(p.id).map((it, i) => html`
+                <figure class="look-item ${i === 0 ? 'wide' : ''}">
+                  <img src="./assets/look/${it.file}" alt="${p.name} — ${it.alt}" width="1792" height="1024" loading="lazy" decoding="async" />
+                  <figcaption>${it.cap}</figcaption>
+                </figure>`)}
+            </div>
+          </div>
+        </section>
+
+        <section class="block macro">
+          <div class="inner">
+            <figure class="macro-item">
+              <img src="./assets/detail/${p.id}-detail.png" alt="${p.name} 细节特写" width="1792" height="1024" loading="lazy" decoding="async" />
+              <figcaption>工艺细节 · 微距</figcaption>
+            </figure>
+          </div>
+        </section>
+
         <section class="block"><div class="inner">
           <dl class="specs">
             ${(d.specs || []).map((s) => html`<div class="spec"><dt>${s.k}</dt><dd>${s.v}</dd></div>`)}
@@ -123,6 +185,10 @@ class PhProductPage extends PhPage {
         </div></div>
 
         <section class="block" id="bom"><div class="inner">
+          <figure class="explode">
+            <img src="./assets/detail/${p.id}-explode.png" alt="${p.name} 结构爆炸图" width="1792" height="1024" loading="lazy" decoding="async" />
+            <figcaption>结构分解 · 按层拆解</figcaption>
+          </figure>
           <div class="block-head">
             <p class="eyebrow">Bill of Materials</p>
             <h2 class="h2">物料清单 · BOM</h2>
@@ -198,14 +264,13 @@ class PhProductPage extends PhPage {
 customElements.define('ph-product', PhProductPage);
 
 function currentId() {
-  const m = location.hash.match(/^#\/p\/([^/?#]+)/);
+  const m = (currentPath() || '').match(/^\/p\/([^/?#]+)/);
   return m ? decodeURIComponent(m[1]) : '';
 }
 
 export function productPage(ctx) {
   const el = new PhProductPage();
+  el.ctx = ctx;
   el.title = 'Pocket Hardware Lab · FmodeCode';
-  // ctx.params.id 与 currentId() 一致;setUp 以 hash 为准(导航竞态下更稳)
-  void ctx;
   return el;
 }

+ 18 - 1
site/page/styles/product-style.js

@@ -94,7 +94,24 @@ const own = String.raw`  :host {
     .sec.has-fig { grid-template-columns: minmax(0, 1fr) minmax(0, 360px); }
     @media (max-width: 860px) { .sec.has-fig { grid-template-columns: 1fr; } }
     .sec .eyebrow { margin-bottom: 18px; }
-    .sec p { margin: 0; font-size: clamp(18px, 1.8vw, 20px); line-height: 1.75; color: var(--ink); letter-spacing: 0.002em; }
+
+    /* ——— 场景 look 图 ——— */
+    .look-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: clamp(16px, 2.4vw, 28px); margin-top: clamp(24px, 3vw, 40px); }
+    .look-item { margin: 0; }
+    .look-item img { width: 100%; height: auto; display: block; border-radius: 18px; background: var(--bg-soft); }
+    .look-item figcaption { margin-top: 12px; font-size: 14px; line-height: 1.5; color: var(--ink-2); }
+    @media (max-width: 760px) { .look-grid { grid-template-columns: 1fr; } }
+
+    /* ——— 微距细节 ——— */
+    .macro-item { margin: 0; }
+    .macro-item img { width: 100%; height: auto; display: block; border-radius: 22px; background: var(--bg-soft); }
+    .macro-item figcaption { margin-top: 14px; font-size: 14px; color: var(--ink-3); text-align: center; letter-spacing: 0.04em; }
+
+    /* ——— 结构爆炸图 ——— */
+    .explode { margin: 0 0 clamp(32px, 4vw, 56px); }
+    .explode img { width: 100%; height: auto; display: block; border-radius: 22px; background: var(--bg-soft); }
+    .explode figcaption { margin-top: 14px; font-size: 14px; color: var(--ink-3); text-align: center; letter-spacing: 0.04em; }
+    .sec p { margin: 0 0 1.15em; font-size: clamp(18px, 1.8vw, 20px); line-height: 1.85; color: var(--ink); letter-spacing: 0.002em; }
     .fig { margin: 0; }
 
     /* 5. BOM */

+ 87 - 28
site/utils/router.js

@@ -1,20 +1,43 @@
 /**
- * utils/router.js —— hash 路由(#/、#/p/<id>、#/lab/<id>)。
- * 原生 hashchange 驱动;子路径部署安全(hash 与部署前缀无关)。链接用 <a data-link href="#/...">,
- * 全局统一拦截,只改 hash,不整页刷新。
+ * utils/router.js —— History API path 路由(/、/p/<id>、/lab/<id>)。
+ *
+ * - 子路径部署:base 取自 <base href>(解成绝对 URL),所有链接 / 比较都带 base 前缀。
+ * - 不支持 pushState(file:// 等)时自动退回 hash(#/p/<id>),功能不变。
+ * - 旧 hash 链接(#/p/<id>)启动时 replaceState 改写成对应 path,刷新也不丢。
+ * - 链接统一 <a data-link href="...">:全局拦截左键点击 → 只改 history,不整页刷新;
+ *   target="_blank" / ctrl·cmd·shift·alt 点击 / 中键 / download / 外域 一律交还浏览器默认。
  */
+import { docBase } from '../config.js';
 
-/** '/p/ai-pin' → '#/p/ai-pin' */
+let BASE = '/';
+try { BASE = new URL(docBase()).pathname.replace(/\/+$/, ''); } catch { BASE = ''; }
+/** 应用内路径 → 浏览器路径('/p/x' → '<base>/p/x') */
+export function appPath(p) {
+  const clean = '/' + String(p || '').replace(/^#/, '').replace(/^\/+/, '');
+  return BASE + (clean === '/' ? '/' : clean);
+}
+
+/** pushState 是否可用(file:// 下不可用) */
+export const canHistory = (() => {
+  try { return location.protocol !== 'file:' && typeof history.pushState === 'function'; } catch { return false; }
+})();
+
+/** '/p/ai-pin' → '/base/p/ai-pin'(history 模式)或 '#/p/ai-pin'(hash 回退) */
 export function linkHref(path) {
-  const clean = String(path || '/').replace(/^#/, '');
-  return '#' + (clean.startsWith('/') ? clean : '/' + clean);
+  return canHistory ? appPath(path) : '#' + (String(path || '/').startsWith('/') ? path : '/' + path);
 }
 
-/** 当前 hash → 应用内路径('#/' → '/', '' → '/') */
+/** 浏览器路径 → 应用内路径;不在 base 下(外域 / 静态资源)返回 null */
 export function currentPath() {
-  const h = location.hash.replace(/^#/, '');
-  if (!h) return '/';
-  return '/' + h.replace(/^\/+/, '');
+  if (!canHistory) {
+    const h = location.hash.replace(/^#/, '');
+    return h ? '/' + h.replace(/^\/+/, '') : '/';
+  }
+  let p = location.pathname;
+  try { p = decodeURIComponent(p); } catch { /* 保留原文 */ }
+  if (BASE && p !== BASE && !p.startsWith(BASE + '/')) return null;
+  p = p.slice(BASE.length) || '/';
+  return p.startsWith('/') ? p : '/' + p;
 }
 
 /** 路由匹配:支持 :param;'*' 为兜底 */
@@ -34,22 +57,36 @@ export function matchRoute(pattern, path) {
   return params;
 }
 
+/** 启动时把 '#/...' 旧链接改写成 path(或把缺失的 hash 规范) */
+function normalizeLegacy() {
+  const h = location.hash;
+  if (!h || !h.startsWith('#/')) return false;
+  const path = h.slice(1);
+  const url = canHistory ? appPath(path) + location.search : location.pathname + location.search + '#' + path;
+  try { history.replaceState({ ph: 1, legacy: true }, '', url); } catch { return false; }
+  return true;
+}
+
 export function createRouter(routes) {
   const listeners = new Set();
+  const notify = () => { for (const fn of listeners) fn(); };
   const router = {
+    base: BASE,
     navigate(path, { replace = false } = {}) {
-      const hash = linkHref(path);
-      if (location.hash === hash) { for (const fn of listeners) fn(); return; }
-      if (replace) {
-        const url = location.pathname + location.search + hash;
-        history.replaceState({}, '', url);
-        for (const fn of listeners) fn();
-      } else {
-        location.hash = hash; // 触发 hashchange → notify
+      if (!canHistory) {
+        const hash = linkHref(path);
+        if (location.hash === hash) { notify(); return; }
+        if (replace) { history.replaceState({}, '', location.pathname + location.search + hash); notify(); }
+        else location.hash = hash;
+        return;
       }
+      const url = appPath(path) + location.search;
+      if (location.pathname + location.search === url && !location.hash) { notify(); return; }
+      history[replace ? 'replaceState' : 'pushState']({ ph: 1 }, '', url);
+      notify();
     },
     resolve() {
-      const path = currentPath();
+      const path = currentPath() ?? location.pathname;
       for (const r of routes) {
         const params = matchRoute(r.path, path);
         if (params) return { path, params, route: r.path, render: r.render };
@@ -59,22 +96,44 @@ export function createRouter(routes) {
     },
     subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn); },
     start(paint) {
-      try { paint(); } catch (e) { console.error('[router] paint initial', e); }
-      addEventListener('hashchange', paint);
       history.scrollRestoration = 'manual';
+      normalizeLegacy();
+      try { paint(); } catch (e) { console.error('[router] paint initial', e); }
+      if (canHistory) {
+        addEventListener('popstate', paint);
+        // 中转站页面(404.html 副本)把目标路径塞进 sessionStorage:地址栏修正为干净的 path
+        try {
+          const saved = sessionStorage.getItem('ph:spa-target');
+          if (saved) {
+            sessionStorage.removeItem('ph:spa-target');
+            if (saved !== location.pathname) history.replaceState({ ph: 1, from404: true }, '', saved + location.search + location.hash);
+          }
+        } catch { /* 隐私模式 */ }
+      } else {
+        addEventListener('hashchange', paint);
+      }
       listeners.add(paint);
       // composedPath 穿透 Shadow DOM;无修饰键左键才算导航
       document.addEventListener('click', (e) => {
         if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
-        const a = e.composedPath().find((n) => n instanceof HTMLAnchorElement && n.hasAttribute('data-link'));
-        if (!a || a.target === '_blank') return;
-        e.preventDefault();
+        const a = e.composedPath().find((n) => n instanceof HTMLAnchorElement);
+        if (!a) return;
+        if (a.target && a.target !== '_self') return;
+        if (a.hasAttribute('download')) return;
         const href = a.getAttribute('href');
-        if (!href.startsWith('#')) return;
-        if (location.hash === href) { for (const fn of listeners) fn(); return; }
-        location.hash = href;
+        if (!href || href.startsWith('mailto:') || href.startsWith('tel:')) return;
+        const u = new URL(href, location.href);
+        if (u.origin !== location.origin) return;            // 外域:交给浏览器
+        if (canHistory && href.startsWith('#')) return;       // 页内锚点:交给浏览器
+        if (!canHistory && !href.startsWith('#')) return;
+        // 只接管站内路径;静态资源(带扩展名)与 base 之外的路径交还浏览器
+        const isStatic = /\.[a-z0-9]{2,5}$/i.test(u.pathname);
+        if (canHistory && (isStatic || (BASE && u.pathname !== BASE && !u.pathname.startsWith(BASE + '/')))) return;
+        if (!canHistory && !href.startsWith('#/') && href !== '#') return;
+        e.preventDefault();
+        const path = canHistory ? (u.pathname.slice(BASE.length) || '/') : u.hash.slice(1);
+        router.navigate(path);
       });
-      if (!location.hash) history.replaceState({}, '', location.pathname + location.search + '#/');
       return router;
     },
   };

+ 201 - 0
site/vendor/manifold/LICENSE

@@ -0,0 +1,201 @@
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.

+ 18 - 0
site/vendor/manifold/index.js

@@ -0,0 +1,18 @@
+/**
+ * vendor/manifold/index.js —— manifold-3d 3.4.0(Apache-2.0,本地随包,零外链)。
+ * 给 Babylon CSG2 提供布尔运算内核:Babylon.InitializeCSG2Async({ manifoldInstance, manifoldMeshInstance })
+ * 按 manufacture 模式初始化({ wasm }),wasm 文件与 manifold.js 同目录,由 locateFile 自动解析。
+ */
+import Module from './manifold.js';
+
+let ready = null;
+
+export function manifoldReady() {
+  if (!ready) {
+    ready = Module({}).then((wasm) => {
+      wasm.setup();
+      return { Manifold: wasm.Manifold, Mesh: wasm.Mesh };
+    });
+  }
+  return ready;
+}

+ 3047 - 0
site/vendor/manifold/manifold.js

@@ -0,0 +1,3047 @@
+var Module = (() => {
+  var _scriptName = import.meta.url;
+
+  return (async function(moduleArg = {}) {
+    var moduleRtn;
+
+    var Module = moduleArg;
+    var readyPromiseResolve, readyPromiseReject;
+    var readyPromise = new Promise((resolve, reject) => {
+      readyPromiseResolve = resolve;
+      readyPromiseReject = reject
+    });
+    var ENVIRONMENT_IS_WEB = typeof window == 'object';
+    var ENVIRONMENT_IS_WORKER = typeof WorkerGlobalScope != 'undefined';
+    var ENVIRONMENT_IS_NODE = typeof process == 'object' &&
+        typeof process.versions == 'object' &&
+        typeof process.versions.node == 'string' && process.type != 'renderer';
+    if (ENVIRONMENT_IS_NODE) {
+      const {createRequire} = await import('module');
+      var require = createRequire(import.meta.url)
+    }
+    var _ManifoldInitialized = false;
+    Module.setup = function() {
+      if (_ManifoldInitialized) return;
+      _ManifoldInitialized = true;
+      Module.initTBB();
+      function toVec(vec, list, f = (x => x)) {
+        if (list) {
+          for (let x of list) {
+            vec.push_back(f(x))
+          }
+        }
+        return vec
+      }
+      function fromVec(vec, f = (x => x)) {
+        const result = [];
+        const size = vec.size();
+        for (let i = 0; i < size; i++) result.push(f(vec.get(i)));
+        return result
+      }
+      function vec2polygons(vec, f = (x => x)) {
+        const result = [];
+        const nPoly = vec.size();
+        for (let i = 0; i < nPoly; i++) {
+          const v = vec.get(i);
+          const nPts = v.size();
+          const poly = [];
+          for (let j = 0; j < nPts; j++) {
+            poly.push(f(v.get(j)))
+          }
+          result.push(poly)
+        }
+        return result
+      }
+      function polygons2vec(polygons) {
+        if (polygons[0].length < 3) {
+          polygons = [polygons]
+        }
+        return toVec(
+            new Module.Vector2_vec2, polygons,
+            poly => toVec(new Module.Vector_vec2, poly, p => {
+              if (p instanceof Array) return {x: p[0], y: p[1]};
+              return p
+            }))
+      }
+      function disposePolygons(polygonsVec) {
+        for (let i = 0; i < polygonsVec.size(); i++)
+          polygonsVec.get(i).delete();
+        polygonsVec.delete()
+      }
+      function vararg2vec2(vec) {
+        if (vec[0] instanceof Array) return {x: vec[0][0], y: vec[0][1]};
+        if (typeof vec[0] == 'number') return {x: vec[0] || 0, y: vec[1] || 0};
+        return vec[0]
+      }
+      function vararg2vec3(vec) {
+        if (vec[0] instanceof Array)
+          return {x: vec[0][0], y: vec[0][1], z: vec[0][2]};
+        if (typeof vec[0] == 'number')
+          return {x: vec[0] || 0, y: vec[1] || 0, z: vec[2] || 0};
+        return vec[0]
+      }
+      function fillRuleToInt(fillRule) {
+        return fillRule == 'EvenOdd' ? 0 :
+            fillRule == 'NonZero'    ? 1 :
+            fillRule == 'Negative'   ? 3 :
+                                       2
+      }
+      function joinTypeToInt(joinType) {
+        return joinType == 'Round' ? 1 : joinType == 'Miter' ? 2 : 0
+      }
+      const CrossSectionCtor = Module.CrossSection;
+      function cross(polygons, fillRule = 'Positive') {
+        if (polygons instanceof CrossSectionCtor) {
+          return polygons
+        } else {
+          const polygonsVec = polygons2vec(polygons);
+          const cs = new CrossSectionCtor(polygonsVec, fillRuleToInt(fillRule));
+          disposePolygons(polygonsVec);
+          return cs
+        }
+      }
+      Module.CrossSection.prototype.translate = function(...vec) {
+        return this._Translate(vararg2vec2(vec))
+      };
+      Module.CrossSection.prototype.scale = function(vec) {
+        if (typeof vec == 'number') {
+          return this._Scale({x: vec, y: vec})
+        }
+        return this._Scale(vararg2vec2([vec]))
+      };
+      Module.CrossSection.prototype.mirror = function(vec) {
+        return this._Mirror(vararg2vec2([vec]))
+      };
+      Module.CrossSection.prototype.warp = function(func) {
+        const wasmFuncPtr = addFunction(function(vec2Ptr) {
+          const x = getValue(vec2Ptr, 'double');
+          const y = getValue(vec2Ptr + 8, 'double');
+          const vert = [x, y];
+          func(vert);
+          setValue(vec2Ptr, vert[0], 'double');
+          setValue(vec2Ptr + 8, vert[1], 'double')
+        }, 'vi');
+        const out = this._Warp(wasmFuncPtr);
+        removeFunction(wasmFuncPtr);
+        return out
+      };
+      Module.CrossSection.prototype.decompose = function() {
+        const vec = this._Decompose();
+        const result = fromVec(vec);
+        vec.delete();
+        return result
+      };
+      Module.CrossSection.prototype.bounds = function() {
+        const result = this._Bounds();
+        return {
+          min: ['x', 'y'].map(f => result.min[f]),
+              max: ['x', 'y'].map(f => result.max[f])
+        }
+      };
+      Module.CrossSection.prototype.offset = function(
+          delta, joinType = 'Square', miterLimit = 2, circularSegments = 0) {
+        return this._Offset(
+            delta, joinTypeToInt(joinType), miterLimit, circularSegments)
+      };
+      Module.CrossSection.prototype.simplify = function(epsilon = 1e-6) {
+        return this._Simplify(epsilon)
+      };
+      Module.CrossSection.prototype.extrude = function(
+          height, nDivisions = 0, twistDegrees = 0, scaleTop = [1, 1],
+          center = false) {
+        scaleTop = vararg2vec2([scaleTop]);
+        const man = Module._Extrude(
+            this._ToPolygons(), height, nDivisions, twistDegrees, scaleTop);
+        return center ? man.translate([0, 0, -height / 2]) : man
+      };
+      Module.CrossSection.prototype.revolve = function(
+          circularSegments = 0, revolveDegrees = 360) {
+        return Module._Revolve(
+            this._ToPolygons(), circularSegments, revolveDegrees)
+      };
+      Module.CrossSection.prototype.add = function(other) {
+        return this._add(cross(other))
+      };
+      Module.CrossSection.prototype.subtract = function(other) {
+        return this._subtract(cross(other))
+      };
+      Module.CrossSection.prototype.intersect = function(other) {
+        return this._intersect(cross(other))
+      };
+      Module.CrossSection.prototype.toPolygons = function() {
+        const vec = this._ToPolygons();
+        const result = vec2polygons(vec, v => [v.x, v.y]);
+        vec.delete();
+        return result
+      };
+      Module.Manifold.prototype.smoothOut = function(
+          minSharpAngle = 60, minSmoothness = 0) {
+        return this._SmoothOut(minSharpAngle, minSmoothness)
+      };
+      Module.Manifold.prototype.warp = function(func) {
+        const wasmFuncPtr = addFunction(function(vec3Ptr) {
+          const x = getValue(vec3Ptr, 'double');
+          const y = getValue(vec3Ptr + 8, 'double');
+          const z = getValue(vec3Ptr + 16, 'double');
+          const vert = [x, y, z];
+          func(vert);
+          setValue(vec3Ptr, vert[0], 'double');
+          setValue(vec3Ptr + 8, vert[1], 'double');
+          setValue(vec3Ptr + 16, vert[2], 'double')
+        }, 'vi');
+        const out = this._Warp(wasmFuncPtr);
+        removeFunction(wasmFuncPtr);
+        const status = out.status();
+        if (status.value !== 0) {
+          throw new Module.ManifoldError(status.value)
+        }
+        return out
+      };
+      Module.Manifold.prototype.calculateNormals = function(
+          normalIdx, minSharpAngle = 60) {
+        return this._CalculateNormals(normalIdx, minSharpAngle)
+      };
+      Module.Manifold.prototype.setProperties = function(numProp, func) {
+        const oldNumProp = this.numProp();
+        const wasmFuncPtr = addFunction(function(newPtr, vec3Ptr, oldPtr) {
+          const newProp = [];
+          for (let i = 0; i < numProp; ++i) {
+            newProp[i] = getValue(newPtr + 8 * i, 'double')
+          }
+          const pos = [];
+          for (let i = 0; i < 3; ++i) {
+            pos[i] = getValue(vec3Ptr + 8 * i, 'double')
+          }
+          const oldProp = [];
+          for (let i = 0; i < oldNumProp; ++i) {
+            oldProp[i] = getValue(oldPtr + 8 * i, 'double')
+          }
+          func(newProp, pos, oldProp);
+          for (let i = 0; i < numProp; ++i) {
+            setValue(newPtr + 8 * i, newProp[i], 'double')
+          }
+        }, 'viii');
+        const out = this._SetProperties(numProp, wasmFuncPtr);
+        removeFunction(wasmFuncPtr);
+        return out
+      };
+      Module.Manifold.prototype.translate = function(...vec) {
+        return this._Translate(vararg2vec3(vec))
+      };
+      Module.Manifold.prototype.rotate = function(xOrVec, y, z) {
+        if (Array.isArray(xOrVec)) {
+          return this._Rotate(...xOrVec)
+        } else {
+          return this._Rotate(xOrVec, y || 0, z || 0)
+        }
+      };
+      Module.Manifold.prototype.scale = function(vec) {
+        if (typeof vec == 'number') {
+          return this._Scale({x: vec, y: vec, z: vec})
+        }
+        return this._Scale(vararg2vec3([vec]))
+      };
+      Module.Manifold.prototype.mirror = function(vec) {
+        return this._Mirror(vararg2vec3([vec]))
+      };
+      Module.Manifold.prototype.trimByPlane = function(normal, offset = 0) {
+        return this._TrimByPlane(vararg2vec3([normal]), offset)
+      };
+      Module.Manifold.prototype.slice = function(height = 0) {
+        const polygonsVec = this._Slice(height);
+        const result =
+            new CrossSectionCtor(polygonsVec, fillRuleToInt('Positive'));
+        disposePolygons(polygonsVec);
+        return result
+      };
+      Module.Manifold.prototype.project = function() {
+        const polygonsVec = this._Project();
+        const result =
+            new CrossSectionCtor(polygonsVec, fillRuleToInt('Positive'));
+        disposePolygons(polygonsVec);
+        return result
+      };
+      Module.Manifold.prototype.split = function(manifold) {
+        const vec = this._Split(manifold);
+        const result = fromVec(vec);
+        vec.delete();
+        return result
+      };
+      Module.Manifold.prototype.splitByPlane = function(normal, offset = 0) {
+        const vec = this._SplitByPlane(vararg2vec3([normal]), offset);
+        const result = fromVec(vec);
+        vec.delete();
+        return result
+      };
+      Module.Manifold.prototype.decompose = function() {
+        const vec = this._Decompose();
+        const result = fromVec(vec);
+        vec.delete();
+        return result
+      };
+      Module.Manifold.prototype.boundingBox = function() {
+        const result = this._boundingBox();
+        return {
+          min: ['x', 'y', 'z'].map(f => result.min[f]),
+              max: ['x', 'y', 'z'].map(f => result.max[f])
+        }
+      };
+      class Mesh {
+        constructor({
+          numProp = 3,
+          triVerts = new Uint32Array,
+          vertProperties = new Float32Array,
+          mergeFromVert,
+          mergeToVert,
+          runIndex,
+          runOriginalID,
+          faceID,
+          halfedgeTangent,
+          runTransform
+        } = {}) {
+          this.numProp = numProp;
+          this.triVerts = triVerts;
+          this.vertProperties = vertProperties;
+          this.mergeFromVert = mergeFromVert;
+          this.mergeToVert = mergeToVert;
+          this.runIndex = runIndex;
+          this.runOriginalID = runOriginalID;
+          this.faceID = faceID;
+          this.halfedgeTangent = halfedgeTangent;
+          this.runTransform = runTransform
+        }
+        get numTri() {
+          return this.triVerts.length / 3
+        }
+        get numVert() {
+          return this.vertProperties.length / this.numProp
+        }
+        get numRun() {
+          return this.runOriginalID.length
+        }
+        merge() {
+          const {changed, mesh} = Module._Merge(this);
+          Object.assign(this, {...mesh});
+          return changed
+        }
+        verts(tri) {
+          return this.triVerts.subarray(3 * tri, 3 * (tri + 1))
+        }
+        position(vert) {
+          return this.vertProperties.subarray(
+              this.numProp * vert, this.numProp * vert + 3)
+        }
+        extras(vert) {
+          return this.vertProperties.subarray(
+              this.numProp * vert + 3, this.numProp * (vert + 1))
+        }
+        tangent(halfedge) {
+          return this.halfedgeTangent.subarray(4 * halfedge, 4 * (halfedge + 1))
+        }
+        transform(run) {
+          const mat4 = new Array(16);
+          for (const col of [0, 1, 2, 3]) {
+            for (const row of [0, 1, 2]) {
+              mat4[4 * col + row] = this.runTransform[12 * run + 3 * col + row]
+            }
+          }
+          mat4[15] = 1;
+          return mat4
+        }
+      }
+      Module.Mesh = Mesh;
+      Module.Manifold.prototype.getMesh = function(normalIdx = -1) {
+        return new Mesh(this._GetMeshJS(normalIdx))
+      };
+      Module.ManifoldError = function ManifoldError(code, ...args) {
+        let message = 'Unknown error';
+        switch (code) {
+          case Module.status.NonFiniteVertex.value:
+            message = 'Non-finite vertex';
+            break;
+          case Module.status.NotManifold.value:
+            message = 'Not manifold';
+            break;
+          case Module.status.VertexOutOfBounds.value:
+            message = 'Vertex index out of bounds';
+            break;
+          case Module.status.PropertiesWrongLength.value:
+            message = 'Properties have wrong length';
+            break;
+          case Module.status.MissingPositionProperties.value:
+            message = 'Less than three properties';
+            break;
+          case Module.status.MergeVectorsDifferentLengths.value:
+            message = 'Merge vectors have different lengths';
+            break;
+          case Module.status.MergeIndexOutOfBounds.value:
+            message = 'Merge index out of bounds';
+            break;
+          case Module.status.TransformWrongLength.value:
+            message = 'Transform vector has wrong length';
+            break;
+          case Module.status.RunIndexWrongLength.value:
+            message = 'Run index vector has wrong length';
+            break;
+          case Module.status.FaceIDWrongLength.value:
+            message = 'Face ID vector has wrong length';
+          case Module.status.InvalidConstruction.value:
+            message = 'Manifold constructed with invalid parameters'
+        }
+        const base = Error.apply(this, [message, ...args]);
+        base.name = this.name = 'ManifoldError';
+        this.message = base.message;
+        this.stack = base.stack;
+        this.code = code
+      };
+      Module.ManifoldError.prototype = Object.create(Error.prototype, {
+        constructor:
+            {value: Module.ManifoldError, writable: true, configurable: true}
+      });
+      Module.CrossSection = function(polygons, fillRule = 'Positive') {
+        const polygonsVec = polygons2vec(polygons);
+        const cs = new CrossSectionCtor(polygonsVec, fillRuleToInt(fillRule));
+        disposePolygons(polygonsVec);
+        return cs
+      };
+      Module.CrossSection.ofPolygons = function(
+          polygons, fillRule = 'Positive') {
+        return new Module.CrossSection(polygons, fillRule)
+      };
+      Module.CrossSection.square = function(...args) {
+        let size = undefined;
+        if (args.length == 0)
+          size = {x: 1, y: 1};
+        else if (typeof args[0] == 'number')
+          size = {x: args[0], y: args[0]};
+        else
+          size = vararg2vec2(args);
+        const center = args[1] || false;
+        return Module._Square(size, center)
+      };
+      Module.CrossSection.circle = function(radius, circularSegments = 0) {
+        return Module._Circle(radius, circularSegments)
+      };
+      function crossSectionBatchbool(name) {
+        return function(...args) {
+          if (args.length == 1) args = args[0];
+          const v = new Module.Vector_crossSection;
+          for (const cs of args) v.push_back(cross(cs));
+          const result = Module['_crossSection' + name](v);
+          v.delete();
+          return result
+        }
+      }
+      Module.CrossSection.compose = crossSectionBatchbool('Compose');
+      Module.CrossSection.union = crossSectionBatchbool('UnionN');
+      Module.CrossSection.difference = crossSectionBatchbool('DifferenceN');
+      Module.CrossSection.intersection = crossSectionBatchbool('IntersectionN');
+      function pushVec2(vec, ps) {
+        toVec(vec, ps, p => {
+          if (p instanceof Array) return {x: p[0], y: p[1]};
+          return p
+        })
+      }
+      Module.CrossSection.hull = function(...args) {
+        if (args.length == 1) args = args[0];
+        let pts = new Module.Vector_vec2;
+        for (const cs of args) {
+          if (cs instanceof CrossSectionCtor) {
+            Module._crossSectionCollectVertices(pts, cs)
+          } else if (
+              cs instanceof Array && cs.length == 2 &&
+              typeof cs[0] == 'number') {
+            pts.push_back({x: cs[0], y: cs[1]})
+          } else if (cs.x) {
+            pts.push_back(cs)
+          } else {
+            const wrap =
+                cs[0].length == 2 && typeof cs[0][0] == 'number' || cs[0].x;
+            const polys = wrap ? [cs] : cs;
+            for (const poly of polys) pushVec2(pts, poly)
+          }
+        }
+        const result = Module._crossSectionHullPoints(pts);
+        pts.delete();
+        return result
+      };
+      Module.CrossSection.prototype = Object.create(CrossSectionCtor.prototype);
+      Object.defineProperty(
+          Module.CrossSection, Symbol.hasInstance,
+          {get: () => t => t instanceof CrossSectionCtor});
+      const ManifoldCtor = Module.Manifold;
+      Module.Manifold = function(mesh) {
+        const manifold = new ManifoldCtor(mesh);
+        const status = manifold.status();
+        if (status.value !== 0) {
+          throw new Module.ManifoldError(status.value)
+        }
+        return manifold
+      };
+      Module.Manifold.ofMesh = function(mesh) {
+        return new Module.Manifold(mesh)
+      };
+      Module.Manifold.tetrahedron = function() {
+        return Module._Tetrahedron()
+      };
+      Module.Manifold.cube = function(...args) {
+        let size = undefined;
+        if (args.length == 0)
+          size = {x: 1, y: 1, z: 1};
+        else if (typeof args[0] == 'number')
+          size = {x: args[0], y: args[0], z: args[0]};
+        else
+          size = vararg2vec3(args);
+        const center = args[1] || false;
+        return Module._Cube(size, center)
+      };
+      Module.Manifold.cylinder = function(
+          height, radiusLow, radiusHigh = -1, circularSegments = 0,
+          center = false) {
+        return Module._Cylinder(
+            height, radiusLow, radiusHigh, circularSegments, center)
+      };
+      Module.Manifold.sphere = function(radius, circularSegments = 0) {
+        return Module._Sphere(radius, circularSegments)
+      };
+      Module.Manifold.smooth = function(mesh, sharpenedEdges = []) {
+        const sharp = new Module.Vector_smoothness;
+        toVec(sharp, sharpenedEdges);
+        const result = Module._Smooth(mesh, sharp);
+        sharp.delete();
+        return result
+      };
+      Module.Manifold.extrude = function(
+          polygons, height, nDivisions = 0, twistDegrees = 0, scaleTop = [1, 1],
+          center = false) {
+        const cs = polygons instanceof CrossSectionCtor ?
+            polygons :
+            Module.CrossSection(polygons, 'Positive');
+        return cs.extrude(height, nDivisions, twistDegrees, scaleTop, center)
+      };
+      Module.Manifold.revolve = function(
+          polygons, circularSegments = 0, revolveDegrees = 360) {
+        const cs = polygons instanceof CrossSectionCtor ?
+            polygons :
+            Module.CrossSection(polygons, 'Positive');
+        return cs.revolve(circularSegments, revolveDegrees)
+      };
+      Module.Manifold.reserveIDs = function(n) {
+        return Module._ReserveIDs(n)
+      };
+      Module.Manifold.compose = function(manifolds) {
+        const vec = new Module.Vector_manifold;
+        toVec(vec, manifolds);
+        const result = Module._manifoldCompose(vec);
+        vec.delete();
+        return result
+      };
+      function manifoldBatchbool(name) {
+        return function(...args) {
+          if (args.length == 1) args = args[0];
+          const v = new Module.Vector_manifold;
+          for (const m of args) v.push_back(m);
+          const result = Module['_manifold' + name + 'N'](v);
+          v.delete();
+          return result
+        }
+      }
+      Module.Manifold.union = manifoldBatchbool('Union');
+      Module.Manifold.difference = manifoldBatchbool('Difference');
+      Module.Manifold.intersection = manifoldBatchbool('Intersection');
+      Module.Manifold.levelSet = function(
+          sdf, bounds, edgeLength, level = 0, tolerance = -1) {
+        const bounds2 = {
+          min: {x: bounds.min[0], y: bounds.min[1], z: bounds.min[2]},
+          max: {x: bounds.max[0], y: bounds.max[1], z: bounds.max[2]}
+        };
+        const wasmFuncPtr = addFunction(function(vec3Ptr) {
+          const x = getValue(vec3Ptr, 'double');
+          const y = getValue(vec3Ptr + 8, 'double');
+          const z = getValue(vec3Ptr + 16, 'double');
+          const vert = [x, y, z];
+          return sdf(vert)
+        }, 'di');
+        const out = Module._LevelSet(
+            wasmFuncPtr, bounds2, edgeLength, level, tolerance);
+        removeFunction(wasmFuncPtr);
+        return out
+      };
+      function pushVec3(vec, ps) {
+        toVec(vec, ps, p => {
+          if (p instanceof Array) return {x: p[0], y: p[1], z: p[2]};
+          return p
+        })
+      }
+      Module.Manifold.hull = function(...args) {
+        if (args.length == 1) args = args[0];
+        let pts = new Module.Vector_vec3;
+        for (const m of args) {
+          if (m instanceof ManifoldCtor) {
+            Module._manifoldCollectVertices(pts, m)
+          } else if (
+              m instanceof Array && m.length == 3 && typeof m[0] == 'number') {
+            pts.push_back({x: m[0], y: m[1], z: m[2]})
+          } else if (m.x) {
+            pts.push_back(m)
+          } else {
+            pushVec3(pts, m)
+          }
+        }
+        const result = Module._manifoldHullPoints(pts);
+        pts.delete();
+        return result
+      };
+      Module.Manifold.prototype = Object.create(ManifoldCtor.prototype);
+      Object.defineProperty(
+          Module.Manifold, Symbol.hasInstance,
+          {get: () => t => t instanceof ManifoldCtor});
+      Module.triangulate = function(
+          polygons, epsilon = -1, allowConvex = true) {
+        const polygonsVec = polygons2vec(polygons);
+        const result = fromVec(
+            Module._Triangulate(polygonsVec, epsilon, allowConvex),
+            x => [x[0], x[1], x[2]]);
+        disposePolygons(polygonsVec);
+        return result
+      }
+    };
+    var moduleOverrides = {...Module};
+    var arguments_ = [];
+    var thisProgram = './this.program';
+    var quit_ = (status, toThrow) => {
+      throw toThrow
+    };
+    var scriptDirectory = '';
+    function locateFile(path) {
+      if (Module['locateFile']) {
+        return Module['locateFile'](path, scriptDirectory)
+      }
+      return scriptDirectory + path
+    }
+    var readAsync, readBinary;
+    if (ENVIRONMENT_IS_NODE) {
+      var fs = require('fs');
+      var nodePath = require('path');
+      if (!import.meta.url.startsWith('data:')) {
+        scriptDirectory =
+            nodePath.dirname(require('url').fileURLToPath(import.meta.url)) +
+            '/'
+      }
+      readBinary = filename => {
+        filename = isFileURI(filename) ? new URL(filename) : filename;
+        var ret = fs.readFileSync(filename);
+        return ret
+      };
+      readAsync = async (filename, binary = true) => {
+        filename = isFileURI(filename) ? new URL(filename) : filename;
+        var ret = fs.readFileSync(filename, binary ? undefined : 'utf8');
+        return ret
+      };
+      if (!Module['thisProgram'] && process.argv.length > 1) {
+        thisProgram = process.argv[1].replace(/\\/g, '/')
+      }
+      arguments_ = process.argv.slice(2);
+      quit_ = (status, toThrow) => {
+        process.exitCode = status;
+        throw toThrow
+      }
+    } else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
+      if (ENVIRONMENT_IS_WORKER) {
+        scriptDirectory = self.location.href
+      } else if (typeof document != 'undefined' && document.currentScript) {
+        scriptDirectory = document.currentScript.src
+      }
+      if (_scriptName) {
+        scriptDirectory = _scriptName
+      }
+      if (scriptDirectory.startsWith('blob:')) {
+        scriptDirectory = ''
+      } else {
+        scriptDirectory = scriptDirectory.slice(
+            0, scriptDirectory.replace(/[?#].*/, '').lastIndexOf('/') + 1)
+      }
+      {
+        if (ENVIRONMENT_IS_WORKER) {
+          readBinary = url => {
+            var xhr = new XMLHttpRequest;
+            xhr.open('GET', url, false);
+            xhr.responseType = 'arraybuffer';
+            xhr.send(null);
+            return new Uint8Array(xhr.response)
+          }
+        }
+        readAsync = async url => {
+          if (isFileURI(url)) {
+            return new Promise((resolve, reject) => {
+              var xhr = new XMLHttpRequest;
+              xhr.open('GET', url, true);
+              xhr.responseType = 'arraybuffer';
+              xhr.onload = () => {
+                if (xhr.status == 200 || xhr.status == 0 && xhr.response) {
+                  resolve(xhr.response);
+                  return
+                }
+                reject(xhr.status)
+              };
+              xhr.onerror = reject;
+              xhr.send(null)
+            })
+          }
+          var response = await fetch(url, {credentials: 'same-origin'});
+          if (response.ok) {
+            return response.arrayBuffer()
+          }
+          throw new Error(response.status + ' : ' + response.url)
+        }
+      }
+    } else {
+    }
+    var out = Module['print'] || console.log.bind(console);
+    var err = Module['printErr'] || console.error.bind(console);
+    Object.assign(Module, moduleOverrides);
+    moduleOverrides = null;
+    if (Module['arguments']) arguments_ = Module['arguments'];
+    if (Module['thisProgram']) thisProgram = Module['thisProgram'];
+    var wasmBinary = Module['wasmBinary'];
+    var wasmMemory;
+    var ABORT = false;
+    var HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAP64,
+        HEAPU64, HEAPF64;
+    var runtimeInitialized = false;
+    var isFileURI = filename => filename.startsWith('file://');
+    function updateMemoryViews() {
+      var b = wasmMemory.buffer;
+      Module['HEAP8'] = HEAP8 = new Int8Array(b);
+      Module['HEAP16'] = HEAP16 = new Int16Array(b);
+      Module['HEAPU8'] = HEAPU8 = new Uint8Array(b);
+      Module['HEAPU16'] = HEAPU16 = new Uint16Array(b);
+      Module['HEAP32'] = HEAP32 = new Int32Array(b);
+      Module['HEAPU32'] = HEAPU32 = new Uint32Array(b);
+      Module['HEAPF32'] = HEAPF32 = new Float32Array(b);
+      Module['HEAPF64'] = HEAPF64 = new Float64Array(b);
+      Module['HEAP64'] = HEAP64 = new BigInt64Array(b);
+      Module['HEAPU64'] = HEAPU64 = new BigUint64Array(b)
+    }
+    function preRun() {
+      if (Module['preRun']) {
+        if (typeof Module['preRun'] == 'function')
+          Module['preRun'] = [Module['preRun']];
+        while (Module['preRun'].length) {
+          addOnPreRun(Module['preRun'].shift())
+        }
+      }
+      callRuntimeCallbacks(onPreRuns)
+    }
+    function initRuntime() {
+      runtimeInitialized = true;
+      wasmExports['J']()
+    }
+    function postRun() {
+      if (Module['postRun']) {
+        if (typeof Module['postRun'] == 'function')
+          Module['postRun'] = [Module['postRun']];
+        while (Module['postRun'].length) {
+          addOnPostRun(Module['postRun'].shift())
+        }
+      }
+      callRuntimeCallbacks(onPostRuns)
+    }
+    var runDependencies = 0;
+    var dependenciesFulfilled = null;
+    function addRunDependency(id) {
+      runDependencies++;
+      Module['monitorRunDependencies']?.(runDependencies)
+    }
+    function removeRunDependency(id) {
+      runDependencies--;
+      Module['monitorRunDependencies']?.(runDependencies);
+      if (runDependencies == 0) {
+        if (dependenciesFulfilled) {
+          var callback = dependenciesFulfilled;
+          dependenciesFulfilled = null;
+          callback()
+        }
+      }
+    }
+    function abort(what) {
+      Module['onAbort']?.(what);
+      what = 'Aborted(' + what + ')';
+      err(what);
+      ABORT = true;
+      what += '. Build with -sASSERTIONS for more info.';
+      var e = new WebAssembly.RuntimeError(what);
+      readyPromiseReject(e);
+      throw e
+    }
+    var wasmBinaryFile;
+    function findWasmBinary() {
+      if (Module['locateFile']) {
+        return locateFile('manifold.wasm')
+      }
+      return new URL('manifold.wasm', import.meta.url).href
+    }
+    function getBinarySync(file) {
+      if (file == wasmBinaryFile && wasmBinary) {
+        return new Uint8Array(wasmBinary)
+      }
+      if (readBinary) {
+        return readBinary(file)
+      }
+      throw 'both async and sync fetching of the wasm failed'
+    }
+    async function getWasmBinary(binaryFile) {
+      if (!wasmBinary) {
+        try {
+          var response = await readAsync(binaryFile);
+          return new Uint8Array(response)
+        } catch {
+        }
+      }
+      return getBinarySync(binaryFile)
+    }
+    async function instantiateArrayBuffer(binaryFile, imports) {
+      try {
+        var binary = await getWasmBinary(binaryFile);
+        var instance = await WebAssembly.instantiate(binary, imports);
+        return instance
+      } catch (reason) {
+        err(`failed to asynchronously prepare wasm: ${reason}`);
+        abort(reason)
+      }
+    }
+    async function instantiateAsync(binary, binaryFile, imports) {
+      if (!binary && typeof WebAssembly.instantiateStreaming == 'function' &&
+          !isFileURI(binaryFile) && !ENVIRONMENT_IS_NODE) {
+        try {
+          var response = fetch(binaryFile, {credentials: 'same-origin'});
+          var instantiationResult =
+              await WebAssembly.instantiateStreaming(response, imports);
+          return instantiationResult
+        } catch (reason) {
+          err(`wasm streaming compile failed: ${reason}`);
+          err('falling back to ArrayBuffer instantiation')
+        }
+      }
+      return instantiateArrayBuffer(binaryFile, imports)
+    }
+    function getWasmImports() {
+      return {
+        a: wasmImports
+      }
+    }
+    async function createWasm() {
+      function receiveInstance(instance, module) {
+        wasmExports = instance.exports;
+        wasmExports = applySignatureConversions(wasmExports);
+        wasmMemory = wasmExports['I'];
+        updateMemoryViews();
+        wasmTable = wasmExports['L'];
+        removeRunDependency('wasm-instantiate');
+        return wasmExports
+      }
+      addRunDependency('wasm-instantiate');
+      function receiveInstantiationResult(result) {
+        return receiveInstance(result['instance'])
+      }
+      var info = getWasmImports();
+      if (Module['instantiateWasm']) {
+        return new Promise(
+            (resolve,
+             reject) => {Module['instantiateWasm'](info, (mod, inst) => {
+              receiveInstance(mod, inst);
+              resolve(mod.exports)
+            })})
+      }
+      wasmBinaryFile ??= findWasmBinary();
+      try {
+        var result = await instantiateAsync(wasmBinary, wasmBinaryFile, info);
+        var exports = receiveInstantiationResult(result);
+        return exports
+      } catch (e) {
+        readyPromiseReject(e);
+        return Promise.reject(e)
+      }
+    }
+    class ExitStatus {
+      name = 'ExitStatus';
+      constructor(status) {
+        this.message = `Program terminated with exit(${status})`;
+        this.status = status
+      }
+    }
+    var callRuntimeCallbacks = callbacks => {
+      while (callbacks.length > 0) {
+        callbacks.shift()(Module)
+      }
+    };
+    var onPostRuns = [];
+    var addOnPostRun = cb => onPostRuns.unshift(cb);
+    var onPreRuns = [];
+    var addOnPreRun = cb => onPreRuns.unshift(cb);
+    function getValue(ptr, type = 'i8') {
+      if (type.endsWith('*')) type = '*';
+      switch (type) {
+        case 'i1':
+          return HEAP8[ptr >>> 0];
+        case 'i8':
+          return HEAP8[ptr >>> 0];
+        case 'i16':
+          return HEAP16[ptr >>> 1 >>> 0];
+        case 'i32':
+          return HEAP32[ptr >>> 2 >>> 0];
+        case 'i64':
+          return HEAP64[ptr >>> 3];
+        case 'float':
+          return HEAPF32[ptr >>> 2 >>> 0];
+        case 'double':
+          return HEAPF64[ptr >>> 3 >>> 0];
+        case '*':
+          return HEAPU32[ptr >>> 2 >>> 0];
+        default:
+          abort(`invalid type for getValue: ${type}`)
+      }
+    }
+    var noExitRuntime = Module['noExitRuntime'] || true;
+    function setValue(ptr, value, type = 'i8') {
+      if (type.endsWith('*')) type = '*';
+      switch (type) {
+        case 'i1':
+          HEAP8[ptr >>> 0] = value;
+          break;
+        case 'i8':
+          HEAP8[ptr >>> 0] = value;
+          break;
+        case 'i16':
+          HEAP16[ptr >>> 1 >>> 0] = value;
+          break;
+        case 'i32':
+          HEAP32[ptr >>> 2 >>> 0] = value;
+          break;
+        case 'i64':
+          HEAP64[ptr >>> 3] = BigInt(value);
+          break;
+        case 'float':
+          HEAPF32[ptr >>> 2 >>> 0] = value;
+          break;
+        case 'double':
+          HEAPF64[ptr >>> 3 >>> 0] = value;
+          break;
+        case '*':
+          HEAPU32[ptr >>> 2 >>> 0] = value;
+          break;
+        default:
+          abort(`invalid type for setValue: ${type}`)
+      }
+    }
+    class ExceptionInfo {
+      constructor(excPtr) {
+        this.excPtr = excPtr;
+        this.ptr = excPtr - 24
+      }
+      set_type(type) {
+        HEAPU32[this.ptr + 4 >>> 2 >>> 0] = type
+      }
+      get_type() {
+        return HEAPU32[this.ptr + 4 >>> 2 >>> 0]
+      }
+      set_destructor(destructor) {
+        HEAPU32[this.ptr + 8 >>> 2 >>> 0] = destructor
+      }
+      get_destructor() {
+        return HEAPU32[this.ptr + 8 >>> 2 >>> 0]
+      }
+      set_caught(caught) {
+        caught = caught ? 1 : 0;
+        HEAP8[this.ptr + 12 >>> 0] = caught
+      }
+      get_caught() {
+        return HEAP8[this.ptr + 12 >>> 0] != 0
+      }
+      set_rethrown(rethrown) {
+        rethrown = rethrown ? 1 : 0;
+        HEAP8[this.ptr + 13 >>> 0] = rethrown
+      }
+      get_rethrown() {
+        return HEAP8[this.ptr + 13 >>> 0] != 0
+      }
+      init(type, destructor) {
+        this.set_adjusted_ptr(0);
+        this.set_type(type);
+        this.set_destructor(destructor)
+      }
+      set_adjusted_ptr(adjustedPtr) {
+        HEAPU32[this.ptr + 16 >>> 2 >>> 0] = adjustedPtr
+      }
+      get_adjusted_ptr() {
+        return HEAPU32[this.ptr + 16 >>> 2 >>> 0]
+      }
+    }
+    var exceptionLast = 0;
+    var uncaughtExceptionCount = 0;
+    function ___cxa_throw(ptr, type, destructor) {
+      ptr >>>= 0;
+      type >>>= 0;
+      destructor >>>= 0;
+      var info = new ExceptionInfo(ptr);
+      info.init(type, destructor);
+      exceptionLast = ptr;
+      uncaughtExceptionCount++;
+      throw exceptionLast
+    }
+    var __abort_js = () => abort('');
+    var structRegistrations = {};
+    var runDestructors = destructors => {
+      while (destructors.length) {
+        var ptr = destructors.pop();
+        var del = destructors.pop();
+        del(ptr)
+      }
+    };
+    function readPointer(pointer) {
+      return this['fromWireType'](HEAPU32[pointer >>> 2 >>> 0])
+    }
+    var awaitingDependencies = {};
+    var registeredTypes = {};
+    var typeDependencies = {};
+    var InternalError = Module['InternalError'] =
+        class InternalError extends Error {
+      constructor(message) {
+        super(message);
+        this.name = 'InternalError'
+      }
+    };
+    var throwInternalError = message => {
+      throw new InternalError(message)
+    };
+    var whenDependentTypesAreResolved =
+        (myTypes, dependentTypes, getTypeConverters) => {
+          myTypes.forEach(type => typeDependencies[type] = dependentTypes);
+          function onComplete(typeConverters) {
+            var myTypeConverters = getTypeConverters(typeConverters);
+            if (myTypeConverters.length !== myTypes.length) {
+              throwInternalError('Mismatched type converter count')
+            }
+            for (var i = 0; i < myTypes.length; ++i) {
+              registerType(myTypes[i], myTypeConverters[i])
+            }
+          }
+          var typeConverters = new Array(dependentTypes.length);
+          var unregisteredTypes = [];
+          var registered = 0;
+          dependentTypes.forEach((dt, i) => {
+            if (registeredTypes.hasOwnProperty(dt)) {
+              typeConverters[i] = registeredTypes[dt]
+            } else {
+              unregisteredTypes.push(dt);
+              if (!awaitingDependencies.hasOwnProperty(dt)) {
+                awaitingDependencies[dt] = []
+              }
+              awaitingDependencies[dt].push(() => {
+                typeConverters[i] = registeredTypes[dt];
+                ++registered;
+                if (registered === unregisteredTypes.length) {
+                  onComplete(typeConverters)
+                }
+              })
+            }
+          });
+          if (0 === unregisteredTypes.length) {
+            onComplete(typeConverters)
+          }
+        };
+    var __embind_finalize_value_object = function(structType) {
+      structType >>>= 0;
+      var reg = structRegistrations[structType];
+      delete structRegistrations[structType];
+      var rawConstructor = reg.rawConstructor;
+      var rawDestructor = reg.rawDestructor;
+      var fieldRecords = reg.fields;
+      var fieldTypes =
+          fieldRecords.map(field => field.getterReturnType)
+              .concat(fieldRecords.map(field => field.setterArgumentType));
+      whenDependentTypesAreResolved([structType], fieldTypes, fieldTypes => {
+        var fields = {};
+        fieldRecords.forEach((field, i) => {
+          var fieldName = field.fieldName;
+          var getterReturnType = fieldTypes[i];
+          var optional = fieldTypes[i].optional;
+          var getter = field.getter;
+          var getterContext = field.getterContext;
+          var setterArgumentType = fieldTypes[i + fieldRecords.length];
+          var setter = field.setter;
+          var setterContext = field.setterContext;
+          fields[fieldName] = {
+            read: ptr =>
+                getterReturnType['fromWireType'](getter(getterContext, ptr)),
+            write: (ptr, o) => {
+              var destructors = [];
+              setter(
+                  setterContext, ptr,
+                  setterArgumentType['toWireType'](destructors, o));
+              runDestructors(destructors)
+            },
+            optional
+          }
+        });
+        return [{
+          name: reg.name,
+          fromWireType: ptr => {
+            var rv = {};
+            for (var i in fields) {
+              rv[i] = fields[i].read(ptr)
+            }
+            rawDestructor(ptr);
+            return rv
+          },
+          toWireType: (destructors, o) => {
+            for (var fieldName in fields) {
+              if (!(fieldName in o) && !fields[fieldName].optional) {
+                throw new TypeError(`Missing field: "${fieldName}"`)
+              }
+            }
+            var ptr = rawConstructor();
+            for (fieldName in fields) {
+              fields[fieldName].write(ptr, o[fieldName])
+            }
+            if (destructors !== null) {
+              destructors.push(rawDestructor, ptr)
+            }
+            return ptr
+          },
+          argPackAdvance: GenericWireTypeSize,
+          readValueFromPointer: readPointer,
+          destructorFunction: rawDestructor
+        }]
+      })
+    };
+    var embindRepr = v => {
+      if (v === null) {
+        return 'null'
+      }
+      var t = typeof v;
+      if (t === 'object' || t === 'array' || t === 'function') {
+        return v.toString()
+      } else {
+        return '' + v
+      }
+    };
+    var embind_init_charCodes = () => {
+      var codes = new Array(256);
+      for (var i = 0; i < 256; ++i) {
+        codes[i] = String.fromCharCode(i)
+      }
+      embind_charCodes = codes
+    };
+    var embind_charCodes;
+    var readLatin1String = ptr => {
+      var ret = '';
+      var c = ptr;
+      while (HEAPU8[c >>> 0]) {
+        ret += embind_charCodes[HEAPU8[c++ >>> 0]]
+      }
+      return ret
+    };
+    var BindingError = Module['BindingError'] =
+        class BindingError extends Error {
+      constructor(message) {
+        super(message);
+        this.name = 'BindingError'
+      }
+    };
+    var throwBindingError = message => {
+      throw new BindingError(message)
+    };
+    function sharedRegisterType(rawType, registeredInstance, options = {}) {
+      var name = registeredInstance.name;
+      if (!rawType) {
+        throwBindingError(
+            `type "${name}" must have a positive integer typeid pointer`)
+      }
+      if (registeredTypes.hasOwnProperty(rawType)) {
+        if (options.ignoreDuplicateRegistrations) {
+          return
+        } else {
+          throwBindingError(`Cannot register type '${name}' twice`)
+        }
+      }
+      registeredTypes[rawType] = registeredInstance;
+      delete typeDependencies[rawType];
+      if (awaitingDependencies.hasOwnProperty(rawType)) {
+        var callbacks = awaitingDependencies[rawType];
+        delete awaitingDependencies[rawType];
+        callbacks.forEach(cb => cb())
+      }
+    }
+    function registerType(rawType, registeredInstance, options = {}) {
+      return sharedRegisterType(rawType, registeredInstance, options)
+    }
+    var integerReadValueFromPointer = (name, width, signed) => {
+      switch (width) {
+        case 1:
+          return signed ? pointer => HEAP8[pointer >>> 0] :
+                          pointer => HEAPU8[pointer >>> 0];
+        case 2:
+          return signed ? pointer => HEAP16[pointer >>> 1 >>> 0] :
+                          pointer => HEAPU16[pointer >>> 1 >>> 0];
+        case 4:
+          return signed ? pointer => HEAP32[pointer >>> 2 >>> 0] :
+                          pointer => HEAPU32[pointer >>> 2 >>> 0];
+        case 8:
+          return signed ? pointer => HEAP64[pointer >>> 3] :
+                          pointer => HEAPU64[pointer >>> 3];
+        default:
+          throw new TypeError(`invalid integer width (${width}): ${name}`)
+      }
+    };
+    function __embind_register_bigint(
+        primitiveType, name, size, minRange, maxRange) {
+      primitiveType >>>= 0;
+      name >>>= 0;
+      size >>>= 0;
+      name = readLatin1String(name);
+      var isUnsignedType = name.indexOf('u') != -1;
+      if (isUnsignedType) {
+        maxRange = (1n << 64n) - 1n
+      }
+      registerType(primitiveType, {
+        name,
+        fromWireType: value => value,
+        toWireType: function(destructors, value) {
+          if (typeof value != 'bigint' && typeof value != 'number') {
+            throw new TypeError(
+                `Cannot convert "${embindRepr(value)}" to ${this.name}`)
+          }
+          if (typeof value == 'number') {
+            value = BigInt(value)
+          }
+          return value
+        },
+        argPackAdvance: GenericWireTypeSize,
+        readValueFromPointer:
+            integerReadValueFromPointer(name, size, !isUnsignedType),
+        destructorFunction: null
+      })
+    }
+    var GenericWireTypeSize = 8;
+    function __embind_register_bool(rawType, name, trueValue, falseValue) {
+      rawType >>>= 0;
+      name >>>= 0;
+      name = readLatin1String(name);
+      registerType(rawType, {
+        name,
+        fromWireType: function(wt) {
+          return !!wt
+        },
+        toWireType: function(destructors, o) {
+          return o ? trueValue : falseValue
+        },
+        argPackAdvance: GenericWireTypeSize,
+        readValueFromPointer: function(pointer) {
+          return this['fromWireType'](HEAPU8[pointer >>> 0])
+        },
+        destructorFunction: null
+      })
+    }
+    var shallowCopyInternalPointer = o => ({
+      count: o.count,
+      deleteScheduled: o.deleteScheduled,
+      preservePointerOnDelete: o.preservePointerOnDelete,
+      ptr: o.ptr,
+      ptrType: o.ptrType,
+      smartPtr: o.smartPtr,
+      smartPtrType: o.smartPtrType
+    });
+    var throwInstanceAlreadyDeleted = obj => {
+      function getInstanceTypeName(handle) {
+        return handle.$$.ptrType.registeredClass.name
+      }
+      throwBindingError(getInstanceTypeName(obj) + ' instance already deleted')
+    };
+    var finalizationRegistry = false;
+    var detachFinalizer = handle => {};
+    var runDestructor = $$ => {
+      if ($$.smartPtr) {
+        $$.smartPtrType.rawDestructor($$.smartPtr)
+      } else {
+        $$.ptrType.registeredClass.rawDestructor($$.ptr)
+      }
+    };
+    var releaseClassHandle = $$ => {
+      $$.count.value -= 1;
+      var toDelete = 0 === $$.count.value;
+      if (toDelete) {
+        runDestructor($$)
+      }
+    };
+    var attachFinalizer = handle => {
+      if ('undefined' === typeof FinalizationRegistry) {
+        attachFinalizer = handle => handle;
+        return handle
+      }
+      finalizationRegistry =
+          new FinalizationRegistry(info => {releaseClassHandle(info.$$)});
+      attachFinalizer = handle => {
+        var $$ = handle.$$;
+        var hasSmartPtr = !!$$.smartPtr;
+        if (hasSmartPtr) {
+          var info = {$$};
+          finalizationRegistry.register(handle, info, handle)
+        }
+        return handle
+      };
+      detachFinalizer = handle => finalizationRegistry.unregister(handle);
+      return attachFinalizer(handle)
+    };
+    var deletionQueue = [];
+    var flushPendingDeletes = () => {
+      while (deletionQueue.length) {
+        var obj = deletionQueue.pop();
+        obj.$$.deleteScheduled = false;
+        obj['delete']()
+      }
+    };
+    var delayFunction;
+    var init_ClassHandle = () => {
+      let proto = ClassHandle.prototype;
+      Object.assign(proto, {
+        isAliasOf(other) {
+          if (!(this instanceof ClassHandle)) {
+            return false
+          }
+          if (!(other instanceof ClassHandle)) {
+            return false
+          }
+          var leftClass = this.$$.ptrType.registeredClass;
+          var left = this.$$.ptr;
+          other.$$ = other.$$;
+          var rightClass = other.$$.ptrType.registeredClass;
+          var right = other.$$.ptr;
+          while (leftClass.baseClass) {
+            left = leftClass.upcast(left);
+            leftClass = leftClass.baseClass
+          }
+          while (rightClass.baseClass) {
+            right = rightClass.upcast(right);
+            rightClass = rightClass.baseClass
+          }
+          return leftClass === rightClass && left === right
+        },
+        clone() {
+          if (!this.$$.ptr) {
+            throwInstanceAlreadyDeleted(this)
+          }
+          if (this.$$.preservePointerOnDelete) {
+            this.$$.count.value += 1;
+            return this
+          } else {
+            var clone = attachFinalizer(Object.create(
+                Object.getPrototypeOf(this),
+                {$$: {value: shallowCopyInternalPointer(this.$$)}}));
+            clone.$$.count.value += 1;
+            clone.$$.deleteScheduled = false;
+            return clone
+          }
+        },
+        delete () {
+          if (!this.$$.ptr) {
+            throwInstanceAlreadyDeleted(this)
+          }
+          if (this.$$.deleteScheduled && !this.$$.preservePointerOnDelete) {
+            throwBindingError('Object already scheduled for deletion')
+          }
+          detachFinalizer(this);
+          releaseClassHandle(this.$$);
+          if (!this.$$.preservePointerOnDelete) {
+            this.$$.smartPtr = undefined;
+            this.$$.ptr = undefined
+          }
+        },
+        isDeleted() {
+          return !this.$$.ptr
+        },
+        deleteLater() {
+          if (!this.$$.ptr) {
+            throwInstanceAlreadyDeleted(this)
+          }
+          if (this.$$.deleteScheduled && !this.$$.preservePointerOnDelete) {
+            throwBindingError('Object already scheduled for deletion')
+          }
+          deletionQueue.push(this);
+          if (deletionQueue.length === 1 && delayFunction) {
+            delayFunction(flushPendingDeletes)
+          }
+          this.$$.deleteScheduled = true;
+          return this
+        }
+      });
+      const symbolDispose = Symbol.dispose;
+      if (symbolDispose) {
+        proto[symbolDispose] = proto['delete']
+      }
+    };
+    function ClassHandle() {}
+    var createNamedFunction = (name, func) =>
+        Object.defineProperty(func, 'name', {value: name});
+    var registeredPointers = {};
+    var ensureOverloadTable = (proto, methodName, humanName) => {
+      if (undefined === proto[methodName].overloadTable) {
+        var prevFunc = proto[methodName];
+        proto[methodName] = function(...args) {
+          if (!proto[methodName].overloadTable.hasOwnProperty(args.length)) {
+            throwBindingError(`Function '${
+                humanName}' called with an invalid number of arguments (${
+                args.length}) - expects one of (${
+                proto[methodName].overloadTable})!`)
+          }
+          return proto[methodName].overloadTable[args.length].apply(this, args)
+        };
+        proto[methodName].overloadTable = [];
+        proto[methodName].overloadTable[prevFunc.argCount] = prevFunc
+      }
+    };
+    var exposePublicSymbol = (name, value, numArguments) => {
+      if (Module.hasOwnProperty(name)) {
+        if (undefined === numArguments ||
+            undefined !== Module[name].overloadTable &&
+                undefined !== Module[name].overloadTable[numArguments]) {
+          throwBindingError(`Cannot register public name '${name}' twice`)
+        }
+        ensureOverloadTable(Module, name, name);
+        if (Module[name].overloadTable.hasOwnProperty(numArguments)) {
+          throwBindingError(
+              `Cannot register multiple overloads of a function with the same number of arguments (${
+                  numArguments})!`)
+        }
+        Module[name].overloadTable[numArguments] = value
+      } else {
+        Module[name] = value;
+        Module[name].argCount = numArguments
+      }
+    };
+    var char_0 = 48;
+    var char_9 = 57;
+    var makeLegalFunctionName = name => {
+      name = name.replace(/[^a-zA-Z0-9_]/g, '$');
+      var f = name.charCodeAt(0);
+      if (f >= char_0 && f <= char_9) {
+        return `_${name}`
+      }
+      return name
+    };
+    function RegisteredClass(
+        name, constructor, instancePrototype, rawDestructor, baseClass,
+        getActualType, upcast, downcast) {
+      this.name = name;
+      this.constructor = constructor;
+      this.instancePrototype = instancePrototype;
+      this.rawDestructor = rawDestructor;
+      this.baseClass = baseClass;
+      this.getActualType = getActualType;
+      this.upcast = upcast;
+      this.downcast = downcast;
+      this.pureVirtualFunctions = []
+    }
+    var upcastPointer = (ptr, ptrClass, desiredClass) => {
+      while (ptrClass !== desiredClass) {
+        if (!ptrClass.upcast) {
+          throwBindingError(`Expected null or instance of ${
+              desiredClass.name}, got an instance of ${ptrClass.name}`)
+        }
+        ptr = ptrClass.upcast(ptr);
+        ptrClass = ptrClass.baseClass
+      }
+      return ptr
+    };
+    function constNoSmartPtrRawPointerToWireType(destructors, handle) {
+      if (handle === null) {
+        if (this.isReference) {
+          throwBindingError(`null is not a valid ${this.name}`)
+        }
+        return 0
+      }
+      if (!handle.$$) {
+        throwBindingError(
+            `Cannot pass "${embindRepr(handle)}" as a ${this.name}`)
+      }
+      if (!handle.$$.ptr) {
+        throwBindingError(
+            `Cannot pass deleted object as a pointer of type ${this.name}`)
+      }
+      var handleClass = handle.$$.ptrType.registeredClass;
+      var ptr = upcastPointer(handle.$$.ptr, handleClass, this.registeredClass);
+      return ptr
+    }
+    function genericPointerToWireType(destructors, handle) {
+      var ptr;
+      if (handle === null) {
+        if (this.isReference) {
+          throwBindingError(`null is not a valid ${this.name}`)
+        }
+        if (this.isSmartPointer) {
+          ptr = this.rawConstructor();
+          if (destructors !== null) {
+            destructors.push(this.rawDestructor, ptr)
+          }
+          return ptr
+        } else {
+          return 0
+        }
+      }
+      if (!handle || !handle.$$) {
+        throwBindingError(
+            `Cannot pass "${embindRepr(handle)}" as a ${this.name}`)
+      }
+      if (!handle.$$.ptr) {
+        throwBindingError(
+            `Cannot pass deleted object as a pointer of type ${this.name}`)
+      }
+      if (!this.isConst && handle.$$.ptrType.isConst) {
+        throwBindingError(`Cannot convert argument of type ${
+            handle.$$.smartPtrType ?
+                handle.$$.smartPtrType.name :
+                handle.$$.ptrType.name} to parameter type ${this.name}`)
+      }
+      var handleClass = handle.$$.ptrType.registeredClass;
+      ptr = upcastPointer(handle.$$.ptr, handleClass, this.registeredClass);
+      if (this.isSmartPointer) {
+        if (undefined === handle.$$.smartPtr) {
+          throwBindingError('Passing raw pointer to smart pointer is illegal')
+        }
+        switch (this.sharingPolicy) {
+          case 0:
+            if (handle.$$.smartPtrType === this) {
+              ptr = handle.$$.smartPtr
+            } else {
+              throwBindingError(`Cannot convert argument of type ${
+                  handle.$$.smartPtrType ?
+                      handle.$$.smartPtrType.name :
+                      handle.$$.ptrType.name} to parameter type ${this.name}`)
+            }
+            break;
+          case 1:
+            ptr = handle.$$.smartPtr;
+            break;
+          case 2:
+            if (handle.$$.smartPtrType === this) {
+              ptr = handle.$$.smartPtr
+            } else {
+              var clonedHandle = handle['clone']();
+              ptr = this.rawShare(
+                  ptr, Emval.toHandle(() => clonedHandle['delete']()));
+              if (destructors !== null) {
+                destructors.push(this.rawDestructor, ptr)
+              }
+            }
+            break;
+          default:
+            throwBindingError('Unsupporting sharing policy')
+        }
+      }
+      return ptr
+    }
+    function nonConstNoSmartPtrRawPointerToWireType(destructors, handle) {
+      if (handle === null) {
+        if (this.isReference) {
+          throwBindingError(`null is not a valid ${this.name}`)
+        }
+        return 0
+      }
+      if (!handle.$$) {
+        throwBindingError(
+            `Cannot pass "${embindRepr(handle)}" as a ${this.name}`)
+      }
+      if (!handle.$$.ptr) {
+        throwBindingError(
+            `Cannot pass deleted object as a pointer of type ${this.name}`)
+      }
+      if (handle.$$.ptrType.isConst) {
+        throwBindingError(`Cannot convert argument of type ${
+            handle.$$.ptrType.name} to parameter type ${this.name}`)
+      }
+      var handleClass = handle.$$.ptrType.registeredClass;
+      var ptr = upcastPointer(handle.$$.ptr, handleClass, this.registeredClass);
+      return ptr
+    }
+    var downcastPointer = (ptr, ptrClass, desiredClass) => {
+      if (ptrClass === desiredClass) {
+        return ptr
+      }
+      if (undefined === desiredClass.baseClass) {
+        return null
+      }
+      var rv = downcastPointer(ptr, ptrClass, desiredClass.baseClass);
+      if (rv === null) {
+        return null
+      }
+      return desiredClass.downcast(rv)
+    };
+    var registeredInstances = {};
+    var getBasestPointer = (class_, ptr) => {
+      if (ptr === undefined) {
+        throwBindingError('ptr should not be undefined')
+      }
+      while (class_.baseClass) {
+        ptr = class_.upcast(ptr);
+        class_ = class_.baseClass
+      }
+      return ptr
+    };
+    var getInheritedInstance = (class_, ptr) => {
+      ptr = getBasestPointer(class_, ptr);
+      return registeredInstances[ptr]
+    };
+    var makeClassHandle = (prototype, record) => {
+      if (!record.ptrType || !record.ptr) {
+        throwInternalError('makeClassHandle requires ptr and ptrType')
+      }
+      var hasSmartPtrType = !!record.smartPtrType;
+      var hasSmartPtr = !!record.smartPtr;
+      if (hasSmartPtrType !== hasSmartPtr) {
+        throwInternalError('Both smartPtrType and smartPtr must be specified')
+      }
+      record.count = {value: 1};
+      return attachFinalizer(
+          Object.create(prototype, {$$: {value: record, writable: true}}))
+    };
+    function RegisteredPointer_fromWireType(ptr) {
+      var rawPointer = this.getPointee(ptr);
+      if (!rawPointer) {
+        this.destructor(ptr);
+        return null
+      }
+      var registeredInstance =
+          getInheritedInstance(this.registeredClass, rawPointer);
+      if (undefined !== registeredInstance) {
+        if (0 === registeredInstance.$$.count.value) {
+          registeredInstance.$$.ptr = rawPointer;
+          registeredInstance.$$.smartPtr = ptr;
+          return registeredInstance['clone']()
+        } else {
+          var rv = registeredInstance['clone']();
+          this.destructor(ptr);
+          return rv
+        }
+      }
+      function makeDefaultHandle() {
+        if (this.isSmartPointer) {
+          return makeClassHandle(this.registeredClass.instancePrototype, {
+            ptrType: this.pointeeType,
+            ptr: rawPointer,
+            smartPtrType: this,
+            smartPtr: ptr
+          })
+        } else {
+          return makeClassHandle(
+              this.registeredClass.instancePrototype, {ptrType: this, ptr})
+        }
+      }
+      var actualType = this.registeredClass.getActualType(rawPointer);
+      var registeredPointerRecord = registeredPointers[actualType];
+      if (!registeredPointerRecord) {
+        return makeDefaultHandle.call(this)
+      }
+      var toType;
+      if (this.isConst) {
+        toType = registeredPointerRecord.constPointerType
+      } else {
+        toType = registeredPointerRecord.pointerType
+      }
+      var dp = downcastPointer(
+          rawPointer, this.registeredClass, toType.registeredClass);
+      if (dp === null) {
+        return makeDefaultHandle.call(this)
+      }
+      if (this.isSmartPointer) {
+        return makeClassHandle(
+            toType.registeredClass.instancePrototype,
+            {ptrType: toType, ptr: dp, smartPtrType: this, smartPtr: ptr})
+      } else {
+        return makeClassHandle(
+            toType.registeredClass.instancePrototype,
+            {ptrType: toType, ptr: dp})
+      }
+    }
+    var init_RegisteredPointer = () => {
+      Object.assign(RegisteredPointer.prototype, {
+        getPointee(ptr) {
+          if (this.rawGetPointee) {
+            ptr = this.rawGetPointee(ptr)
+          }
+          return ptr
+        },
+        destructor(ptr) {
+          this.rawDestructor?.(ptr)
+        },
+        argPackAdvance: GenericWireTypeSize,
+        readValueFromPointer: readPointer,
+        fromWireType: RegisteredPointer_fromWireType
+      })
+    };
+    function RegisteredPointer(
+        name, registeredClass, isReference, isConst, isSmartPointer,
+        pointeeType, sharingPolicy, rawGetPointee, rawConstructor, rawShare,
+        rawDestructor) {
+      this.name = name;
+      this.registeredClass = registeredClass;
+      this.isReference = isReference;
+      this.isConst = isConst;
+      this.isSmartPointer = isSmartPointer;
+      this.pointeeType = pointeeType;
+      this.sharingPolicy = sharingPolicy;
+      this.rawGetPointee = rawGetPointee;
+      this.rawConstructor = rawConstructor;
+      this.rawShare = rawShare;
+      this.rawDestructor = rawDestructor;
+      if (!isSmartPointer && registeredClass.baseClass === undefined) {
+        if (isConst) {
+          this['toWireType'] = constNoSmartPtrRawPointerToWireType;
+          this.destructorFunction = null
+        } else {
+          this['toWireType'] = nonConstNoSmartPtrRawPointerToWireType;
+          this.destructorFunction = null
+        }
+      } else {
+        this['toWireType'] = genericPointerToWireType
+      }
+    }
+    var replacePublicSymbol = (name, value, numArguments) => {
+      if (!Module.hasOwnProperty(name)) {
+        throwInternalError('Replacing nonexistent public symbol')
+      }
+      if (undefined !== Module[name].overloadTable &&
+          undefined !== numArguments) {
+        Module[name].overloadTable[numArguments] = value
+      } else {
+        Module[name] = value;
+        Module[name].argCount = numArguments
+      }
+    };
+    var wasmTable;
+    var getWasmTableEntry = funcPtr => wasmTable.get(funcPtr);
+    var dynCall = (sig, ptr, args = [], promising = false) => {
+      var func = getWasmTableEntry(ptr);
+      var rtn = func(...args);
+      return sig[0] == 'p' ? rtn >>> 0 : rtn
+    };
+    var getDynCaller = (sig, ptr, promising = false) => (...args) =>
+        dynCall(sig, ptr, args, promising);
+    var embind__requireFunction = (signature, rawFunction, isAsync = false) => {
+      signature = readLatin1String(signature);
+      function makeDynCaller() {
+        if (signature.includes('p')) {
+          return getDynCaller(signature, rawFunction, isAsync)
+        }
+        var rtn = getWasmTableEntry(rawFunction);
+        return rtn
+      }
+      var fp = makeDynCaller();
+      if (typeof fp != 'function') {
+        throwBindingError(`unknown function pointer with signature ${
+            signature}: ${rawFunction}`)
+      }
+      return fp
+    };
+    class UnboundTypeError extends Error {}
+    var getTypeName = type => {
+      var ptr = ___getTypeName(type);
+      var rv = readLatin1String(ptr);
+      _free(ptr);
+      return rv
+    };
+    var throwUnboundTypeError = (message, types) => {
+      var unboundTypes = [];
+      var seen = {};
+      function visit(type) {
+        if (seen[type]) {
+          return
+        }
+        if (registeredTypes[type]) {
+          return
+        }
+        if (typeDependencies[type]) {
+          typeDependencies[type].forEach(visit);
+          return
+        }
+        unboundTypes.push(type);
+        seen[type] = true
+      }
+      types.forEach(visit);
+      throw new UnboundTypeError(
+          `${message}: ` + unboundTypes.map(getTypeName).join([', ']))
+    };
+    function __embind_register_class(
+        rawType, rawPointerType, rawConstPointerType, baseClassRawType,
+        getActualTypeSignature, getActualType, upcastSignature, upcast,
+        downcastSignature, downcast, name, destructorSignature, rawDestructor) {
+      rawType >>>= 0;
+      rawPointerType >>>= 0;
+      rawConstPointerType >>>= 0;
+      baseClassRawType >>>= 0;
+      getActualTypeSignature >>>= 0;
+      getActualType >>>= 0;
+      upcastSignature >>>= 0;
+      upcast >>>= 0;
+      downcastSignature >>>= 0;
+      downcast >>>= 0;
+      name >>>= 0;
+      destructorSignature >>>= 0;
+      rawDestructor >>>= 0;
+      name = readLatin1String(name);
+      getActualType =
+          embind__requireFunction(getActualTypeSignature, getActualType);
+      upcast &&= embind__requireFunction(upcastSignature, upcast);
+      downcast &&= embind__requireFunction(downcastSignature, downcast);
+      rawDestructor =
+          embind__requireFunction(destructorSignature, rawDestructor);
+      var legalFunctionName = makeLegalFunctionName(name);
+      exposePublicSymbol(legalFunctionName, function() {
+        throwUnboundTypeError(
+            `Cannot construct ${name} due to unbound types`, [baseClassRawType])
+      });
+      whenDependentTypesAreResolved(
+          [rawType, rawPointerType, rawConstPointerType],
+          baseClassRawType ? [baseClassRawType] : [], base => {
+            base = base[0];
+            var baseClass;
+            var basePrototype;
+            if (baseClassRawType) {
+              baseClass = base.registeredClass;
+              basePrototype = baseClass.instancePrototype
+            } else {
+              basePrototype = ClassHandle.prototype
+            }
+            var constructor = createNamedFunction(name, function(...args) {
+              if (Object.getPrototypeOf(this) !== instancePrototype) {
+                throw new BindingError(`Use 'new' to construct ${name}`)
+              }
+              if (undefined === registeredClass.constructor_body) {
+                throw new BindingError(`${name} has no accessible constructor`)
+              }
+              var body = registeredClass.constructor_body[args.length];
+              if (undefined === body) {
+                throw new BindingError(`Tried to invoke ctor of ${
+                    name} with invalid number of parameters (${
+                    args.length}) - expected (${
+                    Object.keys(registeredClass.constructor_body)
+                        .toString()}) parameters instead!`)
+              }
+              return body.apply(this, args)
+            });
+            var instancePrototype = Object.create(
+                basePrototype, {constructor: {value: constructor}});
+            constructor.prototype = instancePrototype;
+            var registeredClass = new RegisteredClass(
+                name, constructor, instancePrototype, rawDestructor, baseClass,
+                getActualType, upcast, downcast);
+            if (registeredClass.baseClass) {
+              registeredClass.baseClass.__derivedClasses ??= [];
+              registeredClass.baseClass.__derivedClasses.push(registeredClass)
+            }
+            var referenceConverter = new RegisteredPointer(
+                name, registeredClass, true, false, false);
+            var pointerConverter = new RegisteredPointer(
+                name + '*', registeredClass, false, false, false);
+            var constPointerConverter = new RegisteredPointer(
+                name + ' const*', registeredClass, false, true, false);
+            registeredPointers[rawType] = {
+              pointerType: pointerConverter,
+              constPointerType: constPointerConverter
+            };
+            replacePublicSymbol(legalFunctionName, constructor);
+            return [referenceConverter, pointerConverter, constPointerConverter]
+          })
+    }
+    var heap32VectorToArray = (count, firstElement) => {
+      var array = [];
+      for (var i = 0; i < count; i++) {
+        array.push(HEAPU32[firstElement + i * 4 >>> 2 >>> 0])
+      }
+      return array
+    };
+    function usesDestructorStack(argTypes) {
+      for (var i = 1; i < argTypes.length; ++i) {
+        if (argTypes[i] !== null &&
+            argTypes[i].destructorFunction === undefined) {
+          return true
+        }
+      }
+      return false
+    }
+    function createJsInvoker(argTypes, isClassMethodFunc, returns, isAsync) {
+      var needsDestructorStack = usesDestructorStack(argTypes);
+      var argCount = argTypes.length - 2;
+      var argsList = [];
+      var argsListWired = ['fn'];
+      if (isClassMethodFunc) {
+        argsListWired.push('thisWired')
+      }
+      for (var i = 0; i < argCount; ++i) {
+        argsList.push(`arg${i}`);
+        argsListWired.push(`arg${i}Wired`)
+      }
+      argsList = argsList.join(',');
+      argsListWired = argsListWired.join(',');
+      var invokerFnBody = `return function (${argsList}) {\n`;
+      if (needsDestructorStack) {
+        invokerFnBody += 'var destructors = [];\n'
+      }
+      var dtorStack = needsDestructorStack ? 'destructors' : 'null';
+      var args1 = [
+        'humanName', 'throwBindingError', 'invoker', 'fn', 'runDestructors',
+        'retType', 'classParam'
+      ];
+      if (isClassMethodFunc) {
+        invokerFnBody +=
+            `var thisWired = classParam['toWireType'](${dtorStack}, this);\n`
+      }
+      for (var i = 0; i < argCount; ++i) {
+        invokerFnBody += `var arg${i}Wired = argType${i}['toWireType'](${
+            dtorStack}, arg${i});\n`;
+        args1.push(`argType${i}`)
+      }
+      invokerFnBody += (returns || isAsync ? 'var rv = ' : '') +
+          `invoker(${argsListWired});\n`;
+      if (needsDestructorStack) {
+        invokerFnBody += 'runDestructors(destructors);\n'
+      } else {
+        for (var i = isClassMethodFunc ? 1 : 2; i < argTypes.length; ++i) {
+          var paramName = i === 1 ? 'thisWired' : 'arg' + (i - 2) + 'Wired';
+          if (argTypes[i].destructorFunction !== null) {
+            invokerFnBody += `${paramName}_dtor(${paramName});\n`;
+            args1.push(`${paramName}_dtor`)
+          }
+        }
+      }
+      if (returns) {
+        invokerFnBody += 'var ret = retType[\'fromWireType\'](rv);\n' +
+            'return ret;\n'
+      } else {
+      }
+      invokerFnBody += '}\n';
+      return [args1, invokerFnBody]
+    }
+    function craftInvokerFunction(
+        humanName, argTypes, classType, cppInvokerFunc, cppTargetFunc,
+        isAsync) {
+      var argCount = argTypes.length;
+      if (argCount < 2) {
+        throwBindingError(
+            'argTypes array size mismatch! Must at least get return value and \'this\' types!')
+      }
+      var isClassMethodFunc = argTypes[1] !== null && classType !== null;
+      var needsDestructorStack = usesDestructorStack(argTypes);
+      var returns = argTypes[0].name !== 'void';
+      var closureArgs = [
+        humanName, throwBindingError, cppInvokerFunc, cppTargetFunc,
+        runDestructors, argTypes[0], argTypes[1]
+      ];
+      for (var i = 0; i < argCount - 2; ++i) {
+        closureArgs.push(argTypes[i + 2])
+      }
+      if (!needsDestructorStack) {
+        for (var i = isClassMethodFunc ? 1 : 2; i < argTypes.length; ++i) {
+          if (argTypes[i].destructorFunction !== null) {
+            closureArgs.push(argTypes[i].destructorFunction)
+          }
+        }
+      }
+      let [args, invokerFnBody] =
+          createJsInvoker(argTypes, isClassMethodFunc, returns, isAsync);
+      var invokerFn = new Function(...args, invokerFnBody)(...closureArgs);
+      return createNamedFunction(humanName, invokerFn)
+    }
+    var __embind_register_class_constructor = function(
+        rawClassType, argCount, rawArgTypesAddr, invokerSignature, invoker,
+        rawConstructor) {
+      rawClassType >>>= 0;
+      rawArgTypesAddr >>>= 0;
+      invokerSignature >>>= 0;
+      invoker >>>= 0;
+      rawConstructor >>>= 0;
+      var rawArgTypes = heap32VectorToArray(argCount, rawArgTypesAddr);
+      invoker = embind__requireFunction(invokerSignature, invoker);
+      whenDependentTypesAreResolved([], [rawClassType], classType => {
+        classType = classType[0];
+        var humanName = `constructor ${classType.name}`;
+        if (undefined === classType.registeredClass.constructor_body) {
+          classType.registeredClass.constructor_body = []
+        }
+        if (undefined !==
+            classType.registeredClass.constructor_body[argCount - 1]) {
+          throw new BindingError(
+              `Cannot register multiple constructors with identical number of parameters (${
+                  argCount - 1}) for class '${
+                  classType
+                      .name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`)
+        }
+        classType.registeredClass.constructor_body[argCount - 1] = () => {
+          throwUnboundTypeError(
+              `Cannot construct ${classType.name} due to unbound types`,
+              rawArgTypes)
+        };
+        whenDependentTypesAreResolved([], rawArgTypes, argTypes => {
+          argTypes.splice(1, 0, null);
+          classType.registeredClass.constructor_body[argCount - 1] =
+              craftInvokerFunction(
+                  humanName, argTypes, null, invoker, rawConstructor);
+          return []
+        });
+        return []
+      })
+    };
+    var getFunctionName = signature => {
+      signature = signature.trim();
+      const argsIndex = signature.indexOf('(');
+      if (argsIndex === -1) return signature;
+      return signature.slice(0, argsIndex)
+    };
+    var __embind_register_class_function = function(
+        rawClassType, methodName, argCount, rawArgTypesAddr, invokerSignature,
+        rawInvoker, context, isPureVirtual, isAsync, isNonnullReturn) {
+      rawClassType >>>= 0;
+      methodName >>>= 0;
+      rawArgTypesAddr >>>= 0;
+      invokerSignature >>>= 0;
+      rawInvoker >>>= 0;
+      context >>>= 0;
+      var rawArgTypes = heap32VectorToArray(argCount, rawArgTypesAddr);
+      methodName = readLatin1String(methodName);
+      methodName = getFunctionName(methodName);
+      rawInvoker =
+          embind__requireFunction(invokerSignature, rawInvoker, isAsync);
+      whenDependentTypesAreResolved([], [rawClassType], classType => {
+        classType = classType[0];
+        var humanName = `${classType.name}.${methodName}`;
+        if (methodName.startsWith('@@')) {
+          methodName = Symbol[methodName.substring(2)]
+        }
+        if (isPureVirtual) {
+          classType.registeredClass.pureVirtualFunctions.push(methodName)
+        }
+        function unboundTypesHandler() {
+          throwUnboundTypeError(
+              `Cannot call ${humanName} due to unbound types`, rawArgTypes)
+        }
+        var proto = classType.registeredClass.instancePrototype;
+        var method = proto[methodName];
+        if (undefined === method ||
+            undefined === method.overloadTable &&
+                method.className !== classType.name &&
+                method.argCount === argCount - 2) {
+          unboundTypesHandler.argCount = argCount - 2;
+          unboundTypesHandler.className = classType.name;
+          proto[methodName] = unboundTypesHandler
+        } else {
+          ensureOverloadTable(proto, methodName, humanName);
+          proto[methodName].overloadTable[argCount - 2] = unboundTypesHandler
+        }
+        whenDependentTypesAreResolved([], rawArgTypes, argTypes => {
+          var memberFunction = craftInvokerFunction(
+              humanName, argTypes, classType, rawInvoker, context, isAsync);
+          if (undefined === proto[methodName].overloadTable) {
+            memberFunction.argCount = argCount - 2;
+            proto[methodName] = memberFunction
+          } else {
+            proto[methodName].overloadTable[argCount - 2] = memberFunction
+          }
+          return []
+        });
+        return []
+      })
+    };
+    var emval_freelist = [];
+    var emval_handles = [];
+    function __emval_decref(handle) {
+      handle >>>= 0;
+      if (handle > 9 && 0 === --emval_handles[handle + 1]) {
+        emval_handles[handle] = undefined;
+        emval_freelist.push(handle)
+      }
+    }
+    var count_emval_handles = () =>
+        emval_handles.length / 2 - 5 - emval_freelist.length;
+    var init_emval = () => {
+      emval_handles.push(0, 1, undefined, 1, null, 1, true, 1, false, 1);
+      Module['count_emval_handles'] = count_emval_handles
+    };
+    var Emval = {
+      toValue: handle => {
+        if (!handle) {
+          throwBindingError(`Cannot use deleted val. handle = ${handle}`)
+        }
+        return emval_handles[handle]
+      },
+      toHandle: value => {
+        switch (value) {
+          case undefined:
+            return 2;
+          case null:
+            return 4;
+          case true:
+            return 6;
+          case false:
+            return 8;
+          default: {
+            const handle = emval_freelist.pop() || emval_handles.length;
+            emval_handles[handle] = value;
+            emval_handles[handle + 1] = 1;
+            return handle
+          }
+        }
+      }
+    };
+    var EmValType = {
+      name: 'emscripten::val',
+      fromWireType: handle => {
+        var rv = Emval.toValue(handle);
+        __emval_decref(handle);
+        return rv
+      },
+      toWireType: (destructors, value) => Emval.toHandle(value),
+      argPackAdvance: GenericWireTypeSize,
+      readValueFromPointer: readPointer,
+      destructorFunction: null
+    };
+    function __embind_register_emval(rawType) {
+      rawType >>>= 0;
+      return registerType(rawType, EmValType)
+    }
+    var enumReadValueFromPointer = (name, width, signed) => {
+      switch (width) {
+        case 1:
+          return signed ? function(pointer) {
+            return this['fromWireType'](HEAP8[pointer >>> 0])
+          } : function(pointer) {
+            return this['fromWireType'](HEAPU8[pointer >>> 0])
+          };
+        case 2:
+          return signed ? function(pointer) {
+            return this['fromWireType'](HEAP16[pointer >>> 1 >>> 0])
+          } : function(pointer) {
+            return this['fromWireType'](HEAPU16[pointer >>> 1 >>> 0])
+          };
+        case 4:
+          return signed ? function(pointer) {
+            return this['fromWireType'](HEAP32[pointer >>> 2 >>> 0])
+          } : function(pointer) {
+            return this['fromWireType'](HEAPU32[pointer >>> 2 >>> 0])
+          };
+        default:
+          throw new TypeError(`invalid integer width (${width}): ${name}`)
+      }
+    };
+    function __embind_register_enum(rawType, name, size, isSigned) {
+      rawType >>>= 0;
+      name >>>= 0;
+      size >>>= 0;
+      name = readLatin1String(name);
+      function ctor() {}
+      ctor.values = {};
+      registerType(rawType, {
+        name,
+        constructor: ctor,
+        fromWireType: function(c) {
+          return this.constructor.values[c]
+        },
+        toWireType: (destructors, c) => c.value,
+        argPackAdvance: GenericWireTypeSize,
+        readValueFromPointer: enumReadValueFromPointer(name, size, isSigned),
+        destructorFunction: null
+      });
+      exposePublicSymbol(name, ctor)
+    }
+    var requireRegisteredType = (rawType, humanName) => {
+      var impl = registeredTypes[rawType];
+      if (undefined === impl) {
+        throwBindingError(
+            `${humanName} has unknown type ${getTypeName(rawType)}`)
+      }
+      return impl
+    };
+    function __embind_register_enum_value(rawEnumType, name, enumValue) {
+      rawEnumType >>>= 0;
+      name >>>= 0;
+      var enumType = requireRegisteredType(rawEnumType, 'enum');
+      name = readLatin1String(name);
+      var Enum = enumType.constructor;
+      var Value = Object.create(enumType.constructor.prototype, {
+        value: {value: enumValue},
+        constructor: {
+          value: createNamedFunction(`${enumType.name}_${name}`, function() {})
+        }
+      });
+      Enum.values[enumValue] = Value;
+      Enum[name] = Value
+    }
+    var floatReadValueFromPointer = (name, width) => {
+      switch (width) {
+        case 4:
+          return function(pointer) {
+            return this['fromWireType'](HEAPF32[pointer >>> 2 >>> 0])
+          };
+        case 8:
+          return function(pointer) {
+            return this['fromWireType'](HEAPF64[pointer >>> 3 >>> 0])
+          };
+        default:
+          throw new TypeError(`invalid float width (${width}): ${name}`)
+      }
+    };
+    var __embind_register_float = function(rawType, name, size) {
+      rawType >>>= 0;
+      name >>>= 0;
+      size >>>= 0;
+      name = readLatin1String(name);
+      registerType(rawType, {
+        name,
+        fromWireType: value => value,
+        toWireType: (destructors, value) => value,
+        argPackAdvance: GenericWireTypeSize,
+        readValueFromPointer: floatReadValueFromPointer(name, size),
+        destructorFunction: null
+      })
+    };
+    function __embind_register_function(
+        name, argCount, rawArgTypesAddr, signature, rawInvoker, fn, isAsync,
+        isNonnullReturn) {
+      name >>>= 0;
+      rawArgTypesAddr >>>= 0;
+      signature >>>= 0;
+      rawInvoker >>>= 0;
+      fn >>>= 0;
+      var argTypes = heap32VectorToArray(argCount, rawArgTypesAddr);
+      name = readLatin1String(name);
+      name = getFunctionName(name);
+      rawInvoker = embind__requireFunction(signature, rawInvoker, isAsync);
+      exposePublicSymbol(name, function() {
+        throwUnboundTypeError(
+            `Cannot call ${name} due to unbound types`, argTypes)
+      }, argCount - 1);
+      whenDependentTypesAreResolved([], argTypes, argTypes => {
+        var invokerArgsArray = [argTypes[0], null].concat(argTypes.slice(1));
+        replacePublicSymbol(
+            name,
+            craftInvokerFunction(
+                name, invokerArgsArray, null, rawInvoker, fn, isAsync),
+            argCount - 1);
+        return []
+      })
+    }
+    function __embind_register_integer(
+        primitiveType, name, size, minRange, maxRange) {
+      primitiveType >>>= 0;
+      name >>>= 0;
+      size >>>= 0;
+      name = readLatin1String(name);
+      if (maxRange === -1) {
+        maxRange = 4294967295
+      }
+      var fromWireType = value => value;
+      if (minRange === 0) {
+        var bitshift = 32 - 8 * size;
+        fromWireType = value => value << bitshift >>> bitshift
+      }
+      var isUnsignedType = name.includes('unsigned');
+      var checkAssertions = (value, toTypeName) => {};
+      var toWireType;
+      if (isUnsignedType) {
+        toWireType = function(destructors, value) {
+          checkAssertions(value, this.name);
+          return value >>> 0
+        }
+      } else {
+        toWireType = function(destructors, value) {
+          checkAssertions(value, this.name);
+          return value
+        }
+      }
+      registerType(primitiveType, {
+        name,
+        fromWireType,
+        toWireType,
+        argPackAdvance: GenericWireTypeSize,
+        readValueFromPointer:
+            integerReadValueFromPointer(name, size, minRange !== 0),
+        destructorFunction: null
+      })
+    }
+    function __embind_register_memory_view(rawType, dataTypeIndex, name) {
+      rawType >>>= 0;
+      name >>>= 0;
+      var typeMapping = [
+        Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array,
+        Float32Array, Float64Array, BigInt64Array, BigUint64Array
+      ];
+      var TA = typeMapping[dataTypeIndex];
+      function decodeMemoryView(handle) {
+        var size = HEAPU32[handle >>> 2 >>> 0];
+        var data = HEAPU32[handle + 4 >>> 2 >>> 0];
+        return new TA(HEAP8.buffer, data, size)
+      }
+      name = readLatin1String(name);
+      registerType(
+          rawType, {
+            name,
+            fromWireType: decodeMemoryView,
+            argPackAdvance: GenericWireTypeSize,
+            readValueFromPointer: decodeMemoryView
+          },
+          {ignoreDuplicateRegistrations: true})
+    }
+    var EmValOptionalType = Object.assign({optional: true}, EmValType);
+    function __embind_register_optional(rawOptionalType, rawType) {
+      rawOptionalType >>>= 0;
+      rawType >>>= 0;
+      registerType(rawOptionalType, EmValOptionalType)
+    }
+    var stringToUTF8Array = (str, heap, outIdx, maxBytesToWrite) => {
+      outIdx >>>= 0;
+      if (!(maxBytesToWrite > 0)) return 0;
+      var startIdx = outIdx;
+      var endIdx = outIdx + maxBytesToWrite - 1;
+      for (var i = 0; i < str.length; ++i) {
+        var u = str.charCodeAt(i);
+        if (u >= 55296 && u <= 57343) {
+          var u1 = str.charCodeAt(++i);
+          u = 65536 + ((u & 1023) << 10) | u1 & 1023
+        }
+        if (u <= 127) {
+          if (outIdx >= endIdx) break;
+          heap[outIdx++ >>> 0] = u
+        } else if (u <= 2047) {
+          if (outIdx + 1 >= endIdx) break;
+          heap[outIdx++ >>> 0] = 192 | u >> 6;
+          heap[outIdx++ >>> 0] = 128 | u & 63
+        } else if (u <= 65535) {
+          if (outIdx + 2 >= endIdx) break;
+          heap[outIdx++ >>> 0] = 224 | u >> 12;
+          heap[outIdx++ >>> 0] = 128 | u >> 6 & 63;
+          heap[outIdx++ >>> 0] = 128 | u & 63
+        } else {
+          if (outIdx + 3 >= endIdx) break;
+          heap[outIdx++ >>> 0] = 240 | u >> 18;
+          heap[outIdx++ >>> 0] = 128 | u >> 12 & 63;
+          heap[outIdx++ >>> 0] = 128 | u >> 6 & 63;
+          heap[outIdx++ >>> 0] = 128 | u & 63
+        }
+      }
+      heap[outIdx >>> 0] = 0;
+      return outIdx - startIdx
+    };
+    var stringToUTF8 = (str, outPtr, maxBytesToWrite) =>
+        stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite);
+    var lengthBytesUTF8 = str => {
+      var len = 0;
+      for (var i = 0; i < str.length; ++i) {
+        var c = str.charCodeAt(i);
+        if (c <= 127) {
+          len++
+        } else if (c <= 2047) {
+          len += 2
+        } else if (c >= 55296 && c <= 57343) {
+          len += 4;
+          ++i
+        } else {
+          len += 3
+        }
+      }
+      return len
+    };
+    var UTF8Decoder =
+        typeof TextDecoder != 'undefined' ? new TextDecoder : undefined;
+    var UTF8ArrayToString = (heapOrArray, idx = 0, maxBytesToRead = NaN) => {
+      idx >>>= 0;
+      var endIdx = idx + maxBytesToRead;
+      var endPtr = idx;
+      while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr;
+      if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {
+        return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr))
+      }
+      var str = '';
+      while (idx < endPtr) {
+        var u0 = heapOrArray[idx++];
+        if (!(u0 & 128)) {
+          str += String.fromCharCode(u0);
+          continue
+        }
+        var u1 = heapOrArray[idx++] & 63;
+        if ((u0 & 224) == 192) {
+          str += String.fromCharCode((u0 & 31) << 6 | u1);
+          continue
+        }
+        var u2 = heapOrArray[idx++] & 63;
+        if ((u0 & 240) == 224) {
+          u0 = (u0 & 15) << 12 | u1 << 6 | u2
+        } else {
+          u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | heapOrArray[idx++] & 63
+        }
+        if (u0 < 65536) {
+          str += String.fromCharCode(u0)
+        } else {
+          var ch = u0 - 65536;
+          str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023)
+        }
+      }
+      return str
+    };
+    var UTF8ToString = (ptr, maxBytesToRead) => {
+      ptr >>>= 0;
+      return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : ''
+    };
+    function __embind_register_std_string(rawType, name) {
+      rawType >>>= 0;
+      name >>>= 0;
+      name = readLatin1String(name);
+      var stdStringIsUTF8 = true;
+      registerType(rawType, {
+        name,
+        fromWireType(value) {
+          var length = HEAPU32[value >>> 2 >>> 0];
+          var payload = value + 4;
+          var str;
+          if (stdStringIsUTF8) {
+            var decodeStartPtr = payload;
+            for (var i = 0; i <= length; ++i) {
+              var currentBytePtr = payload + i;
+              if (i == length || HEAPU8[currentBytePtr >>> 0] == 0) {
+                var maxRead = currentBytePtr - decodeStartPtr;
+                var stringSegment = UTF8ToString(decodeStartPtr, maxRead);
+                if (str === undefined) {
+                  str = stringSegment
+                } else {
+                  str += String.fromCharCode(0);
+                  str += stringSegment
+                }
+                decodeStartPtr = currentBytePtr + 1
+              }
+            }
+          } else {
+            var a = new Array(length);
+            for (var i = 0; i < length; ++i) {
+              a[i] = String.fromCharCode(HEAPU8[payload + i >>> 0])
+            }
+            str = a.join('')
+          }
+          _free(value);
+          return str
+        },
+        toWireType(destructors, value) {
+          if (value instanceof ArrayBuffer) {
+            value = new Uint8Array(value)
+          }
+          var length;
+          var valueIsOfTypeString = typeof value == 'string';
+          if (!(valueIsOfTypeString ||
+                ArrayBuffer.isView(value) && value.BYTES_PER_ELEMENT == 1)) {
+            throwBindingError('Cannot pass non-string to std::string')
+          }
+          if (stdStringIsUTF8 && valueIsOfTypeString) {
+            length = lengthBytesUTF8(value)
+          } else {
+            length = value.length
+          }
+          var base = _malloc(4 + length + 1);
+          var ptr = base + 4;
+          HEAPU32[base >>> 2 >>> 0] = length;
+          if (valueIsOfTypeString) {
+            if (stdStringIsUTF8) {
+              stringToUTF8(value, ptr, length + 1)
+            } else {
+              for (var i = 0; i < length; ++i) {
+                var charCode = value.charCodeAt(i);
+                if (charCode > 255) {
+                  _free(base);
+                  throwBindingError(
+                      'String has UTF-16 code units that do not fit in 8 bits')
+                }
+                HEAPU8[ptr + i >>> 0] = charCode
+              }
+            }
+          } else {
+            HEAPU8.set(value, ptr >>> 0)
+          }
+          if (destructors !== null) {
+            destructors.push(_free, base)
+          }
+          return base
+        },
+        argPackAdvance: GenericWireTypeSize,
+        readValueFromPointer: readPointer,
+        destructorFunction(ptr) {
+          _free(ptr)
+        }
+      })
+    }
+    var UTF16Decoder = typeof TextDecoder != 'undefined' ?
+        new TextDecoder('utf-16le') :
+        undefined;
+    var UTF16ToString = (ptr, maxBytesToRead) => {
+      var endPtr = ptr;
+      var idx = endPtr >> 1;
+      var maxIdx = idx + maxBytesToRead / 2;
+      while (!(idx >= maxIdx) && HEAPU16[idx >>> 0]) ++idx;
+      endPtr = idx << 1;
+      if (endPtr - ptr > 32 && UTF16Decoder)
+        return UTF16Decoder.decode(HEAPU8.subarray(ptr >>> 0, endPtr >>> 0));
+      var str = '';
+      for (var i = 0; !(i >= maxBytesToRead / 2); ++i) {
+        var codeUnit = HEAP16[ptr + i * 2 >>> 1 >>> 0];
+        if (codeUnit == 0) break;
+        str += String.fromCharCode(codeUnit)
+      }
+      return str
+    };
+    var stringToUTF16 = (str, outPtr, maxBytesToWrite) => {
+      maxBytesToWrite ??= 2147483647;
+      if (maxBytesToWrite < 2) return 0;
+      maxBytesToWrite -= 2;
+      var startPtr = outPtr;
+      var numCharsToWrite =
+          maxBytesToWrite < str.length * 2 ? maxBytesToWrite / 2 : str.length;
+      for (var i = 0; i < numCharsToWrite; ++i) {
+        var codeUnit = str.charCodeAt(i);
+        HEAP16[outPtr >>> 1 >>> 0] = codeUnit;
+        outPtr += 2
+      }
+      HEAP16[outPtr >>> 1 >>> 0] = 0;
+      return outPtr - startPtr
+    };
+    var lengthBytesUTF16 = str => str.length * 2;
+    var UTF32ToString = (ptr, maxBytesToRead) => {
+      var i = 0;
+      var str = '';
+      while (!(i >= maxBytesToRead / 4)) {
+        var utf32 = HEAP32[ptr + i * 4 >>> 2 >>> 0];
+        if (utf32 == 0) break;
+        ++i;
+        if (utf32 >= 65536) {
+          var ch = utf32 - 65536;
+          str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023)
+        } else {
+          str += String.fromCharCode(utf32)
+        }
+      }
+      return str
+    };
+    var stringToUTF32 = (str, outPtr, maxBytesToWrite) => {
+      outPtr >>>= 0;
+      maxBytesToWrite ??= 2147483647;
+      if (maxBytesToWrite < 4) return 0;
+      var startPtr = outPtr;
+      var endPtr = startPtr + maxBytesToWrite - 4;
+      for (var i = 0; i < str.length; ++i) {
+        var codeUnit = str.charCodeAt(i);
+        if (codeUnit >= 55296 && codeUnit <= 57343) {
+          var trailSurrogate = str.charCodeAt(++i);
+          codeUnit = 65536 + ((codeUnit & 1023) << 10) | trailSurrogate & 1023
+        }
+        HEAP32[outPtr >>> 2 >>> 0] = codeUnit;
+        outPtr += 4;
+        if (outPtr + 4 > endPtr) break
+      }
+      HEAP32[outPtr >>> 2 >>> 0] = 0;
+      return outPtr - startPtr
+    };
+    var lengthBytesUTF32 = str => {
+      var len = 0;
+      for (var i = 0; i < str.length; ++i) {
+        var codeUnit = str.charCodeAt(i);
+        if (codeUnit >= 55296 && codeUnit <= 57343) ++i;
+        len += 4
+      }
+      return len
+    };
+    var __embind_register_std_wstring = function(rawType, charSize, name) {
+      rawType >>>= 0;
+      charSize >>>= 0;
+      name >>>= 0;
+      name = readLatin1String(name);
+      var decodeString, encodeString, readCharAt, lengthBytesUTF;
+      if (charSize === 2) {
+        decodeString = UTF16ToString;
+        encodeString = stringToUTF16;
+        lengthBytesUTF = lengthBytesUTF16;
+        readCharAt = pointer => HEAPU16[pointer >>> 1 >>> 0]
+      } else if (charSize === 4) {
+        decodeString = UTF32ToString;
+        encodeString = stringToUTF32;
+        lengthBytesUTF = lengthBytesUTF32;
+        readCharAt = pointer => HEAPU32[pointer >>> 2 >>> 0]
+      }
+      registerType(rawType, {
+        name,
+        fromWireType: value => {
+          var length = HEAPU32[value >>> 2 >>> 0];
+          var str;
+          var decodeStartPtr = value + 4;
+          for (var i = 0; i <= length; ++i) {
+            var currentBytePtr = value + 4 + i * charSize;
+            if (i == length || readCharAt(currentBytePtr) == 0) {
+              var maxReadBytes = currentBytePtr - decodeStartPtr;
+              var stringSegment = decodeString(decodeStartPtr, maxReadBytes);
+              if (str === undefined) {
+                str = stringSegment
+              } else {
+                str += String.fromCharCode(0);
+                str += stringSegment
+              }
+              decodeStartPtr = currentBytePtr + charSize
+            }
+          }
+          _free(value);
+          return str
+        },
+        toWireType: (destructors, value) => {
+          if (!(typeof value == 'string')) {
+            throwBindingError(
+                `Cannot pass non-string to C++ string type ${name}`)
+          }
+          var length = lengthBytesUTF(value);
+          var ptr = _malloc(4 + length + charSize);
+          HEAPU32[ptr >>> 2 >>> 0] = length / charSize;
+          encodeString(value, ptr + 4, length + charSize);
+          if (destructors !== null) {
+            destructors.push(_free, ptr)
+          }
+          return ptr
+        },
+        argPackAdvance: GenericWireTypeSize,
+        readValueFromPointer: readPointer,
+        destructorFunction(ptr) {
+          _free(ptr)
+        }
+      })
+    };
+    function __embind_register_value_object(
+        rawType, name, constructorSignature, rawConstructor,
+        destructorSignature, rawDestructor) {
+      rawType >>>= 0;
+      name >>>= 0;
+      constructorSignature >>>= 0;
+      rawConstructor >>>= 0;
+      destructorSignature >>>= 0;
+      rawDestructor >>>= 0;
+      structRegistrations[rawType] = {
+        name: readLatin1String(name),
+        rawConstructor:
+            embind__requireFunction(constructorSignature, rawConstructor),
+        rawDestructor:
+            embind__requireFunction(destructorSignature, rawDestructor),
+        fields: []
+      }
+    }
+    function __embind_register_value_object_field(
+        structType, fieldName, getterReturnType, getterSignature, getter,
+        getterContext, setterArgumentType, setterSignature, setter,
+        setterContext) {
+      structType >>>= 0;
+      fieldName >>>= 0;
+      getterReturnType >>>= 0;
+      getterSignature >>>= 0;
+      getter >>>= 0;
+      getterContext >>>= 0;
+      setterArgumentType >>>= 0;
+      setterSignature >>>= 0;
+      setter >>>= 0;
+      setterContext >>>= 0;
+      structRegistrations[structType].fields.push({
+        fieldName: readLatin1String(fieldName),
+        getterReturnType,
+        getter: embind__requireFunction(getterSignature, getter),
+        getterContext,
+        setterArgumentType,
+        setter: embind__requireFunction(setterSignature, setter),
+        setterContext
+      })
+    }
+    var __embind_register_void = function(rawType, name) {
+      rawType >>>= 0;
+      name >>>= 0;
+      name = readLatin1String(name);
+      registerType(rawType, {
+        isVoid: true,
+        name,
+        argPackAdvance: 0,
+        fromWireType: () => undefined,
+        toWireType: (destructors, o) => undefined
+      })
+    };
+    var emval_returnValue = (returnType, destructorsRef, handle) => {
+      var destructors = [];
+      var result = returnType['toWireType'](destructors, handle);
+      if (destructors.length) {
+        HEAPU32[destructorsRef >>> 2 >>> 0] = Emval.toHandle(destructors)
+      }
+      return result
+    };
+    function __emval_as(handle, returnType, destructorsRef) {
+      handle >>>= 0;
+      returnType >>>= 0;
+      destructorsRef >>>= 0;
+      handle = Emval.toValue(handle);
+      returnType = requireRegisteredType(returnType, 'emval::as');
+      return emval_returnValue(returnType, destructorsRef, handle)
+    }
+    var emval_symbols = {};
+    var getStringOrSymbol = address => {
+      var symbol = emval_symbols[address];
+      if (symbol === undefined) {
+        return readLatin1String(address)
+      }
+      return symbol
+    };
+    var emval_methodCallers = [];
+    function __emval_call_method(
+        caller, objHandle, methodName, destructorsRef, args) {
+      caller >>>= 0;
+      objHandle >>>= 0;
+      methodName >>>= 0;
+      destructorsRef >>>= 0;
+      args >>>= 0;
+      caller = emval_methodCallers[caller];
+      objHandle = Emval.toValue(objHandle);
+      methodName = getStringOrSymbol(methodName);
+      return caller(objHandle, objHandle[methodName], destructorsRef, args)
+    }
+    function __emval_equals(first, second) {
+      first >>>= 0;
+      second >>>= 0;
+      first = Emval.toValue(first);
+      second = Emval.toValue(second);
+      return first == second
+    }
+    var emval_addMethodCaller = caller => {
+      var id = emval_methodCallers.length;
+      emval_methodCallers.push(caller);
+      return id
+    };
+    var emval_lookupTypes = (argCount, argTypes) => {
+      var a = new Array(argCount);
+      for (var i = 0; i < argCount; ++i) {
+        a[i] = requireRegisteredType(
+            HEAPU32[argTypes + i * 4 >>> 2 >>> 0], `parameter ${i}`)
+      }
+      return a
+    };
+    function __emval_get_method_caller(argCount, argTypes, kind) {
+      argTypes >>>= 0;
+      var types = emval_lookupTypes(argCount, argTypes);
+      var retType = types.shift();
+      argCount--;
+      var functionBody =
+          `return function (obj, func, destructorsRef, args) {\n`;
+      var offset = 0;
+      var argsList = [];
+      if (kind === 0) {
+        argsList.push('obj')
+      }
+      var params = ['retType'];
+      var args = [retType];
+      for (var i = 0; i < argCount; ++i) {
+        argsList.push(`arg${i}`);
+        params.push(`argType${i}`);
+        args.push(types[i]);
+        functionBody += `  var arg${i} = argType${i}.readValueFromPointer(args${
+            offset ? '+' + offset : ''});\n`;
+        offset += types[i].argPackAdvance
+      }
+      var invoker = kind === 1 ? 'new func' : 'func.call';
+      functionBody += `  var rv = ${invoker}(${argsList.join(', ')});\n`;
+      if (!retType.isVoid) {
+        params.push('emval_returnValue');
+        args.push(emval_returnValue);
+        functionBody +=
+            '  return emval_returnValue(retType, destructorsRef, rv);\n'
+      }
+      functionBody += '};\n';
+      var invokerFunction = new Function(...params, functionBody)(...args);
+      var functionName = `methodCaller<(${
+          types.map(t => t.name).join(', ')}) => ${retType.name}>`;
+      return emval_addMethodCaller(
+          createNamedFunction(functionName, invokerFunction))
+    }
+    function __emval_get_property(handle, key) {
+      handle >>>= 0;
+      key >>>= 0;
+      handle = Emval.toValue(handle);
+      key = Emval.toValue(key);
+      return Emval.toHandle(handle[key])
+    }
+    function __emval_incref(handle) {
+      handle >>>= 0;
+      if (handle > 9) {
+        emval_handles[handle + 1] += 1
+      }
+    }
+    function __emval_new_cstring(v) {
+      v >>>= 0;
+      return Emval.toHandle(getStringOrSymbol(v))
+    }
+    function __emval_new_object() {
+      return Emval.toHandle({})
+    }
+    function __emval_run_destructors(handle) {
+      handle >>>= 0;
+      var destructors = Emval.toValue(handle);
+      runDestructors(destructors);
+      __emval_decref(handle)
+    }
+    function __emval_set_property(handle, key, value) {
+      handle >>>= 0;
+      key >>>= 0;
+      value >>>= 0;
+      handle = Emval.toValue(handle);
+      key = Emval.toValue(key);
+      value = Emval.toValue(value);
+      handle[key] = value
+    }
+    function __emval_take_value(type, arg) {
+      type >>>= 0;
+      arg >>>= 0;
+      type = requireRegisteredType(type, '_emval_take_value');
+      var v = type['readValueFromPointer'](arg);
+      return Emval.toHandle(v)
+    }
+    var getHeapMax = () => 4294901760;
+    var alignMemory = (size, alignment) =>
+        Math.ceil(size / alignment) * alignment;
+    var growMemory = size => {
+      var b = wasmMemory.buffer;
+      var pages = (size - b.byteLength + 65535) / 65536 | 0;
+      try {
+        wasmMemory.grow(pages);
+        updateMemoryViews();
+        return 1
+      } catch (e) {
+      }
+    };
+    function _emscripten_resize_heap(requestedSize) {
+      requestedSize >>>= 0;
+      var oldSize = HEAPU8.length;
+      var maxHeapSize = getHeapMax();
+      if (requestedSize > maxHeapSize) {
+        return false
+      }
+      for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
+        var overGrownHeapSize = oldSize * (1 + .2 / cutDown);
+        overGrownHeapSize =
+            Math.min(overGrownHeapSize, requestedSize + 100663296);
+        var newSize = Math.min(
+            maxHeapSize,
+            alignMemory(Math.max(requestedSize, overGrownHeapSize), 65536));
+        var replacement = growMemory(newSize);
+        if (replacement) {
+          return true
+        }
+      }
+      return false
+    }
+    var uleb128Encode = (n, target) => {
+      if (n < 128) {
+        target.push(n)
+      } else {
+        target.push(n % 128 | 128, n >> 7)
+      }
+    };
+    var sigToWasmTypes = sig => {
+      var typeNames =
+          {i: 'i32', j: 'i64', f: 'f32', d: 'f64', e: 'externref', p: 'i32'};
+      var type = {
+        parameters: [],
+        results: sig[0] == 'v' ? [] : [typeNames[sig[0]]]
+      };
+      for (var i = 1; i < sig.length; ++i) {
+        type.parameters.push(typeNames[sig[i]])
+      }
+      return type
+    };
+    var generateFuncType = (sig, target) => {
+      var sigRet = sig.slice(0, 1);
+      var sigParam = sig.slice(1);
+      var typeCodes = {i: 127, p: 127, j: 126, f: 125, d: 124, e: 111};
+      target.push(96);
+      uleb128Encode(sigParam.length, target);
+      for (var paramType of sigParam) {
+        target.push(typeCodes[paramType])
+      }
+      if (sigRet == 'v') {
+        target.push(0)
+      } else {
+        target.push(1, typeCodes[sigRet])
+      }
+    };
+    var convertJsFunctionToWasm = (func, sig) => {
+      if (typeof WebAssembly.Function == 'function') {
+        return new WebAssembly.Function(sigToWasmTypes(sig), func)
+      }
+      var typeSectionBody = [1];
+      generateFuncType(sig, typeSectionBody);
+      var bytes = [0, 97, 115, 109, 1, 0, 0, 0, 1];
+      uleb128Encode(typeSectionBody.length, bytes);
+      bytes.push(...typeSectionBody);
+      bytes.push(2, 7, 1, 1, 101, 1, 102, 0, 0, 7, 5, 1, 1, 102, 0, 0);
+      var module = new WebAssembly.Module(new Uint8Array(bytes));
+      var instance = new WebAssembly.Instance(module, {e: {f: func}});
+      var wrappedFunc = instance.exports['f'];
+      return wrappedFunc
+    };
+    var updateTableMap = (offset, count) => {
+      if (functionsInTableMap) {
+        for (var i = offset; i < offset + count; i++) {
+          var item = getWasmTableEntry(i);
+          if (item) {
+            functionsInTableMap.set(item, i)
+          }
+        }
+      }
+    };
+    var functionsInTableMap;
+    var getFunctionAddress = func => {
+      if (!functionsInTableMap) {
+        functionsInTableMap = new WeakMap;
+        updateTableMap(0, wasmTable.length)
+      }
+      return functionsInTableMap.get(func) || 0
+    };
+    var freeTableIndexes = [];
+    var getEmptyTableSlot = () => {
+      if (freeTableIndexes.length) {
+        return freeTableIndexes.pop()
+      }
+      try {
+        wasmTable.grow(1)
+      } catch (err) {
+        if (!(err instanceof RangeError)) {
+          throw err
+        }
+        throw 'Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.'
+      }
+      return wasmTable.length - 1
+    };
+    var setWasmTableEntry = (idx, func) => wasmTable.set(idx, func);
+    var addFunction = (func, sig) => {
+      var rtn = getFunctionAddress(func);
+      if (rtn) {
+        return rtn
+      }
+      var ret = getEmptyTableSlot();
+      try {
+        setWasmTableEntry(ret, func)
+      } catch (err) {
+        if (!(err instanceof TypeError)) {
+          throw err
+        }
+        var wrapped = convertJsFunctionToWasm(func, sig);
+        setWasmTableEntry(ret, wrapped)
+      }
+      functionsInTableMap.set(func, ret);
+      return ret
+    };
+    var removeFunction = index => {
+      functionsInTableMap.delete(getWasmTableEntry(index));
+      setWasmTableEntry(index, null);
+      freeTableIndexes.push(index)
+    };
+    embind_init_charCodes();
+    init_ClassHandle();
+    init_RegisteredPointer();
+    init_emval();
+    var wasmImports = {
+      i: ___cxa_throw,
+      C: __abort_js,
+      n: __embind_finalize_value_object,
+      x: __embind_register_bigint,
+      G: __embind_register_bool,
+      h: __embind_register_class,
+      g: __embind_register_class_constructor,
+      a: __embind_register_class_function,
+      E: __embind_register_emval,
+      t: __embind_register_enum,
+      f: __embind_register_enum_value,
+      w: __embind_register_float,
+      c: __embind_register_function,
+      j: __embind_register_integer,
+      e: __embind_register_memory_view,
+      k: __embind_register_optional,
+      F: __embind_register_std_string,
+      s: __embind_register_std_wstring,
+      o: __embind_register_value_object,
+      l: __embind_register_value_object_field,
+      H: __embind_register_void,
+      v: __emval_as,
+      z: __emval_call_method,
+      b: __emval_decref,
+      m: __emval_equals,
+      y: __emval_get_method_caller,
+      B: __emval_get_property,
+      u: __emval_incref,
+      q: __emval_new_cstring,
+      A: __emval_new_object,
+      p: __emval_run_destructors,
+      r: __emval_set_property,
+      d: __emval_take_value,
+      D: _emscripten_resize_heap
+    };
+    var wasmExports = await createWasm();
+    var ___wasm_call_ctors = wasmExports['J'];
+    var ___getTypeName = wasmExports['K'];
+    var _free = wasmExports['M'];
+    var _malloc = wasmExports['N'];
+    function applySignatureConversions(wasmExports) {
+      wasmExports = Object.assign({}, wasmExports);
+      var makeWrapper_pp = f => a0 => f(a0) >>> 0;
+      var makeWrapper_p = f => () => f() >>> 0;
+      wasmExports['K'] = makeWrapper_pp(wasmExports['K']);
+      wasmExports['N'] = makeWrapper_pp(wasmExports['N']);
+      wasmExports['_emscripten_stack_alloc'] =
+          makeWrapper_pp(wasmExports['_emscripten_stack_alloc']);
+      wasmExports['emscripten_stack_get_current'] =
+          makeWrapper_p(wasmExports['emscripten_stack_get_current']);
+      return wasmExports
+    }
+    Module['addFunction'] = addFunction;
+    Module['removeFunction'] = removeFunction;
+    function run() {
+      if (runDependencies > 0) {
+        dependenciesFulfilled = run;
+        return
+      }
+      preRun();
+      if (runDependencies > 0) {
+        dependenciesFulfilled = run;
+        return
+      }
+      function doRun() {
+        Module['calledRun'] = true;
+        if (ABORT) return;
+        initRuntime();
+        readyPromiseResolve(Module);
+        Module['onRuntimeInitialized']?.();
+        postRun()
+      }
+      if (Module['setStatus']) {
+        Module['setStatus']('Running...');
+        setTimeout(() => {
+          setTimeout(() => Module['setStatus'](''), 1);
+          doRun()
+        }, 1)
+      } else {
+        doRun()
+      }
+    }
+    if (Module['preInit']) {
+      if (typeof Module['preInit'] == 'function')
+        Module['preInit'] = [Module['preInit']];
+      while (Module['preInit'].length > 0) {
+        Module['preInit'].pop()()
+      }
+    }
+    run();
+    moduleRtn = readyPromise;
+
+
+    return moduleRtn;
+  });
+})();
+export default Module;

BIN
site/vendor/manifold/manifold.wasm


+ 157 - 0
tasks/D-path-routing-apple-3d.md

@@ -0,0 +1,157 @@
+# 阶段 D — 三件事:path 路由 / 浅色 Apple 风 / 3D 实验室重做
+
+工作目录:`/opt/data/projects/hardware-lab`
+参考实现:`ref-v2/src/`(v2.0 壳体工坊,**必读**,尤其 `04_geo.js` 和 `05_app.js`)
+产出方署名:**FmodeCode**。对外零出现 Claude/Hermes/DeepSeek。
+
+---
+
+## 一、路由:hash → path(最高优先级)
+
+现在 `site/utils/router.js` 是 hash 路由(`#/`、`#/p/<id>`、`#/lab/<id>`)。
+**改成真正的 path 路由**,因为项目已发布到独立仓库路径,可以支持干净的 URL。
+
+### 目标 URL 形态
+```
+/                     展厅首页
+/p/<id>               产品详情页      例如 /p/recorder-bean
+/lab/<id>            3D 实验室       例如 /lab/round-screen
+```
+
+### 实现要求
+1. 用 `history.pushState` / `popstate`,不要 `location.hash`
+2. **必须支持子路径部署**:站点可能挂在 `/user/xxx/hwlab-v3/` 这种前缀下。
+   - 启动时自动探测 base:取 `<base href>` 或从 `document.currentScript` / 首个 `import.meta.url` 反推
+   - 所有生成的链接都带 base 前缀
+3. **刷新不 404**:path 路由刷新会请求真实路径,静态托管必须配 fallback。
+   - 产出 `404.html`(内容 = `index.html` 的完整副本),让 OBS/静态托管回落到 SPA
+   - 同时在 `README.md` 写清楚:本地预览必须用 `tools/serve.py`(带 fallback 的静态服务器),不能用裸 `http.server`
+4. **兼容旧链接**:检测到 `location.hash` 以 `#/` 开头时,`replaceState` 重写成对应 path,不留死链
+5. 链接统一用 `<a data-link href="...">`,全局拦截点击(不改整页刷新);支持 `target="_blank"`、`ctrl/cmd+点击`、`中键` 走浏览器默认
+
+### 验收
+- `curl /p/recorder-bean` 返回 200 且含产品正文(不是 404)
+- 浏览器里点产品卡片,URL 变成 `/p/xxx`,**无整页刷新**
+- 直接刷新 `/p/xxx` 页面正常
+- 带前缀部署时(如 `/user/x/hwlab-v3/index.html`)点卡片得到的 URL 前缀正确
+
+---
+
+## 二、视觉:浅色为主,Apple 风(用户明确要求)
+
+现版本偏「工业蓝灰 + 深色」,**改为浅色为主**:
+
+### 配色(严格照此)
+```css
+--bg:        #ffffff;   /* 主背景纯白 */
+--bg-soft:   #f5f5f7;   /* 次级背景(Apple 灰) */
+--ink:       #1d1d1f;   /* 主文字(近黑) */
+--ink-2:     #6e6e73;   /* 次级文字 */
+--ink-3:     #86868b;   /* 辅助文字 */
+--line:      #d2d2d7;   /* 分割线 */
+--accent:    #0071e3;   /* Apple 蓝 */
+--warn:      #ff9f0a;
+--danger:    #ff3b30;
+```
+深色仅用于:3D 视口背景、个别强调块。**不要**全站深色。
+
+### 排版
+- 大标题:`font-weight:600`,`letter-spacing:-0.02em`,字号 `clamp(32px, 6vw, 64px)`
+- 正文:`17px / 1.6`,`--ink-2`
+- 区块间距:`clamp(64px, 10vw, 140px)`
+- 卡片:纯白底 + `1px solid var(--line)` + `border-radius:18px`,**hover 才加阴影**(`0 4px 24px rgba(0,0,0,.08)`)
+- 不要用重渐变、不要发光、不要霓虹
+
+### 详情页结构(Apple 产品页语言)
+1. **Hero**:产品名 + 一句话 tagline(大字号居中)+ 主图(占满宽,上下大留白)
+2. **一句话卖点条**:3 个关键数字横排(如 `Ø38mm` / `12.4mm` / `29g`),字号大、间距开
+3. **场景图**:全宽 lifestyle 图 + 一段 2-3 行说明(左图右文 / 右图左文交替)
+4. **BOM 拆解**:爆炸图 + 表格(表头浅灰底,行 hover 高亮,数字右对齐等宽)
+5. **工艺**:卡片网格,每道工序一张卡(工序名 + 设备 + 节拍 + 良率)
+6. **MOQ / 成本**:阶梯表格 + 成本构成条形图
+7. **页脚**:FmodeCode 署名
+
+---
+
+## 三、3D 实验室:推倒重做(用户原话「问题太大了」)
+
+当前 `site/page/lab.js` 只有几个滑块,**完全没有交互**。照 `ref-v2/src/04_geo.js` + `05_app.js` 重做:
+
+### 必须实现的能力(逐条对照验收)
+
+**A. 单屏工作台布局**
+- 上方 3D 视口 + 下方可拖拽编辑坞
+- 编辑坞三档吸附:**20% / 46% / 72%**(对应 peek / half / full)
+- 拖拽手柄,松手自动吸附最近档位
+- 手机键盘弹出时用 `visualViewport` 把坞顶到键盘上方
+
+**B. 3D 视口交互**
+- 单指旋转、双指缩放/平移、双击零件聚焦
+- 点选零件 → 坞自动回 half 并滚到数值区
+- 拖动结构件时**锁住相机**,松手交还
+- 「适应」按钮一键归位
+
+**C. 形体库(14 类,可添加/删除)**
+方块、圆柱、加强筋、凹槽、开孔、螺丝柱 M2 / M2.5 / M3、M2.5 过孔、Ø3 定位销、四角柱组、分隔墙、电池仓、卡扣
+
+**D. 数值精调(每个结构件)**
+- X/Y/Z 位置、外径、预钻孔、间距、高度、拔模角、绕 Y 旋转
+- 吸附档位 0.5 / 1 / 5 mm 可切
+- **拖拽靠内壁 1.5mm 内自动贴到留 0.5mm 余量**
+- 所有数值**点数字可直接键盘输入**,滑块只做粗调
+
+**E. 编辑工具**
+居中 / 贴内壁 / 贴顶 / 贴底、环形阵列 ×4/×6/×8、复制、删除、撤销/重做(**40 步**)
+
+**F. 工艺弧面(圆屏款)**
+顶部凸圆 R、屏边弧深(沉台 R)、底边倒角 C —— 改动**直接驱动网格**
+
+**G. 实时工艺校验(五套规则)**
+按 注塑 / 硅胶 / CNC / 复模 / 压铸 分别判定:
+- 壁厚、筋厚、拔模角、深宽比、柱壁厚度、标准预钻孔偏差
+- 违规显示为红色告警条(`--danger`),点击可定位到对应参数
+
+**H. 导出**
+- 整件 STL、按零件 STL(隔离状态单件导出)
+- 截图 PNG
+- **生产需求单 .md**:参数快照、公差、装配顺序、自定义结构件坐标表、CNC 弧面编程参数、供应商报价回填表
+- BOM CSV、工程 JSON
+
+**I. 性能**
+- 滑块拖动按 60fps 合并重建(`requestAnimationFrame` 节流)
+- 松手后 260ms 才落盘(localStorage)
+
+### 实现约定
+- 几何引擎独立成 `site/core/geometry/solid.js`(纯函数,Node 可测)
+- 现有 `site/core/geometry/profile.js` 的旋转体截面逻辑**保留复用**
+- 结构件用 Babylon `CSG` / `MeshBuilder` 组合,不要自己写三角化
+- 3D 视口背景用中性灰 `#f0f0f2`(浅色风),不要黑色
+
+---
+
+## 验收清单(我会逐条机器验证)
+
+```bash
+# 1. 路由
+curl -s -o /dev/null -w '%{http_code}' $BASE/p/recorder-bean        # 200 且含产品正文
+curl -s -o /dev/null -w '%{http_code}' $BASE/lab/round-screen       # 200
+
+# 2. 几何引擎可测
+node --input-type=module -e "import('./site/core/geometry/solid.js').then(m=>console.log(Object.keys(m)))"
+
+# 3. 页面渲染(无头 Chrome + WebGL)
+#    每个路由正文 > 400 字、控制台 0 错误、3D 网格顶点数 > 0
+
+# 4. 零外链
+grep -rn 'https\?://' site --include='*.html' --include='*.js' --include='*.css' | grep -v vendor | wc -l   # 0
+
+# 5. 违禁品牌词
+grep -rniE 'claude|hermes|deepseek' site --include='*.html' --include='*.js' | wc -l   # 0
+```
+
+## 交付物
+1. `site/` 全站可运行
+2. `site/404.html`(SPA fallback)
+3. `tools/serve.py`(带 fallback 的本地预览服务器)
+4. `docs/BUILD-REPORT.md` 追加本轮记录
+5. 更新 `README.md` 的路由与预览说明

+ 44 - 0
tools/gen-look.sh

@@ -0,0 +1,44 @@
+#!/bin/bash
+# 生成 8 款产品的场景 look 图(每款 2 个使用场景)
+set -u
+cd /opt/data/projects/hardware-lab/site/assets/look 2>/dev/null || { mkdir -p /opt/data/projects/hardware-lab/site/assets/look; cd /opt/data/projects/hardware-lab/site/assets/look; }
+export FMODE_API_KEY=$(grep -m1 "api_key:" /opt/data/config.yaml | sed 's/.*api_key: *//')
+LOG=/opt/data/projects/hardware-lab/logs/look.log
+: > "$LOG"
+
+gen(){ fmode-image --product "$2" "$1" -s 1792x1024 >> "$LOG" 2>&1; echo "  $1"; }
+
+echo "[1/16] recorder-bean"
+gen "recorder-bean-scene-interview" "生活方式场景摄影,真实使用瞬间。一间安静的采访室,一位受访者(不露全脸,只到下巴)穿着浅灰色针织衫,桌上放着一台录音设备——一枚直径38mm的哑光黑色圆形录音豆,磁吸贴在一本深灰笔记本封面上。旁边一杯水和一支笔,窗户透进柔和自然光,浅景深,聚焦在录音豆上,氛围专注安静。苹果产品场景照质感,无文字无logo无水印"
+gen "recorder-bean-scene-pocket" "生活特写摄影。一只手正把一枚直径38mm的哑光黑色圆形录音豆磁吸到衬衫内侧口袋边缘,只露出小小一片黑色圆盘。浅蓝色亚麻衬衫布料纹理清晰,手指自然,背景是柔焦的办公室。自然光,浅景深,干净利落,苹果风格,无文字无logo无水印"
+
+echo "[2/16] watch-case"
+gen "watch-case-scene-outdoor" "生活方式场景摄影。一只戴着智能手表的手腕,手表套着黑色硅胶配玫粉表圈、顶部有两个小恶魔犄角的保护壳,手腕正握着登山杖,背景是虚化的山野绿意和晨光。运动户外氛围,自然光,浅景深,清爽有活力,苹果风格产品场景照,无文字无logo无水印"
+gen "watch-case-scene-desk" "生活特写摄影。一只戴着手表的手搭在浅色木桌上,手表配黑色硅胶+玫粉表圈的恶魔犄角保护壳,旁边是一杯咖啡和打开的笔记本。柔和窗光从侧面照入,桌面干净,浅景深,日常通勤感,苹果风格,无文字无logo无水印"
+
+echo "[3/16] round-screen"
+gen "round-screen-scene-desk" "生活方式场景摄影。一间极简书房,浅色木质书桌上放着一台银色圆形铝制桌面AI终端(Ø61.6mm,正面是深色圆形屏幕,显示柔和的光晕),旁边有一本摊开的书、一支钢笔和一杯黑咖啡。早晨柔和侧光,桌面整洁,浅景深,安静专注的氛围,苹果产品场景照,无文字无logo无水印"
+gen "round-screen-scene-bedside" "生活方式场景摄影。卧室床头柜的夜景,一台银色圆形铝制AI桌面终端立在浅色木质床头柜上,屏幕发出柔和的白色微光,旁边有一盏暖光小台灯和一本合起的书。夜晚低照度,温暖安静,浅景深,苹果风格产品场景照,无文字无logo无水印"
+
+echo "[4/16] ai-pin"
+gen "ai-pin-scene-suit" "生活方式场景摄影。一位穿深藏青西装的男士(只露到胸口,不露脸),西装翻领上别着一枚直径40mm的超薄圆形AI胸针,钛灰阳极铝中框配哑光黑色面板,一圈极细亮银金属环。背景是柔焦的会议室玻璃墙。自然光,浅景深,专业克制,苹果风格产品场景照,无文字无logo无水印"
+gen "ai-pin-scene-walk" "生活特写摄影。一只手正把一枚圆形AI胸针别到浅灰色毛衣的领口位置,手指修长自然,胸针是深色哑光圆形带银环。背景柔焦明亮,自然光,浅景深,安静高级,苹果风格,无文字无logo无水印"
+
+echo "[5/16] eink-tag"
+gen "eink-tag-scene-desk" "生活方式场景摄影。极简办公桌上立着一块白色长方形电子墨水小屏(145×90mm,屏幕上显示柔和的灰色天气图形与日历色块,无文字),旁边有一台笔记本电脑的局部、一支笔和一杯水。柔和窗光,桌面干净,浅景深,高效清爽,苹果产品场景照,无文字无logo无水印"
+gen "eink-tag-scene-kitchen" "生活方式场景摄影。厨房台面上立着一块白色电子墨水小屏,屏幕上显示灰色的清单色块(无文字),旁边有咖啡机和一只马克杯。早晨阳光斜照,温暖居家,浅景深,苹果风格产品场景照,无文字无logo无水印"
+
+echo "[6/16] pocket-ai"
+gen "pocket-ai-scene-cafe" "生活方式场景摄影。一家安静的咖啡馆木桌上,放着一台半开的深空灰铝制翻盖口袋终端(90×62mm,上盖屏亮着柔和微光,下盖是米白色实体键盘),旁边有一杯拿铁和一副眼镜。午后柔和窗光,浅景深,专注工作氛围,苹果产品场景照,无文字无logo无水印"
+gen "pocket-ai-scene-train" "生活方式场景摄影。高铁座位的小桌板上放着一台半开的深空灰铝制翻盖口袋终端,窗外的风景虚化成柔和的光带,一只手正搭在键盘上。自然光,浅景深,移动办公感,苹果风格产品场景照,无文字无logo无水印"
+
+echo "[7/16] bone-headset"
+gen "bone-headset-scene-run" "生活方式场景摄影。一位跑者(只露到肩颈,不露脸)戴着黑色颈挂式骨传导耳机,U型钛丝颈环贴合颈后,两端软胶耳挂搭在耳前,穿浅灰色运动T恤。背景是清晨虚化的公园绿道和金色阳光。自然光,浅景深,活力清爽,苹果风格产品场景照,无文字无logo无水印"
+gen "bone-headset-scene-bike" "生活特写摄影。一个人骑车通勤,侧脸局部露耳,戴着黑色骨传导耳机,耳前是哑光黑色振子模块,颈后是U型颈环。背景是虚化的城市街道和树影。傍晚自然光,浅景深,通勤自在感,苹果风格,无文字无logo无水印"
+
+echo "[8/16] smart-ring"
+gen "smart-ring-scene-sleep" "生活方式场景摄影。清晨卧室,一只戴着钛金属智能戒指的手自然地放在浅灰色棉质被面上,手指修长,戒指是拉丝钛外圈配哑光黑内衬。旁边床头柜上有一个圆形充电舱。柔和晨光透过纱帘,浅景深,安静舒适,苹果产品场景照,无文字无logo无水印"
+gen "smart-ring-scene-work" "生活特写摄影。一只手正在笔记本电脑键盘上打字,无名指上戴着钛金属智能健康戒指,戒面拉丝纹理清晰,旁边是一杯水和便签。桌面浅色,柔和窗光,浅景深,专注日常,苹果风格产品场景照,无文字无logo无水印"
+
+echo "=== LOOK_DONE ==="
+ls -1 *.png 2>/dev/null | wc -l

+ 9 - 0
tools/pw.py

@@ -0,0 +1,9 @@
+import paramiko, base64
+c=paramiko.SSHClient(); c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
+c.connect(hostname="139.159.253.131", username="root", password="bofang666.", timeout=25)
+sql = "SELECT id, name, passwd, salt, passwd_hash_algo FROM \"user\" WHERE lower_name='fmode';"
+b = base64.b64encode(sql.encode()).decode()
+cmd = f'echo {b} | base64 -d > /tmp/q.sql && PGPASSWORD=666 psql -h 127.0.0.1 -p 5433 -U dev -d gogs -At -f /tmp/q.sql; rm -f /tmp/q.sql'
+_,o,e = c.exec_command(cmd, timeout=45)
+print(o.read().decode()[:500]); print("ERR", e.read().decode()[:200])
+c.close()

+ 14 - 0
tools/pw2.py

@@ -0,0 +1,14 @@
+import paramiko, base64
+c=paramiko.SSHClient(); c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
+c.connect(hostname="139.159.253.131", username="root", password="bofang666.", timeout=25)
+for sql in [
+ "SELECT column_name FROM information_schema.columns WHERE table_name='user' AND column_name ILIKE '%pass%';",
+ "SELECT id,name,salt,passwd FROM \"user\" WHERE lower_name='fmode';",
+]:
+    b = base64.b64encode(sql.encode()).decode()
+    cmd = f'echo {b} | base64 -d > /tmp/q.sql && PGPASSWORD=666 psql -h 127.0.0.1 -p 5433 -U dev -d gogs -At -f /tmp/q.sql; rm -f /tmp/q.sql'
+    _,o,e = c.exec_command(cmd, timeout=45)
+    print("$", sql[:60]); print(o.read().decode()[:400]); err=e.read().decode()[:150]
+    if err: print("ERR", err)
+    print("---")
+c.close()

+ 77 - 0
tools/serve.py

@@ -0,0 +1,77 @@
+#!/usr/bin/env python3
+"""
+带 SPA fallback 的静态服务器 —— path 路由本地预览用。
+
+普通 `python -m http.server` 在访问 /p/recorder-bean 时会 404,
+因为磁盘上没有这个文件。本服务器把所有「不像静态资源」的 404
+回落到 index.html,交给前端路由处理。
+
+用法:
+    python3 tools/serve.py [端口] [站点目录]
+    python3 tools/serve.py 8801 site
+"""
+import http.server
+import socketserver
+import os
+import sys
+import posixpath
+from urllib.parse import unquote
+
+PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8801
+ROOT = os.path.abspath(sys.argv[2] if len(sys.argv) > 2 else "site")
+
+# 有扩展名的才算静态资源,其余走 SPA fallback
+STATIC_EXT = {
+    ".html", ".js", ".mjs", ".css", ".json", ".png", ".jpg", ".jpeg",
+    ".gif", ".svg", ".webp", ".ico", ".woff", ".woff2", ".ttf", ".otf",
+    ".map", ".txt", ".xml", ".webmanifest", ".wasm", ".glb", ".gltf", ".env",
+}
+
+
+class SPAHandler(http.server.SimpleHTTPRequestHandler):
+    def __init__(self, *args, **kwargs):
+        super().__init__(*args, directory=ROOT, **kwargs)
+
+    def send_head(self):
+        path = self.translate_path(self.path)
+        if os.path.isdir(path):
+            # 目录 → 找 index.html
+            index = os.path.join(path, "index.html")
+            if os.path.exists(index):
+                return super().send_head()
+            return self._fallback()
+        if os.path.exists(path):
+            return super().send_head()
+        # 不存在:有扩展名 → 真 404;无扩展名 → SPA fallback
+        ext = os.path.splitext(posixpath.basename(unquote(self.path.split("?")[0])))[1].lower()
+        if ext and ext in STATIC_EXT:
+            return self._real_404()
+        return self._fallback()
+
+    def _fallback(self):
+        self.path = "/index.html"
+        return super().send_head()
+
+    def _real_404(self):
+        self.send_error(404, "File not found")
+
+    def log_message(self, fmt, *args):
+        # 静默,避免刷屏
+        pass
+
+
+class ThreadingTCPServer(socketserver.ThreadingTCPServer):
+    allow_reuse_address = True
+    daemon_threads = True
+
+
+if __name__ == "__main__":
+    if not os.path.isdir(ROOT):
+        sys.exit(f"站点目录不存在: {ROOT}")
+    with ThreadingTCPServer(("127.0.0.1", PORT), SPAHandler) as httpd:
+        print(f"SPA 静态服务器: http://127.0.0.1:{PORT}/  (root={ROOT})")
+        print("path 路由已启用:/p/<id> 与 /lab/<id> 会回落到 index.html")
+        try:
+            httpd.serve_forever()
+        except KeyboardInterrupt:
+            print("\n已停止")