rect.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /**
  2. * core/geometry/rect.js —— 方件(rect)与戒指(ring)的包络与体积计算,纯函数零 DOM。
  3. * 3D 造型在 wc/ph-viewer3d.js 里用 Babylon 建;这里只负责「数学」,保证 Node 可测、与 3D 同源。
  4. */
  5. export function clamp(v, lo, hi) { return Math.max(lo, Math.min(hi, v)); }
  6. /** 圆角矩形面积(mm²) */
  7. export function roundedRectArea(l, w, r) {
  8. const rr = clamp(r, 0, Math.min(l, w) / 2);
  9. return l * w - (4 - Math.PI) * rr * rr;
  10. }
  11. /** 方件外形(拔模后底面积略小),hollow 时扣除壁厚一圈 */
  12. export function partsVolumeCm3(p) {
  13. const l = +p.l || 40, w = +p.w || 30, t = +p.t || 5, r = +p.cornerR || 0;
  14. const wall = +p.wall || 1.5;
  15. const draft = +p.draft || 0;
  16. const shrink = Math.tan((draft * Math.PI) / 180) * t * 0.5;
  17. const A0 = roundedRectArea(l, w, r);
  18. const A1 = roundedRectArea(Math.max(1, l - 2 * shrink), Math.max(1, w - 2 * shrink), Math.max(0, r - shrink));
  19. let v = ((A0 + A1) / 2) * t;
  20. if (p.hollow) {
  21. const li = l - 2 * wall, wi = w - 2 * wall;
  22. if (li > 0 && wi > 0) v -= roundedRectArea(li, wi, Math.max(0, r - wall)) * Math.max(0, t - 2 * wall);
  23. }
  24. return Math.max(0, v) / 1000;
  25. }
  26. /** 方件在 z 高度处截面半尺寸(线性拔模) */
  27. export function rectHalfAt(shape, z) {
  28. const d = shape.defaults || shape;
  29. const H = +d.height || 10;
  30. const draft = +d.draft || 0;
  31. const k = 1 - (Math.tan((draft * Math.PI) / 180) * (H - z)) / Math.max(+d.dTop || 40, 1);
  32. return { hx: ((+d.dTop || 40) / 2) * k, hy: ((+d.length || 60) / 2) * k };
  33. }
  34. /** 戒指(圆环)体积 cm³:平均周长 × 截面面积 */
  35. export function ringVolumeCm3(p) {
  36. const d = p.defaults || p;
  37. const rAvg = (+d.ringD + +d.ringBandW) / 2;
  38. const w = +d.ringBandW || 6.5;
  39. const h = +d.height || 6;
  40. const inner = (+d.wall || 1.2);
  41. const bandArea = w * h - Math.max(0, w - inner) * Math.max(0, h - inner);
  42. return (2 * Math.PI * rAvg * bandArea) / 1000;
  43. }
  44. /** 外形包络尺寸 {l, w, h}(rect → 宽/长/高;round → 直径/直径/高) */
  45. export function envelope(shape) {
  46. const d = shape.defaults || shape;
  47. if (shape.type === 'ring') return { l: +d.ringD + 2 * d.ringBandW, w: +d.ringD + 2 * d.ringBandW, h: +d.height };
  48. if (shape.type === 'rect') return { l: +d.dTop, w: +d.length, h: +d.height };
  49. return { l: +d.dTop, w: +d.dTop, h: +d.height };
  50. }