@adatechnology/game-destruction-three 1.3.0 → 1.3.2

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.
@@ -4112,7 +4112,6 @@ var GameDestructionThree = (() => {
4112
4112
  ...DEBRIS_EFFECT_FAMILIES.flatMap((family) => [stageCrack(family), breachDust(family), collapseDust(family)]),
4113
4113
  REBAR_EXPOSE
4114
4114
  ];
4115
- var FACING5 = [0, 0, 1];
4116
4115
  var ORIGIN2 = [0, 0, 0];
4117
4116
  var FORWARD4 = [0, 0, -1];
4118
4117
  var IMPACT_MATERIALS = ["concrete", "metal", "wood", "glass", "flesh", "water"];
@@ -4122,7 +4121,7 @@ var GameDestructionThree = (() => {
4122
4121
  team: "weapons",
4123
4122
  budget: { particles: 40, decals: 1 },
4124
4123
  loop: 2,
4125
- timeline: [call2("impact", material, ORIGIN2, FACING5, 1, 0)]
4124
+ timeline: [call2("impact", material, ORIGIN2, NORMAL, 1, 0)]
4126
4125
  });
4127
4126
  var muzzleEffect = (weapon) => ({
4128
4127
  id: `muzzle_${weapon}`,
@@ -7828,7 +7827,6 @@ var GameDestructionThree = (() => {
7828
7827
  var FIRE_FLICKER_SWAY = 0.25;
7829
7828
  var FIRE_FLICKER_JITTER = 0.08;
7830
7829
  var LENS_FADE = 0.16;
7831
- var FLOOR_NORMAL_Y = 0.9;
7832
7830
  function rotate2(q, v) {
7833
7831
  const [qx, qy, qz, qw] = q;
7834
7832
  const ix = qw * v[0] + qy * v[2] - qz * v[1];
@@ -7965,7 +7963,7 @@ var GameDestructionThree = (() => {
7965
7963
  const [x, y, z] = this.place([recipe2[0], recipe2[1], recipe2[2]]);
7966
7964
  const options = recipe2[5];
7967
7965
  const normal = options?.n ? this.turn(options.n) : void 0;
7968
- const onFloor = !normal || normal[1] > FLOOR_NORMAL_Y;
7966
+ const onFloor = !normal;
7969
7967
  args = [x, onFloor ? this.context.groundAt(x, z) : y, z, recipe2[3], recipe2[4], normal ? { ...options, n: normal } : options];
7970
7968
  }
7971
7969
  this.context.trace?.("decal", args);
@@ -10925,6 +10923,78 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
10925
10923
  return box;
10926
10924
  }
10927
10925
 
10926
+ // src/fragment-support.ts
10927
+ var SUPPORT_SHARE = 1e-4;
10928
+ var createSupport = () => ({ count: 0, x: 0, y: 0, z: 0, edgeX: 0, edgeZ: 0 });
10929
+ function writeCorners(params) {
10930
+ const { e, half, corners } = params;
10931
+ for (let i = 0; i < 8; i++) {
10932
+ const sx = i & 1 ? half.x : -half.x;
10933
+ const sy = i & 2 ? half.y : -half.y;
10934
+ const sz = i & 4 ? half.z : -half.z;
10935
+ corners[3 * i] = e[0] * sx + e[4] * sy + e[8] * sz;
10936
+ corners[3 * i + 1] = e[1] * sx + e[5] * sy + e[9] * sz;
10937
+ corners[3 * i + 2] = e[2] * sx + e[6] * sy + e[10] * sz;
10938
+ }
10939
+ }
10940
+ function findSupport(params) {
10941
+ const { corners, support } = params;
10942
+ let low = Infinity;
10943
+ for (let i = 0; i < 8; i++) low = Math.min(low, corners[3 * i + 1]);
10944
+ const level = low + SUPPORT_SHARE * params.reach;
10945
+ let count = 0, x = 0, y = 0, z = 0, first = -1, edgeX = 0, edgeZ = 0;
10946
+ for (let i = 0; i < 8; i++) {
10947
+ if (corners[3 * i + 1] > level) continue;
10948
+ count++;
10949
+ x += corners[3 * i];
10950
+ y += corners[3 * i + 1];
10951
+ z += corners[3 * i + 2];
10952
+ if (first < 0) first = i;
10953
+ else if (count === 2) {
10954
+ edgeX = corners[3 * i] - corners[3 * first];
10955
+ edgeZ = corners[3 * i + 2] - corners[3 * first + 2];
10956
+ }
10957
+ }
10958
+ const along2 = Math.hypot(edgeX, edgeZ);
10959
+ support.count = count;
10960
+ support.x = x / count;
10961
+ support.y = y / count;
10962
+ support.z = z / count;
10963
+ support.edgeX = along2 > 0 ? edgeX / along2 : 0;
10964
+ support.edgeZ = along2 > 0 ? edgeZ / along2 : 0;
10965
+ }
10966
+ function inertiaAbout(params) {
10967
+ const { e, half, x, y, z } = params;
10968
+ const ax = x * e[0] + y * e[1] + z * e[2];
10969
+ const ay = x * e[4] + y * e[5] + z * e[6];
10970
+ const az = x * e[8] + y * e[9] + z * e[10];
10971
+ const xx = half.x * half.x, yy = half.y * half.y, zz = half.z * half.z;
10972
+ return (ax * ax * (yy + zz) + ay * ay * (xx + zz) + az * az * (xx + yy)) / 3;
10973
+ }
10974
+ function applyInverseInertia(params) {
10975
+ const { e, half, v } = params;
10976
+ const xx = half.x * half.x, yy = half.y * half.y, zz = half.z * half.z;
10977
+ const ax = 3 * (v.x * e[0] + v.y * e[1] + v.z * e[2]) / (yy + zz);
10978
+ const ay = 3 * (v.x * e[4] + v.y * e[5] + v.z * e[6]) / (xx + zz);
10979
+ const az = 3 * (v.x * e[8] + v.y * e[9] + v.z * e[10]) / (xx + yy);
10980
+ v.x = ax * e[0] + ay * e[4] + az * e[8];
10981
+ v.y = ax * e[1] + ay * e[5] + az * e[9];
10982
+ v.z = ax * e[2] + ay * e[6] + az * e[10];
10983
+ }
10984
+ function turnToLanding(params) {
10985
+ const { corners, pivot, axisX, axisZ } = params;
10986
+ let first = Infinity;
10987
+ for (let i = 0; i < 8; i++) {
10988
+ const px = corners[3 * i] - pivot.x;
10989
+ const py = corners[3 * i + 1] - pivot.y;
10990
+ const pz = corners[3 * i + 2] - pivot.z;
10991
+ if (py <= SUPPORT_SHARE * params.reach) continue;
10992
+ const qy = axisZ * px - axisX * pz;
10993
+ first = Math.min(first, Math.atan2(qy, py) + Math.PI / 2);
10994
+ }
10995
+ return first;
10996
+ }
10997
+
10928
10998
  // src/fragment-instances.ts
10929
10999
  var INSTANCED_FRAGMENT_LAYER = 29;
10930
11000
  var FRAGMENT_INSTANCES_NAME = "fragment-instances";
@@ -11420,6 +11490,67 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
11420
11490
  out.set(x / length, y / length, z / length, w / length);
11421
11491
  }
11422
11492
 
11493
+ // src/support-hull.ts
11494
+ var cross2 = (o, a, b) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
11495
+ function planHull(points) {
11496
+ const sorted = [...points].sort((a, b) => a[0] - b[0] || a[1] - b[1]);
11497
+ if (sorted.length < 3) return sorted;
11498
+ const lower = [];
11499
+ for (const p of sorted) {
11500
+ while (lower.length >= 2 && cross2(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) lower.pop();
11501
+ lower.push(p);
11502
+ }
11503
+ const upper = [];
11504
+ for (let i = sorted.length - 1; i >= 0; i--) {
11505
+ const p = sorted[i];
11506
+ while (upper.length >= 2 && cross2(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) upper.pop();
11507
+ upper.push(p);
11508
+ }
11509
+ return [...lower.slice(0, -1), ...upper.slice(0, -1)];
11510
+ }
11511
+ function toSegment(p, a, b) {
11512
+ const dx = b[0] - a[0];
11513
+ const dz = b[1] - a[1];
11514
+ const length = dx * dx + dz * dz;
11515
+ const t = length > 0 ? Math.max(0, Math.min(1, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dz) / length)) : 0;
11516
+ return Math.hypot(p[0] - a[0] - t * dx, p[1] - a[1] - t * dz);
11517
+ }
11518
+ function isOverSupport(points, centre, tolerance) {
11519
+ const hull = planHull(points);
11520
+ if (hull.length === 0) return false;
11521
+ if (hull.length === 1) return Math.hypot(centre[0] - hull[0][0], centre[1] - hull[0][1]) <= tolerance;
11522
+ let inside = hull.length >= 3;
11523
+ let nearest = Infinity;
11524
+ for (let i = 0; i < hull.length; i++) {
11525
+ const a = hull[i];
11526
+ const b = hull[(i + 1) % hull.length];
11527
+ if (hull.length >= 3 && cross2(a, b, centre) < 0) inside = false;
11528
+ nearest = Math.min(nearest, toSegment(centre, a, b));
11529
+ }
11530
+ return inside || nearest <= tolerance;
11531
+ }
11532
+ function clipConvex(subject, window) {
11533
+ let kept = [...subject];
11534
+ for (let e = 0; e < window.length && kept.length > 0; e++) {
11535
+ const a = window[e];
11536
+ const b = window[(e + 1) % window.length];
11537
+ const next = [];
11538
+ for (let i = 0; i < kept.length; i++) {
11539
+ const p = kept[i];
11540
+ const q = kept[(i + 1) % kept.length];
11541
+ const sp = cross2(a, b, p);
11542
+ const sq = cross2(a, b, q);
11543
+ if (sp >= 0) next.push(p);
11544
+ if (sp >= 0 !== sq >= 0) {
11545
+ const t = sp / (sp - sq);
11546
+ next.push([p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t]);
11547
+ }
11548
+ }
11549
+ kept = next;
11550
+ }
11551
+ return kept;
11552
+ }
11553
+
11423
11554
  // src/fragments.ts
11424
11555
  function rotationOf(q) {
11425
11556
  const { x, y, z, w } = q;
@@ -11442,6 +11573,20 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
11442
11573
  return [e[0] * half.x, e[2] * half.x, e[4] * half.y, e[6] * half.y, e[8] * half.z, e[10] * half.z];
11443
11574
  }
11444
11575
  var reachAlong = (shadow, nx, nz) => Math.abs(nx * shadow[0] + nz * shadow[1]) + Math.abs(nx * shadow[2] + nz * shadow[3]) + Math.abs(nx * shadow[4] + nz * shadow[5]);
11576
+ function shadowPolygon(shadow, cx, cz) {
11577
+ const corners = [];
11578
+ for (let k = 0; k < 8; k++) {
11579
+ const a = k & 1 ? 1 : -1, b = k & 2 ? 1 : -1, c = k & 4 ? 1 : -1;
11580
+ corners.push([cx + a * shadow[0] + b * shadow[2] + c * shadow[4], cz + a * shadow[1] + b * shadow[3] + c * shadow[5]]);
11581
+ }
11582
+ return planHull(corners);
11583
+ }
11584
+ function contactsOf(mine, under, x, z) {
11585
+ const own = shadowPolygon(mine, 0, 0);
11586
+ const points = [];
11587
+ for (const box of under) points.push(...clipConvex(own, shadowPolygon(box.shadow, box.x - x, box.z - z)));
11588
+ return points;
11589
+ }
11445
11590
  function shadowsOverlap(first, second, dx, dz) {
11446
11591
  for (const shadow of [first, second]) {
11447
11592
  for (let g = 0; g < 6; g += 2) {
@@ -11463,7 +11608,8 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
11463
11608
  z: p.z,
11464
11609
  reachX: Math.abs(e[0]) * x + Math.abs(e[4]) * y + Math.abs(e[8]) * z,
11465
11610
  reachZ: Math.abs(e[2]) * x + Math.abs(e[6]) * y + Math.abs(e[10]) * z,
11466
- top: p.y + Math.abs(e[1]) * x + Math.abs(e[5]) * y + Math.abs(e[9]) * z
11611
+ top: p.y + Math.abs(e[1]) * x + Math.abs(e[5]) * y + Math.abs(e[9]) * z,
11612
+ bottom: p.y - Math.abs(e[1]) * x - Math.abs(e[5]) * y - Math.abs(e[9]) * z
11467
11613
  };
11468
11614
  }
11469
11615
  var BUILDERS = {
@@ -11486,14 +11632,27 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
11486
11632
  var PILE_STEP = 0.01;
11487
11633
  var TIP_SPEED = 0.6;
11488
11634
  var TIP_TURN = 3;
11635
+ var RIDGE_TURN = Math.PI * (3 - Math.sqrt(5));
11636
+ var SIDE_BY_SIDE = 1e-4;
11489
11637
  var POINT = [0, 0, 0, 0, 0, 0];
11490
11638
  var SHARD_SHAPES = 6;
11491
11639
  var SWEEP_MIN_SPEED = 1;
11492
11640
  var WALL_RESTITUTION = 0.25;
11641
+ var ACROSS_MIN_STEP = 1e-4;
11493
11642
  var WALL_GLIDE = 0.7;
11494
11643
  var TUMBLE_REACH = 0.1;
11644
+ var GROUND_RESTITUTION = 0.25;
11645
+ var GROUND_GLIDE = 0.7;
11646
+ var GROUND_SPIN_KEPT = 0.55;
11647
+ var BOUNCE_LIFT_SHARE = 0.05;
11648
+ var ROUGHNESS_SHARE = 0.05;
11649
+ var SETTLE_FALL_HALVES = 2;
11650
+ var NUDGE_ENERGY_SHARE = 0.1;
11651
+ var DEBRIS_BOUNCE_SPEED = 0.6;
11652
+ var DEBRIS_LAY_RATE = 7;
11495
11653
  var LAID_GAP = 5e-3;
11496
11654
  var STAND_RATIO = 0.6;
11655
+ var FADE_SECONDS3 = 0.6;
11497
11656
  var SETTLE_SECONDS = 0.4;
11498
11657
  var isSlow = (f) => f.vel.lengthSq() < 0.012 && f.ang.lengthSq() < 0.2;
11499
11658
  var isBig = (size) => {
@@ -11524,6 +11683,13 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
11524
11683
  __publicField(this, "v");
11525
11684
  __publicField(this, "w");
11526
11685
  __publicField(this, "rng", createRng(FRAGMENT_SEED));
11686
+ /** The corners of the fragment being stepped (`writeCorners`), what of them it rests on, its halves at its fade, and its centre over that support: kept between calls. */
11687
+ __publicField(this, "corners", new Float64Array(24));
11688
+ /** The corners of `corners` from the lowest (`ridgeUnder`). */
11689
+ __publicField(this, "lowCorners", [0, 0, 0, 0, 0, 0, 0, 0]);
11690
+ __publicField(this, "support", createSupport());
11691
+ __publicField(this, "halves", { x: 0, y: 0, z: 0 });
11692
+ __publicField(this, "lever", { x: 0, y: 0, z: 0 });
11527
11693
  /** The fragments in flight drawn by instances, a draw per shared geometry and material (`FragmentInstances`). */
11528
11694
  __publicField(this, "instances");
11529
11695
  /** The instanced probe of the last `warmMeshes` (a new one each call, as the other probes are new meshes), freed by the next call or by `dispose`. */
@@ -11535,8 +11701,20 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
11535
11701
  __publicField(this, "supportTurn", 0);
11536
11702
  /** The pose before the last update and after it, of the fragments that were awake (`interpolate`); null when the option is off. */
11537
11703
  __publicField(this, "trail");
11704
+ /** Fragments crushed so far under a moving piece that came down on them with no room left (`meetMover`): they fade where they were. */
11705
+ __publicField(this, "crushed", 0);
11706
+ /** The pieces moving this update (`FragmentSystemOptions.movers`). */
11707
+ __publicField(this, "moving", []);
11708
+ /** Where a fragment was when its step began, and that point carried by a moving piece. */
11709
+ __publicField(this, "before");
11710
+ __publicField(this, "carried");
11711
+ /** The move of a piece since the last update, and its inverse. */
11712
+ __publicField(this, "shift");
11713
+ __publicField(this, "unshift");
11538
11714
  __publicField(this, "markGeometry", null);
11539
11715
  __publicField(this, "markMaterial", null);
11716
+ /** The floor under the fragment `pileUnder` is asked about (`floorUnder`, or the ground when that is all that was measured): what two pieces at one height must both stand on. */
11717
+ __publicField(this, "pileFloor", 0);
11540
11718
  /** Set by `pileUnder`: the way off the edge when the fragment's centre is past what it lies on, else null. */
11541
11719
  __publicField(this, "offEdge", null);
11542
11720
  this.box = new THREE.BoxGeometry(1, 1, 1);
@@ -11545,6 +11723,10 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
11545
11723
  this.m = new THREE.Matrix4();
11546
11724
  this.v = new THREE.Vector3();
11547
11725
  this.w = new THREE.Vector3();
11726
+ this.before = new THREE.Vector3();
11727
+ this.carried = new THREE.Vector3();
11728
+ this.shift = new THREE.Matrix4();
11729
+ this.unshift = new THREE.Matrix4();
11548
11730
  this.instances = new FragmentInstances(THREE, o.scene);
11549
11731
  this.trail = o.interpolate ? new PoseTrail() : null;
11550
11732
  }
@@ -11713,6 +11895,8 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
11713
11895
  const live = {
11714
11896
  mesh: mesh2,
11715
11897
  floor: null,
11898
+ ridgeTries: 0,
11899
+ ridgeWay: null,
11716
11900
  home,
11717
11901
  vel: new this.THREE.Vector3(f.velocity[0], f.velocity[1], f.velocity[2]),
11718
11902
  ang: new this.THREE.Vector3(f.angularVelocity[0], f.angularVelocity[1], f.angularVelocity[2]),
@@ -11825,6 +12009,13 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
11825
12009
  continue;
11826
12010
  }
11827
12011
  if (this.clock > f.deadline) {
12012
+ const held = this.heldUntil(f);
12013
+ if (held > f.deadline) {
12014
+ f.deadline = held;
12015
+ if (held < next) next = held;
12016
+ this.mortal[kept++] = f;
12017
+ continue;
12018
+ }
11828
12019
  f.isMortal = false;
11829
12020
  f.dying = true;
11830
12021
  f.mesh.matrixAutoUpdate = true;
@@ -11837,6 +12028,26 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
11837
12028
  this.mortal.length = kept;
11838
12029
  this.nextDeadline = next;
11839
12030
  }
12031
+ /**
12032
+ * When `f` may start to fade: once every chip lying on it (light and small, its bottom on f's top, their floor areas sharing ground) has shrunk away; never while one that
12033
+ * never fades lies on it, a settling time from now while one still moves on it, and at `f.deadline` when nothing lies on it.
12034
+ */
12035
+ heldUntil(f) {
12036
+ const box = f.box ?? (f.box = restingBox(f));
12037
+ let until = f.deadline;
12038
+ for (const other of this.list) {
12039
+ if (other === f || other.rigid || other.body) continue;
12040
+ const on = other.box ?? (other.box = restingBox(other));
12041
+ const e = rotationOf(other.mesh.quaternion);
12042
+ const bottom = other.mesh.position.y - (Math.abs(e[1]) * other.half.x + Math.abs(e[5]) * other.half.y + Math.abs(e[9]) * other.half.z);
12043
+ if (bottom <= f.mesh.position.y || bottom > box.top + SUPPORT_GAP) continue;
12044
+ if (Math.abs(on.x - box.x) >= on.reachX + box.reachX || Math.abs(on.z - box.z) >= on.reachZ + box.reachZ) continue;
12045
+ if (!shadowsOverlap(box.shadow, on.shadow, on.x - box.x, on.z - box.z)) continue;
12046
+ const gone = other.dying ? this.clock + other.fade * FADE_SECONDS3 : other.asleep ? other.deadline + FADE_SECONDS3 : this.clock + SETTLE_SECONDS;
12047
+ until = Math.max(until, gone);
12048
+ }
12049
+ return until;
12050
+ }
11840
12051
  /** What lies inside the disc looks at the ground again: it was dug or heaped under it. */
11841
12052
  wakeRegion(x, z, radius) {
11842
12053
  for (const f of this.list) {
@@ -11847,7 +12058,9 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
11847
12058
  update(dt) {
11848
12059
  this.tick++;
11849
12060
  this.clock += dt;
12061
+ this.moving = this.o.movers?.() ?? [];
11850
12062
  this.wakeUnsupported();
12063
+ this.wakeMoved();
11851
12064
  this.wakeRigid();
11852
12065
  this.beginTick();
11853
12066
  const g = this.o.gravity;
@@ -11855,7 +12068,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
11855
12068
  const f = this.active[i];
11856
12069
  if (f.dying) {
11857
12070
  f.mesh.matrixAutoUpdate = true;
11858
- f.fade -= dt / 0.6;
12071
+ f.fade -= dt / FADE_SECONDS3;
11859
12072
  if (f.fade <= 0) {
11860
12073
  this.instances.remove(f.mesh);
11861
12074
  this.o.scene.remove(f.mesh);
@@ -11881,6 +12094,23 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
11881
12094
  if (f.rigid) this.o.rigid?.remove(f.rigid);
11882
12095
  f.rigid = null;
11883
12096
  }
12097
+ /** A fragment asleep in the box of a piece that moves wakes in the same update: what it lay on, or what lies on it, is going. */
12098
+ wakeMoved() {
12099
+ if (this.moving.length === 0) return;
12100
+ for (const f of this.list) if (f.asleep && !f.dying && !f.rigid && this.nearAnyMover(f)) this.rouse(f);
12101
+ }
12102
+ /** Whether the fragment is in the box of the moving piece (or within its reach of it). */
12103
+ nearMover(f, mover) {
12104
+ const p = f.mesh.position;
12105
+ const reach2 = Math.max(f.half.x, f.half.y, f.half.z);
12106
+ const b = mover.box;
12107
+ return p.x >= b[0] - reach2 && p.x <= b[3] + reach2 && p.y >= b[1] - reach2 && p.y <= b[4] + reach2 && p.z >= b[2] - reach2 && p.z <= b[5] + reach2;
12108
+ }
12109
+ /** Whether the fragment is in the box of any piece moving this update. */
12110
+ nearAnyMover(f) {
12111
+ for (const mover of this.moving) if (this.nearMover(f, mover)) return true;
12112
+ return false;
12113
+ }
11884
12114
  /** The debris moved by a rigid body that the body's world woke (something fell on it, a blast, its ground dug): it is awake here too. */
11885
12115
  wakeRigid() {
11886
12116
  for (const f of this.list) if (f.rigid && f.asleep && !f.dying && !f.rigid.sleeping) this.rouse(f);
@@ -11962,29 +12192,77 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
11962
12192
  const ext = Math.abs(e[1]) * f.half.x + Math.abs(e[5]) * f.half.y + Math.abs(e[9]) * f.half.z;
11963
12193
  f.floor = null;
11964
12194
  const bottom = f.mesh.position.y - ext;
11965
- const pile = this.pileUnder(f, bottom);
11966
- const offEdge = this.offEdge;
11967
12195
  const ground = this.o.groundAt(f.mesh.position.x, f.mesh.position.z);
12196
+ this.pileFloor = ground;
12197
+ let pile = this.pileUnder(f, bottom);
11968
12198
  if (bottom <= ground + SUPPORT_GAP && pile <= ground) continue;
11969
12199
  const floor2 = this.floorUnder(f);
12200
+ if (floor2 > ground) {
12201
+ this.pileFloor = floor2;
12202
+ pile = this.pileUnder(f, bottom);
12203
+ }
12204
+ const offEdge = this.offEdge;
11970
12205
  if (bottom > Math.max(floor2, pile) + SUPPORT_GAP || pile > floor2 && offEdge) this.rouse(f);
11971
12206
  }
11972
12207
  }
11973
- /** What a fragment lands on: measured where it is, and again only once it moved `FLOOR_REMEASURE` m off that spot (a ray down is not free). */
12208
+ /** What a fragment lands on: measured where it is, and again only once it moved half its size (at most `FLOOR_REMEASURE` m) off that spot (a ray down is not free). */
11974
12209
  floorUnder(f) {
11975
12210
  const p = f.mesh.position;
11976
12211
  if (!this.o.surfaceAt) return this.o.groundAt(p.x, p.z);
11977
12212
  const at3 = f.floor;
11978
- if (!at3 || Math.abs(at3.x - p.x) > FLOOR_REMEASURE || Math.abs(at3.z - p.z) > FLOOR_REMEASURE || p.y < at3.y - FLOOR_REMEASURE) {
12213
+ const away = Math.min(FLOOR_REMEASURE, Math.max(f.half.x, f.half.y, f.half.z));
12214
+ if (!at3 || Math.abs(at3.x - p.x) > away || Math.abs(at3.z - p.z) > away || p.y < at3.y - FLOOR_REMEASURE) {
11979
12215
  f.floor = { x: p.x, z: p.z, y: this.o.surfaceAt(p.x, p.y, p.z) };
11980
12216
  }
11981
12217
  return f.floor.y;
11982
12218
  }
12219
+ /**
12220
+ * Whether the fragment, come down on `floor` (what is built under its centre), lies only on its centre: none of its four lowest corners is over anything that high, so it
12221
+ * balances on an edge narrower than itself. Then the way it slides off (towards its lowest corner, or one more `RIDGE_TURN` round each time it lands so again, kept while it
12222
+ * slides), else null.
12223
+ * Asked once per measure of the floor (`floorUnder`), at the first contact.
12224
+ */
12225
+ ridgeUnder(f, e, floor2) {
12226
+ const at3 = f.floor;
12227
+ const surfaceAt = this.o.surfaceAt;
12228
+ if (!at3 || !surfaceAt) return null;
12229
+ if (at3.ridge !== void 0) return at3.ridge;
12230
+ at3.ridge = null;
12231
+ const p = f.mesh.position;
12232
+ if (floor2 <= this.o.groundAt(p.x, p.z) + SUPPORT_GAP) return f.ridgeWay = null;
12233
+ const c = this.corners;
12234
+ writeCorners({ e, half: f.half, corners: c });
12235
+ const low = this.lowCorners;
12236
+ for (let i = 0; i < 8; i++) {
12237
+ let k = i;
12238
+ while (k > 0 && c[3 * low[k - 1] + 1] > c[3 * i + 1]) {
12239
+ low[k] = low[k - 1];
12240
+ k--;
12241
+ }
12242
+ low[k] = i;
12243
+ }
12244
+ for (let k = 0; k < 4; k++) {
12245
+ const i = low[k];
12246
+ if (surfaceAt(p.x + c[3 * i], p.y, p.z + c[3 * i + 2]) >= floor2 - SUPPORT_GAP) return f.ridgeWay = null;
12247
+ }
12248
+ if (f.ridgeWay) return at3.ridge = f.ridgeWay;
12249
+ const lowest = low[0];
12250
+ const lx = c[3 * lowest], lz = c[3 * lowest + 2];
12251
+ const tilt = c[3 * low[3] + 1] - c[3 * lowest + 1];
12252
+ const d = Math.hypot(lx, lz);
12253
+ f.ridgeTries++;
12254
+ const angle = f.seq * RIDGE_TURN + f.ridgeTries * RIDGE_TURN;
12255
+ f.ridgeWay = tilt > SUPPORT_GAP && d > 1e-6 && f.ridgeTries === 1 ? { x: lx / d, z: lz / d } : { x: Math.cos(angle), z: Math.sin(angle) };
12256
+ return at3.ridge = f.ridgeWay;
12257
+ }
11983
12258
  step(f, dt, g) {
11984
12259
  const mesh2 = f.mesh;
11985
12260
  f.box = void 0;
11986
12261
  f.vel.y -= g * dt;
12262
+ this.before.copy(mesh2.position);
11987
12263
  if (!this.hitWall(f, dt)) mesh2.position.addScaledVector(f.vel, dt);
12264
+ const stirred = this.nearAnyMover(f);
12265
+ if (stirred) f.floor = null;
11988
12266
  const w = f.ang.length();
11989
12267
  if (w > 1e-5) {
11990
12268
  this.dq.setFromAxisAngle(this.v.copy(f.ang).multiplyScalar(1 / w), w * dt);
@@ -11996,6 +12274,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
11996
12274
  const sc = f.dying ? f.fade : 1;
11997
12275
  const ext = (Math.abs(e[1]) * h.x + Math.abs(e[5]) * h.y + Math.abs(e[9]) * h.z) * sc;
11998
12276
  const floor2 = this.floorUnder(f);
12277
+ this.pileFloor = floor2;
11999
12278
  const pile = this.pileUnder(f, mesh2.position.y - ext + Math.max(0, -f.vel.y) * dt);
12000
12279
  const gy = Math.max(floor2, pile);
12001
12280
  const tip = pile > floor2 ? this.offEdge : null;
@@ -12004,35 +12283,31 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
12004
12283
  if (mesh2.position.y - ext < gy) {
12005
12284
  contact = true;
12006
12285
  mesh2.position.y = gy + ext;
12007
- if (f.vel.y < -0.6) {
12008
- f.vel.y = -f.vel.y * 0.25;
12009
- f.vel.x *= 0.7;
12010
- f.vel.z *= 0.7;
12011
- f.ang.multiplyScalar(0.55);
12012
- const tumble = Math.min(1, TUMBLE_REACH / Math.max(h.x, h.y, h.z));
12013
- f.ang.x += (this.rng() - 0.5) * 2 * tumble;
12014
- f.ang.z += (this.rng() - 0.5) * 2 * tumble;
12015
- } else {
12286
+ const ridge = pile > floor2 ? null : this.ridgeUnder(f, e, floor2);
12287
+ if (pile > floor2) {
12288
+ turning = this.restOnDebris(f, { g, dt, gy, sc, tip });
12289
+ } else if (ridge) {
12016
12290
  f.vel.y = 0;
12017
- const sliding = Math.hypot(f.vel.x, f.vel.z);
12018
- const kept = sliding > 0 ? Math.max(0, sliding - DEBRIS_FRICTION * g * dt) / sliding : 0;
12019
- f.vel.x *= kept;
12020
- f.vel.z *= kept;
12021
- f.ang.multiplyScalar(Math.exp(-6 * dt));
12291
+ f.vel.x += ridge.x * TIP_SPEED * dt * 10;
12292
+ f.vel.z += ridge.z * TIP_SPEED * dt * 10;
12293
+ f.floor = null;
12294
+ turning = true;
12295
+ } else {
12296
+ writeCorners({ e, half: this.scaledHalf(f, sc), corners: this.corners });
12297
+ findSupport({ corners: this.corners, reach: Math.max(h.x, h.y, h.z) * sc, support: this.support });
12298
+ if (!f.contact && this.bounces(f, { g, dt, sc })) {
12299
+ this.bounce(f, sc);
12300
+ } else {
12301
+ f.vel.y = 0;
12302
+ turning = this.restOn(f, { g, dt, sc });
12303
+ }
12022
12304
  }
12023
12305
  } else {
12024
12306
  f.ang.multiplyScalar(Math.exp(-0.15 * dt));
12025
12307
  if (f.air > 0) this.flutter(f, dt);
12026
12308
  }
12027
- if (contact && tip) {
12028
- f.vel.x += tip.x * TIP_SPEED * dt * 10;
12029
- f.vel.z += tip.z * TIP_SPEED * dt * 10;
12030
- f.ang.x += tip.z * TIP_TURN * dt * 10;
12031
- f.ang.z -= tip.x * TIP_TURN * dt * 10;
12032
- } else if (contact && f.vel.lengthSq() < 4) {
12033
- turning = this.settle(f, dt);
12034
- this.m.makeRotationFromQuaternion(mesh2.quaternion);
12035
- mesh2.position.y = gy + (Math.abs(e[1]) * h.x + Math.abs(e[5]) * h.y + Math.abs(e[9]) * h.z) * sc;
12309
+ if (stirred) {
12310
+ for (const mover of this.moving) if (this.nearMover(f, mover)) this.meetMover(f, mover, dt);
12036
12311
  }
12037
12312
  f.contact = contact;
12038
12313
  if (contact && !turning && isSlow(f)) {
@@ -12049,11 +12324,12 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
12049
12324
  hitWall(f, dt) {
12050
12325
  const sweep = this.o.sweep;
12051
12326
  if (!sweep) return false;
12052
- const speed = f.vel.length();
12053
- if (speed < SWEEP_MIN_SPEED) return false;
12054
- if (f.contact && f.vel.y <= 0 && Math.hypot(f.vel.x, f.vel.z) < SWEEP_MIN_SPEED) return false;
12327
+ const across = f.vel.length() < SWEEP_MIN_SPEED || f.contact && f.vel.y <= 0 && Math.hypot(f.vel.x, f.vel.z) < SWEEP_MIN_SPEED;
12328
+ const vy2 = across ? 0 : f.vel.y;
12329
+ const speed = Math.hypot(f.vel.x, vy2, f.vel.z);
12330
+ if (speed * dt < ACROSS_MIN_STEP) return false;
12055
12331
  const p = f.mesh.position;
12056
- const dir = [f.vel.x / speed, f.vel.y / speed, f.vel.z / speed];
12332
+ const dir = [f.vel.x / speed, vy2 / speed, f.vel.z / speed];
12057
12333
  const e = this.m.makeRotationFromQuaternion(f.mesh.quaternion).elements;
12058
12334
  const reach2 = (x, y, z) => (Math.abs(e[0] * x + e[1] * y + e[2] * z) * f.half.x + Math.abs(e[4] * x + e[5] * y + e[6] * z) * f.half.y + Math.abs(e[8] * x + e[9] * y + e[10] * z) * f.half.z) * (f.dying ? f.fade : 1);
12059
12335
  const ahead = reach2(dir[0], dir[1], dir[2]);
@@ -12070,6 +12346,68 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
12070
12346
  f.floor = null;
12071
12347
  return true;
12072
12348
  }
12349
+ /**
12350
+ * The fragment's way this step as the moving piece sees it: from where the piece carried the fragment's start to where the fragment got. A face of the piece on that way
12351
+ * stops it on the face, moving as the piece moves there, with what it had across the face kept as off a wall: a panel coming down on a sheet takes it along.
12352
+ */
12353
+ meetMover(f, mover, dt) {
12354
+ const p = f.mesh.position;
12355
+ const shift = this.shift.fromArray(mover.delta);
12356
+ const from = this.carried.copy(this.before).applyMatrix4(shift);
12357
+ const rx = p.x - from.x, ry = p.y - from.y, rz = p.z - from.z;
12358
+ const span = Math.hypot(rx, ry, rz);
12359
+ if (span < 1e-6) return;
12360
+ const dir = [rx / span, ry / span, rz / span];
12361
+ const e = this.m.makeRotationFromQuaternion(f.mesh.quaternion).elements;
12362
+ const reach2 = (x, y, z) => (Math.abs(e[0] * x + e[1] * y + e[2] * z) * f.half.x + Math.abs(e[4] * x + e[5] * y + e[6] * z) * f.half.y + Math.abs(e[8] * x + e[9] * y + e[10] * z) * f.half.z) * (f.dying ? f.fade : 1);
12363
+ const hit = mover.sweep([from.x, from.y, from.z], dir, span + reach2(dir[0], dir[1], dir[2]));
12364
+ if (!hit) return;
12365
+ const nx = hit.normal[0] ?? 0, ny = hit.normal[1] ?? 0, nz = hit.normal[2] ?? 0;
12366
+ if (rx * nx + ry * ny + rz * nz >= 0) return;
12367
+ const px = hit.point[0] ?? p.x, py = hit.point[1] ?? p.y, pz = hit.point[2] ?? p.z;
12368
+ const was = this.v.set(px, py, pz).applyMatrix4(this.unshift.copy(shift).invert());
12369
+ const cx = (px - was.x) / dt, cy = (py - was.y) / dt, cz = (pz - was.z) / dt;
12370
+ this.alongFace(f, nx, ny, nz);
12371
+ const off2 = Math.min(f.half.x, f.half.y, f.half.z) * (f.dying ? f.fade : 1) + 2e-3;
12372
+ const qx = px + nx * off2, qy = py + ny * off2, qz = pz + nz * off2;
12373
+ if (this.pinched(from, qx, qy, qz, off2)) {
12374
+ p.copy(from);
12375
+ f.vel.set(cx, cy, cz);
12376
+ this.crushed++;
12377
+ f.dying = true;
12378
+ this.activate(f);
12379
+ return;
12380
+ }
12381
+ p.set(qx, qy, qz);
12382
+ const ux = f.vel.x - cx, uy = f.vel.y - cy, uz = f.vel.z - cz;
12383
+ const inward = Math.min(0, ux * nx + uy * ny + uz * nz);
12384
+ const tx = ux - inward * nx, ty = uy - inward * ny, tz = uz - inward * nz;
12385
+ f.vel.set(cx + tx * WALL_GLIDE - inward * WALL_RESTITUTION * nx, cy + ty * WALL_GLIDE - inward * WALL_RESTITUTION * ny, cz + tz * WALL_GLIDE - inward * WALL_RESTITUTION * nz);
12386
+ f.ang.multiplyScalar(0.55);
12387
+ }
12388
+ /**
12389
+ * Whether a fragment the piece carried to `p` and pushed on to (x, y, z), `off` its reach from the face, gets there through something else or ends below what is under it there.
12390
+ */
12391
+ pinched(p, x, y, z, off2) {
12392
+ const floor2 = this.o.surfaceAt ? this.o.surfaceAt(x, y, z) : this.o.groundAt(x, z);
12393
+ if (y - off2 < floor2) return true;
12394
+ const sweep = this.o.sweep;
12395
+ const dx = x - p.x, dy = y - p.y, dz = z - p.z;
12396
+ const length = Math.hypot(dx, dy, dz);
12397
+ if (!sweep || length < 1e-6) return false;
12398
+ return sweep([p.x, p.y, p.z], [dx / length, dy / length, dz / length], length) !== null;
12399
+ }
12400
+ /** Turns the fragment the least way that lays its thinnest side on the face of normal (nx, ny, nz). */
12401
+ alongFace(f, nx, ny, nz) {
12402
+ const e = this.m.makeRotationFromQuaternion(f.mesh.quaternion).elements;
12403
+ const half = [f.half.x, f.half.y, f.half.z];
12404
+ let thin = 0;
12405
+ for (let i = 1; i < 3; i++) if (half[i] < half[thin]) thin = i;
12406
+ const side = e[thin * 4] * nx + e[thin * 4 + 1] * ny + e[thin * 4 + 2] * nz >= 0 ? 1 : -1;
12407
+ this.v.set(e[thin * 4] * side, e[thin * 4 + 1] * side, e[thin * 4 + 2] * side);
12408
+ this.dq.setFromUnitVectors(this.v, this.w.set(nx, ny, nz));
12409
+ f.mesh.quaternion.premultiply(this.dq).normalize();
12410
+ }
12073
12411
  /**
12074
12412
  * The top of the debris lying under a falling fragment: a piece lands on the pile, not through it, so two flat pieces never end up inside each other. Only pieces
12075
12413
  * below it count (a resting one keeps its box), those whose top is at or below where the faller's bottom was a step ago plus a small step.
@@ -12080,13 +12418,16 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
12080
12418
  const reachX = Math.abs(e[0]) * f.half.x + Math.abs(e[4]) * f.half.y + Math.abs(e[8]) * f.half.z;
12081
12419
  const reachZ = Math.abs(e[2]) * f.half.x + Math.abs(e[6]) * f.half.y + Math.abs(e[10]) * f.half.z;
12082
12420
  const mine = shadowOf(e, f.half);
12421
+ const lowest = p.y - (Math.abs(e[1]) * f.half.x + Math.abs(e[5]) * f.half.y + Math.abs(e[9]) * f.half.z);
12083
12422
  let top = Number.NEGATIVE_INFINITY;
12084
12423
  const under = this.under;
12085
12424
  under.length = 0;
12086
12425
  for (const other of this.list) {
12087
12426
  if (other === f || other.dying) continue;
12088
12427
  const box = other.box ?? (other.box = restingBox(other));
12089
- if (box.top > bottom + PILE_STEP || box.top < top - PILE_STEP) continue;
12428
+ const beneath = !other.asleep && other.mesh.position.y < bottom;
12429
+ if (box.top > bottom + PILE_STEP && !beneath || box.top < top - PILE_STEP) continue;
12430
+ if (box.bottom >= lowest - SIDE_BY_SIDE && (other.seq > f.seq || box.bottom > this.pileFloor + SUPPORT_GAP)) continue;
12090
12431
  if (Math.abs(box.x - p.x) >= box.reachX + reachX || Math.abs(box.z - p.z) >= box.reachZ + reachZ) continue;
12091
12432
  if (!shadowsOverlap(mine, box.shadow, box.x - p.x, box.z - p.z)) continue;
12092
12433
  if (box.top > top + PILE_STEP) under.length = 0;
@@ -12095,13 +12436,16 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
12095
12436
  }
12096
12437
  this.offEdge = null;
12097
12438
  if (under.length > 0 && !under.some((box) => box.top >= top - PILE_STEP && shadowsOverlap(POINT, box.shadow, box.x - p.x, box.z - p.z))) {
12098
- let x = 0, z = 0;
12099
- for (const box of under) {
12100
- x += p.x - box.x;
12101
- z += p.z - box.z;
12439
+ const contacts = contactsOf(mine, under, p.x, p.z);
12440
+ if (!isOverSupport(contacts, [0, 0], 0)) {
12441
+ let x = 0, z = 0;
12442
+ for (const [cx, cz] of contacts) {
12443
+ x -= cx;
12444
+ z -= cz;
12445
+ }
12446
+ const d = Math.hypot(x, z);
12447
+ this.offEdge = d > 1e-6 ? { x: x / d, z: z / d } : { x: 1, z: 0 };
12102
12448
  }
12103
- const d = Math.hypot(x, z);
12104
- this.offEdge = d > 1e-6 ? { x: x / d, z: z / d } : { x: 1, z: 0 };
12105
12449
  }
12106
12450
  return top;
12107
12451
  }
@@ -12113,8 +12457,41 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
12113
12457
  f.ang.x += (this.rng() - 0.5) * SHEET_SWAY * 4 * dt;
12114
12458
  f.ang.z += (this.rng() - 0.5) * SHEET_SWAY * 4 * dt;
12115
12459
  }
12116
- /** Tip the fragment towards lying on its flattest face. True while its end is still more than `LAID_GAP` from lying. */
12117
- settle(f, dt) {
12460
+ /**
12461
+ * On other debris, by the pile's rules (`DEBRIS_BOUNCE_SPEED`): a bounce with a tumble by the speed of its end, Coulomb friction, its spin damped, off the edge of what holds
12462
+ * it when its centre is past it (`tip`), else laid flat (`layOnDebris`). True while it is still being laid flat.
12463
+ */
12464
+ restOnDebris(f, params) {
12465
+ const { g, dt, gy, sc, tip } = params;
12466
+ const h = f.half;
12467
+ if (f.vel.y < -DEBRIS_BOUNCE_SPEED) {
12468
+ f.vel.y = -f.vel.y * GROUND_RESTITUTION;
12469
+ f.vel.x *= GROUND_GLIDE;
12470
+ f.vel.z *= GROUND_GLIDE;
12471
+ f.ang.multiplyScalar(GROUND_SPIN_KEPT);
12472
+ const tumble = Math.min(1, TUMBLE_REACH / Math.max(h.x, h.y, h.z));
12473
+ f.ang.x += (this.rng() - 0.5) * 2 * tumble;
12474
+ f.ang.z += (this.rng() - 0.5) * 2 * tumble;
12475
+ } else {
12476
+ f.vel.y = 0;
12477
+ this.slide(f, g, dt);
12478
+ f.ang.multiplyScalar(Math.exp(-6 * dt));
12479
+ }
12480
+ if (tip) {
12481
+ f.vel.x += tip.x * TIP_SPEED * dt * 10;
12482
+ f.vel.z += tip.z * TIP_SPEED * dt * 10;
12483
+ f.ang.x += tip.z * TIP_TURN * dt * 10;
12484
+ f.ang.z -= tip.x * TIP_TURN * dt * 10;
12485
+ return false;
12486
+ }
12487
+ if (f.vel.lengthSq() >= 4) return false;
12488
+ const turning = this.layOnDebris(f, dt);
12489
+ const e = this.m.makeRotationFromQuaternion(f.mesh.quaternion).elements;
12490
+ f.mesh.position.y = gy + (Math.abs(e[1]) * h.x + Math.abs(e[5]) * h.y + Math.abs(e[9]) * h.z) * sc;
12491
+ return turning;
12492
+ }
12493
+ /** Tip the fragment lying on other debris towards lying on its flattest face. True while its end is still more than `LAID_GAP` from lying. */
12494
+ layOnDebris(f, dt) {
12118
12495
  const mesh2 = f.mesh;
12119
12496
  this.m.makeRotationFromQuaternion(mesh2.quaternion);
12120
12497
  const e = this.m.elements;
@@ -12134,9 +12511,204 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
12134
12511
  this.w.set(0, 1, 0);
12135
12512
  this.dq.setFromUnitVectors(this.v, this.w);
12136
12513
  this.q.copy(this.dq).multiply(mesh2.quaternion);
12137
- mesh2.quaternion.slerp(this.q, clamp6(dt * 7, 0, 1));
12514
+ mesh2.quaternion.slerp(this.q, Math.min(1, dt * DEBRIS_LAY_RATE));
12138
12515
  return Math.sqrt(Math.max(0, 1 - this.v.y * this.v.y)) * Math.max(half[0], half[1], half[2]) > LAID_GAP;
12139
12516
  }
12517
+ /** The fragment's halves (m) at its fade, into `halves`. */
12518
+ scaledHalf(f, sc) {
12519
+ this.halves.x = f.half.x * sc;
12520
+ this.halves.y = f.half.y * sc;
12521
+ this.halves.z = f.half.z * sc;
12522
+ return this.halves;
12523
+ }
12524
+ /** The speed (m/s, up) of the point it rests on (`support`): its centre's, and its spin's about the centre there. */
12525
+ supportSpeed(f) {
12526
+ const s = this.support;
12527
+ return f.vel.y + f.ang.z * s.x - f.ang.x * s.z;
12528
+ }
12529
+ /**
12530
+ * It hits the floor hard enough to bounce: the point it comes down on goes into it faster than the rebound that lifts it `BOUNCE_LIFT_SHARE` of its thinnest half, and than one
12531
+ * step of gravity gives what lies on it.
12532
+ */
12533
+ bounces(f, params) {
12534
+ const { g, dt, sc } = params;
12535
+ const thinnest = Math.min(f.half.x, f.half.y, f.half.z) * sc;
12536
+ const least = Math.max(2 * g * dt, Math.sqrt(2 * g * BOUNCE_LIFT_SHARE * thinnest) / GROUND_RESTITUTION);
12537
+ return this.supportSpeed(f) < -least;
12538
+ }
12539
+ /**
12540
+ * The hit on the floor as an impulse at the point it comes down on (`support`): j = (1 + e) v / (1 + n · ((I⁻¹ (r × n)) × r)) per unit of mass, which sends the centre up
12541
+ * and turns it by its own inertia about that point. A box landing flat on a face is not turned; one coming down on a corner tumbles as much as its size and the hit give,
12542
+ * so a board metres long is turned as a long body is, not as a chip.
12543
+ */
12544
+ bounce(f, sc) {
12545
+ const s = this.support;
12546
+ const into = this.supportSpeed(f);
12547
+ const rough = ROUGHNESS_SHARE * Math.max(f.half.x, f.half.y, f.half.z) * sc;
12548
+ s.x += (this.rng() - 0.5) * 2 * rough;
12549
+ s.z += (this.rng() - 0.5) * 2 * rough;
12550
+ const turn2 = this.w.set(-s.z, 0, s.x);
12551
+ applyInverseInertia({ e: this.m.elements, half: this.scaledHalf(f, sc), v: turn2 });
12552
+ const share = 1 + (turn2.z * s.x - turn2.x * s.z);
12553
+ const impulse = -(1 + GROUND_RESTITUTION) * into / share;
12554
+ f.vel.y += impulse;
12555
+ f.ang.addScaledVector(turn2, impulse);
12556
+ f.vel.x *= GROUND_GLIDE;
12557
+ f.vel.z *= GROUND_GLIDE;
12558
+ f.ang.multiplyScalar(GROUND_SPIN_KEPT);
12559
+ }
12560
+ /**
12561
+ * Coulomb friction on the floor: the sliding speed falls by mu g each second, so a piece leaving at v slides v^2 / (2 mu g), as a body of the piece system does (a snapped
12562
+ * shovel handle thrown at 7.5 m/s comes to rest 5.7 m away, near the blade, not a metre from where it broke).
12563
+ */
12564
+ slide(f, g, dt) {
12565
+ const sliding = Math.hypot(f.vel.x, f.vel.z);
12566
+ const kept = sliding > 0 ? Math.max(0, sliding - DEBRIS_FRICTION * g * dt) / sliding : 0;
12567
+ f.vel.x *= kept;
12568
+ f.vel.z *= kept;
12569
+ }
12570
+ /**
12571
+ * On the floor and not bouncing: friction acts on its foot (the point it rests on), which slides or holds while the piece turns over it; it turns only as what it rests on lets
12572
+ * it (not at all on a face, only about the edge on an edge), its spin about the vertical falls by the friction under it, and gravity tips it over its foot (`settle`). True
12573
+ * while it is still turning over.
12574
+ */
12575
+ restOn(f, params) {
12576
+ const { g, dt, sc } = params;
12577
+ const s = this.support;
12578
+ const ang = f.ang;
12579
+ const dx = -s.x, dy = -s.y, dz = -s.z;
12580
+ f.vel.x -= ang.y * dz - ang.z * dy;
12581
+ f.vel.z -= ang.x * dy - ang.y * dx;
12582
+ this.slide(f, g, dt);
12583
+ const footX = f.vel.x;
12584
+ const footZ = f.vel.z;
12585
+ const half = this.scaledHalf(f, sc);
12586
+ const gyration = Math.sqrt(inertiaAbout({ e: this.m.elements, half, x: 0, y: 1, z: 0 }));
12587
+ if (gyration > 0) ang.y = Math.sign(ang.y) * Math.max(0, Math.abs(ang.y) - DEBRIS_FRICTION * g * dt / gyration);
12588
+ if (s.count >= 3) {
12589
+ ang.x = 0;
12590
+ ang.z = 0;
12591
+ } else if (s.count === 2) {
12592
+ const along2 = ang.x * s.edgeX + ang.z * s.edgeZ;
12593
+ ang.x = along2 * s.edgeX;
12594
+ ang.z = along2 * s.edgeZ;
12595
+ }
12596
+ const lever = this.lever;
12597
+ lever.x = dx;
12598
+ lever.y = dy;
12599
+ lever.z = dz;
12600
+ const slow = footX * footX + footZ * footZ < 2 * g * SETTLE_FALL_HALVES * Math.max(half.x, half.y, half.z);
12601
+ const turning = slow && this.settle(f, g, dt);
12602
+ f.vel.x = footX + (ang.y * lever.z - ang.z * lever.y);
12603
+ f.vel.y = ang.z * lever.x - ang.x * lever.z;
12604
+ f.vel.z = footZ + (ang.x * lever.y - ang.y * lever.x);
12605
+ return turning;
12606
+ }
12607
+ /**
12608
+ * Gravity tips it over what it rests on (`support`), as a rigid body tips over its foot: the turn m g × the lever from the foot to the centre (`lever`), over its inertia about
12609
+ * the foot (its own, more the lever squared), so the time to lie down goes as √(L / g), never at a fixed rate. On a face it does not turn; balanced on a face too narrow for
12610
+ * it, or on an edge, it is let over (`nudge`, which moves `lever` to that edge). Its turn this step stops where the face it falls onto reaches the floor, and that face then
12611
+ * holds it. True while it still turns.
12612
+ */
12613
+ settle(f, g, dt) {
12614
+ const s = this.support;
12615
+ const e = this.m.elements;
12616
+ const half = this.halves;
12617
+ const reach2 = Math.max(half.x, half.y, half.z);
12618
+ const lever = this.lever;
12619
+ let torqueX = g * lever.z;
12620
+ let torqueZ = -g * lever.x;
12621
+ if (s.count >= 3) {
12622
+ torqueX = 0;
12623
+ torqueZ = 0;
12624
+ } else if (s.count === 2) {
12625
+ const along2 = torqueX * s.edgeX + torqueZ * s.edgeZ;
12626
+ torqueX = along2 * s.edgeX;
12627
+ torqueZ = along2 * s.edgeZ;
12628
+ }
12629
+ const torque = Math.hypot(torqueX, torqueZ);
12630
+ const ang = f.ang;
12631
+ if (torque <= g * SUPPORT_SHARE * reach2 && ang.x === 0 && ang.z === 0) {
12632
+ if (s.count >= 3 && !this.isUnsteady(f)) return false;
12633
+ if (!this.nudge(f, g)) return false;
12634
+ } else if (torque > 0) {
12635
+ const axisX = torqueX / torque;
12636
+ const axisZ = torqueZ / torque;
12637
+ const along2 = lever.x * axisX + lever.z * axisZ;
12638
+ const inertia = inertiaAbout({ e, half, x: axisX, y: 0, z: axisZ }) + lever.x * lever.x + lever.y * lever.y + lever.z * lever.z - along2 * along2;
12639
+ ang.x += axisX * torque / inertia * dt;
12640
+ ang.z += axisZ * torque / inertia * dt;
12641
+ }
12642
+ const spin = Math.hypot(ang.x, ang.z);
12643
+ if (spin === 0) return false;
12644
+ const landing2 = turnToLanding({ corners: this.corners, pivot: { x: -lever.x, y: -lever.y, z: -lever.z }, axisX: ang.x / spin, axisZ: ang.z / spin, reach: reach2 });
12645
+ if (spin * dt > landing2) {
12646
+ ang.x *= landing2 / (spin * dt);
12647
+ ang.z *= landing2 / (spin * dt);
12648
+ }
12649
+ return true;
12650
+ }
12651
+ /**
12652
+ * It stands on a face it would not stay on: a sheet on its edge or a board on its end (the face narrower than `STAND_RATIO` of its height), or a big piece on any face but
12653
+ * its flattest.
12654
+ */
12655
+ isUnsteady(f) {
12656
+ const e = this.m.elements;
12657
+ const up = [Math.abs(e[1]), Math.abs(e[5]), Math.abs(e[9])];
12658
+ const half = [f.half.x, f.half.y, f.half.z];
12659
+ let small = 0;
12660
+ let standing = 0;
12661
+ for (let i = 1; i < 3; i++) {
12662
+ if (half[i] < half[small]) small = i;
12663
+ if (up[i] > up[standing]) standing = i;
12664
+ }
12665
+ if (f.body) return half[standing] > half[small] * (1 + SUPPORT_SHARE);
12666
+ const across = Math.min(...half.filter((_, i) => i !== standing));
12667
+ return across < STAND_RATIO * half[standing];
12668
+ }
12669
+ /**
12670
+ * Let over the edge towards lying on its flattest face, from balance: the spin about that edge that lifts its centre over it with `NUDGE_ENERGY_SHARE` to spare (½ I ω² =
12671
+ * m g Δh), so it falls from there by its own weight, as a piece a breath tipped over. The edge becomes the lever (`lever`). False when there is no way down to that face.
12672
+ */
12673
+ nudge(f, g) {
12674
+ const e = this.m.elements;
12675
+ const half = this.halves;
12676
+ const tolerance = SUPPORT_SHARE * Math.max(half.x, half.y, half.z);
12677
+ let small = 0;
12678
+ if (half.y < half.x) small = 1;
12679
+ if (half.z < (small === 1 ? half.y : half.x)) small = 2;
12680
+ const sign = e[small * 4 + 1] >= 0 ? 1 : -1;
12681
+ const axisX = -e[small * 4 + 2] * sign;
12682
+ const axisZ = e[small * 4] * sign;
12683
+ const length = Math.hypot(axisX, axisZ);
12684
+ if (length < SUPPORT_SHARE) return false;
12685
+ const kx = axisX / length;
12686
+ const kz = axisZ / length;
12687
+ const c = this.corners;
12688
+ const floor2 = this.support.y + tolerance;
12689
+ let far2 = -Infinity;
12690
+ for (let i = 0; i < 8; i++) if (c[3 * i + 1] <= floor2) far2 = Math.max(far2, kx * c[3 * i + 2] - kz * c[3 * i]);
12691
+ let count = 0, x = 0, y = 0, z = 0;
12692
+ for (let i = 0; i < 8; i++) {
12693
+ if (c[3 * i + 1] > floor2 || kx * c[3 * i + 2] - kz * c[3 * i] < far2 - tolerance) continue;
12694
+ count++;
12695
+ x += c[3 * i];
12696
+ y += c[3 * i + 1];
12697
+ z += c[3 * i + 2];
12698
+ }
12699
+ const lever = this.lever;
12700
+ lever.x = -x / count;
12701
+ lever.y = -y / count;
12702
+ lever.z = -z / count;
12703
+ const along2 = lever.x * kx + lever.z * kz;
12704
+ const square = lever.x * lever.x + lever.y * lever.y + lever.z * lever.z - along2 * along2;
12705
+ const rise = Math.max(Math.sqrt(square) - lever.y, tolerance);
12706
+ const inertia = inertiaAbout({ e, half, x: kx, y: 0, z: kz }) + square;
12707
+ const spinOfInertia = Math.sqrt(2 * g * rise * (1 + NUDGE_ENERGY_SHARE) / inertia);
12708
+ f.ang.x = kx * spinOfInertia;
12709
+ f.ang.z = kz * spinOfInertia;
12710
+ return true;
12711
+ }
12140
12712
  /** Remove the fragments of one object (after `restore`). */
12141
12713
  removeHome(home) {
12142
12714
  for (let i = this.list.length - 1; i >= 0; i--) {
@@ -14876,6 +15448,10 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
14876
15448
  var TILE_KEY_ORIGIN = 32768;
14877
15449
  var MU_STATIC = 0.7;
14878
15450
  var ROLLING_RESISTANCE = 0.015;
15451
+ var roundPartsRadius = (parts) => {
15452
+ if (!parts || parts.length === 0 || !parts.every((part) => part.round && !part.hull)) return void 0;
15453
+ return Math.max(...parts.map((part) => (part.half[0] + part.half[2]) / 2));
15454
+ };
14879
15455
  var MU_DYNAMIC = 0.6;
14880
15456
  var GROUND = { frictionStatic: MU_STATIC, frictionDynamic: MU_DYNAMIC, restitution: 0, rolling: ROLLING_RESISTANCE };
14881
15457
  var tileRollingAt = (rollingAt, x, z) => rollingAt((Math.floor(x / TILE) + 0.5) * TILE, (Math.floor(z / TILE) + 0.5) * TILE);
@@ -15424,9 +16000,13 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
15424
16000
  out[round2.axis] = about;
15425
16001
  return out;
15426
16002
  }
15427
- /** A round piece rolls to a stop by its surface's rolling resistance (the adapter's rule; the engine has none). */
16003
+ /**
16004
+ * A round piece rolls to a stop by its surface's rolling resistance (the adapter's rule; the engine has none). Round is its shape: the `round` of the piece, or parts
16005
+ * that are all cylinders (a valve knob cut off a shower), which roll on the widest of them; without it such a knob rolled 9 m and was still rolling 8 s later.
16006
+ */
15428
16007
  rollingOf(b) {
15429
- return b.round ? { coefficient: b.friction?.rolling ?? ROLLING_RESISTANCE, radius: b.round.radius, damping: b.friction?.rollingDamping ?? PIECE_ROLLING_DAMPING } : void 0;
16008
+ const radius = b.round?.radius ?? roundPartsRadius(b.partBoxes);
16009
+ return radius === void 0 ? void 0 : { coefficient: b.friction?.rolling ?? ROLLING_RESISTANCE, radius, damping: b.friction?.rollingDamping ?? PIECE_ROLLING_DAMPING };
15430
16010
  }
15431
16011
  material(b) {
15432
16012
  return {
@@ -16387,46 +16967,6 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
16387
16967
  return { loop: createPhysicsLoop(option), stepsItself: true };
16388
16968
  };
16389
16969
 
16390
- // src/support-hull.ts
16391
- var cross2 = (o, a, b) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
16392
- function planHull(points) {
16393
- const sorted = [...points].sort((a, b) => a[0] - b[0] || a[1] - b[1]);
16394
- if (sorted.length < 3) return sorted;
16395
- const lower = [];
16396
- for (const p of sorted) {
16397
- while (lower.length >= 2 && cross2(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) lower.pop();
16398
- lower.push(p);
16399
- }
16400
- const upper = [];
16401
- for (let i = sorted.length - 1; i >= 0; i--) {
16402
- const p = sorted[i];
16403
- while (upper.length >= 2 && cross2(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) upper.pop();
16404
- upper.push(p);
16405
- }
16406
- return [...lower.slice(0, -1), ...upper.slice(0, -1)];
16407
- }
16408
- function toSegment(p, a, b) {
16409
- const dx = b[0] - a[0];
16410
- const dz = b[1] - a[1];
16411
- const length = dx * dx + dz * dz;
16412
- const t = length > 0 ? Math.max(0, Math.min(1, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dz) / length)) : 0;
16413
- return Math.hypot(p[0] - a[0] - t * dx, p[1] - a[1] - t * dz);
16414
- }
16415
- function isOverSupport(points, centre, tolerance) {
16416
- const hull = planHull(points);
16417
- if (hull.length === 0) return false;
16418
- if (hull.length === 1) return Math.hypot(centre[0] - hull[0][0], centre[1] - hull[0][1]) <= tolerance;
16419
- let inside = hull.length >= 3;
16420
- let nearest = Infinity;
16421
- for (let i = 0; i < hull.length; i++) {
16422
- const a = hull[i];
16423
- const b = hull[(i + 1) % hull.length];
16424
- if (hull.length >= 3 && cross2(a, b, centre) < 0) inside = false;
16425
- nearest = Math.min(nearest, toSegment(centre, a, b));
16426
- }
16427
- return inside || nearest <= tolerance;
16428
- }
16429
-
16430
16970
  // src/pieces.ts
16431
16971
  var BALANCE_TOLERANCE = 0.01;
16432
16972
  var MU_STATIC2 = 0.7;
@@ -21318,6 +21858,12 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
21318
21858
  var MASONRY_CRUMBLE_SPEED = 0.6;
21319
21859
  var MASONRY_TOPPLE = 0.4;
21320
21860
  var MASONRY_TOPPLE_MIN_HEIGHT = 0.5;
21861
+ var SPIN_REACH = 0.1;
21862
+ var bornSpin = (size, chipSpin, rnd2) => {
21863
+ const reach2 = Math.hypot(size[0] ?? 0, size[1] ?? 0, size[2] ?? 0) / 2;
21864
+ const scale = reach2 <= SPIN_REACH ? 1 : SPIN_REACH / reach2;
21865
+ return [(rnd2() - 0.5) * chipSpin * scale, (rnd2() - 0.5) * chipSpin * scale, (rnd2() - 0.5) * chipSpin * scale];
21866
+ };
21321
21867
  var TILE_CLUMPS = 160;
21322
21868
  var TILE_THICKNESS = 0.018;
21323
21869
  var PANEL_EDGE_PILLAR = 2;
@@ -21897,7 +22443,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
21897
22443
  return (above2 + p.st.mass * share) / load;
21898
22444
  };
21899
22445
  };
21900
- const contactsOf = (p, support) => {
22446
+ const contactsOf2 = (p, support) => {
21901
22447
  const box = contactBox(p, support);
21902
22448
  const broken = support.rt.broken;
21903
22449
  if (!broken?.length) return [box];
@@ -21942,7 +22488,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
21942
22488
  }
21943
22489
  const corners = [];
21944
22490
  for (const k of lower) {
21945
- for (const [lo, hi] of contactsOf(p, o.parts[k])) {
22491
+ for (const [lo, hi] of contactsOf2(p, o.parts[k])) {
21946
22492
  for (let c = 0; c < 4; c++) {
21947
22493
  const local2 = [c & 1 ? hi[0] : lo[0], (lo[1] + hi[1]) / 2, c & 2 ? hi[2] : lo[2]];
21948
22494
  const at3 = toWorld(p.pos, p.q, local2);
@@ -21998,13 +22544,13 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
21998
22544
  };
21999
22545
  const specSpans = /* @__PURE__ */ new WeakMap();
22000
22546
  const spanOver = (p, g, supports) => {
22001
- if (p.posed || supports.some((k) => k.posed || k.rt.broken?.length)) return spanOf(g, supports.flatMap((k) => contactsOf(p, k)));
22547
+ if (p.posed || supports.some((k) => k.posed || k.rt.broken?.length)) return spanOf(g, supports.flatMap((k) => contactsOf2(p, k)));
22002
22548
  let byKey = specSpans.get(p.spec);
22003
22549
  if (!byKey) specSpans.set(p.spec, byKey = /* @__PURE__ */ new Map());
22004
22550
  const key = supports.map((k) => k.spec.id).join("\0");
22005
22551
  const known = byKey.get(key);
22006
22552
  if (known !== void 0) return known;
22007
- const span = spanOf(g, supports.flatMap((k) => contactsOf(p, k)));
22553
+ const span = spanOf(g, supports.flatMap((k) => contactsOf2(p, k)));
22008
22554
  byKey.set(key, span);
22009
22555
  return span;
22010
22556
  };
@@ -22092,7 +22638,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
22092
22638
  }
22093
22639
  const d = p.dims;
22094
22640
  const L = [0, 1, 2].sort((a, b) => d[b] - d[a])[0];
22095
- const spans2 = supports.flatMap((k) => contactsOf(p, k)).map(([lo, hi]) => [lo[L], hi[L]]);
22641
+ const spans2 = supports.flatMap((k) => contactsOf2(p, k)).map(([lo, hi]) => [lo[L], hi[L]]);
22096
22642
  let far2 = 0;
22097
22643
  for (let i = 0; i <= 16; i++) {
22098
22644
  const x = (i / 16 - 0.5) * d[L];
@@ -23933,7 +24479,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
23933
24479
  size: [cell.size[0], cell.size[1], cell.size[2]],
23934
24480
  rotation: q,
23935
24481
  velocity: [dv[0] * k, dv[1] * k + 0.5 * rnd2(), dv[2] * k],
23936
- angularVelocity: [(rnd2() - 0.5) * 8, (rnd2() - 0.5) * 8, (rnd2() - 0.5) * 8],
24482
+ angularVelocity: bornSpin(cell.size, 8, rnd2),
23937
24483
  mass: mass * faceArea(cell) / total,
23938
24484
  ...marks.length > 0 ? { marks } : {},
23939
24485
  ...inner && laid ? { unit: true } : inner ? { inner } : {}
@@ -23972,7 +24518,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
23972
24518
  size,
23973
24519
  rotation: q,
23974
24520
  velocity: [out0[0] * k, out0[1] * k + 0.5 * rnd2(), out0[2] * k],
23975
- angularVelocity: [(rnd2() - 0.5) * 12, (rnd2() - 0.5) * 12, (rnd2() - 0.5) * 12],
24521
+ angularVelocity: bornSpin(size, 12, rnd2),
23976
24522
  mass: layer3.mat.density * size[0] * size[1] * size[2]
23977
24523
  });
23978
24524
  }
@@ -24298,7 +24844,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
24298
24844
  size,
24299
24845
  rotation: q,
24300
24846
  velocity: [vdir[0] * k, vdir[1] * k + 0.5 * rnd2(), vdir[2] * k],
24301
- angularVelocity: [(rnd2() - 0.5) * 20, (rnd2() - 0.5) * 20, (rnd2() - 0.5) * 20],
24847
+ angularVelocity: bornSpin(size, 20, rnd2),
24302
24848
  mass: mass / n,
24303
24849
  inner: true
24304
24850
  });
@@ -24704,7 +25250,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
24704
25250
  size: f.size,
24705
25251
  rotation: quat.mul(q, f.q),
24706
25252
  velocity: [dv[0] * k, dv[1] * k + 0.5 * rnd2(), dv[2] * k],
24707
- angularVelocity: [(rnd2() - 0.5) * 12, (rnd2() - 0.5) * 12, (rnd2() - 0.5) * 12],
25253
+ angularVelocity: bornSpin(f.size, 12, rnd2),
24708
25254
  mass: mass * f.weight / totW,
24709
25255
  ...marks.length > 0 ? { marks } : {},
24710
25256
  ...f.inner ? { inner: true } : {}
@@ -24843,7 +25389,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
24843
25389
  rotation: q,
24844
25390
  velocity: v,
24845
25391
  inner: true,
24846
- angularVelocity: [(rnd2() - 0.5) * 30, (rnd2() - 0.5) * 30, (rnd2() - 0.5) * 30],
25392
+ angularVelocity: bornSpin(size, 30, rnd2),
24847
25393
  mass
24848
25394
  });
24849
25395
  }
@@ -29022,8 +29568,10 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
29022
29568
  var STATIC_REFRESH = 0.5;
29023
29569
  var STATIC_REFRESH_PER_UPDATE = 8;
29024
29570
  var SURFACE_RAYS = 4;
29025
- var SURFACE_INSIDE = 5e-3;
29571
+ var SURFACE_INSIDE = 1e-3;
29026
29572
  var SURFACE_STEP = 0.15;
29573
+ var MOVER_MIN_MOVE = 1e-3;
29574
+ var MOVER_RAYS = 4;
29027
29575
  var STATIC_SPAN = 3;
29028
29576
  var VERTICES_PER_UPDATE = 3e3;
29029
29577
  var FEET_BAND = 0.03;
@@ -29166,7 +29714,8 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
29166
29714
  var UNDERMINED_STAND = 0.4;
29167
29715
  var UNDERMINED_KEEP = 0.6;
29168
29716
  var SOLIDS_MAX = 64;
29169
- var UNDERMINED_PUSH = 0.6;
29717
+ var UNDERMINED_FROUDE = 0.13;
29718
+ var GRAVITY5 = 9.81;
29170
29719
  var DEBRIS_ID = "debris#";
29171
29720
  var UNDERMINED_STILL = 0.05;
29172
29721
  var SOLID_WELD = 1e-4;
@@ -29433,6 +29982,15 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
29433
29982
  __publicField(this, "stopContactHits", null);
29434
29983
  __publicField(this, "box");
29435
29984
  __publicField(this, "tmpQ");
29985
+ /** The pieces that moved this update, as the fragments see them (`collectMovers`), and the record kept per piece. */
29986
+ __publicField(this, "moving", []);
29987
+ __publicField(this, "movers", /* @__PURE__ */ new WeakMap());
29988
+ __publicField(this, "moverFrom");
29989
+ __publicField(this, "moverTo");
29990
+ __publicField(this, "moverBox");
29991
+ __publicField(this, "moverBoxMoved");
29992
+ /** The box of a geometry's positions, made once (`drawnBoxOf`). */
29993
+ __publicField(this, "geometryBoxes", /* @__PURE__ */ new WeakMap());
29436
29994
  __publicField(this, "v1");
29437
29995
  __publicField(this, "v2");
29438
29996
  __publicField(this, "v3");
@@ -29461,6 +30019,10 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
29461
30019
  this.workCosts = resolveWorkUnitCosts(o.workBudget?.costs);
29462
30020
  this.box = new THREE.Box3();
29463
30021
  this.tmpQ = new THREE.Quaternion();
30022
+ this.moverFrom = new THREE.Matrix4();
30023
+ this.moverTo = new THREE.Matrix4();
30024
+ this.moverBox = new THREE.Box3();
30025
+ this.moverBoxMoved = new THREE.Box3();
29464
30026
  this.v1 = new THREE.Vector3();
29465
30027
  this.v2 = new THREE.Vector3();
29466
30028
  this.v3 = new THREE.Vector3();
@@ -29490,6 +30052,8 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
29490
30052
  sweep: (from, direction, distance) => typeof this.world.raycast === "function" ? this.world.raycast([from[0], from[1], from[2]], [direction[0], direction[1], direction[2]], distance) : null,
29491
30053
  maxAwake: o.maxAwakeFragments ?? Infinity,
29492
30054
  ...o.interpolate ? { interpolate: true } : {},
30055
+ // the loose pieces that moved: the scraps on and in them go with them, and a part coming at a scrap meets it
30056
+ movers: () => this.moving,
29493
30057
  rigid: {
29494
30058
  add: (mesh2, half, mass, velocity, angular) => {
29495
30059
  const body = this.pieceSys.create(`${DEBRIS_ID}${++this.debrisMade}`, mesh2, [half[0], half[1], half[2]], new THREE.Vector3(), mass, [velocity[0], velocity[1], velocity[2]], [angular[0], angular[1], angular[2]]);
@@ -30093,6 +30657,8 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
30093
30657
  this.pieceSys.update(dt);
30094
30658
  this.measureCost();
30095
30659
  this.updateFading(dt);
30660
+ this.collectMovers();
30661
+ this.syncTransforms();
30096
30662
  this.fragments.update(dt);
30097
30663
  this.updateActive(dt);
30098
30664
  this.updateLeaks(dt);
@@ -31026,13 +31592,13 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
31026
31592
  }
31027
31593
  /**
31028
31594
  * Plays the effect the event map names for a destruction event (`data/event-effects.json` of `game-vfx`, or `RendererOptions.eventEffects`) at a point.
31029
- * `play` gives the family of the material (the map's `{material}`) and the colours of its debris and dust. Answers whether one played, so the caller can
31030
- * leave out the burst it replaces.
31595
+ * `play` gives the family of the material (the map's `{material}`) and the colours of its debris and dust, `normal` the face it happened on (world). Answers
31596
+ * whether one played, so the caller can leave out the burst it replaces.
31031
31597
  */
31032
- playEvent(event, point, play) {
31598
+ playEvent(event, point, play, normal) {
31033
31599
  const id = effectForEvent(play && event.material === void 0 ? { ...event, material: play.material } : event, this.o.eventEffects ?? EVENT_EFFECTS_MAP);
31034
31600
  if (!id) return false;
31035
- return this.vfx.play(id, point, { seed: hashNumbers(point[0], point[1], point[2], this.time), ...play ? { values: play.values } : {} }) !== null;
31601
+ return this.vfx.play(id, point, { seed: hashNumbers(point[0], point[1], point[2], this.time), ...play ? { values: play.values } : {}, ...normal ? { normal } : {} }) !== null;
31036
31602
  }
31037
31603
  /** The family and colours of a part's material, for the effects of the event map. */
31038
31604
  partPlay(objectId, partId) {
@@ -31052,7 +31618,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
31052
31618
  const core = def?.visual?.innerColor;
31053
31619
  const look = debrisLook(def, "spall", { partColor: this.partColor(pv, def) ?? void 0 });
31054
31620
  if (core !== void 0 || look.impact === void 0) this.vfx.burst(look.debris, ev.point, [normal.x, normal.y, normal.z], 5, 2.5, { color: look.color });
31055
- else this.playEvent({ kind: "spall", material: look.impact }, ev.point);
31621
+ else this.playEvent({ kind: "spall", material: look.impact }, ev.point, void 0, [normal.x, normal.y, normal.z]);
31056
31622
  if (core !== void 0) this.trickleFrom(ev.point, [normal.x, normal.y, normal.z], core, mv);
31057
31623
  if (mv.mesh.userData.drawnSpalls?.includes(ev.part)) return;
31058
31624
  this.visuals.addSpall(mv, wp, normal, Math.sqrt(ev.area / Math.PI), core ?? fallbackColor(def));
@@ -31594,6 +32160,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
31594
32160
  }
31595
32161
  }
31596
32162
  this.bounds.set(newId, nb);
32163
+ nb.lastWorld = Float64Array.from(group.matrixWorld.elements);
31597
32164
  for (const pv of nb.parts.values()) this.tagPart(pv, newId);
31598
32165
  this.followSplit(from, nb);
31599
32166
  const meshes = this.meshesOf(nb);
@@ -31772,7 +32339,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
31772
32339
  body.sleeping = false;
31773
32340
  body.still = 0;
31774
32341
  body.calmAt = null;
31775
- if (held.length > 0 && length > 1e-6) this.pieceSys.ruleImpulse(KIT_RULE.CHECK_UNDERMINED, body, [0, -body.mass * UNDERMINED_PUSH, 0], [centre[0] + gx, floor2, centre[2] + gz]);
32342
+ if (held.length > 0 && length > 1e-6) this.pieceSys.ruleImpulse(KIT_RULE.CHECK_UNDERMINED, body, [0, -body.mass * startDownSpeed(centre[1] - floor2), 0], [centre[0] + gx, floor2, centre[2] + gz]);
31776
32343
  if (!was) this.o.onLoosened?.(b.id, body, "ground");
31777
32344
  }
31778
32345
  }
@@ -31789,7 +32356,8 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
31789
32356
  if (this.standsWith(held, null, centre, feet.floor)) return;
31790
32357
  const inside = insideBy(convexHull2(held), [centre[0], centre[2]]);
31791
32358
  const reach2 = this.reachAlong(body, inside.out.x, inside.out.z);
31792
- this.pieceSys.ruleImpulse(KIT_RULE.GO_OVER_IF_BALANCED, body, [0, -body.mass * UNDERMINED_PUSH, 0], [centre[0] + inside.out.x * reach2, feet.floor, centre[2] + inside.out.z * reach2]);
32359
+ const mid = this.pieceSys.centerOf(body, new this.THREE.Vector3());
32360
+ this.pieceSys.ruleImpulse(KIT_RULE.GO_OVER_IF_BALANCED, body, [0, -body.mass * startDownSpeed(centre[1] - feet.floor), 0], [mid.x + inside.out.x * reach2, feet.floor, mid.z + inside.out.z * reach2]);
31793
32361
  }
31794
32362
  /** How far (m) the box of a piece reaches from its middle along the level direction (x, z), turned as it is: the support of its box that way. */
31795
32363
  reachAlong(body, x, z) {
@@ -31894,6 +32462,103 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
31894
32462
  }
31895
32463
  return "";
31896
32464
  }
32465
+ /**
32466
+ * The loose pieces that moved since the world was last told where they are (`FragmentSystemOptions.movers`), read before it is told: each with the box it took then and
32467
+ * takes now, its move, and a ray through its own parts.
32468
+ */
32469
+ collectMovers() {
32470
+ const out = this.moving;
32471
+ out.length = 0;
32472
+ for (const b of this.bounds.values()) {
32473
+ const piece = b.piece;
32474
+ const was = b.lastWorld;
32475
+ if (!piece || piece.sleeping || !b.sync || !was || !this.world.has(b.id)) continue;
32476
+ b.root.updateWorldMatrix(true, false);
32477
+ const now = b.root.matrixWorld.elements;
32478
+ let same2 = true;
32479
+ for (let i = 0; i < 16 && same2; i++) same2 = now[i] === was[i];
32480
+ if (same2) continue;
32481
+ let solid = this.movers.get(b);
32482
+ if (!solid) {
32483
+ solid = this.moverOf(b.id);
32484
+ this.movers.set(b, solid);
32485
+ }
32486
+ const before = this.moverFrom.fromArray(was);
32487
+ this.moverTo.copy(b.root.matrixWorld).multiply(before.invert()).toArray(solid.delta);
32488
+ const box = solid.box;
32489
+ box.fill(Infinity, 0, 3);
32490
+ box.fill(-Infinity, 3, 6);
32491
+ this.drawnBoxOf(b.root, this.moverBox);
32492
+ const back = this.moverFrom.fromArray(solid.delta).invert();
32493
+ if (this.farthestCorner(back) < MOVER_MIN_MOVE) continue;
32494
+ this.growBox(box);
32495
+ this.growBox(box, back);
32496
+ out.push(solid);
32497
+ }
32498
+ }
32499
+ /**
32500
+ * The world box of what is drawn under `root`, from the box of each mesh's positions, kept per geometry here: never by `Box3.setFromObject`, which writes a bounding box
32501
+ * into each geometry it reads and so changes what the piece is made of for anyone who reads it whole.
32502
+ */
32503
+ drawnBoxOf(root, out) {
32504
+ out.makeEmpty();
32505
+ root.updateWorldMatrix(true, true);
32506
+ root.traverseVisible((node) => {
32507
+ const mesh2 = node;
32508
+ const position = mesh2.isMesh ? mesh2.geometry?.getAttribute("position") : void 0;
32509
+ if (!position) return;
32510
+ let local2 = this.geometryBoxes.get(mesh2.geometry);
32511
+ if (!local2) {
32512
+ local2 = new this.THREE.Box3().setFromBufferAttribute(position);
32513
+ this.geometryBoxes.set(mesh2.geometry, local2);
32514
+ }
32515
+ out.union(this.moverBoxMoved.copy(local2).applyMatrix4(mesh2.matrixWorld));
32516
+ });
32517
+ }
32518
+ /** How far (m) the corner of `moverBox` that moves most goes under `matrix`. */
32519
+ farthestCorner(matrix) {
32520
+ if (this.moverBox.isEmpty()) return 0;
32521
+ const { min: min2, max: max2 } = this.moverBox;
32522
+ let most = 0;
32523
+ for (let i = 0; i < 8; i++) {
32524
+ const corner = this.v1.set(i & 1 ? max2.x : min2.x, i & 2 ? max2.y : min2.y, i & 4 ? max2.z : min2.z);
32525
+ const x = corner.x, y = corner.y, z = corner.z;
32526
+ corner.applyMatrix4(matrix);
32527
+ most = Math.max(most, Math.hypot(corner.x - x, corner.y - y, corner.z - z));
32528
+ }
32529
+ return most;
32530
+ }
32531
+ /** `box` grown by `moverBox`, under `matrix` when one is given. */
32532
+ growBox(box, matrix) {
32533
+ if (this.moverBox.isEmpty()) return;
32534
+ const at3 = matrix ? this.moverBoxMoved.copy(this.moverBox).applyMatrix4(matrix) : this.moverBox;
32535
+ box[0] = Math.min(box[0], at3.min.x);
32536
+ box[1] = Math.min(box[1], at3.min.y);
32537
+ box[2] = Math.min(box[2], at3.min.z);
32538
+ box[3] = Math.max(box[3], at3.max.x);
32539
+ box[4] = Math.max(box[4], at3.max.y);
32540
+ box[5] = Math.max(box[5], at3.max.z);
32541
+ }
32542
+ /** A moving piece as the fragments see it, made once per bound object: its sweep meets only its own parts, the first of them past whatever else is on the way. */
32543
+ moverOf(objectId) {
32544
+ return {
32545
+ box: [0, 0, 0, 0, 0, 0],
32546
+ delta: new Array(16).fill(0),
32547
+ sweep: (from, direction, distance) => {
32548
+ let start = [from[0], from[1], from[2]];
32549
+ let left = distance;
32550
+ for (let k = 0; k < MOVER_RAYS && left > 0; k++) {
32551
+ const hit = this.world.raycast(start, [direction[0], direction[1], direction[2]], left);
32552
+ if (!hit) return null;
32553
+ if (hit.object === objectId) return { point: [start[0] + direction[0] * hit.distance, start[1] + direction[1] * hit.distance, start[2] + direction[2] * hit.distance], normal: hit.normal };
32554
+ const past = hit.distance + SURFACE_INSIDE;
32555
+ start = [start[0] + direction[0] * past, start[1] + direction[1] * past, start[2] + direction[2] * past];
32556
+ left -= past;
32557
+ }
32558
+ return null;
32559
+ }
32560
+ };
32561
+ }
31897
32562
  /** The top of the ground or of a standing part of the world under (x, z), below height y: a ray straight down through the destruction world. */
31898
32563
  surfaceAt(x, y, z) {
31899
32564
  const ground = this.groundAt(x, z);
@@ -32854,6 +33519,9 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
32854
33519
  };
32855
33520
  return [...half(sorted), ...half([...sorted].reverse())];
32856
33521
  }
33522
+ function startDownSpeed(height) {
33523
+ return UNDERMINED_FROUDE * Math.sqrt(GRAVITY5 * height);
33524
+ }
32857
33525
  function centreOfBoxes(boxes) {
32858
33526
  const sum = [0, 0, 0];
32859
33527
  let total = 0;