@adatechnology/game-destruction-three 0.29.3 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -742,18 +742,18 @@ function slerpInto(out, a, ai, b, bi, t) {
742
742
  let by = b[bi + 1];
743
743
  let bz = b[bi + 2];
744
744
  let bw = b[bi + 3];
745
- let dot2 = ax * bx + ay * by + az * bz + aw * bw;
746
- if (dot2 < 0) {
745
+ let dot3 = ax * bx + ay * by + az * bz + aw * bw;
746
+ if (dot3 < 0) {
747
747
  bx = -bx;
748
748
  by = -by;
749
749
  bz = -bz;
750
750
  bw = -bw;
751
- dot2 = -dot2;
751
+ dot3 = -dot3;
752
752
  }
753
753
  let from = 1 - t;
754
754
  let to = t;
755
- if (dot2 < 0.9995) {
756
- const angle = Math.acos(dot2);
755
+ if (dot3 < 0.9995) {
756
+ const angle = Math.acos(dot3);
757
757
  const sine = Math.sin(angle);
758
758
  from = Math.sin((1 - t) * angle) / sine;
759
759
  to = Math.sin(t * angle) / sine;
@@ -1590,10 +1590,26 @@ var squareBoxOf = (box) => {
1590
1590
  return { center: box.center, half };
1591
1591
  };
1592
1592
 
1593
+ // src/built-solids.ts
1594
+ var numbers = (value, count) => Array.isArray(value) && value.length === count && value.every((v) => typeof v === "number" && Number.isFinite(v));
1595
+ var isBuiltSolid = (value) => {
1596
+ if (typeof value !== "object" || value === null) return false;
1597
+ const solid = value;
1598
+ return numbers(solid.center, 3) && numbers(solid.half, 3) && numbers(solid.rotation, 4) && (solid.kind === void 0 || typeof solid.kind === "string");
1599
+ };
1600
+ var builtSolidsOf = (mesh) => {
1601
+ const list = mesh.userData.solids;
1602
+ if (!Array.isArray(list) || list.length === 0 || !list.every(isBuiltSolid)) return null;
1603
+ return list;
1604
+ };
1605
+ var ROUND_SIDES = 0.05;
1606
+ var isRoundSolid = (solid) => solid.kind === "cylinder" && Math.abs(solid.half[0] - solid.half[2]) <= ROUND_SIDES * Math.max(solid.half[0], solid.half[2]);
1607
+
1593
1608
  // src/static-part-job.ts
1594
1609
  import { fitOrientedBox, hugs } from "@adatechnology/game-shapes";
1595
1610
  var FIT = 0.01;
1596
1611
  var FILL = 0.5;
1612
+ var SOLID = 0.5;
1597
1613
  var MIN_HALF = 5e-3;
1598
1614
  var COLLAPSED = 2e-3;
1599
1615
  var MIN_FACE = 1e-6;
@@ -1630,10 +1646,11 @@ function measureStaticPart(job) {
1630
1646
  const size = [high[0] - low[0], high[1] - low[1], high[2] - low[2]];
1631
1647
  const s = [Math.abs(scale[0]), Math.abs(scale[1]), Math.abs(scale[2])];
1632
1648
  if (Math.max(size[0] * s[0], size[1] * s[1], size[2] * s[2]) < COLLAPSED) return [];
1649
+ if (job.solids && job.solids.length > 0) return job.solids.map((solid) => builtSolidIn(solid, pos, quat, scale));
1633
1650
  const centre = [(low[0] + high[0]) / 2, (low[1] + high[1]) / 2, (low[2] + high[2]) / 2];
1634
1651
  const half = [size[0] / 2, size[1] / 2, size[2] / 2];
1635
1652
  const straight = { center: centre, half, axes: IDENTITY, tolerance: [FIT / s[0], FIT / s[1], FIT / s[2]] };
1636
- if (hugs(points, straight) && fillsFaces(points, found, from, straight)) {
1653
+ if (hugs(points, straight) && fillsFaces(points, found, from, straight) && fillsVolume(points, found, from, straight)) {
1637
1654
  const [cx, cy, cz] = turn(centre[0] * scale[0], centre[1] * scale[1], centre[2] * scale[2], quat);
1638
1655
  return [{ center: [cx + pos[0], cy + pos[1], cz + pos[2]], half: [Math.max(MIN_HALF, half[0] * s[0]), Math.max(MIN_HALF, half[1] * s[1]), Math.max(MIN_HALF, half[2] * s[2])], rotation: [quat[0], quat[1], quat[2], quat[3]] }];
1639
1656
  }
@@ -1646,9 +1663,24 @@ function measureStaticPart(job) {
1646
1663
  world[i + 2] = e[2] * x + e[6] * y + e[10] * z + e[14];
1647
1664
  }
1648
1665
  const turned = fitOrientedBox(world);
1649
- if (turned && fitsTurned(world, turned) && fillsFaces(world, found, from, turnedBox(turned))) return [turned];
1666
+ if (turned && fitsTurned(world, turned) && fillsFaces(world, found, from, turnedBox(turned)) && fillsVolume(world, found, from, turnedBox(turned))) return [turned];
1650
1667
  return [trimeshOf(world, from, found)];
1651
1668
  }
1669
+ var builtSolidIn = (solid, pos, quat, scale) => {
1670
+ const [cx, cy, cz] = turn(solid.center[0] * scale[0], solid.center[1] * scale[1], solid.center[2] * scale[2], quat);
1671
+ const [ax, ay, az, aw] = quat;
1672
+ const [bx, by, bz, bw] = solid.rotation;
1673
+ const turned = Math.abs(bw) < 1 - 1e-9;
1674
+ const even = (Math.abs(scale[0]) + Math.abs(scale[1]) + Math.abs(scale[2])) / 3;
1675
+ const s = turned ? [even, even, even] : [Math.abs(scale[0]), Math.abs(scale[1]), Math.abs(scale[2])];
1676
+ return {
1677
+ ...isRoundSolid(solid) && Math.abs(s[0] - s[2]) <= 1e-9 ? { round: true } : {},
1678
+ center: [cx + pos[0], cy + pos[1], cz + pos[2]],
1679
+ half: [Math.max(MIN_HALF, solid.half[0] * s[0]), Math.max(MIN_HALF, solid.half[1] * s[1]), Math.max(MIN_HALF, solid.half[2] * s[2])],
1680
+ // the mesh's turn, then the solid's own
1681
+ rotation: [aw * bx + ax * bw + ay * bz - az * by, aw * by - ax * bz + ay * bw + az * bx, aw * bz + ax * by - ay * bx + az * bw, aw * bw - ax * bx - ay * by - az * bz]
1682
+ };
1683
+ };
1652
1684
  var staticSolidsTransfer = (solids) => {
1653
1685
  const out = [];
1654
1686
  for (const solid of solids) if (solid.mesh) out.push(solid.mesh.vertices.buffer, solid.mesh.indices.buffer);
@@ -1687,6 +1719,21 @@ var fillsFaces = (points, found, from, box) => {
1687
1719
  }
1688
1720
  return true;
1689
1721
  };
1722
+ var fillsVolume = (points, found, from, box) => {
1723
+ if (found.length === 0) return true;
1724
+ const whole = 8 * box.half[0] * box.half[1] * box.half[2];
1725
+ if (!(whole > 0)) return true;
1726
+ const [cx, cy, cz] = box.center;
1727
+ let six = 0;
1728
+ for (let i = 0; i + 2 < found.length; i += 3) {
1729
+ const a = (found[i] - from) * 3, b = (found[i + 1] - from) * 3, c = (found[i + 2] - from) * 3;
1730
+ const ax = points[a] - cx, ay = points[a + 1] - cy, az = points[a + 2] - cz;
1731
+ const bx = points[b] - cx, by = points[b + 1] - cy, bz = points[b + 2] - cz;
1732
+ const dx = points[c] - cx, dy = points[c + 1] - cy, dz = points[c + 2] - cz;
1733
+ six += ax * (by * dz - bz * dy) + ay * (bz * dx - bx * dz) + az * (bx * dy - by * dx);
1734
+ }
1735
+ return Math.abs(six) / 6 >= whole * SOLID;
1736
+ };
1690
1737
  var trimeshOf = (world, from, found) => {
1691
1738
  const indices = new Uint32Array(found.length);
1692
1739
  for (let i = 0; i < found.length; i++) indices[i] = found[i] - from;
@@ -2632,6 +2679,7 @@ var jobOf = (THREE, mv, points, matrix, local) => {
2632
2679
  const quat = new THREE.Quaternion();
2633
2680
  const scale = new THREE.Vector3();
2634
2681
  mv.mesh.matrixWorld.decompose(pos, quat, scale);
2682
+ const built = mv.range ? null : builtSolidsOf(mv.mesh);
2635
2683
  return {
2636
2684
  points,
2637
2685
  matrix: Float64Array.from(matrix),
@@ -2639,7 +2687,9 @@ var jobOf = (THREE, mv, points, matrix, local) => {
2639
2687
  quaternion: [quat.x, quat.y, quat.z, quat.w],
2640
2688
  scale: [scale.x, scale.y, scale.z],
2641
2689
  found: Uint32Array.from(trianglesOfPart(mv, local)),
2642
- from: local.from
2690
+ from: local.from,
2691
+ // a mesh of its own that says what it was built from is held by that (a part of a merged mesh is only some of its mesh)
2692
+ ...built ? { solids: built } : {}
2643
2693
  };
2644
2694
  };
2645
2695
  var trianglesOfRanges = (mv, ranges) => {
@@ -2683,41 +2733,99 @@ var trianglesOfPart = (mv, local) => mv.host ? trianglesOfRanges(mv, mv.host.sha
2683
2733
  var BOX_VERTICES = 24;
2684
2734
  var MAX_BOXES = 16;
2685
2735
  var CORNER = 1e-4;
2686
- var HOLLOW = 0.5;
2687
- var hollowBoxesOf = (points) => {
2736
+ var RANGED = { share: 0.5, turned: false };
2737
+ var OWN_MESH = { share: 0.8, turned: true };
2738
+ var dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
2739
+ var quaternionOf = (x, y, z) => {
2740
+ const [m00, m10, m20] = x;
2741
+ const [m01, m11, m21] = y;
2742
+ const [m02, m12, m22] = z;
2743
+ const trace = m00 + m11 + m22;
2744
+ if (trace > 0) {
2745
+ const s2 = 0.5 / Math.sqrt(trace + 1);
2746
+ return [(m21 - m12) * s2, (m02 - m20) * s2, (m10 - m01) * s2, 0.25 / s2];
2747
+ }
2748
+ if (m00 > m11 && m00 > m22) {
2749
+ const s2 = 2 * Math.sqrt(1 + m00 - m11 - m22);
2750
+ return [0.25 * s2, (m01 + m10) / s2, (m02 + m20) / s2, (m21 - m12) / s2];
2751
+ }
2752
+ if (m11 > m22) {
2753
+ const s2 = 2 * Math.sqrt(1 + m11 - m00 - m22);
2754
+ return [(m01 + m10) / s2, 0.25 * s2, (m12 + m21) / s2, (m02 - m20) / s2];
2755
+ }
2756
+ const s = 2 * Math.sqrt(1 + m22 - m00 - m11);
2757
+ return [(m02 + m20) / s, (m12 + m21) / s, 0.25 * s, (m10 - m01) / s];
2758
+ };
2759
+ var straightBoxOf = (points, first) => {
2760
+ const low = [Infinity, Infinity, Infinity];
2761
+ const high = [-Infinity, -Infinity, -Infinity];
2762
+ for (let v = first; v < first + BOX_VERTICES; v++) {
2763
+ for (let k = 0; k < 3; k++) {
2764
+ low[k] = Math.min(low[k], points[v * 3 + k]);
2765
+ high[k] = Math.max(high[k], points[v * 3 + k]);
2766
+ }
2767
+ }
2768
+ const corners = /* @__PURE__ */ new Set();
2769
+ for (let v = first; v < first + BOX_VERTICES; v++) {
2770
+ let corner = 0;
2771
+ for (let k = 0; k < 3; k++) {
2772
+ const x = points[v * 3 + k];
2773
+ if (Math.abs(x - high[k]) <= CORNER) corner |= 1 << k;
2774
+ else if (Math.abs(x - low[k]) > CORNER) return null;
2775
+ }
2776
+ corners.add(corner);
2777
+ }
2778
+ if (corners.size !== 8) return null;
2779
+ return { center: [(low[0] + high[0]) / 2, (low[1] + high[1]) / 2, (low[2] + high[2]) / 2], half: [(high[0] - low[0]) / 2, (high[1] - low[1]) / 2, (high[2] - low[2]) / 2] };
2780
+ };
2781
+ var turnedBoxOf = (points, first) => {
2782
+ const corners = [];
2783
+ for (let v = first; v < first + BOX_VERTICES; v++) {
2784
+ const p = [points[v * 3], points[v * 3 + 1], points[v * 3 + 2]];
2785
+ if (!corners.some((c) => Math.abs(c[0] - p[0]) <= CORNER && Math.abs(c[1] - p[1]) <= CORNER && Math.abs(c[2] - p[2]) <= CORNER)) corners.push(p);
2786
+ }
2787
+ if (corners.length !== 8) return null;
2788
+ const origin = corners[0];
2789
+ const edges = corners.slice(1).map((c) => [c[0] - origin[0], c[1] - origin[1], c[2] - origin[2]]);
2790
+ const lengths = edges.map((e) => Math.hypot(e[0], e[1], e[2]));
2791
+ const square = (i, j) => Math.abs(dot(edges[i], edges[j])) <= CORNER * (lengths[i] + lengths[j] + 1);
2792
+ for (let i = 0; i < 7; i++) for (let j = i + 1; j < 7; j++) for (let k = j + 1; k < 7; k++) {
2793
+ if (!square(i, j) || !square(i, k) || !square(j, k)) continue;
2794
+ const [a, b, c] = [edges[i], edges[j], edges[k]];
2795
+ const sums = [[0, 0, 0], a, b, c, [a[0] + b[0], a[1] + b[1], a[2] + b[2]], [a[0] + c[0], a[1] + c[1], a[2] + c[2]], [b[0] + c[0], b[1] + c[1], b[2] + c[2]], [a[0] + b[0] + c[0], a[1] + b[1] + c[1], a[2] + b[2] + c[2]]];
2796
+ const found = sums.every((s) => corners.some((p) => Math.abs(p[0] - origin[0] - s[0]) <= 4 * CORNER && Math.abs(p[1] - origin[1] - s[1]) <= 4 * CORNER && Math.abs(p[2] - origin[2] - s[2]) <= 4 * CORNER));
2797
+ if (!found) continue;
2798
+ const [la, lb, lc] = [lengths[i], lengths[j], lengths[k]];
2799
+ if (la <= 0 || lb <= 0 || lc <= 0) return null;
2800
+ const x = [a[0] / la, a[1] / la, a[2] / la];
2801
+ const y = [b[0] / lb, b[1] / lb, b[2] / lb];
2802
+ let z = [c[0] / lc, c[1] / lc, c[2] / lc];
2803
+ const cross2 = [x[1] * y[2] - x[2] * y[1], x[2] * y[0] - x[0] * y[2], x[0] * y[1] - x[1] * y[0]];
2804
+ if (dot(cross2, z) < 0) z = [-z[0], -z[1], -z[2]];
2805
+ const far2 = sums[7];
2806
+ return { center: [origin[0] + far2[0] / 2, origin[1] + far2[1] / 2, origin[2] + far2[2] / 2], half: [la / 2, lb / 2, lc / 2], rotation: quaternionOf(x, y, z) };
2807
+ }
2808
+ return null;
2809
+ };
2810
+ var hollowBoxesOf = (points, rule = RANGED) => {
2688
2811
  const count = points.length / 3;
2689
- if (count % BOX_VERTICES !== 0 || count / BOX_VERTICES < 2 || count / BOX_VERTICES > MAX_BOXES) return null;
2812
+ if (count % BOX_VERTICES !== 0 || count / BOX_VERTICES < (rule.turned ? 1 : 2) || count / BOX_VERTICES > MAX_BOXES) return null;
2690
2813
  const boxes = [];
2691
- const all = { low: [Infinity, Infinity, Infinity], high: [-Infinity, -Infinity, -Infinity] };
2814
+ const low = [Infinity, Infinity, Infinity];
2815
+ const high = [-Infinity, -Infinity, -Infinity];
2692
2816
  for (let first = 0; first < count; first += BOX_VERTICES) {
2693
- const low = [Infinity, Infinity, Infinity];
2694
- const high = [-Infinity, -Infinity, -Infinity];
2695
- for (let v = first; v < first + BOX_VERTICES; v++) {
2696
- for (let k = 0; k < 3; k++) {
2697
- low[k] = Math.min(low[k], points[v * 3 + k]);
2698
- high[k] = Math.max(high[k], points[v * 3 + k]);
2699
- }
2700
- }
2701
- const corners = /* @__PURE__ */ new Set();
2702
- for (let v = first; v < first + BOX_VERTICES; v++) {
2703
- let corner = 0;
2704
- for (let k = 0; k < 3; k++) {
2705
- const x = points[v * 3 + k];
2706
- if (Math.abs(x - high[k]) <= CORNER) corner |= 1 << k;
2707
- else if (Math.abs(x - low[k]) > CORNER) return null;
2708
- }
2709
- corners.add(corner);
2710
- }
2711
- if (corners.size !== 8) return null;
2817
+ const box = straightBoxOf(points, first) ?? (rule.turned ? turnedBoxOf(points, first) : null);
2818
+ if (!box) return null;
2819
+ boxes.push(box);
2820
+ }
2821
+ for (let i = 0; i < points.length; i += 3) {
2712
2822
  for (let k = 0; k < 3; k++) {
2713
- all.low[k] = Math.min(all.low[k], low[k]);
2714
- all.high[k] = Math.max(all.high[k], high[k]);
2823
+ low[k] = Math.min(low[k], points[i + k]);
2824
+ high[k] = Math.max(high[k], points[i + k]);
2715
2825
  }
2716
- boxes.push({ low, high });
2717
2826
  }
2718
- const volume = (low, high) => (high[0] - low[0]) * (high[1] - low[1]) * (high[2] - low[2]);
2719
- const filled = boxes.reduce((sum, box) => sum + volume(box.low, box.high), 0);
2720
- return filled < HOLLOW * volume(all.low, all.high) ? boxes : null;
2827
+ const filled = boxes.reduce((sum, box) => sum + 8 * box.half[0] * box.half[1] * box.half[2], 0);
2828
+ return filled < rule.share * (high[0] - low[0]) * (high[1] - low[1]) * (high[2] - low[2]) ? boxes : null;
2721
2829
  };
2722
2830
 
2723
2831
  // src/rigid-pose.ts
@@ -2772,7 +2880,11 @@ var orientedReach = (s) => {
2772
2880
  row(2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y))
2773
2881
  ];
2774
2882
  };
2775
- var shapeOf = (s) => s.mesh ? { kind: "trimesh", vertices: s.mesh.vertices, indices: s.mesh.indices } : { kind: "box", half: s.half };
2883
+ var shapeOf = (s) => {
2884
+ if (s.mesh) return { kind: "trimesh", vertices: s.mesh.vertices, indices: s.mesh.indices };
2885
+ if (s.round) return { kind: "cylinder", halfHeight: s.half[1], radius: (s.half[0] + s.half[2]) / 2 };
2886
+ return { kind: "box", half: s.half };
2887
+ };
2776
2888
  var EngineStatics = class {
2777
2889
  constructor(world, material) {
2778
2890
  __publicField(this, "world", world);
@@ -3018,30 +3130,30 @@ var GROUND_ROLLING_DAMPING = 0.3;
3018
3130
  var SEGMENT_BOX_ROUNDS = 4;
3019
3131
  var PARALLEL = 1e-4;
3020
3132
  var sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
3021
- var dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
3133
+ var dot2 = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
3022
3134
  var along = (a, d, t) => [a[0] + d[0] * t, a[1] + d[1] * t, a[2] + d[2] * t];
3023
3135
  var clamp01 = (t) => t < 0 ? 0 : t > 1 ? 1 : t;
3024
3136
  var nearestOnSegment = (from, to, p) => {
3025
3137
  const d = sub(to, from);
3026
- const len2 = dot(d, d);
3027
- return len2 < 1e-12 ? from : along(from, d, clamp01(dot(sub(p, from), d) / len2));
3138
+ const len2 = dot2(d, d);
3139
+ return len2 < 1e-12 ? from : along(from, d, clamp01(dot2(sub(p, from), d) / len2));
3028
3140
  };
3029
3141
  var nearestOfSegments = (p1, q1, p2, q2) => {
3030
3142
  const d1 = sub(q1, p1);
3031
3143
  const d2 = sub(q2, p2);
3032
3144
  const r = sub(p1, p2);
3033
- const a = dot(d1, d1);
3034
- const e = dot(d2, d2);
3035
- const f = dot(d2, r);
3145
+ const a = dot2(d1, d1);
3146
+ const e = dot2(d2, d2);
3147
+ const f = dot2(d2, r);
3036
3148
  let s = 0;
3037
3149
  let t = 0;
3038
3150
  if (a < 1e-12 && e < 1e-12) return [p1, p2];
3039
3151
  if (a < 1e-12) t = clamp01(f / e);
3040
3152
  else {
3041
- const c = dot(d1, r);
3153
+ const c = dot2(d1, r);
3042
3154
  if (e < 1e-12) s = clamp01(-c / a);
3043
3155
  else {
3044
- const b = dot(d1, d2);
3156
+ const b = dot2(d1, d2);
3045
3157
  const denom = a * e - b * b;
3046
3158
  if (denom > PARALLEL * a * e) s = clamp01((b * f - c * e) / denom);
3047
3159
  else {
@@ -3155,8 +3267,8 @@ var boxBox = (a, b) => {
3155
3267
  }
3156
3268
  const normal = [nx, ny, nz];
3157
3269
  const mid = [(a.c[0] + b.c[0]) / 2, (a.c[1] + b.c[1]) / 2, (a.c[2] + b.c[2]) / 2];
3158
- const middle = (dot(a.c, normal) - reachAlong2(a, nx, ny, nz) + dot(b.c, normal) + reachAlong2(b, nx, ny, nz)) / 2;
3159
- return { point: along(mid, normal, middle - dot(mid, normal)), normal, depth };
3270
+ const middle = (dot2(a.c, normal) - reachAlong2(a, nx, ny, nz) + dot2(b.c, normal) + reachAlong2(b, nx, ny, nz)) / 2;
3271
+ return { point: along(mid, normal, middle - dot2(mid, normal)), normal, depth };
3160
3272
  };
3161
3273
  var LEVEL_SHARE = 1e-3;
3162
3274
  var boxBoxAlongGround = (a, b) => {
@@ -3642,7 +3754,7 @@ var sameTurn = (a, b) => {
3642
3754
  return a.rotation.every((v, i) => Math.abs(v - b.rotation[i]) < FLUSH);
3643
3755
  };
3644
3756
  var flushAxis = (a, b) => {
3645
- if (!sameTurn(a, b)) return -1;
3757
+ if (a.round || b.round || a.hull || b.hull || !sameTurn(a, b)) return -1;
3646
3758
  let along2 = -1;
3647
3759
  for (let axis = 0; axis < 3; axis++) {
3648
3760
  const same2 = Math.abs(a.half[axis] - b.half[axis]) < FLUSH && Math.abs(a.center[axis] - b.center[axis]) < FLUSH;
@@ -3694,7 +3806,6 @@ var MU_STATIC = 0.7;
3694
3806
  var ROLLING_RESISTANCE = 0.015;
3695
3807
  var MU_DYNAMIC = 0.6;
3696
3808
  var GROUND = { frictionStatic: MU_STATIC, frictionDynamic: MU_DYNAMIC, restitution: 0, rolling: ROLLING_RESISTANCE };
3697
- var groundTileKey = (x, z) => (Math.floor(x / TILE) + TILE_KEY_ORIGIN) * TILE_KEY + (Math.floor(z / TILE) + TILE_KEY_ORIGIN);
3698
3809
  var tileRollingAt = (rollingAt, x, z) => rollingAt((Math.floor(x / TILE) + 0.5) * TILE, (Math.floor(z / TILE) + 0.5) * TILE);
3699
3810
  var STILL_SPEED = 0.12;
3700
3811
  var STILL_SPIN = 0.45;
@@ -4167,7 +4278,7 @@ var EnginePieces = class {
4167
4278
  return { kind: "compound", children: [{ shape: { kind: "cylinder", halfHeight: b.halfExtents[round.axis], radius: round.radius }, position: [0, 0, 0], rotation }] };
4168
4279
  }
4169
4280
  if (b.partBoxes && b.partBoxes.length > 0) {
4170
- return { kind: "compound", children: mergeFlushBoxes(b.partBoxes).map((part, i) => ({ shape: { kind: "box", half: part.half }, position: part.center, ...part.rotation ? { rotation: part.rotation } : {}, tag: i })) };
4281
+ return { kind: "compound", children: mergeFlushBoxes(b.partBoxes).map((part, i) => ({ shape: part.hull ? { kind: "convex", points: [...part.hull] } : part.round ? { kind: "cylinder", halfHeight: part.half[1], radius: (part.half[0] + part.half[2]) / 2 } : { kind: "box", half: part.half }, position: part.center, ...part.rotation ? { rotation: part.rotation } : {}, tag: i })) };
4171
4282
  }
4172
4283
  return { kind: "box", half: b.halfExtents };
4173
4284
  }
@@ -5114,9 +5225,8 @@ var PhysicsOptionError = class extends Error {
5114
5225
  }
5115
5226
  };
5116
5227
  var resolvePhysics = (option) => {
5117
- if (option === "own") return null;
5118
5228
  if (option === void 0 || typeof option !== "object") {
5119
- throw new PhysicsOptionError("the `physics` option is required: pass a PhysicsLoop, a world from the host, or 'own' for the kit's own solver");
5229
+ throw new PhysicsOptionError("the `physics` option is required: pass a PhysicsLoop or a world from the host");
5120
5230
  }
5121
5231
  if (isPhysicsLoop(option)) return { loop: option, stepsItself: false };
5122
5232
  if (typeof option.stepFixed !== "function") {
@@ -5166,44 +5276,20 @@ function isOverSupport(points, centre, tolerance) {
5166
5276
  }
5167
5277
 
5168
5278
  // src/pieces.ts
5169
- var SLAM_MIN_SPEED2 = 2;
5170
- var SLAM_BOUNCE2 = 0.2;
5171
5279
  var BALANCE_TOLERANCE = 0.01;
5172
- var SLAM_FLOOR_NORMAL2 = 0.7;
5173
- var SUB_DT = 1 / 120;
5174
5280
  var MU_STATIC2 = 0.7;
5175
5281
  var MU_DYNAMIC2 = 0.6;
5176
- var SLIP_SPEED = 0.02;
5177
5282
  var ROLLING_RESISTANCE2 = 0.015;
5178
- var ROUND_LYING = Math.SQRT1_2;
5179
5283
  var MIN_PIECE_HALF = 1e-3;
5180
- var OWN_MIN_PIECE_HALF = 0.01;
5181
- var OWN_MIN_MEASURED_HALF = 0.02;
5182
- var minPieceHalf = (physics) => physics === "own" ? OWN_MIN_MEASURED_HALF : MIN_PIECE_HALF;
5183
5284
  var SLEEP_AFTER = 0.5;
5184
5285
  var STILL_SPEED2 = 0.12;
5185
5286
  var STILL_SPIN2 = 0.45;
5186
- var CALM_DRIFT = 0.01;
5187
- var CALM_TURN = 0.05;
5188
- var CALM_SLEEP_AFTER = 1.5;
5189
- var STEADY_TURN2 = 0.1;
5190
5287
  var STEADY_SECONDS2 = 1.5;
5191
- var HARD_LANDING2 = 3;
5192
5288
  var SLOP = 2e-3;
5193
- var NARROW2 = 0.3;
5194
- var SUPPORT_MARGIN = 0.05;
5195
- var TOPPLE2 = 3;
5196
- var TIP_ACCELERATION = 30;
5197
- var TIP_RISING = 0.02;
5198
- var TIP_RISE_AFTER = 0.5;
5199
- var TIP_LYING = 0.25;
5200
5289
  var TIP_SECONDS = 3;
5201
5290
  var STEP = 0.03;
5202
5291
  var WAKE_SAMPLES = 4;
5203
5292
  var WAKE_DROP = 0.05;
5204
- var WARM_SLOTS = 8 + 12 * 7;
5205
- var SOLVER_PASSES = 10;
5206
- var SIDE_BOUNCE = 0.1;
5207
5293
  var EDGE_POINTS = [-0.75, -0.5, -0.25, 0, 0.25, 0.5, 0.75];
5208
5294
  var EDGE_SPACING = 0.05;
5209
5295
  var MAX_EDGE_POINTS = 31;
@@ -5220,15 +5306,9 @@ var STEEP_MARGIN = 1.1;
5220
5306
  var SLOPE_MIN_NORMAL = 0.5;
5221
5307
  var LIES_FLAT = 0.985;
5222
5308
  var KEEP_EVERY = 0.5;
5223
- var WAKE_ABOVE_SPEED = 0.05;
5224
- var WAKE_ABOVE_SPIN = 0.1;
5225
5309
  var SURFACE_CELL = 0.5;
5226
5310
  var SURFACE_CELLS_ACROSS = 24;
5227
5311
  var cellKey = (ix, iz) => (ix + 32768) * 65536 + (iz + 32768);
5228
- var MAX_COLLISION_STEPS = 8;
5229
- var MIN_ROUND_RADIUS = 5e-3;
5230
- var BOUNCE_MIN_SPEED = 0.1;
5231
- var BOX_IMPACT_SPEED = 1.5;
5232
5312
  var KNOCK_FLAT = 0.5;
5233
5313
  var SEPARATE_SPEED = 1.5;
5234
5314
  var LIFT_DEPTH = STEP;
@@ -5277,8 +5357,6 @@ var pairFriction = (a, b) => ({
5277
5357
  // both lose energy in the contact: a log on grass is held by its bark and by the blades
5278
5358
  rollingDamping: (a?.rollingDamping ?? PIECE_ROLLING_DAMPING) + (b?.rollingDamping ?? GROUND_ROLLING_DAMPING)
5279
5359
  });
5280
- var pairRestitution = (a, b) => Math.sqrt((a ?? SLAM_BOUNCE2) * (b ?? SLAM_BOUNCE2));
5281
- var turnBetween = (a, q) => 2 * Math.acos(Math.min(1, Math.abs(a[0] * q.x + a[1] * q.y + a[2] * q.z + a[3] * q.w)));
5282
5360
  var PieceSystem = class {
5283
5361
  constructor(THREE, o) {
5284
5362
  __publicField(this, "THREE", THREE);
@@ -5287,19 +5365,14 @@ var PieceSystem = class {
5287
5365
  __publicField(this, "time", 0);
5288
5366
  __publicField(this, "generations", 0);
5289
5367
  __publicField(this, "p");
5290
- __publicField(this, "q");
5291
5368
  __publicField(this, "dq");
5292
- __publicField(this, "nextQ");
5293
5369
  __publicField(this, "m");
5294
- __publicField(this, "hingeM");
5295
5370
  __publicField(this, "ax");
5296
5371
  __publicField(this, "wakeBox");
5297
5372
  __publicField(this, "solids", []);
5298
- /** The engine stepping the pieces (`PieceSystemOptions.physics`), or null for the kit's own solver. */
5373
+ /** The engine stepping the pieces (`PieceSystemOptions.physics`). */
5299
5374
  __publicField(this, "engine");
5300
- /** The host's ground worker, disposed with the system: by the engine, or here when there is none (the kit's own solver lays no tiles). */
5301
- __publicField(this, "groundWorker");
5302
- /** The loop the system steps itself (a world was handed), the loop it only registers on (a loop was handed), or null on `'own'`. */
5375
+ /** The loop the system steps itself (a world was handed) or only registers on (a loop was handed). */
5303
5376
  __publicField(this, "loop");
5304
5377
  __publicField(this, "stepsItself");
5305
5378
  /** The phases' way out of the loop, and whether this frame's `prepare` ran (it runs once, in the first fixed step). */
@@ -5349,12 +5422,8 @@ var PieceSystem = class {
5349
5422
  __publicField(this, "supportNormal", UP);
5350
5423
  __publicField(this, "supportFriction", null);
5351
5424
  __publicField(this, "supportBody", null);
5352
- /** The terrain's surfaces by rolling resistance and damping (`terrainSurface`), one object each. */
5353
- __publicField(this, "terrainSurfaces", /* @__PURE__ */ new Map());
5354
- /** The terrain's surface by ground tile (`groundTileKey`) this update, null for the default: read once per tile, not per contact per substep. */
5355
- __publicField(this, "surfaceByTile", /* @__PURE__ */ new Map());
5356
- /** A piece is asleep on both sides (the engine's too) or, on the kit's own solver, asleep and not held: nothing of it changes until it wakes. */
5357
- __publicField(this, "isSettled", (body) => this.engine ? this.engine.isSettled(body) : body.sleeping && !body.held);
5425
+ /** A piece is asleep on both sides (the engine's too): nothing of it changes until it wakes. */
5426
+ __publicField(this, "isSettled", (body) => this.engine.isSettled(body));
5358
5427
  __publicField(this, "measureAwake", (body) => {
5359
5428
  const rec = this.measured(body);
5360
5429
  const from = rec.from;
@@ -5378,18 +5447,15 @@ var PieceSystem = class {
5378
5447
  if (rec.from !== from || rec.list.length !== count || rec.list[0] !== first) this.reshaped = true;
5379
5448
  });
5380
5449
  this.p = new THREE.Vector3();
5381
- this.q = new THREE.Quaternion();
5382
5450
  this.dq = new THREE.Quaternion();
5383
- this.nextQ = new THREE.Quaternion();
5384
5451
  this.m = new THREE.Matrix4();
5385
- this.hingeM = new THREE.Matrix4();
5386
5452
  this.ax = new THREE.Vector3();
5387
5453
  this.wakeBox = new THREE.Box3();
5388
5454
  const resolved = resolvePhysics(o.physics);
5389
- this.loop = resolved?.loop ?? null;
5390
- this.stepsItself = resolved?.stepsItself ?? false;
5455
+ this.loop = resolved.loop;
5456
+ this.stepsItself = resolved.stepsItself;
5391
5457
  this.trail = o.interpolate ? new PoseTrail() : null;
5392
- this.engine = resolved ? new EnginePieces(THREE, resolved.loop.world, {
5458
+ this.engine = new EnginePieces(THREE, resolved.loop.world, {
5393
5459
  groundAt: o.terrainAt ?? o.groundAt,
5394
5460
  ...o.terrainRollingAt ? { groundRollingAt: o.terrainRollingAt } : {},
5395
5461
  ...o.terrainRollingDampingAt ? { groundRollingDampingAt: o.terrainRollingDampingAt } : {},
@@ -5409,13 +5475,12 @@ var PieceSystem = class {
5409
5475
  ...o.heldIgnores ? { heldIgnores: o.heldIgnores } : {},
5410
5476
  ...o.groundWorker ? { groundWorker: o.groundWorker } : {},
5411
5477
  ...o.groundWorkerFrames !== void 0 ? { groundWorkerFrames: o.groundWorkerFrames } : {}
5412
- }) : null;
5413
- this.groundWorker = o.groundWorker ?? null;
5414
- if (resolved && !resolved.stepsItself) this.joinLoop(resolved.loop, this.engine);
5478
+ });
5479
+ if (!resolved.stepsItself) this.joinLoop(resolved.loop, this.engine);
5415
5480
  }
5416
- /** Contact blows on the fixed parts become `blunt` hits of `destruction` (`engine-impacts.ts`); null when the pieces are not in the engine's loop. Returns the way to stop it. */
5481
+ /** Contact blows on the fixed parts become `blunt` hits of `destruction` (`engine-impacts.ts`). Returns the way to stop it. */
5417
5482
  contactHits(destruction, options) {
5418
- return this.engine && this.loop ? createEngineImpacts(this.loop, this.engine.statics, destruction, options) : null;
5483
+ return createEngineImpacts(this.loop, this.engine.statics, destruction, options);
5419
5484
  }
5420
5485
  /**
5421
5486
  * The pieces a blast at `point` can reach: the bodies the engine's `blastQuery` finds within `radius` (the pieces among them), in the order of `list`, and the pieces that have no
@@ -5423,7 +5488,6 @@ var PieceSystem = class {
5423
5488
  */
5424
5489
  piecesInBlast(blastQuery, point, radius) {
5425
5490
  const engine = this.engine;
5426
- if (!engine) return [...this.list];
5427
5491
  const found = blastQuery.run({ origin: point, radius });
5428
5492
  const reached = /* @__PURE__ */ new Set();
5429
5493
  for (let i = 0; i < found.bodyCount; i++) {
@@ -5432,9 +5496,9 @@ var PieceSystem = class {
5432
5496
  }
5433
5497
  return this.list.filter((piece) => reached.has(piece) || !engine.hasBody(piece));
5434
5498
  }
5435
- /** The engine's fixed bodies as the broad phase of the world's rays, or null when the pieces are not in the engine. */
5499
+ /** The engine's fixed bodies as the broad phase of the world's rays. */
5436
5500
  rayBroadPhase() {
5437
- return this.engine?.rayBroadPhase() ?? null;
5501
+ return this.engine.rayBroadPhase();
5438
5502
  }
5439
5503
  /**
5440
5504
  * The loop mode: the system's work goes into the loop's phases. `prepare` (sync, kinematic targets, the kit's rules that came before the step) runs in the first fixed step of
@@ -5484,8 +5548,7 @@ var PieceSystem = class {
5484
5548
  dispose() {
5485
5549
  this.trail?.clear();
5486
5550
  for (const leave of this.leaveLoop.splice(0)) leave();
5487
- if (this.engine) this.engine.dispose();
5488
- else this.groundWorker?.dispose();
5551
+ this.engine.dispose();
5489
5552
  }
5490
5553
  /**
5491
5554
  * Pairs born overlapping (both made in the same update, or one made inside the other) deeper than a contact (`LIFT_DEPTH`: chunks of one wall) go apart along the ground by
@@ -5596,7 +5659,7 @@ var PieceSystem = class {
5596
5659
  return existing;
5597
5660
  }
5598
5661
  const awake = this.awake;
5599
- const least = this.engine ? MIN_PIECE_HALF : OWN_MIN_PIECE_HALF;
5662
+ const least = MIN_PIECE_HALF;
5600
5663
  let asleep = false;
5601
5664
  let inHand = false;
5602
5665
  const body = {
@@ -5637,13 +5700,13 @@ var PieceSystem = class {
5637
5700
  this.bornAt.set(body, this.time);
5638
5701
  return body;
5639
5702
  }
5640
- /** What the loop's last frame cost (ms) and how many bodies the world had awake: the pair the cost of a body is read from. Null on the kit's own solver. */
5703
+ /** What the loop's last frame cost (ms) and how many bodies the world had awake: the pair the cost of a body is read from. */
5641
5704
  stepCost() {
5642
- return this.loop ? { stepMs: this.loop.frame.stepMs, active: this.loop.world.activeCount } : null;
5705
+ return { stepMs: this.loop.frame.stepMs, active: this.loop.world.activeCount };
5643
5706
  }
5644
- /** Bodies awake in the physics world, or the pieces not asleep on the kit's own solver. */
5707
+ /** Bodies awake in the physics world. */
5645
5708
  activeBodies() {
5646
- return this.loop ? this.loop.world.activeCount : this.list.filter((b) => !b.sleeping).length;
5709
+ return this.loop.world.activeCount;
5647
5710
  }
5648
5711
  /** Move the centre of mass (after a part broke off). */
5649
5712
  setCenter(b, c) {
@@ -5663,12 +5726,12 @@ var PieceSystem = class {
5663
5726
  }
5664
5727
  if (gone) {
5665
5728
  this.forgetSolids(gone);
5666
- this.engine?.remove(gone);
5729
+ this.engine.remove(gone);
5667
5730
  }
5668
5731
  }
5669
5732
  clear() {
5670
5733
  this.trail?.clear();
5671
- this.engine?.clear();
5734
+ this.engine.clear();
5672
5735
  this.list.length = 0;
5673
5736
  this.awake.clear();
5674
5737
  this.layoutDirty = true;
@@ -5782,29 +5845,13 @@ var PieceSystem = class {
5782
5845
  }
5783
5846
  return out;
5784
5847
  }
5785
- /**
5786
- * An impulse along the unit normal `n` at `r` (from the centre of mass, world) that stops the point closing in along `n` (with `bounce`); `e` holds the body's rotation.
5787
- */
5788
- contactImpulse(b, e, r, n, bounce) {
5789
- const v = b.velocity;
5790
- const w = b.angularVelocity;
5791
- const vn = (v[0] + w[1] * r[2] - w[2] * r[1]) * n[0] + (v[1] + w[2] * r[0] - w[0] * r[2]) * n[1] + (v[2] + w[0] * r[1] - w[1] * r[0]) * n[2];
5792
- if (vn >= 0) return;
5793
- const a = this.mulInvInertiaWith(b, e, r[1] * n[2] - r[2] * n[1], r[2] * n[0] - r[0] * n[2], r[0] * n[1] - r[1] * n[0]);
5794
- const k = (a[1] * r[2] - a[2] * r[1]) * n[0] + (a[2] * r[0] - a[0] * r[2]) * n[1] + (a[0] * r[1] - a[1] * r[0]) * n[2];
5795
- const j = -(1 + bounce) * vn / (1 / b.mass + k);
5796
- for (let i = 0; i < 3; i++) {
5797
- v[i] += j * n[i] / b.mass;
5798
- w[i] += a[i] * j;
5799
- }
5800
- }
5801
5848
  /** A blast at (x, z) of `radius`: the ground within its reach is laid at the next update, before the pieces it makes need it (`EnginePieces.layAhead`). */
5802
5849
  layGroundAt(x, z, radius) {
5803
- this.engine?.layAhead(x, z, radius);
5850
+ this.engine.layAhead(x, z, radius);
5804
5851
  }
5805
5852
  /** What lies inside the disc looks at the ground again: it was dug or heaped under it. */
5806
5853
  wakeRegion(x, z, radius) {
5807
- this.engine?.groundChanged(x, z, radius);
5854
+ this.engine.groundChanged(x, z, radius);
5808
5855
  for (const b of this.list) {
5809
5856
  if (!b.sleeping || b.held) continue;
5810
5857
  if (Math.hypot(b.root.position.x - x, b.root.position.z - z) > radius && !this.lostGroundIn(b, x, z, radius)) continue;
@@ -5847,7 +5894,7 @@ var PieceSystem = class {
5847
5894
  this.trail?.blend(alpha);
5848
5895
  }
5849
5896
  update(dt) {
5850
- if (this.trail && !(this.engine && this.loop && !this.stepsItself)) {
5897
+ if (this.trail && this.stepsItself) {
5851
5898
  this.beginTick();
5852
5899
  this.advance(dt);
5853
5900
  this.trail.commit();
@@ -5856,96 +5903,21 @@ var PieceSystem = class {
5856
5903
  this.advance(dt);
5857
5904
  }
5858
5905
  advance(dt) {
5859
- if (this.engine && this.loop) {
5860
- if (!this.stepsItself) {
5861
- this.time = this.loop.frame.time;
5862
- this.keepFar();
5863
- return;
5864
- }
5865
- this.time += dt;
5866
- this.engine.wakePending(this.list, this.awake);
5867
- this.measure();
5868
- this.wakeUnsupported(true);
5869
- if (dt > 0) {
5870
- this.engine.prepare(this.list, dt, dt, this.apartAll(dt), this.awake);
5871
- this.loop.step(dt);
5872
- this.engine.finish(this.list, dt, this.time, this.awake);
5873
- }
5874
- this.measure();
5875
- this.keepBudget();
5906
+ if (!this.stepsItself) {
5907
+ this.time = this.loop.frame.time;
5876
5908
  this.keepFar();
5877
5909
  return;
5878
5910
  }
5879
- const { steps, near: near2 } = this.collisionSteps(dt);
5880
- if (steps === 1) {
5881
- this.time += dt;
5882
- this.step(dt);
5883
- return;
5884
- }
5885
- const start = this.time;
5886
- this.time = start + dt;
5887
- const far2 = (b) => !near2.has(b);
5888
- this.step(dt, { moves: far2, meets: (a, b) => far2(a) && far2(b) });
5889
- for (let i = 0; i < steps; i++) {
5890
- this.time = start + dt * (i + 1) / steps;
5891
- this.step(dt / steps, { moves: (b) => near2.has(b), meets: (a, b) => near2.has(a) || near2.has(b) });
5892
- }
5893
- }
5894
- /**
5895
- * Steps of an update: one, or more while a round piece and a piece it could meet within the update close in fast enough to pass through each other between two (closing at
5896
- * their two speeds they cover at most the round one's radius per step: two cans at 3.6 m/s close 12 cm in a frame, a can is 7 cm across; a plank thrown at a can still counts).
5897
- * A round piece with nothing in reach takes one step, so its sweep against the world (the costly part) runs once; `near` holds the pieces of the pairs that need more.
5898
- */
5899
- collisionSteps(dt) {
5900
- let need = 1;
5901
- const near2 = /* @__PURE__ */ new Set();
5902
- const p = this.p;
5903
- const speedOf = (b) => b.held ? 0 : Math.hypot(b.velocity[0], b.velocity[1], b.velocity[2]);
5904
- for (const b of this.list) {
5905
- if (!b.round || b.held) continue;
5906
- const radius = Math.max(MIN_ROUND_RADIUS, b.round.radius);
5907
- const speed = b.sleeping ? 0 : speedOf(b);
5908
- const c = this.centerOf(b, p);
5909
- const cx = c.x, cy = c.y, cz = c.z;
5910
- const rb = Math.hypot(b.halfExtents[0], b.halfExtents[1], b.halfExtents[2]);
5911
- for (const o of this.list) {
5912
- if (o === b || b.sleeping && o.sleeping) continue;
5913
- const closing = speed + (o.sleeping ? 0 : speedOf(o));
5914
- if (closing * dt < radius * 0.5) continue;
5915
- const reach = closing * dt + rb + Math.hypot(o.halfExtents[0], o.halfExtents[1], o.halfExtents[2]);
5916
- const oc = this.centerOf(o, p);
5917
- if (Math.abs(oc.x - cx) > reach || Math.abs(oc.y - cy) > reach || Math.abs(oc.z - cz) > reach) continue;
5918
- const pair = Math.ceil(closing * dt / radius);
5919
- if (pair < 2) continue;
5920
- need = Math.max(need, pair);
5921
- near2.add(b);
5922
- near2.add(o);
5923
- }
5924
- }
5925
- return { steps: Math.max(1, Math.min(MAX_COLLISION_STEPS, need)), near: near2 };
5926
- }
5927
- /** A step of `dt`: the pieces `only.moves` takes move (all when absent) and the pairs `only.meets` takes meet, so each pair meets in one of the steps of an update. */
5928
- step(dt, only) {
5929
- this.surfaceByTile.clear();
5911
+ this.time += dt;
5912
+ this.engine.wakePending(this.list, this.awake);
5930
5913
  this.measure();
5931
- this.wakeUnsupported();
5932
- for (const b of this.list) {
5933
- if (b.held) {
5934
- b.velocity = [0, 0, 0];
5935
- b.angularVelocity = [0, 0, 0];
5936
- b.sleeping = false;
5937
- b.still = 0;
5938
- b.calmAt = null;
5939
- continue;
5940
- }
5941
- if (b.sleeping || only && !only.moves(b)) continue;
5942
- this.integrate(b, dt);
5943
- if (b.sleeping) continue;
5944
- const v = b.velocity;
5945
- const w = b.angularVelocity;
5946
- if (Math.hypot(v[0], v[1], v[2]) > WAKE_ABOVE_SPEED || Math.hypot(w[0], w[1], w[2]) > WAKE_ABOVE_SPIN) this.wakeAbove(b);
5914
+ this.wakeUnsupported(true);
5915
+ if (dt > 0) {
5916
+ this.engine.prepare(this.list, dt, dt, this.apartAll(dt), this.awake);
5917
+ this.loop.step(dt);
5918
+ this.engine.finish(this.list, dt, this.time, this.awake);
5947
5919
  }
5948
- this.collide(dt, only?.meets);
5920
+ this.measure();
5949
5921
  this.keepBudget();
5950
5922
  this.keepFar();
5951
5923
  }
@@ -6096,29 +6068,6 @@ var PieceSystem = class {
6096
6068
  }
6097
6069
  return top;
6098
6070
  }
6099
- /** What lay asleep on `b` (a box over its top) wakes at once when `b` moves: a can on a table that goes over goes with it. */
6100
- wakeAbove(b) {
6101
- const below = this.solidOf.get(b);
6102
- if (!below) return;
6103
- const top = below.c[1] + below.half[0] * Math.abs(below.e[1]) + below.half[1] * Math.abs(below.e[5]) + below.half[2] * Math.abs(below.e[9]);
6104
- const x0 = Math.floor((below.c[0] - below.r) / SURFACE_CELL);
6105
- const x1 = Math.floor((below.c[0] + below.r) / SURFACE_CELL);
6106
- const z0 = Math.floor((below.c[2] - below.r) / SURFACE_CELL);
6107
- const z1 = Math.floor((below.c[2] + below.r) / SURFACE_CELL);
6108
- const wide = x1 - x0 > SURFACE_CELLS_ACROSS || z1 - z0 > SURFACE_CELLS_ACROSS;
6109
- const look = (part) => {
6110
- const o = part.body;
6111
- const s = this.solidOf.get(o);
6112
- if (!s || !o.sleeping || o.held || o === b) return;
6113
- if (s.c[1] < below.c[1] || s.c[1] - s.r > top + STEP || Math.hypot(s.c[0] - below.c[0], s.c[2] - below.c[2]) > s.r + below.r) return;
6114
- if (boxTopAt(below, s.c[0], s.c[2]) === -Infinity && !this.restsOn(o, b, true)) return;
6115
- o.sleeping = false;
6116
- o.still = 0;
6117
- o.calmAt = null;
6118
- };
6119
- if (wide) for (const s of this.solids) look(s);
6120
- else for (let ix = x0; ix <= x1; ix++) for (let iz = z0; iz <= z1; iz++) for (const part of this.surfaceGrid.get(cellKey(ix, iz)) ?? []) look(part);
6121
- }
6122
6071
  /**
6123
6072
  * Whether `o` rests on a top of `below` (its parts, or its box): a corner of `o` (its contacts or its box) is over that top and within `STEP` of it. With `lowest`, only its
6124
6073
  * lowest corners count (within `STEP` of its lowest): a can rolling by another is beside it, not on it; without, a board leaning on a seat by its high end rests on the seat.
@@ -6135,36 +6084,6 @@ var PieceSystem = class {
6135
6084
  }
6136
6085
  return false;
6137
6086
  }
6138
- /**
6139
- * The terrain's own surface under a round piece's contact at (x, z) that stands at `y` on the ground `raw` (`groundAt` there), when it is the terrain and not a top above it
6140
- * (`terrainAt`, which `groundAt` equals to the bit where nothing is on it); null otherwise (the default surface). Read as the engine reads it (`tileRollingAt`), once per tile
6141
- * per update, and one object per value, so a substep makes none.
6142
- */
6143
- terrainSurface(x, y, z, raw) {
6144
- const rollingAt = this.o.terrainRollingAt;
6145
- if (!rollingAt || y !== raw || this.o.terrainAt && y !== this.o.terrainAt(x, z)) return null;
6146
- const key = groundTileKey(x, z);
6147
- let surface = this.surfaceByTile.get(key);
6148
- if (surface === void 0) {
6149
- surface = this.tileSurface(rollingAt, x, z);
6150
- this.surfaceByTile.set(key, surface);
6151
- }
6152
- return surface;
6153
- }
6154
- /** The terrain's surface of the tile at (x, z) (`tileRollingAt`), or null when it says nothing (the default surface). */
6155
- tileSurface(rollingAt, x, z) {
6156
- const dampingAt = this.o.terrainRollingDampingAt;
6157
- const rolling = tileRollingAt(rollingAt, x, z);
6158
- const rollingDamping = dampingAt ? tileRollingAt(dampingAt, x, z) : void 0;
6159
- if (rolling === void 0 && rollingDamping === void 0) return null;
6160
- const id = `${rolling ?? ROLLING_RESISTANCE2}|${rollingDamping ?? GROUND_ROLLING_DAMPING}`;
6161
- let surface = this.terrainSurfaces.get(id);
6162
- if (!surface) {
6163
- surface = { static: MU_STATIC2, dynamic: MU_DYNAMIC2, rolling: rolling ?? ROLLING_RESISTANCE2, rollingDamping: rollingDamping ?? GROUND_ROLLING_DAMPING };
6164
- this.terrainSurfaces.set(id, surface);
6165
- }
6166
- return surface;
6167
- }
6168
6087
  /** Where a corner of `self` at `(x, y, z)` lands: the ground, the top of another piece or of something fixed under it. */
6169
6088
  supportAt(self, x, y, z, step) {
6170
6089
  let top = this.o.groundAt(x, z);
@@ -6186,391 +6105,6 @@ var PieceSystem = class {
6186
6105
  this.supportBody = on?.body ?? null;
6187
6106
  return Math.max(top, fixed);
6188
6107
  }
6189
- /** Stops a piece that ran into something on its way from `start` to `pos` (`sweep`): moves it back to where it met it and takes the speed into it. */
6190
- sweepOn(b, start, pos) {
6191
- const travel = Math.hypot(pos[0] - start[0], pos[1] - start[1], pos[2] - start[2]);
6192
- if (travel < 1e-3) return;
6193
- const hit = this.o.sweep?.(b, start, pos);
6194
- if (!hit || hit.normal[1] > SLAM_FLOOR_NORMAL2) return;
6195
- const v = b.velocity;
6196
- const n = hit.normal;
6197
- const into = -(v[0] * n[0] + v[1] * n[1] + v[2] * n[2]);
6198
- if (into <= 0) return;
6199
- const k = Math.min(1, hit.distance / travel);
6200
- const bounce = pairRestitution(b.restitution, hit.restitution);
6201
- for (let i = 0; i < 3; i++) {
6202
- pos[i] = start[i] + (pos[i] - start[i]) * k;
6203
- v[i] += (1 + bounce) * into * n[i];
6204
- }
6205
- const w = b.angularVelocity;
6206
- w[0] *= 0.5;
6207
- w[1] *= 0.5;
6208
- w[2] *= 0.5;
6209
- if (into >= SLAM_MIN_SPEED2 && this.time - b.lastHit > 0.15) {
6210
- b.lastHit = this.time;
6211
- this.o.onSlam?.(b, hit, into);
6212
- }
6213
- }
6214
- /**
6215
- * The impulse that stops the hinge point of a piece: the point's velocity v + w x r goes to zero through J = -K^-1 (v + w x r), with K = 1/m - [r]x I^-1 [r]x, so what
6216
- * gravity gave the centre turns into a swing about the hinge.
6217
- */
6218
- holdOnHinge(b, hinge, q) {
6219
- const e = this.hingeM.makeRotationFromQuaternion(q).elements;
6220
- const [lx, ly, lz] = hinge.local;
6221
- const r = [e[0] * lx + e[4] * ly + e[8] * lz, e[1] * lx + e[5] * ly + e[9] * lz, e[2] * lx + e[6] * ly + e[10] * lz];
6222
- const v = b.velocity;
6223
- const w = b.angularVelocity;
6224
- const point = [v[0] + w[1] * r[2] - w[2] * r[1], v[1] + w[2] * r[0] - w[0] * r[2], v[2] + w[0] * r[1] - w[1] * r[0]];
6225
- const k = [0, 1, 2].map((i) => {
6226
- const d = [i === 0 ? 1 : 0, i === 1 ? 1 : 0, i === 2 ? 1 : 0];
6227
- const t = this.mulInvInertiaWith(b, e, r[1] * d[2] - r[2] * d[1], r[2] * d[0] - r[0] * d[2], r[0] * d[1] - r[1] * d[0]);
6228
- return [d[0] / b.mass + t[1] * r[2] - t[2] * r[1], d[1] / b.mass + t[2] * r[0] - t[0] * r[2], d[2] / b.mass + t[0] * r[1] - t[1] * r[0]];
6229
- });
6230
- const j = solve3(k, [-point[0], -point[1], -point[2]]);
6231
- if (!j) return;
6232
- for (let i = 0; i < 3; i++) v[i] += j[i] / b.mass;
6233
- const dw = this.mulInvInertiaWith(b, e, r[1] * j[2] - r[2] * j[1], r[2] * j[0] - r[0] * j[2], r[0] * j[1] - r[1] * j[0]);
6234
- for (let i = 0; i < 3; i++) w[i] += dw[i];
6235
- }
6236
- /** Puts the hinge point back where it hangs (what the step's rounding moved it by), moving the centre. */
6237
- keepOnHinge(hinge, pos, q) {
6238
- const e = this.hingeM.makeRotationFromQuaternion(q).elements;
6239
- const [lx, ly, lz] = hinge.local;
6240
- pos[0] = hinge.point[0] - (e[0] * lx + e[4] * ly + e[8] * lz);
6241
- pos[1] = hinge.point[1] - (e[1] * lx + e[5] * ly + e[9] * lz);
6242
- pos[2] = hinge.point[2] - (e[2] * lx + e[6] * ly + e[10] * lz);
6243
- }
6244
- /** The screw tears out: past `HINGE_RELEASE` of turn, or after `HINGE_SECONDS`, the piece falls free. */
6245
- wearHinge(b, hinge, q, dt) {
6246
- hinge.seconds -= dt;
6247
- const [x, y, z, w] = hinge.from;
6248
- const turned = 2 * Math.acos(Math.min(1, Math.abs(q.x * x + q.y * y + q.z * z + q.w * w)));
6249
- if (turned >= HINGE_RELEASE || hinge.seconds <= 0) b.hinge = void 0;
6250
- }
6251
- integrate(b, dt) {
6252
- const c = this.centerOf(b, this.p);
6253
- const pos = [c.x, c.y, c.z];
6254
- const start = [c.x, c.y, c.z];
6255
- const q = this.q.copy(b.root.quaternion);
6256
- const v = b.velocity;
6257
- const w = b.angularVelocity;
6258
- const invM = 1 / b.mass;
6259
- const steps = clamp(Math.ceil(dt / SUB_DT), 1, 8);
6260
- const h = dt / steps;
6261
- let landing = 0;
6262
- let landPoint = [pos[0], pos[1], pos[2]];
6263
- let contactedLast = false;
6264
- const propped = b.propped;
6265
- const proppedAt = b.proppedAt;
6266
- b.propped = void 0;
6267
- b.proppedAt = void 0;
6268
- let touched = false;
6269
- let unstable = false;
6270
- const corners = this.samples(b, false);
6271
- this.m.makeRotationFromQuaternion(q);
6272
- let gLow = Infinity;
6273
- let gHigh = -Infinity;
6274
- for (const [sx, sy, sz] of corners) {
6275
- const e0 = this.m.elements;
6276
- const y = pos[1] + e0[1] * sx + e0[5] * sy + e0[9] * sz;
6277
- const x = pos[0] + e0[0] * sx + e0[4] * sy + e0[8] * sz;
6278
- const z = pos[2] + e0[2] * sx + e0[6] * sy + e0[10] * sz;
6279
- const g = Math.max(this.o.groundAt(x, z), this.o.staticTopAt?.(x, z, y, STEP) ?? -Infinity);
6280
- gLow = Math.min(gLow, g);
6281
- gHigh = Math.max(gHigh, g);
6282
- }
6283
- let local = b.round ? this.roundSamples(b, q) : gHigh - gLow > STEP ? this.samples(b, true) : corners;
6284
- let prev = local.map(() => [0, 0, 0]);
6285
- for (let s = 0; s < steps; s++) {
6286
- if (b.round) {
6287
- const wl0 = Math.hypot(w[0], w[1], w[2]);
6288
- const next = this.nextQ.copy(q);
6289
- if (wl0 > 1e-6) next.premultiply(this.dq.setFromAxisAngle(this.ax.set(w[0] / wl0, w[1] / wl0, w[2] / wl0), wl0 * h)).normalize();
6290
- local = this.roundSamples(b, next);
6291
- if (prev.length !== local.length) prev = local.map(() => [0, 0, 0]);
6292
- }
6293
- this.m.makeRotationFromQuaternion(q);
6294
- const e0 = this.m.elements;
6295
- for (let i = 0; i < local.length; i++) {
6296
- const [sx, sy, sz] = local[i];
6297
- prev[i][0] = pos[0] + e0[0] * sx + e0[4] * sy + e0[8] * sz;
6298
- prev[i][1] = pos[1] + e0[1] * sx + e0[5] * sy + e0[9] * sz;
6299
- prev[i][2] = pos[2] + e0[2] * sx + e0[6] * sy + e0[10] * sz;
6300
- }
6301
- v[1] -= this.o.gravity * h;
6302
- if (b.hinge) this.holdOnHinge(b, b.hinge, q);
6303
- if (propped) {
6304
- const into = v[0] * propped[0] + v[1] * propped[1] + v[2] * propped[2];
6305
- if (into < 0) for (let k = 0; k < 3; k++) v[k] -= into * propped[k];
6306
- }
6307
- pos[0] += v[0] * h;
6308
- pos[1] += v[1] * h;
6309
- pos[2] += v[2] * h;
6310
- const wl = Math.hypot(w[0], w[1], w[2]);
6311
- if (wl > 1e-6) {
6312
- this.dq.setFromAxisAngle(this.ax.set(w[0] / wl, w[1] / wl, w[2] / wl), wl * h);
6313
- q.premultiply(this.dq).normalize();
6314
- }
6315
- if (b.hinge) this.keepOnHinge(b.hinge, pos, q);
6316
- const damp = b.round ? 1 : Math.exp(-0.15 * h);
6317
- w[0] *= damp;
6318
- w[1] *= damp;
6319
- w[2] *= damp;
6320
- this.m.makeRotationFromQuaternion(q);
6321
- const e = this.m.elements;
6322
- const rs = [];
6323
- const ids = [];
6324
- const ns = [];
6325
- const mus = [];
6326
- let maxPen = 0;
6327
- let penNormal = UP;
6328
- const rise = STEP + Math.max(0, -v[1]) * h * 2;
6329
- let side = null;
6330
- let lowest = Infinity;
6331
- for (let i = 0; i < local.length; i++) {
6332
- const [sx, sy, sz] = local[i];
6333
- const r = [e[0] * sx + e[4] * sy + e[8] * sz, e[1] * sx + e[5] * sy + e[9] * sz, e[2] * sx + e[6] * sy + e[10] * sz];
6334
- const px = pos[0] + r[0];
6335
- const pz = pos[2] + r[2];
6336
- const cy = pos[1] + r[1];
6337
- const was = prev[i];
6338
- const raw = this.o.groundAt(px, pz);
6339
- if (raw > cy - SLOP && was[1] < raw - STEP) {
6340
- if (this.o.groundAt(was[0], was[2]) >= raw - STEP) {
6341
- const floor = b.floor;
6342
- if (floor !== void 0 && floor - cy > -SLOP && floor < raw - STEP) {
6343
- rs.push(r);
6344
- ids.push(i);
6345
- ns.push(UP);
6346
- mus.push(pairFriction(b.friction, b.round ? this.terrainSurface(px, floor, pz, floor) : null));
6347
- maxPen = Math.max(maxPen, floor - cy);
6348
- }
6349
- continue;
6350
- }
6351
- const dx = px - was[0];
6352
- const dz = pz - was[2];
6353
- const len = Math.hypot(dx, dz);
6354
- if (len > 1e-6) {
6355
- let lo = 0;
6356
- let hi = 1;
6357
- for (let it = 0; it < 6; it++) {
6358
- const mid = (lo + hi) / 2;
6359
- if (this.o.groundAt(was[0] + dx * mid, was[2] + dz * mid) >= raw - STEP) hi = mid;
6360
- else lo = mid;
6361
- }
6362
- const back = (1 - lo) * len + 1e-3;
6363
- if (!side || back > side.back) side = { back, dir: [dx / len, dz / len], r };
6364
- }
6365
- continue;
6366
- }
6367
- this.supportNormal = UP;
6368
- this.supportFriction = null;
6369
- const gy = i < 8 || b.contacts ? this.supportAt(b, px, cy, pz, rise) : Math.max(raw, this.o.staticTopAt?.(px, pz, cy, rise) ?? -Infinity);
6370
- const pen = gy - cy;
6371
- if (pen > -SLOP) {
6372
- rs.push(r);
6373
- ids.push(i);
6374
- ns.push(this.supportNormal);
6375
- mus.push(pairFriction(b.friction, this.supportFriction ?? (b.round ? this.terrainSurface(px, gy, pz, raw) : null)));
6376
- if (pen > maxPen) {
6377
- maxPen = pen;
6378
- penNormal = this.supportNormal;
6379
- }
6380
- lowest = Math.min(lowest, gy);
6381
- }
6382
- }
6383
- if (lowest < Infinity) b.floor = lowest;
6384
- if (b.round && ns.length > 0) {
6385
- const sum = [0, 0, 0];
6386
- for (const one of ns) for (let k = 0; k < 3; k++) sum[k] += one[k];
6387
- const len = Math.hypot(sum[0], sum[1], sum[2]);
6388
- b.surfaceNormal = len > 1e-6 ? [sum[0] / len, sum[1] / len, sum[2] / len] : UP;
6389
- } else if (b.round && rs.length === 0) b.surfaceNormal = UP;
6390
- if (side) {
6391
- pos[0] -= side.dir[0] * side.back;
6392
- pos[2] -= side.dir[1] * side.back;
6393
- this.contactImpulse(b, e, side.r, [-side.dir[0], 0, -side.dir[1]], SIDE_BOUNCE);
6394
- }
6395
- contactedLast = rs.length > 0;
6396
- if (contactedLast) touched = true;
6397
- if (!contactedLast) continue;
6398
- const out = Math.max(0, maxPen - SLOP * 0.5) * penNormal[1];
6399
- pos[0] += penNormal[0] * out;
6400
- pos[1] += penNormal[1] * out;
6401
- pos[2] += penNormal[2] * out;
6402
- let impact2 = 0;
6403
- for (const r of rs) impact2 = Math.max(impact2, -(v[1] + w[2] * r[0] - w[0] * r[2]));
6404
- const restitution = impact2 > 2 ? 0.25 : 0;
6405
- if (impact2 > landing) {
6406
- landing = impact2;
6407
- let sx = 0;
6408
- let sz = 0;
6409
- for (const r of rs) {
6410
- sx += r[0];
6411
- sz += r[2];
6412
- }
6413
- const lx = pos[0] + sx / rs.length;
6414
- const lz = pos[2] + sz / rs.length;
6415
- landPoint = [lx, pos[1] - Math.max(...rs.map((r) => -r[1])), lz];
6416
- }
6417
- const pointV = (r) => [v[0] + w[1] * r[2] - w[2] * r[1], v[1] + w[2] * r[0] - w[0] * r[2], v[2] + w[0] * r[1] - w[1] * r[0]];
6418
- const dot2 = (a, c2) => a[0] * c2[0] + a[1] * c2[1] + a[2] * c2[2];
6419
- const goal = rs.map((r, k) => {
6420
- const vn = dot2(pointV(r), ns[k]);
6421
- return vn < 0 ? -restitution * vn : 0;
6422
- });
6423
- const slipping = rs.map((r, k) => {
6424
- const pv = pointV(r);
6425
- pv[1] += this.o.gravity * h;
6426
- const vn = dot2(pv, ns[k]);
6427
- return Math.hypot(pv[0] - vn * ns[k][0], pv[1] - vn * ns[k][1], pv[2] - vn * ns[k][2]) > SLIP_SPEED;
6428
- });
6429
- const vx0 = v[0];
6430
- const vz0 = v[2];
6431
- if (!b.warm || b.warm.length !== WARM_SLOTS * 4) b.warm = new Float64Array(WARM_SLOTS * 4);
6432
- const warm = b.warm;
6433
- const accN = ids.map((id) => id < WARM_SLOTS ? warm[id * 4] : 0);
6434
- const accT = ids.map((id) => id < WARM_SLOTS ? [warm[id * 4 + 1], warm[id * 4 + 2], warm[id * 4 + 3]] : [0, 0, 0]);
6435
- const push = (r, j) => {
6436
- v[0] += j[0] * invM;
6437
- v[1] += j[1] * invM;
6438
- v[2] += j[2] * invM;
6439
- const dw = this.mulInvInertiaWith(b, e, r[1] * j[2] - r[2] * j[1], r[2] * j[0] - r[0] * j[2], r[0] * j[1] - r[1] * j[0]);
6440
- w[0] += dw[0];
6441
- w[1] += dw[1];
6442
- w[2] += dw[2];
6443
- };
6444
- const reach = (r, d) => {
6445
- const a = this.mulInvInertiaWith(b, e, r[1] * d[2] - r[2] * d[1], r[2] * d[0] - r[0] * d[2], r[0] * d[1] - r[1] * d[0]);
6446
- return invM + (a[1] * r[2] - a[2] * r[1]) * d[0] + (a[2] * r[0] - a[0] * r[2]) * d[1] + (a[0] * r[1] - a[1] * r[0]) * d[2];
6447
- };
6448
- for (let k = 0; k < rs.length; k++) {
6449
- const n = ns[k];
6450
- const t = accT[k];
6451
- if (accN[k] !== 0 || t[0] !== 0 || t[1] !== 0 || t[2] !== 0) push(rs[k], [n[0] * accN[k] + t[0], n[1] * accN[k] + t[1], n[2] * accN[k] + t[2]]);
6452
- }
6453
- for (let it = 0; it < SOLVER_PASSES; it++) {
6454
- for (let k = 0; k < rs.length; k++) {
6455
- const r = rs[k];
6456
- const n = ns[k];
6457
- const vn = dot2(pointV(r), n);
6458
- const total = Math.max(0, accN[k] + (goal[k] - vn) / reach(r, n));
6459
- const j = total - accN[k];
6460
- accN[k] = total;
6461
- if (j !== 0) push(r, [n[0] * j, n[1] * j, n[2] * j]);
6462
- const pv = pointV(r);
6463
- const pn = dot2(pv, n);
6464
- const vt = [pv[0] - pn * n[0], pv[1] - pn * n[1], pv[2] - pn * n[2]];
6465
- const speed = Math.hypot(vt[0], vt[1], vt[2]);
6466
- const f = [accT[k][0], accT[k][1], accT[k][2]];
6467
- if (speed > 1e-6) {
6468
- const d = [vt[0] / speed, vt[1] / speed, vt[2] / speed];
6469
- const jt = speed / reach(r, d);
6470
- f[0] -= d[0] * jt;
6471
- f[1] -= d[1] * jt;
6472
- f[2] -= d[2] * jt;
6473
- } else if (f[0] === 0 && f[1] === 0 && f[2] === 0) continue;
6474
- const most = (slipping[k] ? mus[k].dynamic : mus[k].static) * accN[k];
6475
- const fl = Math.hypot(f[0], f[1], f[2]);
6476
- if (fl > most) {
6477
- f[0] *= most / fl;
6478
- f[1] *= most / fl;
6479
- f[2] *= most / fl;
6480
- }
6481
- const dj = [f[0] - accT[k][0], f[1] - accT[k][1], f[2] - accT[k][2]];
6482
- accT[k] = f;
6483
- if (dj[0] !== 0 || dj[1] !== 0 || dj[2] !== 0) push(r, dj);
6484
- }
6485
- }
6486
- pos[0] += (v[0] - vx0) * h;
6487
- pos[2] += (v[2] - vz0) * h;
6488
- warm.fill(0);
6489
- for (let k = 0; k < rs.length; k++) {
6490
- const id = ids[k];
6491
- if (id >= WARM_SLOTS) continue;
6492
- warm[id * 4] = accN[k];
6493
- warm[id * 4 + 1] = accT[k][0];
6494
- warm[id * 4 + 2] = accT[k][1];
6495
- warm[id * 4 + 3] = accT[k][2];
6496
- }
6497
- let x0 = Infinity, x1 = -Infinity, z0 = Infinity, z1 = -Infinity, low = 0;
6498
- for (const r of rs) {
6499
- x0 = Math.min(x0, r[0]);
6500
- x1 = Math.max(x1, r[0]);
6501
- z0 = Math.min(z0, r[2]);
6502
- z1 = Math.max(z1, r[2]);
6503
- low = Math.min(low, r[1]);
6504
- }
6505
- if (proppedAt) {
6506
- x0 = Math.min(x0, proppedAt[0]);
6507
- x1 = Math.max(x1, proppedAt[0]);
6508
- z0 = Math.min(z0, proppedAt[2]);
6509
- z1 = Math.max(z1, proppedAt[2]);
6510
- }
6511
- const height = -low;
6512
- const wx = x1 - x0;
6513
- const wz = z1 - z0;
6514
- const pastX = x0 > -SUPPORT_MARGIN * wx || x1 < SUPPORT_MARGIN * wx;
6515
- const pastZ = z0 > -SUPPORT_MARGIN * wz || z1 < SUPPORT_MARGIN * wz;
6516
- unstable = !b.round && (Math.min(wx, wz) < NARROW2 * height || pastX || pastZ);
6517
- if (b.tipping) {
6518
- b.tipping.seconds -= h;
6519
- const [hx, hy, hz] = b.halfExtents;
6520
- const upHalf = Math.abs(e[1]) * hx + Math.abs(e[5]) * hy + Math.abs(e[9]) * hz;
6521
- const rising = TIP_SECONDS - b.tipping.seconds > TIP_RISE_AFTER && v[1] > TIP_RISING;
6522
- if (upHalf < TIP_LYING || b.tipping.seconds <= 0 || rising) b.tipping = null;
6523
- else {
6524
- w[0] += b.tipping.x * TIP_ACCELERATION * h;
6525
- w[2] += b.tipping.z * TIP_ACCELERATION * h;
6526
- unstable = true;
6527
- }
6528
- }
6529
- if (unstable) {
6530
- const dirX = x0 + x1 > 0 ? -1 : 1;
6531
- const dirZ = z0 + z1 > 0 ? -1 : 1;
6532
- const k = TOPPLE2 * Math.min(height, 1) * h;
6533
- const overZ = pastX === pastZ ? wx <= wz : pastX;
6534
- if (overZ) w[2] -= dirX * k;
6535
- else w[0] += dirZ * k;
6536
- }
6537
- if (b.round) {
6538
- let rolling = 0;
6539
- let damping = 0;
6540
- for (const mu of mus) {
6541
- rolling = Math.max(rolling, mu.rolling ?? ROLLING_RESISTANCE2);
6542
- damping = Math.max(damping, mu.rollingDamping ?? 0);
6543
- }
6544
- this.rollingResistance(b, q, w, h, { rolling, damping });
6545
- } else {
6546
- const rd = Math.exp((rs.length >= 3 ? -3 : -1.5) * h);
6547
- w[0] *= rd;
6548
- w[1] *= rd;
6549
- w[2] *= rd;
6550
- const fd = Math.exp(-0.3 * h);
6551
- v[0] *= fd;
6552
- v[2] *= fd;
6553
- }
6554
- }
6555
- if (b.hinge) this.wearHinge(b, b.hinge, q, dt);
6556
- if (this.o.sweep && !b.held) this.sweepOn(b, start, pos);
6557
- b.root.quaternion.copy(q);
6558
- const off2 = this.ax.copy(b.centerV).applyQuaternion(q);
6559
- b.root.position.set(pos[0] - off2.x, pos[1] - off2.y, pos[2] - off2.z);
6560
- b.root.updateMatrixWorld(true);
6561
- b.onGround = contactedLast;
6562
- if (landing > HARD_LANDING2 && this.time - b.lastHit > 0.15) {
6563
- b.lastHit = this.time;
6564
- this.o.onHardLanding(b, landPoint, landing);
6565
- }
6566
- const still = touched && !unstable && Math.hypot(v[0], v[1], v[2]) < STILL_SPEED2 && Math.hypot(w[0], w[1], w[2]) < STILL_SPIN2;
6567
- if (still) b.still += dt;
6568
- else b.still = 0;
6569
- b.balancing = unstable;
6570
- this.keepsTilt(b, q, dt);
6571
- const held = (touched || propped !== void 0) && !b.tipping;
6572
- if (!b.hinge && (b.still >= SLEEP_AFTER || this.staysInPlace(b, held, pos, q, dt)) && !this.onSteepSupport(b)) this.sleep(b);
6573
- }
6574
6108
  /**
6575
6109
  * Whether `b` lies flat on a settled top (asleep) tilted past what the friction of the two holds (a laptop on a table top gone over at 42 degrees, held by 0.49 up to 26),
6576
6110
  * with every corner that touches on it: it slides, it does not sleep there, and one asleep there wakes. Held by anything else (the floor, a flat top, a side it leans on, a
@@ -6604,15 +6138,6 @@ var PieceSystem = class {
6604
6138
  b.velocity[0] = b.velocity[1] = b.velocity[2] = 0;
6605
6139
  b.angularVelocity[0] = b.angularVelocity[1] = b.angularVelocity[2] = 0;
6606
6140
  }
6607
- /** How long the piece has kept its tilt (within `STEADY_TURN`): one going over leaves it within a moment, one held up at an angle keeps it. */
6608
- keepsTilt(b, q, dt) {
6609
- const at = b.steady;
6610
- if (at && turnBetween(at.quaternion, q) <= STEADY_TURN2) {
6611
- at.seconds += dt;
6612
- return;
6613
- }
6614
- b.steady = { quaternion: [q.x, q.y, q.z, q.w], seconds: 0 };
6615
- }
6616
6141
  /**
6617
6142
  * Over `maxAwake` pieces awake, the oldest that have come to rest sleep where they lie: on the ground, slower than `STILL_SPEED` and `STILL_SPIN`, not falling over (`tip`),
6618
6143
  * and one held up at an angle (a board leaning on a seat) only once it kept its tilt for `STEADY_SECONDS`; that one sleeps then under the budget too, since nothing else puts
@@ -6723,118 +6248,6 @@ var PieceSystem = class {
6723
6248
  const y = c.y + e[1] * sx + e[5] * sy + e[9] * sz;
6724
6249
  return this.supportAt(b, c.x + e[0] * sx + e[4] * sy + e[8] * sz, y, c.z + e[2] * sx + e[6] * sy + e[10] * sz, STEP) >= y - SUPPORT_GAP2;
6725
6250
  }
6726
- /** Whether the piece has kept to the same spot on the ground for `CALM_SLEEP_AFTER` (see `CALM_DRIFT`). */
6727
- staysInPlace(b, touched, center, q, dt) {
6728
- const at = b.calmAt;
6729
- const turned = at ? turnBetween(at.quaternion, q) : Infinity;
6730
- if (!touched || !at || Math.hypot(center[0] - at.center[0], center[1] - at.center[1], center[2] - at.center[2]) > CALM_DRIFT || turned > CALM_TURN) {
6731
- b.calmAt = touched ? { center: [center[0], center[1], center[2]], quaternion: [q.x, q.y, q.z, q.w] } : null;
6732
- b.calm = 0;
6733
- return false;
6734
- }
6735
- b.calm += dt;
6736
- return b.calm >= CALM_SLEEP_AFTER;
6737
- }
6738
- /** Whether the centre `c` of `upper` is over the top of `lower`'s box (as it was at the start of the update). */
6739
- onTopOf(upper, lower, c) {
6740
- const s = this.solidOf.get(lower);
6741
- if (!s) return false;
6742
- const top = boxTopAt(s, c.x, c.z);
6743
- return top > -Infinity && c.y >= top - 0.01;
6744
- }
6745
- /**
6746
- * The points a round piece touches the ground by as it is turned now (`q`): its rims (`contacts`), which hold it standing on an end, and the exact lowest point of each
6747
- * rim (of the ball), so lying on its side it rests on a line and rolls smoothly instead of over the corners of a polygon.
6748
- */
6749
- roundSamples(b, q) {
6750
- const round = b.round;
6751
- const rims = b.contacts ?? [];
6752
- if (!round) return rims;
6753
- const e = this.m.makeRotationFromQuaternion(q).elements;
6754
- const n = b.surfaceNormal ?? UP;
6755
- const down = [-(e[0] * n[0] + e[1] * n[1] + e[2] * n[2]), -(e[4] * n[0] + e[5] * n[1] + e[6] * n[2]), -(e[8] * n[0] + e[9] * n[1] + e[10] * n[2])];
6756
- if (round.kind === "sphere") return [...rims, [down[0] * round.radius, down[1] * round.radius, down[2] * round.radius]];
6757
- const k = round.axis;
6758
- const across = [down[0], down[1], down[2]];
6759
- across[k] = 0;
6760
- const len = Math.hypot(across[0], across[1], across[2]);
6761
- if (len < 1e-3) return rims;
6762
- const lowest = (at, radius) => {
6763
- const p = [across[0] / len * radius, across[1] / len * radius, across[2] / len * radius];
6764
- p[k] = at;
6765
- return p;
6766
- };
6767
- const half = b.halfExtents[k];
6768
- const low = (round.profile ?? [[-half, round.radius], [half, round.radius]]).map(([at, radius]) => lowest(at, radius));
6769
- return len > ROUND_LYING ? low : [...rims, ...low];
6770
- }
6771
- /**
6772
- * Slows the spin of a round piece on the ground by its rolling resistance: a torque C_rr N r about the axis it rolls on (N = m g n_y on a surface of normal n), so with
6773
- * I = k m r^2 the spin loses C_rr g n_y / (k r) per second, and down a slope of angle t it rolls at g (sin t - C_rr cos t) / (1 + k). Standing on its rim, a can's spin
6774
- * about the rest dies down; lying, it keeps turning about the line it touches by (a tapered bottle rounds its narrow end). Its rolling damping (`PieceFriction.rollingDamping`,
6775
- * the pair's) then takes exp(-d h) of what is left, as the grass or the sand drag more the faster it rolls.
6776
- */
6777
- rollingResistance(b, q, w, h, { rolling, damping }) {
6778
- const round = b.round;
6779
- if (!round) return;
6780
- const e = this.m.makeRotationFromQuaternion(q).elements;
6781
- const cylinder = round.kind === "cylinder";
6782
- const a = cylinder ? [e[round.axis * 4], e[round.axis * 4 + 1], e[round.axis * 4 + 2]] : [0, 0, 0];
6783
- const along2 = cylinder ? w[0] * a[0] + w[1] * a[1] + w[2] * a[2] : 0;
6784
- const roll = cylinder ? [a[0] * along2, a[1] * along2, a[2] * along2] : [w[0], w[1], w[2]];
6785
- const rest = [w[0] - roll[0], w[1] - roll[1], w[2] - roll[2]];
6786
- const spin = Math.hypot(roll[0], roll[1], roll[2]);
6787
- const upright = b.surfaceNormal?.[1] ?? 1;
6788
- const slow = spin > 0 ? Math.max(0, spin - rolling * this.o.gravity * upright * h / (round.inertia * round.radius)) / spin * Math.exp(-damping * h) : 0;
6789
- const lying = cylinder && Math.abs(a[1]) < ROUND_LYING;
6790
- const damp = lying ? 1 : Math.exp(-3 * h);
6791
- for (let i = 0; i < 3; i++) w[i] = roll[i] * slow + rest[i] * damp;
6792
- }
6793
- /** Half the height of the box of a piece as it is turned now. */
6794
- halfHeight(b) {
6795
- const e = this.m.makeRotationFromQuaternion(b.root.quaternion).elements;
6796
- return Math.abs(e[1]) * b.halfExtents[0] + Math.abs(e[5]) * b.halfExtents[1] + Math.abs(e[9]) * b.halfExtents[2];
6797
- }
6798
- /**
6799
- * Pieces against each other. Candidates by sweep and prune along x on their bounding spheres (sorted once per step: fifty cans cost a sort and a handful of pairs, not
6800
- * 1225); a pair with a round piece in it meets by its shapes (`shapeContact`) and exchanges an impulse, two boxes are put apart by their separating axes (`separatePair`).
6801
- */
6802
- collide(dt, meets) {
6803
- const n = this.list.length;
6804
- if (n < 2) return;
6805
- const centers = this.list.map((b) => {
6806
- const c = this.centerOf(b, this.p);
6807
- return [c.x, c.y, c.z];
6808
- });
6809
- const radii = this.list.map((b) => Math.hypot(b.halfExtents[0], b.halfExtents[1], b.halfExtents[2]));
6810
- const order = this.list.map((_, i) => i).sort((i, j) => centers[i][0] - radii[i] - (centers[j][0] - radii[j]));
6811
- for (let oi = 0; oi < n; oi++) {
6812
- const i = order[oi];
6813
- const reach = centers[i][0] + radii[i];
6814
- for (let oj = oi + 1; oj < n; oj++) {
6815
- const j = order[oj];
6816
- if (centers[j][0] - radii[j] > reach) break;
6817
- const a = this.list[i];
6818
- const b = this.list[j];
6819
- if ((a.held || a.sleeping) && (b.held || b.sleeping)) continue;
6820
- if (meets && !meets(a, b)) continue;
6821
- const r = radii[i] + radii[j];
6822
- const ca = centers[i];
6823
- const cb = centers[j];
6824
- if (Math.abs(ca[1] - cb[1]) > r || Math.abs(ca[2] - cb[2]) > r) continue;
6825
- const stacked = !a.round && !b.round && Math.abs(ca[1] - cb[1]) >= (this.halfHeight(a) + this.halfHeight(b)) * 0.9;
6826
- const onTop = this.onTopOf(b, a, new this.THREE.Vector3(...cb)) || this.onTopOf(a, b, new this.THREE.Vector3(...ca));
6827
- if (a.round || b.round) {
6828
- if (!stacked && !onTop) this.knock(a, b, ca, cb);
6829
- continue;
6830
- }
6831
- if (!this.partsOverlap(a, b)) continue;
6832
- this.boxImpact(a, b, ca, cb, dt);
6833
- this.separatePair(a, b, ca, cb, dt, stacked || onTop || this.restsOn(a, b, false) || this.restsOn(b, a, false));
6834
- }
6835
- }
6836
- this.applyPushes(dt);
6837
- }
6838
6251
  /**
6839
6252
  * Moves each piece by what its pairs put it apart this step (`pushes`), at most `SEPARATE_SPEED` along the ground and as much up: a chunk in five others is not pushed five
6840
6253
  * times as fast, and nothing is ever moved down (into what holds it). A piece still being put apart is moving, though its speed is nil: it does not fall asleep in the other.
@@ -6869,129 +6282,6 @@ var PieceSystem = class {
6869
6282
  last.push[2] = push[2];
6870
6283
  return last.share;
6871
6284
  }
6872
- /** The shape a piece meets others by (`ContactShape`), as it stands now: a round one a capsule round its axis, any other the boxes of its parts or its box. */
6873
- contactShape(b, c) {
6874
- const e = [...this.m.makeRotationFromQuaternion(b.root.quaternion).elements];
6875
- const round = b.round;
6876
- if (round) {
6877
- if (round.kind === "sphere") return { kind: "capsule", from: c, to: c, radius: round.radius };
6878
- const reach = Math.max(0, b.halfExtents[round.axis] - round.radius);
6879
- const k = round.axis * 4;
6880
- const d = [e[k] * reach, e[k + 1] * reach, e[k + 2] * reach];
6881
- return { kind: "capsule", from: [c[0] - d[0], c[1] - d[1], c[2] - d[2]], to: [c[0] + d[0], c[1] + d[1], c[2] + d[2]], radius: round.radius };
6882
- }
6883
- const parts = b.partBoxes ?? [{ center: [0, 0, 0], half: b.halfExtents }];
6884
- return {
6885
- kind: "boxes",
6886
- boxes: parts.map(squareBoxOf).map(({ center, half }) => ({
6887
- c: [c[0] + e[0] * center[0] + e[4] * center[1] + e[8] * center[2], c[1] + e[1] * center[0] + e[5] * center[1] + e[9] * center[2], c[2] + e[2] * center[0] + e[6] * center[1] + e[10] * center[2]],
6888
- e,
6889
- half
6890
- }))
6891
- };
6892
- }
6893
- /**
6894
- * Two pieces that met, one of them round: they are put apart along the normal (by their inverse masses) and, closing in, exchange an impulse
6895
- * j = -(1 + e) v_n / (1/m_a + 1/m_b + the turning of each), with the restitution e of their two materials, and the friction of their surfaces across it. The impulses are
6896
- * equal and opposite, so the momentum of the pair is kept. A held piece is not moved (the hand holds it); a sleeping one wakes when it is knocked.
6897
- */
6898
- knock(a, b, ca, cb) {
6899
- const hit = shapeContact(this.contactShape(a, ca), this.contactShape(b, cb));
6900
- if (!hit) return;
6901
- if (Math.abs(hit.normal[1]) > SLAM_FLOOR_NORMAL2) return;
6902
- this.impact({ a, b, ca, cb, hit, apart: true, above: 0 });
6903
- }
6904
- /**
6905
- * Two boxes that hit each other (a book falling on the top edge of one standing, a board swinging into a row): they exchange the impulse of `knock` at the point they meet,
6906
- * so the one hit turns about that point as well as moving, and a sleeping one wakes. Only a hit faster than `BOX_IMPACT_SPEED`, and no deeper than a contact: pieces resting on each other, or
6907
- * made inside each other, are left to `separatePair`, which holds or slides them without a kick.
6908
- */
6909
- boxImpact(a, b, ca, cb, dt) {
6910
- const hit = shapeContact(this.contactShape(a, ca), this.contactShape(b, cb));
6911
- if (!hit) return;
6912
- const n = hit.normal;
6913
- const va = a.velocity;
6914
- const vb = b.velocity;
6915
- const closing = (va[0] - vb[0]) * n[0] + (va[1] - vb[1]) * n[1] + (va[2] - vb[2]) * n[2];
6916
- if (hit.depth > LIFT_DEPTH + 2 * Math.max(0, -closing) * dt) return;
6917
- this.impact({ a, b, ca, cb, hit, apart: false, above: BOX_IMPACT_SPEED });
6918
- }
6919
- /** The impulse two pieces that met exchange (`knock`), put apart first when `apart`, and only when they close faster than `above` (m/s). */
6920
- impact({ a, b, ca, cb, hit, apart: apart2, above }) {
6921
- const n = hit.normal;
6922
- const ra = [hit.point[0] - ca[0], hit.point[1] - ca[1], hit.point[2] - ca[2]];
6923
- const rb = [hit.point[0] - cb[0], hit.point[1] - cb[1], hit.point[2] - cb[2]];
6924
- const pointV = (body, r) => {
6925
- const v2 = body.velocity;
6926
- const w = body.angularVelocity;
6927
- return [v2[0] + w[1] * r[2] - w[2] * r[1], v2[1] + w[2] * r[0] - w[0] * r[2], v2[2] + w[0] * r[1] - w[1] * r[0]];
6928
- };
6929
- const relative = () => {
6930
- const va = pointV(a, ra);
6931
- const vb = pointV(b, rb);
6932
- return [va[0] - vb[0], va[1] - vb[1], va[2] - vb[2]];
6933
- };
6934
- const vn0 = relative();
6935
- const closing = vn0[0] * n[0] + vn0[1] * n[1] + vn0[2] * n[2];
6936
- if (closing >= -above) return;
6937
- const wake = (body) => {
6938
- body.sleeping = false;
6939
- body.still = 0;
6940
- body.calmAt = null;
6941
- };
6942
- if (closing < -WAKE_ABOVE_SPEED) {
6943
- if (a.sleeping) wake(a);
6944
- if (b.sleeping) wake(b);
6945
- }
6946
- const ima = a.held || a.sleeping ? 0 : 1 / a.mass;
6947
- const imb = b.held || b.sleeping ? 0 : 1 / b.mass;
6948
- if (ima + imb === 0) return;
6949
- const ea = [...this.m.makeRotationFromQuaternion(a.root.quaternion).elements];
6950
- const eb = [...this.m.makeRotationFromQuaternion(b.root.quaternion).elements];
6951
- const flat = Math.hypot(n[0], n[2]);
6952
- const out = flat > KNOCK_FLAT ? [n[0] / flat, 0, n[2] / flat] : n;
6953
- const depth = Math.max(0, hit.depth - SLOP) / (flat > KNOCK_FLAT ? flat : 1);
6954
- for (const [body, share, sign] of [[a, ima, 1], [b, imb, -1]]) {
6955
- if (share === 0 || !apart2) continue;
6956
- const move = depth * share * sign / (ima + imb);
6957
- body.root.position.x += out[0] * move;
6958
- body.root.position.y += out[1] * move;
6959
- body.root.position.z += out[2] * move;
6960
- }
6961
- if (closing >= 0) return;
6962
- const turning = (body, e, r, d) => {
6963
- const t2 = this.mulInvInertiaWith(body, e, r[1] * d[2] - r[2] * d[1], r[2] * d[0] - r[0] * d[2], r[0] * d[1] - r[1] * d[0]);
6964
- return (t2[1] * r[2] - t2[2] * r[1]) * d[0] + (t2[2] * r[0] - t2[0] * r[2]) * d[1] + (t2[0] * r[1] - t2[1] * r[0]) * d[2];
6965
- };
6966
- const resist = (d) => ima + imb + (ima > 0 ? turning(a, ea, ra, d) : 0) + (imb > 0 ? turning(b, eb, rb, d) : 0);
6967
- const give = (j2) => {
6968
- if (ima > 0) {
6969
- for (let i = 0; i < 3; i++) a.velocity[i] += j2[i] * ima;
6970
- const dw = this.mulInvInertiaWith(a, ea, ra[1] * j2[2] - ra[2] * j2[1], ra[2] * j2[0] - ra[0] * j2[2], ra[0] * j2[1] - ra[1] * j2[0]);
6971
- for (let i = 0; i < 3; i++) a.angularVelocity[i] += dw[i];
6972
- }
6973
- if (imb > 0) {
6974
- for (let i = 0; i < 3; i++) b.velocity[i] -= j2[i] * imb;
6975
- const dw = this.mulInvInertiaWith(b, eb, rb[1] * j2[2] - rb[2] * j2[1], rb[2] * j2[0] - rb[0] * j2[2], rb[0] * j2[1] - rb[1] * j2[0]);
6976
- for (let i = 0; i < 3; i++) b.angularVelocity[i] -= dw[i];
6977
- }
6978
- };
6979
- const bounce = apart2 && -closing > BOUNCE_MIN_SPEED ? pairRestitution(a.restitution, b.restitution) : 0;
6980
- const j = -(1 + bounce) * closing / resist(n);
6981
- give([n[0] * j, n[1] * j, n[2] * j]);
6982
- const v = relative();
6983
- const vn = v[0] * n[0] + v[1] * n[1] + v[2] * n[2];
6984
- const vt = [v[0] - vn * n[0], v[1] - vn * n[1], v[2] - vn * n[2]];
6985
- const slide = Math.hypot(vt[0], vt[1], vt[2]);
6986
- if (slide < 1e-6) return;
6987
- const t = [vt[0] / slide, vt[1] / slide, vt[2] / slide];
6988
- const jt = Math.min(slide / resist(t), pairFriction(a.friction, b.friction ?? null).dynamic * j);
6989
- give([-t[0] * jt, -t[1] * jt, -t[2] * jt]);
6990
- if (-closing >= SLAM_MIN_SPEED2 && this.time - Math.max(a.lastHit, b.lastHit) > 0.15) {
6991
- a.lastHit = b.lastHit = this.time;
6992
- this.o.onKnock?.(a, b, hit.point, -closing);
6993
- }
6994
- }
6995
6285
  /** Whether a part of `a` and a part of `b` (their boxes of the step, as world-aligned boxes around them) overlap. */
6996
6286
  partsOverlap(a, b) {
6997
6287
  for (const pa of this.surfacesOf.get(a) ?? []) {
@@ -7003,66 +6293,6 @@ var PieceSystem = class {
7003
6293
  }
7004
6294
  return false;
7005
6295
  }
7006
- /**
7007
- * Two boxes overlapping, put apart by their separating axes (`shapeContact`); a held or sleeping piece is not moved. The move (`SEPARATE_SHARE` of the overlap less `SLOP`) is
7008
- * summed into `pushes` and bounded per piece in `applyPushes`.
7009
- * - Side by side (a normal at least `KNOCK_FLAT` level): apart along the ground only, as in `knock`, split by their inverse masses; the speed they close in with stops.
7010
- * - One over the other as deep as a contact (`LIFT_DEPTH` and what the closing speed sank them this step): left alone when `resting` (stacked, on a top, leaning on a
7011
- * part: its support holds it); else only the upper rises, held up by the lower (`propped`), and its point in the lower stops sinking (`contactImpulse`): never a kick up.
7012
- * - One over the other deeper than that: they were made inside each other (chunks of one wall), or stand on one floor side by side. Lifting the upper out would give it
7013
- * m g d nothing supplied (a 3 m chunk climbing 5 m through a pile), so they slide apart along the ground by their least level overlaps (`boxesApartAlongGround`).
7014
- */
7015
- separatePair(a, b, ca, cb, dt, resting) {
7016
- const sa = this.contactShape(a, ca);
7017
- const sb = this.contactShape(b, cb);
7018
- const hit = shapeContact(sa, sb);
7019
- if (!hit) return;
7020
- const ima = a.held || a.sleeping ? 0 : 1 / a.mass;
7021
- const imb = b.held || b.sleeping ? 0 : 1 / b.mass;
7022
- if (ima + imb === 0) return;
7023
- if (Math.hypot(hit.normal[0], hit.normal[2]) > KNOCK_FLAT) {
7024
- this.slideApart(a, b, ima, imb, levelBoxesApart(sa, sb) ?? hit);
7025
- return;
7026
- }
7027
- const n = hit.normal;
7028
- const va = a.velocity;
7029
- const vb = b.velocity;
7030
- const contact = LIFT_DEPTH + Math.max(0, -((va[0] - vb[0]) * n[0] + (va[1] - vb[1]) * n[1] + (va[2] - vb[2]) * n[2])) * dt;
7031
- if (hit.depth > contact) {
7032
- const level = boxesApartAlongGround(sa, sb);
7033
- if (level) this.slideApart(a, b, ima, imb, level);
7034
- return;
7035
- }
7036
- if (resting) return;
7037
- const [upper, c, up] = n[1] > 0 ? [a, ca, n] : [b, cb, [-n[0], -n[1], -n[2]]];
7038
- if (upper.held || upper.sleeping) return;
7039
- const otherCentre = upper === a ? cb : ca;
7040
- if (c[1] < otherCentre[1] - SLOP) {
7041
- const level = boxesApartAlongGround(sa, sb);
7042
- if (level) this.slideApart(a, b, ima, imb, level);
7043
- return;
7044
- }
7045
- upper.propped = up;
7046
- const e = this.m.makeRotationFromQuaternion(upper.root.quaternion).elements;
7047
- const r = [hit.point[0] - c[0], hit.point[1] - c[1], hit.point[2] - c[2]];
7048
- upper.proppedAt = r;
7049
- const turn2 = this.mulInvInertiaWith(upper, e, r[1] * up[2] - r[2] * up[1], r[2] * up[0] - r[0] * up[2], r[0] * up[1] - r[1] * up[0]);
7050
- const angular = (turn2[1] * r[2] - turn2[2] * r[1]) * up[0] + (turn2[2] * r[0] - turn2[0] * r[2]) * up[1] + (turn2[0] * r[1] - turn2[1] * r[0]) * up[2];
7051
- const lift = SEPARATE_SHARE * Math.max(0, hit.depth - SLOP) / (1 + angular * upper.mass);
7052
- const push = this.pushes.get(upper) ?? [0, 0, 0];
7053
- for (let i = 0; i < 3; i++) push[i] = Math.abs(up[i] * lift) > Math.abs(push[i]) ? up[i] * lift : push[i];
7054
- this.pushes.set(upper, push);
7055
- this.turnAboutCentre(upper, c, [turn2[0] * lift * upper.mass, turn2[1] * lift * upper.mass, turn2[2] * lift * upper.mass]);
7056
- this.contactImpulse(upper, e, r, up, 0);
7057
- }
7058
- /** Turns a piece by the rotation vector `by` (rad) about its centre `c`, which stays where it is. */
7059
- turnAboutCentre(b, c, by) {
7060
- const angle = Math.hypot(by[0], by[1], by[2]);
7061
- if (angle < 1e-9) return;
7062
- b.root.quaternion.premultiply(this.dq.setFromAxisAngle(this.ax.set(by[0] / angle, by[1] / angle, by[2] / angle), angle)).normalize();
7063
- const off2 = this.ax.copy(b.centerV).applyQuaternion(b.root.quaternion);
7064
- b.root.position.set(c[0] - off2.x, c[1] - off2.y, c[2] - off2.z);
7065
- }
7066
6296
  /** Two boxes put apart along the ground by `hit` (its normal from `b` to `a`, laid level), split by their inverse masses; the speed they close in with along it stops. */
7067
6297
  slideApart(a, b, ima, imb, hit) {
7068
6298
  const n = hit.normal;
@@ -7084,12 +6314,6 @@ var PieceSystem = class {
7084
6314
  }
7085
6315
  }
7086
6316
  };
7087
- function solve3(k, rhs) {
7088
- const det = (a, b, c) => a[0] * (b[1] * c[2] - b[2] * c[1]) - b[0] * (a[1] * c[2] - a[2] * c[1]) + c[0] * (a[1] * b[2] - a[2] * b[1]);
7089
- const d = det(k[0], k[1], k[2]);
7090
- if (Math.abs(d) < 1e-12) return null;
7091
- return [det(rhs, k[1], k[2]) / d, det(k[0], rhs, k[2]) / d, det(k[0], k[1], rhs) / d];
7092
- }
7093
6317
 
7094
6318
  // src/rebar.ts
7095
6319
  var RebarCages = class {
@@ -7454,7 +6678,6 @@ var CRATER_DEPTH = 0.3;
7454
6678
  var CRATER_RADIUS = 2.5;
7455
6679
  var ORIGIN = [4e3, 0, 4e3];
7456
6680
  var warmed = /* @__PURE__ */ new WeakSet();
7457
- var OWN_SOLVER = {};
7458
6681
  var brickWall = (THREE) => {
7459
6682
  const parts = [];
7460
6683
  const geometries = [];
@@ -7484,7 +6707,7 @@ var brickWall = (THREE) => {
7484
6707
  merged.setIndex(index);
7485
6708
  return { parts, joints: inferJoints2(parts), mesh: new THREE.Mesh(merged, new THREE.MeshStandardMaterial()), ranges };
7486
6709
  };
7487
- var runScene = (THREE, makeRenderer, options) => {
6710
+ var runScene = (THREE, makeRenderer, engine, worldDesc) => {
7488
6711
  const scene2 = new THREE.Scene();
7489
6712
  const world = createDestruction();
7490
6713
  const vfx = createVfx({});
@@ -7494,12 +6717,12 @@ var runScene = (THREE, makeRenderer, options) => {
7494
6717
  let renderer;
7495
6718
  let bound;
7496
6719
  try {
7497
- engineWorld = options.engine?.createWorld(options.world ?? KIT_WORLD);
7498
- const loop = engineWorld ? createPhysicsLoop2(engineWorld) : void 0;
6720
+ engineWorld = engine.createWorld(worldDesc ?? KIT_WORLD);
6721
+ const loop = createPhysicsLoop2(engineWorld);
7499
6722
  const terrainGridAt = (xs, zs, out) => {
7500
6723
  for (let j = 0; j < zs.length; j++) for (let i = 0; i < xs.length; i++) out[j * xs.length + i] = terrainAt(xs[i], zs[j]);
7501
6724
  };
7502
- renderer = makeRenderer({ physics: loop ?? "own", scene: scene2, world, vfx, eventBudgetMs: Infinity, groundAt: terrainAt, terrainAt, terrainGridAt, jitWarmUp: false });
6725
+ renderer = makeRenderer({ physics: loop, scene: scene2, world, vfx, eventBudgetMs: Infinity, groundAt: terrainAt, terrainAt, terrainGridAt, jitWarmUp: false });
7503
6726
  const wall = brickWall(THREE);
7504
6727
  const root = new THREE.Group();
7505
6728
  root.position.set(...ORIGIN);
@@ -7526,7 +6749,7 @@ var blastAndRun = ({ world, loop, renderer, onCrater }) => {
7526
6749
  renderer.wakeRegion(point[0], point[2], CRATER_RADIUS);
7527
6750
  for (let frame = 0; frame < FRAMES; frame++) {
7528
6751
  world.update(FRAME_SECONDS);
7529
- loop?.step(FRAME_SECONDS);
6752
+ loop.step(FRAME_SECONDS);
7530
6753
  renderer.update(FRAME_SECONDS);
7531
6754
  const stats = renderer.stats();
7532
6755
  seen.pieces = Math.max(seen.pieces, stats.pieces);
@@ -7535,10 +6758,10 @@ var blastAndRun = ({ world, loop, renderer, onCrater }) => {
7535
6758
  return seen;
7536
6759
  };
7537
6760
  var warmUpDestructionJit = (THREE, makeRenderer, options = {}) => {
7538
- const key = options.engine ?? OWN_SOLVER;
7539
- if (warmed.has(key)) return void 0;
7540
- warmed.add(key);
7541
- return runScene(THREE, makeRenderer, options);
6761
+ const { engine } = options;
6762
+ if (!engine || warmed.has(engine)) return void 0;
6763
+ warmed.add(engine);
6764
+ return runScene(THREE, makeRenderer, engine, options.world);
7542
6765
  };
7543
6766
 
7544
6767
  // src/visual.ts
@@ -7560,10 +6783,10 @@ function bendPositions(positions, from, to, point, axis, side, angle, radius) {
7560
6783
  const turn2 = angle * share * share * (3 - 2 * share);
7561
6784
  const cos = Math.cos(turn2);
7562
6785
  const sin = Math.sin(turn2);
7563
- const dot2 = kx * rx + ky * ry + kz * rz;
7564
- positions[i] = point[0] + rx * cos + (ky * rz - kz * ry) * sin + kx * dot2 * (1 - cos);
7565
- positions[i + 1] = point[1] + ry * cos + (kz * rx - kx * rz) * sin + ky * dot2 * (1 - cos);
7566
- positions[i + 2] = point[2] + rz * cos + (kx * ry - ky * rx) * sin + kz * dot2 * (1 - cos);
6786
+ const dot3 = kx * rx + ky * ry + kz * rz;
6787
+ positions[i] = point[0] + rx * cos + (ky * rz - kz * ry) * sin + kx * dot3 * (1 - cos);
6788
+ positions[i + 1] = point[1] + ry * cos + (kz * rx - kx * rz) * sin + ky * dot3 * (1 - cos);
6789
+ positions[i + 2] = point[2] + rz * cos + (kx * ry - ky * rx) * sin + kz * dot3 * (1 - cos);
7567
6790
  }
7568
6791
  }
7569
6792
 
@@ -7732,9 +6955,9 @@ var MeshRayProbe = class {
7732
6955
  const grown = new Uint32Array(size);
7733
6956
  grown.set(this.candidates);
7734
6957
  this.candidates = grown;
7735
- const numbers = new Uint32Array(Math.max(this.triangles.length, Math.ceil(size / 3)));
7736
- numbers.set(this.triangles);
7737
- this.triangles = numbers;
6958
+ const numbers2 = new Uint32Array(Math.max(this.triangles.length, Math.ceil(size / 3)));
6959
+ numbers2.set(this.triangles);
6960
+ this.triangles = numbers2;
7738
6961
  this.candidateIndex = new this.THREE.BufferAttribute(this.candidates, 1);
7739
6962
  }
7740
6963
  };
@@ -9329,6 +8552,9 @@ var COLLAPSE_CLOUD_KG = 1e3;
9329
8552
  var REBAR_COLOR = 7628380;
9330
8553
  var STEEL_DENSITY = 7850;
9331
8554
  var CHIP_DECAL_EDGE = 0.05;
8555
+ var CHIP_GAP_REACH = 0.03;
8556
+ var CHIP_GAP_SHADE = 0.4;
8557
+ var CHIP_GAP_WIDTH = 1.15;
9332
8558
  var CRATER_RADIUS2 = 2.5;
9333
8559
  var CRATER_MIN_RADIUS = 0.012;
9334
8560
  var CRATER_LIGHTEN = 0.12;
@@ -9360,10 +8586,71 @@ var HINGE_STILL_SPEED = 0.2;
9360
8586
  var HINGE_STILL_SPIN = 0.5;
9361
8587
  var PREFIT_SLICE_MS = 1;
9362
8588
  var CONTACT_MESHES = 12;
9363
- var PART_BOX_MESHES = 64;
8589
+ var PART_BOX_MESHES = 96;
9364
8590
  var ROUND_SAMPLES = 400;
9365
- var ROUND_SIDES = 0.12;
8591
+ var ROUND_SIDES2 = 0.12;
9366
8592
  var ROUND_SLACK = 1.12;
8593
+ var ROUND_FILL = 0.9;
8594
+ var FILL_GRID = 8;
8595
+ var hullRadiusAt = (profile, radius, at) => {
8596
+ if (!profile || profile.length < 2) return radius;
8597
+ const hull = [];
8598
+ for (const point of profile) {
8599
+ while (hull.length >= 2) {
8600
+ const [a, ra] = hull[hull.length - 2];
8601
+ const [b, rb] = hull[hull.length - 1];
8602
+ if ((b - a) * (point[1] - ra) - (rb - ra) * (point[0] - a) >= 0) hull.pop();
8603
+ else break;
8604
+ }
8605
+ hull.push(point);
8606
+ }
8607
+ if (at <= hull[0][0]) return hull[0][1];
8608
+ for (let i = 1; i < hull.length; i++) {
8609
+ const [a, ra] = hull[i - 1];
8610
+ const [b, rb] = hull[i];
8611
+ if (at <= b) return ra + (rb - ra) * (at - a) / (b - a || 1);
8612
+ }
8613
+ return hull[hull.length - 1][1];
8614
+ };
8615
+ var insideDrawn = (mesh, built, x, y, z) => {
8616
+ if (built) {
8617
+ for (const solid of built) {
8618
+ const [qx, qy, qz, qw] = solid.rotation;
8619
+ const px = x - solid.center[0], py = y - solid.center[1], pz = z - solid.center[2];
8620
+ const tx = 2 * (-qy * pz + qz * py), ty = 2 * (-qz * px + qx * pz), tz = 2 * (-qx * py + qy * px);
8621
+ const lx = px + qw * tx - qy * tz + qz * ty, ly = py + qw * ty - qz * tx + qx * tz, lz = pz + qw * tz - qx * ty + qy * tx;
8622
+ const [hx, hy, hz] = solid.half;
8623
+ if (solid.kind === "cylinder" || solid.kind === "cone") {
8624
+ if (Math.abs(ly) <= hy && (lx / hx) ** 2 + (lz / hz) ** 2 <= 1) return true;
8625
+ } else if (solid.kind === "sphere") {
8626
+ if ((lx / hx) ** 2 + (ly / hy) ** 2 + (lz / hz) ** 2 <= 1) return true;
8627
+ } else if (Math.abs(lx) <= hx && Math.abs(ly) <= hy && Math.abs(lz) <= hz) return true;
8628
+ }
8629
+ return false;
8630
+ }
8631
+ const geometry = mesh.geometry;
8632
+ const p = geometry.parameters ?? {};
8633
+ const n = (key, fallback) => typeof p[key] === "number" ? p[key] : fallback;
8634
+ switch (geometry.type) {
8635
+ case "BoxGeometry":
8636
+ return Math.abs(x) <= n("width", 1) / 2 && Math.abs(y) <= n("height", 1) / 2 && Math.abs(z) <= n("depth", 1) / 2;
8637
+ case "CylinderGeometry":
8638
+ case "ConeGeometry": {
8639
+ const h = n("height", 1) / 2;
8640
+ if (Math.abs(y) > h || p.openEnded === true) return false;
8641
+ const top = geometry.type === "ConeGeometry" ? 0 : n("radiusTop", 1);
8642
+ const bottom = geometry.type === "ConeGeometry" ? n("radius", 1) : n("radiusBottom", 1);
8643
+ return Math.hypot(x, z) <= bottom + (top - bottom) * (y + h) / (2 * h || 1);
8644
+ }
8645
+ case "SphereGeometry":
8646
+ return Math.hypot(x, y, z) <= n("radius", 1);
8647
+ default: {
8648
+ if (!geometry.boundingBox) geometry.computeBoundingBox();
8649
+ const box = geometry.boundingBox;
8650
+ return !!box && x >= box.min.x && x <= box.max.x && y >= box.min.y && y <= box.max.y && z >= box.min.z && z <= box.max.z;
8651
+ }
8652
+ }
8653
+ };
9367
8654
  var RIM_POINTS = 12;
9368
8655
  var rimPoints = (round, half) => {
9369
8656
  const out = [];
@@ -9421,6 +8708,16 @@ var profileOf = (points, axis, half, radius) => {
9421
8708
  };
9422
8709
  var BROKEN_GAP = 0.03;
9423
8710
  var BROKEN_SAMPLES = [[0.5, 0.5], [0.1, 0.1], [0.9, 0.1], [0.1, 0.9], [0.9, 0.9]];
8711
+ var UNDERMINED_MAX = 64;
8712
+ var UNDERMINED_RIM = 0.04;
8713
+ var UNDERMINED_RIM_DROP = 0.05;
8714
+ var UNDERMINED_RIM_RISE = 0.1;
8715
+ var UNDERMINED_STAND = 0.4;
8716
+ var UNDERMINED_KEEP = 0.6;
8717
+ var SOLIDS_MAX = 64;
8718
+ var UNDERMINED_PUSH = 0.6;
8719
+ var UNDERMINED_STILL = 0.05;
8720
+ var SOLID_WELD = 1e-4;
9424
8721
  var UNCHECKED_KINDS = /* @__PURE__ */ new Set(["structure", "room", "ground"]);
9425
8722
  var FIRE_CEILING_SECONDS = 3600;
9426
8723
  var GENERIC_REFERENCE_RADIUS = 15;
@@ -9531,7 +8828,7 @@ var Renderer = class {
9531
8828
  __publicField(this, "blastDebris");
9532
8829
  __publicField(this, "blastWakes");
9533
8830
  __publicField(this, "costMeter");
9534
- /** The step cost the debris policy reads this frame (`debrisCost`), null when there is none (the kit's own solver, or `fixed`). */
8831
+ /** The step cost the debris policy reads this frame (`debrisCost`), null when there is none (`fixed`). */
9535
8832
  __publicField(this, "cost", null);
9536
8833
  __publicField(this, "costFrame", 0);
9537
8834
  /** The pieces faded away (`faded`): their root shrinks, then leaves the scene. */
@@ -9542,6 +8839,9 @@ var Renderer = class {
9542
8839
  __publicField(this, "staticBoxes", /* @__PURE__ */ new Map());
9543
8840
  /** `staticSolids` per object, kept until `staticNow` measures the object again for a reason. */
9544
8841
  __publicField(this, "solidCache", /* @__PURE__ */ new Map());
8842
+ /** The fixed bodies a host module gives that are no bound object (`setHostSolids`), and the list last made of each: the same numbers keep the same list. */
8843
+ __publicField(this, "hostSolids", /* @__PURE__ */ new Map());
8844
+ __publicField(this, "hostSolidLists", /* @__PURE__ */ new Map());
9545
8845
  /** The objects whose last `staticSolids` list is not all of what a ray can hit: measured in part, or with a loose or hidden part left out. */
9546
8846
  __publicField(this, "unsureSolids", /* @__PURE__ */ new Set());
9547
8847
  /** The objects `staticNow` measured again for a reason (an event, a moved root, boxes that changed): their `staticSolids` are measured again too. */
@@ -9565,6 +8865,8 @@ var Renderer = class {
9565
8865
  __publicField(this, "pieceBoxes", /* @__PURE__ */ new WeakMap());
9566
8866
  /** Objects broken since the last update: `checkBroken` looks at what is left of them. */
9567
8867
  __publicField(this, "broken", /* @__PURE__ */ new Set());
8868
+ /** Discs of ground that changed since the last update (`wakeRegion`): `checkUndermined` looks at what stood on them. */
8869
+ __publicField(this, "undermined", []);
9568
8870
  __publicField(this, "staticAt", 0);
9569
8871
  __publicField(this, "queue", []);
9570
8872
  /** The cover of each body around a part of the world that went off, read as the event is emitted: before the blast tore or moved anything. */
@@ -9945,8 +9247,7 @@ var Renderer = class {
9945
9247
  }
9946
9248
  if (total.isEmpty()) return { half: [0.25, 0.25, 0.25], center: new this.THREE.Vector3() };
9947
9249
  const size = total.getSize(new this.THREE.Vector3());
9948
- const least = minPieceHalf(this.o.physics);
9949
- return { half: [Math.max(least, size.x / 2), Math.max(least, size.y / 2), Math.max(least, size.z / 2)], center: total.getCenter(new this.THREE.Vector3()) };
9250
+ return { half: [Math.max(MIN_PIECE_HALF, size.x / 2), Math.max(MIN_PIECE_HALF, size.y / 2), Math.max(MIN_PIECE_HALF, size.z / 2)], center: total.getCenter(new this.THREE.Vector3()) };
9950
9251
  }
9951
9252
  /**
9952
9253
  * A hosted body's boxes (`hostedSolids`: its damage zones) cut to the box of what its root draws, in the root's frame: the zones reach past the drawn body (17 cm each
@@ -10137,8 +9438,8 @@ var Renderer = class {
10137
9438
  mv.mesh.updateWorldMatrix(true, false);
10138
9439
  m4.multiplyMatrices(inv, mv.mesh.matrixWorld);
10139
9440
  const stride = Math.max(1, Math.floor(pos.count / ROUND_SAMPLES));
10140
- for (let i = 0; i < pos.count; i += stride) {
10141
- p.fromBufferAttribute(pos, i).applyMatrix4(m4);
9441
+ for (let i2 = 0; i2 < pos.count; i2 += stride) {
9442
+ p.fromBufferAttribute(pos, i2).applyMatrix4(m4);
10142
9443
  points.push([p.x - cx, p.y - cy, p.z - cz]);
10143
9444
  }
10144
9445
  }
@@ -10146,22 +9447,64 @@ var Renderer = class {
10146
9447
  const drawn = new Float64Array(3);
10147
9448
  for (const q of points) for (let k = 0; k < 3; k++) drawn[k] = Math.max(drawn[k], Math.abs(q[k]));
10148
9449
  const fits = (axis2) => {
10149
- const [i, j] = axis2 === 0 ? [1, 2] : axis2 === 1 ? [0, 2] : [0, 1];
10150
- if (Math.abs(half[i] - half[j]) > ROUND_SIDES * Math.max(half[i], half[j])) return null;
10151
- if (Math.abs(drawn[i] - drawn[j]) > ROUND_SIDES * Math.max(drawn[i], drawn[j])) return null;
10152
- const reach = (drawn[i] + drawn[j]) / 2;
10153
- for (const q of points) if (Math.hypot(q[i], q[j]) > reach * ROUND_SLACK) return null;
10154
- return (half[i] + half[j]) / 2;
9450
+ const [i2, j2] = axis2 === 0 ? [1, 2] : axis2 === 1 ? [0, 2] : [0, 1];
9451
+ if (Math.abs(half[i2] - half[j2]) > ROUND_SIDES2 * Math.max(half[i2], half[j2])) return null;
9452
+ if (Math.abs(drawn[i2] - drawn[j2]) > ROUND_SIDES2 * Math.max(drawn[i2], drawn[j2])) return null;
9453
+ const reach = (drawn[i2] + drawn[j2]) / 2;
9454
+ for (const q of points) if (Math.hypot(q[i2], q[j2]) > reach * ROUND_SLACK) return null;
9455
+ return (half[i2] + half[j2]) / 2;
10155
9456
  };
10156
9457
  const radii = [0, 1, 2].map(fits);
10157
9458
  if (radii.every((r) => r !== null)) {
10158
9459
  const radius2 = (half[0] + half[1] + half[2]) / 3;
9460
+ if (this.drawnShareOf(b, body, (q) => Math.hypot(q[0], q[1], q[2]) <= radius2) < ROUND_FILL) return null;
10159
9461
  return { kind: "sphere", axis: 1, radius: radius2, inertia: body.inertiaGiven ?? this.inertiaOf(b, body, "sphere", 1, radius2) };
10160
9462
  }
10161
9463
  const axis = [0, 1, 2].find((k) => radii[k] !== null);
10162
9464
  if (axis === void 0) return null;
10163
9465
  const radius = radii[axis] ?? 0;
10164
- return { kind: "cylinder", axis, radius, inertia: body.inertiaGiven ?? this.inertiaOf(b, body, "cylinder", axis, radius), profile: profileOf(points, axis, half[axis], radius) };
9466
+ const profile = profileOf(points, axis, half[axis], radius);
9467
+ const [i, j] = axis === 0 ? [1, 2] : axis === 1 ? [0, 2] : [0, 1];
9468
+ if (this.drawnShareOf(b, body, (q) => Math.abs(q[axis]) <= half[axis] && Math.hypot(q[i], q[j]) <= hullRadiusAt(profile, radius, q[axis])) < ROUND_FILL) return null;
9469
+ return { kind: "cylinder", axis, radius, inertia: body.inertiaGiven ?? this.inertiaOf(b, body, "cylinder", axis, radius), profile };
9470
+ }
9471
+ /** The vertices of a mesh about the centre of its box (`lb`, its own space), scaled as it is drawn: the points of the hull the engine holds it by (`PartBox.hull`). */
9472
+ hullOf(mv, lb, scale) {
9473
+ const own = [];
9474
+ this.visuals.rangePoints(mv, new this.THREE.Matrix4(), own);
9475
+ const c = lb.getCenter(new this.THREE.Vector3());
9476
+ const out = [];
9477
+ for (let i = 0; i < own.length; i += 3) out.push((own[i] - c.x) * Math.abs(scale.x), (own[i + 1] - c.y) * Math.abs(scale.y), (own[i + 2] - c.z) * Math.abs(scale.z));
9478
+ return out;
9479
+ }
9480
+ /**
9481
+ * The share of a round body the engine would hold (`inside`: a point from the piece's centre of mass) that is drawn: a grid of points through its box (`FILL_GRID`), those
9482
+ * inside the body, and of them those inside a primitive of the piece (`insideDrawn`). Primitives that overlap count once (a lamp's glow over its shade).
9483
+ */
9484
+ drawnShareOf(b, body, inside) {
9485
+ const inv = specFrameInverse(this.THREE, b.root);
9486
+ const meshes = this.meshesOf(b).filter((mv) => this.visuals.shown(mv) && !mv.host).map((mv) => {
9487
+ mv.mesh.updateWorldMatrix(true, false);
9488
+ return { mesh: mv.mesh, built: builtSolidsOf(mv.mesh), back: new this.THREE.Matrix4().multiplyMatrices(inv, mv.mesh.matrixWorld).invert() };
9489
+ });
9490
+ const [cx, cy, cz] = body.localCenter;
9491
+ const half = body.halfExtents;
9492
+ const p = new this.THREE.Vector3();
9493
+ let shape = 0;
9494
+ let drawn = 0;
9495
+ for (let a = 0; a < FILL_GRID; a++) for (let c = 0; c < FILL_GRID; c++) for (let d = 0; d < FILL_GRID; d++) {
9496
+ const q = [half[0] * ((a + 0.5) / FILL_GRID * 2 - 1), half[1] * ((c + 0.5) / FILL_GRID * 2 - 1), half[2] * ((d + 0.5) / FILL_GRID * 2 - 1)];
9497
+ if (!inside(q)) continue;
9498
+ shape++;
9499
+ for (const m of meshes) {
9500
+ p.set(q[0] + cx, q[1] + cy, q[2] + cz).applyMatrix4(m.back);
9501
+ if (insideDrawn(m.mesh, m.built, p.x, p.y, p.z)) {
9502
+ drawn++;
9503
+ break;
9504
+ }
9505
+ }
9506
+ }
9507
+ return shape === 0 ? 1 : drawn / shape;
10165
9508
  }
10166
9509
  pieces() {
10167
9510
  return [...this.pieceSys.list];
@@ -10251,6 +9594,7 @@ var Renderer = class {
10251
9594
  this.work?.beginFrame();
10252
9595
  if (!this.attached) this.drainQueue();
10253
9596
  this.checkBroken();
9597
+ this.checkUndermined();
10254
9598
  for (const b of this.bounds.values()) b.onFrame?.(dt);
10255
9599
  for (const b of this.bounds.values()) if (b.soilNode && this.world.state(b.id)?.soil?.status === "yielding") this.onSettle(b.id);
10256
9600
  this.settlement.update(dt);
@@ -10640,8 +9984,28 @@ var Renderer = class {
10640
9984
  } finally {
10641
9985
  this.measuredMeshes.clear();
10642
9986
  }
9987
+ for (const [id, source] of this.hostSolids) out.set(id, this.hostSolidsOf(id, source()));
10643
9988
  return out;
10644
9989
  }
9990
+ setHostSolids(id, source) {
9991
+ if (source) this.hostSolids.set(id, source);
9992
+ else {
9993
+ this.hostSolids.delete(id);
9994
+ this.hostSolidLists.delete(id);
9995
+ }
9996
+ }
9997
+ /** The module's boxes as static solids: measured again to the same numbers, the list is the one held (an engine finds it unchanged by identity). */
9998
+ hostSolidsOf(id, given) {
9999
+ const kept = this.hostSolidLists.get(id);
10000
+ if (kept && kept.given.length === given.length && given.every((s, i) => s === kept.given[i])) return kept.solids;
10001
+ const next = given.map((s, i) => ({ center: [s.center[0], s.center[1], s.center[2]], half: [s.half[0], s.half[1], s.half[2]], rotation: s.rotation ? [s.rotation[0], s.rotation[1], s.rotation[2], s.rotation[3]] : [0, 0, 0, 1], key: s.key ?? String(i) }));
10002
+ if (kept && sameSolids(kept.solids, next)) {
10003
+ this.hostSolidLists.set(id, { given, solids: kept.solids });
10004
+ return kept.solids;
10005
+ }
10006
+ this.hostSolidLists.set(id, { given, solids: next });
10007
+ return next;
10008
+ }
10645
10009
  /** `staticSolids` for each fixed object of `now`, into `out`. */
10646
10010
  measureEach(now, budget, out) {
10647
10011
  for (const id of now.keys()) {
@@ -11289,9 +10653,33 @@ var Renderer = class {
11289
10653
  const rotation = new T.Quaternion(ev.rotation[0], ev.rotation[1], ev.rotation[2], ev.rotation[3]);
11290
10654
  for (const part of this.bounds.get(ev.object)?.parts.values() ?? []) for (const mv of part.meshes) this.visuals.clearDecals(mv, center, half, rotation);
11291
10655
  this.vfx.peekWorkshop()?.decals.clearInside(ev.center, [half.x, half.y, half.z], ev.rotation);
10656
+ if (pv) this.drawChipGap(pv, ev, center, rotation);
11292
10657
  this.vfx.burst("dust", ev.center, [0, 1, 0], ev.units ? Math.min(40, 8 + ev.units.length) : 8, ev.units ? 1.6 : 0.8, { color });
11293
10658
  this.impactSound(pv?.material ?? "", ev.center, 0.7, ev.blow);
11294
10659
  }
10660
+ /**
10661
+ * The gap a unit leaves in an object the renderer draws whole (a concrete pole, a block, a post): on each outer face the unit reached, the broken inside of its material,
10662
+ * as wide as the unit there, so the bars it bared show in a hole and not on a smooth face. A drawing that cuts its own gaps (the house's breach, `drawnSpalls`) takes none.
10663
+ */
10664
+ drawChipGap(pv, ev, center, rotation) {
10665
+ const mv = this.nearestMesh(pv, center);
10666
+ if (!mv || mv.mesh.userData.drawnSpalls?.includes(ev.part)) return;
10667
+ const def = this.world.materials.get(pv.material);
10668
+ const inner = def?.visual?.innerColor ?? fallbackColor(def);
10669
+ const color = [16, 8, 0].reduce((hex, shift) => hex | Math.round((inner >> shift & 255) * CHIP_GAP_SHADE) << shift, 0);
10670
+ const box = this.visuals.worldBox(mv, new this.THREE.Box3());
10671
+ for (let axis = 0; axis < 3; axis++) {
10672
+ for (const side of [-1, 1]) {
10673
+ const normal = new this.THREE.Vector3(axis === 0 ? side : 0, axis === 1 ? side : 0, axis === 2 ? side : 0).applyQuaternion(rotation);
10674
+ const face = center.clone().addScaledVector(normal, ev.size[axis] / 2);
10675
+ const k = Math.abs(normal.x) >= Math.abs(normal.y) && Math.abs(normal.x) >= Math.abs(normal.z) ? "x" : Math.abs(normal.y) >= Math.abs(normal.z) ? "y" : "z";
10676
+ const surface = normal[k] > 0 ? box.max[k] : box.min[k];
10677
+ if (Math.abs(face[k] - surface) > CHIP_GAP_REACH) continue;
10678
+ face[k] = surface;
10679
+ this.visuals.addSpall(mv, face, normal, Math.min(ev.size[(axis + 1) % 3], ev.size[(axis + 2) % 3]) / 2 * CHIP_GAP_WIDTH, color);
10680
+ }
10681
+ }
10682
+ }
11295
10683
  onFracture(ev) {
11296
10684
  const b = this.bounds.get(ev.object);
11297
10685
  const pv = b?.parts.get(ev.part);
@@ -11482,7 +10870,7 @@ var Renderer = class {
11482
10870
  if (!old.round) this.setContacts(b, old, this.meshesOf(b).filter((mv) => this.visuals.shown(mv)));
11483
10871
  } else if (old.partBoxes) this.fitPartBoxes(b, old);
11484
10872
  if (!this.splittingAtLoad) old.sleeping = false;
11485
- } else if (kitOriginOf3(b.root)?.kind === "furniture" && !this.splittingAtLoad) {
10873
+ } else if (kitOriginOf3(b.root)?.kind === "furniture" && !this.splittingAtLoad && !this.heldByWorld(objectId)) {
11486
10874
  const piece = this.makePiece(objectId);
11487
10875
  piece.apart = true;
11488
10876
  this.tipIfTopHeavy(b, true);
@@ -11768,9 +11156,10 @@ var Renderer = class {
11768
11156
  if (!body.round) this.setContacts(b, body, left);
11769
11157
  }
11770
11158
  body.sleeping = false;
11159
+ if (!structural && !body.round && !body.held && kitOriginOf3(b.root)?.kind === "furniture" && Math.hypot(...body.velocity) <= UNDERMINED_STILL) this.goOverIfBalanced(b, body, left);
11771
11160
  return;
11772
11161
  }
11773
- if (structural) return;
11162
+ if (structural || this.heldByWorld(objectId)) return;
11774
11163
  const boxOf = (mv) => this.visuals.worldBox(mv, new this.THREE.Box3());
11775
11164
  const whole = [...b.parts.values()].flatMap((pv) => pv.meshes).map(boxOf).filter((one) => !one.isEmpty());
11776
11165
  if (!this.standsOn(objectId, whole.map((one) => [one.min.x, one.min.y, one.min.z, one.max.x, one.max.y, one.max.z]))) return;
@@ -11833,7 +11222,7 @@ var Renderer = class {
11833
11222
  }
11834
11223
  releaseIfFloating(objectId) {
11835
11224
  const b = this.bounds.get(objectId);
11836
- if (!b || b.piece || this.pieceSys.get(objectId) || !this.autoSplit || UNCHECKED_KINDS.has(this.kindOf(b))) return false;
11225
+ if (!b || b.piece || this.pieceSys.get(objectId) || !this.autoSplit || UNCHECKED_KINDS.has(this.kindOf(b)) || this.heldByWorld(objectId)) return false;
11837
11226
  const boxes = this.shownBoxes(objectId);
11838
11227
  if (boxes.length === 0) return false;
11839
11228
  const whole = new this.THREE.Box3();
@@ -11852,6 +11241,139 @@ var Renderer = class {
11852
11241
  this.o.onLoosened?.(objectId, piece, "apart");
11853
11242
  return true;
11854
11243
  }
11244
+ /**
11245
+ * The ground changed under what stands on feet (`wakeRegion`: a hole shot, dug or blown in the floor): furniture and what the host lets move (`shoveable`), not a piece yet or
11246
+ * a piece lying still. It looks at its feet again (`lowPoints`): a point of them with nothing left under it (`holdsAt`) no longer holds. While the points that still hold keep its
11247
+ * centre inside their polygon by `UNDERMINED_STAND` it stands (a cabinet on a full base over a small hole); otherwise it becomes a piece if it was not one, its corner over the
11248
+ * gap is started down, and the engine takes it into the hole by its own weight: a bed with a leg over the hole goes down on that corner until its frame meets the floor, and
11249
+ * what lay on it slides or falls off. Structures answer to their own load path.
11250
+ */
11251
+ checkUndermined() {
11252
+ if (this.undermined.length === 0) return;
11253
+ const discs = this.undermined.splice(0);
11254
+ const inDisc = (x, z, d) => Math.hypot(x - d.x, z - d.z) <= d.radius;
11255
+ for (const b of [...this.bounds.values()]) {
11256
+ if (this.kindOf(b) !== "furniture" && !this.o.shoveable?.(b.id)) continue;
11257
+ const was = b.piece ?? this.pieceSys.get(b.id) ?? null;
11258
+ if (was && (was.held || Math.hypot(...was.velocity) > UNDERMINED_STILL)) continue;
11259
+ const meshes = this.meshesOf(b).filter((mv) => this.visuals.shown(mv));
11260
+ const boxes = meshes.map((mv) => this.visuals.worldBox(mv, new this.THREE.Box3())).filter((one) => !one.isEmpty());
11261
+ if (boxes.length === 0) continue;
11262
+ const reach = boxes.reduce((all, one) => all.union(one), new this.THREE.Box3());
11263
+ if (!discs.some((d) => Math.hypot(Math.max(reach.min.x - d.x, 0, d.x - reach.max.x), Math.max(reach.min.z - d.z, 0, d.z - reach.max.z)) <= d.radius)) continue;
11264
+ const feet = this.lowPoints(meshes);
11265
+ if (!feet) continue;
11266
+ const { floor, points } = feet;
11267
+ const held = [];
11268
+ const lost = [];
11269
+ for (const point of points) (this.holdsAt(b.id, point[0], point[1], floor) ? held : lost).push(point);
11270
+ if (lost.length === 0) continue;
11271
+ if (!lost.some(([x, z]) => discs.some((d) => inDisc(x, z, d) && this.stoodBeside(x, z, d, floor)))) continue;
11272
+ const centre = centreOfBoxes(boxes);
11273
+ if (this.standsWith(held, points, centre, floor)) continue;
11274
+ let body;
11275
+ if (was) body = was;
11276
+ else {
11277
+ const piece = this.makePiece(b.id);
11278
+ body = b.piece ?? piece;
11279
+ body.apart = true;
11280
+ this.setContacts(b, body, meshes, true);
11281
+ }
11282
+ const gx = lost.reduce((sum, p) => sum + p[0], 0) / lost.length - centre[0];
11283
+ const gz = lost.reduce((sum, p) => sum + p[1], 0) / lost.length - centre[2];
11284
+ const length = Math.hypot(gx, gz);
11285
+ body.sleeping = false;
11286
+ body.still = 0;
11287
+ body.calmAt = null;
11288
+ if (held.length > 0 && length > 1e-6) this.pieceSys.impulse(body, [0, -body.mass * UNDERMINED_PUSH, 0], [centre[0] + gx, floor, centre[2] + gz]);
11289
+ if (!was) this.o.onLoosened?.(b.id, body, "ground");
11290
+ }
11291
+ }
11292
+ /**
11293
+ * A piece whose feet that still hold keep its centre inside their polygon by less than `UNDERMINED_STAND` per metre of its height is started down over the nearest edge of
11294
+ * that polygon (its weight does the rest); one that stands on nothing falls by itself.
11295
+ */
11296
+ goOverIfBalanced(b, body, meshes) {
11297
+ const feet = this.lowPoints(meshes);
11298
+ if (!feet) return;
11299
+ const held = feet.points.filter(([x, z]) => this.holdsAt(b.id, x, z, feet.floor));
11300
+ if (held.length < 3) return;
11301
+ const centre = centreOfBoxes(meshes.map((mv) => this.visuals.worldBox(mv, new this.THREE.Box3())).filter((one) => !one.isEmpty()));
11302
+ if (this.standsWith(held, null, centre, feet.floor)) return;
11303
+ const inside = insideBy(convexHull(held), [centre[0], centre[2]]);
11304
+ const reach = Math.max(body.halfExtents[0], body.halfExtents[2]);
11305
+ this.pieceSys.impulse(body, [0, -body.mass * UNDERMINED_PUSH, 0], [centre[0] + inside.out.x * reach, feet.floor, centre[2] + inside.out.z * reach]);
11306
+ }
11307
+ /**
11308
+ * Whether what stands on the points `held` of its feet (`all` of them whole) stays up with its centre at `centre`: the centre is inside what holds by `UNDERMINED_STAND` per metre of its height above `floor`, or it keeps
11309
+ * most of the hold it had (`UNDERMINED_KEEP` of how far inside its whole feet `all` the centre was; null when those are gone with a leg).
11310
+ */
11311
+ standsWith(held, all, centre, floor) {
11312
+ if (held.length < 3) return false;
11313
+ const now = insideBy(convexHull([...held]), [centre[0], centre[2]]).depth;
11314
+ if (now > UNDERMINED_STAND * (centre[1] - floor)) return true;
11315
+ return all !== null && now >= UNDERMINED_KEEP * insideBy(convexHull([...all]), [centre[0], centre[2]]).depth;
11316
+ }
11317
+ /**
11318
+ * Where `meshes` touch the floor, (x, z) in the world, and how high that floor is (their lowest drawn point); null with nothing drawn. The bottom faces (triangles
11319
+ * within `FEET_BAND` of the lowest point) give their corners, the middles of their sides and their own middles: the base of a cabinet is held along its edges and
11320
+ * across, not only at its four corners, and a mesh merged from a frame and its legs is held under each leg, not in the air between them.
11321
+ */
11322
+ lowPoints(meshes) {
11323
+ const faces = [];
11324
+ let floor = Infinity;
11325
+ for (const mv of meshes) {
11326
+ mv.mesh.updateWorldMatrix(true, false);
11327
+ const points = [];
11328
+ this.visuals.rangePoints(mv, mv.mesh.matrixWorld, points);
11329
+ const count = points.length / 3;
11330
+ const index = mv.mesh.geometry.getIndex()?.array;
11331
+ const from = mv.range ? mv.range[0] : 0;
11332
+ const total = index ? index.length : count;
11333
+ for (let i = 0; i + 2 < total; i += 3) {
11334
+ const a = (index ? index[i] : i) - from, b = (index ? index[i + 1] : i + 1) - from, c = (index ? index[i + 2] : i + 2) - from;
11335
+ if (a < 0 || b < 0 || c < 0 || a >= count || b >= count || c >= count) continue;
11336
+ for (const k of [a, b, c]) {
11337
+ faces.push(points[k * 3], points[k * 3 + 1], points[k * 3 + 2]);
11338
+ floor = Math.min(floor, points[k * 3 + 1]);
11339
+ }
11340
+ }
11341
+ }
11342
+ if (faces.length === 0) return null;
11343
+ const out = [];
11344
+ const seen = /* @__PURE__ */ new Set();
11345
+ const add = (x, z) => {
11346
+ const key = `${Math.round(x * 1e3)},${Math.round(z * 1e3)}`;
11347
+ if (seen.has(key)) return;
11348
+ seen.add(key);
11349
+ out.push([x, z]);
11350
+ };
11351
+ for (let i = 0; i < faces.length; i += 9) {
11352
+ if (faces[i + 1] > floor + FEET_BAND || faces[i + 4] > floor + FEET_BAND || faces[i + 7] > floor + FEET_BAND) continue;
11353
+ const ax = faces[i], az = faces[i + 2], bx = faces[i + 3], bz = faces[i + 5], cx = faces[i + 6], cz = faces[i + 8];
11354
+ add(ax, az);
11355
+ add(bx, bz);
11356
+ add(cx, cz);
11357
+ add((ax + bx) / 2, (az + bz) / 2);
11358
+ add((bx + cx) / 2, (bz + cz) / 2);
11359
+ add((ax + cx) / 2, (az + cz) / 2);
11360
+ add((ax + bx + cx) / 3, (az + bz + cz) / 3);
11361
+ }
11362
+ return out.length > 0 ? { floor, points: out } : null;
11363
+ }
11364
+ /** Whether the ground, a fixed top or a piece (not `objectId` itself) is within `BROKEN_GAP` under the point (x, z) of a foot at height `y`. */
11365
+ holdsAt(objectId, x, z, y) {
11366
+ return Math.max(this.groundAt(x, z), this.staticTopAtBut(objectId, x, z, y, BROKEN_GAP), this.pieceSys.topAt(x, z, y, BROKEN_GAP, objectId)) >= y - BROKEN_GAP;
11367
+ }
11368
+ /** Whether the ground just past the disc `d`, on the way from its middle to the foot at (x, z), is where the object's feet (`floor`) were: it stood on the ground that went. */
11369
+ stoodBeside(x, z, d, floor) {
11370
+ const fx = x - d.x, fz = z - d.z;
11371
+ const length = Math.hypot(fx, fz);
11372
+ const ux = length > 1e-6 ? fx / length : 1, uz = length > 1e-6 ? fz / length : 0;
11373
+ const reach = d.radius + UNDERMINED_RIM;
11374
+ const ground = this.groundAt(d.x + ux * reach, d.z + uz * reach);
11375
+ return ground >= floor - BROKEN_GAP - UNDERMINED_RIM_DROP && ground <= floor + UNDERMINED_RIM_RISE;
11376
+ }
11855
11377
  /** Whether the lowest of `boxes` (world boxes of the object `objectId`) has the ground, a fixed top or a piece within `BROKEN_GAP` under it. */
11856
11378
  standsOn(objectId, boxes) {
11857
11379
  if (boxes.length === 0) return false;
@@ -11868,6 +11390,10 @@ var Renderer = class {
11868
11390
  return false;
11869
11391
  }
11870
11392
  /** The kind of kit piece a bound object is, by the mark on its root or the nearest one above it (a house binds a group inside its marked root); '' when unmarked. */
11393
+ /** Whether what is left of the object is fixed where it was laid and still anchored (`DestructionWorld.fixedInPlace`): it stands by its load path, it is never let go as a piece. */
11394
+ heldByWorld(objectId) {
11395
+ return this.world.fixedInPlace(objectId);
11396
+ }
11871
11397
  kindOf(b) {
11872
11398
  for (let o = b.root; o; o = o.parent) {
11873
11399
  const kind = kitOriginOf3(o)?.kind;
@@ -11906,7 +11432,7 @@ var Renderer = class {
11906
11432
  * what holds it and it goes over until the top meets the floor. Past `CONTACT_MESHES` meshes it keeps the corners of its box; up to `PART_BOX_MESHES`, what lands on it lands
11907
11433
  * on its parts.
11908
11434
  */
11909
- setContacts(b, body, meshes) {
11435
+ setContacts(b, body, meshes, fitWhole = false) {
11910
11436
  if (meshes.length > PART_BOX_MESHES) {
11911
11437
  body.contacts = void 0;
11912
11438
  body.partBoxes = void 0;
@@ -11923,7 +11449,7 @@ var Renderer = class {
11923
11449
  this.visuals.localBox(mv, lb);
11924
11450
  if (lb.isEmpty()) continue;
11925
11451
  m4.multiplyMatrices(inv, mv.mesh.matrixWorld);
11926
- this.partBoxesOf(mv, { lb, m4, from: [cx, cy, cz] }, boxes);
11452
+ this.partBoxesOf(mv, { lb, m4, from: [cx, cy, cz], fitWhole }, boxes);
11927
11453
  lb.applyMatrix4(m4);
11928
11454
  for (let i = 0; i < 8; i++) points.push([(i & 1 ? lb.max.x : lb.min.x) - cx, (i & 2 ? lb.max.y : lb.min.y) - cy, (i & 4 ? lb.max.z : lb.min.z) - cz]);
11929
11455
  }
@@ -12044,28 +11570,67 @@ var Renderer = class {
12044
11570
  return own;
12045
11571
  }
12046
11572
  /**
12047
- * The boxes of one mesh in the piece's frame, from its centre of mass, turned as the mesh is drawn: a plain mesh is its geometry's box in its own space, turned by its
12048
- * place in the piece; a part drawn by a range of a merged mesh (a roof sheet in the house's roof mesh) is fitted to its own vertices (`fitOrientedBoxes`), since the box
11573
+ * The boxes of one mesh in the piece's frame, from its centre of mass, turned as the mesh is drawn: a mesh drawn as boxes round the air is those boxes (`hollowBoxesOf`);
11574
+ * else a plain mesh is its geometry's box in its own space, turned by its place in the piece; a part drawn by a range of a merged mesh (a roof sheet in the house's roof mesh) is fitted to its own vertices (`fitOrientedBoxes`), since the box
12049
11575
  * of those vertices in the merged mesh's space is the box around a tilted sheet, mostly air.
12050
11576
  */
12051
11577
  partBoxesOf(mv, at, out) {
12052
11578
  const [cx, cy, cz] = at.from;
12053
- if (mv.range) {
12054
- const own = [];
12055
- this.visuals.rangePoints(mv, new this.THREE.Matrix4(), own);
12056
- const drawn = hollowBoxesOf(own);
12057
- if (drawn) {
12058
- const pos2 = new this.THREE.Vector3();
12059
- const quat2 = new this.THREE.Quaternion();
12060
- const scale2 = new this.THREE.Vector3();
12061
- at.m4.decompose(pos2, quat2, scale2);
12062
- for (const box of drawn) {
12063
- const c2 = new this.THREE.Vector3((box.low[0] + box.high[0]) / 2, (box.low[1] + box.high[1]) / 2, (box.low[2] + box.high[2]) / 2).applyMatrix4(at.m4);
12064
- const half = [Math.abs((box.high[0] - box.low[0]) * scale2.x) / 2, Math.abs((box.high[1] - box.low[1]) * scale2.y) / 2, Math.abs((box.high[2] - box.low[2]) * scale2.z) / 2];
12065
- out.push({ center: [c2.x - cx, c2.y - cy, c2.z - cz], half, rotation: [quat2.x, quat2.y, quat2.z, quat2.w] });
12066
- }
12067
- return;
11579
+ const built = mv.range ? null : builtSolidsOf(mv.mesh);
11580
+ const solids = at.fitWhole && !mv.range && !built ? solidBoxesOf(mv.mesh.geometry) : null;
11581
+ if (solids) {
11582
+ const pos2 = new this.THREE.Vector3();
11583
+ const quat2 = new this.THREE.Quaternion();
11584
+ const scale2 = new this.THREE.Vector3();
11585
+ at.m4.decompose(pos2, quat2, scale2);
11586
+ for (const box of solids) {
11587
+ const c2 = new this.THREE.Vector3((box[0] + box[3]) / 2, (box[1] + box[4]) / 2, (box[2] + box[5]) / 2).applyMatrix4(at.m4);
11588
+ const half2 = [Math.max(5e-3, Math.abs((box[3] - box[0]) * scale2.x) / 2), Math.max(5e-3, Math.abs((box[4] - box[1]) * scale2.y) / 2), Math.max(5e-3, Math.abs((box[5] - box[2]) * scale2.z) / 2)];
11589
+ out.push({ center: [c2.x - cx, c2.y - cy, c2.z - cz], half: half2, rotation: [quat2.x, quat2.y, quat2.z, quat2.w] });
12068
11590
  }
11591
+ return;
11592
+ }
11593
+ if (built) {
11594
+ const pos2 = new this.THREE.Vector3();
11595
+ const quat2 = new this.THREE.Quaternion();
11596
+ const scale2 = new this.THREE.Vector3();
11597
+ at.m4.decompose(pos2, quat2, scale2);
11598
+ const c2 = new this.THREE.Vector3();
11599
+ const q = new this.THREE.Quaternion();
11600
+ const even = (Math.abs(scale2.x) + Math.abs(scale2.y) + Math.abs(scale2.z)) / 3;
11601
+ for (const solid of built) {
11602
+ c2.set(solid.center[0], solid.center[1], solid.center[2]).applyMatrix4(at.m4);
11603
+ q.set(solid.rotation[0], solid.rotation[1], solid.rotation[2], solid.rotation[3]);
11604
+ const turned = Math.abs(q.w) < 1 - 1e-9;
11605
+ const s = turned ? [even, even, even] : [Math.abs(scale2.x), Math.abs(scale2.y), Math.abs(scale2.z)];
11606
+ q.premultiply(quat2).normalize();
11607
+ const round = isRoundSolid(solid) && Math.abs(s[0] - s[2]) <= 1e-9;
11608
+ out.push({ center: [c2.x - cx, c2.y - cy, c2.z - cz], half: [Math.max(5e-3, solid.half[0] * s[0]), Math.max(5e-3, solid.half[1] * s[1]), Math.max(5e-3, solid.half[2] * s[2])], rotation: [q.x, q.y, q.z, q.w], ...round ? { round: true } : {} });
11609
+ }
11610
+ return;
11611
+ }
11612
+ const own = [];
11613
+ this.visuals.rangePoints(mv, new this.THREE.Matrix4(), own);
11614
+ const drawn = hollowBoxesOf(own, mv.range ? RANGED : OWN_MESH);
11615
+ if (drawn) {
11616
+ const pos2 = new this.THREE.Vector3();
11617
+ const quat2 = new this.THREE.Quaternion();
11618
+ const scale2 = new this.THREE.Vector3();
11619
+ at.m4.decompose(pos2, quat2, scale2);
11620
+ const c2 = new this.THREE.Vector3();
11621
+ const q = new this.THREE.Quaternion();
11622
+ const even = (Math.abs(scale2.x) + Math.abs(scale2.y) + Math.abs(scale2.z)) / 3;
11623
+ for (const box of drawn) {
11624
+ c2.set(box.center[0], box.center[1], box.center[2]).applyMatrix4(at.m4);
11625
+ const half2 = box.rotation ? [box.half[0] * even, box.half[1] * even, box.half[2] * even] : [Math.abs(box.half[0] * scale2.x), Math.abs(box.half[1] * scale2.y), Math.abs(box.half[2] * scale2.z)];
11626
+ if (box.rotation) q.set(box.rotation[0], box.rotation[1], box.rotation[2], box.rotation[3]).premultiply(quat2).normalize();
11627
+ else q.copy(quat2);
11628
+ const thin = mv.range ? 0 : 5e-3;
11629
+ out.push({ center: [c2.x - cx, c2.y - cy, c2.z - cz], half: [Math.max(thin, half2[0]), Math.max(thin, half2[1]), Math.max(thin, half2[2])], rotation: [q.x, q.y, q.z, q.w] });
11630
+ }
11631
+ return;
11632
+ }
11633
+ if (mv.range) {
12069
11634
  if (isRigidPose(at.m4.elements)) {
12070
11635
  const turn2 = new this.THREE.Quaternion().setFromRotationMatrix(at.m4);
12071
11636
  const c2 = new this.THREE.Vector3();
@@ -12088,11 +11653,14 @@ var Renderer = class {
12088
11653
  at.m4.decompose(pos, quat, scale);
12089
11654
  const c = at.lb.getCenter(new this.THREE.Vector3()).applyMatrix4(at.m4);
12090
11655
  const size = at.lb.getSize(new this.THREE.Vector3());
12091
- out.push({
12092
- center: [c.x - cx, c.y - cy, c.z - cz],
12093
- half: [Math.max(5e-3, Math.abs(size.x * scale.x) / 2), Math.max(5e-3, Math.abs(size.y * scale.y) / 2), Math.max(5e-3, Math.abs(size.z * scale.z) / 2)],
12094
- rotation: [quat.x, quat.y, quat.z, quat.w]
12095
- });
11656
+ const half = [Math.max(5e-3, Math.abs(size.x * scale.x) / 2), Math.max(5e-3, Math.abs(size.y * scale.y) / 2), Math.max(5e-3, Math.abs(size.z * scale.z) / 2)];
11657
+ const geometry = mv.mesh.geometry;
11658
+ const params = geometry.parameters ?? {};
11659
+ const whole = typeof params.thetaLength !== "number" || Math.abs(params.thetaLength - 2 * Math.PI) < 1e-6;
11660
+ const cylinder = geometry.type === "CylinderGeometry" && !mv.range;
11661
+ const straight = cylinder && whole && params.openEnded !== true && isRoundSolid({ kind: params.radiusTop === params.radiusBottom ? "cylinder" : "cone", half });
11662
+ const curved = !mv.range && !straight && (cylinder || geometry.type === "ConeGeometry" || geometry.type === "SphereGeometry");
11663
+ out.push({ center: [c.x - cx, c.y - cy, c.z - cz], half, rotation: [quat.x, quat.y, quat.z, quat.w], ...straight ? { round: true } : {}, ...curved ? { hull: this.hullOf(mv, at.lb, scale) } : {} });
12096
11664
  }
12097
11665
  /**
12098
11666
  * A piece of furniture standing on feet too close for its height (a board on two legs in a line, a lone leg) does not stay up: the box of a piece hides that its weight is up
@@ -12669,6 +12237,7 @@ var Renderer = class {
12669
12237
  wakeRegion(x, z, radius) {
12670
12238
  this.fragments.wakeRegion(x, z, radius);
12671
12239
  this.pieceSys.wakeRegion(x, z, radius);
12240
+ if (this.autoSplit && this.undermined.length < UNDERMINED_MAX) this.undermined.push({ x, z, radius });
12672
12241
  }
12673
12242
  stats() {
12674
12243
  return { fragments: this.fragments.count, particles: this.vfx.sprites().live + this.ownedVfxParticles(), pieces: this.pieceSys.list.length, decals: this.visuals.decalCount + this.ground.count };
@@ -12727,6 +12296,55 @@ function lighten(color, t) {
12727
12296
  };
12728
12297
  return ch(16) | ch(8) | ch(0);
12729
12298
  }
12299
+ function solidBoxesOf(geometry) {
12300
+ const position = geometry.getAttribute("position");
12301
+ if (!position || position.count <= 24) return null;
12302
+ const parent = new Int32Array(position.count);
12303
+ for (let i = 0; i < parent.length; i++) parent[i] = i;
12304
+ const find = (i) => {
12305
+ while (parent[i] !== i) {
12306
+ parent[i] = parent[parent[i]];
12307
+ i = parent[i];
12308
+ }
12309
+ return i;
12310
+ };
12311
+ const join = (a, b) => {
12312
+ const ra = find(a), rb = find(b);
12313
+ if (ra !== rb) parent[ra] = rb;
12314
+ };
12315
+ const corners = /* @__PURE__ */ new Map();
12316
+ for (let i = 0; i < position.count; i++) {
12317
+ const key = `${Math.round(position.getX(i) / SOLID_WELD)},${Math.round(position.getY(i) / SOLID_WELD)},${Math.round(position.getZ(i) / SOLID_WELD)}`;
12318
+ const first = corners.get(key);
12319
+ if (first === void 0) corners.set(key, i);
12320
+ else join(i, first);
12321
+ }
12322
+ const index = geometry.getIndex();
12323
+ const triangles2 = index ? index.count / 3 : position.count / 3;
12324
+ for (let t = 0; t < triangles2; t++) {
12325
+ const a = index ? index.getX(t * 3) : t * 3;
12326
+ join(a, index ? index.getX(t * 3 + 1) : t * 3 + 1);
12327
+ join(a, index ? index.getX(t * 3 + 2) : t * 3 + 2);
12328
+ }
12329
+ const boxes = /* @__PURE__ */ new Map();
12330
+ for (let i = 0; i < position.count; i++) {
12331
+ const root = find(i);
12332
+ const x = position.getX(i), y = position.getY(i), z = position.getZ(i);
12333
+ const box = boxes.get(root);
12334
+ if (!box) {
12335
+ if (boxes.size >= SOLIDS_MAX) return null;
12336
+ boxes.set(root, [x, y, z, x, y, z]);
12337
+ continue;
12338
+ }
12339
+ box[0] = Math.min(box[0], x);
12340
+ box[1] = Math.min(box[1], y);
12341
+ box[2] = Math.min(box[2], z);
12342
+ box[3] = Math.max(box[3], x);
12343
+ box[4] = Math.max(box[4], y);
12344
+ box[5] = Math.max(box[5], z);
12345
+ }
12346
+ return boxes.size > 1 ? [...boxes.values()] : null;
12347
+ }
12730
12348
  function convexHull(points) {
12731
12349
  const sorted = [...points].sort((a, b) => a[0] - b[0] || a[1] - b[1]);
12732
12350
  if (sorted.length < 3) return sorted;