solid.js 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  1. /**
  2. * core/geometry/solid.js —— 参数化壳体几何引擎(纯函数,零 DOM / 零 Babylon,Node 可测)。
  3. *
  4. * 坐标:X 向右、Y 向上、Z 向前,单位 mm;壳体外底面中心 = 原点,壳高沿 +Y。
  5. *
  6. * 构造方法(所有主壳通用):把截面离散成「若干条同点数的水平环」(外环 → 内环 → 屏孔环),
  7. * 相邻两条环之间用桥接四边形连成水平环带;竖直壁 = 环沿 Y 的挤出;封口 = 环内三角扇。
  8. * 所有三角形统一取 (a,b,c) 绕向,使几何法线 (p2−p1)×(p3−p1) 朝外(Babylon 约定),
  9. * 面板的朝向在构造参数里显式给出,不靠运行时猜绕向 —— 结果拓扑干净,可直接进 CSG / STL。
  10. *
  11. * 结构件(形体库 14 类)生成密闭切割体;工艺校验、内腔包络、派生尺寸、需求单文本也在这里。
  12. */
  13. export const PRIMS = {
  14. box: { n: '方块', short: '基础', d: { w: 8, h: 6, dd: 8 } },
  15. cyl: { n: '圆柱', short: '基础', d: { dia: 10, h: 8 } },
  16. rib: { n: '加强筋', short: '基础', d: { w: 14, h: 5, dd: 1.2 } },
  17. pocket: { n: '凹槽(铣削)', short: '基础', d: { w: 10, h: 2, dd: 10 } },
  18. hole: { n: '开孔(钻孔)', short: '基础', d: { dia: 3, h: 4 } },
  19. boss2: { n: '螺丝柱 M2', short: '紧固', d: { dia: 4.0, h: 7, dd: 1.6 } },
  20. boss25: { n: '螺丝柱 M2.5', short: '紧固', d: { dia: 4.8, h: 8, dd: 2.1 } },
  21. boss3: { n: '螺丝柱 M3', short: '紧固', d: { dia: 5.6, h: 9, dd: 2.6 } },
  22. thru25: { n: 'M2.5 过孔', short: '紧固', d: { dia: 2.7, h: 4, dd: 2.7 } },
  23. pin3: { n: '定位销 Ø3', short: '紧固', d: { dia: 3, h: 4 } },
  24. pad4: { n: '四角柱组 M2.5', short: '腔体', d: { w: 30, h: 7, dd: 30, dia: 4.8, hd: 2.1 } },
  25. wall: { n: '分隔墙', short: '腔体', d: { w: 20, h: 6, dd: 0.8 } },
  26. tray: { n: '电池仓', short: '腔体', d: { w: 22, h: 6, dd: 18 } },
  27. clip: { n: '卡扣', short: '腔体', d: { w: 5, h: 4, dd: 1.2 } },
  28. };
  29. export const PRIM_KEYS = Object.keys(PRIMS);
  30. export const HOLLOW_TYPES = ['boss2', 'boss25', 'boss3', 'thru25'];
  31. export const CYL_TYPES = ['cyl', 'hole', 'pin3', ...HOLLOW_TYPES];
  32. export const RECT_TYPES = ['box', 'pocket', 'rib', 'wall', 'clip', 'tray'];
  33. /** 标准自攻预钻孔(mm):M2 / M2.5 / M3 */
  34. export const STD_PILOT = { boss2: 1.6, boss25: 2.1, boss3: 2.6 };
  35. const TAU = Math.PI * 2;
  36. const RAD = Math.PI / 180;
  37. const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
  38. const r2 = (v) => Math.round(v * 100) / 100;
  39. const num = (v, d = 0) => (+v || d);
  40. export function primDims(s) {
  41. return s.w !== undefined ? [num(s.w), num(s.dd), num(s.h)] : [num(s.dia), num(s.dia), num(s.h)];
  42. }
  43. /* =========================================================
  44. 网格工具
  45. ========================================================= */
  46. export function computeNormals(positions, indices) {
  47. const n = new Float64Array(positions.length);
  48. for (let i = 0; i < indices.length; i += 3) {
  49. const a = indices[i] * 3, b = indices[i + 1] * 3, c = indices[i + 2] * 3;
  50. const ux = positions[b] - positions[a], uy = positions[b + 1] - positions[a + 1], uz = positions[b + 2] - positions[a + 2];
  51. const vx = positions[c] - positions[a], vy = positions[c + 1] - positions[a + 1], vz = positions[c + 2] - positions[a + 2];
  52. const nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx;
  53. n[a] += nx; n[a + 1] += ny; n[a + 2] += nz;
  54. n[b] += nx; n[b + 1] += ny; n[b + 2] += nz;
  55. n[c] += nx; n[c + 1] += ny; n[c + 2] += nz;
  56. }
  57. const out = new Array(positions.length);
  58. for (let i = 0; i < n.length; i += 3) {
  59. const l = Math.hypot(n[i], n[i + 1], n[i + 2]) || 1;
  60. out[i] = n[i] / l; out[i + 1] = n[i + 1] / l; out[i + 2] = n[i + 2] / l;
  61. }
  62. return out;
  63. }
  64. /** 有向体积(mm³):封闭、外法向网格为正 */
  65. export function meshVolume(positions, indices) {
  66. let v = 0;
  67. for (let i = 0; i < indices.length; i += 3) {
  68. const a = indices[i] * 3, b = indices[i + 1] * 3, c = indices[i + 2] * 3;
  69. v += (positions[a] * (positions[b + 1] * positions[c + 2] - positions[b + 2] * positions[c + 1])
  70. - positions[a + 1] * (positions[b] * positions[c + 2] - positions[b + 2] * positions[c])
  71. + positions[a + 2] * (positions[b] * positions[c + 1] - positions[b + 1] * positions[c])) / 6;
  72. }
  73. return v;
  74. }
  75. export function bbox(positions) {
  76. const mn = [Infinity, Infinity, Infinity], mx = [-Infinity, -Infinity, -Infinity];
  77. for (let i = 0; i < positions.length; i += 3) for (let k = 0; k < 3; k++) {
  78. const v = positions[i + k]; if (v < mn[k]) mn[k] = v; if (v > mx[k]) mx[k] = v;
  79. }
  80. return { min: mn, max: mx };
  81. }
  82. export function mergeMeshes(list) {
  83. const positions = [], indices = [];
  84. for (const m of list) {
  85. if (!m) continue;
  86. const base = positions.length / 3;
  87. for (const v of m.positions) positions.push(v);
  88. for (const i of m.indices) indices.push(i + base);
  89. }
  90. return { positions, indices };
  91. }
  92. export function translate(mesh, x, y, z) {
  93. const p = mesh.positions.slice();
  94. for (let i = 0; i < p.length; i += 3) { p[i] += x; p[i + 1] += y; p[i + 2] += z; }
  95. return { positions: p, indices: mesh.indices.slice() };
  96. }
  97. /** 绕 Y 轴旋转(角度制)后平移 —— 和 Babylon rotation.y = deg 同向 */
  98. export function rotateY(mesh, deg, tx = 0, ty = 0, tz = 0) {
  99. const a = deg * RAD, c = Math.cos(a), s = Math.sin(a);
  100. const p = mesh.positions.slice();
  101. for (let i = 0; i < p.length; i += 3) {
  102. const x = p[i], z = p[i + 2];
  103. p[i] = tx + x * c + z * s;
  104. p[i + 2] = tz - x * s + z * c;
  105. p[i + 1] += ty;
  106. }
  107. return { positions: p, indices: mesh.indices.slice() };
  108. }
  109. /* =========================================================
  110. 环 / 环带 / 竖壁 / 扇面
  111. ========================================================= */
  112. /** 环面积(XZ 平面,>0 = 俯视逆时针);点可为 {x,z} 或 {r}(半径型,自动转 xz) */
  113. export function ringArea(ring) {
  114. let a = 0;
  115. for (let i = 0; i < ring.length; i++) {
  116. const p = ring[i], q = ring[(i + 1) % ring.length];
  117. a += p.x * q.z - q.x * p.z;
  118. }
  119. return a / 2;
  120. }
  121. /** 闭合环去重(相邻点 < tol 合并,末点与首点重合去掉) */
  122. export function dedupeRing(pts, tol = 0.02) {
  123. const out = [];
  124. for (const p of pts) {
  125. const q = out[out.length - 1];
  126. if (q && Math.hypot(p.x - q.x, p.z - q.z) < tol) { q.x = p.x; q.z = p.z; continue; }
  127. out.push({ x: p.x, z: p.z });
  128. }
  129. 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();
  130. return out;
  131. }
  132. /**
  133. * 朝外三角形:triO(B, a, b, c, nx, ny, nz) 让三角形 (a,b,c) 的几何法线与期望法向 (nx,ny,nz) 同向。
  134. * 期望法向:水平面用 (0,±1,0);竖壁用该面中点的水平径向 (x,0,z)(凸环朝外、凹环朝内均为径向)。
  135. * 零面积三角形跳过 —— 凹弧在径向法向下的退化面由此安全剔除。
  136. */
  137. function triO(B, a, b, c, nx, ny, nz) {
  138. const P = (i) => [B.pos[i * 3], B.pos[i * 3 + 1], B.pos[i * 3 + 2]];
  139. const A = P(a), Bp = P(b), C = P(c);
  140. const e1 = [Bp[0] - A[0], Bp[1] - A[1], Bp[2] - A[2]];
  141. const e2 = [C[0] - A[0], C[1] - A[1], C[2] - A[2]];
  142. 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];
  143. if (gx * gx + gy * gy + gz * gz < 1e-14) return;
  144. const dot = gx * nx + gy * ny + gz * nz;
  145. if (dot >= 0) B.idx.push(a, b, c); else B.idx.push(a, c, b);
  146. }
  147. /** 四边形 a,b,c,d(按环序 A_j, A_j2, B_j2, B_j)→ 两三角形,法向同 (nx,ny,nz) */
  148. 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); }
  149. /** 环带:A(外)与 B(内)等长;法线朝 +Y(up)或 −Y(down) */
  150. function bandTris(B, A, Bn, dir) {
  151. const n = A.length;
  152. for (let j = 0; j < n; j++) {
  153. const j2 = (j + 1) % n;
  154. quadN(B, A[j], A[j2], Bn[j2], Bn[j], 0, dir === 'up' ? 1 : -1, 0);
  155. }
  156. }
  157. /** 环在 XZ 平面的绕向(> 0 = 俯视逆时针),用鞋带公式在网格坐标上算 */
  158. function ringCcw(B, ring) {
  159. let a = 0;
  160. for (let j = 0; j < ring.length; j++) {
  161. const p = ring[j] * 3, q = ring[(j + 1) % ring.length] * 3;
  162. a += B.pos[p] * B.pos[q + 2] - B.pos[q] * B.pos[p + 2];
  163. }
  164. return a < 0; // 鞋带和 < 0 表示 CCW(XZ 视角,z 向上为屏幕下方)
  165. }
  166. /** 直接按 flip 输出四边形(不猜法线) */
  167. function quadW(B, a, b, c, d, flip) {
  168. if (flip) { B.idx.push(a, c, b, a, d, c); } else { B.idx.push(a, b, c, a, c, d); }
  169. }
  170. /** 竖壁:环 A(底 y0)与 B(顶 y1);法线由面中点的水平径向决定(凸面/凹面都正确朝外) */
  171. function wallTris(B, A, Bn, radial = 1) {
  172. const n = A.length;
  173. const P = (i, k) => B.pos[i * 3 + k];
  174. for (let j = 0; j < n; j++) {
  175. const j2 = (j + 1) % n;
  176. const a = A[j], b = A[j2], c = Bn[j2], d = Bn[j];
  177. const mx = (P(a, 0) + P(b, 0) + P(c, 0) + P(d, 0)) / 4;
  178. const mz = (P(a, 2) + P(b, 2) + P(c, 2) + P(d, 2)) / 4;
  179. quadN(B, a, b, c, d, mx * radial, 0, mz * radial);
  180. }
  181. }
  182. /** 环内封口三角扇到轴心点 c(扇面朝 +Y / −Y) */
  183. function capTris(B, ring, c, dir) {
  184. const n = ring.length;
  185. for (let j = 0; j < n; j++) quadN(B, ring[j], ring[(j + 1) % n], c, c, 0, dir === 'up' ? 1 : -1, 0);
  186. }
  187. class Builder {
  188. constructor() { this.pos = []; this.idx = []; }
  189. add(x, y, z) { this.pos.push(x, y, z); return this.pos.length / 3 - 1; }
  190. ring(pts, y, cx = 0, cz = 0) {
  191. const ids = [];
  192. for (const p of pts) ids.push(this.add(cx + p.x, y, cz + p.z));
  193. return ids;
  194. }
  195. mesh() { return { positions: this.pos, indices: this.idx }; }
  196. }
  197. /* =========================================================
  198. 壳体主体
  199. ========================================================= */
  200. /** 圆角矩形环(XZ,CCW,中心原点) */
  201. export function roundedRectRing(w, d, r, seg = 8) {
  202. const hw = w / 2, hd = d / 2;
  203. const rr = Math.max(0.001, Math.min(r, hw - 0.001, hd - 0.001));
  204. const out = [];
  205. 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]];
  206. for (const [cx, cz, a0] of corners) for (let i = 0; i <= seg; i++) {
  207. const a = a0 + (Math.PI / 2) * (i / seg);
  208. out.push({ x: cx + rr * Math.cos(a), z: cz + rr * Math.sin(a) });
  209. }
  210. return out;
  211. }
  212. /** circleRing */
  213. export function circleRing(r, seg = 64, cw = false) {
  214. const out = [];
  215. 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) }); }
  216. return out;
  217. }
  218. /**
  219. * 回转体(圆件 / 表壳 / 戒指):截面点 [[r, y], …](r ≥ 0,闭合;r=0 的两端为轴心)。
  220. * 每个面的法向取「面中点的径向(含高度分量)」—— 回转面上它要么指向外侧(凸段),
  221. * 要么指向轴线(内腔 / 沉台内壁),截面可以任意来回,朝外由 triO 保证。
  222. * seg:圆周分段;cx/cz:水平偏移。
  223. */
  224. export function roundShell(points, seg = 112, _sign = 1) {
  225. 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);
  226. const b = new Builder();
  227. // 每行一个环(轴心行只放一个顶点),环与环之间三角化;绕向按「面中点径向」逐面校正
  228. // 轴心点按连续等值(r≈0)合并为一个顶点(CSG 需要坐标去重后的封闭流形)
  229. const P = (i) => [b.pos[i * 3], b.pos[i * 3 + 1], b.pos[i * 3 + 2]];
  230. const rows = [];
  231. let lastAxis = -1;
  232. for (const [r, y] of pts) {
  233. if (r < 1e-4) {
  234. if (lastAxis < 0 || Math.abs(P(lastAxis)[1] - y) > 1e-6) lastAxis = b.add(0, y, 0);
  235. rows.push([lastAxis]);
  236. continue;
  237. }
  238. lastAxis = -1;
  239. const ids = [];
  240. 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))); }
  241. rows.push(ids);
  242. }
  243. const pushT = (a, b2, c, nrm) => {
  244. const A = P(a), Bp = P(b2), C = P(c);
  245. 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]];
  246. 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];
  247. if (nx * nx + ny * ny + nz * nz < 1e-12) return;
  248. const dot = nx * nrm[0] + ny * nrm[1] + nz * nrm[2];
  249. if (dot >= 0) b.idx.push(a, b2, c); else b.idx.push(a, c, b2);
  250. };
  251. for (let i = 0; i < rows.length - 1; i++) {
  252. const A = rows[i], Bn = rows[i + 1];
  253. const aAxis = A.length === 1, bAxis = Bn.length === 1;
  254. for (let s = 0; s < seg; s++) {
  255. const s2 = (s + 1) % seg;
  256. const a = aAxis ? A[0] : A[s], b2 = aAxis ? A[0] : A[s2];
  257. const c = bAxis ? Bn[0] : Bn[s2], d = bAxis ? Bn[0] : Bn[s];
  258. const ids4 = [a, b2, c, d];
  259. const ys = ids4.map((id) => P(id)[1]);
  260. let mut = 0, muz = 0;
  261. for (const id of ids4) { mut += P(id)[0] / 4; muz += P(id)[2] / 4; }
  262. const flat = ys.every((y) => Math.abs(y - ys[0]) < 1e-6);
  263. if (aAxis || bAxis) {
  264. // 轴心侧:单个三角形,期望法向取该三角形所在环面的径向(平面圆盘为 ±Y)
  265. const nrm = flat ? [0, P(A[0])[1] > P(Bn[0])[1] ? 1 : -1, 0] : [mut, 0, muz];
  266. if (aAxis) pushT(a, d, c, nrm); else pushT(a, c, b2, nrm);
  267. continue;
  268. }
  269. // pushT 内部按法线校正绕向;这里先给「互不相反」的基础顺序:(a,d,c) 与 (a,b,c)
  270. const nrm = flat ? [0, P(A[0])[1] > P(Bn[0])[1] ? 1 : -1, 0] : [mut, 0, muz];
  271. pushT(a, d, c, nrm); pushT(a, b2, c, nrm);
  272. }
  273. }
  274. return b.mesh();
  275. }
  276. /**
  277. * 四边面:两个三角形顶点完全一致(不生成对角新点),CSG 内部按「闭合多边形」处理,
  278. * 不会产生 T 形半边。绕向先按 (a,b,c) 与 (a,c,d) 同向写入,再按「面中点径向」保证朝外。
  279. */
  280. function addQuad(b, a, b2, c, d) {
  281. const P = (i) => [b.pos[i * 3], b.pos[i * 3 + 1], b.pos[i * 3 + 2]];
  282. const A = P(a), Bp = P(b2), C = P(c), D = P(d);
  283. // 三个非对顶组合中取非零面积的那个判定绕向:(a,b,c) 与 (a,c,d) 同向
  284. 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]];
  285. 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];
  286. 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;
  287. const dot = nx * mx + ny * my + nz * mz;
  288. if (dot >= 0) { b.idx.push(a, b2, c, a, c, d); } else { b.idx.push(a, c, b2, a, d, c); }
  289. }
  290. /**
  291. * 等距内缩点(与 roundedRectRing 同点序):直边沿法向收 d,圆角沿径向、R 减 d。
  292. * 关键:用生成外环时的「拐角采样参数」判断点在圆角还是直边,保证内外环一一对应。
  293. * angs = 每个点的 { c: 拐角0..3, a: 采样角 }(由 ringAngles() 给出)。
  294. */
  295. export function insetPoint(p, L, W, d, r0, angs = null) {
  296. const hw = L / 2, hd = W / 2;
  297. const rr = clamp(r0, 0.001, Math.min(hw, hd) - 0.001);
  298. if (angs) {
  299. // 每个采样点归属:拐角 c 的弧(a ∈ (0, π/2))、水平边(a = 0 或 π/2 的端点,线段按两端点序号判定)。
  300. // 水平边沿 z 收 d;竖直边沿 x 收 d;弧沿径向。段端点是相邻弧的切点,归入该边。
  301. const c = angs.c, a = angs.a, i = angs.i;
  302. // 拐角序号 → 圆心:0 右上、1 左上、2 左下、3 右下
  303. const ccx = [hw - rr, -hw + rr, -hw + rr, hw - rr][c];
  304. const ccz = [hd - rr, hd - rr, -hd + rr, -hd + rr][c];
  305. const rk = Math.max(rr * 0.2, rr - d);
  306. const p0 = rr - d; // 内缩后圆角终点距内边坐标的距离
  307. 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) };
  308. // 段端点:线段自本拐角 a=0 端点到相邻拐角 a=π/2 端点
  309. if (i % 9 === 0) {
  310. // 弧起点(调用端):角0 在右侧竖边(x=hw);角1 在顶边(z=hd);角2 在左侧竖边(x=-hw);角3 在底边(z=-hd)
  311. 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 };
  312. }
  313. 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 };
  314. void p0;
  315. }
  316. // 无参数时按几何位置判断
  317. if (Math.abs(p.x) >= hw - rr - 1e-6 && Math.abs(p.z) >= hd - rr - 1e-6) {
  318. const cx = (p.x >= 0 ? 1 : -1) * (hw - rr), cz = (p.z >= 0 ? 1 : -1) * (hd - rr);
  319. const ax = p.x - cx, az = p.z - cz, l = Math.hypot(ax, az) || 1;
  320. const rk = Math.max(rr * 0.2, rr - d);
  321. return { x: cx + (ax / l) * rk, z: cz + (az / l) * rk };
  322. }
  323. if (p.x === hw || p.x === -hw) return { x: p.x - Math.sign(p.x) * d, z: p.z };
  324. if (p.z === hd || p.z === -hd) return { x: p.x, z: p.z - Math.sign(p.z) * d };
  325. 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 };
  326. }
  327. /** 圆角矩形环 + 每点的采样参数(拐角序号 c、采样角 a):点序与 roundedRectRing 完全一致 */
  328. export function roundedRectRingAngles(w, d, r, seg = 8) {
  329. const hw = w / 2, hd = d / 2;
  330. const rr = Math.max(0.001, Math.min(r, hw - 0.001, hd - 0.001));
  331. 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]];
  332. const out = [];
  333. corners.forEach(([cx, cz, a0], c) => {
  334. for (let i = 0; i <= seg; i++) {
  335. const a = a0 + (Math.PI / 2) * (i / seg);
  336. out.push({ x: cx + rr * Math.cos(a), z: cz + rr * Math.sin(a), c, a: (Math.PI / 2) * (i / seg), i });
  337. }
  338. });
  339. return out;
  340. }
  341. /**
  342. * 方件(rect / watch):圆角矩形挤出 + 底腔 + 顶面圆角 + 屏沉台。
  343. * o = { L, W, H, wall, cornerR, domeR, chamferC, floorT, screenW, screenHh, recessDepth, seg }
  344. * 环序(自外向内,全部 CCW,点数一致):
  345. * O 外壁底 → Oce 底边倒角顶 → O 外壁顶 → Oin 顶面圆角内沿 → C 内腔口 → C 内腔底 → S 屏孔底 → S 沉台顶
  346. */
  347. export function boxShell(o) {
  348. const L = Math.max(2, o.L), W = Math.max(2, o.W), H = Math.max(1.5, o.H);
  349. const wall = clamp(o.wall ?? 1.5, 0.3, Math.min(L, W) / 2 - 0.5);
  350. const seg = o.seg || 8;
  351. const r0 = o.cornerR ?? 0;
  352. const floor = clamp(o.floorT ?? wall, 0.4, H * 0.45);
  353. const dome = clamp(o.domeR ?? 0, 0, Math.min(H - floor - 0.6, Math.min(L, W) / 4));
  354. const bot = clamp(o.chamferC ?? 0, 0, Math.min(H * 0.3, wall * 0.8));
  355. const depth = clamp(o.recessDepth ?? Math.min(1.2, (H - floor) * 0.35), 0.2, H - floor - 0.3);
  356. const sw = clamp(o.screenW ?? L - 2 * wall - 6, 1, L - 2 * wall);
  357. const sh = clamp(o.screenHh ?? W - 2 * wall - 6, 1, W - 2 * wall);
  358. const OA = roundedRectRingAngles(L, W, r0, seg);
  359. const O = OA.map((p) => ({ x: p.x, z: p.z }));
  360. const inset = (d) => OA.map((p) => insetPoint(p, L, W, d, r0, p));
  361. const b = new Builder();
  362. const rO = b.ring(O, 0);
  363. const rOce = bot > 0.01 ? b.ring(inset(bot), bot) : rO;
  364. const rOtop = b.ring(O, H);
  365. const Cpts = inset(wall);
  366. const rCavTop = b.ring(Cpts, H);
  367. const rCavBot = b.ring(Cpts, floor);
  368. // ① 顶面:外环 → 内腔口(朝上;dome 用中间过渡环近似圆角)
  369. if (dome > 0.01) {
  370. const rMid = b.ring(inset(wall / 2 + dome * 0.5), H - dome * 0.35);
  371. bandTris(b, rOtop, rMid, 'up');
  372. bandTris(b, rMid, rCavTop, 'up');
  373. } else bandTris(b, rOtop, rCavTop, 'up');
  374. // ② 底面:内腔环 → 外环(朝下)
  375. bandTris(b, rCavBot, rO, 'down');
  376. // ③ 外壁:倒角环 → 外顶(朝外)
  377. if (rOce !== rO) wallTris(b, rO, rOce);
  378. wallTris(b, rOce, rOtop);
  379. // ④ 内腔壁:顶 → 底(径向朝内,凹环自动朝腔)
  380. wallTris(b, rCavTop, rCavBot, -1);
  381. return b.mesh();
  382. }
  383. /** 表壳(watch):圆角矩形挤出 + 底腔 + 顶面圆角,开口为方角屏(表盘) */
  384. export function watchShell(o) {
  385. const { dTop: D, length: L, height: H, wall, cornerR, domeR, chamferC } = o;
  386. return boxShell({
  387. L, W: D, H, wall,
  388. cornerR: cornerR ?? Math.min(D, L) * 0.25,
  389. domeR: domeR ?? 1,
  390. chamferC: chamferC ?? 0.5,
  391. floorT: wall,
  392. screenW: Math.max(4, D - 2 * wall - 5),
  393. screenHh: Math.max(4, D - 2 * wall - 5),
  394. recessDepth: Math.max(0.6, Math.min(1.4, H * 0.2)),
  395. seg: 10,
  396. });
  397. }
  398. /**
  399. * 戒指(ring):扁圆环带。截面行进方向(外法向 = 行进方向右侧):内底 → 外底 → 外壁上升 → 外顶圆角 → 顶面内收 → 内壁下降 → 内底圆角。
  400. * o = { ringD, ringBandW, height, wall, cornerR }
  401. */
  402. export function ringShell(o) {
  403. const D = num(o.ringD, 19), bw = num(o.ringBandW, 6.5), H = Math.max(1, num(o.height, 7));
  404. const wall = clamp(num(o.wall, 1.2), 0.3, bw / 2 - 0.1);
  405. const ri = D / 2, ro = ri + bw;
  406. const rc = Math.min(ro - 0.6, ri + Math.max(0.6, wall)); // 贴指面半径(内圈外沿)
  407. const rr = Math.max(0.1, Math.min(num(o.cornerR, 2), bw / 2 - 0.05, H / 2 - 0.05));
  408. const seg = 96;
  409. const b = new Builder();
  410. const circ = (r, y) => b.ring(circleRing(r, seg, false), y);
  411. 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) }); } };
  412. const band = (A, Bn, outward) => {
  413. for (let j = 0; j < A.length; j++) {
  414. const j2 = (j + 1) % A.length;
  415. const a = A[j], b2 = A[j2], c = Bn[j2], d = Bn[j];
  416. const mx = (b.pos[a * 3] + b.pos[b2 * 3] + b.pos[c * 3] + b.pos[d * 3]) / 4;
  417. const mz = (b.pos[a * 3 + 2] + b.pos[b2 * 3 + 2] + b.pos[c * 3 + 2] + b.pos[d * 3 + 2]) / 4;
  418. quadN(b, a, b2, c, d, mx * outward, 0, mz * outward);
  419. }
  420. };
  421. // ① 外壁:底(含外底圆角)→ 外顶(含外顶圆角)
  422. const outerPts = [{ x: ro - rr, z: 0 }];
  423. arc(outerPts, ro - rr, rr, rr, -Math.PI / 2, 0, 5);
  424. outerPts.push({ x: ro - rr, z: H - rr });
  425. arc(outerPts, ro - rr, H - rr, rr, 0, Math.PI / 2, 5);
  426. for (let i = 1; i < outerPts.length; i++) {
  427. band(circ(outerPts[i - 1].x, outerPts[i - 1].z), circ(outerPts[i].x, outerPts[i].z), 1);
  428. }
  429. // ② 内圈(贴指面,凸向轴心):顶部小圆角下行到底
  430. const collarPts = [{ x: rc, z: H - 0.4 }];
  431. arc(collarPts, rc + 0.4, H - 0.4, 0.4, Math.PI, 1.5 * Math.PI, 4);
  432. collarPts.push({ x: rc + 0.4, z: H });
  433. for (let i = 1; i < collarPts.length; i++) {
  434. band(circ(collarPts[i - 1].x, collarPts[i - 1].z), circ(collarPts[i].x, collarPts[i].z), -1);
  435. }
  436. // ③ 指孔内壁(圆柱面)
  437. band(circ(ri, 0), circ(ri, H), -1);
  438. // ④ 底面:底环带(ro−rr → ri,朝下)+ 底内环(rc → ri,朝下)
  439. const capBand = (rOuter, rInner) => {
  440. const O = circ(rOuter, 0), I = circ(rInner, 0);
  441. for (let j = 0; j < seg; j++) {
  442. const j2 = (j + 1) % seg;
  443. quadN(b, O[j], O[j2], I[j2], I[j], 0, -1, 0);
  444. }
  445. };
  446. capBand(ro - rr, ri);
  447. capBand(ri, rc);
  448. // ⑤ 顶面:外顶圆角末端(ro−rr)→ 内圈顶部末端(rc+0.4,y=H)朝上环带
  449. const T1 = circ(ro - rr, H), T2 = circ(rc + 0.4, H);
  450. for (let j = 0; j < seg; j++) {
  451. const j2 = (j + 1) % seg;
  452. quadN(b, T1[j], T1[j2], T2[j2], T2[j], 0, 1, 0);
  453. }
  454. // ⑥ 指孔底沿:ri(y=0)与 rc(y=0)之间的底环已由 ④ capBand(ri, rc) 覆盖;指孔顶沿:
  455. const K1 = circ(ri, H), K2 = circ(rc, H - 0.4);
  456. for (let j = 0; j < seg; j++) {
  457. const j2 = (j + 1) % seg;
  458. quadN(b, K1[j], K1[j2], K2[j2], K2[j], 0, 1, 0);
  459. }
  460. return b.mesh();
  461. }
  462. /* =========================================================
  463. 结构件(形体库,局部坐标:Y 向上,原点在件中心)
  464. ========================================================= */
  465. function hollowCylinder(od, id, h, tess = 24) {
  466. const b = new Builder();
  467. const ri = Math.max(0.05, id / 2), ro = Math.max(ri + 0.3, od / 2), hh = Math.max(0.1, h / 2);
  468. 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; };
  469. const oT = mk(ro, hh), oB = mk(ro, -hh), iT = mk(ri, hh), iB = mk(ri, -hh);
  470. wallTris(b, oB, oT);
  471. wallTris(b, iB, iT, -1);
  472. bandTris(b, oT, iT, 'up');
  473. bandTris(b, oB, iB, 'down');
  474. return b.mesh();
  475. }
  476. export function solidCylinder(dia, h, tess = 32, y0 = null) {
  477. const b = new Builder();
  478. 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);
  479. 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; };
  480. const T = mk(yt), B = mk(yb);
  481. wallTris(b, B, T);
  482. capTris(b, T, b.add(0, yt, 0), 'up');
  483. capTris(b, B, b.add(0, yb, 0), 'down');
  484. return b.mesh();
  485. }
  486. export function boxMesh(w, h, d) {
  487. const hw = w / 2, hh = h / 2, hd = d / 2;
  488. 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]];
  489. return {
  490. positions: v.flat(),
  491. indices: [
  492. 4, 5, 6, 4, 6, 7, // +z
  493. 1, 0, 3, 1, 3, 2, // −z
  494. 5, 1, 2, 5, 2, 6, // +x
  495. 0, 4, 7, 0, 7, 3, // −x
  496. 3, 7, 6, 3, 6, 2, // +y
  497. 0, 1, 5, 0, 5, 4, // −y
  498. ],
  499. };
  500. }
  501. /** 带拔模的方柱(顶面内收);draft=0 即普通方柱 */
  502. export function taperedBox(w, h, d, draftDeg) {
  503. const m = boxMesh(w, h, d);
  504. const t = Math.tan(Math.max(0, draftDeg) * RAD) * h;
  505. 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);
  506. 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; }
  507. return m;
  508. }
  509. /**
  510. * 结构件 → 局部坐标三角网格(Y 向上,原点在件中心高度)。
  511. * 实心件(螺丝柱 / 方块)整体保留:既是本体也是切割体(壳内相交部分会被布尔吃掉)。
  512. * 切割件(凹槽 / 开孔 / 过孔):其「孔壁」切割体;同型再生成一个细杆指示体(show)。
  513. */
  514. export function primMesh(spec) {
  515. const t = spec.type, h = Math.max(0.1, num(spec.h, 1));
  516. if (t === 'box') return { part: boxMesh(Math.max(0.1, num(spec.w, 1)), h, Math.max(0.1, num(spec.dd, 1))) };
  517. 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) };
  518. if (t === 'clip') return { part: taperedBox(Math.max(0.1, num(spec.w, 1)), h, Math.max(0.1, num(spec.dd, 1)), 0) };
  519. if (t === 'pocket') return { part: boxMesh(Math.max(0.2, num(spec.w, 1)), h, Math.max(0.2, num(spec.dd, 1))) };
  520. if (t === 'hole' || t === 'thru25') return { part: solidCylinder(Math.max(0.2, num(spec.dia, 1)), h, 24) };
  521. if (t === 'cyl') return { part: solidCylinder(Math.max(0.2, num(spec.dia, 1)), h, 32) };
  522. if (t === 'pin3') return { part: solidCylinder(Math.max(0.2, num(spec.dia, 1)), h, 20) };
  523. 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) };
  524. if (t === 'pad4') {
  525. 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));
  526. const one = hollowCylinder(od, hd, h, 20);
  527. const parts = [];
  528. 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)));
  529. return { part: mergeMeshes(parts) };
  530. }
  531. if (t === 'tray') {
  532. 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));
  533. const parts = [translate(boxMesh(w, th, d), 0, -h / 2 + th / 2, 0)];
  534. for (const sg of [-1, 1]) {
  535. parts.push(translate(boxMesh(th, h, d), sg * (w / 2 - th / 2), 0, 0));
  536. parts.push(translate(boxMesh(w, h, th), 0, 0, sg * (d / 2 - th / 2)));
  537. }
  538. return { part: mergeMeshes(parts) };
  539. }
  540. return { part: boxMesh(8, h, 8) };
  541. }
  542. /** 结构件世界网格:按 spec.x / spec.y / spec.z / spec.rot 摆到位 */
  543. export function placePrim(mesh, spec) {
  544. return rotateY(mesh, spec.rot || 0, num(spec.x), num(spec.y), num(spec.z));
  545. }
  546. /** 结构件是否「减料」(CSG 减去);其余按实体加入 */
  547. export function isCutType(type) { return type === 'pocket' || type === 'hole' || type === 'thru25'; }
  548. /* =========================================================
  549. 内腔包络 / 结构件落位
  550. ========================================================= */
  551. export function cavity(shapeType, p) {
  552. if (shapeType === 'rect') {
  553. const L = num(p.length, 40), W = num(p.dTop, 30), H = num(p.height, 8), wall = num(p.wall, 1.5);
  554. 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) };
  555. }
  556. if (shapeType === 'watch') {
  557. const D = num(p.dTop, 45), L = num(p.length, 54), H = num(p.height, 12), wall = num(p.wall, 2);
  558. 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 };
  559. }
  560. if (shapeType === 'ring') {
  561. const D = num(p.dTop, 40), H = num(p.height, 6), wall = num(p.wall, 1.2);
  562. return { kind: 'cyl', r: Math.max(1, D / 2 - wall), floor: Math.max(0.4, wall), top: Math.max(0.8, H - 0.2) };
  563. }
  564. const D = num(p.dTop, 40), H = num(p.height, 10), wall = num(p.wall, 1.5);
  565. 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)) };
  566. }
  567. /** 件到内腔边界的余量(mm;正 = 在内腔里) */
  568. export function clearanceTo(cav, s) {
  569. const [w, d] = primDims(s);
  570. const x = num(s.x), z = num(s.z), y = num(s.y), h = num(s.h, 1);
  571. let side;
  572. if (cav.kind === 'cyl') side = cav.r - Math.hypot(x, z) - Math.max(w, d) / 2;
  573. else side = Math.min(cav.halfX - Math.abs(x) - w / 2, cav.halfZ - Math.abs(z) - d / 2);
  574. const bottom = y - h / 2 - cav.floor;
  575. const top = cav.top - (y + h / 2);
  576. return r2(Math.min(side, bottom, top));
  577. }
  578. export function snapToWall(cav, s, margin = 1) {
  579. const [w, d] = primDims(s);
  580. if (cav.kind === 'cyl') return { x: r2(Math.max(0, cav.r - Math.max(w, d) / 2 - margin)), z: 0 };
  581. return { x: 0, z: r2(Math.max(0, cav.halfZ - d / 2 - margin)) };
  582. }
  583. export function snapY(cav, s, mode) {
  584. const h = num(s.h, 1);
  585. if (mode === 'top') return r2(cav.top - h / 2);
  586. if (mode === 'bottom') return r2(cav.floor + h / 2);
  587. return r2((cav.floor + cav.top) / 2);
  588. }
  589. /** 拖拽吸附:先按 step 取整;离内壁 < tol(1.5mm)时贴到「留 margin(0.5mm) 余量」处 */
  590. export function snapDrag(cav, s, x, z, step = 0.5, tol = 1.5, margin = 0.5) {
  591. const st = Math.max(0.05, +step || 0.5);
  592. let X = Math.round(x / st) * st, Z = Math.round(z / st) * st;
  593. const [w, d] = primDims(s);
  594. if (cav.kind === 'cyl') {
  595. const r = Math.hypot(X, Z), lim = cav.r - Math.max(w, d) / 2 - margin;
  596. if (r > 0.01 && lim > 0 && Math.abs(r - lim) < tol) { X = (X / r) * lim; Z = (Z / r) * lim; }
  597. } else {
  598. const lx = cav.halfX - w / 2 - margin, lz = cav.halfZ - d / 2 - margin;
  599. if (lx > 0 && Math.abs(Math.abs(X) - lx) < tol) X = Math.sign(X || 1) * lx;
  600. if (lz > 0 && Math.abs(Math.abs(Z) - lz) < tol) Z = Math.sign(Z || 1) * lz;
  601. }
  602. return { x: r2(X), z: r2(Z) };
  603. }
  604. /** 新建结构件:默认尺寸 + 落在内腔底 */
  605. export function newSpec(type, cav, patch = {}) {
  606. const base = (PRIMS[type] || PRIMS.box).d;
  607. const s = { uid: 1, type, x: 0, z: 0, y: 0, rot: 0, draft: 1, snap: 0.5, note: '', ...base, ...patch };
  608. if (cav) s.y = snapY(cav, s, 'bottom');
  609. return s;
  610. }
  611. /* =========================================================
  612. 工艺规则(五套)
  613. ========================================================= */
  614. export const RULES = {
  615. injection: { name: '注塑(ABS/PC)', minWall: 0.8, minRib: 0.8, draft: 1,
  616. items: [['最小壁厚', '0.8 mm,薄壁区建议 1.0'], ['拔模角', '≥1°,外观面 ≥2°'], ['内角圆角', 'R ≥ 0.5'], ['筋厚', '≥0.8 且 ≤ 主壁厚 0.8 倍'], ['深宽比', '≤ 3:1'], ['缩水', '0.4%~0.6%']] },
  617. silicone: { name: '硅胶模压', minWall: 1.2, minRib: 1.0, draft: 3,
  618. items: [['壁厚', '1.5~3.0 mm'], ['脱模角', '≥3°,双角根部 ≥5°'], ['圆角', 'R ≥ 0.5'], ['硬度', '30~70 Shore A'], ['最小批次', '500 套']] },
  619. cnc: { name: 'CNC 铝 6061', minWall: 1.0, minRib: 1.0, draft: 0,
  620. items: [['最小刀具', 'Ø2,内角 R≥1'], ['最小壁厚', '1.0 mm'], ['深腔', '≤ 4× 刀径'], ['公差', '±0.05 关键 / ±0.1 一般'], ['螺纹', '阳极后二次回攻']] },
  621. vac: { name: '真空复模', minWall: 1.2, minRib: 1.0, draft: 1.5,
  622. items: [['壁厚', '≥1.2 mm'], ['收缩补偿', '0.3%'], ['批量', '10 套起']] },
  623. die: { name: '压铸铝', minWall: 1.5, minRib: 1.2, draft: 1.5,
  624. items: [['壁厚', '≥1.5 mm'], ['拔模', '≥1.5°'], ['模具费', '¥12,000 起'], ['MOQ', '1000 套']] },
  625. };
  626. export const RULE_KEYS = { injection: '注塑', silicone: '硅胶', cnc: 'CNC', vac: '复模', die: '压铸' };
  627. /** 工艺选项:优先用产品 processParams / processes 的键,保证每个产品都有五套规则可选 */
  628. export function procOptions(product) {
  629. const keys = Object.keys(product?.processParams || {});
  630. const procs = product?.processes || [];
  631. const opts = [];
  632. for (const k of ['injection', 'cnc', 'silicone', 'diecast', 'vacuum']) {
  633. if (keys.length && !keys.includes(k) && !(k === 'diecast' && keys.includes('die'))) continue;
  634. const pr = procs.find((x) => x.id === k) || (k === 'diecast' ? procs.find((x) => /压铸/.test(x.name || '')) : null);
  635. opts.push({ key: k, label: RULE_KEYS[ruleKey(k, product)], rule: ruleKey(k, product), name: pr ? pr.name : RULE_KEYS[ruleKey(k, product)] });
  636. }
  637. // 至少给出五个规则里的四类
  638. const have = new Set(opts.map((o) => o.rule));
  639. for (const [k, id] of [['injection', 'injection'], ['cnc', 'cnc'], ['silicone', 'silicone'], ['vacuum', 'vac'], ['diecast', 'die']]) {
  640. if (!have.has(id)) { opts.push({ key: k, label: RULE_KEYS[id], rule: id, name: RULE_KEYS[id] }); have.add(id); }
  641. }
  642. return opts;
  643. }
  644. /** 工艺 id → 规则键 */
  645. export function ruleKey(procId, product) {
  646. const id = String(procId || '').toLowerCase();
  647. const pr = (product?.processes || []).find((x) => x.id === procId || x.key === procId);
  648. const name = `${id} ${pr?.name || ''} ${(product?.craftTags || []).join(' ')}`;
  649. if (/硅胶|silicone|vulcanize|sil-|bond/.test(name)) return 'silicone';
  650. if (/压铸|diecast|die-cast|\bdie\b/.test(name)) return 'die';
  651. if (/复模|vacuum|\bvac\b/.test(name)) return 'vac';
  652. if (/cnc|阳极|五轴|车铣|polish|sandblast|车削/.test(name)) return 'cnc';
  653. return 'injection';
  654. }
  655. /** 工艺弧面默认值(随规则),用于圆件 / 表壳 */
  656. export function procArcDefaults(rk) {
  657. if (rk === 'silicone') return { crownR: 1.2, recessR: 0.8, chamferC: 0.8 };
  658. if (rk === 'die') return { crownR: 1.0, recessR: 0.6, chamferC: 0.6 };
  659. if (rk === 'vac') return { crownR: 1.0, recessR: 0.5, chamferC: 0.5 };
  660. if (rk === 'cnc') return { crownR: 0.8, recessR: 0.5, chamferC: 0.5 };
  661. return { crownR: 0.6, recessR: 0.4, chamferC: 0.4 };
  662. }
  663. /** 有效壁厚(圆件按外径 − 内腔推算;与 cavity() 同源) */
  664. export function effWall(shapeType, p) {
  665. if (shapeType === 'round' || shapeType === 'ring') return r2(num(p.dTop) / 2 - cavity(shapeType, p).r);
  666. return r2(num(p.wall));
  667. }
  668. /**
  669. * 五套规则下的模型校验 → [{ ok, t, field?, partId?, rule? }]。
  670. * field 指向主体参数(点击定位到滑块),partId 指向结构件。
  671. */
  672. export function modelChecks(product, p, list, rk, arc = {}) {
  673. const out = [];
  674. const rule = RULES[rk] || RULES.injection;
  675. const type = product?.shape?.type;
  676. const cav = cavity(type, p);
  677. const ew = effWall(type, p);
  678. if (ew < rule.minWall - 0.001) out.push({ ok: false, field: 'wall', t: `主壁厚 ${ew} mm 低于${rule.name}下限 ${rule.minWall} mm` });
  679. else out.push({ ok: true, field: 'wall', t: `主壁厚 ${ew} mm ≥ ${rule.minWall} mm(${rule.name})` });
  680. const draft = num(p.draft);
  681. if (rule.draft > 0) {
  682. if (draft + 1e-6 < rule.draft) out.push({ ok: false, field: 'draft', t: `拔模角 ${r2(draft)}° < ${rule.draft}°(${rule.name}易粘模)` });
  683. else out.push({ ok: true, field: 'draft', t: `拔模角 ${r2(draft)}° ≥ ${rule.draft}°` });
  684. }
  685. if (type === 'round' || type === 'ring' || type === 'watch') {
  686. const crown = +arc.crownR || 0;
  687. if (crown > 0 && crown < 0.4) out.push({ ok: false, field: 'crownR', arc: true, t: `顶部凸圆 R${r2(crown)} 小于工艺最小 0.4` });
  688. if (rk === 'cnc' && (+arc.recessR || 0) < 0.4) out.push({ ok: false, field: 'recessR', arc: true, t: `屏边凹圆 R${r2(arc.recessR)} 小于球头刀最小 0.4` });
  689. if (type !== 'watch') {
  690. const cut = (num(p.dTop) - num(p.screenD)) / 2;
  691. if (cut < ew + crown + (rule.draft > 0 ? 0.2 : 0)) out.push({ ok: false, field: 'screenD', t: `屏径 Ø${r2(p.screenD)} 过大:屏到外壁只剩 ${r2(cut)} mm,放不下壁厚 + 凸圆 R` });
  692. }
  693. }
  694. const deep = num(p.height) - cav.top;
  695. if (deep > 0 && type !== 'round') out.push({ ok: true, t: `顶壁 ${r2(deep)} mm(顶面圆角过渡)` });
  696. if (!list.length) out.push({ ok: true, t: '尚无自定义结构件:当前为参数化主体' });
  697. for (const s of list) {
  698. const nm = (PRIMS[s.type] || { n: s.type }).n;
  699. const [w, d] = primDims(s);
  700. const thin = Math.min(w, d);
  701. const clr = clearanceTo(cav, s);
  702. const id = 'c' + s.uid;
  703. if ((s.type === 'rib' || s.type === 'wall' || s.type === 'box') && thin < rule.minRib)
  704. out.push({ ok: false, partId: id, t: `${nm} 厚 ${r2(thin)} mm < ${rule.name} 最小 ${rule.minRib} mm` });
  705. if (clr < 1.0) out.push({ ok: false, partId: id, t: `${nm} 距内壁/底/顶只剩 ${r2(clr)} mm(<1 mm,装配与脱模都会出问题)` });
  706. else out.push({ ok: true, partId: id, t: `${nm} 距内壁 ${r2(clr)} mm,余量可用` });
  707. if (rule.draft > 0 && (s.type === 'rib' || s.type === 'wall') && num(s.draft) < rule.draft)
  708. out.push({ ok: false, partId: id, field: 'draft', t: `${nm} 拔模 ${r2(s.draft)}° < ${rule.draft}°(${rule.name}易粘模)` });
  709. if (['boss2', 'boss25', 'boss3'].includes(s.type)) {
  710. const bw = (num(s.dia) - num(s.dd)) / 2, minW = rk === 'cnc' ? 0.9 : Math.max(0.9, rule.minRib * 0.9);
  711. if (bw < minW) out.push({ ok: false, partId: id, field: 'dia', t: `${nm} 柱壁 ${r2(bw)} mm < ${r2(minW)} mm,自攻牙会胀裂` });
  712. const std = STD_PILOT[s.type];
  713. if (Math.abs(num(s.dd) - std) > 0.15) out.push({ ok: false, partId: id, field: 'dd', t: `${nm} 预钻孔 Ø${r2(s.dd)} 非标准(该规格应为 Ø${std})` });
  714. }
  715. if (s.type === 'pad4') {
  716. const bw = (num(s.dia) - num(s.hd)) / 2;
  717. if (bw < 0.9) out.push({ ok: false, partId: id, field: 'dia', t: `${nm} 柱壁 ${r2(bw)} mm 偏薄(<0.9)` });
  718. 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` });
  719. }
  720. if ((s.type === 'pocket' || s.type === 'hole') && num(s.h) > thin * 2)
  721. out.push({ ok: false, partId: id, field: 'h', t: `${nm} 深宽比 ${r2(num(s.h) / Math.max(1, thin))}:1 > 2:1,需分层铣 / 镶件` });
  722. }
  723. return out;
  724. }
  725. /* =========================================================
  726. 派生尺寸 / 需求单 / BOM
  727. ========================================================= */
  728. const f2 = (v) => (num(v)).toFixed(2);
  729. const f1 = (v) => (num(v)).toFixed(1);
  730. export function derived(type, p, arc = {}) {
  731. const cav = cavity(type, p);
  732. const density = type === 'ring' ? 4.5 : type === 'round' ? 2.7 : 1.05;
  733. if (type === 'round') {
  734. const vol = Math.PI * ((num(p.dTop) / 2) ** 2 - cav.r ** 2) * num(p.height);
  735. return [
  736. ['外形', `Ø${f2(p.dTop)} × ${f2(p.height)} mm`],
  737. ['内腔可用', `Ø${f1(cav.r * 2)} × H${f1(cav.top - cav.floor)} mm`],
  738. ['屏径 / 沉台', `Ø${f2(p.screenD)} · 沉台 ${f1(p.recessDepth)} mm`],
  739. ['工艺弧面', `顶部凸圆 R${f2(arc.crownR)} / 屏边凹圆 R${f2(arc.recessR)} / 底倒角 C${f1(arc.chamferC)}`],
  740. ['壳重估算', `${f1((vol / 1000) * density)} g(铝 2.7 g/cm³)`],
  741. ['屏占比', `${(num(p.screenD) / Math.max(1, num(p.dTop)) * 100).toFixed(0)}%`],
  742. ];
  743. }
  744. if (type === 'ring') {
  745. return [
  746. ['内径 / 截面', `Ø${f1(p.ringD)} / ${f1(p.ringBandW)} × ${f1(p.height)} mm`],
  747. ['外径', `Ø${f1(num(p.ringD) + 2 * num(p.ringBandW))} mm`],
  748. ['壁厚', `${f2(effWall(type, p))} mm`],
  749. ['工艺弧面', `顶部凸圆 R${f2(arc.crownR)} / 底倒角 C${f1(arc.chamferC)}`],
  750. ];
  751. }
  752. if (type === 'watch') {
  753. 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);
  754. return [
  755. ['外形', `${f1(p.dTop)} × ${f1(p.length)} × ${f1(p.height)} mm`],
  756. ['内腔可用', `${f1(cav.halfX * 2)} × ${f1(cav.halfZ * 2)} mm`],
  757. ['壁厚 / 角 R', `${f2(p.wall)} / R${f1(p.cornerR)}`],
  758. ['壳重估算', `${f1((vol / 1000) * 1.15)} g(硅胶 1.15 g/cm³)`],
  759. ];
  760. }
  761. 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;
  762. return [
  763. ['外形', `${f1(p.length)} × ${f1(p.dTop)} × ${f1(p.height)} mm`],
  764. ['内腔可用', `${f1(cav.halfX * 2)} × ${f1(cav.halfZ * 2)} × H${f1(cav.top - cav.floor)} mm`],
  765. ['屏视窗', `${f1(p.screenD)} × ${f1(p.screenH)} mm · 沉台 ${f1(p.recessDepth)}`],
  766. ['角 R / 顶圆角', `R${f1(p.cornerR)} / R${f1(p.capR)}`],
  767. ['壳重估算', `${f1((vol / 1000) * 1.05)} g(ABS 1.05 g/cm³)`],
  768. ];
  769. }
  770. export function primDimText(s) {
  771. if (CYL_TYPES.includes(s.type)) return `Ø${f2(s.dia)} × H${f2(s.h)}`;
  772. if (s.type === 'pad4') return `${f1(s.w)} × ${f1(s.dd)} · 柱 Ø${f2(s.dia)}`;
  773. return `${f2(s.w)} × ${f2(s.dd)} × H${f2(s.h)}`;
  774. }
  775. export function primRequirement(s, rk) {
  776. const t = s.type;
  777. const m = { boss2: 'M2', boss25: 'M2.5', boss3: 'M3' }[t];
  778. if (t === 'rib' || t === 'wall') return `拔模 ${f1(s.draft)}°,厚 ${f2(s.dd)} mm,根部 R0.5`;
  779. if (m) return `${m} 自攻牙:预钻 Ø${f2(s.dd)},柱径 Ø${f2(s.dia)},同轴度 ≤0.05${rk === 'cnc' ? ',建议嵌铜螺母' : ''}`;
  780. if (t === 'thru25') return `Ø${f2(s.dia)} 过孔(M2.5),位置度 ±0.05`;
  781. if (t === 'pin3') return `Ø${f2(s.dia)} 定位销,H7 配合`;
  782. if (t === 'pad4') return `四角柱:中心距 ${f1(s.w)}×${f1(s.dd)},预钻 Ø${f2(s.hd)},与 PCB 孔位同轴 ±0.05`;
  783. if (t === 'pocket') return `铣削凹槽 ${f1(s.w)}×${f1(s.dd)},内角 R≥1,深 ${f2(s.h)}`;
  784. if (t === 'hole') return `钻孔 Ø${f2(s.dia)},位置度 ±0.05`;
  785. if (t === 'tray') return '电池仓:壁厚 0.8~1.2,底部 R0.5,留极耳缺口';
  786. if (t === 'clip') return '卡扣:根部 R0.4,扣合量 0.3~0.5,试插 50 次不疲劳';
  787. return '与主体同材质,去刀纹';
  788. }
  789. const PARAM_LABEL = {
  790. dTop: '顶部外径 / 宽', dBottom: '底部外径', height: '总高 / 厚', wall: '壁厚', domeR: '顶部凸圆 R', platform: '顶部平台',
  791. recessR: '屏边凹圆 R', recessDepth: '沉台深度', screenD: '屏 / 沉台直径', screenH: '屏高', chamferC: '底边倒角 C', draft: '拔模角',
  792. cornerR: '水平角 R', length: '长度', capR: '长边圆角 R', ringD: '内径', ringBandW: '截面宽', split: '拼色分割', bandD: '表带连接宽',
  793. };
  794. export { PARAM_LABEL };
  795. /** 生产需求单(Markdown) */
  796. export function specMarkdown({ product, params, arc, customs, qty, rk, checks }) {
  797. const p = product;
  798. const rule = RULES[rk] || RULES.injection;
  799. const L = [];
  800. const date = new Date().toISOString().slice(0, 10);
  801. L.push(`# 生产需求单 · ${p.name}`, '');
  802. L.push(`- 型号:${p.latin || p.name}(${p.id})`);
  803. L.push(`- 日期:${date};单位 mm;数量 ${qty} 套;币种 CNY`);
  804. L.push('- 本单由 Pocket Hardware Lab 实验室按当前 3D 参数快照自动生成(FmodeCode)', '');
  805. L.push('## 1. 参数快照', '', '| 参数 | 键 | 数值 |', '| --- | --- | --- |');
  806. for (const [k, v] of Object.entries(params || {})) if (typeof v === 'number') L.push(`| ${PARAM_LABEL[k] || k} | ${k} | ${f2(v)} |`);
  807. L.push('', '派生尺寸:', ...derived(p.shape?.type, params || {}, arc || {}).map(([k, v]) => `- ${k}:${v}`), '');
  808. if (p.shape?.type === 'round' || p.shape?.type === 'ring' || p.shape?.type === 'watch') {
  809. L.push('> **CNC 弧面编程参数**:外壁顶部凸圆 R' + f2(arc?.crownR) + `,屏边凹圆弧 R${f2(arc?.recessR)}(沉台深 ${f2(params?.recessDepth)}),底边倒角 C${f2(arc?.chamferC)}。`);
  810. L.push('> 弧面用 R≥1 的球头 / 圆鼻刀连续走刀;过渡区允许刀纹,不允许接刀台阶;关键尺寸按 ±0.05 检验并出首件报告。', '');
  811. }
  812. L.push('## 2. 公差与验收', '', '| 部位 | 公差 |', '| --- | --- |');
  813. for (const pt of p.parts || []) if (pt.tolerance) L.push(`| ${pt.name} | ${pt.tolerance} |`);
  814. L.push('| 首件 | 三坐标 / 影像仪报告 + 实配照片 |', '| 抽检 | AQL 1.0 外观 / 0.65 关键尺寸 |', '');
  815. L.push('## 3. 装配顺序', '');
  816. (p.processes || []).forEach((pr, i) => L.push(`${i + 1}. **${pr.name}**:${pr.desc || pr.equipment || '—'}${pr.bulkDays ? `(批量 ${pr.bulkDays})` : ''}`));
  817. L.push('', '## 4. 自定义结构件坐标表(壳底中心为原点;X 右 / Y 上(高度)/ Z 前)', '');
  818. if (!(customs || []).length) L.push('- 暂无自定义结构件(按主体参数推定)。');
  819. else {
  820. L.push('| # | 类型 | x (mm) | y (mm) | z (mm) | 外形尺寸 | 绕 Y 转向 | 工艺要求 |', '| --- | --- | --- | --- | --- | --- | --- | --- |');
  821. (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)} |`));
  822. L.push('', '> 结构件已随主体写入 STL;CNC 报价请按「上表坐标 + 刀具半径」评估,注塑按壁厚 / 拔模评估。');
  823. }
  824. L.push('', `## 5. 工艺校验(${rule.name})`, '');
  825. for (const c of checks || []) L.push(`- [${c.ok ? 'x' : ' '}] ${c.ok ? '通过' : '待改'}:${c.t}`);
  826. L.push('', '## 6. 供应商报价回填表', '', '| 项目 | 供应商填写 |', '| --- | --- |');
  827. for (const x of ['模具费(含试模 / 改模)', '单品单价(含税 / 不含税)', '最小起订量 MOQ', '打样费及抵扣规则', '交期(打样 / 大货)', '模具归属', '包装方式与费用', '有效期']) L.push(`| ${x} | |`);
  828. L.push('', '---', '生产需求单由 Pocket Hardware Lab · FmodeCode 生成;价格口径见产品页,不构成报价承诺。');
  829. return L.join('\n');
  830. }
  831. export function bomCsv(product) {
  832. const rows = [['序号', '分组', '名称', '规格', '供应商', '单价', '数量', '小计']];
  833. 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]);
  834. rows.push(['', '', '合计', '', '', '', '', product.bom?.bomTotal ?? '']);
  835. return rows.map((r) => r.map((v) => `"${String(v ?? '').replace(/"/g, '""')}"`).join(',')).join('\n');
  836. }
  837. export function specJson({ product, params, arc, customs, qty, rk }) {
  838. return JSON.stringify({
  839. app: 'Pocket Hardware Lab', version: 'v3', generator: 'FmodeCode', exportedAt: new Date().toISOString(), unit: 'mm',
  840. product: { id: product.id, name: product.name, latin: product.latin, shape: product.shape?.type },
  841. rule: rk, qty, params, arc, customParts: customs || [], derived: derived(product.shape?.type, params, arc),
  842. bom: product.bom, processes: product.processes,
  843. }, null, 2);
  844. }
  845. /* =========================================================
  846. 工艺弧面 → 解码后的实体尺寸(3D 适配器直接读这些值)
  847. ========================================================= */
  848. /**
  849. * 圆件「工艺弧面」三参数(顶部凸圆 R / 屏边凹圆 R / 沉台深)+ 底边倒角 C,
  850. * 折成 roundProfile 能吃的形参:凸圆/凹圆/平台占壁厚预算,沉台按弧深加深。
  851. */
  852. export function arcApplied(profileParams, arc, rk) {
  853. const p = { ...profileParams };
  854. const wall = num(p.wall, 1.5);
  855. const D = num(p.dTop, 40);
  856. const crown = clamp(num(arc?.crownR, 0.8), 0.4, 4);
  857. const recess = clamp(num(arc?.recessR, 0.5), 0.2, Math.min(4, wall * 0.9));
  858. const cham = clamp(num(arc?.chamferC, 0.5), 0, 3);
  859. const dep = clamp(num(p.recessDepth, 1) + recess * 0.5, 0.3, Math.max(0.4, num(p.height) * 0.5));
  860. // 圆角/倒角有工艺最小;注塑/硅胶 凸圆不能把壁厚吃光
  861. const budget = Math.max(0.6, D / 2 - num(p.screenD, D) / 2);
  862. const crownUse = Math.min(crown, Math.max(0.4, budget - recess - 0.1), wall * 0.9);
  863. p.domeR = r2(crownUse);
  864. p.recessR = r2(recess);
  865. p.platform = r2(Math.max(0.1, Math.min(num(p.platform, 0.3), budget - crownUse - recess - 0.05)));
  866. p.recessDepth = r2(dep);
  867. p.chamferC = r2(cham);
  868. if (rk === 'cnc') p.draft = num(p.draft, 1);
  869. return p;
  870. }