@adatechnology/game-destruction-three 0.21.0 → 0.22.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.
@@ -5306,12 +5306,14 @@ var GameDestructionThree = (() => {
5306
5306
  return bands.scales[3];
5307
5307
  }
5308
5308
  var BLOOD_LIMIT = 450;
5309
+ var SCRAPE_LIMIT = 400;
5309
5310
  var SCORCH_VARIANTS = 3;
5310
5311
  var RIM_COLORS = [2829359, 3815478];
5311
5312
  function createMarkStore() {
5312
5313
  const entries2 = [];
5313
5314
  let version = 0;
5314
5315
  let bloodCount = 0;
5316
+ let scrapeCount = 0;
5315
5317
  const listeners = /* @__PURE__ */ new Set();
5316
5318
  return {
5317
5319
  entries: entries2,
@@ -5321,16 +5323,25 @@ var GameDestructionThree = (() => {
5321
5323
  get bloodCount() {
5322
5324
  return bloodCount;
5323
5325
  },
5326
+ get scrapeCount() {
5327
+ return scrapeCount;
5328
+ },
5324
5329
  lift: 0,
5325
5330
  add(mark) {
5331
+ if (mark.kind === "scrape" && scrapeCount >= SCRAPE_LIMIT) {
5332
+ entries2.splice(entries2.findIndex((m) => m.kind === "scrape"), 1);
5333
+ scrapeCount--;
5334
+ }
5326
5335
  entries2.push(mark);
5327
5336
  if (mark.kind === "blood") bloodCount++;
5337
+ if (mark.kind === "scrape") scrapeCount++;
5328
5338
  version++;
5329
5339
  for (const listener of listeners) listener({ type: "add", mark });
5330
5340
  },
5331
5341
  clear() {
5332
5342
  entries2.length = 0;
5333
5343
  bloodCount = 0;
5344
+ scrapeCount = 0;
5334
5345
  this.lift = 0;
5335
5346
  version++;
5336
5347
  for (const listener of listeners) listener({ type: "clear" });
@@ -5390,6 +5401,9 @@ var GameDestructionThree = (() => {
5390
5401
  const scaleZ = spec.radius * random.between(1.2, 2);
5391
5402
  store.add({ kind: "blood", x: spec.x, y, z: spec.z, scaleX, scaleZ, rotation: random.next() * 6 });
5392
5403
  }
5404
+ function addScrape(store, spec) {
5405
+ store.add({ kind: "scrape", ...spec, y: spec.y + 2e-3 + nextLift(store) * 2e-4 });
5406
+ }
5393
5407
  function createRingPool(capacity) {
5394
5408
  return new OrderedPool(capacity, () => ({ x: 0, z: 0, y0: 0, rise: 0, rk: 0, R0: 0, R1: 0, r: 0, roll: 0, t: 0, life: 0 }));
5395
5409
  }
@@ -7688,6 +7702,7 @@ var GameDestructionThree = (() => {
7688
7702
  }),
7689
7703
  fires: () => core.fires.items,
7690
7704
  onMarks: (listener) => core.marks.subscribe(listener),
7705
+ scrape: (mark) => addScrape(core.marks, mark),
7691
7706
  time: () => core.clock.time,
7692
7707
  randomState: () => sharedRandom.state,
7693
7708
  clear() {
@@ -7741,7 +7756,7 @@ var GameDestructionThree = (() => {
7741
7756
  };
7742
7757
  var EFFECT_STEP_SECONDS = 1 / 50;
7743
7758
 
7744
- // ../game-vfx-three/dist/chunk-IOGYK5RO.js
7759
+ // ../game-vfx-three/dist/chunk-PZ6IVOLZ.js
7745
7760
  var GLOW_VERTEX = `attribute vec4 aP;attribute vec4 aC;varying vec2 vU;varying vec4 vC;
7746
7761
  void main(){vec3 R=vec3(viewMatrix[0][0],viewMatrix[1][0],viewMatrix[2][0]);vec3 Up=vec3(viewMatrix[0][1],viewMatrix[1][1],viewMatrix[2][1]);
7747
7762
  vec3 wp=aP.xyz+(R*position.x+Up*position.y)*aP.w;vU=position.xy;vC=aC;gl_Position=projectionMatrix*viewMatrix*vec4(wp,1.);}`;
@@ -8221,6 +8236,9 @@ void main(){
8221
8236
  const bloodMaterial = new THREE.MeshStandardMaterial({ color: 6031882, roughness: 0.15, metalness: 0.1, polygonOffset: true, polygonOffsetFactor: -3, polygonOffsetUnits: -3 });
8222
8237
  const bloodGeometry = new THREE.CircleGeometry(0.5, 9).rotateX(-Math.PI / 2);
8223
8238
  owned.push(bloodMaterial, bloodGeometry);
8239
+ const scrapeMaterial = new THREE.MeshStandardMaterial({ color: 16777215, roughness: 0.6, transparent: true, opacity: 0.55, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -4, polygonOffsetUnits: -4 });
8240
+ const scrapeGeometry = new THREE.PlaneGeometry(1, 1).rotateX(-Math.PI / 2);
8241
+ owned.push(scrapeMaterial, scrapeGeometry);
8224
8242
  const maxGroundMarks = options.maxGroundMarks ?? DEFAULT_MAX_GROUND_MARKS;
8225
8243
  const instanced = {};
8226
8244
  function rockMaterial() {
@@ -8233,6 +8251,9 @@ void main(){
8233
8251
  function bloodMesh() {
8234
8252
  return instanced.blood ?? (instanced.blood = attach(createInstanced(bloodGeometry, bloodMaterial, options.maxBlood ?? DEFAULT_MAX_BLOOD)));
8235
8253
  }
8254
+ function scrapeMesh() {
8255
+ return instanced.scrape ?? (instanced.scrape = attach(createInstanced(scrapeGeometry, scrapeMaterial, SCRAPE_LIMIT)));
8256
+ }
8236
8257
  function rockMesh() {
8237
8258
  return instanced.rock ?? (instanced.rock = attach(createInstanced(options.rockGeometry, rockMaterial(), options.maxRocks ?? DEFAULT_MAX_ROCKS), true));
8238
8259
  }
@@ -8248,7 +8269,7 @@ void main(){
8248
8269
  const groundMarks = [];
8249
8270
  const spareGeometries = [];
8250
8271
  const blood = [];
8251
- const placed = { blood: 0, rock: 0, plate: 0 };
8272
+ const placed = { blood: 0, rock: 0, plate: 0, scrape: 0 };
8252
8273
  const matrix = new THREE.Matrix4();
8253
8274
  const position = new THREE.Vector3();
8254
8275
  const quaternion = new THREE.Quaternion();
@@ -8335,10 +8356,21 @@ void main(){
8335
8356
  writeBlood(index, drawn, BLOOD_START_GROWTH);
8336
8357
  bloodMesh().count = Math.min(placed.blood, bloodMesh().instanceMatrix.count);
8337
8358
  }
8359
+ function addScrape2(mark) {
8360
+ const mesh2 = scrapeMesh();
8361
+ const index = placed.scrape++ % mesh2.instanceMatrix.count;
8362
+ quaternion.setFromAxisAngle(up, -mark.rotation);
8363
+ mesh2.setMatrixAt(index, matrix.compose(position.set(mark.x, mark.y, mark.z), quaternion, scale.set(mark.length, 1, mark.width)));
8364
+ mesh2.setColorAt(index, color.set(mark.color));
8365
+ mesh2.count = Math.min(placed.scrape, mesh2.instanceMatrix.count);
8366
+ mesh2.instanceMatrix.needsUpdate = true;
8367
+ mesh2.instanceColor.needsUpdate = true;
8368
+ }
8338
8369
  function build(mark) {
8339
8370
  if (mark.kind === "scorch") conform(mark, scorchMaterials[mark.variant]);
8340
8371
  else if (mark.kind === "dirt") conform(mark, dirtMaterial);
8341
8372
  else if (mark.kind === "rock") addRock(mark);
8373
+ else if (mark.kind === "scrape") addScrape2(mark);
8342
8374
  else addBlood(mark);
8343
8375
  }
8344
8376
  function clearMarks() {
@@ -8348,8 +8380,8 @@ void main(){
8348
8380
  for (const geometry of spareGeometries) geometry.dispose();
8349
8381
  spareGeometries.length = 0;
8350
8382
  blood.length = 0;
8351
- placed.blood = placed.rock = placed.plate = 0;
8352
- for (const mesh2 of [instanced.blood, instanced.rock, instanced.plate]) if (mesh2) mesh2.count = 0;
8383
+ placed.blood = placed.rock = placed.plate = placed.scrape = 0;
8384
+ for (const mesh2 of [instanced.blood, instanced.rock, instanced.plate, instanced.scrape]) if (mesh2) mesh2.count = 0;
8353
8385
  }
8354
8386
  return {
8355
8387
  group,
@@ -8361,6 +8393,7 @@ void main(){
8361
8393
  bloodMesh();
8362
8394
  rockMesh();
8363
8395
  plateMesh();
8396
+ scrapeMesh();
8364
8397
  },
8365
8398
  probes() {
8366
8399
  probeGeometry ?? (probeGeometry = new THREE.PlaneGeometry(1e-3, 1e-3).rotateX(-Math.PI / 2));
@@ -8379,10 +8412,10 @@ void main(){
8379
8412
  writeBlood(index, drawn, Math.max(BLOOD_START_GROWTH, 1 - Math.pow(1 - Math.min(1, drawn.age), 2.5)));
8380
8413
  }
8381
8414
  },
8382
- count: () => groundMarks.length + [instanced.blood, instanced.rock, instanced.plate].filter((mesh2) => mesh2 && mesh2.count > 0).length,
8415
+ count: () => groundMarks.length + [instanced.blood, instanced.rock, instanced.plate, instanced.scrape].filter((mesh2) => mesh2 && mesh2.count > 0).length,
8383
8416
  dispose() {
8384
8417
  clearMarks();
8385
- for (const mesh2 of [instanced.blood, instanced.rock, instanced.plate]) mesh2?.dispose();
8418
+ for (const mesh2 of [instanced.blood, instanced.rock, instanced.plate, instanced.scrape]) mesh2?.dispose();
8386
8419
  probeGeometry?.dispose();
8387
8420
  for (const item of owned) item.dispose();
8388
8421
  }
@@ -9943,6 +9976,110 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
9943
9976
  }
9944
9977
  };
9945
9978
 
9979
+ // src/piece-contacts.ts
9980
+ var SEGMENT_BOX_ROUNDS = 4;
9981
+ var PARALLEL = 1e-4;
9982
+ var sub2 = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
9983
+ var dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
9984
+ var along = (a, d, t) => [a[0] + d[0] * t, a[1] + d[1] * t, a[2] + d[2] * t];
9985
+ var clamp01 = (t) => t < 0 ? 0 : t > 1 ? 1 : t;
9986
+ var nearestOnSegment = (from, to, p) => {
9987
+ const d = sub2(to, from);
9988
+ const len2 = dot(d, d);
9989
+ return len2 < 1e-12 ? from : along(from, d, clamp01(dot(sub2(p, from), d) / len2));
9990
+ };
9991
+ var nearestOfSegments = (p1, q1, p2, q2) => {
9992
+ const d1 = sub2(q1, p1);
9993
+ const d2 = sub2(q2, p2);
9994
+ const r = sub2(p1, p2);
9995
+ const a = dot(d1, d1);
9996
+ const e = dot(d2, d2);
9997
+ const f = dot(d2, r);
9998
+ let s = 0;
9999
+ let t = 0;
10000
+ if (a < 1e-12 && e < 1e-12) return [p1, p2];
10001
+ if (a < 1e-12) t = clamp01(f / e);
10002
+ else {
10003
+ const c = dot(d1, r);
10004
+ if (e < 1e-12) s = clamp01(-c / a);
10005
+ else {
10006
+ const b = dot(d1, d2);
10007
+ const denom = a * e - b * b;
10008
+ if (denom > PARALLEL * a * e) s = clamp01((b * f - c * e) / denom);
10009
+ else {
10010
+ const s0 = clamp01(-c / a);
10011
+ const s1 = clamp01((b - c) / a);
10012
+ s = (s0 + s1) / 2;
10013
+ }
10014
+ t = (b * s + f) / e;
10015
+ if (t < 0) {
10016
+ t = 0;
10017
+ s = clamp01(-c / a);
10018
+ } else if (t > 1) {
10019
+ t = 1;
10020
+ s = clamp01((b - c) / a);
10021
+ }
10022
+ }
10023
+ }
10024
+ return [along(p1, d1, s), along(p2, d2, t)];
10025
+ };
10026
+ var toBox = (box, p) => {
10027
+ const d = sub2(p, box.c);
10028
+ const e = box.e;
10029
+ return [e[0] * d[0] + e[1] * d[1] + e[2] * d[2], e[4] * d[0] + e[5] * d[1] + e[6] * d[2], e[8] * d[0] + e[9] * d[1] + e[10] * d[2]];
10030
+ };
10031
+ var fromBox = (box, l) => {
10032
+ const e = box.e;
10033
+ return [box.c[0] + e[0] * l[0] + e[4] * l[1] + e[8] * l[2], box.c[1] + e[1] * l[0] + e[5] * l[1] + e[9] * l[2], box.c[2] + e[2] * l[0] + e[6] * l[1] + e[10] * l[2]];
10034
+ };
10035
+ var capsuleBox = (from, to, radius, box) => {
10036
+ let p = nearestOnSegment(from, to, box.c);
10037
+ let l = toBox(box, p);
10038
+ for (let round2 = 0; round2 < SEGMENT_BOX_ROUNDS; round2++) {
10039
+ const clamped = [Math.max(-box.half[0], Math.min(box.half[0], l[0])), Math.max(-box.half[1], Math.min(box.half[1], l[1])), Math.max(-box.half[2], Math.min(box.half[2], l[2]))];
10040
+ p = nearestOnSegment(from, to, fromBox(box, clamped));
10041
+ l = toBox(box, p);
10042
+ }
10043
+ const q = [Math.max(-box.half[0], Math.min(box.half[0], l[0])), Math.max(-box.half[1], Math.min(box.half[1], l[1])), Math.max(-box.half[2], Math.min(box.half[2], l[2]))];
10044
+ const gap = [l[0] - q[0], l[1] - q[1], l[2] - q[2]];
10045
+ const distance = Math.hypot(gap[0], gap[1], gap[2]);
10046
+ if (distance >= radius) return null;
10047
+ const e = box.e;
10048
+ if (distance > 1e-6) {
10049
+ const n = [gap[0] / distance, gap[1] / distance, gap[2] / distance];
10050
+ const normal = [e[0] * n[0] + e[4] * n[1] + e[8] * n[2], e[1] * n[0] + e[5] * n[1] + e[9] * n[2], e[2] * n[0] + e[6] * n[1] + e[10] * n[2]];
10051
+ return { point: fromBox(box, q), normal, depth: radius - distance };
10052
+ }
10053
+ let axis2 = 0;
10054
+ for (let k = 1; k < 3; k++) if (box.half[k] - Math.abs(l[k]) < box.half[axis2] - Math.abs(l[axis2])) axis2 = k;
10055
+ const sign = l[axis2] < 0 ? -1 : 1;
10056
+ return { point: p, normal: [sign * e[axis2 * 4], sign * e[axis2 * 4 + 1], sign * e[axis2 * 4 + 2]], depth: radius + box.half[axis2] - Math.abs(l[axis2]) };
10057
+ };
10058
+ function shapeContact(a, b) {
10059
+ if (a.kind === "capsule" && b.kind === "capsule") {
10060
+ const [pa, pb] = nearestOfSegments(a.from, a.to, b.from, b.to);
10061
+ const d = sub2(pa, pb);
10062
+ const distance = Math.hypot(d[0], d[1], d[2]);
10063
+ const reach = a.radius + b.radius;
10064
+ if (distance >= reach) return null;
10065
+ const normal = distance > 1e-6 ? [d[0] / distance, d[1] / distance, d[2] / distance] : [1, 0, 0];
10066
+ return { point: along(pb, normal, b.radius - (reach - distance) / 2), normal, depth: reach - distance };
10067
+ }
10068
+ if (a.kind === "capsule" && b.kind === "boxes") {
10069
+ let best = null;
10070
+ for (const box of b.boxes) {
10071
+ const hit = capsuleBox(a.from, a.to, a.radius, box);
10072
+ if (hit && (!best || hit.depth > best.depth)) best = hit;
10073
+ }
10074
+ return best;
10075
+ }
10076
+ if (a.kind === "boxes" && b.kind === "capsule") {
10077
+ const hit = shapeContact(b, a);
10078
+ return hit && { point: hit.point, normal: [-hit.normal[0], -hit.normal[1], -hit.normal[2]], depth: hit.depth };
10079
+ }
10080
+ return null;
10081
+ }
10082
+
9946
10083
  // src/pieces.ts
9947
10084
  var SLAM_MIN_SPEED = 2;
9948
10085
  var SLAM_BOUNCE = 0.2;
@@ -9951,6 +10088,8 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
9951
10088
  var MU_STATIC = 0.7;
9952
10089
  var MU_DYNAMIC = 0.6;
9953
10090
  var SLIP_SPEED = 0.02;
10091
+ var ROLLING_RESISTANCE = 0.015;
10092
+ var ROUND_LYING = Math.SQRT1_2;
9954
10093
  var SLEEP_AFTER = 0.5;
9955
10094
  var CALM_DRIFT = 0.01;
9956
10095
  var CALM_TURN = 0.05;
@@ -9971,6 +10110,13 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
9971
10110
  var SUPPORT_GAP2 = 0.02;
9972
10111
  var WAKE_ABOVE_SPEED = 0.05;
9973
10112
  var WAKE_ABOVE_SPIN = 0.1;
10113
+ var SURFACE_CELL = 0.5;
10114
+ var SURFACE_CELLS_ACROSS = 24;
10115
+ var cellKey = (ix, iz) => (ix + 32768) * 65536 + (iz + 32768);
10116
+ var MAX_COLLISION_STEPS = 8;
10117
+ var MIN_ROUND_RADIUS = 5e-3;
10118
+ var BOUNCE_MIN_SPEED = 0.1;
10119
+ var KNOCK_FLAT = 0.5;
9974
10120
  var topFace = 1;
9975
10121
  var boxTopAt = (s, x, z) => {
9976
10122
  const e = s.e;
@@ -10003,8 +10149,11 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
10003
10149
  };
10004
10150
  var pairFriction = (a, b) => ({
10005
10151
  static: Math.sqrt((a?.static ?? MU_STATIC) * (b?.static ?? MU_STATIC)),
10006
- dynamic: Math.sqrt((a?.dynamic ?? MU_DYNAMIC) * (b?.dynamic ?? MU_DYNAMIC))
10152
+ dynamic: Math.sqrt((a?.dynamic ?? MU_DYNAMIC) * (b?.dynamic ?? MU_DYNAMIC)),
10153
+ // the softer of the two sets how much a round thing rolling on the other sinks in and is held back
10154
+ rolling: Math.max(a?.rolling ?? 0, b?.rolling ?? ROLLING_RESISTANCE)
10007
10155
  });
10156
+ var pairRestitution = (a, b) => Math.sqrt((a ?? SLAM_BOUNCE) * (b ?? SLAM_BOUNCE));
10008
10157
  var PieceSystem = class {
10009
10158
  constructor(THREE, o) {
10010
10159
  __publicField(this, "THREE", THREE);
@@ -10014,9 +10163,20 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
10014
10163
  __publicField(this, "p");
10015
10164
  __publicField(this, "q");
10016
10165
  __publicField(this, "dq");
10166
+ __publicField(this, "nextQ");
10017
10167
  __publicField(this, "m");
10018
10168
  __publicField(this, "ax");
10019
10169
  __publicField(this, "solids", []);
10170
+ /** The boxes other pieces land on: a piece's own parts when it has them (`partBoxes`), else its box. */
10171
+ __publicField(this, "surfaces", []);
10172
+ /** The surfaces by the cells of a grid on the ground (`SURFACE_CELL`) their bounding circle covers: what is under a point is looked for in its cell only. */
10173
+ __publicField(this, "surfaceGrid", /* @__PURE__ */ new Map());
10174
+ /** The surfaces wider than `SURFACE_CELLS_ACROSS` cells (a slab come down whole): looked at for every point. */
10175
+ __publicField(this, "wideSurfaces", []);
10176
+ /** Each piece's box of the step (`solids`), by its body. */
10177
+ __publicField(this, "solidOf", /* @__PURE__ */ new Map());
10178
+ /** Each piece's surfaces of the step (its parts' boxes, or its box), by its body. */
10179
+ __publicField(this, "surfacesOf", /* @__PURE__ */ new Map());
10020
10180
  __publicField(this, "supportTurn", 0);
10021
10181
  /** The surface normal and the friction of what the last `supportAt` found under the point (the ground and fixed tops are level: up, and no piece). */
10022
10182
  __publicField(this, "supportNormal", UP16);
@@ -10024,6 +10184,7 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
10024
10184
  this.p = new THREE.Vector3();
10025
10185
  this.q = new THREE.Quaternion();
10026
10186
  this.dq = new THREE.Quaternion();
10187
+ this.nextQ = new THREE.Quaternion();
10027
10188
  this.m = new THREE.Matrix4();
10028
10189
  this.ax = new THREE.Vector3();
10029
10190
  }
@@ -10074,10 +10235,33 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
10074
10235
  }
10075
10236
  remove(objectId) {
10076
10237
  const i = this.list.findIndex((b) => b.objectId === objectId);
10077
- if (i >= 0) this.list.splice(i, 1);
10238
+ if (i < 0) return;
10239
+ const [gone] = this.list.splice(i, 1);
10240
+ if (gone) this.forgetSolids(gone);
10078
10241
  }
10079
10242
  clear() {
10080
10243
  this.list.length = 0;
10244
+ this.solids = [];
10245
+ this.surfaces = [];
10246
+ this.solidOf.clear();
10247
+ this.surfacesOf.clear();
10248
+ this.surfaceGrid.clear();
10249
+ this.wideSurfaces.length = 0;
10250
+ }
10251
+ /** Drops a piece from the boxes of the step (`solids`, `surfaces` and their grid). */
10252
+ forgetSolids(body) {
10253
+ this.solidOf.delete(body);
10254
+ this.surfacesOf.delete(body);
10255
+ this.solids = this.solids.filter((s) => s.body !== body);
10256
+ this.surfaces = this.surfaces.filter((s) => s.body !== body);
10257
+ for (const [key, cell] of this.surfaceGrid) {
10258
+ const kept = cell.filter((s) => s.body !== body);
10259
+ if (kept.length === 0) this.surfaceGrid.delete(key);
10260
+ else if (kept.length !== cell.length) this.surfaceGrid.set(key, kept);
10261
+ }
10262
+ const wide2 = this.wideSurfaces.filter((s) => s.body !== body);
10263
+ this.wideSurfaces.length = 0;
10264
+ this.wideSurfaces.push(...wide2);
10081
10265
  }
10082
10266
  /** `clear` and the clock back to 0. */
10083
10267
  reset() {
@@ -10118,9 +10302,17 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
10118
10302
  mulInvInertiaWith(b, e, x, y, z) {
10119
10303
  const [hx, hy, hz2] = b.halfExtents;
10120
10304
  const k = 3 / b.mass;
10121
- const ix = k / (hy * hy + hz2 * hz2);
10122
- const iy = k / (hx * hx + hz2 * hz2);
10123
- const iz = k / (hx * hx + hy * hy);
10305
+ let ix = k / (hy * hy + hz2 * hz2);
10306
+ let iy = k / (hx * hx + hz2 * hz2);
10307
+ let iz = k / (hx * hx + hy * hy);
10308
+ const round2 = b.round;
10309
+ if (round2) {
10310
+ const about = 1 / (round2.inertia * b.mass * round2.radius * round2.radius);
10311
+ if (round2.kind === "sphere") ix = iy = iz = about;
10312
+ else if (round2.axis === 0) ix = about;
10313
+ else if (round2.axis === 1) iy = about;
10314
+ else iz = about;
10315
+ }
10124
10316
  const lx = (e[0] * x + e[1] * y + e[2] * z) * ix;
10125
10317
  const ly = (e[4] * x + e[5] * y + e[6] * z) * iy;
10126
10318
  const lz = (e[8] * x + e[9] * y + e[10] * z) * iz;
@@ -10175,12 +10367,106 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
10175
10367
  }
10176
10368
  }
10177
10369
  update(dt) {
10178
- this.time += dt;
10370
+ const { steps, near } = this.collisionSteps(dt);
10371
+ if (steps === 1) {
10372
+ this.time += dt;
10373
+ this.step(dt);
10374
+ return;
10375
+ }
10376
+ const start = this.time;
10377
+ this.time = start + dt;
10378
+ const far = (b) => !near.has(b);
10379
+ this.step(dt, { moves: far, meets: (a, b) => far(a) && far(b) });
10380
+ for (let i = 0; i < steps; i++) {
10381
+ this.time = start + dt * (i + 1) / steps;
10382
+ this.step(dt / steps, { moves: (b) => near.has(b), meets: (a, b) => near.has(a) || near.has(b) });
10383
+ }
10384
+ }
10385
+ /**
10386
+ * Steps of an update: one, or more while a round piece and a piece it could meet within the update close in fast enough to pass through each other between two (closing at
10387
+ * their two speeds they cover at most the round one's radius per step: two cans at 3.6 m/s close 12 cm in a frame, a can is 7 cm across; a plank thrown at a can still counts).
10388
+ * A round piece with nothing in reach takes one step, so its sweep against the world (the costly part) runs once; `near` holds the pieces of the pairs that need more.
10389
+ */
10390
+ collisionSteps(dt) {
10391
+ let need = 1;
10392
+ const near = /* @__PURE__ */ new Set();
10393
+ const p = this.p;
10394
+ const speedOf = (b) => b.held ? 0 : Math.hypot(b.velocity[0], b.velocity[1], b.velocity[2]);
10395
+ for (const b of this.list) {
10396
+ if (!b.round || b.held) continue;
10397
+ const radius = Math.max(MIN_ROUND_RADIUS, b.round.radius);
10398
+ const speed = b.sleeping ? 0 : speedOf(b);
10399
+ const c = this.centerOf(b, p);
10400
+ const cx = c.x, cy = c.y, cz = c.z;
10401
+ const rb = Math.hypot(b.halfExtents[0], b.halfExtents[1], b.halfExtents[2]);
10402
+ for (const o of this.list) {
10403
+ if (o === b || b.sleeping && o.sleeping) continue;
10404
+ const closing = speed + (o.sleeping ? 0 : speedOf(o));
10405
+ if (closing * dt < radius * 0.5) continue;
10406
+ const reach = closing * dt + rb + Math.hypot(o.halfExtents[0], o.halfExtents[1], o.halfExtents[2]);
10407
+ const oc = this.centerOf(o, p);
10408
+ if (Math.abs(oc.x - cx) > reach || Math.abs(oc.y - cy) > reach || Math.abs(oc.z - cz) > reach) continue;
10409
+ const pair = Math.ceil(closing * dt / radius);
10410
+ if (pair < 2) continue;
10411
+ need = Math.max(need, pair);
10412
+ near.add(b);
10413
+ near.add(o);
10414
+ }
10415
+ }
10416
+ return { steps: Math.max(1, Math.min(MAX_COLLISION_STEPS, need)), near };
10417
+ }
10418
+ /** A step of `dt`: the pieces `only.moves` takes move (all when absent) and the pairs `only.meets` takes meet, so each pair meets in one of the steps of an update. */
10419
+ step(dt, only) {
10179
10420
  this.solids = this.list.map((body) => {
10180
10421
  const c = this.centerOf(body, new this.THREE.Vector3());
10181
10422
  const h = body.halfExtents;
10182
10423
  return { body, c: [c.x, c.y, c.z], e: [...new this.THREE.Matrix4().makeRotationFromQuaternion(body.root.quaternion).elements], half: h, r: Math.hypot(h[0], h[1], h[2]) };
10183
10424
  });
10425
+ this.surfaces = this.solids.flatMap((whole) => {
10426
+ const parts = whole.body.partBoxes;
10427
+ if (!parts) return [whole];
10428
+ const e = whole.e;
10429
+ return parts.map(({ center, half }) => ({
10430
+ body: whole.body,
10431
+ c: [
10432
+ whole.c[0] + e[0] * center[0] + e[4] * center[1] + e[8] * center[2],
10433
+ whole.c[1] + e[1] * center[0] + e[5] * center[1] + e[9] * center[2],
10434
+ whole.c[2] + e[2] * center[0] + e[6] * center[1] + e[10] * center[2]
10435
+ ],
10436
+ e,
10437
+ half,
10438
+ r: Math.hypot(half[0], half[1], half[2])
10439
+ }));
10440
+ });
10441
+ this.solidOf.clear();
10442
+ for (const one of this.solids) this.solidOf.set(one.body, one);
10443
+ this.surfacesOf.clear();
10444
+ for (const one of this.surfaces) {
10445
+ const list = this.surfacesOf.get(one.body);
10446
+ if (list) list.push(one);
10447
+ else this.surfacesOf.set(one.body, [one]);
10448
+ }
10449
+ this.surfaceGrid.clear();
10450
+ this.wideSurfaces.length = 0;
10451
+ for (const one of this.surfaces) {
10452
+ const x0 = Math.floor((one.c[0] - one.r) / SURFACE_CELL);
10453
+ const x1 = Math.floor((one.c[0] + one.r) / SURFACE_CELL);
10454
+ const z0 = Math.floor((one.c[2] - one.r) / SURFACE_CELL);
10455
+ const z1 = Math.floor((one.c[2] + one.r) / SURFACE_CELL);
10456
+ if (x1 - x0 > SURFACE_CELLS_ACROSS || z1 - z0 > SURFACE_CELLS_ACROSS) {
10457
+ this.wideSurfaces.push(one);
10458
+ continue;
10459
+ }
10460
+ for (let ix = x0; ix <= x1; ix++) {
10461
+ for (let iz = z0; iz <= z1; iz++) {
10462
+ const key = cellKey(ix, iz);
10463
+ const cell = this.surfaceGrid.get(key);
10464
+ if (cell) cell.push(one);
10465
+ else this.surfaceGrid.set(key, [one]);
10466
+ }
10467
+ }
10468
+ }
10469
+ if (this.wideSurfaces.length > 0) for (const cell of this.surfaceGrid.values()) cell.push(...this.wideSurfaces);
10184
10470
  this.wakeUnsupported();
10185
10471
  for (const b of this.list) {
10186
10472
  if (b.held) {
@@ -10191,14 +10477,14 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
10191
10477
  b.calmAt = null;
10192
10478
  continue;
10193
10479
  }
10194
- if (b.sleeping) continue;
10480
+ if (b.sleeping || only && !only.moves(b)) continue;
10195
10481
  this.integrate(b, dt);
10196
10482
  if (b.sleeping) continue;
10197
10483
  const v = b.velocity;
10198
10484
  const w = b.angularVelocity;
10199
10485
  if (Math.hypot(v[0], v[1], v[2]) > WAKE_ABOVE_SPEED || Math.hypot(w[0], w[1], w[2]) > WAKE_ABOVE_SPIN) this.wakeAbove(b);
10200
10486
  }
10201
- this.separate(dt);
10487
+ this.collide(dt, only?.meets);
10202
10488
  }
10203
10489
  /** A few sleeping pieces each update (`SUPPORT_CHECKS`, in turn) look under them again: one whose table broke, or whose shelf fell over, falls. */
10204
10490
  wakeUnsupported() {
@@ -10227,11 +10513,15 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
10227
10513
  }
10228
10514
  return false;
10229
10515
  }
10516
+ /** The surfaces whose cell holds `(x, z)`, the wide ones (`wideSurfaces`) among them. */
10517
+ surfacesAt(x, z) {
10518
+ return this.surfaceGrid.get(cellKey(Math.floor(x / SURFACE_CELL), Math.floor(z / SURFACE_CELL))) ?? this.wideSurfaces;
10519
+ }
10230
10520
  /** The highest top of a piece (other than `self`) under `(x, z)` that a point at height `y` stands on (at most `step` above it), -Infinity when none; the boxes of the last update. */
10231
10521
  topAt(x, z, y, step, self) {
10232
10522
  let top = -Infinity;
10233
- for (const s of this.solids) {
10234
- if (s.body.objectId === self || s.body.held || Math.abs(x - s.c[0]) > s.r || Math.abs(z - s.c[2]) > s.r) continue;
10523
+ for (const s of this.surfacesAt(x, z)) {
10524
+ if (s.body.objectId === self || s.body.held && !s.body.carrying || Math.abs(x - s.c[0]) > s.r || Math.abs(z - s.c[2]) > s.r) continue;
10235
10525
  const t = boxTopAt(s, x, z);
10236
10526
  if (t > top && t <= y + step) top = t;
10237
10527
  }
@@ -10239,25 +10529,50 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
10239
10529
  }
10240
10530
  /** What lay asleep on `b` (a box over its top) wakes at once when `b` moves: a can on a table that goes over goes with it. */
10241
10531
  wakeAbove(b) {
10242
- const below = this.solids.find((s) => s.body === b);
10532
+ const below = this.solidOf.get(b);
10243
10533
  if (!below) return;
10244
10534
  const top = below.c[1] + below.half[0] * Math.abs(below.e[1]) + below.half[1] * Math.abs(below.e[5]) + below.half[2] * Math.abs(below.e[9]);
10245
- for (const s of this.solids) {
10246
- const o = s.body;
10247
- if (!o.sleeping || o.held || o === b) continue;
10248
- if (s.c[1] < below.c[1] || s.c[1] - s.r > top + STEP || Math.hypot(s.c[0] - below.c[0], s.c[2] - below.c[2]) > s.r + below.r) continue;
10535
+ const x0 = Math.floor((below.c[0] - below.r) / SURFACE_CELL);
10536
+ const x1 = Math.floor((below.c[0] + below.r) / SURFACE_CELL);
10537
+ const z0 = Math.floor((below.c[2] - below.r) / SURFACE_CELL);
10538
+ const z1 = Math.floor((below.c[2] + below.r) / SURFACE_CELL);
10539
+ const wide2 = x1 - x0 > SURFACE_CELLS_ACROSS || z1 - z0 > SURFACE_CELLS_ACROSS;
10540
+ const look = (part) => {
10541
+ const o = part.body;
10542
+ const s = this.solidOf.get(o);
10543
+ if (!s || !o.sleeping || o.held || o === b) return;
10544
+ if (s.c[1] < below.c[1] || s.c[1] - s.r > top + STEP || Math.hypot(s.c[0] - below.c[0], s.c[2] - below.c[2]) > s.r + below.r) return;
10545
+ if (boxTopAt(below, s.c[0], s.c[2]) === -Infinity && !this.restsOn(o, b, true)) return;
10249
10546
  o.sleeping = false;
10250
10547
  o.still = 0;
10251
10548
  o.calmAt = null;
10549
+ };
10550
+ if (wide2) for (const s of this.solids) look(s);
10551
+ else for (let ix = x0; ix <= x1; ix++) for (let iz = z0; iz <= z1; iz++) for (const part of this.surfaceGrid.get(cellKey(ix, iz)) ?? []) look(part);
10552
+ }
10553
+ /**
10554
+ * Whether `o` rests on a top of `below` (its parts, or its box): a corner of `o` (its contacts or its box) is over that top and within `STEP` of it. With `lowest`, only its
10555
+ * lowest corners count (within `STEP` of its lowest): a can rolling by another is beside it, not on it; without, a board leaning on a seat by its high end rests on the seat.
10556
+ */
10557
+ restsOn(o, below, lowest) {
10558
+ const c = this.centerOf(o, this.p);
10559
+ const e = this.m.makeRotationFromQuaternion(o.root.quaternion).elements;
10560
+ const points = this.samples(o, false).map(([sx, sy, sz]) => [c.x + e[0] * sx + e[4] * sy + e[8] * sz, c.y + e[1] * sx + e[5] * sy + e[9] * sz, c.z + e[2] * sx + e[6] * sy + e[10] * sz]);
10561
+ let low = Infinity;
10562
+ for (const p of points) low = Math.min(low, p[1]);
10563
+ for (const [x, y, z] of points) {
10564
+ if (lowest && y > low + STEP) continue;
10565
+ for (const s of this.surfacesAt(x, z)) if (s.body === below && Math.abs(y - boxTopAt(s, x, z)) <= STEP) return true;
10252
10566
  }
10567
+ return false;
10253
10568
  }
10254
10569
  /** Where a corner of `self` at `(x, y, z)` lands: the ground, the top of another piece or of something fixed under it. */
10255
10570
  supportAt(self, x, y, z, step) {
10256
10571
  let top = this.o.groundAt(x, z);
10257
10572
  let on = null;
10258
10573
  let face = 1;
10259
- for (const s of this.solids) {
10260
- if (s.body === self || s.body.held || Math.abs(x - s.c[0]) > s.r || Math.abs(z - s.c[2]) > s.r) continue;
10574
+ for (const s of this.surfacesAt(x, z)) {
10575
+ if (s.body === self || s.body.held && !s.body.carrying || Math.abs(x - s.c[0]) > s.r || Math.abs(z - s.c[2]) > s.r) continue;
10261
10576
  const t = boxTopAt(s, x, z);
10262
10577
  if (t > top && t <= y + step) {
10263
10578
  top = t;
@@ -10282,9 +10597,10 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
10282
10597
  const into = -(v[0] * n[0] + v[1] * n[1] + v[2] * n[2]);
10283
10598
  if (into <= 0) return;
10284
10599
  const k = Math.min(1, hit.distance / travel);
10600
+ const bounce2 = pairRestitution(b.restitution, hit.restitution);
10285
10601
  for (let i = 0; i < 3; i++) {
10286
10602
  pos[i] = start[i] + (pos[i] - start[i]) * k;
10287
- v[i] += (1 + SLAM_BOUNCE) * into * n[i];
10603
+ v[i] += (1 + bounce2) * into * n[i];
10288
10604
  }
10289
10605
  const w = b.angularVelocity;
10290
10606
  w[0] *= 0.5;
@@ -10323,9 +10639,16 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
10323
10639
  gLow = Math.min(gLow, g);
10324
10640
  gHigh = Math.max(gHigh, g);
10325
10641
  }
10326
- const local2 = gHigh - gLow > STEP ? this.samples(b, true) : corners;
10327
- const prev = local2.map(() => [0, 0, 0]);
10642
+ let local2 = b.round ? this.roundSamples(b, q) : gHigh - gLow > STEP ? this.samples(b, true) : corners;
10643
+ let prev = local2.map(() => [0, 0, 0]);
10328
10644
  for (let s = 0; s < steps; s++) {
10645
+ if (b.round) {
10646
+ const wl0 = Math.hypot(w[0], w[1], w[2]);
10647
+ const next = this.nextQ.copy(q);
10648
+ if (wl0 > 1e-6) next.premultiply(this.dq.setFromAxisAngle(this.ax.set(w[0] / wl0, w[1] / wl0, w[2] / wl0), wl0 * h)).normalize();
10649
+ local2 = this.roundSamples(b, next);
10650
+ if (prev.length !== local2.length) prev = local2.map(() => [0, 0, 0]);
10651
+ }
10329
10652
  this.m.makeRotationFromQuaternion(q);
10330
10653
  const e0 = this.m.elements;
10331
10654
  for (let i = 0; i < local2.length; i++) {
@@ -10343,7 +10666,7 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
10343
10666
  this.dq.setFromAxisAngle(this.ax.set(w[0] / wl, w[1] / wl, w[2] / wl), wl * h);
10344
10667
  q.premultiply(this.dq).normalize();
10345
10668
  }
10346
- const damp = Math.exp(-0.15 * h);
10669
+ const damp = b.round ? 1 : Math.exp(-0.15 * h);
10347
10670
  w[0] *= damp;
10348
10671
  w[1] *= damp;
10349
10672
  w[2] *= damp;
@@ -10411,6 +10734,12 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
10411
10734
  }
10412
10735
  }
10413
10736
  if (lowest < Infinity) b.floor = lowest;
10737
+ if (b.round && ns.length > 0) {
10738
+ const sum = [0, 0, 0];
10739
+ for (const one of ns) for (let k = 0; k < 3; k++) sum[k] += one[k];
10740
+ const len = Math.hypot(sum[0], sum[1], sum[2]);
10741
+ b.surfaceNormal = len > 1e-6 ? [sum[0] / len, sum[1] / len, sum[2] / len] : UP16;
10742
+ } else if (b.round && rs.length === 0) b.surfaceNormal = UP16;
10414
10743
  if (side) {
10415
10744
  pos[0] -= side.dir[0] * side.back;
10416
10745
  pos[2] -= side.dir[1] * side.back;
@@ -10439,14 +10768,15 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
10439
10768
  landPoint = [lx, pos[1] - Math.max(...rs.map((r) => -r[1])), lz];
10440
10769
  }
10441
10770
  const pointV = (r) => [v[0] + w[1] * r[2] - w[2] * r[1], v[1] + w[2] * r[0] - w[0] * r[2], v[2] + w[0] * r[1] - w[1] * r[0]];
10442
- const dot = (a, c2) => a[0] * c2[0] + a[1] * c2[1] + a[2] * c2[2];
10771
+ const dot2 = (a, c2) => a[0] * c2[0] + a[1] * c2[1] + a[2] * c2[2];
10443
10772
  const goal = rs.map((r, k) => {
10444
- const vn = dot(pointV(r), ns[k]);
10773
+ const vn = dot2(pointV(r), ns[k]);
10445
10774
  return vn < 0 ? -restitution * vn : 0;
10446
10775
  });
10447
10776
  const slipping = rs.map((r, k) => {
10448
10777
  const pv = pointV(r);
10449
- const vn = dot(pv, ns[k]);
10778
+ pv[1] += this.o.gravity * h;
10779
+ const vn = dot2(pv, ns[k]);
10450
10780
  return Math.hypot(pv[0] - vn * ns[k][0], pv[1] - vn * ns[k][1], pv[2] - vn * ns[k][2]) > SLIP_SPEED;
10451
10781
  });
10452
10782
  const vx0 = v[0];
@@ -10477,13 +10807,13 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
10477
10807
  for (let k = 0; k < rs.length; k++) {
10478
10808
  const r = rs[k];
10479
10809
  const n = ns[k];
10480
- const vn = dot(pointV(r), n);
10810
+ const vn = dot2(pointV(r), n);
10481
10811
  const total = Math.max(0, accN[k] + (goal[k] - vn) / reach(r, n));
10482
10812
  const j = total - accN[k];
10483
10813
  accN[k] = total;
10484
10814
  if (j !== 0) push(r, [n[0] * j, n[1] * j, n[2] * j]);
10485
10815
  const pv = pointV(r);
10486
- const pn = dot(pv, n);
10816
+ const pn = dot2(pv, n);
10487
10817
  const vt = [pv[0] - pn * n[0], pv[1] - pn * n[1], pv[2] - pn * n[2]];
10488
10818
  const speed = Math.hypot(vt[0], vt[1], vt[2]);
10489
10819
  const f = [accT[k][0], accT[k][1], accT[k][2]];
@@ -10528,7 +10858,7 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
10528
10858
  const height = -low;
10529
10859
  const wx = x1 - x0;
10530
10860
  const wz = z1 - z0;
10531
- unstable = Math.min(wx, wz) < NARROW * height || x0 > 0 || x1 < 0 || z0 > 0 || z1 < 0;
10861
+ unstable = !b.round && (Math.min(wx, wz) < NARROW * height || x0 > 0 || x1 < 0 || z0 > 0 || z1 < 0);
10532
10862
  if (b.tipping) {
10533
10863
  b.tipping.seconds -= h;
10534
10864
  const [hx, hy, hz2] = b.halfExtents;
@@ -10547,13 +10877,19 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
10547
10877
  if (wx <= wz) w[2] -= dirX * k;
10548
10878
  else w[0] += dirZ * k;
10549
10879
  }
10550
- const rd = Math.exp((rs.length >= 3 ? -3 : -1.5) * h);
10551
- w[0] *= rd;
10552
- w[1] *= rd;
10553
- w[2] *= rd;
10554
- const fd = Math.exp(-0.3 * h);
10555
- v[0] *= fd;
10556
- v[2] *= fd;
10880
+ if (b.round) {
10881
+ let rolling = 0;
10882
+ for (const mu of mus) rolling = Math.max(rolling, mu.rolling ?? ROLLING_RESISTANCE);
10883
+ this.rollingResistance(b, q, w, h, rolling);
10884
+ } else {
10885
+ const rd = Math.exp((rs.length >= 3 ? -3 : -1.5) * h);
10886
+ w[0] *= rd;
10887
+ w[1] *= rd;
10888
+ w[2] *= rd;
10889
+ const fd = Math.exp(-0.3 * h);
10890
+ v[0] *= fd;
10891
+ v[2] *= fd;
10892
+ }
10557
10893
  }
10558
10894
  if (this.o.sweep && !b.held) this.sweepOn(b, start, pos);
10559
10895
  b.root.quaternion.copy(q);
@@ -10589,63 +10925,241 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
10589
10925
  }
10590
10926
  /** Whether the centre `c` of `upper` is over the top of `lower`'s box (as it was at the start of the update). */
10591
10927
  onTopOf(upper, lower, c) {
10592
- const s = this.solids.find((one) => one.body === lower);
10928
+ const s = this.solidOf.get(lower);
10593
10929
  if (!s) return false;
10594
10930
  const top = boxTopAt(s, c.x, c.z);
10595
10931
  return top > -Infinity && c.y >= top - 0.01;
10596
10932
  }
10933
+ /**
10934
+ * The points a round piece touches the ground by as it is turned now (`q`): its rims (`contacts`), which hold it standing on an end, and the exact lowest point of each
10935
+ * rim (of the ball), so lying on its side it rests on a line and rolls smoothly instead of over the corners of a polygon.
10936
+ */
10937
+ roundSamples(b, q) {
10938
+ const round2 = b.round;
10939
+ const rims = b.contacts ?? [];
10940
+ if (!round2) return rims;
10941
+ const e = this.m.makeRotationFromQuaternion(q).elements;
10942
+ const n = b.surfaceNormal ?? UP16;
10943
+ const down = [-(e[0] * n[0] + e[1] * n[1] + e[2] * n[2]), -(e[4] * n[0] + e[5] * n[1] + e[6] * n[2]), -(e[8] * n[0] + e[9] * n[1] + e[10] * n[2])];
10944
+ if (round2.kind === "sphere") return [...rims, [down[0] * round2.radius, down[1] * round2.radius, down[2] * round2.radius]];
10945
+ const k = round2.axis;
10946
+ const across = [down[0], down[1], down[2]];
10947
+ across[k] = 0;
10948
+ const len = Math.hypot(across[0], across[1], across[2]);
10949
+ if (len < 1e-3) return rims;
10950
+ const lowest = (at3, radius) => {
10951
+ const p = [across[0] / len * radius, across[1] / len * radius, across[2] / len * radius];
10952
+ p[k] = at3;
10953
+ return p;
10954
+ };
10955
+ const half = b.halfExtents[k];
10956
+ const low = (round2.profile ?? [[-half, round2.radius], [half, round2.radius]]).map(([at3, radius]) => lowest(at3, radius));
10957
+ return len > ROUND_LYING ? low : [...rims, ...low];
10958
+ }
10959
+ /**
10960
+ * Slows the spin of a round piece on the ground by its rolling resistance: a torque C_rr N r about the axis it rolls on (N = m g n_y on a surface of normal n), so with
10961
+ * I = k m r^2 the spin loses C_rr g n_y / (k r) per second, and down a slope of angle t it rolls at g (sin t - C_rr cos t) / (1 + k). Standing on its rim, a can's spin
10962
+ * about the rest dies down; lying, it keeps turning about the line it touches by (a tapered bottle rounds its narrow end).
10963
+ */
10964
+ rollingResistance(b, q, w, h, rolling) {
10965
+ const round2 = b.round;
10966
+ if (!round2) return;
10967
+ const e = this.m.makeRotationFromQuaternion(q).elements;
10968
+ const cylinder = round2.kind === "cylinder";
10969
+ const a = cylinder ? [e[round2.axis * 4], e[round2.axis * 4 + 1], e[round2.axis * 4 + 2]] : [0, 0, 0];
10970
+ const along2 = cylinder ? w[0] * a[0] + w[1] * a[1] + w[2] * a[2] : 0;
10971
+ const roll = cylinder ? [a[0] * along2, a[1] * along2, a[2] * along2] : [w[0], w[1], w[2]];
10972
+ const rest = [w[0] - roll[0], w[1] - roll[1], w[2] - roll[2]];
10973
+ const spin = Math.hypot(roll[0], roll[1], roll[2]);
10974
+ const upright = b.surfaceNormal?.[1] ?? 1;
10975
+ const slow = spin > 0 ? Math.max(0, spin - rolling * this.o.gravity * upright * h / (round2.inertia * round2.radius)) / spin : 0;
10976
+ const lying = cylinder && Math.abs(a[1]) < ROUND_LYING;
10977
+ const damp = lying ? 1 : Math.exp(-3 * h);
10978
+ for (let i = 0; i < 3; i++) w[i] = roll[i] * slow + rest[i] * damp;
10979
+ }
10597
10980
  /** Half the height of the box of a piece as it is turned now. */
10598
10981
  halfHeight(b) {
10599
10982
  const e = this.m.makeRotationFromQuaternion(b.root.quaternion).elements;
10600
10983
  return Math.abs(e[1]) * b.halfExtents[0] + Math.abs(e[5]) * b.halfExtents[1] + Math.abs(e[9]) * b.halfExtents[2];
10601
10984
  }
10602
- /** Push overlapping pieces apart (horizontal bounding circles), gently, so they do not interpenetrate forever. */
10603
- separate(dt) {
10985
+ /**
10986
+ * Pieces against each other. Candidates by sweep and prune along x on their bounding spheres (sorted once per step: fifty cans cost a sort and a handful of pairs, not
10987
+ * 1225); a pair with a round piece in it meets by its shapes (`shapeContact`) and exchanges an impulse, two boxes are only pushed apart (`separatePair`).
10988
+ */
10989
+ collide(dt, meets) {
10604
10990
  const n = this.list.length;
10605
10991
  if (n < 2) return;
10606
- const maxMove = 1.5 * dt;
10607
- const ca = new this.THREE.Vector3();
10608
- const cb = new this.THREE.Vector3();
10609
- for (let i = 0; i < n; i++) {
10610
- const a = this.list[i];
10611
- for (let j = i + 1; j < n; j++) {
10992
+ const centers = this.list.map((b) => {
10993
+ const c = this.centerOf(b, this.p);
10994
+ return [c.x, c.y, c.z];
10995
+ });
10996
+ const radii = this.list.map((b) => Math.hypot(b.halfExtents[0], b.halfExtents[1], b.halfExtents[2]));
10997
+ const order = this.list.map((_, i) => i).sort((i, j) => centers[i][0] - radii[i] - (centers[j][0] - radii[j]));
10998
+ for (let oi = 0; oi < n; oi++) {
10999
+ const i = order[oi];
11000
+ const reach = centers[i][0] + radii[i];
11001
+ for (let oj = oi + 1; oj < n; oj++) {
11002
+ const j = order[oj];
11003
+ if (centers[j][0] - radii[j] > reach) break;
11004
+ const a = this.list[i];
10612
11005
  const b = this.list[j];
10613
- const fixedA = a.held || a.sleeping;
10614
- const fixedB = b.held || b.sleeping;
10615
- if (fixedA && fixedB) continue;
10616
- const ra = Math.hypot(a.halfExtents[0], a.halfExtents[1], a.halfExtents[2]);
10617
- const rb = Math.hypot(b.halfExtents[0], b.halfExtents[1], b.halfExtents[2]);
10618
- this.centerOf(a, ca);
10619
- this.centerOf(b, cb);
10620
- if (Math.abs(ca.y - cb.y) > ra + rb) continue;
10621
- if (Math.abs(ca.y - cb.y) >= (this.halfHeight(a) + this.halfHeight(b)) * 0.9) continue;
10622
- if (this.onTopOf(b, a, cb) || this.onTopOf(a, b, ca)) continue;
10623
- const rh = (Math.max(a.halfExtents[0], a.halfExtents[2]) + Math.max(b.halfExtents[0], b.halfExtents[2])) * 0.8;
10624
- let dx = cb.x - ca.x;
10625
- let dz = cb.z - ca.z;
10626
- let d = Math.hypot(dx, dz);
10627
- if (d >= rh) continue;
10628
- if (d < 1e-5) {
10629
- dx = 1;
10630
- dz = 0;
10631
- d = 1;
10632
- }
10633
- const push = Math.min(maxMove, (rh - d) * 0.5);
10634
- const wa = fixedA ? 0 : fixedB ? 1 : b.mass / (a.mass + b.mass);
10635
- const wb = fixedB ? 0 : fixedA ? 1 : a.mass / (a.mass + b.mass);
10636
- const ux = dx / (d || 1);
10637
- const uz = dz / (d || 1);
10638
- if (!fixedA) {
10639
- a.root.position.x -= ux * push * 2 * wa;
10640
- a.root.position.z -= uz * push * 2 * wa;
10641
- }
10642
- if (!fixedB) {
10643
- b.root.position.x += ux * push * 2 * wb;
10644
- b.root.position.z += uz * push * 2 * wb;
10645
- }
11006
+ if ((a.held || a.sleeping) && (b.held || b.sleeping)) continue;
11007
+ if (meets && !meets(a, b)) continue;
11008
+ const r = radii[i] + radii[j];
11009
+ const ca = centers[i];
11010
+ const cb = centers[j];
11011
+ if (Math.abs(ca[1] - cb[1]) > r || Math.abs(ca[2] - cb[2]) > r) continue;
11012
+ if (!a.round && !b.round && Math.abs(ca[1] - cb[1]) >= (this.halfHeight(a) + this.halfHeight(b)) * 0.9) continue;
11013
+ if (this.onTopOf(b, a, new this.THREE.Vector3(...cb)) || this.onTopOf(a, b, new this.THREE.Vector3(...ca))) continue;
11014
+ if (a.round || b.round) this.knock(a, b, ca, cb);
11015
+ else if (this.partsOverlap(a, b) && !this.restsOn(a, b, false) && !this.restsOn(b, a, false)) this.separatePair(a, b, ca, cb, dt);
10646
11016
  }
10647
11017
  }
10648
11018
  }
11019
+ /** The shape a piece meets others by (`ContactShape`), as it stands now: a round one a capsule round its axis, any other the boxes of its parts or its box. */
11020
+ contactShape(b, c) {
11021
+ const e = [...this.m.makeRotationFromQuaternion(b.root.quaternion).elements];
11022
+ const round2 = b.round;
11023
+ if (round2) {
11024
+ if (round2.kind === "sphere") return { kind: "capsule", from: c, to: c, radius: round2.radius };
11025
+ const reach = Math.max(0, b.halfExtents[round2.axis] - round2.radius);
11026
+ const k = round2.axis * 4;
11027
+ const d = [e[k] * reach, e[k + 1] * reach, e[k + 2] * reach];
11028
+ return { kind: "capsule", from: [c[0] - d[0], c[1] - d[1], c[2] - d[2]], to: [c[0] + d[0], c[1] + d[1], c[2] + d[2]], radius: round2.radius };
11029
+ }
11030
+ const parts = b.partBoxes ?? [{ center: [0, 0, 0], half: b.halfExtents }];
11031
+ return {
11032
+ kind: "boxes",
11033
+ boxes: parts.map(({ center, half }) => ({
11034
+ c: [c[0] + e[0] * center[0] + e[4] * center[1] + e[8] * center[2], c[1] + e[1] * center[0] + e[5] * center[1] + e[9] * center[2], c[2] + e[2] * center[0] + e[6] * center[1] + e[10] * center[2]],
11035
+ e,
11036
+ half
11037
+ }))
11038
+ };
11039
+ }
11040
+ /**
11041
+ * Two pieces that met, one of them round: they are put apart along the normal (by their inverse masses) and, closing in, exchange an impulse
11042
+ * j = -(1 + e) v_n / (1/m_a + 1/m_b + the turning of each), with the restitution e of their two materials, and the friction of their surfaces across it. The impulses are
11043
+ * equal and opposite, so the momentum of the pair is kept. A held piece is not moved (the hand holds it); a sleeping one wakes when it is knocked.
11044
+ */
11045
+ knock(a, b, ca, cb) {
11046
+ const hit = shapeContact(this.contactShape(a, ca), this.contactShape(b, cb));
11047
+ if (!hit) return;
11048
+ const n = hit.normal;
11049
+ if (Math.abs(n[1]) > SLAM_FLOOR_NORMAL) return;
11050
+ const ra = [hit.point[0] - ca[0], hit.point[1] - ca[1], hit.point[2] - ca[2]];
11051
+ const rb = [hit.point[0] - cb[0], hit.point[1] - cb[1], hit.point[2] - cb[2]];
11052
+ const pointV = (body, r) => {
11053
+ const v2 = body.velocity;
11054
+ const w = body.angularVelocity;
11055
+ return [v2[0] + w[1] * r[2] - w[2] * r[1], v2[1] + w[2] * r[0] - w[0] * r[2], v2[2] + w[0] * r[1] - w[1] * r[0]];
11056
+ };
11057
+ const relative = () => {
11058
+ const va = pointV(a, ra);
11059
+ const vb = pointV(b, rb);
11060
+ return [va[0] - vb[0], va[1] - vb[1], va[2] - vb[2]];
11061
+ };
11062
+ const vn0 = relative();
11063
+ const closing = vn0[0] * n[0] + vn0[1] * n[1] + vn0[2] * n[2];
11064
+ const wake = (body) => {
11065
+ body.sleeping = false;
11066
+ body.still = 0;
11067
+ body.calmAt = null;
11068
+ };
11069
+ if (closing < -WAKE_ABOVE_SPEED) {
11070
+ if (a.sleeping) wake(a);
11071
+ if (b.sleeping) wake(b);
11072
+ }
11073
+ const ima = a.held || a.sleeping ? 0 : 1 / a.mass;
11074
+ const imb = b.held || b.sleeping ? 0 : 1 / b.mass;
11075
+ if (ima + imb === 0) return;
11076
+ const ea = [...this.m.makeRotationFromQuaternion(a.root.quaternion).elements];
11077
+ const eb = [...this.m.makeRotationFromQuaternion(b.root.quaternion).elements];
11078
+ const flat = Math.hypot(n[0], n[2]);
11079
+ const out = flat > KNOCK_FLAT ? [n[0] / flat, 0, n[2] / flat] : n;
11080
+ const depth = Math.max(0, hit.depth - SLOP) / (flat > KNOCK_FLAT ? flat : 1);
11081
+ for (const [body, share, sign] of [[a, ima, 1], [b, imb, -1]]) {
11082
+ if (share === 0) continue;
11083
+ const move = depth * share * sign / (ima + imb);
11084
+ body.root.position.x += out[0] * move;
11085
+ body.root.position.y += out[1] * move;
11086
+ body.root.position.z += out[2] * move;
11087
+ }
11088
+ if (closing >= 0) return;
11089
+ const turning = (body, e, r, d) => {
11090
+ const t2 = this.mulInvInertiaWith(body, e, r[1] * d[2] - r[2] * d[1], r[2] * d[0] - r[0] * d[2], r[0] * d[1] - r[1] * d[0]);
11091
+ return (t2[1] * r[2] - t2[2] * r[1]) * d[0] + (t2[2] * r[0] - t2[0] * r[2]) * d[1] + (t2[0] * r[1] - t2[1] * r[0]) * d[2];
11092
+ };
11093
+ const resist = (d) => ima + imb + (ima > 0 ? turning(a, ea, ra, d) : 0) + (imb > 0 ? turning(b, eb, rb, d) : 0);
11094
+ const give = (j2) => {
11095
+ if (ima > 0) {
11096
+ for (let i = 0; i < 3; i++) a.velocity[i] += j2[i] * ima;
11097
+ const dw = this.mulInvInertiaWith(a, ea, ra[1] * j2[2] - ra[2] * j2[1], ra[2] * j2[0] - ra[0] * j2[2], ra[0] * j2[1] - ra[1] * j2[0]);
11098
+ for (let i = 0; i < 3; i++) a.angularVelocity[i] += dw[i];
11099
+ }
11100
+ if (imb > 0) {
11101
+ for (let i = 0; i < 3; i++) b.velocity[i] -= j2[i] * imb;
11102
+ const dw = this.mulInvInertiaWith(b, eb, rb[1] * j2[2] - rb[2] * j2[1], rb[2] * j2[0] - rb[0] * j2[2], rb[0] * j2[1] - rb[1] * j2[0]);
11103
+ for (let i = 0; i < 3; i++) b.angularVelocity[i] -= dw[i];
11104
+ }
11105
+ };
11106
+ const bounce2 = -closing > BOUNCE_MIN_SPEED ? pairRestitution(a.restitution, b.restitution) : 0;
11107
+ const j = -(1 + bounce2) * closing / resist(n);
11108
+ give([n[0] * j, n[1] * j, n[2] * j]);
11109
+ const v = relative();
11110
+ const vn = v[0] * n[0] + v[1] * n[1] + v[2] * n[2];
11111
+ const vt = [v[0] - vn * n[0], v[1] - vn * n[1], v[2] - vn * n[2]];
11112
+ const slide = Math.hypot(vt[0], vt[1], vt[2]);
11113
+ if (slide < 1e-6) return;
11114
+ const t = [vt[0] / slide, vt[1] / slide, vt[2] / slide];
11115
+ const jt = Math.min(slide / resist(t), pairFriction(a.friction, b.friction ?? null).dynamic * j);
11116
+ give([-t[0] * jt, -t[1] * jt, -t[2] * jt]);
11117
+ if (-closing >= SLAM_MIN_SPEED && this.time - Math.max(a.lastHit, b.lastHit) > 0.15) {
11118
+ a.lastHit = b.lastHit = this.time;
11119
+ this.o.onKnock?.(a, b, hit.point, -closing);
11120
+ }
11121
+ }
11122
+ /** Whether a part of `a` and a part of `b` (their boxes of the step, as world-aligned boxes around them) overlap. */
11123
+ partsOverlap(a, b) {
11124
+ const extent = (s, k) => Math.abs(s.e[k]) * s.half[0] + Math.abs(s.e[k + 4]) * s.half[1] + Math.abs(s.e[k + 8]) * s.half[2];
11125
+ for (const pa of this.surfacesOf.get(a) ?? []) {
11126
+ for (const pb of this.surfacesOf.get(b) ?? []) {
11127
+ let apart = false;
11128
+ for (let k = 0; k < 3 && !apart; k++) apart = Math.abs(pa.c[k] - pb.c[k]) > extent(pa, k) + extent(pb, k);
11129
+ if (!apart) return true;
11130
+ }
11131
+ }
11132
+ return false;
11133
+ }
11134
+ /** Two boxes overlapping side by side (horizontal bounding circles): pushed apart, gently, so they do not interpenetrate forever. */
11135
+ separatePair(a, b, ca, cb, dt) {
11136
+ const fixedA = a.held || a.sleeping;
11137
+ const fixedB = b.held || b.sleeping;
11138
+ const maxMove = 1.5 * dt;
11139
+ const rh = (Math.max(a.halfExtents[0], a.halfExtents[2]) + Math.max(b.halfExtents[0], b.halfExtents[2])) * 0.8;
11140
+ let dx = cb[0] - ca[0];
11141
+ let dz = cb[2] - ca[2];
11142
+ let d = Math.hypot(dx, dz);
11143
+ if (d >= rh) return;
11144
+ if (d < 1e-5) {
11145
+ dx = 1;
11146
+ dz = 0;
11147
+ d = 1;
11148
+ }
11149
+ const push = Math.min(maxMove, (rh - d) * 0.5);
11150
+ const wa = fixedA ? 0 : fixedB ? 1 : b.mass / (a.mass + b.mass);
11151
+ const wb = fixedB ? 0 : fixedA ? 1 : a.mass / (a.mass + b.mass);
11152
+ const ux = dx / (d || 1);
11153
+ const uz = dz / (d || 1);
11154
+ if (!fixedA) {
11155
+ a.root.position.x -= ux * push * 2 * wa;
11156
+ a.root.position.z -= uz * push * 2 * wa;
11157
+ }
11158
+ if (!fixedB) {
11159
+ b.root.position.x += ux * push * 2 * wb;
11160
+ b.root.position.z += uz * push * 2 * wb;
11161
+ }
11162
+ }
10649
11163
  };
10650
11164
 
10651
11165
  // src/rebar.ts
@@ -10868,6 +11382,17 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
10868
11382
  pileElasticGPa: 25,
10869
11383
  footingWidth: 0.6
10870
11384
  };
11385
+ var GROUND_LOSS_DEFAULTS = {
11386
+ footingDepth: 0.5,
11387
+ spread: 1,
11388
+ voidDepth: 0.05,
11389
+ maxSettlement: 0.05,
11390
+ crackDistortion: 1 / 300,
11391
+ damageDistortion: 1 / 150,
11392
+ distortionDamage: 0.3,
11393
+ bridgeSpanDepth: 10,
11394
+ beamRebarRatio: 4e-3
11395
+ };
10871
11396
  var WIND_DEFAULTS = {
10872
11397
  speed: 40,
10873
11398
  direction: [1, 0, 0],
@@ -12472,6 +12997,23 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
12472
12997
  return { spec, parts: meshesOf };
12473
12998
  }
12474
12999
 
13000
+ // src/friction.ts
13001
+ var SURFACE_BY_KEY = [
13002
+ [/rubber|tire|tyre/, { static: 1, dynamic: 0.8, rolling: 0.03, restitution: 0.8 }],
13003
+ [/foam|sponge|fabric|cloth|leather|textile|carpet/, { static: 0.6, dynamic: 0.5, rolling: 0.08, restitution: 0.2 }],
13004
+ [/concrete|brick|stone|masonry|cement|asphalt|plaster/, { static: 0.7, dynamic: 0.6, rolling: 0.012, restitution: 0.4 }],
13005
+ [/steel|iron|metal|alumin|copper|brass|tin/, { static: 0.6, dynamic: 0.4, rolling: 2e-3, restitution: 0.6 }],
13006
+ [/glass/, { static: 0.4, dynamic: 0.35, rolling: 2e-3, restitution: 0.7 }],
13007
+ [/ceramic|porcelain|tile/, { static: 0.5, dynamic: 0.4, rolling: 5e-3, restitution: 0.5 }],
13008
+ [/wood|mdf|plywood|board|cork/, { static: 0.4, dynamic: 0.3, rolling: 0.01, restitution: 0.5 }],
13009
+ [/plastic|polycarbonate|acrylic|nylon|pvc/, { static: 0.4, dynamic: 0.3, rolling: 0.01, restitution: 0.5 }],
13010
+ [/paper|cardboard|carton/, { static: 0.4, dynamic: 0.3, rolling: 0.02, restitution: 0.2 }]
13011
+ ];
13012
+ function surfaceOf(materialId, def) {
13013
+ const keys = [materialId, ...def?.tags ?? []].join(" ").toLowerCase();
13014
+ return SURFACE_BY_KEY.find(([key]) => key.test(keys))?.[1];
13015
+ }
13016
+
12475
13017
  // src/heat.ts
12476
13018
  var STOPS = [
12477
13019
  [450, 0],
@@ -13577,6 +14119,63 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
13577
14119
  var TIP_MIN_HEIGHT = 0.3;
13578
14120
  var TIP_NARROW = 0.3;
13579
14121
  var CONTACT_MESHES = 12;
14122
+ var PART_BOX_MESHES = 64;
14123
+ var ROUND_SAMPLES = 400;
14124
+ var ROUND_SIDES = 0.12;
14125
+ var ROUND_SLACK = 1.12;
14126
+ var RIM_POINTS = 12;
14127
+ var rimPoints = (round2, half) => {
14128
+ const out = [];
14129
+ const circle = (axis2, at3, radius) => {
14130
+ const [i, j] = axis2 === 0 ? [1, 2] : axis2 === 1 ? [0, 2] : [0, 1];
14131
+ for (let k = 0; k < RIM_POINTS; k++) {
14132
+ const a = k / RIM_POINTS * Math.PI * 2;
14133
+ const p = [0, 0, 0];
14134
+ p[axis2] = at3;
14135
+ p[i] = Math.cos(a) * radius;
14136
+ p[j] = Math.sin(a) * radius;
14137
+ out.push(p);
14138
+ }
14139
+ };
14140
+ if (round2.kind === "sphere") for (const axis2 of [0, 1, 2]) circle(axis2, 0, round2.radius);
14141
+ else {
14142
+ const ends = round2.profile ?? [];
14143
+ circle(round2.axis, -half[round2.axis], ends[0]?.[1] ?? round2.radius);
14144
+ circle(round2.axis, half[round2.axis], ends[ends.length - 1]?.[1] ?? round2.radius);
14145
+ }
14146
+ return out;
14147
+ };
14148
+ var PROFILE_RINGS = 8;
14149
+ var SHELL_CYLINDER = 1;
14150
+ var SOLID_CYLINDER = 0.5;
14151
+ var SHELL_SPHERE = 2 / 3;
14152
+ var SOLID_SPHERE = 0.4;
14153
+ var LIQUID_KG_PER_L = 1;
14154
+ var profileOf = (points, axis2, half, radius) => {
14155
+ const [i, j] = axis2 === 0 ? [1, 2] : axis2 === 1 ? [0, 2] : [0, 1];
14156
+ const widest = new Array(PROFILE_RINGS).fill(0);
14157
+ for (const p of points) {
14158
+ const ring2 = Math.min(PROFILE_RINGS - 1, Math.max(0, Math.floor((p[axis2] + half) / (2 * half) * PROFILE_RINGS)));
14159
+ widest[ring2] = Math.max(widest[ring2], Math.hypot(p[i], p[j]));
14160
+ }
14161
+ const rings = [];
14162
+ for (let k = 0; k < PROFILE_RINGS; k++) {
14163
+ if (widest[k] <= 0) continue;
14164
+ const at3 = k === 0 ? -half : k === PROFILE_RINGS - 1 ? half : -half + (k + 0.5) / PROFILE_RINGS * 2 * half;
14165
+ rings.push([at3, Math.min(radius, widest[k])]);
14166
+ }
14167
+ const hull = [];
14168
+ for (const ring2 of rings) {
14169
+ while (hull.length >= 2) {
14170
+ const [a0, r0] = hull[hull.length - 2];
14171
+ const [a1, r1] = hull[hull.length - 1];
14172
+ if ((r1 - r0) * (ring2[0] - a0) <= (ring2[1] - r0) * (a1 - a0)) hull.pop();
14173
+ else break;
14174
+ }
14175
+ hull.push(ring2);
14176
+ }
14177
+ return hull;
14178
+ };
13580
14179
  var BROKEN_GAP = 0.03;
13581
14180
  var BROKEN_SAMPLES = [[0.5, 0.5], [0.1, 0.1], [0.9, 0.1], [0.1, 0.9], [0.9, 0.9]];
13582
14181
  var UNCHECKED_KINDS = /* @__PURE__ */ new Set(["structure", "room", "ground"]);
@@ -13777,7 +14376,12 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
13777
14376
  scene: o.scene,
13778
14377
  onHardLanding: (p, point, speed) => this.hardLanding(p, point, speed),
13779
14378
  sweep: (p, from, to) => this.sweepPiece(p, from, to),
13780
- onSlam: (p, hit, speed) => this.slam(p, hit, speed)
14379
+ onSlam: (p, hit, speed) => this.slam(p, hit, speed),
14380
+ // two pieces knocked together: each sounds as its material does (a can on a can, a bottle on a table's leg)
14381
+ onKnock: (a, b, point, speed) => {
14382
+ this.landingSound(a.objectId, point, clamp6(speed / 10, 0.2, 1));
14383
+ this.landingSound(b.objectId, point, clamp6(speed / 10, 0.2, 1));
14384
+ }
13781
14385
  });
13782
14386
  this.unsubscribe = this.world.on("*", (ev) => {
13783
14387
  if (ev.type === "explode") this.coverWhenWentOff.set(ev, this.coverAround(ev));
@@ -13956,8 +14560,129 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
13956
14560
  const { half, center } = this.measure(b.root, this.meshesOf(b));
13957
14561
  const piece = this.pieceSys.create(objectId, b.root, half, center, options.mass ?? this.massOf(objectId), options.velocity);
13958
14562
  b.piece = piece;
14563
+ this.fitSurface(b, piece, options.inertia);
14564
+ this.fitPartBoxes(b, piece);
13959
14565
  return piece;
13960
14566
  }
14567
+ /**
14568
+ * What lands on or runs into a piece of several meshes meets its parts as drawn (`partBoxes`: a bench's slats, a table's top and legs), from the moment it is made a piece, not
14569
+ * the box around them all: a board laid on a bench rests on its seat, a can rolls under a table between its legs. Its own contacts with the ground are left as they were.
14570
+ */
14571
+ fitPartBoxes(b, body) {
14572
+ if (body.round) return;
14573
+ const contacts = body.contacts;
14574
+ this.setContacts(b, body, this.meshesOf(b).filter((mv) => this.visuals.shown(mv)));
14575
+ body.contacts = contacts;
14576
+ }
14577
+ /** What the piece's surface is (the friction of the material it stands on) and whether it is round (`round`: it rolls on rings of contacts). */
14578
+ fitSurface(b, body, inertia) {
14579
+ const box = new this.THREE.Box3();
14580
+ let low = Infinity;
14581
+ let material = null;
14582
+ for (const [partId, pv] of b.parts) {
14583
+ if (pv.gone !== "none") continue;
14584
+ for (const mv of pv.meshes) {
14585
+ if (!this.visuals.shown(mv)) continue;
14586
+ this.visuals.worldBox(mv, box);
14587
+ if (box.isEmpty() || box.min.y >= low - 5e-3) continue;
14588
+ low = box.min.y;
14589
+ material = this.world.part(b.id, partId)?.material ?? pv.material ?? null;
14590
+ }
14591
+ }
14592
+ const surface = material ? surfaceOf(material, this.world.materials.get(material)) : void 0;
14593
+ body.friction = surface && { static: surface.static, dynamic: surface.dynamic, rolling: surface.rolling };
14594
+ body.restitution = surface?.restitution;
14595
+ const wasRound = body.round !== void 0;
14596
+ if (inertia !== void 0) body.inertiaGiven = inertia;
14597
+ const round2 = this.roundOf(b, body);
14598
+ body.round = round2 ?? void 0;
14599
+ if (round2) {
14600
+ body.contacts = rimPoints(round2, body.halfExtents);
14601
+ body.partBoxes = void 0;
14602
+ } else if (wasRound) body.contacts = void 0;
14603
+ }
14604
+ /**
14605
+ * k of a round piece's moment of inertia about its axis (I = k m r^2), from where its mass is. A piece that is not hollow is a solid (k 1/2 for a cylinder, 2/5 for a ball).
14606
+ * A hollow one (`userData.hollow`) with nothing inside (no `destructionContains` liquid, no `destructionPowder`) is all wall, a thin shell (k 1, 2/3): an empty can. One with
14607
+ * contents weighs its walls as their area times their thickness (`destructionThickness`) times density, or, without a thickness, as what is left of its mass besides the liquid
14608
+ * (`LIQUID_KG_PER_L`), and the rest as a solid: a full 350 ml can comes to about 0.53 and rolls down a slope at g sin t / 1.53, an empty one at g sin t / 2.
14609
+ */
14610
+ inertiaOf(b, body, kind, axis2, radius) {
14611
+ const shell = kind === "sphere" ? SHELL_SPHERE : SHELL_CYLINDER;
14612
+ const solid = kind === "sphere" ? SOLID_SPHERE : SOLID_CYLINDER;
14613
+ let hollow = false;
14614
+ let filled = false;
14615
+ let liters = 0;
14616
+ let thickness = 0;
14617
+ let material = null;
14618
+ for (const [partId, pv] of b.parts) {
14619
+ if (pv.gone !== "none") continue;
14620
+ for (const mv of pv.meshes) {
14621
+ const ud = mv.mesh.userData;
14622
+ if (ud.hollow !== true) continue;
14623
+ hollow = true;
14624
+ if (ud.destructionPowder) filled = true;
14625
+ if (ud.destructionContains) {
14626
+ filled = true;
14627
+ const left = this.world.part(b.id, partId)?.liters;
14628
+ liters += left ?? (typeof ud.destructionContains.liters === "number" ? ud.destructionContains.liters : 0);
14629
+ }
14630
+ const t = typeof ud.destructionThickness === "number" ? ud.destructionThickness : 0;
14631
+ if (t > thickness) {
14632
+ thickness = t;
14633
+ material = this.world.part(b.id, partId)?.material ?? pv.material;
14634
+ }
14635
+ }
14636
+ }
14637
+ if (!hollow) return solid;
14638
+ if (!filled) return shell;
14639
+ const density = material ? this.world.materials.get(material)?.density : void 0;
14640
+ const area = kind === "sphere" ? 4 * Math.PI * radius * radius : 2 * Math.PI * radius * 2 * body.halfExtents[axis2] + 2 * Math.PI * radius * radius;
14641
+ const walls = density && thickness > 0 ? area * thickness * density : body.mass - liters * LIQUID_KG_PER_L;
14642
+ const share = clamp6(walls / body.mass, 0, 1);
14643
+ return share * shell + (1 - share) * solid;
14644
+ }
14645
+ /**
14646
+ * Whether what is drawn of the piece is round about one of its axes (a can, a bottle, a plate) or all of them (a ball): its points, in its frame from the centre of
14647
+ * mass, all lie within the circle the box's two other sides draw (a box's corners would stick out of it by sqrt 2). Null for anything else.
14648
+ */
14649
+ roundOf(b, body) {
14650
+ const half = body.halfExtents;
14651
+ const inv = specFrameInverse(this.THREE, b.root);
14652
+ const m4 = new this.THREE.Matrix4();
14653
+ const p = new this.THREE.Vector3();
14654
+ const [cx, cy, cz] = body.localCenter;
14655
+ const points = [];
14656
+ for (const mv of this.meshesOf(b)) {
14657
+ if (!this.visuals.shown(mv) || mv.host) continue;
14658
+ const pos = mv.mesh.geometry.getAttribute("position");
14659
+ if (!pos) continue;
14660
+ mv.mesh.updateWorldMatrix(true, false);
14661
+ m4.multiplyMatrices(inv, mv.mesh.matrixWorld);
14662
+ const stride = Math.max(1, Math.floor(pos.count / ROUND_SAMPLES));
14663
+ for (let i = 0; i < pos.count; i += stride) {
14664
+ p.fromBufferAttribute(pos, i).applyMatrix4(m4);
14665
+ points.push([p.x - cx, p.y - cy, p.z - cz]);
14666
+ }
14667
+ }
14668
+ if (points.length < 12) return null;
14669
+ const fits = (axis3) => {
14670
+ const [i, j] = axis3 === 0 ? [1, 2] : axis3 === 1 ? [0, 2] : [0, 1];
14671
+ if (Math.abs(half[i] - half[j]) > ROUND_SIDES * Math.max(half[i], half[j])) return null;
14672
+ const radius2 = (half[i] + half[j]) / 2;
14673
+ for (const q of points) if (Math.hypot(q[i], q[j]) > radius2 * ROUND_SLACK) return null;
14674
+ return radius2;
14675
+ };
14676
+ const radii = [0, 1, 2].map(fits);
14677
+ if (radii.every((r) => r !== null)) {
14678
+ const radius2 = (half[0] + half[1] + half[2]) / 3;
14679
+ return { kind: "sphere", axis: 1, radius: radius2, inertia: body.inertiaGiven ?? this.inertiaOf(b, body, "sphere", 1, radius2) };
14680
+ }
14681
+ const axis2 = [0, 1, 2].find((k) => radii[k] !== null);
14682
+ if (axis2 === void 0) return null;
14683
+ const radius = radii[axis2] ?? 0;
14684
+ return { kind: "cylinder", axis: axis2, radius, inertia: body.inertiaGiven ?? this.inertiaOf(b, body, "cylinder", axis2, radius), profile: profileOf(points, axis2, half[axis2], radius) };
14685
+ }
13961
14686
  pieces() {
13962
14687
  return [...this.pieceSys.list];
13963
14688
  }
@@ -13981,7 +14706,11 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
13981
14706
  const box = { min: [from[0] - core, from[1] - core, from[2] - core], max: [from[0] + core, from[1] + core, from[2] + core] };
13982
14707
  const hit = this.world.sweepBox(box, d, travel, { ignore: p.objectId, spacing: Math.max(0.05, core) });
13983
14708
  if (!hit) return null;
13984
- return { object: hit.object, part: hit.part, distance: hit.distance, point: hit.point, normal: hit.normal };
14709
+ const other = this.pieceSys.get(hit.object);
14710
+ if (other && (p.round || other.round)) return null;
14711
+ const material = this.world.part(hit.object, hit.part)?.material;
14712
+ const restitution = material === void 0 ? void 0 : surfaceOf(material, this.world.materials.get(material))?.restitution;
14713
+ return { object: hit.object, part: hit.part, distance: hit.distance, point: hit.point, normal: hit.normal, ...restitution === void 0 ? {} : { restitution } };
13985
14714
  }
13986
14715
  /** 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. */
13987
14716
  slam(p, hit, speed) {
@@ -14754,6 +15483,10 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
14754
15483
  old.halfExtents = half;
14755
15484
  this.pieceSys.setCenter(old, center);
14756
15485
  old.mass = Math.max(0.05, this.massOf(objectId));
15486
+ if (old.contacts || old.round) {
15487
+ this.fitSurface(b, old);
15488
+ if (!old.round) this.setContacts(b, old, this.meshesOf(b).filter((mv) => this.visuals.shown(mv)));
15489
+ } else if (old.partBoxes) this.fitPartBoxes(b, old);
14757
15490
  old.sleeping = false;
14758
15491
  } else if (kitOriginOf(b.root)?.kind === "furniture") {
14759
15492
  const piece = this.makePiece(objectId);
@@ -14807,6 +15540,7 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
14807
15540
  }
14808
15541
  const piece = this.pieceSys.create(newId, group, half, center, this.massOf(newId), vel, ang);
14809
15542
  nb.piece = piece;
15543
+ this.fitSurface(nb, piece);
14810
15544
  if (kitOriginOf(from.root)?.kind === "furniture") this.tipIfTopHeavy(nb);
14811
15545
  this.o.onPiece?.(piece);
14812
15546
  }
@@ -14827,7 +15561,10 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
14827
15561
  body.halfExtents = half;
14828
15562
  this.pieceSys.setCenter(body, center);
14829
15563
  body.mass = Math.max(0.05, this.massOf(objectId));
14830
- if (!structural) this.setContacts(b, body, left);
15564
+ if (!structural) {
15565
+ this.fitSurface(b, body);
15566
+ if (!body.round) this.setContacts(b, body, left);
15567
+ }
14831
15568
  body.sleeping = false;
14832
15569
  return;
14833
15570
  }
@@ -14939,11 +15676,13 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
14939
15676
  }
14940
15677
  /**
14941
15678
  * The piece touches the ground by the corners of each part left of it, not by the box around them all: on one leg, or on the legs of one side, its centre of mass is off
14942
- * what holds it and it goes over until the top meets the floor. Past `CONTACT_MESHES` meshes it keeps the corners of its box.
15679
+ * what holds it and it goes over until the top meets the floor. Past `CONTACT_MESHES` meshes it keeps the corners of its box; up to `PART_BOX_MESHES`, what lands on it lands
15680
+ * on its parts.
14943
15681
  */
14944
15682
  setContacts(b, body, meshes) {
14945
- if (meshes.length > CONTACT_MESHES) {
15683
+ if (meshes.length > PART_BOX_MESHES) {
14946
15684
  body.contacts = void 0;
15685
+ body.partBoxes = void 0;
14947
15686
  return;
14948
15687
  }
14949
15688
  const inv = specFrameInverse(this.THREE, b.root);
@@ -14951,14 +15690,20 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
14951
15690
  const lb = new this.THREE.Box3();
14952
15691
  const [cx, cy, cz] = body.localCenter;
14953
15692
  const points = [];
15693
+ const boxes = [];
14954
15694
  for (const mv of meshes) {
14955
15695
  mv.mesh.updateWorldMatrix(true, false);
14956
15696
  this.visuals.localBox(mv, lb);
14957
15697
  if (lb.isEmpty()) continue;
14958
15698
  lb.applyMatrix4(m4.multiplyMatrices(inv, mv.mesh.matrixWorld));
14959
15699
  for (let i = 0; i < 8; i++) points.push([(i & 1 ? lb.max.x : lb.min.x) - cx, (i & 2 ? lb.max.y : lb.min.y) - cy, (i & 4 ? lb.max.z : lb.min.z) - cz]);
15700
+ boxes.push({
15701
+ center: [(lb.min.x + lb.max.x) / 2 - cx, (lb.min.y + lb.max.y) / 2 - cy, (lb.min.z + lb.max.z) / 2 - cz],
15702
+ half: [Math.max(5e-3, (lb.max.x - lb.min.x) / 2), Math.max(5e-3, (lb.max.y - lb.min.y) / 2), Math.max(5e-3, (lb.max.z - lb.min.z) / 2)]
15703
+ });
14960
15704
  }
14961
- body.contacts = points.length > 0 ? points : void 0;
15705
+ body.contacts = points.length > 0 && meshes.length <= CONTACT_MESHES ? points : void 0;
15706
+ body.partBoxes = boxes.length > 1 ? boxes : void 0;
14962
15707
  }
14963
15708
  /**
14964
15709
  * A piece of furniture standing on feet too close for its height (a board on two legs in a line, a lone leg) does not stay up: the box of a piece hides that its weight is up
@@ -15331,7 +16076,7 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
15331
16076
  }
15332
16077
  };
15333
16078
 
15334
- // ../game-audio/dist/chunk-JV5XXCQE.js
16079
+ // ../game-audio/dist/chunk-TXGRBRE6.js
15335
16080
  var SFX_TIERS = { light: 0, medium: 0.34, heavy: 0.67 };
15336
16081
  function splitTier(id) {
15337
16082
  const match = /^(.*)_(light|medium|heavy)$/.exec(id);
@@ -15380,14 +16125,47 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
15380
16125
  ...numbers.cutoffK === void 0 ? {} : { cutoffK: numbers.cutoffK },
15381
16126
  ...numbers.group ? { group: numbers.group } : {},
15382
16127
  ...numbers.priority === void 0 ? {} : { priority: numbers.priority },
16128
+ ...numbers.choke ? { choke: numbers.choke } : {},
15383
16129
  ...numbers.fallback ? { fallback: numbers.fallback } : {},
15384
16130
  sources: files.map((file) => `${file.file}: ${file.source} ${file.author} ${file.license}`)
15385
16131
  });
15386
16132
  }
15387
16133
  return { id: options.id, samples };
15388
16134
  }
16135
+ var sample_levels_default = {
16136
+ $comment: "How loud each family of recorded sound plays against a gunshot, in dB under the shot (the converter normalizes every file to about -1 dBFS, so without these numbers a spent case lands as loud as the rifle that ejected it). A rifle is 155-165 dB SPL at the muzzle and a brass case on concrete 60-75 dB SPL at a metre: a game cannot hold 80 dB between two sounds, so the case sits 32 dB under the shot and a dropped magazine 24 dB, which keeps both audible near and below the shot after the mix. choke = how many of the family ring at once, per sound id: a full-auto burst leaves a few cases ringing, not one per round.",
16137
+ casing: {
16138
+ gainDb: -32,
16139
+ pitch: 0.06,
16140
+ cutoffK: 0.03,
16141
+ priority: 1,
16142
+ falloff: { model: "inverse_square", k: 0.08, minGain: 3e-3 },
16143
+ choke: { voices: 3, fade: 0.05 }
16144
+ },
16145
+ magazine: {
16146
+ gainDb: -24,
16147
+ pitch: 0.06,
16148
+ cutoffK: 0.03,
16149
+ priority: 1,
16150
+ falloff: { model: "inverse_square", k: 0.08, minGain: 3e-3 },
16151
+ choke: { voices: 2, fade: 0.05 }
16152
+ }
16153
+ };
16154
+ var SAMPLE_LEVELS = sample_levels_default;
16155
+ var gainOf = (gainDb) => 10 ** (gainDb / 20);
16156
+ var defaultsOf = (entry) => ({
16157
+ bus: "weapons",
16158
+ gain: gainOf(entry.gainDb),
16159
+ pitch: entry.pitch,
16160
+ falloff: entry.falloff,
16161
+ cutoffK: entry.cutoffK,
16162
+ priority: entry.priority,
16163
+ choke: entry.choke
16164
+ });
16165
+ var CASING_DEFAULTS = defaultsOf(SAMPLE_LEVELS.casing);
16166
+ var MAGAZINE_DROP_DEFAULTS = defaultsOf(SAMPLE_LEVELS.magazine);
15389
16167
 
15390
- // ../game-audio/dist/chunk-S6WJVZGX.js
16168
+ // ../game-audio/dist/chunk-KGYMFUK7.js
15391
16169
  var DISTANCE_CURVES = {
15392
16170
  /** The game's `sfx`: `vol / (1 + d² × 0.004)`, cutoff `/ (1 + d × 0.01)`, silent below 0.01 (jogo L62091–62092, L62101). */
15393
16171
  game_sfx: { model: "inverse_square", k: 4e-3, cutoffK: 0.01, minGain: 0.01 },