@adatechnology/game-destruction-three 1.2.0 → 1.3.1

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.
@@ -57,6 +57,8 @@ var GameDestructionThree = (() => {
57
57
  IMPACT_FAMILY_TAGS: () => IMPACT_FAMILY_TAGS,
58
58
  IMPACT_SOUNDS: () => IMPACT_SOUNDS,
59
59
  IMPACT_SOUND_KEYS: () => IMPACT_SOUND_KEYS,
60
+ KIT_ENERGY_RESOLUTION: () => KIT_ENERGY_RESOLUTION,
61
+ KIT_RULE: () => KIT_RULE,
60
62
  MIN_PIECE_MASS_KG: () => MIN_PIECE_MASS_KG,
61
63
  PhysicsOptionError: () => PhysicsOptionError,
62
64
  ROCKET_MOTOR_LOOP: () => ROCKET_MOTOR_LOOP,
@@ -4110,7 +4112,6 @@ var GameDestructionThree = (() => {
4110
4112
  ...DEBRIS_EFFECT_FAMILIES.flatMap((family) => [stageCrack(family), breachDust(family), collapseDust(family)]),
4111
4113
  REBAR_EXPOSE
4112
4114
  ];
4113
- var FACING5 = [0, 0, 1];
4114
4115
  var ORIGIN2 = [0, 0, 0];
4115
4116
  var FORWARD4 = [0, 0, -1];
4116
4117
  var IMPACT_MATERIALS = ["concrete", "metal", "wood", "glass", "flesh", "water"];
@@ -4120,7 +4121,7 @@ var GameDestructionThree = (() => {
4120
4121
  team: "weapons",
4121
4122
  budget: { particles: 40, decals: 1 },
4122
4123
  loop: 2,
4123
- timeline: [call2("impact", material, ORIGIN2, FACING5, 1, 0)]
4124
+ timeline: [call2("impact", material, ORIGIN2, NORMAL, 1, 0)]
4124
4125
  });
4125
4126
  var muzzleEffect = (weapon) => ({
4126
4127
  id: `muzzle_${weapon}`,
@@ -7826,7 +7827,6 @@ var GameDestructionThree = (() => {
7826
7827
  var FIRE_FLICKER_SWAY = 0.25;
7827
7828
  var FIRE_FLICKER_JITTER = 0.08;
7828
7829
  var LENS_FADE = 0.16;
7829
- var FLOOR_NORMAL_Y = 0.9;
7830
7830
  function rotate2(q, v) {
7831
7831
  const [qx, qy, qz, qw] = q;
7832
7832
  const ix = qw * v[0] + qy * v[2] - qz * v[1];
@@ -7963,7 +7963,7 @@ var GameDestructionThree = (() => {
7963
7963
  const [x, y, z] = this.place([recipe2[0], recipe2[1], recipe2[2]]);
7964
7964
  const options = recipe2[5];
7965
7965
  const normal = options?.n ? this.turn(options.n) : void 0;
7966
- const onFloor = !normal || normal[1] > FLOOR_NORMAL_Y;
7966
+ const onFloor = !normal;
7967
7967
  args = [x, onFloor ? this.context.groundAt(x, z) : y, z, recipe2[3], recipe2[4], normal ? { ...options, n: normal } : options];
7968
7968
  }
7969
7969
  this.context.trace?.("decal", args);
@@ -10923,6 +10923,78 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
10923
10923
  return box;
10924
10924
  }
10925
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
+
10926
10998
  // src/fragment-instances.ts
10927
10999
  var INSTANCED_FRAGMENT_LAYER = 29;
10928
11000
  var FRAGMENT_INSTANCES_NAME = "fragment-instances";
@@ -11418,6 +11490,67 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
11418
11490
  out.set(x / length, y / length, z / length, w / length);
11419
11491
  }
11420
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
+
11421
11554
  // src/fragments.ts
11422
11555
  function rotationOf(q) {
11423
11556
  const { x, y, z, w } = q;
@@ -11440,6 +11573,20 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
11440
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];
11441
11574
  }
11442
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
+ }
11443
11590
  function shadowsOverlap(first, second, dx, dz) {
11444
11591
  for (const shadow of [first, second]) {
11445
11592
  for (let g = 0; g < 6; g += 2) {
@@ -11490,8 +11637,18 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
11490
11637
  var WALL_RESTITUTION = 0.25;
11491
11638
  var WALL_GLIDE = 0.7;
11492
11639
  var TUMBLE_REACH = 0.1;
11640
+ var GROUND_RESTITUTION = 0.25;
11641
+ var GROUND_GLIDE = 0.7;
11642
+ var GROUND_SPIN_KEPT = 0.55;
11643
+ var BOUNCE_LIFT_SHARE = 0.05;
11644
+ var ROUGHNESS_SHARE = 0.05;
11645
+ var SETTLE_FALL_HALVES = 2;
11646
+ var NUDGE_ENERGY_SHARE = 0.1;
11647
+ var DEBRIS_BOUNCE_SPEED = 0.6;
11648
+ var DEBRIS_LAY_RATE = 7;
11493
11649
  var LAID_GAP = 5e-3;
11494
11650
  var STAND_RATIO = 0.6;
11651
+ var FADE_SECONDS3 = 0.6;
11495
11652
  var SETTLE_SECONDS = 0.4;
11496
11653
  var isSlow = (f) => f.vel.lengthSq() < 0.012 && f.ang.lengthSq() < 0.2;
11497
11654
  var isBig = (size) => {
@@ -11522,6 +11679,11 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
11522
11679
  __publicField(this, "v");
11523
11680
  __publicField(this, "w");
11524
11681
  __publicField(this, "rng", createRng(FRAGMENT_SEED));
11682
+ /** 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. */
11683
+ __publicField(this, "corners", new Float64Array(24));
11684
+ __publicField(this, "support", createSupport());
11685
+ __publicField(this, "halves", { x: 0, y: 0, z: 0 });
11686
+ __publicField(this, "lever", { x: 0, y: 0, z: 0 });
11525
11687
  /** The fragments in flight drawn by instances, a draw per shared geometry and material (`FragmentInstances`). */
11526
11688
  __publicField(this, "instances");
11527
11689
  /** 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`. */
@@ -11823,6 +11985,13 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
11823
11985
  continue;
11824
11986
  }
11825
11987
  if (this.clock > f.deadline) {
11988
+ const held = this.heldUntil(f);
11989
+ if (held > f.deadline) {
11990
+ f.deadline = held;
11991
+ if (held < next) next = held;
11992
+ this.mortal[kept++] = f;
11993
+ continue;
11994
+ }
11826
11995
  f.isMortal = false;
11827
11996
  f.dying = true;
11828
11997
  f.mesh.matrixAutoUpdate = true;
@@ -11835,6 +12004,26 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
11835
12004
  this.mortal.length = kept;
11836
12005
  this.nextDeadline = next;
11837
12006
  }
12007
+ /**
12008
+ * 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
12009
+ * 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.
12010
+ */
12011
+ heldUntil(f) {
12012
+ const box = f.box ?? (f.box = restingBox(f));
12013
+ let until = f.deadline;
12014
+ for (const other of this.list) {
12015
+ if (other === f || other.rigid || other.body) continue;
12016
+ const on = other.box ?? (other.box = restingBox(other));
12017
+ const e = rotationOf(other.mesh.quaternion);
12018
+ 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);
12019
+ if (bottom <= f.mesh.position.y || bottom > box.top + SUPPORT_GAP) continue;
12020
+ if (Math.abs(on.x - box.x) >= on.reachX + box.reachX || Math.abs(on.z - box.z) >= on.reachZ + box.reachZ) continue;
12021
+ if (!shadowsOverlap(box.shadow, on.shadow, on.x - box.x, on.z - box.z)) continue;
12022
+ const gone = other.dying ? this.clock + other.fade * FADE_SECONDS3 : other.asleep ? other.deadline + FADE_SECONDS3 : this.clock + SETTLE_SECONDS;
12023
+ until = Math.max(until, gone);
12024
+ }
12025
+ return until;
12026
+ }
11838
12027
  /** What lies inside the disc looks at the ground again: it was dug or heaped under it. */
11839
12028
  wakeRegion(x, z, radius) {
11840
12029
  for (const f of this.list) {
@@ -11853,7 +12042,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
11853
12042
  const f = this.active[i];
11854
12043
  if (f.dying) {
11855
12044
  f.mesh.matrixAutoUpdate = true;
11856
- f.fade -= dt / 0.6;
12045
+ f.fade -= dt / FADE_SECONDS3;
11857
12046
  if (f.fade <= 0) {
11858
12047
  this.instances.remove(f.mesh);
11859
12048
  this.o.scene.remove(f.mesh);
@@ -12002,36 +12191,22 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
12002
12191
  if (mesh2.position.y - ext < gy) {
12003
12192
  contact = true;
12004
12193
  mesh2.position.y = gy + ext;
12005
- if (f.vel.y < -0.6) {
12006
- f.vel.y = -f.vel.y * 0.25;
12007
- f.vel.x *= 0.7;
12008
- f.vel.z *= 0.7;
12009
- f.ang.multiplyScalar(0.55);
12010
- const tumble = Math.min(1, TUMBLE_REACH / Math.max(h.x, h.y, h.z));
12011
- f.ang.x += (this.rng() - 0.5) * 2 * tumble;
12012
- f.ang.z += (this.rng() - 0.5) * 2 * tumble;
12194
+ if (pile > floor2) {
12195
+ turning = this.restOnDebris(f, { g, dt, gy, sc, tip });
12013
12196
  } else {
12014
- f.vel.y = 0;
12015
- const sliding = Math.hypot(f.vel.x, f.vel.z);
12016
- const kept = sliding > 0 ? Math.max(0, sliding - DEBRIS_FRICTION * g * dt) / sliding : 0;
12017
- f.vel.x *= kept;
12018
- f.vel.z *= kept;
12019
- f.ang.multiplyScalar(Math.exp(-6 * dt));
12197
+ writeCorners({ e, half: this.scaledHalf(f, sc), corners: this.corners });
12198
+ findSupport({ corners: this.corners, reach: Math.max(h.x, h.y, h.z) * sc, support: this.support });
12199
+ if (!f.contact && this.bounces(f, { g, dt, sc })) {
12200
+ this.bounce(f, sc);
12201
+ } else {
12202
+ f.vel.y = 0;
12203
+ turning = this.restOn(f, { g, dt, sc });
12204
+ }
12020
12205
  }
12021
12206
  } else {
12022
12207
  f.ang.multiplyScalar(Math.exp(-0.15 * dt));
12023
12208
  if (f.air > 0) this.flutter(f, dt);
12024
12209
  }
12025
- if (contact && tip) {
12026
- f.vel.x += tip.x * TIP_SPEED * dt * 10;
12027
- f.vel.z += tip.z * TIP_SPEED * dt * 10;
12028
- f.ang.x += tip.z * TIP_TURN * dt * 10;
12029
- f.ang.z -= tip.x * TIP_TURN * dt * 10;
12030
- } else if (contact && f.vel.lengthSq() < 4) {
12031
- turning = this.settle(f, dt);
12032
- this.m.makeRotationFromQuaternion(mesh2.quaternion);
12033
- mesh2.position.y = gy + (Math.abs(e[1]) * h.x + Math.abs(e[5]) * h.y + Math.abs(e[9]) * h.z) * sc;
12034
- }
12035
12210
  f.contact = contact;
12036
12211
  if (contact && !turning && isSlow(f)) {
12037
12212
  f.still += dt;
@@ -12084,7 +12259,8 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
12084
12259
  for (const other of this.list) {
12085
12260
  if (other === f || other.dying) continue;
12086
12261
  const box = other.box ?? (other.box = restingBox(other));
12087
- if (box.top > bottom + PILE_STEP || box.top < top - PILE_STEP) continue;
12262
+ const beneath = !other.asleep && other.mesh.position.y < bottom;
12263
+ if (box.top > bottom + PILE_STEP && !beneath || box.top < top - PILE_STEP) continue;
12088
12264
  if (Math.abs(box.x - p.x) >= box.reachX + reachX || Math.abs(box.z - p.z) >= box.reachZ + reachZ) continue;
12089
12265
  if (!shadowsOverlap(mine, box.shadow, box.x - p.x, box.z - p.z)) continue;
12090
12266
  if (box.top > top + PILE_STEP) under.length = 0;
@@ -12093,13 +12269,16 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
12093
12269
  }
12094
12270
  this.offEdge = null;
12095
12271
  if (under.length > 0 && !under.some((box) => box.top >= top - PILE_STEP && shadowsOverlap(POINT, box.shadow, box.x - p.x, box.z - p.z))) {
12096
- let x = 0, z = 0;
12097
- for (const box of under) {
12098
- x += p.x - box.x;
12099
- z += p.z - box.z;
12272
+ const contacts = contactsOf(mine, under, p.x, p.z);
12273
+ if (!isOverSupport(contacts, [0, 0], 0)) {
12274
+ let x = 0, z = 0;
12275
+ for (const [cx, cz] of contacts) {
12276
+ x -= cx;
12277
+ z -= cz;
12278
+ }
12279
+ const d = Math.hypot(x, z);
12280
+ this.offEdge = d > 1e-6 ? { x: x / d, z: z / d } : { x: 1, z: 0 };
12100
12281
  }
12101
- const d = Math.hypot(x, z);
12102
- this.offEdge = d > 1e-6 ? { x: x / d, z: z / d } : { x: 1, z: 0 };
12103
12282
  }
12104
12283
  return top;
12105
12284
  }
@@ -12111,8 +12290,41 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
12111
12290
  f.ang.x += (this.rng() - 0.5) * SHEET_SWAY * 4 * dt;
12112
12291
  f.ang.z += (this.rng() - 0.5) * SHEET_SWAY * 4 * dt;
12113
12292
  }
12114
- /** Tip the fragment towards lying on its flattest face. True while its end is still more than `LAID_GAP` from lying. */
12115
- settle(f, dt) {
12293
+ /**
12294
+ * 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
12295
+ * it when its centre is past it (`tip`), else laid flat (`layOnDebris`). True while it is still being laid flat.
12296
+ */
12297
+ restOnDebris(f, params) {
12298
+ const { g, dt, gy, sc, tip } = params;
12299
+ const h = f.half;
12300
+ if (f.vel.y < -DEBRIS_BOUNCE_SPEED) {
12301
+ f.vel.y = -f.vel.y * GROUND_RESTITUTION;
12302
+ f.vel.x *= GROUND_GLIDE;
12303
+ f.vel.z *= GROUND_GLIDE;
12304
+ f.ang.multiplyScalar(GROUND_SPIN_KEPT);
12305
+ const tumble = Math.min(1, TUMBLE_REACH / Math.max(h.x, h.y, h.z));
12306
+ f.ang.x += (this.rng() - 0.5) * 2 * tumble;
12307
+ f.ang.z += (this.rng() - 0.5) * 2 * tumble;
12308
+ } else {
12309
+ f.vel.y = 0;
12310
+ this.slide(f, g, dt);
12311
+ f.ang.multiplyScalar(Math.exp(-6 * dt));
12312
+ }
12313
+ if (tip) {
12314
+ f.vel.x += tip.x * TIP_SPEED * dt * 10;
12315
+ f.vel.z += tip.z * TIP_SPEED * dt * 10;
12316
+ f.ang.x += tip.z * TIP_TURN * dt * 10;
12317
+ f.ang.z -= tip.x * TIP_TURN * dt * 10;
12318
+ return false;
12319
+ }
12320
+ if (f.vel.lengthSq() >= 4) return false;
12321
+ const turning = this.layOnDebris(f, dt);
12322
+ const e = this.m.makeRotationFromQuaternion(f.mesh.quaternion).elements;
12323
+ f.mesh.position.y = gy + (Math.abs(e[1]) * h.x + Math.abs(e[5]) * h.y + Math.abs(e[9]) * h.z) * sc;
12324
+ return turning;
12325
+ }
12326
+ /** 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. */
12327
+ layOnDebris(f, dt) {
12116
12328
  const mesh2 = f.mesh;
12117
12329
  this.m.makeRotationFromQuaternion(mesh2.quaternion);
12118
12330
  const e = this.m.elements;
@@ -12132,9 +12344,204 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
12132
12344
  this.w.set(0, 1, 0);
12133
12345
  this.dq.setFromUnitVectors(this.v, this.w);
12134
12346
  this.q.copy(this.dq).multiply(mesh2.quaternion);
12135
- mesh2.quaternion.slerp(this.q, clamp6(dt * 7, 0, 1));
12347
+ mesh2.quaternion.slerp(this.q, Math.min(1, dt * DEBRIS_LAY_RATE));
12136
12348
  return Math.sqrt(Math.max(0, 1 - this.v.y * this.v.y)) * Math.max(half[0], half[1], half[2]) > LAID_GAP;
12137
12349
  }
12350
+ /** The fragment's halves (m) at its fade, into `halves`. */
12351
+ scaledHalf(f, sc) {
12352
+ this.halves.x = f.half.x * sc;
12353
+ this.halves.y = f.half.y * sc;
12354
+ this.halves.z = f.half.z * sc;
12355
+ return this.halves;
12356
+ }
12357
+ /** The speed (m/s, up) of the point it rests on (`support`): its centre's, and its spin's about the centre there. */
12358
+ supportSpeed(f) {
12359
+ const s = this.support;
12360
+ return f.vel.y + f.ang.z * s.x - f.ang.x * s.z;
12361
+ }
12362
+ /**
12363
+ * 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
12364
+ * step of gravity gives what lies on it.
12365
+ */
12366
+ bounces(f, params) {
12367
+ const { g, dt, sc } = params;
12368
+ const thinnest = Math.min(f.half.x, f.half.y, f.half.z) * sc;
12369
+ const least = Math.max(2 * g * dt, Math.sqrt(2 * g * BOUNCE_LIFT_SHARE * thinnest) / GROUND_RESTITUTION);
12370
+ return this.supportSpeed(f) < -least;
12371
+ }
12372
+ /**
12373
+ * 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
12374
+ * 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,
12375
+ * so a board metres long is turned as a long body is, not as a chip.
12376
+ */
12377
+ bounce(f, sc) {
12378
+ const s = this.support;
12379
+ const into = this.supportSpeed(f);
12380
+ const rough = ROUGHNESS_SHARE * Math.max(f.half.x, f.half.y, f.half.z) * sc;
12381
+ s.x += (this.rng() - 0.5) * 2 * rough;
12382
+ s.z += (this.rng() - 0.5) * 2 * rough;
12383
+ const turn2 = this.w.set(-s.z, 0, s.x);
12384
+ applyInverseInertia({ e: this.m.elements, half: this.scaledHalf(f, sc), v: turn2 });
12385
+ const share = 1 + (turn2.z * s.x - turn2.x * s.z);
12386
+ const impulse = -(1 + GROUND_RESTITUTION) * into / share;
12387
+ f.vel.y += impulse;
12388
+ f.ang.addScaledVector(turn2, impulse);
12389
+ f.vel.x *= GROUND_GLIDE;
12390
+ f.vel.z *= GROUND_GLIDE;
12391
+ f.ang.multiplyScalar(GROUND_SPIN_KEPT);
12392
+ }
12393
+ /**
12394
+ * 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
12395
+ * 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).
12396
+ */
12397
+ slide(f, g, dt) {
12398
+ const sliding = Math.hypot(f.vel.x, f.vel.z);
12399
+ const kept = sliding > 0 ? Math.max(0, sliding - DEBRIS_FRICTION * g * dt) / sliding : 0;
12400
+ f.vel.x *= kept;
12401
+ f.vel.z *= kept;
12402
+ }
12403
+ /**
12404
+ * 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
12405
+ * 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
12406
+ * while it is still turning over.
12407
+ */
12408
+ restOn(f, params) {
12409
+ const { g, dt, sc } = params;
12410
+ const s = this.support;
12411
+ const ang = f.ang;
12412
+ const dx = -s.x, dy = -s.y, dz = -s.z;
12413
+ f.vel.x -= ang.y * dz - ang.z * dy;
12414
+ f.vel.z -= ang.x * dy - ang.y * dx;
12415
+ this.slide(f, g, dt);
12416
+ const footX = f.vel.x;
12417
+ const footZ = f.vel.z;
12418
+ const half = this.scaledHalf(f, sc);
12419
+ const gyration = Math.sqrt(inertiaAbout({ e: this.m.elements, half, x: 0, y: 1, z: 0 }));
12420
+ if (gyration > 0) ang.y = Math.sign(ang.y) * Math.max(0, Math.abs(ang.y) - DEBRIS_FRICTION * g * dt / gyration);
12421
+ if (s.count >= 3) {
12422
+ ang.x = 0;
12423
+ ang.z = 0;
12424
+ } else if (s.count === 2) {
12425
+ const along2 = ang.x * s.edgeX + ang.z * s.edgeZ;
12426
+ ang.x = along2 * s.edgeX;
12427
+ ang.z = along2 * s.edgeZ;
12428
+ }
12429
+ const lever = this.lever;
12430
+ lever.x = dx;
12431
+ lever.y = dy;
12432
+ lever.z = dz;
12433
+ const slow = footX * footX + footZ * footZ < 2 * g * SETTLE_FALL_HALVES * Math.max(half.x, half.y, half.z);
12434
+ const turning = slow && this.settle(f, g, dt);
12435
+ f.vel.x = footX + (ang.y * lever.z - ang.z * lever.y);
12436
+ f.vel.y = ang.z * lever.x - ang.x * lever.z;
12437
+ f.vel.z = footZ + (ang.x * lever.y - ang.y * lever.x);
12438
+ return turning;
12439
+ }
12440
+ /**
12441
+ * 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
12442
+ * 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
12443
+ * 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
12444
+ * holds it. True while it still turns.
12445
+ */
12446
+ settle(f, g, dt) {
12447
+ const s = this.support;
12448
+ const e = this.m.elements;
12449
+ const half = this.halves;
12450
+ const reach2 = Math.max(half.x, half.y, half.z);
12451
+ const lever = this.lever;
12452
+ let torqueX = g * lever.z;
12453
+ let torqueZ = -g * lever.x;
12454
+ if (s.count >= 3) {
12455
+ torqueX = 0;
12456
+ torqueZ = 0;
12457
+ } else if (s.count === 2) {
12458
+ const along2 = torqueX * s.edgeX + torqueZ * s.edgeZ;
12459
+ torqueX = along2 * s.edgeX;
12460
+ torqueZ = along2 * s.edgeZ;
12461
+ }
12462
+ const torque = Math.hypot(torqueX, torqueZ);
12463
+ const ang = f.ang;
12464
+ if (torque <= g * SUPPORT_SHARE * reach2 && ang.x === 0 && ang.z === 0) {
12465
+ if (s.count >= 3 && !this.isUnsteady(f)) return false;
12466
+ if (!this.nudge(f, g)) return false;
12467
+ } else if (torque > 0) {
12468
+ const axisX = torqueX / torque;
12469
+ const axisZ = torqueZ / torque;
12470
+ const along2 = lever.x * axisX + lever.z * axisZ;
12471
+ 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;
12472
+ ang.x += axisX * torque / inertia * dt;
12473
+ ang.z += axisZ * torque / inertia * dt;
12474
+ }
12475
+ const spin = Math.hypot(ang.x, ang.z);
12476
+ if (spin === 0) return false;
12477
+ 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 });
12478
+ if (spin * dt > landing2) {
12479
+ ang.x *= landing2 / (spin * dt);
12480
+ ang.z *= landing2 / (spin * dt);
12481
+ }
12482
+ return true;
12483
+ }
12484
+ /**
12485
+ * 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
12486
+ * its flattest.
12487
+ */
12488
+ isUnsteady(f) {
12489
+ const e = this.m.elements;
12490
+ const up = [Math.abs(e[1]), Math.abs(e[5]), Math.abs(e[9])];
12491
+ const half = [f.half.x, f.half.y, f.half.z];
12492
+ let small = 0;
12493
+ let standing = 0;
12494
+ for (let i = 1; i < 3; i++) {
12495
+ if (half[i] < half[small]) small = i;
12496
+ if (up[i] > up[standing]) standing = i;
12497
+ }
12498
+ if (f.body) return half[standing] > half[small] * (1 + SUPPORT_SHARE);
12499
+ const across = Math.min(...half.filter((_, i) => i !== standing));
12500
+ return across < STAND_RATIO * half[standing];
12501
+ }
12502
+ /**
12503
+ * 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 ω² =
12504
+ * 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.
12505
+ */
12506
+ nudge(f, g) {
12507
+ const e = this.m.elements;
12508
+ const half = this.halves;
12509
+ const tolerance = SUPPORT_SHARE * Math.max(half.x, half.y, half.z);
12510
+ let small = 0;
12511
+ if (half.y < half.x) small = 1;
12512
+ if (half.z < (small === 1 ? half.y : half.x)) small = 2;
12513
+ const sign = e[small * 4 + 1] >= 0 ? 1 : -1;
12514
+ const axisX = -e[small * 4 + 2] * sign;
12515
+ const axisZ = e[small * 4] * sign;
12516
+ const length = Math.hypot(axisX, axisZ);
12517
+ if (length < SUPPORT_SHARE) return false;
12518
+ const kx = axisX / length;
12519
+ const kz = axisZ / length;
12520
+ const c = this.corners;
12521
+ const floor2 = this.support.y + tolerance;
12522
+ let far2 = -Infinity;
12523
+ 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]);
12524
+ let count = 0, x = 0, y = 0, z = 0;
12525
+ for (let i = 0; i < 8; i++) {
12526
+ if (c[3 * i + 1] > floor2 || kx * c[3 * i + 2] - kz * c[3 * i] < far2 - tolerance) continue;
12527
+ count++;
12528
+ x += c[3 * i];
12529
+ y += c[3 * i + 1];
12530
+ z += c[3 * i + 2];
12531
+ }
12532
+ const lever = this.lever;
12533
+ lever.x = -x / count;
12534
+ lever.y = -y / count;
12535
+ lever.z = -z / count;
12536
+ const along2 = lever.x * kx + lever.z * kz;
12537
+ const square = lever.x * lever.x + lever.y * lever.y + lever.z * lever.z - along2 * along2;
12538
+ const rise = Math.max(Math.sqrt(square) - lever.y, tolerance);
12539
+ const inertia = inertiaAbout({ e, half, x: kx, y: 0, z: kz }) + square;
12540
+ const spinOfInertia = Math.sqrt(2 * g * rise * (1 + NUDGE_ENERGY_SHARE) / inertia);
12541
+ f.ang.x = kx * spinOfInertia;
12542
+ f.ang.z = kz * spinOfInertia;
12543
+ return true;
12544
+ }
12138
12545
  /** Remove the fragments of one object (after `restore`). */
12139
12546
  removeHome(home) {
12140
12547
  for (let i = this.list.length - 1; i >= 0; i--) {
@@ -14389,6 +14796,97 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
14389
14796
  });
14390
14797
  };
14391
14798
 
14799
+ // src/kit-energy.ts
14800
+ var KIT_RULE = {
14801
+ /** A piece that lost a leg and is balanced on the line between the ones left is started down over it (`renderer.ts`). */
14802
+ GO_OVER_IF_BALANCED: "goOverIfBalanced",
14803
+ /** What stood on ground that went (a hole under a foot) is started down over the gap (`renderer.ts`). */
14804
+ CHECK_UNDERMINED: "checkUndermined",
14805
+ /** Furniture made a piece balanced on an edge of its feet is started over it (`EDGE_NUDGE`, `renderer.ts`). */
14806
+ LOOSEN_IF_FOOTLESS: "loosenIfFootless",
14807
+ /** A piece of the engine balanced on a narrow support is turned about its edge (`engine-pieces.ts`). */
14808
+ TOPPLE: "topple"
14809
+ };
14810
+ var RULES = Object.values(KIT_RULE);
14811
+ var GRAVITY3 = 9.81;
14812
+ var KIT_ENERGY_RESOLUTION = 1e-3;
14813
+ var REST_HEIGHT = KIT_ENERGY_RESOLUTION;
14814
+ var kineticEnergyOf = (body) => {
14815
+ const [vx2, vy2, vz2] = body.velocity;
14816
+ const [wx, wy, wz] = body.angularVelocity;
14817
+ const { x, y, z, w } = body.root.quaternion;
14818
+ const lx = (1 - 2 * (y * y + z * z)) * wx + 2 * (x * y + z * w) * wy + 2 * (x * z - y * w) * wz;
14819
+ const ly = 2 * (x * y - z * w) * wx + (1 - 2 * (x * x + z * z)) * wy + 2 * (y * z + x * w) * wz;
14820
+ const lz = 2 * (x * z + y * w) * wx + 2 * (y * z - x * w) * wy + (1 - 2 * (x * x + y * y)) * wz;
14821
+ const [hx, hy, hz2] = body.halfExtents;
14822
+ const m = body.mass;
14823
+ let ix = m * (hy * hy + hz2 * hz2) / 3;
14824
+ let iy = m * (hx * hx + hz2 * hz2) / 3;
14825
+ let iz = m * (hx * hx + hy * hy) / 3;
14826
+ const round2 = body.round;
14827
+ if (round2) {
14828
+ const about = round2.inertia * m * round2.radius * round2.radius;
14829
+ if (round2.kind === "sphere") ix = iy = iz = about;
14830
+ else if (round2.axis === 0) ix = about;
14831
+ else if (round2.axis === 1) iy = about;
14832
+ else iz = about;
14833
+ }
14834
+ return 0.5 * m * (vx2 * vx2 + vy2 * vy2 + vz2 * vz2) + 0.5 * (ix * lx * lx + iy * ly * ly + iz * lz * lz);
14835
+ };
14836
+ var fallEnergyOf = (body) => {
14837
+ const { x, y, z, w } = body.root.quaternion;
14838
+ const [hx, hy, hz2] = body.halfExtents;
14839
+ const [cx, cy, cz] = body.massCentre ?? [0, 0, 0];
14840
+ const rx = 2 * (x * y + z * w);
14841
+ const ry = 1 - 2 * (x * x + z * z);
14842
+ const rz = 2 * (y * z - x * w);
14843
+ const over2 = hx * Math.abs(rx) + hy * Math.abs(ry) + hz2 * Math.abs(rz) + rx * cx + ry * cy + rz * cz;
14844
+ const lowest = Math.min(hx - Math.abs(cx), hy - Math.abs(cy), hz2 - Math.abs(cz));
14845
+ return body.mass * GRAVITY3 * Math.max(0, over2 - lowest);
14846
+ };
14847
+ var KitEnergyLedger = class {
14848
+ constructor(onOver) {
14849
+ __publicField(this, "onOver", onOver);
14850
+ __publicField(this, "before", 0);
14851
+ __publicField(this, "tallies", new Map(RULES.map((rule) => [rule, { pushes: 0, overs: 0, worstShare: 0, worst: null }])));
14852
+ __publicField(this, "episodes", /* @__PURE__ */ new WeakMap());
14853
+ }
14854
+ begin(body) {
14855
+ this.before = kineticEnergyOf(body);
14856
+ if (this.before > body.mass * GRAVITY3 * REST_HEIGHT) return;
14857
+ const episode = this.episodes.get(body);
14858
+ if (!episode) {
14859
+ this.episodes.set(body, { given: new Float64Array(RULES.length), over: new Uint8Array(RULES.length), fall: fallEnergyOf(body) });
14860
+ return;
14861
+ }
14862
+ episode.given.fill(0);
14863
+ episode.over.fill(0);
14864
+ episode.fall = fallEnergyOf(body);
14865
+ }
14866
+ end(rule, body) {
14867
+ const tally = this.tallies.get(rule);
14868
+ tally.pushes++;
14869
+ const episode = this.episodes.get(body);
14870
+ const open = episode ?? { given: new Float64Array(RULES.length), over: new Uint8Array(RULES.length), fall: fallEnergyOf(body) };
14871
+ if (!episode) this.episodes.set(body, open);
14872
+ const index = RULES.indexOf(rule);
14873
+ const given = open.given[index] + kineticEnergyOf(body) - this.before;
14874
+ open.given[index] = given;
14875
+ const share = given <= 0 ? 0 : given / (open.fall + body.mass * GRAVITY3 * KIT_ENERGY_RESOLUTION);
14876
+ if (share > tally.worstShare) {
14877
+ tally.worstShare = share;
14878
+ tally.worst = { rule, objectId: body.objectId, given, fall: open.fall };
14879
+ }
14880
+ if (share <= 1 || open.over[index]) return;
14881
+ open.over[index] = 1;
14882
+ tally.overs++;
14883
+ this.onOver?.({ rule, objectId: body.objectId, given, fall: open.fall });
14884
+ }
14885
+ tally() {
14886
+ return RULES.map((rule) => ({ rule, ...this.tallies.get(rule) }));
14887
+ }
14888
+ };
14889
+
14392
14890
  // src/engine-ground-heights.ts
14393
14891
  var changedHeights = (before, after2, size) => {
14394
14892
  let minX = size;
@@ -14783,6 +15281,10 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
14783
15281
  var TILE_KEY_ORIGIN = 32768;
14784
15282
  var MU_STATIC = 0.7;
14785
15283
  var ROLLING_RESISTANCE = 0.015;
15284
+ var roundPartsRadius = (parts) => {
15285
+ if (!parts || parts.length === 0 || !parts.every((part) => part.round && !part.hull)) return void 0;
15286
+ return Math.max(...parts.map((part) => (part.half[0] + part.half[2]) / 2));
15287
+ };
14786
15288
  var MU_DYNAMIC = 0.6;
14787
15289
  var GROUND = { frictionStatic: MU_STATIC, frictionDynamic: MU_DYNAMIC, restitution: 0, rolling: ROLLING_RESISTANCE };
14788
15290
  var tileRollingAt = (rollingAt, x, z) => rollingAt((Math.floor(x / TILE) + 0.5) * TILE, (Math.floor(z / TILE) + 0.5) * TILE);
@@ -15331,9 +15833,13 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
15331
15833
  out[round2.axis] = about;
15332
15834
  return out;
15333
15835
  }
15334
- /** A round piece rolls to a stop by its surface's rolling resistance (the adapter's rule; the engine has none). */
15836
+ /**
15837
+ * 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
15838
+ * 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.
15839
+ */
15335
15840
  rollingOf(b) {
15336
- return b.round ? { coefficient: b.friction?.rolling ?? ROLLING_RESISTANCE, radius: b.round.radius, damping: b.friction?.rollingDamping ?? PIECE_ROLLING_DAMPING } : void 0;
15841
+ const radius = b.round?.radius ?? roundPartsRadius(b.partBoxes);
15842
+ return radius === void 0 ? void 0 : { coefficient: b.friction?.rolling ?? ROLLING_RESISTANCE, radius, damping: b.friction?.rollingDamping ?? PIECE_ROLLING_DAMPING };
15337
15843
  }
15338
15844
  material(b) {
15339
15845
  return {
@@ -15712,20 +16218,25 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
15712
16218
  if (wx <= wz) {
15713
16219
  const edge = dirX > 0 ? x1 : x0;
15714
16220
  const dw = edge * dirX > 0 ? -dirX * this.topplePush(edge, height, isColumn && Math.abs(w[2]) < PUSH_SPIN, this.turningOf(b, 2)) * dt : 0;
16221
+ if (dw === 0) return;
15715
16222
  const rx = -edge;
15716
16223
  const ry = -low;
16224
+ this.o.kitEnergy?.begin(b);
15717
16225
  w[2] += dw;
15718
16226
  v[0] += -dw * ry;
15719
16227
  v[1] += dw * rx;
15720
16228
  } else {
15721
16229
  const edge = dirZ > 0 ? z1 : z0;
15722
16230
  const dw = edge * dirZ > 0 ? dirZ * this.topplePush(edge, height, isColumn && Math.abs(w[0]) < PUSH_SPIN, this.turningOf(b, 0)) * dt : 0;
16231
+ if (dw === 0) return;
15723
16232
  const rz = -edge;
15724
16233
  const ry = -low;
16234
+ this.o.kitEnergy?.begin(b);
15725
16235
  w[0] += dw;
15726
16236
  v[1] += -dw * rz;
15727
16237
  v[2] += dw * ry;
15728
16238
  }
16239
+ this.o.kitEnergy?.end(KIT_RULE.TOPPLE, b);
15729
16240
  }
15730
16241
  /** Propped pieces lose most of their friction until they move or sleep (the push only presses them into the prop: an energy-free way to end a wedge). */
15731
16242
  slip(b, link, isSlipping) {
@@ -16289,46 +16800,6 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
16289
16800
  return { loop: createPhysicsLoop(option), stepsItself: true };
16290
16801
  };
16291
16802
 
16292
- // src/support-hull.ts
16293
- var cross2 = (o, a, b) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
16294
- function planHull(points) {
16295
- const sorted = [...points].sort((a, b) => a[0] - b[0] || a[1] - b[1]);
16296
- if (sorted.length < 3) return sorted;
16297
- const lower = [];
16298
- for (const p of sorted) {
16299
- while (lower.length >= 2 && cross2(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) lower.pop();
16300
- lower.push(p);
16301
- }
16302
- const upper = [];
16303
- for (let i = sorted.length - 1; i >= 0; i--) {
16304
- const p = sorted[i];
16305
- while (upper.length >= 2 && cross2(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) upper.pop();
16306
- upper.push(p);
16307
- }
16308
- return [...lower.slice(0, -1), ...upper.slice(0, -1)];
16309
- }
16310
- function toSegment(p, a, b) {
16311
- const dx = b[0] - a[0];
16312
- const dz = b[1] - a[1];
16313
- const length = dx * dx + dz * dz;
16314
- const t = length > 0 ? Math.max(0, Math.min(1, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dz) / length)) : 0;
16315
- return Math.hypot(p[0] - a[0] - t * dx, p[1] - a[1] - t * dz);
16316
- }
16317
- function isOverSupport(points, centre, tolerance) {
16318
- const hull = planHull(points);
16319
- if (hull.length === 0) return false;
16320
- if (hull.length === 1) return Math.hypot(centre[0] - hull[0][0], centre[1] - hull[0][1]) <= tolerance;
16321
- let inside = hull.length >= 3;
16322
- let nearest = Infinity;
16323
- for (let i = 0; i < hull.length; i++) {
16324
- const a = hull[i];
16325
- const b = hull[(i + 1) % hull.length];
16326
- if (hull.length >= 3 && cross2(a, b, centre) < 0) inside = false;
16327
- nearest = Math.min(nearest, toSegment(centre, a, b));
16328
- }
16329
- return inside || nearest <= tolerance;
16330
- }
16331
-
16332
16803
  // src/pieces.ts
16333
16804
  var BALANCE_TOLERANCE = 0.01;
16334
16805
  var MU_STATIC2 = 0.7;
@@ -16476,6 +16947,8 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
16476
16947
  __publicField(this, "supportNormal", UP16);
16477
16948
  __publicField(this, "supportFriction", null);
16478
16949
  __publicField(this, "supportBody", null);
16950
+ /** What each rule of the kit gave the pieces it pushed (`ruleImpulse`, and the engine's own `topple`). */
16951
+ __publicField(this, "kitEnergy");
16479
16952
  /** A piece is asleep on both sides (the engine's too): nothing of it changes until it wakes. */
16480
16953
  __publicField(this, "isSettled", (body) => this.engine.isSettled(body));
16481
16954
  __publicField(this, "measureAwake", (body) => {
@@ -16509,7 +16982,9 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
16509
16982
  this.loop = resolved.loop;
16510
16983
  this.stepsItself = resolved.stepsItself;
16511
16984
  this.trail = o.interpolate ? new PoseTrail() : null;
16985
+ this.kitEnergy = new KitEnergyLedger(o.onKitEnergy);
16512
16986
  this.engine = new EnginePieces(THREE, resolved.loop.world, {
16987
+ kitEnergy: this.kitEnergy,
16513
16988
  groundAt: o.terrainAt ?? o.groundAt,
16514
16989
  ...o.terrainRollingAt ? { groundRollingAt: o.terrainRollingAt } : {},
16515
16990
  ...o.terrainRollingDampingAt ? { groundRollingDampingAt: o.terrainRollingDampingAt } : {},
@@ -16851,6 +17326,20 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
16851
17326
  b.still = 0;
16852
17327
  b.calmAt = null;
16853
17328
  }
17329
+ /** `impulse` given by a rule of the kit on its own, measured by its name (`kitEnergy`). */
17330
+ ruleImpulse(rule, b, impulse, point) {
17331
+ this.kitEnergy.begin(b);
17332
+ this.impulse(b, impulse, point);
17333
+ this.kitEnergy.end(rule, b);
17334
+ }
17335
+ /** Spin (rad/s, world axes x and z) added by a rule of the kit on its own, measured by its name (`kitEnergy`). */
17336
+ ruleSpin(rule, b, x, z) {
17337
+ this.kitEnergy.begin(b);
17338
+ b.angularVelocity[0] += x;
17339
+ b.angularVelocity[2] += z;
17340
+ b.sleeping = false;
17341
+ this.kitEnergy.end(rule, b);
17342
+ }
16854
17343
  /** I^-1 * (x, y, z) in world space for a box with the body's half extents and mass (needs `this.m` to hold the body's rotation). */
16855
17344
  mulInvInertia(b, x, y, z) {
16856
17345
  this.m.makeRotationFromQuaternion(b.root.quaternion);
@@ -18636,7 +19125,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
18636
19125
  for (const [a, b] of bars) length += Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]) + Math.abs(a[2] - b[2]);
18637
19126
  return Math.PI * (diameter / 2) * (diameter / 2) * length * density;
18638
19127
  };
18639
- var GRAVITY3 = 9.81;
19128
+ var GRAVITY4 = 9.81;
18640
19129
  var MPA = 1e6;
18641
19130
  var FLEXURE_DEFAULTS = {
18642
19131
  enabled: true,
@@ -18739,7 +19228,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
18739
19228
  var sectionWidth = (g, axis2) => g.member ? g.dims[g.depthAxes.find((a) => a !== axis2) ?? axis2] : 1;
18740
19229
  var lineLoad = (g, load) => {
18741
19230
  const area = g.member ? g.dims[g.spanAxes[0]] : g.dims[g.spanAxes[0]] * g.dims[g.spanAxes[1]];
18742
- return load * GRAVITY3 / Math.max(area, 1e-6);
19231
+ return load * GRAVITY4 / Math.max(area, 1e-6);
18743
19232
  };
18744
19233
  var spanOf = (g, contacts, samples = 9) => {
18745
19234
  if (contacts.length === 0) return 0;
@@ -19379,7 +19868,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
19379
19868
  let anyFoundation = false;
19380
19869
  for (let i = 0; i < parts.length; i++) {
19381
19870
  const p = parts[i];
19382
- weight += p.mass * GRAVITY3;
19871
+ weight += p.mass * GRAVITY4;
19383
19872
  wu += p.mass * g[i].u;
19384
19873
  if (p.kind === "foundation") {
19385
19874
  anyFoundation = true;
@@ -19398,7 +19887,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
19398
19887
  if (!anyFoundation) {
19399
19888
  for (let i = 0; i < parts.length; i++) if (parts[i].min[1] - ground < 0.1) footEnd = Math.max(footEnd, g[i].u + g[i].du / 2);
19400
19889
  }
19401
- const totalMass = weight / GRAVITY3;
19890
+ const totalMass = weight / GRAVITY4;
19402
19891
  const uCg = totalMass > 0 ? wu / totalMass : 0;
19403
19892
  const width = vmax.map((hi, j) => hi > vmin[j] ? hi - vmin[j] : 0);
19404
19893
  const widest = Math.max(...width);
@@ -21030,7 +21519,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
21030
21519
  const steel = bars * Math.PI * (part.reinforcement.diameter / 2) ** 2;
21031
21520
  newtons = m.concreteFactor * fc * section + steel * resolveFlexure(options.flexure).rebarYieldMPa * 1e6;
21032
21521
  }
21033
- return Math.max(1, newtons / GRAVITY3 * foundation);
21522
+ return Math.max(1, newtons / GRAVITY4 * foundation);
21034
21523
  };
21035
21524
  var fragility = (ductility, thickness) => {
21036
21525
  if (ductility >= 0.3) return 1;
@@ -21202,6 +21691,12 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
21202
21691
  var MASONRY_CRUMBLE_SPEED = 0.6;
21203
21692
  var MASONRY_TOPPLE = 0.4;
21204
21693
  var MASONRY_TOPPLE_MIN_HEIGHT = 0.5;
21694
+ var SPIN_REACH = 0.1;
21695
+ var bornSpin = (size, chipSpin, rnd2) => {
21696
+ const reach2 = Math.hypot(size[0] ?? 0, size[1] ?? 0, size[2] ?? 0) / 2;
21697
+ const scale = reach2 <= SPIN_REACH ? 1 : SPIN_REACH / reach2;
21698
+ return [(rnd2() - 0.5) * chipSpin * scale, (rnd2() - 0.5) * chipSpin * scale, (rnd2() - 0.5) * chipSpin * scale];
21699
+ };
21205
21700
  var TILE_CLUMPS = 160;
21206
21701
  var TILE_THICKNESS = 0.018;
21207
21702
  var PANEL_EDGE_PILLAR = 2;
@@ -21781,7 +22276,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
21781
22276
  return (above2 + p.st.mass * share) / load;
21782
22277
  };
21783
22278
  };
21784
- const contactsOf = (p, support) => {
22279
+ const contactsOf2 = (p, support) => {
21785
22280
  const box = contactBox(p, support);
21786
22281
  const broken = support.rt.broken;
21787
22282
  if (!broken?.length) return [box];
@@ -21826,7 +22321,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
21826
22321
  }
21827
22322
  const corners = [];
21828
22323
  for (const k of lower) {
21829
- for (const [lo, hi] of contactsOf(p, o.parts[k])) {
22324
+ for (const [lo, hi] of contactsOf2(p, o.parts[k])) {
21830
22325
  for (let c = 0; c < 4; c++) {
21831
22326
  const local2 = [c & 1 ? hi[0] : lo[0], (lo[1] + hi[1]) / 2, c & 2 ? hi[2] : lo[2]];
21832
22327
  const at3 = toWorld(p.pos, p.q, local2);
@@ -21882,13 +22377,13 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
21882
22377
  };
21883
22378
  const specSpans = /* @__PURE__ */ new WeakMap();
21884
22379
  const spanOver = (p, g, supports) => {
21885
- if (p.posed || supports.some((k) => k.posed || k.rt.broken?.length)) return spanOf(g, supports.flatMap((k) => contactsOf(p, k)));
22380
+ if (p.posed || supports.some((k) => k.posed || k.rt.broken?.length)) return spanOf(g, supports.flatMap((k) => contactsOf2(p, k)));
21886
22381
  let byKey = specSpans.get(p.spec);
21887
22382
  if (!byKey) specSpans.set(p.spec, byKey = /* @__PURE__ */ new Map());
21888
22383
  const key = supports.map((k) => k.spec.id).join("\0");
21889
22384
  const known = byKey.get(key);
21890
22385
  if (known !== void 0) return known;
21891
- const span = spanOf(g, supports.flatMap((k) => contactsOf(p, k)));
22386
+ const span = spanOf(g, supports.flatMap((k) => contactsOf2(p, k)));
21892
22387
  byKey.set(key, span);
21893
22388
  return span;
21894
22389
  };
@@ -21941,7 +22436,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
21941
22436
  const width = sectionWidth(g, axis2);
21942
22437
  const impulse = sum / offsets.length * cos2 * reach2 * width * L;
21943
22438
  const weight = axis2 === g.gravity ? p.bendLoad : p.st.mass;
21944
- const kinetic = impulseEnergy(impulse, lineLoad(g, weight) / GRAVITY3 * L, flexure);
22439
+ const kinetic = impulseEnergy(impulse, lineLoad(g, weight) / GRAVITY4 * L, flexure);
21945
22440
  const sec = sectionOf(p, axis2);
21946
22441
  const EI = s.elasticGPa * 1e9 * sec.section.b * sec.section.h ** 3 / 12;
21947
22442
  const along2 = axis2 === g.gravity ? -Math.sign(away[axis2] * g.up[axis2]) : 0;
@@ -21976,7 +22471,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
21976
22471
  }
21977
22472
  const d = p.dims;
21978
22473
  const L = [0, 1, 2].sort((a, b) => d[b] - d[a])[0];
21979
- const spans2 = supports.flatMap((k) => contactsOf(p, k)).map(([lo, hi]) => [lo[L], hi[L]]);
22474
+ const spans2 = supports.flatMap((k) => contactsOf2(p, k)).map(([lo, hi]) => [lo[L], hi[L]]);
21980
22475
  let far2 = 0;
21981
22476
  for (let i = 0; i <= 16; i++) {
21982
22477
  const x = (i / 16 - 0.5) * d[L];
@@ -22196,8 +22691,8 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
22196
22691
  const dead = p.st.load ?? p.st.mass;
22197
22692
  const force = N * cfg.loadFactor;
22198
22693
  let stress = 0;
22199
- if (force >= 0) stress = (dead * structureSafety + force / GRAVITY3) / (p.cap * capacityScale(p));
22200
- else if (dead + force / GRAVITY3 < 0) {
22694
+ if (force >= 0) stress = (dead * structureSafety + force / GRAVITY4) / (p.cap * capacityScale(p));
22695
+ else if (dead + force / GRAVITY4 < 0) {
22201
22696
  let cap = w.tension.get(i);
22202
22697
  if (cap === void 0) {
22203
22698
  const r = p.spec.reinforcement;
@@ -22210,7 +22705,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
22210
22705
  });
22211
22706
  w.tension.set(i, cap);
22212
22707
  }
22213
- stress = Math.min(10, -(dead + force / GRAVITY3) * GRAVITY3 / Math.max(cap * capacityScale(p), 1));
22708
+ stress = Math.min(10, -(dead + force / GRAVITY4) * GRAVITY4 / Math.max(cap * capacityScale(p), 1));
22214
22709
  }
22215
22710
  if (stress > (p.st.stress ?? 0)) p.st.stress = stress;
22216
22711
  if ((p.st.stress ?? 0) > o.maxStress) o.maxStress = p.st.stress ?? 0;
@@ -22352,7 +22847,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
22352
22847
  m += p.st.mass;
22353
22848
  for (let k = 0; k < 3; k++) c[k] += p.st.mass * p.pos[k];
22354
22849
  }
22355
- return { w: m * GRAVITY3, c: m > 0 ? [c[0] / m, c[1] / m, c[2] / m] : c };
22850
+ return { w: m * GRAVITY4, c: m > 0 ? [c[0] / m, c[1] / m, c[2] / m] : c };
22356
22851
  };
22357
22852
  const initSoil = (o, profile, carried, carrySets) => {
22358
22853
  const so = { profile, s: 0, a: 0, b: 0, imp: [0, 0], pivot: [0, 0, 0], dirty: true, sets: /* @__PURE__ */ new Map(), emitted: { t: -Infinity, s: 0, tilt: 0, status: "stable" } };
@@ -22517,7 +23012,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
22517
23012
  if (flat < 0.5) return pieces;
22518
23013
  const side = hashOf(p.spec.id) & 1 ? -1 : 1;
22519
23014
  const nx = side * across[0] / flat, nz = side * across[2] / flat;
22520
- const spin = Math.sqrt(3 * GRAVITY3 / height);
23015
+ const spin = Math.sqrt(3 * GRAVITY4 / height);
22521
23016
  const foot = box.min[1];
22522
23017
  return pieces.map((f) => {
22523
23018
  const up = Math.max(0, f.center[1] - foot);
@@ -22745,7 +23240,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
22745
23240
  loadFactor: structureSafety,
22746
23241
  points: over2.map(({ q }) => {
22747
23242
  const c = aabbOf(q.spec.shape, q.pos, q.q);
22748
- return { weight: (q.st.load ?? q.st.mass) * GRAVITY3, side: Math.min(c.max[0] - c.min[0], c.max[2] - c.min[2]) };
23243
+ return { weight: (q.st.load ?? q.st.mass) * GRAVITY4, side: Math.min(c.max[0] - c.min[0], c.max[2] - c.min[2]) };
22749
23244
  })
22750
23245
  });
22751
23246
  if (fp.share > 1 - 1 / soilCfg.safety) return { status: "unsupported", failed: [], cracks: [] };
@@ -23817,7 +24312,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
23817
24312
  size: [cell.size[0], cell.size[1], cell.size[2]],
23818
24313
  rotation: q,
23819
24314
  velocity: [dv[0] * k, dv[1] * k + 0.5 * rnd2(), dv[2] * k],
23820
- angularVelocity: [(rnd2() - 0.5) * 8, (rnd2() - 0.5) * 8, (rnd2() - 0.5) * 8],
24315
+ angularVelocity: bornSpin(cell.size, 8, rnd2),
23821
24316
  mass: mass * faceArea(cell) / total,
23822
24317
  ...marks.length > 0 ? { marks } : {},
23823
24318
  ...inner && laid ? { unit: true } : inner ? { inner } : {}
@@ -23856,7 +24351,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
23856
24351
  size,
23857
24352
  rotation: q,
23858
24353
  velocity: [out0[0] * k, out0[1] * k + 0.5 * rnd2(), out0[2] * k],
23859
- angularVelocity: [(rnd2() - 0.5) * 12, (rnd2() - 0.5) * 12, (rnd2() - 0.5) * 12],
24354
+ angularVelocity: bornSpin(size, 12, rnd2),
23860
24355
  mass: layer3.mat.density * size[0] * size[1] * size[2]
23861
24356
  });
23862
24357
  }
@@ -24182,7 +24677,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
24182
24677
  size,
24183
24678
  rotation: q,
24184
24679
  velocity: [vdir[0] * k, vdir[1] * k + 0.5 * rnd2(), vdir[2] * k],
24185
- angularVelocity: [(rnd2() - 0.5) * 20, (rnd2() - 0.5) * 20, (rnd2() - 0.5) * 20],
24680
+ angularVelocity: bornSpin(size, 20, rnd2),
24186
24681
  mass: mass / n,
24187
24682
  inner: true
24188
24683
  });
@@ -24588,7 +25083,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
24588
25083
  size: f.size,
24589
25084
  rotation: quat.mul(q, f.q),
24590
25085
  velocity: [dv[0] * k, dv[1] * k + 0.5 * rnd2(), dv[2] * k],
24591
- angularVelocity: [(rnd2() - 0.5) * 12, (rnd2() - 0.5) * 12, (rnd2() - 0.5) * 12],
25086
+ angularVelocity: bornSpin(f.size, 12, rnd2),
24592
25087
  mass: mass * f.weight / totW,
24593
25088
  ...marks.length > 0 ? { marks } : {},
24594
25089
  ...f.inner ? { inner: true } : {}
@@ -24727,7 +25222,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
24727
25222
  rotation: q,
24728
25223
  velocity: v,
24729
25224
  inner: true,
24730
- angularVelocity: [(rnd2() - 0.5) * 30, (rnd2() - 0.5) * 30, (rnd2() - 0.5) * 30],
25225
+ angularVelocity: bornSpin(size, 30, rnd2),
24731
25226
  mass
24732
25227
  });
24733
25228
  }
@@ -29050,7 +29545,8 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
29050
29545
  var UNDERMINED_STAND = 0.4;
29051
29546
  var UNDERMINED_KEEP = 0.6;
29052
29547
  var SOLIDS_MAX = 64;
29053
- var UNDERMINED_PUSH = 0.6;
29548
+ var UNDERMINED_FROUDE = 0.13;
29549
+ var GRAVITY5 = 9.81;
29054
29550
  var DEBRIS_ID = "debris#";
29055
29551
  var UNDERMINED_STILL = 0.05;
29056
29552
  var SOLID_WELD = 1e-4;
@@ -29427,6 +29923,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
29427
29923
  ...o.groundWorkerFrames !== void 0 ? { groundWorkerFrames: o.groundWorkerFrames } : {},
29428
29924
  ...this.blastDebris ? { keep: { maxLive: this.blastDebris.maxLivePieces, far: this.blastDebris.far, ...o.focus ? { focus: o.focus } : {}, onFade: (b) => this.fadePiece(b) } } : {},
29429
29925
  onHardLanding: (p, point, speed) => this.hardLanding(p, point, speed),
29926
+ ...o.onKitEnergy ? { onKitEnergy: o.onKitEnergy } : {},
29430
29927
  sweep: (p, from, to) => this.sweepPiece(p, from, to),
29431
29928
  onSlam: (p, hit, speed) => this.slam(p, hit, speed),
29432
29929
  // two pieces knocked together: each sounds as its material does (a can on a can, a bottle on a table's leg)
@@ -29878,6 +30375,10 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
29878
30375
  const piece = this.pieceSys.get(objectId);
29879
30376
  return piece && !piece.debris ? piece : null;
29880
30377
  }
30378
+ /** What each rule of the kit that moves a piece by itself (`KIT_RULE`) gave the pieces it pushed, against their own fall (see `RendererOptions.onKitEnergy`). */
30379
+ kitEnergy() {
30380
+ return this.pieceSys.kitEnergy.tally();
30381
+ }
29881
30382
  impulse(objectId, impulse, point) {
29882
30383
  const p = this.pieceSys.get(objectId);
29883
30384
  if (p) this.pieceSys.impulse(p, impulse, point);
@@ -30905,13 +31406,13 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
30905
31406
  }
30906
31407
  /**
30907
31408
  * Plays the effect the event map names for a destruction event (`data/event-effects.json` of `game-vfx`, or `RendererOptions.eventEffects`) at a point.
30908
- * `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
30909
- * leave out the burst it replaces.
31409
+ * `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
31410
+ * whether one played, so the caller can leave out the burst it replaces.
30910
31411
  */
30911
- playEvent(event, point, play) {
31412
+ playEvent(event, point, play, normal) {
30912
31413
  const id = effectForEvent(play && event.material === void 0 ? { ...event, material: play.material } : event, this.o.eventEffects ?? EVENT_EFFECTS_MAP);
30913
31414
  if (!id) return false;
30914
- return this.vfx.play(id, point, { seed: hashNumbers(point[0], point[1], point[2], this.time), ...play ? { values: play.values } : {} }) !== null;
31415
+ return this.vfx.play(id, point, { seed: hashNumbers(point[0], point[1], point[2], this.time), ...play ? { values: play.values } : {}, ...normal ? { normal } : {} }) !== null;
30915
31416
  }
30916
31417
  /** The family and colours of a part's material, for the effects of the event map. */
30917
31418
  partPlay(objectId, partId) {
@@ -30931,7 +31432,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
30931
31432
  const core = def?.visual?.innerColor;
30932
31433
  const look = debrisLook(def, "spall", { partColor: this.partColor(pv, def) ?? void 0 });
30933
31434
  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 });
30934
- else this.playEvent({ kind: "spall", material: look.impact }, ev.point);
31435
+ else this.playEvent({ kind: "spall", material: look.impact }, ev.point, void 0, [normal.x, normal.y, normal.z]);
30935
31436
  if (core !== void 0) this.trickleFrom(ev.point, [normal.x, normal.y, normal.z], core, mv);
30936
31437
  if (mv.mesh.userData.drawnSpalls?.includes(ev.part)) return;
30937
31438
  this.visuals.addSpall(mv, wp, normal, Math.sqrt(ev.area / Math.PI), core ?? fallbackColor(def));
@@ -31555,9 +32056,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
31555
32056
  this.setContacts(b, b.piece ?? piece, left);
31556
32057
  const loose = b.piece;
31557
32058
  if (away && loose) {
31558
- loose.angularVelocity[0] += away.z * EDGE_NUDGE;
31559
- loose.angularVelocity[2] -= away.x * EDGE_NUDGE;
31560
- loose.sleeping = false;
32059
+ this.pieceSys.ruleSpin(KIT_RULE.LOOSEN_IF_FOOTLESS, loose, away.z * EDGE_NUDGE, -away.x * EDGE_NUDGE);
31561
32060
  } else this.tipIfTopHeavy(b);
31562
32061
  this.o.onLoosened?.(objectId, piece, "apart");
31563
32062
  }
@@ -31653,7 +32152,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
31653
32152
  body.sleeping = false;
31654
32153
  body.still = 0;
31655
32154
  body.calmAt = null;
31656
- if (held.length > 0 && length > 1e-6) this.pieceSys.impulse(body, [0, -body.mass * UNDERMINED_PUSH, 0], [centre[0] + gx, floor2, centre[2] + gz]);
32155
+ 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]);
31657
32156
  if (!was) this.o.onLoosened?.(b.id, body, "ground");
31658
32157
  }
31659
32158
  }
@@ -31670,7 +32169,8 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
31670
32169
  if (this.standsWith(held, null, centre, feet.floor)) return;
31671
32170
  const inside = insideBy(convexHull2(held), [centre[0], centre[2]]);
31672
32171
  const reach2 = this.reachAlong(body, inside.out.x, inside.out.z);
31673
- this.pieceSys.impulse(body, [0, -body.mass * UNDERMINED_PUSH, 0], [centre[0] + inside.out.x * reach2, feet.floor, centre[2] + inside.out.z * reach2]);
32172
+ const mid = this.pieceSys.centerOf(body, new this.THREE.Vector3());
32173
+ 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]);
31674
32174
  }
31675
32175
  /** 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. */
31676
32176
  reachAlong(body, x, z) {
@@ -32735,6 +33235,9 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
32735
33235
  };
32736
33236
  return [...half(sorted), ...half([...sorted].reverse())];
32737
33237
  }
33238
+ function startDownSpeed(height) {
33239
+ return UNDERMINED_FROUDE * Math.sqrt(GRAVITY5 * height);
33240
+ }
32738
33241
  function centreOfBoxes(boxes) {
32739
33242
  const sum = [0, 0, 0];
32740
33243
  let total = 0;