@adatechnology/game-destruction-three 1.1.2 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1073,6 +1073,7 @@ var FragmentSystem = class {
1073
1073
  dying: false,
1074
1074
  air: f.shape === "scrap" && sz[2] <= SHEET_MAX ? SHEET_AIR : 0,
1075
1075
  body: null,
1076
+ rigid: null,
1076
1077
  born: this.tick,
1077
1078
  life: lasting ? 0 : Math.max(0, typeof this.o.life === "function" ? this.o.life(f, home) : this.o.life),
1078
1079
  seq: this.nextSeq++,
@@ -1081,9 +1082,12 @@ var FragmentSystem = class {
1081
1082
  isMortal: false
1082
1083
  };
1083
1084
  if (lasting || isBig(f.size)) {
1085
+ const rigid = this.o.rigid;
1086
+ if (rigid) live.rigid = rigid.add(mesh, [sc.x / 2, sc.y / 2, sc.z / 2], f.mass, f.velocity, f.angularVelocity);
1084
1087
  live.body = {
1085
1088
  mass: f.mass,
1086
1089
  push: (x, z) => {
1090
+ if (rigid && live.rigid) return rigid.push(live.rigid, x, z);
1087
1091
  live.vel.x = x;
1088
1092
  live.vel.z = z;
1089
1093
  live.vel.y = Math.max(live.vel.y, 0.3);
@@ -1121,8 +1125,14 @@ var FragmentSystem = class {
1121
1125
  const k = (1 - dist / radius) ** 2 * speed;
1122
1126
  d.normalize().multiplyScalar(k);
1123
1127
  d.y += k * 0.4;
1128
+ const spin = this.w.set(this.rng() - 0.5, this.rng() - 0.5, this.rng() - 0.5).multiplyScalar(k);
1129
+ if (f.rigid) {
1130
+ spin.multiplyScalar(Math.min(1, TUMBLE_REACH / Math.max(f.half.x, f.half.y, f.half.z)));
1131
+ this.o.rigid?.shove(f.rigid, [d.x, d.y, d.z], [spin.x, spin.y, spin.z]);
1132
+ continue;
1133
+ }
1124
1134
  f.vel.add(d);
1125
- f.ang.add(this.w.set(this.rng() - 0.5, this.rng() - 0.5, this.rng() - 0.5).multiplyScalar(k));
1135
+ f.ang.add(spin);
1126
1136
  this.rouse(f);
1127
1137
  }
1128
1138
  }
@@ -1176,7 +1186,7 @@ var FragmentSystem = class {
1176
1186
  /** What lies inside the disc looks at the ground again: it was dug or heaped under it. */
1177
1187
  wakeRegion(x, z, radius) {
1178
1188
  for (const f of this.list) {
1179
- if (!f.asleep || Math.hypot(f.mesh.position.x - x, f.mesh.position.z - z) > radius) continue;
1189
+ if (!f.asleep || f.rigid || Math.hypot(f.mesh.position.x - x, f.mesh.position.z - z) > radius) continue;
1180
1190
  this.rouse(f);
1181
1191
  }
1182
1192
  }
@@ -1184,6 +1194,7 @@ var FragmentSystem = class {
1184
1194
  this.tick++;
1185
1195
  this.clock += dt;
1186
1196
  this.wakeUnsupported();
1197
+ this.wakeRigid();
1187
1198
  this.beginTick();
1188
1199
  const g = this.o.gravity;
1189
1200
  for (let i = this.active.length - 1; i >= 0; i--) {
@@ -1194,6 +1205,7 @@ var FragmentSystem = class {
1194
1205
  if (f.fade <= 0) {
1195
1206
  this.instances.remove(f.mesh);
1196
1207
  this.o.scene.remove(f.mesh);
1208
+ this.release(f);
1197
1209
  f.isActive = false;
1198
1210
  this.active.splice(i, 1);
1199
1211
  this.list.splice(this.list.indexOf(f), 1);
@@ -1202,19 +1214,34 @@ var FragmentSystem = class {
1202
1214
  f.mesh.scale.copy(f.baseScale).multiplyScalar(f.fade);
1203
1215
  }
1204
1216
  if (f.asleep) continue;
1205
- this.step(f, dt, g);
1217
+ if (f.rigid) this.follow(f);
1218
+ else this.step(f, dt, g);
1206
1219
  }
1207
1220
  this.expireSleepers();
1208
1221
  this.keepBudget();
1209
1222
  this.trail?.commit();
1210
1223
  this.drawInstanced();
1211
1224
  }
1225
+ /** Its body goes with it. */
1226
+ release(f) {
1227
+ if (f.rigid) this.o.rigid?.remove(f.rigid);
1228
+ f.rigid = null;
1229
+ }
1230
+ /** 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. */
1231
+ wakeRigid() {
1232
+ for (const f of this.list) if (f.rigid && f.asleep && !f.dying && !f.rigid.sleeping) this.rouse(f);
1233
+ }
1234
+ /** A piece of debris moved by its rigid body: the body wrote its pose; it sleeps here when the body does. */
1235
+ follow(f) {
1236
+ f.box = void 0;
1237
+ if (f.rigid?.sleeping) this.sleep(f);
1238
+ }
1212
1239
  /** The meshes go back to the step's pose and the ones awake are recorded as the previous one (`interpolate`). */
1213
1240
  beginTick() {
1214
1241
  const trail = this.trail;
1215
1242
  if (!trail) return;
1216
1243
  trail.begin();
1217
- for (const f of this.active) if (!f.asleep) trail.record(f.mesh);
1244
+ for (const f of this.active) if (!f.asleep && !f.rigid) trail.record(f.mesh);
1218
1245
  }
1219
1246
  /** The meshes get the step pose back, before anything reads them. The instances take it at the next `update`. */
1220
1247
  restoreStepPose() {
@@ -1229,7 +1256,7 @@ var FragmentSystem = class {
1229
1256
  /** The fragments in flight are drawn by the instances, those at rest on their own (the settled batches take them): then the instances take the transforms of this update. */
1230
1257
  drawInstanced() {
1231
1258
  for (const f of this.active) {
1232
- if (f.asleep) this.instances.remove(f.mesh);
1259
+ if (f.asleep || f.rigid) this.instances.remove(f.mesh);
1233
1260
  else this.instances.add(f.mesh);
1234
1261
  }
1235
1262
  this.instances.sync();
@@ -1239,12 +1266,12 @@ var FragmentSystem = class {
1239
1266
  const most = this.o.maxAwake;
1240
1267
  if (most === void 0 || !Number.isFinite(most)) return;
1241
1268
  let awake = 0;
1242
- for (const f of this.active) if (!f.asleep && !f.dying) awake++;
1269
+ for (const f of this.active) if (!f.asleep && !f.dying && !f.rigid) awake++;
1243
1270
  if (awake <= most) return;
1244
1271
  for (let i = 0; i < this.active.length; i++) {
1245
1272
  const f = this.active[i];
1246
1273
  if (awake <= most) return;
1247
- if (f.asleep || f.dying || !f.contact || !isSlow(f)) continue;
1274
+ if (f.asleep || f.dying || f.rigid || !f.contact || !isSlow(f)) continue;
1248
1275
  this.sleep(f);
1249
1276
  i--;
1250
1277
  awake--;
@@ -1276,7 +1303,7 @@ var FragmentSystem = class {
1276
1303
  for (let k = 0; k < Math.min(SUPPORT_CHECKS, n); k++) {
1277
1304
  this.supportTurn = (this.supportTurn + 1) % n;
1278
1305
  const f = this.list[this.supportTurn];
1279
- if (!f.asleep || f.dying) continue;
1306
+ if (!f.asleep || f.dying || f.rigid) continue;
1280
1307
  const e = this.m.makeRotationFromQuaternion(f.mesh.quaternion).elements;
1281
1308
  const ext = Math.abs(e[1]) * f.half.x + Math.abs(e[5]) * f.half.y + Math.abs(e[9]) * f.half.z;
1282
1309
  f.floor = null;
@@ -1462,6 +1489,7 @@ var FragmentSystem = class {
1462
1489
  if (this.list[i].home === home) {
1463
1490
  this.instances.remove(this.list[i].mesh);
1464
1491
  this.o.scene.remove(this.list[i].mesh);
1492
+ this.release(this.list[i]);
1465
1493
  this.deactivate(this.list[i]);
1466
1494
  this.list[i].deadline = Infinity;
1467
1495
  this.list.splice(i, 1);
@@ -1471,7 +1499,10 @@ var FragmentSystem = class {
1471
1499
  clear() {
1472
1500
  this.trail?.clear();
1473
1501
  this.instances.clear();
1474
- for (const f of this.list) this.o.scene.remove(f.mesh);
1502
+ for (const f of this.list) {
1503
+ this.o.scene.remove(f.mesh);
1504
+ this.release(f);
1505
+ }
1475
1506
  this.list.length = 0;
1476
1507
  this.active.length = 0;
1477
1508
  this.mortal.length = 0;
@@ -3388,7 +3419,7 @@ var DEFAULT_MIN_IMPULSE = 30;
3388
3419
  var DEFAULT_HITS_MAX = 32;
3389
3420
  var DEFAULT_MIN_APPROACH = 1.5;
3390
3421
  var DEFAULT_CONTACT_RADIUS = 0.1;
3391
- var createEngineImpacts = (loop, statics, destruction, options = {}) => {
3422
+ var createEngineImpacts = (loop, statics, destruction, options = {}, isDebris) => {
3392
3423
  const hitsMax = options.hitsMax ?? DEFAULT_HITS_MAX;
3393
3424
  const radius = options.contactRadius ?? DEFAULT_CONTACT_RADIUS;
3394
3425
  const minApproach = options.minApproach ?? DEFAULT_MIN_APPROACH;
@@ -3396,8 +3427,11 @@ var createEngineImpacts = (loop, statics, destruction, options = {}) => {
3396
3427
  minImpulse: options.minImpulse ?? DEFAULT_MIN_IMPULSE,
3397
3428
  bodiesMax: hitsMax,
3398
3429
  accepts: (body) => statics.ownerOf.has(body),
3430
+ // what is left of a part that broke breaks nothing again when it lands: a blow of debris is no blow to the world
3431
+ ...isDebris ? { ignores: isDebris } : {},
3399
3432
  onImpact: (impact2) => {
3400
3433
  if (impact2.approach < minApproach) return;
3434
+ if (options.harmless?.(impact2.other)) return;
3401
3435
  const object = statics.ownerOf.get(impact2.body);
3402
3436
  const part = statics.partOf.get(impact2.body);
3403
3437
  if (object === void 0 || part === void 0 || destruction.part(object, part) === null) return;
@@ -3418,6 +3452,97 @@ var createEngineImpacts = (loop, statics, destruction, options = {}) => {
3418
3452
  // src/engine-pieces.ts
3419
3453
  import { samePatch } from "@adatechnology/game-terrain";
3420
3454
 
3455
+ // src/kit-energy.ts
3456
+ var KIT_RULE = {
3457
+ /** A piece that lost a leg and is balanced on the line between the ones left is started down over it (`renderer.ts`). */
3458
+ GO_OVER_IF_BALANCED: "goOverIfBalanced",
3459
+ /** What stood on ground that went (a hole under a foot) is started down over the gap (`renderer.ts`). */
3460
+ CHECK_UNDERMINED: "checkUndermined",
3461
+ /** Furniture made a piece balanced on an edge of its feet is started over it (`EDGE_NUDGE`, `renderer.ts`). */
3462
+ LOOSEN_IF_FOOTLESS: "loosenIfFootless",
3463
+ /** A piece of the engine balanced on a narrow support is turned about its edge (`engine-pieces.ts`). */
3464
+ TOPPLE: "topple"
3465
+ };
3466
+ var RULES = Object.values(KIT_RULE);
3467
+ var GRAVITY = 9.81;
3468
+ var KIT_ENERGY_RESOLUTION = 1e-3;
3469
+ var REST_HEIGHT = KIT_ENERGY_RESOLUTION;
3470
+ var kineticEnergyOf = (body) => {
3471
+ const [vx, vy, vz] = body.velocity;
3472
+ const [wx, wy, wz] = body.angularVelocity;
3473
+ const { x, y, z, w } = body.root.quaternion;
3474
+ const lx = (1 - 2 * (y * y + z * z)) * wx + 2 * (x * y + z * w) * wy + 2 * (x * z - y * w) * wz;
3475
+ const ly = 2 * (x * y - z * w) * wx + (1 - 2 * (x * x + z * z)) * wy + 2 * (y * z + x * w) * wz;
3476
+ const lz = 2 * (x * z + y * w) * wx + 2 * (y * z - x * w) * wy + (1 - 2 * (x * x + y * y)) * wz;
3477
+ const [hx, hy, hz] = body.halfExtents;
3478
+ const m = body.mass;
3479
+ let ix = m * (hy * hy + hz * hz) / 3;
3480
+ let iy = m * (hx * hx + hz * hz) / 3;
3481
+ let iz = m * (hx * hx + hy * hy) / 3;
3482
+ const round = body.round;
3483
+ if (round) {
3484
+ const about = round.inertia * m * round.radius * round.radius;
3485
+ if (round.kind === "sphere") ix = iy = iz = about;
3486
+ else if (round.axis === 0) ix = about;
3487
+ else if (round.axis === 1) iy = about;
3488
+ else iz = about;
3489
+ }
3490
+ return 0.5 * m * (vx * vx + vy * vy + vz * vz) + 0.5 * (ix * lx * lx + iy * ly * ly + iz * lz * lz);
3491
+ };
3492
+ var fallEnergyOf = (body) => {
3493
+ const { x, y, z, w } = body.root.quaternion;
3494
+ const [hx, hy, hz] = body.halfExtents;
3495
+ const [cx, cy, cz] = body.massCentre ?? [0, 0, 0];
3496
+ const rx = 2 * (x * y + z * w);
3497
+ const ry = 1 - 2 * (x * x + z * z);
3498
+ const rz = 2 * (y * z - x * w);
3499
+ const over2 = hx * Math.abs(rx) + hy * Math.abs(ry) + hz * Math.abs(rz) + rx * cx + ry * cy + rz * cz;
3500
+ const lowest = Math.min(hx - Math.abs(cx), hy - Math.abs(cy), hz - Math.abs(cz));
3501
+ return body.mass * GRAVITY * Math.max(0, over2 - lowest);
3502
+ };
3503
+ var KitEnergyLedger = class {
3504
+ constructor(onOver) {
3505
+ __publicField(this, "onOver", onOver);
3506
+ __publicField(this, "before", 0);
3507
+ __publicField(this, "tallies", new Map(RULES.map((rule) => [rule, { pushes: 0, overs: 0, worstShare: 0, worst: null }])));
3508
+ __publicField(this, "episodes", /* @__PURE__ */ new WeakMap());
3509
+ }
3510
+ begin(body) {
3511
+ this.before = kineticEnergyOf(body);
3512
+ if (this.before > body.mass * GRAVITY * REST_HEIGHT) return;
3513
+ const episode = this.episodes.get(body);
3514
+ if (!episode) {
3515
+ this.episodes.set(body, { given: new Float64Array(RULES.length), over: new Uint8Array(RULES.length), fall: fallEnergyOf(body) });
3516
+ return;
3517
+ }
3518
+ episode.given.fill(0);
3519
+ episode.over.fill(0);
3520
+ episode.fall = fallEnergyOf(body);
3521
+ }
3522
+ end(rule, body) {
3523
+ const tally = this.tallies.get(rule);
3524
+ tally.pushes++;
3525
+ const episode = this.episodes.get(body);
3526
+ const open = episode ?? { given: new Float64Array(RULES.length), over: new Uint8Array(RULES.length), fall: fallEnergyOf(body) };
3527
+ if (!episode) this.episodes.set(body, open);
3528
+ const index = RULES.indexOf(rule);
3529
+ const given = open.given[index] + kineticEnergyOf(body) - this.before;
3530
+ open.given[index] = given;
3531
+ const share = given <= 0 ? 0 : given / (open.fall + body.mass * GRAVITY * KIT_ENERGY_RESOLUTION);
3532
+ if (share > tally.worstShare) {
3533
+ tally.worstShare = share;
3534
+ tally.worst = { rule, objectId: body.objectId, given, fall: open.fall };
3535
+ }
3536
+ if (share <= 1 || open.over[index]) return;
3537
+ open.over[index] = 1;
3538
+ tally.overs++;
3539
+ this.onOver?.({ rule, objectId: body.objectId, given, fall: open.fall });
3540
+ }
3541
+ tally() {
3542
+ return RULES.map((rule) => ({ rule, ...this.tallies.get(rule) }));
3543
+ }
3544
+ };
3545
+
3421
3546
  // src/engine-ground-heights.ts
3422
3547
  var changedHeights = (before, after, size) => {
3423
3548
  let minX = size;
@@ -3855,6 +3980,7 @@ var WAKE_MARGIN2 = 0.1;
3855
3980
  var NO_PROGRESS = 0.75;
3856
3981
  var WAY_STEP_MIN = 0.02;
3857
3982
  var WAY_STEP_MAX = 0.1;
3983
+ var BORN_INSIDE = { layers: ["static", "rubble"] };
3858
3984
  var EnginePieces = class {
3859
3985
  constructor(THREE, world, o) {
3860
3986
  __publicField(this, "world", world);
@@ -3897,6 +4023,12 @@ var EnginePieces = class {
3897
4023
  __publicField(this, "blasts", []);
3898
4024
  /** The host's fixed things (`staticSolids`) as static bodies. */
3899
4025
  __publicField(this, "statics");
4026
+ /** The debris still passing through a fixed thing it was made inside (`throughStatics`). */
4027
+ __publicField(this, "passing", /* @__PURE__ */ new Set());
4028
+ /** A set of one fixed body, to ask how deep a piece is in that one. */
4029
+ __publicField(this, "oneStatic", /* @__PURE__ */ new Set());
4030
+ /** The bodies a piece of debris overlaps where it is made (`throughStatics`), kept between asks. */
4031
+ __publicField(this, "overlapped", []);
3900
4032
  __publicField(this, "ignored", /* @__PURE__ */ new Set());
3901
4033
  __publicField(this, "knocks", /* @__PURE__ */ new Map());
3902
4034
  __publicField(this, "footprintOut", { corners: new Float64Array(16), normals: new Float64Array(6), minX: 0, maxX: 0, minZ: 0, maxZ: 0 });
@@ -4001,6 +4133,7 @@ var EnginePieces = class {
4001
4133
  this.byUser.delete(link.user);
4002
4134
  this.byBody.delete(link.id);
4003
4135
  this.bodyIds.delete(link.id);
4136
+ this.passing.delete(b);
4004
4137
  this.active.delete(b);
4005
4138
  if (this.byObject.get(b.objectId) === b) this.byObject.delete(b.objectId);
4006
4139
  this.links.delete(b);
@@ -4141,6 +4274,7 @@ var EnginePieces = class {
4141
4274
  this.makeBodies(each);
4142
4275
  each((b) => this.hang(b));
4143
4276
  each((b) => this.sync(b, dt, h));
4277
+ this.meetStaticsAgain();
4144
4278
  if (this.schedule) this.layGroundLater(each, dt);
4145
4279
  else this.layGround(each, dt);
4146
4280
  this.keepApart(apart2);
@@ -4414,7 +4548,8 @@ var EnginePieces = class {
4414
4548
  this.byBody.set(id, b);
4415
4549
  this.bodyIds.add(id);
4416
4550
  this.byObject.set(b.objectId, b);
4417
- this.outOfStatics(b, link);
4551
+ if (b.debris) this.throughStatics(b, link);
4552
+ else this.outOfStatics(b, link);
4418
4553
  });
4419
4554
  }
4420
4555
  bodyDesc(b, user) {
@@ -4431,7 +4566,7 @@ var EnginePieces = class {
4431
4566
  centreAtOrigin: true,
4432
4567
  keepPartContacts: shape.kind === "compound" && shape.children.length > 1,
4433
4568
  material: this.material(b),
4434
- layer: "debris",
4569
+ layer: b.debris ? "rubble" : "debris",
4435
4570
  // no air drag: the kit's pieces never had any (a round piece's rolling resistance is the adapter's, `rolling`)
4436
4571
  angularDamping: 0,
4437
4572
  linearDamping: 0,
@@ -4495,6 +4630,52 @@ var EnginePieces = class {
4495
4630
  * lifted (`underGround`). Left to the engine it is pushed out a little each step (`maxPushOut`), which reads as the piece rising by itself: a roof sheet made 1 m
4496
4631
  * into a shelf rose 0.83-0.94 m over the room's 11 s. Only past a contact's sink (`SINK`): resting on a shelf it is not moved.
4497
4632
  */
4633
+ /**
4634
+ * A piece of debris made inside something (the bars of a cage that gave way, inside the wall that still stands; a chunk overlapping the part next to the one that broke,
4635
+ * or the chunk cut beside it) is not moved out of it as a piece is (`outOfStatics`), and the engine does not push the two apart: debris is born
4636
+ * where the thing broke. It passes through what it was made inside until it is out of it, and only through that.
4637
+ */
4638
+ throughStatics(b, link) {
4639
+ const q = b.root.quaternion;
4640
+ const c = this.centre(b);
4641
+ const found = this.overlapped;
4642
+ this.world.overlapShape(this.shapeOf(b), [c.x, c.y, c.z], [q.x, q.y, q.z, q.w], found, BORN_INSIDE);
4643
+ for (const id of found) {
4644
+ if (id === link.id || link.through?.includes(id) || !(this.statics.ids.has(id) || this.bodyIds.has(id))) continue;
4645
+ this.world.ignorePair(link.id, id, true);
4646
+ (link.through ?? (link.through = [])).push(id);
4647
+ }
4648
+ if (link.through?.length) this.passing.add(b);
4649
+ }
4650
+ /** The debris passing through what it was made inside meets it again once it is out of it; what was made again meanwhile (a fixed thing's body is a new one) is looked at afresh. */
4651
+ meetStaticsAgain() {
4652
+ if (this.passing.size === 0 || !this.world.penetration) return;
4653
+ const one = this.oneStatic;
4654
+ for (const b of this.passing) {
4655
+ const link = this.links.get(b);
4656
+ const through = link?.through;
4657
+ if (!link || !through) {
4658
+ this.passing.delete(b);
4659
+ continue;
4660
+ }
4661
+ let remade = false;
4662
+ for (let i = through.length - 1; i >= 0; i--) {
4663
+ const id = through[i];
4664
+ if (!this.statics.ids.has(id) && !this.bodyIds.has(id)) {
4665
+ remade = true;
4666
+ through.splice(i, 1);
4667
+ continue;
4668
+ }
4669
+ one.clear();
4670
+ one.add(id);
4671
+ if (this.world.penetration(link.id, this.outAxis, one) > SINK) continue;
4672
+ this.world.ignorePair(link.id, id, false);
4673
+ through.splice(i, 1);
4674
+ }
4675
+ if (remade) this.throughStatics(b, link);
4676
+ if (through.length === 0) this.passing.delete(b);
4677
+ }
4678
+ }
4498
4679
  outOfStatics(b, link) {
4499
4680
  if (!this.world.penetration) return;
4500
4681
  const axis = this.outAxis;
@@ -4686,20 +4867,25 @@ var EnginePieces = class {
4686
4867
  if (wx <= wz) {
4687
4868
  const edge = dirX > 0 ? x1 : x0;
4688
4869
  const dw = edge * dirX > 0 ? -dirX * this.topplePush(edge, height, isColumn && Math.abs(w[2]) < PUSH_SPIN, this.turningOf(b, 2)) * dt : 0;
4870
+ if (dw === 0) return;
4689
4871
  const rx = -edge;
4690
4872
  const ry = -low;
4873
+ this.o.kitEnergy?.begin(b);
4691
4874
  w[2] += dw;
4692
4875
  v[0] += -dw * ry;
4693
4876
  v[1] += dw * rx;
4694
4877
  } else {
4695
4878
  const edge = dirZ > 0 ? z1 : z0;
4696
4879
  const dw = edge * dirZ > 0 ? dirZ * this.topplePush(edge, height, isColumn && Math.abs(w[0]) < PUSH_SPIN, this.turningOf(b, 0)) * dt : 0;
4880
+ if (dw === 0) return;
4697
4881
  const rz = -edge;
4698
4882
  const ry = -low;
4883
+ this.o.kitEnergy?.begin(b);
4699
4884
  w[0] += dw;
4700
4885
  v[1] += -dw * rz;
4701
4886
  v[2] += dw * ry;
4702
4887
  }
4888
+ this.o.kitEnergy?.end(KIT_RULE.TOPPLE, b);
4703
4889
  }
4704
4890
  /** 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). */
4705
4891
  slip(b, link, isSlipping) {
@@ -5451,6 +5637,8 @@ var PieceSystem = class {
5451
5637
  __publicField(this, "supportNormal", UP);
5452
5638
  __publicField(this, "supportFriction", null);
5453
5639
  __publicField(this, "supportBody", null);
5640
+ /** What each rule of the kit gave the pieces it pushed (`ruleImpulse`, and the engine's own `topple`). */
5641
+ __publicField(this, "kitEnergy");
5454
5642
  /** A piece is asleep on both sides (the engine's too): nothing of it changes until it wakes. */
5455
5643
  __publicField(this, "isSettled", (body) => this.engine.isSettled(body));
5456
5644
  __publicField(this, "measureAwake", (body) => {
@@ -5484,7 +5672,9 @@ var PieceSystem = class {
5484
5672
  this.loop = resolved.loop;
5485
5673
  this.stepsItself = resolved.stepsItself;
5486
5674
  this.trail = o.interpolate ? new PoseTrail() : null;
5675
+ this.kitEnergy = new KitEnergyLedger(o.onKitEnergy);
5487
5676
  this.engine = new EnginePieces(THREE, resolved.loop.world, {
5677
+ kitEnergy: this.kitEnergy,
5488
5678
  groundAt: o.terrainAt ?? o.groundAt,
5489
5679
  ...o.terrainRollingAt ? { groundRollingAt: o.terrainRollingAt } : {},
5490
5680
  ...o.terrainRollingDampingAt ? { groundRollingDampingAt: o.terrainRollingDampingAt } : {},
@@ -5509,7 +5699,7 @@ var PieceSystem = class {
5509
5699
  }
5510
5700
  /** Contact blows on the fixed parts become `blunt` hits of `destruction` (`engine-impacts.ts`). Returns the way to stop it. */
5511
5701
  contactHits(destruction, options) {
5512
- return createEngineImpacts(this.loop, this.engine.statics, destruction, options);
5702
+ return createEngineImpacts(this.loop, this.engine.statics, destruction, options, (body) => this.engine.pieceOfBody(body)?.debris === true);
5513
5703
  }
5514
5704
  /**
5515
5705
  * The pieces a blast at `point` can reach: the bodies the engine's `blastQuery` finds within `radius` (the pieces among them), in the order of `list`, and the pieces that have no
@@ -5826,6 +6016,20 @@ var PieceSystem = class {
5826
6016
  b.still = 0;
5827
6017
  b.calmAt = null;
5828
6018
  }
6019
+ /** `impulse` given by a rule of the kit on its own, measured by its name (`kitEnergy`). */
6020
+ ruleImpulse(rule, b, impulse, point) {
6021
+ this.kitEnergy.begin(b);
6022
+ this.impulse(b, impulse, point);
6023
+ this.kitEnergy.end(rule, b);
6024
+ }
6025
+ /** Spin (rad/s, world axes x and z) added by a rule of the kit on its own, measured by its name (`kitEnergy`). */
6026
+ ruleSpin(rule, b, x, z) {
6027
+ this.kitEnergy.begin(b);
6028
+ b.angularVelocity[0] += x;
6029
+ b.angularVelocity[2] += z;
6030
+ b.sleeping = false;
6031
+ this.kitEnergy.end(rule, b);
6032
+ }
5829
6033
  /** 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). */
5830
6034
  mulInvInertia(b, x, y, z) {
5831
6035
  this.m.makeRotationFromQuaternion(b.root.quaternion);
@@ -6178,13 +6382,13 @@ var PieceSystem = class {
6178
6382
  if (most === void 0 || !Number.isFinite(most)) return;
6179
6383
  let awake = 0;
6180
6384
  for (const b of this.list) {
6181
- if (b.sleeping || b.held) continue;
6385
+ if (b.sleeping || b.held || b.debris) continue;
6182
6386
  if (this.hasComeToRest(b) && (b.balancing || b.still >= SLEEP_AFTER && !b.hinge && !this.onSteepSupport(b))) this.sleepByBudget(b);
6183
6387
  else awake++;
6184
6388
  }
6185
6389
  for (const b of this.list) {
6186
6390
  if (awake <= most) return;
6187
- if (b.sleeping || b.held || !this.hasComeToRest(b)) continue;
6391
+ if (b.sleeping || b.held || b.debris || !this.hasComeToRest(b)) continue;
6188
6392
  this.sleepByBudget(b);
6189
6393
  awake--;
6190
6394
  }
@@ -6203,12 +6407,13 @@ var PieceSystem = class {
6203
6407
  const c = this.centerOf(b, this.p);
6204
6408
  return Math.hypot(c.x - focus[0], c.y - focus[1], c.z - focus[2]) > keep.far.distance;
6205
6409
  };
6206
- const atRest = this.list.filter((b) => !b.held && this.hasComeToRest(b));
6410
+ const pieces = this.list.filter((b) => !b.debris);
6411
+ const atRest = pieces.filter((b) => !b.held && this.hasComeToRest(b));
6207
6412
  if (keep.far.action === "sleep") {
6208
6413
  for (const b of atRest) if (!b.sleeping && isFarAndOld(b)) this.sleepByBudget(b);
6209
6414
  }
6210
6415
  const fades = keep.far.action === "fade";
6211
- let over2 = this.list.length - keep.maxLive;
6416
+ let over2 = pieces.length - keep.maxLive;
6212
6417
  const far2 = new Set(atRest.filter(isFarAndOld));
6213
6418
  for (const b of [...atRest].sort((a, c) => Number(far2.has(c)) - Number(far2.has(a)))) {
6214
6419
  if (!(over2 > 0 || fades && far2.has(b))) return;
@@ -8745,6 +8950,7 @@ var UNDERMINED_STAND = 0.4;
8745
8950
  var UNDERMINED_KEEP = 0.6;
8746
8951
  var SOLIDS_MAX = 64;
8747
8952
  var UNDERMINED_PUSH = 0.6;
8953
+ var DEBRIS_ID = "debris#";
8748
8954
  var UNDERMINED_STILL = 0.05;
8749
8955
  var SOLID_WELD = 1e-4;
8750
8956
  var UNCHECKED_KINDS = /* @__PURE__ */ new Set(["structure", "room", "ground"]);
@@ -8978,6 +9184,8 @@ var Renderer = class {
8978
9184
  /** The parts the ground went down under, drawn going down (`subside`). */
8979
9185
  __publicField(this, "settlement");
8980
9186
  __publicField(this, "fragments");
9187
+ /** Count of the bodies made for big debris: each gets an id of its own. */
9188
+ __publicField(this, "debrisMade", 0);
8981
9189
  __publicField(this, "ground");
8982
9190
  __publicField(this, "pieceSys");
8983
9191
  __publicField(this, "cages");
@@ -9064,7 +9272,34 @@ var Renderer = class {
9064
9272
  // and it meets the walls, ceilings and furniture on its way: it stops on their face instead of flying into them
9065
9273
  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,
9066
9274
  maxAwake: o.maxAwakeFragments ?? Infinity,
9067
- ...o.interpolate ? { interpolate: true } : {}
9275
+ ...o.interpolate ? { interpolate: true } : {},
9276
+ rigid: {
9277
+ add: (mesh, half, mass, velocity, angular) => {
9278
+ const body = this.pieceSys.create(`${DEBRIS_ID}${++this.debrisMade}`, mesh, [half[0], half[1], half[2]], new THREE.Vector3(), mass, [velocity[0], velocity[1], velocity[2]], [angular[0], angular[1], angular[2]]);
9279
+ body.debris = true;
9280
+ return body;
9281
+ },
9282
+ remove: (handle) => this.pieceSys.remove(handle.objectId),
9283
+ push: (handle, x, z) => {
9284
+ const body = handle;
9285
+ body.velocity[0] = x;
9286
+ body.velocity[2] = z;
9287
+ body.velocity[1] = Math.max(body.velocity[1], 0.3);
9288
+ body.sleeping = false;
9289
+ body.still = 0;
9290
+ body.calmAt = null;
9291
+ },
9292
+ shove: (handle, velocity, spin) => {
9293
+ const body = handle;
9294
+ for (let i = 0; i < 3; i++) {
9295
+ body.velocity[i] = body.velocity[i] + velocity[i];
9296
+ body.angularVelocity[i] = body.angularVelocity[i] + spin[i];
9297
+ }
9298
+ body.sleeping = false;
9299
+ body.still = 0;
9300
+ body.calmAt = null;
9301
+ }
9302
+ }
9068
9303
  });
9069
9304
  this.cages = new RebarCages(THREE, o.scene);
9070
9305
  this.settledBatches = new SettledBatches(THREE, o.scene, o.settledBatches ?? { enabled: false });
@@ -9091,6 +9326,7 @@ var Renderer = class {
9091
9326
  ...o.groundWorkerFrames !== void 0 ? { groundWorkerFrames: o.groundWorkerFrames } : {},
9092
9327
  ...this.blastDebris ? { keep: { maxLive: this.blastDebris.maxLivePieces, far: this.blastDebris.far, ...o.focus ? { focus: o.focus } : {}, onFade: (b) => this.fadePiece(b) } } : {},
9093
9328
  onHardLanding: (p, point, speed) => this.hardLanding(p, point, speed),
9329
+ ...o.onKitEnergy ? { onKitEnergy: o.onKitEnergy } : {},
9094
9330
  sweep: (p, from, to) => this.sweepPiece(p, from, to),
9095
9331
  onSlam: (p, hit, speed) => this.slam(p, hit, speed),
9096
9332
  // two pieces knocked together: each sounds as its material does (a can on a can, a bottle on a table's leg)
@@ -9536,10 +9772,15 @@ var Renderer = class {
9536
9772
  return shape === 0 ? 1 : drawn / shape;
9537
9773
  }
9538
9774
  pieces() {
9539
- return [...this.pieceSys.list];
9775
+ return this.pieceSys.list.filter((piece) => !piece.debris);
9540
9776
  }
9541
9777
  piece(objectId) {
9542
- return this.pieceSys.get(objectId);
9778
+ const piece = this.pieceSys.get(objectId);
9779
+ return piece && !piece.debris ? piece : null;
9780
+ }
9781
+ /** 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`). */
9782
+ kitEnergy() {
9783
+ return this.pieceSys.kitEnergy.tally();
9543
9784
  }
9544
9785
  impulse(objectId, impulse, point) {
9545
9786
  const p = this.pieceSys.get(objectId);
@@ -9567,6 +9808,7 @@ var Renderer = class {
9567
9808
  }
9568
9809
  /** A piece thrown into a wall: the wall takes the blow of its weight where it met it, the piece takes it too, and each sounds as its material does. */
9569
9810
  slam(p, hit, speed) {
9811
+ if (p.debris) return;
9570
9812
  const energy = 0.5 * p.mass * speed * speed;
9571
9813
  const direction = [-hit.normal[0], -hit.normal[1], -hit.normal[2]];
9572
9814
  this.landingSound(hit.object, hit.point, clamp(speed / 10, 0.2, 1));
@@ -9578,6 +9820,7 @@ var Renderer = class {
9578
9820
  }
9579
9821
  }
9580
9822
  hardLanding(p, point, speed) {
9823
+ if (p.debris) return;
9581
9824
  this.landingSound(p.objectId, point, clamp(speed / 10, 0.2, 1));
9582
9825
  this.syncBound(p.objectId);
9583
9826
  try {
@@ -10186,7 +10429,7 @@ var Renderer = class {
10186
10429
  for (const [id, a] of this.staticNow()) scan(a, id, null, 6);
10187
10430
  const c = this.v1;
10188
10431
  for (const pc of this.pieceSys.list) {
10189
- if (pc.held) continue;
10432
+ if (pc.held || pc.debris) continue;
10190
10433
  this.pieceSys.centerOf(pc, c);
10191
10434
  const reach = Math.hypot(pc.halfExtents[0], pc.halfExtents[1], pc.halfExtents[2]) + radius;
10192
10435
  if (Math.abs(c.x - x) > reach || Math.abs(c.z - z) > reach) continue;
@@ -11216,9 +11459,7 @@ var Renderer = class {
11216
11459
  this.setContacts(b, b.piece ?? piece, left);
11217
11460
  const loose = b.piece;
11218
11461
  if (away && loose) {
11219
- loose.angularVelocity[0] += away.z * EDGE_NUDGE;
11220
- loose.angularVelocity[2] -= away.x * EDGE_NUDGE;
11221
- loose.sleeping = false;
11462
+ this.pieceSys.ruleSpin(KIT_RULE.LOOSEN_IF_FOOTLESS, loose, away.z * EDGE_NUDGE, -away.x * EDGE_NUDGE);
11222
11463
  } else this.tipIfTopHeavy(b);
11223
11464
  this.o.onLoosened?.(objectId, piece, "apart");
11224
11465
  }
@@ -11314,7 +11555,7 @@ var Renderer = class {
11314
11555
  body.sleeping = false;
11315
11556
  body.still = 0;
11316
11557
  body.calmAt = null;
11317
- if (held.length > 0 && length > 1e-6) this.pieceSys.impulse(body, [0, -body.mass * UNDERMINED_PUSH, 0], [centre[0] + gx, floor, centre[2] + gz]);
11558
+ if (held.length > 0 && length > 1e-6) this.pieceSys.ruleImpulse(KIT_RULE.CHECK_UNDERMINED, body, [0, -body.mass * UNDERMINED_PUSH, 0], [centre[0] + gx, floor, centre[2] + gz]);
11318
11559
  if (!was) this.o.onLoosened?.(b.id, body, "ground");
11319
11560
  }
11320
11561
  }
@@ -11331,7 +11572,7 @@ var Renderer = class {
11331
11572
  if (this.standsWith(held, null, centre, feet.floor)) return;
11332
11573
  const inside = insideBy(convexHull(held), [centre[0], centre[2]]);
11333
11574
  const reach = this.reachAlong(body, inside.out.x, inside.out.z);
11334
- this.pieceSys.impulse(body, [0, -body.mass * UNDERMINED_PUSH, 0], [centre[0] + inside.out.x * reach, feet.floor, centre[2] + inside.out.z * reach]);
11575
+ this.pieceSys.ruleImpulse(KIT_RULE.GO_OVER_IF_BALANCED, body, [0, -body.mass * UNDERMINED_PUSH, 0], [centre[0] + inside.out.x * reach, feet.floor, centre[2] + inside.out.z * reach]);
11335
11576
  }
11336
11577
  /** 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. */
11337
11578
  reachAlong(body, x, z) {
@@ -11755,7 +11996,7 @@ var Renderer = class {
11755
11996
  reach(distance, { objectId: pc.objectId, generation: pc.generation, impulse, point }, [c.x, c.y, c.z]);
11756
11997
  };
11757
11998
  const reached = this.o.blastQuery ? this.pieceSys.piecesInBlast(this.o.blastQuery, p, ev.radius) : [...this.pieceSys.list];
11758
- for (const pc of reached) shove(pc);
11999
+ for (const pc of reached) if (!pc.debris) shove(pc);
11759
12000
  if (this.o.shoveable) this.loosen(p, ev.radius, energy, reachOf2, policy, reach);
11760
12001
  this.advanceWakes(0);
11761
12002
  this.fragments.blast(p, ev.radius, Math.min(20, Math.sqrt(energy) * 0.08));
@@ -11823,6 +12064,7 @@ var Renderer = class {
11823
12064
  if (centre.distanceTo(point) <= ev.radius) cover.set(objectId, reach.call(this.world, ev.point, [centre.x, centre.y, centre.z], { ignore: [ev.object, objectId] }));
11824
12065
  };
11825
12066
  for (const pc of this.pieceSys.list) {
12067
+ if (pc.debris) continue;
11826
12068
  this.pieceSys.centerOf(pc, centre);
11827
12069
  read(pc.objectId);
11828
12070
  }
@@ -13402,6 +13644,8 @@ export {
13402
13644
  IMPACT_FAMILY_TAGS,
13403
13645
  IMPACT_SOUNDS,
13404
13646
  IMPACT_SOUND_KEYS,
13647
+ KIT_ENERGY_RESOLUTION,
13648
+ KIT_RULE,
13405
13649
  MIN_PIECE_MASS_KG,
13406
13650
  PhysicsOptionError,
13407
13651
  ROCKET_MOTOR_LOOP,