@adatechnology/game-vehicles-three 0.11.0 → 0.12.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.
@@ -427,6 +427,42 @@ var GameVehiclesThree = (() => {
427
427
  };
428
428
 
429
429
  // ../game-vehicles-fleet/dist/index.js
430
+ var motorcycles = [
431
+ "bicycle",
432
+ "scooter",
433
+ "commuter_motorcycle",
434
+ "trail_bike",
435
+ "adventure_bike",
436
+ "highway_police_bike",
437
+ "quad_bike",
438
+ "step_through_scooter",
439
+ "naked_bike",
440
+ "sport_bike",
441
+ "cruiser",
442
+ "delivery_bike"
443
+ ];
444
+ var cars = [
445
+ "compact_hatch",
446
+ "taxi",
447
+ "entry_hatch",
448
+ "electric_hatch",
449
+ "midsize_sedan",
450
+ "police_sedan",
451
+ "highway_police_sedan",
452
+ "beetle",
453
+ "boxy_hatch",
454
+ "family_hatch",
455
+ "rideshare_hatch",
456
+ "turbo_hatch",
457
+ "fastback_sedan",
458
+ "classic_six_sedan",
459
+ "v8_coupe"
460
+ ];
461
+ var suvs = ["compact_suv", "hybrid_suv", "midsize_suv", "large_suv"];
462
+ var pickups = ["compact_pickup", "crossover_pickup", "midsize_pickup", "monster_truck"];
463
+ var vans = ["cargo_van", "ambulance"];
464
+ var heavy = ["box_truck", "tanker_truck", "school_bus", "city_bus", "armored_truck"];
465
+ var agricultural = ["tractor"];
430
466
  var military = [
431
467
  "light_4x4",
432
468
  "troop_truck",
@@ -437,6 +473,20 @@ var GameVehiclesThree = (() => {
437
473
  "light_attack_turboprop",
438
474
  "attack_helicopter"
439
475
  ];
476
+ var water = ["river_skiff", "speedboat", "fishing_boat", "jet_ski", "sailboat", "rescue_dinghy", "patrol_boat"];
477
+ var air = [
478
+ "single_engine_plane",
479
+ "crop_duster",
480
+ "piston_helicopter",
481
+ "rescue_helicopter",
482
+ "tandem_trainer",
483
+ "regional_turboprop",
484
+ "amphibian_turboprop",
485
+ "light_jet",
486
+ "trainer_helicopter",
487
+ "turbine_helicopter",
488
+ "police_helicopter"
489
+ ];
440
490
  var fleetGroupIds = [
441
491
  "motorcycles",
442
492
  "cars",
@@ -449,6 +499,18 @@ var GameVehiclesThree = (() => {
449
499
  "water",
450
500
  "air"
451
501
  ];
502
+ var fleetGroups = {
503
+ motorcycles,
504
+ cars,
505
+ suvs,
506
+ pickups,
507
+ vans,
508
+ heavy,
509
+ agricultural,
510
+ military,
511
+ water,
512
+ air
513
+ };
452
514
  var legacyVehicleSeeds = {
453
515
  compact_hatch: "hatch",
454
516
  taxi: "taxi",
@@ -28214,6 +28276,9 @@ var GameVehiclesThree = (() => {
28214
28276
  }
28215
28277
  return palette[0][0];
28216
28278
  };
28279
+ var fleetGroupOf = (id) => Object.entries(fleetGroups).find(([, ids]) => ids.includes(id))?.[0];
28280
+ var HULL_CEILING = { motorcycles: 64, cars: 256, suvs: 256, pickups: 256, vans: 300, heavy: 550, agricultural: 150, military: 500, air: 500, water: 450 };
28281
+ var fleetHullCeilingOf = (id) => HULL_CEILING[fleetGroupOf(id) ?? ""];
28217
28282
 
28218
28283
  // src/lite.ts
28219
28284
  var LITE_CLASSES = ["paint", "trim", "metal", "glass", "light", "plate"];
@@ -28537,314 +28602,855 @@ var GameVehiclesThree = (() => {
28537
28602
  }
28538
28603
  }
28539
28604
 
28540
- // ../game-shapes/dist/chunk-E3X7UDDV.js
28541
- function canonicalJson(value) {
28542
- if (value === null) return "null";
28543
- if (typeof value === "number") return Object.is(value, -0) ? "-0" : Number.isFinite(value) ? String(value) : JSON.stringify(String(value));
28544
- if (typeof value === "string") return JSON.stringify(value);
28545
- if (typeof value === "boolean") return value ? "true" : "false";
28546
- if (typeof value === "function") throw new Error("game-shapes: a function cannot be part of a shape (register it as a generator)");
28547
- if (ArrayBuffer.isView(value)) return canonicalJson(Array.from(value));
28548
- if (Array.isArray(value)) return `[${value.map((item) => item === void 0 ? "null" : canonicalJson(item)).join(",")}]`;
28549
- if (typeof value === "object") {
28550
- const record = value;
28551
- const keys = Object.keys(record).filter((key) => record[key] !== void 0).sort();
28552
- return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(",")}}`;
28553
- }
28554
- return "null";
28555
- }
28556
- function needsUint32(array) {
28557
- for (let i = array.length - 1; i >= 0; --i) if (array[i] >= 65535) return true;
28558
- return false;
28559
- }
28560
- var indexArray = (indices) => needsUint32(indices) ? new Uint32Array(indices) : new Uint16Array(indices);
28561
- function pack(type, parameters, a) {
28562
- return {
28563
- type,
28564
- parameters,
28565
- positions: new Float32Array(a.vertices),
28566
- normals: new Float32Array(a.normals),
28567
- uvs: new Float32Array(a.uvs),
28568
- ...a.indices ? { indices: indexArray(a.indices) } : {},
28569
- groups: a.groups
28570
- };
28571
- }
28572
- var normalize3 = (x, y, z) => {
28573
- const length = Math.sqrt(x * x + y * y + z * z);
28574
- const s = 1 / (length || 1);
28575
- return [x * s, y * s, z * s];
28605
+ // ../game-vehicles/dist/chunk-AQFQ246K.js
28606
+ var __defProp2 = Object.defineProperty;
28607
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
28608
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
28609
+ var PLANE_EPS = 1e-7;
28610
+ var DIRECTIONS = (() => {
28611
+ const out = [];
28612
+ for (let x = -1; x <= 1; x++) for (let y = -1; y <= 1; y++) for (let z = -1; z <= 1; z++) if (x !== 0 || y !== 0 || z !== 0) out.push([x, y, z]);
28613
+ return out;
28614
+ })();
28615
+ var faceOf = (p, a, b, c) => {
28616
+ const ux = p[b * 3] - p[a * 3], uy = p[b * 3 + 1] - p[a * 3 + 1], uz = p[b * 3 + 2] - p[a * 3 + 2];
28617
+ const wx = p[c * 3] - p[a * 3], wy = p[c * 3 + 1] - p[a * 3 + 1], wz = p[c * 3 + 2] - p[a * 3 + 2];
28618
+ let nx = uy * wz - uz * wy, ny = uz * wx - ux * wz, nz = ux * wy - uy * wx;
28619
+ const length = Math.hypot(nx, ny, nz) || 1;
28620
+ nx /= length;
28621
+ ny /= length;
28622
+ nz /= length;
28623
+ return { a, b, c, nx, ny, nz, d: nx * p[a * 3] + ny * p[a * 3 + 1] + nz * p[a * 3 + 2] };
28576
28624
  };
28577
- function box(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
28578
- const parameters = { width, height, depth, widthSegments, heightSegments, depthSegments };
28579
- widthSegments = Math.floor(widthSegments);
28580
- heightSegments = Math.floor(heightSegments);
28581
- depthSegments = Math.floor(depthSegments);
28582
- const indices = [];
28583
- const vertices = [];
28584
- const normals = [];
28585
- const uvs = [];
28586
- const groups = [];
28587
- let numberOfVertices = 0;
28588
- let groupStart = 0;
28589
- const buildPlane = (u, v, w, udir, vdir, width2, height2, depth2, gridX, gridY, materialIndex) => {
28590
- const segmentWidth = width2 / gridX;
28591
- const segmentHeight = height2 / gridY;
28592
- const widthHalf = width2 / 2;
28593
- const heightHalf = height2 / 2;
28594
- const depthHalf = depth2 / 2;
28595
- const gridX1 = gridX + 1;
28596
- const gridY1 = gridY + 1;
28597
- let vertexCounter = 0;
28598
- let groupCount = 0;
28599
- const vector = { x: 0, y: 0, z: 0 };
28600
- for (let iy = 0; iy < gridY1; iy++) {
28601
- const y = iy * segmentHeight - heightHalf;
28602
- for (let ix = 0; ix < gridX1; ix++) {
28603
- const x = ix * segmentWidth - widthHalf;
28604
- vector[u] = x * udir;
28605
- vector[v] = y * vdir;
28606
- vector[w] = depthHalf;
28607
- vertices.push(vector.x, vector.y, vector.z);
28608
- vector[u] = 0;
28609
- vector[v] = 0;
28610
- vector[w] = depth2 > 0 ? 1 : -1;
28611
- normals.push(vector.x, vector.y, vector.z);
28612
- uvs.push(ix / gridX);
28613
- uvs.push(1 - iy / gridY);
28614
- vertexCounter += 1;
28615
- }
28616
- }
28617
- for (let iy = 0; iy < gridY; iy++) {
28618
- for (let ix = 0; ix < gridX; ix++) {
28619
- const a = numberOfVertices + ix + gridX1 * iy;
28620
- const b = numberOfVertices + ix + gridX1 * (iy + 1);
28621
- const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
28622
- const d = numberOfVertices + (ix + 1) + gridX1 * iy;
28623
- indices.push(a, b, d);
28624
- indices.push(b, c, d);
28625
- groupCount += 6;
28626
- }
28625
+ var sideOf = (face, p, i) => face.nx * p[i * 3] + face.ny * p[i * 3 + 1] + face.nz * p[i * 3 + 2] - face.d;
28626
+ var tetrahedronOf = (p, count2) => {
28627
+ let a = 0;
28628
+ for (let i = 1; i < count2; i++) if (p[i * 3] < p[a * 3]) a = i;
28629
+ const farthest = (score) => {
28630
+ let best = -1;
28631
+ let bestScore = PLANE_EPS;
28632
+ for (let i = 0; i < count2; i++) {
28633
+ const s = score(i);
28634
+ if (s > bestScore) [best, bestScore] = [i, s];
28627
28635
  }
28628
- groups.push({ start: groupStart, count: groupCount, materialIndex });
28629
- groupStart += groupCount;
28630
- numberOfVertices += vertexCounter;
28636
+ return best;
28631
28637
  };
28632
- buildPlane("z", "y", "x", -1, -1, depth, height, width, depthSegments, heightSegments, 0);
28633
- buildPlane("z", "y", "x", 1, -1, depth, height, -width, depthSegments, heightSegments, 1);
28634
- buildPlane("x", "z", "y", 1, 1, width, depth, height, widthSegments, depthSegments, 2);
28635
- buildPlane("x", "z", "y", 1, -1, width, depth, -height, widthSegments, depthSegments, 3);
28636
- buildPlane("x", "y", "z", 1, -1, width, height, depth, widthSegments, heightSegments, 4);
28637
- buildPlane("x", "y", "z", -1, -1, width, height, -depth, widthSegments, heightSegments, 5);
28638
- return pack("BoxGeometry", parameters, { vertices, normals, uvs, indices, groups });
28639
- }
28640
- function cylinderArrays(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
28641
- radialSegments = Math.floor(radialSegments);
28642
- heightSegments = Math.floor(heightSegments);
28643
- const indices = [];
28644
- const vertices = [];
28645
- const normals = [];
28646
- const uvs = [];
28647
- const groups = [];
28648
- let index = 0;
28649
- const indexArray2 = [];
28650
- const halfHeight = height / 2;
28651
- let groupStart = 0;
28652
- const generateTorso = () => {
28653
- let groupCount = 0;
28654
- const slope = (radiusBottom - radiusTop) / height;
28655
- for (let y = 0; y <= heightSegments; y++) {
28656
- const indexRow = [];
28657
- const v = y / heightSegments;
28658
- const radius = v * (radiusBottom - radiusTop) + radiusTop;
28659
- for (let x = 0; x <= radialSegments; x++) {
28660
- const u = x / radialSegments;
28661
- const theta = u * thetaLength + thetaStart;
28662
- const sinTheta = Math.sin(theta);
28663
- const cosTheta = Math.cos(theta);
28664
- vertices.push(radius * sinTheta, -v * height + halfHeight, radius * cosTheta);
28665
- const n = normalize3(sinTheta, slope, cosTheta);
28666
- normals.push(n[0], n[1], n[2]);
28667
- uvs.push(u, 1 - v);
28668
- indexRow.push(index++);
28669
- }
28670
- indexArray2.push(indexRow);
28671
- }
28672
- for (let x = 0; x < radialSegments; x++) {
28673
- for (let y = 0; y < heightSegments; y++) {
28674
- const a = indexArray2[y][x];
28675
- const b = indexArray2[y + 1][x];
28676
- const c = indexArray2[y + 1][x + 1];
28677
- const d = indexArray2[y][x + 1];
28678
- indices.push(a, b, d);
28679
- indices.push(b, c, d);
28680
- groupCount += 6;
28681
- }
28682
- }
28683
- groups.push({ start: groupStart, count: groupCount, materialIndex: 0 });
28684
- groupStart += groupCount;
28638
+ const b = farthest((i) => Math.hypot(p[i * 3] - p[a * 3], p[i * 3 + 1] - p[a * 3 + 1], p[i * 3 + 2] - p[a * 3 + 2]));
28639
+ if (b < 0) return null;
28640
+ const ux = p[b * 3] - p[a * 3], uy = p[b * 3 + 1] - p[a * 3 + 1], uz = p[b * 3 + 2] - p[a * 3 + 2];
28641
+ const c = farthest((i) => {
28642
+ const wx = p[i * 3] - p[a * 3], wy = p[i * 3 + 1] - p[a * 3 + 1], wz = p[i * 3 + 2] - p[a * 3 + 2];
28643
+ return Math.hypot(uy * wz - uz * wy, uz * wx - ux * wz, ux * wy - uy * wx) / Math.hypot(ux, uy, uz);
28644
+ });
28645
+ if (c < 0) return null;
28646
+ const base = faceOf(p, a, b, c);
28647
+ const d = farthest((i) => Math.abs(sideOf(base, p, i)));
28648
+ return d < 0 ? null : [a, b, c, d];
28649
+ };
28650
+ var convexFaces = (points) => {
28651
+ const count2 = Math.floor(points.length / 3);
28652
+ if (count2 < 4) return null;
28653
+ const corners = tetrahedronOf(points, count2);
28654
+ if (!corners) return null;
28655
+ const [a, b, c, d] = corners;
28656
+ const inside = [0, 1, 2].map((k) => (points[a * 3 + k] + points[b * 3 + k] + points[c * 3 + k] + points[d * 3 + k]) / 4);
28657
+ let faces = [];
28658
+ const add2 = (i, j, k) => {
28659
+ const face = faceOf(points, i, j, k);
28660
+ const towardInside = face.nx * inside[0] + face.ny * inside[1] + face.nz * inside[2] - face.d;
28661
+ faces.push(towardInside > 0 ? faceOf(points, i, k, j) : face);
28685
28662
  };
28686
- const generateCap = (top) => {
28687
- const centerIndexStart = index;
28688
- let groupCount = 0;
28689
- const radius = top === true ? radiusTop : radiusBottom;
28690
- const sign2 = top === true ? 1 : -1;
28691
- for (let x = 1; x <= radialSegments; x++) {
28692
- vertices.push(0, halfHeight * sign2, 0);
28693
- normals.push(0, sign2, 0);
28694
- uvs.push(0.5, 0.5);
28695
- index++;
28663
+ add2(a, b, c);
28664
+ add2(a, b, d);
28665
+ add2(a, c, d);
28666
+ add2(b, c, d);
28667
+ for (let i = 0; i < count2; i++) {
28668
+ if (i === a || i === b || i === c || i === d) continue;
28669
+ const visible = faces.filter((face) => sideOf(face, points, i) > PLANE_EPS);
28670
+ if (visible.length === 0) continue;
28671
+ const edges = /* @__PURE__ */ new Map();
28672
+ const key = (from, to) => from * count2 + to;
28673
+ for (const face of visible) for (const [from, to] of [[face.a, face.b], [face.b, face.c], [face.c, face.a]]) edges.set(key(from, to), [from, to]);
28674
+ const kept = faces.filter((face) => !visible.includes(face));
28675
+ for (const [from, to] of edges.values()) {
28676
+ if (edges.has(key(to, from))) continue;
28677
+ kept.push(faceOf(points, from, to, i));
28696
28678
  }
28697
- const centerIndexEnd = index;
28698
- for (let x = 0; x <= radialSegments; x++) {
28699
- const u = x / radialSegments;
28700
- const theta = u * thetaLength + thetaStart;
28701
- const cosTheta = Math.cos(theta);
28702
- const sinTheta = Math.sin(theta);
28703
- vertices.push(radius * sinTheta, halfHeight * sign2, radius * cosTheta);
28704
- normals.push(0, sign2, 0);
28705
- uvs.push(cosTheta * 0.5 + 0.5, sinTheta * 0.5 * sign2 + 0.5);
28706
- index++;
28679
+ faces = kept;
28680
+ }
28681
+ return faces.map((face) => [face.a, face.b, face.c]);
28682
+ };
28683
+ var hullVolume = (points, faces) => {
28684
+ let sum = 0;
28685
+ for (const [a, b, c] of faces) {
28686
+ const ax = points[a * 3], ay = points[a * 3 + 1], az = points[a * 3 + 2];
28687
+ const bx = points[b * 3], by = points[b * 3 + 1], bz = points[b * 3 + 2];
28688
+ const cx = points[c * 3], cy = points[c * 3 + 1], cz = points[c * 3 + 2];
28689
+ sum += ax * (by * cz - bz * cy) + ay * (bz * cx - bx * cz) + az * (bx * cy - by * cx);
28690
+ }
28691
+ return Math.abs(sum) / 6;
28692
+ };
28693
+ var reducePoints = (points, max) => {
28694
+ const count2 = Math.floor(points.length / 3);
28695
+ const picked = [];
28696
+ const taken = /* @__PURE__ */ new Set();
28697
+ const take = (i) => {
28698
+ if (taken.has(i)) return;
28699
+ taken.add(i);
28700
+ picked.push(i);
28701
+ };
28702
+ for (const [dx, dy, dz] of DIRECTIONS) {
28703
+ let best = 0;
28704
+ let bestDot = -Infinity;
28705
+ for (let i = 0; i < count2; i++) {
28706
+ const dot2 = points[i * 3] * dx + points[i * 3 + 1] * dy + points[i * 3 + 2] * dz;
28707
+ if (dot2 > bestDot) [best, bestDot] = [i, dot2];
28707
28708
  }
28708
- for (let x = 0; x < radialSegments; x++) {
28709
- const c = centerIndexStart + x;
28710
- const i = centerIndexEnd + x;
28711
- if (top === true) indices.push(i, i + 1, c);
28712
- else indices.push(i + 1, i, c);
28713
- groupCount += 3;
28709
+ take(best);
28710
+ }
28711
+ const away = new Float64Array(count2).fill(Infinity);
28712
+ const refresh = (from) => {
28713
+ for (let i = 0; i < count2; i++) {
28714
+ const dist = (points[i * 3] - points[from * 3]) ** 2 + (points[i * 3 + 1] - points[from * 3 + 1]) ** 2 + (points[i * 3 + 2] - points[from * 3 + 2]) ** 2;
28715
+ if (dist < away[i]) away[i] = dist;
28714
28716
  }
28715
- groups.push({ start: groupStart, count: groupCount, materialIndex: top === true ? 1 : 2 });
28716
- groupStart += groupCount;
28717
28717
  };
28718
- generateTorso();
28719
- if (openEnded === false) {
28720
- if (radiusTop > 0) generateCap(true);
28721
- if (radiusBottom > 0) generateCap(false);
28718
+ for (const i of picked) refresh(i);
28719
+ while (picked.length < Math.min(max, count2)) {
28720
+ let far = -1;
28721
+ let farDist = 0;
28722
+ for (let i = 0; i < count2; i++) if (away[i] > farDist) [far, farDist] = [i, away[i]];
28723
+ if (far < 0) break;
28724
+ take(far);
28725
+ refresh(far);
28722
28726
  }
28723
- return { vertices, normals, uvs, indices, groups };
28724
- }
28725
- function cylinder(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
28726
- const parameters = { radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength };
28727
- return pack("CylinderGeometry", parameters, cylinderArrays(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength));
28728
- }
28729
- function cone(radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
28730
- const parameters = { radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength };
28731
- return pack("ConeGeometry", parameters, cylinderArrays(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength));
28732
- }
28733
- function sphere(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
28734
- const parameters = { radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength };
28735
- widthSegments = Math.max(3, Math.floor(widthSegments));
28736
- heightSegments = Math.max(2, Math.floor(heightSegments));
28737
- const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
28738
- let index = 0;
28739
- const grid = [];
28740
- const indices = [];
28741
- const vertices = [];
28742
- const normals = [];
28743
- const uvs = [];
28744
- for (let iy = 0; iy <= heightSegments; iy++) {
28745
- const verticesRow = [];
28746
- const v = iy / heightSegments;
28747
- let uOffset = 0;
28748
- if (iy === 0 && thetaStart === 0) uOffset = 0.5 / widthSegments;
28749
- else if (iy === heightSegments && thetaEnd === Math.PI) uOffset = -0.5 / widthSegments;
28750
- for (let ix = 0; ix <= widthSegments; ix++) {
28751
- const u = ix / widthSegments;
28752
- const x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
28753
- const y = radius * Math.cos(thetaStart + v * thetaLength);
28754
- const z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
28755
- vertices.push(x, y, z);
28756
- const n = normalize3(x, y, z);
28757
- normals.push(n[0], n[1], n[2]);
28758
- uvs.push(u + uOffset, 1 - v);
28759
- verticesRow.push(index++);
28760
- }
28761
- grid.push(verticesRow);
28727
+ return picked.slice(0, max).flatMap((i) => [points[i * 3], points[i * 3 + 1], points[i * 3 + 2]]);
28728
+ };
28729
+ var FLOATING_REACH = 0.05;
28730
+ var FLOATING_AREA = 4e-3;
28731
+ var STEPS = 3;
28732
+ var CELL = 0.1;
28733
+ var MAX_CELLS = 64;
28734
+ var cellKey = (x, y, z) => ((x + 4096) * 8192 + (y + 4096)) * 8192 + (z + 4096);
28735
+ var sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
28736
+ var dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
28737
+ var distanceSquared = (p, a, b, c) => {
28738
+ const ab = sub(b, a), ac = sub(c, a), ap = sub(p, a);
28739
+ const d1 = dot(ab, ap), d2 = dot(ac, ap);
28740
+ let closest;
28741
+ const at = (u, v) => [a[0] + ab[0] * u + ac[0] * v, a[1] + ab[1] * u + ac[1] * v, a[2] + ab[2] * u + ac[2] * v];
28742
+ const bp = sub(p, b), d3 = dot(ab, bp), d4 = dot(ac, bp);
28743
+ const cp = sub(p, c), d5 = dot(ab, cp), d6 = dot(ac, cp);
28744
+ const vc = d1 * d4 - d3 * d2, vb = d5 * d2 - d1 * d6, va = d3 * d6 - d5 * d4;
28745
+ if (d1 <= 0 && d2 <= 0) closest = a;
28746
+ else if (d3 >= 0 && d4 <= d3) closest = b;
28747
+ else if (vc <= 0 && d1 >= 0 && d3 <= 0) closest = at(d1 / (d1 - d3), 0);
28748
+ else if (d6 >= 0 && d5 <= d6) closest = c;
28749
+ else if (vb <= 0 && d2 >= 0 && d6 <= 0) closest = at(0, d2 / (d2 - d6));
28750
+ else if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) closest = at(1 - (d4 - d3) / (d4 - d3 + (d5 - d6)), (d4 - d3) / (d4 - d3 + (d5 - d6)));
28751
+ else {
28752
+ const sum = va + vb + vc;
28753
+ closest = at(vb / sum, vc / sum);
28762
28754
  }
28763
- for (let iy = 0; iy < heightSegments; iy++) {
28764
- for (let ix = 0; ix < widthSegments; ix++) {
28765
- const a = grid[iy][ix + 1];
28766
- const b = grid[iy][ix];
28767
- const c = grid[iy + 1][ix];
28768
- const d = grid[iy + 1][ix + 1];
28769
- if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
28770
- if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
28755
+ const d = sub(p, closest);
28756
+ return dot(d, d);
28757
+ };
28758
+ var drawnIndexOf = (soup) => {
28759
+ let built2 = null;
28760
+ return { isNear: (x, y, z) => (built2 ?? (built2 = buildIndex(soup))).isNear(x, y, z) };
28761
+ };
28762
+ var buildIndex = (soup) => {
28763
+ const triangles = soup.indices.length / 3;
28764
+ const corner = new Float64Array(triangles * 9);
28765
+ const boxes = new Float64Array(triangles * 6);
28766
+ for (let t = 0; t < triangles; t++) {
28767
+ for (let k = 0; k < 3; k++) {
28768
+ const v = soup.indices[t * 3 + k] * 3;
28769
+ for (let a = 0; a < 3; a++) corner[t * 9 + k * 3 + a] = soup.vertices[v + a];
28770
+ }
28771
+ for (let a = 0; a < 3; a++) {
28772
+ const x = corner[t * 9 + a], y = corner[t * 9 + 3 + a], z = corner[t * 9 + 6 + a];
28773
+ boxes[t * 6 + a] = Math.min(x, y, z) - FLOATING_REACH;
28774
+ boxes[t * 6 + 3 + a] = Math.max(x, y, z) + FLOATING_REACH;
28771
28775
  }
28772
28776
  }
28773
- return pack("SphereGeometry", parameters, { vertices, normals, uvs, indices, groups: [] });
28774
- }
28775
- function plane(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
28776
- const parameters = { width, height, widthSegments, heightSegments };
28777
- const widthHalf = width / 2;
28778
- const heightHalf = height / 2;
28779
- const gridX = Math.floor(widthSegments);
28780
- const gridY = Math.floor(heightSegments);
28781
- const gridX1 = gridX + 1;
28782
- const gridY1 = gridY + 1;
28783
- const segmentWidth = width / gridX;
28784
- const segmentHeight = height / gridY;
28785
- const indices = [];
28786
- const vertices = [];
28787
- const normals = [];
28788
- const uvs = [];
28789
- for (let iy = 0; iy < gridY1; iy++) {
28790
- const y = iy * segmentHeight - heightHalf;
28791
- for (let ix = 0; ix < gridX1; ix++) {
28792
- const x = ix * segmentWidth - widthHalf;
28793
- vertices.push(x, -y, 0);
28794
- normals.push(0, 0, 1);
28795
- uvs.push(ix / gridX);
28796
- uvs.push(1 - iy / gridY);
28777
+ const cells = /* @__PURE__ */ new Map();
28778
+ const wide = [];
28779
+ for (let t = 0; t < triangles; t++) {
28780
+ const o = t * 6;
28781
+ const [x0, y0, z0, x1, y1, z1] = [0, 1, 2, 3, 4, 5].map((k) => Math.floor(boxes[o + k] / CELL));
28782
+ if ((x1 - x0 + 1) * (y1 - y0 + 1) * (z1 - z0 + 1) > MAX_CELLS) {
28783
+ wide.push(t);
28784
+ continue;
28785
+ }
28786
+ for (let x = x0; x <= x1; x++) for (let y = y0; y <= y1; y++) for (let z = z0; z <= z1; z++) {
28787
+ const key = cellKey(x, y, z);
28788
+ const list2 = cells.get(key);
28789
+ if (list2) list2.push(t);
28790
+ else cells.set(key, [t]);
28797
28791
  }
28798
28792
  }
28799
- for (let iy = 0; iy < gridY; iy++) {
28800
- for (let ix = 0; ix < gridX; ix++) {
28801
- const a = ix + gridX1 * iy;
28802
- const b = ix + gridX1 * (iy + 1);
28803
- const c = ix + 1 + gridX1 * (iy + 1);
28804
- const d = ix + 1 + gridX1 * iy;
28805
- indices.push(a, b, d);
28806
- indices.push(b, c, d);
28793
+ const isNearTriangle = (t, x, y, z) => {
28794
+ const o = t * 6;
28795
+ if (x < boxes[o] || y < boxes[o + 1] || z < boxes[o + 2] || x > boxes[o + 3] || y > boxes[o + 4] || z > boxes[o + 5]) return false;
28796
+ const c = t * 9;
28797
+ return distanceSquared([x, y, z], [corner[c], corner[c + 1], corner[c + 2]], [corner[c + 3], corner[c + 4], corner[c + 5]], [corner[c + 6], corner[c + 7], corner[c + 8]]) <= FLOATING_REACH * FLOATING_REACH;
28798
+ };
28799
+ return {
28800
+ isNear: (x, y, z) => {
28801
+ for (const t of cells.get(cellKey(Math.floor(x / CELL), Math.floor(y / CELL), Math.floor(z / CELL))) ?? []) if (isNearTriangle(t, x, y, z)) return true;
28802
+ for (const t of wide) if (isNearTriangle(t, x, y, z)) return true;
28803
+ return false;
28804
+ }
28805
+ };
28806
+ };
28807
+ var floatingAreaOf = (points, drawn) => {
28808
+ const faces = convexFaces(points);
28809
+ if (!faces) return 0;
28810
+ const vertex = (i) => [points[i * 3], points[i * 3 + 1], points[i * 3 + 2]];
28811
+ let floating = 0;
28812
+ for (const [ia, ib, ic] of faces) {
28813
+ const a = vertex(ia), b = vertex(ib), c = vertex(ic);
28814
+ const ab = sub(b, a), ac = sub(c, a);
28815
+ const area3 = Math.hypot(ab[1] * ac[2] - ab[2] * ac[1], ab[2] * ac[0] - ab[0] * ac[2], ab[0] * ac[1] - ab[1] * ac[0]) / 2;
28816
+ let samples = 0, far = 0;
28817
+ for (let i = 0; i <= STEPS; i++) {
28818
+ for (let j = 0; i + j <= STEPS; j++) {
28819
+ samples++;
28820
+ const u = i / STEPS, v = j / STEPS;
28821
+ if (!drawn.isNear(a[0] + ab[0] * u + ac[0] * v, a[1] + ab[1] * u + ac[1] * v, a[2] + ab[2] * u + ac[2] * v)) far++;
28822
+ }
28807
28823
  }
28824
+ floating += area3 * far / samples;
28808
28825
  }
28809
- return pack("PlaneGeometry", parameters, { vertices, normals, uvs, indices, groups: [] });
28810
- }
28811
- function circle(radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2) {
28812
- const parameters = { radius, segments, thetaStart, thetaLength };
28813
- segments = Math.max(3, segments);
28814
- const indices = [];
28826
+ return floating;
28827
+ };
28828
+ var THIN_SECTION = 0.08;
28829
+ var PROTRUSION_REACH = 0.03;
28830
+ var THIN_VOLUME = 2e-4;
28831
+ var BULK_BINS = 256;
28832
+ var BULK_SHARE = 0.99;
28833
+ var MIN_DIVISIBLE = 0.05;
28834
+ var subSoup = (soup, triangles) => {
28835
+ const moved = /* @__PURE__ */ new Map();
28815
28836
  const vertices = [];
28816
- const normals = [];
28817
- const uvs = [];
28818
- vertices.push(0, 0, 0);
28819
- normals.push(0, 0, 1);
28820
- uvs.push(0.5, 0.5);
28821
- for (let s = 0, i = 3; s <= segments; s++, i += 3) {
28822
- const segment = thetaStart + s / segments * thetaLength;
28823
- vertices.push(radius * Math.cos(segment), radius * Math.sin(segment), 0);
28824
- normals.push(0, 0, 1);
28825
- uvs.push((vertices[i] / radius + 1) / 2, (vertices[i + 1] / radius + 1) / 2);
28826
- }
28827
- for (let i = 1; i <= segments; i++) indices.push(i, i + 1, 0);
28828
- return pack("CircleGeometry", parameters, { vertices, normals, uvs, indices, groups: [] });
28829
- }
28830
- function ring(innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
28831
- const parameters = { innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength };
28832
- thetaSegments = Math.max(3, thetaSegments);
28833
- phiSegments = Math.max(1, phiSegments);
28834
28837
  const indices = [];
28835
- const vertices = [];
28836
- const normals = [];
28837
- const uvs = [];
28838
- let radius = innerRadius;
28839
- const radiusStep = (outerRadius - innerRadius) / phiSegments;
28840
- for (let j = 0; j <= phiSegments; j++) {
28841
- for (let i = 0; i <= thetaSegments; i++) {
28842
- const segment = thetaStart + i / thetaSegments * thetaLength;
28843
- const x = radius * Math.cos(segment);
28844
- const y = radius * Math.sin(segment);
28845
- vertices.push(x, y, 0);
28846
- normals.push(0, 0, 1);
28847
- uvs.push((x / outerRadius + 1) / 2, (y / outerRadius + 1) / 2);
28838
+ for (const t of triangles) {
28839
+ for (let k = 0; k < 3; k++) {
28840
+ const v = soup.indices[t * 3 + k];
28841
+ let at = moved.get(v);
28842
+ if (at === void 0) {
28843
+ at = vertices.length / 3;
28844
+ moved.set(v, at);
28845
+ vertices.push(soup.vertices[v * 3], soup.vertices[v * 3 + 1], soup.vertices[v * 3 + 2]);
28846
+ }
28847
+ indices.push(at);
28848
+ }
28849
+ }
28850
+ return { vertices, indices };
28851
+ };
28852
+ var WELD = 1e-4;
28853
+ var componentsOf = (soup) => {
28854
+ const welded = /* @__PURE__ */ new Map();
28855
+ const weldOf = (v) => {
28856
+ const key = (Math.round(soup.vertices[v * 3] / WELD) * 73856093 ^ Math.round(soup.vertices[v * 3 + 1] / WELD) * 19349663 ^ Math.round(soup.vertices[v * 3 + 2] / WELD) * 83492791) >>> 0;
28857
+ let id = welded.get(key);
28858
+ if (id === void 0) welded.set(key, id = welded.size);
28859
+ return id;
28860
+ };
28861
+ const parent = [];
28862
+ const rootOf = (v) => {
28863
+ let root = v;
28864
+ while (parent[root] !== root) root = parent[root];
28865
+ for (let node = v; parent[node] !== root; ) [node, parent[node]] = [parent[node], root];
28866
+ return root;
28867
+ };
28868
+ const corners = [];
28869
+ for (let i = 0; i < soup.indices.length; i++) {
28870
+ const id = weldOf(soup.indices[i]);
28871
+ while (parent.length <= id) parent.push(parent.length);
28872
+ corners.push(id);
28873
+ }
28874
+ for (let t = 0; t < corners.length; t += 3) {
28875
+ parent[rootOf(corners[t + 1])] = rootOf(corners[t]);
28876
+ parent[rootOf(corners[t + 2])] = rootOf(corners[t]);
28877
+ }
28878
+ const groups = /* @__PURE__ */ new Map();
28879
+ for (let t = 0; t < corners.length / 3; t++) {
28880
+ const root = rootOf(corners[t * 3]);
28881
+ const list2 = groups.get(root);
28882
+ if (list2) list2.push(t);
28883
+ else groups.set(root, [t]);
28884
+ }
28885
+ return [...groups.values()];
28886
+ };
28887
+ var boxOf = (soup) => {
28888
+ const low = [Infinity, Infinity, Infinity];
28889
+ const high = [-Infinity, -Infinity, -Infinity];
28890
+ for (let i = 0; i < soup.vertices.length; i += 3) {
28891
+ for (let k = 0; k < 3; k++) {
28892
+ const value = soup.vertices[i + k];
28893
+ if (value < low[k]) low[k] = value;
28894
+ if (value > high[k]) high[k] = value;
28895
+ }
28896
+ }
28897
+ return { low, high };
28898
+ };
28899
+ var volumeOf = (soup) => {
28900
+ const points = reducePoints(soup.vertices, 64);
28901
+ const faces = convexFaces(points);
28902
+ return faces ? hullVolume(points, faces) : 0;
28903
+ };
28904
+ var AXES = [[0, 1], [0, -1], [1, 1], [1, -1], [2, 1], [2, -1]];
28905
+ var tailOf = (soup) => {
28906
+ const count2 = soup.indices.length / 3;
28907
+ const areas = [];
28908
+ const centres = [];
28909
+ for (let t = 0; t < count2; t++) {
28910
+ const [a, b, c] = [0, 1, 2].map((k) => soup.indices[t * 3 + k] * 3);
28911
+ const v = soup.vertices;
28912
+ const ux = v[b] - v[a], uy = v[b + 1] - v[a + 1], uz = v[b + 2] - v[a + 2], wx = v[c] - v[a], wy = v[c + 1] - v[a + 1], wz = v[c + 2] - v[a + 2];
28913
+ areas.push(Math.hypot(uy * wz - uz * wy, uz * wx - ux * wz, ux * wy - uy * wx));
28914
+ centres.push([(v[a] + v[b] + v[c]) / 3, (v[a + 1] + v[b + 1] + v[c + 1]) / 3, (v[a + 2] + v[b + 2] + v[c + 2]) / 3]);
28915
+ }
28916
+ const total = areas.reduce((sum, area3) => sum + area3, 0);
28917
+ const tail = /* @__PURE__ */ new Set();
28918
+ for (const [axis, sign2] of AXES) {
28919
+ const values = centres.map((centre) => sign2 * centre[axis]);
28920
+ let low = Infinity, high = -Infinity;
28921
+ for (const value of values) {
28922
+ if (value < low) low = value;
28923
+ if (value > high) high = value;
28924
+ }
28925
+ const step = (high - low) / BULK_BINS || 1;
28926
+ const area3 = new Float64Array(BULK_BINS + 1);
28927
+ values.forEach((value, t) => {
28928
+ area3[Math.floor((value - low) / step)] += areas[t];
28929
+ });
28930
+ let reached = 0, bin = 0;
28931
+ while (bin < BULK_BINS && reached + area3[bin] < total * BULK_SHARE) reached += area3[bin++];
28932
+ const bulk = low + (bin + 1) * step;
28933
+ for (let t = 0; t < count2; t++) if (values[t] > bulk + PROTRUSION_REACH) tail.add(t);
28934
+ }
28935
+ return [...tail].sort((p, q) => p - q);
28936
+ };
28937
+ var protrusionsOf = (soup) => {
28938
+ const taken = /* @__PURE__ */ new Set();
28939
+ const out = [];
28940
+ const add2 = (triangles, from) => {
28941
+ out.push({ id: triangles[0], triangles, soup: from });
28942
+ for (const t of triangles) taken.add(t);
28943
+ };
28944
+ const tail = tailOf(soup);
28945
+ if (tail.length > 0) {
28946
+ for (const group of componentsOf(subSoup(soup, tail))) {
28947
+ const triangles = group.map((t) => tail[t]);
28948
+ const part = subSoup(soup, triangles);
28949
+ if (volumeOf(part) <= THIN_VOLUME) add2(triangles, part);
28950
+ }
28951
+ }
28952
+ const parts = componentsOf(soup);
28953
+ if (parts.length < 2) return out;
28954
+ const soups = parts.map((triangles) => subSoup(soup, triangles));
28955
+ const boxes = soups.map(boxOf);
28956
+ const isThin = boxes.map((box2) => box2.high.map((high, k) => high - box2.low[k]).sort((a, b) => a - b)[1] <= THIN_SECTION);
28957
+ const thick = soups.filter((_, i) => !isThin[i]);
28958
+ if (thick.length === 0) return out;
28959
+ const bodyBox = boxOf({ vertices: thick.flatMap((part) => part.vertices), indices: [] });
28960
+ parts.forEach((triangles, i) => {
28961
+ if (!isThin[i] || triangles.some((t) => taken.has(t))) return;
28962
+ const box2 = boxes[i];
28963
+ if ([0, 1, 2].some((k) => box2.high[k] > bodyBox.high[k] + PROTRUSION_REACH || box2.low[k] < bodyBox.low[k] - PROTRUSION_REACH)) add2(triangles, soups[i]);
28964
+ });
28965
+ return out;
28966
+ };
28967
+ var withoutProtrusions = (soup, protrusions) => {
28968
+ const gone = new Set(protrusions.flatMap((protrusion) => protrusion.triangles));
28969
+ return subSoup(soup, Array.from({ length: soup.indices.length / 3 }, (_, t) => t).filter((t) => !gone.has(t)));
28970
+ };
28971
+ var joined = (a, b) => ({ vertices: [...a.vertices, ...b.vertices], indices: [...a.indices, ...b.indices.map((i) => i + a.vertices.length / 3)] });
28972
+ var unitsOf = (key, soup, taken) => {
28973
+ if (!taken || taken.size === 0) return [{ key, soup }];
28974
+ const off = protrusionsOf(soup).filter((protrusion) => taken.has(protrusion.id));
28975
+ if (off.length === 0) return [{ key, soup }];
28976
+ return [{ key, soup: withoutProtrusions(soup, off) }, ...off.map((protrusion) => ({ key: `${key}~${protrusion.id}`, soup: protrusion.soup }))];
28977
+ };
28978
+ var longestSide = (soup) => {
28979
+ const centres = [];
28980
+ for (let t = 0; t < soup.indices.length / 3; t++) {
28981
+ for (let k = 0; k < 3; k++) centres.push((soup.vertices[soup.indices[t * 3] * 3 + k] + soup.vertices[soup.indices[t * 3 + 1] * 3 + k] + soup.vertices[soup.indices[t * 3 + 2] * 3 + k]) / 3);
28982
+ }
28983
+ const { low, high } = boxOf({ vertices: centres, indices: [] });
28984
+ let axis = 0;
28985
+ for (const k of [1, 2]) if (high[k] - low[k] > high[axis] - low[axis]) axis = k;
28986
+ return { axis, at: (low[axis] + high[axis]) / 2, length: high[axis] - low[axis] };
28987
+ };
28988
+ var cutSoup = (soup, axis, at) => {
28989
+ const lo = [];
28990
+ const hi = [];
28991
+ for (let t = 0; t < soup.indices.length / 3; t++) {
28992
+ const centre = (soup.vertices[soup.indices[t * 3] * 3 + axis] + soup.vertices[soup.indices[t * 3 + 1] * 3 + axis] + soup.vertices[soup.indices[t * 3 + 2] * 3 + axis]) / 3;
28993
+ (centre < at ? lo : hi).push(t);
28994
+ }
28995
+ return [lo.length ? subSoup(soup, lo) : null, hi.length ? subSoup(soup, hi) : null];
28996
+ };
28997
+ var leavesOf = (key, soup, node, path = "") => {
28998
+ if (!node) return [{ key: path ? `${key}:${path}` : key, path, soup }];
28999
+ const [lo, hi] = cutSoup(soup, node.axis, node.at);
29000
+ return [...lo ? leavesOf(key, lo, node.lo, `${path}0`) : [], ...hi ? leavesOf(key, hi, node.hi, `${path}1`) : []];
29001
+ };
29002
+ var MAX_HULL_POINTS = 64;
29003
+ var FLAT_PAD = 25e-4;
29004
+ var mainNormal = (soup) => {
29005
+ const v = soup.vertices;
29006
+ let best = [0, 1, 0];
29007
+ let bestArea = 0;
29008
+ for (let t = 0; t + 2 < soup.indices.length; t += 3) {
29009
+ const a = soup.indices[t] * 3, b = soup.indices[t + 1] * 3, c = soup.indices[t + 2] * 3;
29010
+ const ux = v[b] - v[a], uy = v[b + 1] - v[a + 1], uz = v[b + 2] - v[a + 2];
29011
+ const wx = v[c] - v[a], wy = v[c + 1] - v[a + 1], wz = v[c + 2] - v[a + 2];
29012
+ const cross = [uy * wz - uz * wy, uz * wx - ux * wz, ux * wy - uy * wx];
29013
+ const area3 = Math.hypot(...cross);
29014
+ if (area3 > bestArea) [best, bestArea] = [[cross[0] / area3, cross[1] / area3, cross[2] / area3], area3];
29015
+ }
29016
+ return best;
29017
+ };
29018
+ var spreadAlong = (points, axis) => {
29019
+ let low = Infinity;
29020
+ let high = -Infinity;
29021
+ for (let i = 0; i < points.length; i += 3) {
29022
+ const t = points[i] * axis[0] + points[i + 1] * axis[1] + points[i + 2] * axis[2];
29023
+ if (t < low) low = t;
29024
+ if (t > high) high = t;
29025
+ }
29026
+ return high - low;
29027
+ };
29028
+ var paddedAlong = (points, axis) => {
29029
+ const out = [];
29030
+ for (let i = 0; i < points.length; i += 3) {
29031
+ for (const sign2 of [-1, 1]) out.push(points[i] + sign2 * axis[0] * FLAT_PAD, points[i + 1] + sign2 * axis[1] * FLAT_PAD, points[i + 2] + sign2 * axis[2] * FLAT_PAD);
29032
+ }
29033
+ return out;
29034
+ };
29035
+ var acrossOf = (axis) => {
29036
+ const pick = Math.abs(axis[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0];
29037
+ const cross = [axis[1] * pick[2] - axis[2] * pick[1], axis[2] * pick[0] - axis[0] * pick[2], axis[0] * pick[1] - axis[1] * pick[0]];
29038
+ const length = Math.hypot(...cross);
29039
+ return [cross[0] / length, cross[1] / length, cross[2] / length];
29040
+ };
29041
+ var hullOf = (soup) => {
29042
+ if (soup.vertices.length < 9) return null;
29043
+ const reduced = reducePoints(soup.vertices, MAX_HULL_POINTS);
29044
+ const normal = mainNormal(soup);
29045
+ if (spreadAlong(reduced, normal) >= 2 * FLAT_PAD && convexFaces(reduced)) return reduced;
29046
+ const thick = paddedAlong(reducePoints(reduced, MAX_HULL_POINTS / 2), normal);
29047
+ if (convexFaces(thick)) return thick;
29048
+ const lined = paddedAlong(paddedAlong(reducePoints(reduced, MAX_HULL_POINTS / 4), normal), acrossOf(normal));
29049
+ return convexFaces(lined) ? lined : null;
29050
+ };
29051
+ var newHullPlan = () => ({ cuts: /* @__PURE__ */ new Map(), taken: /* @__PURE__ */ new Map() });
29052
+ var floatingOf = (soup, drawn) => {
29053
+ const points = hullOf(soup);
29054
+ return points ? floatingAreaOf(points, drawn) : 0;
29055
+ };
29056
+ var leafOf = (unit, path, soup, isDone, drawn) => {
29057
+ const points = hullOf(soup);
29058
+ return { unit, path, soup, points, floating: points ? floatingAreaOf(points, drawn) : 0, isDone, drawn };
29059
+ };
29060
+ var insertCut = (cuts, unit, path, node) => {
29061
+ if (path === "") {
29062
+ cuts.set(unit, node);
29063
+ return;
29064
+ }
29065
+ let at = cuts.get(unit);
29066
+ for (const step of path.slice(0, -1)) at = step === "0" ? at.lo : at.hi;
29067
+ if (path.endsWith("0")) at.lo = node;
29068
+ else at.hi = node;
29069
+ };
29070
+ var takeProtrusions = (leaf, room) => {
29071
+ const all = protrusionsOf(leaf.soup);
29072
+ const rest = withoutProtrusions(leaf.soup, all);
29073
+ const base = floatingOf(rest, leaf.drawn);
29074
+ const gains = all.map((protrusion) => ({ protrusion, gain: floatingOf(joined(rest, protrusion.soup), leaf.drawn) - base })).filter(({ gain }) => gain > FLOATING_AREA);
29075
+ const taken = gains.sort((a, b) => b.gain - a.gain || a.protrusion.id - b.protrusion.id).slice(0, Math.max(0, room)).map(({ protrusion }) => protrusion);
29076
+ const body = leafOf(leaf.unit, "", withoutProtrusions(leaf.soup, taken), true, leaf.drawn);
29077
+ return { body, parts: taken.map((protrusion) => leafOf(`${leaf.unit}~${protrusion.id}`, "", protrusion.soup, true, leaf.drawn)), ids: taken.map((protrusion) => protrusion.id) };
29078
+ };
29079
+ var planDivision = (pieces, plan, maxHulls) => {
29080
+ let leaves = pieces.map((piece) => leafOf(piece.key, "", piece.soup, false, drawnIndexOf(piece.soup)));
29081
+ let hulls = leaves.filter((leaf) => leaf.points).length;
29082
+ while (hulls < maxHulls) {
29083
+ let worst = -1;
29084
+ for (let i = 0; i < leaves.length; i++) {
29085
+ const leaf2 = leaves[i];
29086
+ if (leaf2.floating > FLOATING_AREA && (worst < 0 || leaf2.floating > leaves[worst].floating)) worst = i;
29087
+ }
29088
+ if (worst < 0) break;
29089
+ const leaf = leaves[worst];
29090
+ if (!leaf.isDone && leaf.path === "") {
29091
+ const { body, parts, ids } = takeProtrusions(leaf, maxHulls - hulls);
29092
+ if (ids.length > 0) plan.taken.set(leaf.unit, new Set(ids));
29093
+ hulls += parts.filter((part) => part.points).length;
29094
+ leaves = [...leaves.slice(0, worst), body, ...parts, ...leaves.slice(worst + 1)];
29095
+ continue;
29096
+ }
29097
+ const { axis, at, length } = longestSide(leaf.soup);
29098
+ const [lo, hi] = length < MIN_DIVISIBLE ? [null, null] : cutSoup(leaf.soup, axis, at);
29099
+ if (!lo || !hi) {
29100
+ leaves[worst] = { ...leaf, floating: 0 };
29101
+ continue;
29102
+ }
29103
+ insertCut(plan.cuts, leaf.unit, leaf.path, { axis, at, lo: null, hi: null });
29104
+ const halves = [leafOf(leaf.unit, `${leaf.path}0`, lo, true, leaf.drawn), leafOf(leaf.unit, `${leaf.path}1`, hi, true, leaf.drawn)];
29105
+ hulls += halves.filter((half) => half.points).length - 1;
29106
+ leaves = [...leaves.slice(0, worst), ...halves, ...leaves.slice(worst + 1)];
29107
+ }
29108
+ return leaves;
29109
+ };
29110
+ var solidHullsOf = (pieces) => {
29111
+ const parts = /* @__PURE__ */ new Map();
29112
+ for (const piece of pieces) {
29113
+ let part = parts.get(piece.key);
29114
+ if (!part) parts.set(piece.key, part = { vertices: [], indices: [] });
29115
+ const offset = part.vertices.length / 3;
29116
+ for (const value of piece.vertices) part.vertices.push(value);
29117
+ for (const index of piece.indices) part.indices.push(index + offset);
29118
+ }
29119
+ return [...parts].map(([key, soup]) => ({ key, points: new Float32Array(hullOf(soup) ?? []) }));
29120
+ };
29121
+ var planHulls = (job) => {
29122
+ const plan = newHullPlan();
29123
+ const leaves = planDivision(job.pieces.map((piece) => ({ key: piece.key, soup: { vertices: Array.from(piece.vertices), indices: Array.from(piece.indices) } })), plan, job.maxHulls);
29124
+ return {
29125
+ cuts: [...plan.cuts],
29126
+ taken: [...plan.taken].map(([unit, numbers]) => [unit, [...numbers]]),
29127
+ solids: solidHullsOf(job.solids),
29128
+ leaves: leaves.flatMap((leaf) => leaf.points ? [{ unit: leaf.unit, path: leaf.path, points: new Float32Array(leaf.points), vertices: Float64Array.from(leaf.soup.vertices) }] : [])
29129
+ };
29130
+ };
29131
+ var WARMUP = {
29132
+ pieces: [{ key: "roof#1", vertices: Float64Array.of(0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0.5, 1.4, 0.5), indices: Uint32Array.of(0, 1, 2, 0, 2, 3, 0, 1, 4) }],
29133
+ solids: [{ key: "engine", vertices: Float64Array.of(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), indices: Uint32Array.of(0, 1, 2, 0, 1, 3) }],
29134
+ maxHulls: 8
29135
+ };
29136
+ var hullPlanKind = Object.freeze({
29137
+ id: WORKER_KIND_ID.VEHICLE_HULL_PLAN,
29138
+ kind: "task",
29139
+ ...WORKER_KIND_DEFAULTS[WORKER_KIND_ID.VEHICLE_HULL_PLAN],
29140
+ run: planHulls,
29141
+ transferInput: (job) => [...job.pieces, ...job.solids].flatMap((piece) => [piece.vertices.buffer, piece.indices.buffer]),
29142
+ transferOutput: (result) => [...result.leaves.flatMap((leaf) => [leaf.points.buffer, leaf.vertices.buffer]), ...result.solids.map((solid) => solid.points.buffer)],
29143
+ warmup: WARMUP
29144
+ });
29145
+
29146
+ // ../game-shapes/dist/chunk-E3X7UDDV.js
29147
+ function canonicalJson(value) {
29148
+ if (value === null) return "null";
29149
+ if (typeof value === "number") return Object.is(value, -0) ? "-0" : Number.isFinite(value) ? String(value) : JSON.stringify(String(value));
29150
+ if (typeof value === "string") return JSON.stringify(value);
29151
+ if (typeof value === "boolean") return value ? "true" : "false";
29152
+ if (typeof value === "function") throw new Error("game-shapes: a function cannot be part of a shape (register it as a generator)");
29153
+ if (ArrayBuffer.isView(value)) return canonicalJson(Array.from(value));
29154
+ if (Array.isArray(value)) return `[${value.map((item) => item === void 0 ? "null" : canonicalJson(item)).join(",")}]`;
29155
+ if (typeof value === "object") {
29156
+ const record = value;
29157
+ const keys = Object.keys(record).filter((key) => record[key] !== void 0).sort();
29158
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(",")}}`;
29159
+ }
29160
+ return "null";
29161
+ }
29162
+ function needsUint32(array) {
29163
+ for (let i = array.length - 1; i >= 0; --i) if (array[i] >= 65535) return true;
29164
+ return false;
29165
+ }
29166
+ var indexArray = (indices) => needsUint32(indices) ? new Uint32Array(indices) : new Uint16Array(indices);
29167
+ function pack(type, parameters, a) {
29168
+ return {
29169
+ type,
29170
+ parameters,
29171
+ positions: new Float32Array(a.vertices),
29172
+ normals: new Float32Array(a.normals),
29173
+ uvs: new Float32Array(a.uvs),
29174
+ ...a.indices ? { indices: indexArray(a.indices) } : {},
29175
+ groups: a.groups
29176
+ };
29177
+ }
29178
+ var normalize3 = (x, y, z) => {
29179
+ const length = Math.sqrt(x * x + y * y + z * z);
29180
+ const s = 1 / (length || 1);
29181
+ return [x * s, y * s, z * s];
29182
+ };
29183
+ function box(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
29184
+ const parameters = { width, height, depth, widthSegments, heightSegments, depthSegments };
29185
+ widthSegments = Math.floor(widthSegments);
29186
+ heightSegments = Math.floor(heightSegments);
29187
+ depthSegments = Math.floor(depthSegments);
29188
+ const indices = [];
29189
+ const vertices = [];
29190
+ const normals = [];
29191
+ const uvs = [];
29192
+ const groups = [];
29193
+ let numberOfVertices = 0;
29194
+ let groupStart = 0;
29195
+ const buildPlane = (u, v, w, udir, vdir, width2, height2, depth2, gridX, gridY, materialIndex) => {
29196
+ const segmentWidth = width2 / gridX;
29197
+ const segmentHeight = height2 / gridY;
29198
+ const widthHalf = width2 / 2;
29199
+ const heightHalf = height2 / 2;
29200
+ const depthHalf = depth2 / 2;
29201
+ const gridX1 = gridX + 1;
29202
+ const gridY1 = gridY + 1;
29203
+ let vertexCounter = 0;
29204
+ let groupCount = 0;
29205
+ const vector = { x: 0, y: 0, z: 0 };
29206
+ for (let iy = 0; iy < gridY1; iy++) {
29207
+ const y = iy * segmentHeight - heightHalf;
29208
+ for (let ix = 0; ix < gridX1; ix++) {
29209
+ const x = ix * segmentWidth - widthHalf;
29210
+ vector[u] = x * udir;
29211
+ vector[v] = y * vdir;
29212
+ vector[w] = depthHalf;
29213
+ vertices.push(vector.x, vector.y, vector.z);
29214
+ vector[u] = 0;
29215
+ vector[v] = 0;
29216
+ vector[w] = depth2 > 0 ? 1 : -1;
29217
+ normals.push(vector.x, vector.y, vector.z);
29218
+ uvs.push(ix / gridX);
29219
+ uvs.push(1 - iy / gridY);
29220
+ vertexCounter += 1;
29221
+ }
29222
+ }
29223
+ for (let iy = 0; iy < gridY; iy++) {
29224
+ for (let ix = 0; ix < gridX; ix++) {
29225
+ const a = numberOfVertices + ix + gridX1 * iy;
29226
+ const b = numberOfVertices + ix + gridX1 * (iy + 1);
29227
+ const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
29228
+ const d = numberOfVertices + (ix + 1) + gridX1 * iy;
29229
+ indices.push(a, b, d);
29230
+ indices.push(b, c, d);
29231
+ groupCount += 6;
29232
+ }
29233
+ }
29234
+ groups.push({ start: groupStart, count: groupCount, materialIndex });
29235
+ groupStart += groupCount;
29236
+ numberOfVertices += vertexCounter;
29237
+ };
29238
+ buildPlane("z", "y", "x", -1, -1, depth, height, width, depthSegments, heightSegments, 0);
29239
+ buildPlane("z", "y", "x", 1, -1, depth, height, -width, depthSegments, heightSegments, 1);
29240
+ buildPlane("x", "z", "y", 1, 1, width, depth, height, widthSegments, depthSegments, 2);
29241
+ buildPlane("x", "z", "y", 1, -1, width, depth, -height, widthSegments, depthSegments, 3);
29242
+ buildPlane("x", "y", "z", 1, -1, width, height, depth, widthSegments, heightSegments, 4);
29243
+ buildPlane("x", "y", "z", -1, -1, width, height, -depth, widthSegments, heightSegments, 5);
29244
+ return pack("BoxGeometry", parameters, { vertices, normals, uvs, indices, groups });
29245
+ }
29246
+ function cylinderArrays(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
29247
+ radialSegments = Math.floor(radialSegments);
29248
+ heightSegments = Math.floor(heightSegments);
29249
+ const indices = [];
29250
+ const vertices = [];
29251
+ const normals = [];
29252
+ const uvs = [];
29253
+ const groups = [];
29254
+ let index = 0;
29255
+ const indexArray2 = [];
29256
+ const halfHeight = height / 2;
29257
+ let groupStart = 0;
29258
+ const generateTorso = () => {
29259
+ let groupCount = 0;
29260
+ const slope = (radiusBottom - radiusTop) / height;
29261
+ for (let y = 0; y <= heightSegments; y++) {
29262
+ const indexRow = [];
29263
+ const v = y / heightSegments;
29264
+ const radius = v * (radiusBottom - radiusTop) + radiusTop;
29265
+ for (let x = 0; x <= radialSegments; x++) {
29266
+ const u = x / radialSegments;
29267
+ const theta = u * thetaLength + thetaStart;
29268
+ const sinTheta = Math.sin(theta);
29269
+ const cosTheta = Math.cos(theta);
29270
+ vertices.push(radius * sinTheta, -v * height + halfHeight, radius * cosTheta);
29271
+ const n = normalize3(sinTheta, slope, cosTheta);
29272
+ normals.push(n[0], n[1], n[2]);
29273
+ uvs.push(u, 1 - v);
29274
+ indexRow.push(index++);
29275
+ }
29276
+ indexArray2.push(indexRow);
29277
+ }
29278
+ for (let x = 0; x < radialSegments; x++) {
29279
+ for (let y = 0; y < heightSegments; y++) {
29280
+ const a = indexArray2[y][x];
29281
+ const b = indexArray2[y + 1][x];
29282
+ const c = indexArray2[y + 1][x + 1];
29283
+ const d = indexArray2[y][x + 1];
29284
+ indices.push(a, b, d);
29285
+ indices.push(b, c, d);
29286
+ groupCount += 6;
29287
+ }
29288
+ }
29289
+ groups.push({ start: groupStart, count: groupCount, materialIndex: 0 });
29290
+ groupStart += groupCount;
29291
+ };
29292
+ const generateCap = (top) => {
29293
+ const centerIndexStart = index;
29294
+ let groupCount = 0;
29295
+ const radius = top === true ? radiusTop : radiusBottom;
29296
+ const sign2 = top === true ? 1 : -1;
29297
+ for (let x = 1; x <= radialSegments; x++) {
29298
+ vertices.push(0, halfHeight * sign2, 0);
29299
+ normals.push(0, sign2, 0);
29300
+ uvs.push(0.5, 0.5);
29301
+ index++;
29302
+ }
29303
+ const centerIndexEnd = index;
29304
+ for (let x = 0; x <= radialSegments; x++) {
29305
+ const u = x / radialSegments;
29306
+ const theta = u * thetaLength + thetaStart;
29307
+ const cosTheta = Math.cos(theta);
29308
+ const sinTheta = Math.sin(theta);
29309
+ vertices.push(radius * sinTheta, halfHeight * sign2, radius * cosTheta);
29310
+ normals.push(0, sign2, 0);
29311
+ uvs.push(cosTheta * 0.5 + 0.5, sinTheta * 0.5 * sign2 + 0.5);
29312
+ index++;
29313
+ }
29314
+ for (let x = 0; x < radialSegments; x++) {
29315
+ const c = centerIndexStart + x;
29316
+ const i = centerIndexEnd + x;
29317
+ if (top === true) indices.push(i, i + 1, c);
29318
+ else indices.push(i + 1, i, c);
29319
+ groupCount += 3;
29320
+ }
29321
+ groups.push({ start: groupStart, count: groupCount, materialIndex: top === true ? 1 : 2 });
29322
+ groupStart += groupCount;
29323
+ };
29324
+ generateTorso();
29325
+ if (openEnded === false) {
29326
+ if (radiusTop > 0) generateCap(true);
29327
+ if (radiusBottom > 0) generateCap(false);
29328
+ }
29329
+ return { vertices, normals, uvs, indices, groups };
29330
+ }
29331
+ function cylinder(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
29332
+ const parameters = { radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength };
29333
+ return pack("CylinderGeometry", parameters, cylinderArrays(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength));
29334
+ }
29335
+ function cone(radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
29336
+ const parameters = { radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength };
29337
+ return pack("ConeGeometry", parameters, cylinderArrays(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength));
29338
+ }
29339
+ function sphere(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
29340
+ const parameters = { radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength };
29341
+ widthSegments = Math.max(3, Math.floor(widthSegments));
29342
+ heightSegments = Math.max(2, Math.floor(heightSegments));
29343
+ const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
29344
+ let index = 0;
29345
+ const grid = [];
29346
+ const indices = [];
29347
+ const vertices = [];
29348
+ const normals = [];
29349
+ const uvs = [];
29350
+ for (let iy = 0; iy <= heightSegments; iy++) {
29351
+ const verticesRow = [];
29352
+ const v = iy / heightSegments;
29353
+ let uOffset = 0;
29354
+ if (iy === 0 && thetaStart === 0) uOffset = 0.5 / widthSegments;
29355
+ else if (iy === heightSegments && thetaEnd === Math.PI) uOffset = -0.5 / widthSegments;
29356
+ for (let ix = 0; ix <= widthSegments; ix++) {
29357
+ const u = ix / widthSegments;
29358
+ const x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
29359
+ const y = radius * Math.cos(thetaStart + v * thetaLength);
29360
+ const z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
29361
+ vertices.push(x, y, z);
29362
+ const n = normalize3(x, y, z);
29363
+ normals.push(n[0], n[1], n[2]);
29364
+ uvs.push(u + uOffset, 1 - v);
29365
+ verticesRow.push(index++);
29366
+ }
29367
+ grid.push(verticesRow);
29368
+ }
29369
+ for (let iy = 0; iy < heightSegments; iy++) {
29370
+ for (let ix = 0; ix < widthSegments; ix++) {
29371
+ const a = grid[iy][ix + 1];
29372
+ const b = grid[iy][ix];
29373
+ const c = grid[iy + 1][ix];
29374
+ const d = grid[iy + 1][ix + 1];
29375
+ if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
29376
+ if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
29377
+ }
29378
+ }
29379
+ return pack("SphereGeometry", parameters, { vertices, normals, uvs, indices, groups: [] });
29380
+ }
29381
+ function plane(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
29382
+ const parameters = { width, height, widthSegments, heightSegments };
29383
+ const widthHalf = width / 2;
29384
+ const heightHalf = height / 2;
29385
+ const gridX = Math.floor(widthSegments);
29386
+ const gridY = Math.floor(heightSegments);
29387
+ const gridX1 = gridX + 1;
29388
+ const gridY1 = gridY + 1;
29389
+ const segmentWidth = width / gridX;
29390
+ const segmentHeight = height / gridY;
29391
+ const indices = [];
29392
+ const vertices = [];
29393
+ const normals = [];
29394
+ const uvs = [];
29395
+ for (let iy = 0; iy < gridY1; iy++) {
29396
+ const y = iy * segmentHeight - heightHalf;
29397
+ for (let ix = 0; ix < gridX1; ix++) {
29398
+ const x = ix * segmentWidth - widthHalf;
29399
+ vertices.push(x, -y, 0);
29400
+ normals.push(0, 0, 1);
29401
+ uvs.push(ix / gridX);
29402
+ uvs.push(1 - iy / gridY);
29403
+ }
29404
+ }
29405
+ for (let iy = 0; iy < gridY; iy++) {
29406
+ for (let ix = 0; ix < gridX; ix++) {
29407
+ const a = ix + gridX1 * iy;
29408
+ const b = ix + gridX1 * (iy + 1);
29409
+ const c = ix + 1 + gridX1 * (iy + 1);
29410
+ const d = ix + 1 + gridX1 * iy;
29411
+ indices.push(a, b, d);
29412
+ indices.push(b, c, d);
29413
+ }
29414
+ }
29415
+ return pack("PlaneGeometry", parameters, { vertices, normals, uvs, indices, groups: [] });
29416
+ }
29417
+ function circle(radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2) {
29418
+ const parameters = { radius, segments, thetaStart, thetaLength };
29419
+ segments = Math.max(3, segments);
29420
+ const indices = [];
29421
+ const vertices = [];
29422
+ const normals = [];
29423
+ const uvs = [];
29424
+ vertices.push(0, 0, 0);
29425
+ normals.push(0, 0, 1);
29426
+ uvs.push(0.5, 0.5);
29427
+ for (let s = 0, i = 3; s <= segments; s++, i += 3) {
29428
+ const segment = thetaStart + s / segments * thetaLength;
29429
+ vertices.push(radius * Math.cos(segment), radius * Math.sin(segment), 0);
29430
+ normals.push(0, 0, 1);
29431
+ uvs.push((vertices[i] / radius + 1) / 2, (vertices[i + 1] / radius + 1) / 2);
29432
+ }
29433
+ for (let i = 1; i <= segments; i++) indices.push(i, i + 1, 0);
29434
+ return pack("CircleGeometry", parameters, { vertices, normals, uvs, indices, groups: [] });
29435
+ }
29436
+ function ring(innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
29437
+ const parameters = { innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength };
29438
+ thetaSegments = Math.max(3, thetaSegments);
29439
+ phiSegments = Math.max(1, phiSegments);
29440
+ const indices = [];
29441
+ const vertices = [];
29442
+ const normals = [];
29443
+ const uvs = [];
29444
+ let radius = innerRadius;
29445
+ const radiusStep = (outerRadius - innerRadius) / phiSegments;
29446
+ for (let j = 0; j <= phiSegments; j++) {
29447
+ for (let i = 0; i <= thetaSegments; i++) {
29448
+ const segment = thetaStart + i / thetaSegments * thetaLength;
29449
+ const x = radius * Math.cos(segment);
29450
+ const y = radius * Math.sin(segment);
29451
+ vertices.push(x, y, 0);
29452
+ normals.push(0, 0, 1);
29453
+ uvs.push((x / outerRadius + 1) / 2, (y / outerRadius + 1) / 2);
28848
29454
  }
28849
29455
  radius += radiusStep;
28850
29456
  }
@@ -30093,12 +30699,12 @@ var GameVehiclesThree = (() => {
30093
30699
  }
30094
30700
  return out;
30095
30701
  };
30096
- var WELD = 1e-4;
30702
+ var WELD2 = 1e-4;
30097
30703
  var solidsOf = (points, triangles) => {
30098
30704
  const parent = Array.from({ length: points.length / 3 }, (_, v) => v);
30099
30705
  const at = /* @__PURE__ */ new Map();
30100
30706
  for (let v = 0; v < parent.length; v++) {
30101
- const key = `${Math.round(points[v * 3] / WELD)},${Math.round(points[v * 3 + 1] / WELD)},${Math.round(points[v * 3 + 2] / WELD)}`;
30707
+ const key = `${Math.round(points[v * 3] / WELD2)},${Math.round(points[v * 3 + 1] / WELD2)},${Math.round(points[v * 3 + 2] / WELD2)}`;
30102
30708
  const first = at.get(key);
30103
30709
  if (first === void 0) at.set(key, v);
30104
30710
  else parent[v] = first;
@@ -30388,9 +30994,6 @@ var GameVehiclesThree = (() => {
30388
30994
  }
30389
30995
 
30390
30996
  // ../game-vehicles/dist/index.js
30391
- var __defProp2 = Object.defineProperty;
30392
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
30393
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
30394
30997
  var en_default2 = {
30395
30998
  plate: {
30396
30999
  band: "BRAZIL"
@@ -36569,9 +37172,9 @@ var GameVehiclesThree = (() => {
36569
37172
  opts = opts || {};
36570
37173
  dir = dir.clone().normalize();
36571
37174
  const m = c.meta;
36572
- const air = m.kind === "plane" || m.kind === "heli";
36573
- const Wref = air ? m.fuselageWidth || 1.3 : m.width || 1.7;
36574
- const R0 = (0.55 + 0.45 * force) * (air ? 1.25 : 1);
37175
+ const air2 = m.kind === "plane" || m.kind === "heli";
37176
+ const Wref = air2 ? m.fuselageWidth || 1.3 : m.width || 1.7;
37177
+ const R0 = (0.55 + 0.45 * force) * (air2 ? 1.25 : 1);
36575
37178
  const maxD = Math.min(0.18 * Wref, 0.26, R0 * 0.32, opts.maxDepth || 9) * (1 - 0.85 * clamp(m.stiff || 0, 0, 1));
36576
37179
  const H = {
36577
37180
  p,
@@ -36724,7 +37327,7 @@ var GameVehiclesThree = (() => {
36724
37327
  }
36725
37328
  const surf = findSurface(c, p, dir);
36726
37329
  if (surf) {
36727
- if (kit.config.impactStain && !opts.noStain && force > 0.45 && !air && m.kind !== "boat") {
37330
+ if (kit.config.impactStain && !opts.noStain && force > 0.45 && !air2 && m.kind !== "boat") {
36728
37331
  const sp = surf.p.clone().addScaledVector(surf.n, 2e-3);
36729
37332
  markDecal(
36730
37333
  kit.splat(c, sp, surf.n, 0.08 + force * 0.04, {
@@ -38167,17 +38770,17 @@ var GameVehiclesThree = (() => {
38167
38770
  return { lo, hi };
38168
38771
  }
38169
38772
  function regionCands(c, z, cands) {
38170
- if (!cands.some(heavy)) return cands;
38773
+ if (!cands.some(heavy2)) return cands;
38171
38774
  const R = decalRegion(c, z);
38172
38775
  const Mw = c.vehicle.matrixWorld;
38173
38776
  return cands.map(function(o) {
38174
- if (!heavy(o)) return o;
38777
+ if (!heavy2(o)) return o;
38175
38778
  if (!o.geometry.boundingSphere) o.geometry.computeBoundingSphere();
38176
38779
  if (!o.geometry.boundingBox) o.geometry.computeBoundingBox();
38177
38780
  return proxyIn(o, Mw, R);
38178
38781
  });
38179
38782
  }
38180
- function heavy(o) {
38783
+ function heavy2(o) {
38181
38784
  const g = o.geometry;
38182
38785
  const pos = g && g.attributes && g.attributes.position;
38183
38786
  return o.raycast === THREE.Mesh.prototype.raycast && !o.isSkinnedMesh && !Array.isArray(o.material) && pos && !pos.isInterleavedBufferAttribute && pos.itemSize === 3 && !g.groups.length && !(g.morphAttributes && g.morphAttributes.position) && (g.index ? g.index.count : pos.count) / 3 >= PROXY_MIN_TRIANGLES;
@@ -41945,12 +42548,12 @@ var GameVehiclesThree = (() => {
41945
42548
  }
41946
42549
  return members;
41947
42550
  }
41948
- function sideOf(box2) {
42551
+ function sideOf2(box2) {
41949
42552
  const z = (box2.min.z + box2.max.z) / 2;
41950
42553
  return Math.abs(z) < CENTRE_Z ? "center" : z < 0 ? "left" : "right";
41951
42554
  }
41952
42555
  function lampOf(inner, box2, front, flags) {
41953
- return { group: null, lens: [], inner, kind: front ? "headlight" : "taillight", tint: front ? "clear" : "red", broken: false, side: sideOf(box2), ...flags };
42556
+ return { group: null, lens: [], inner, kind: front ? "headlight" : "taillight", tint: front ? "clear" : "red", broken: false, side: sideOf2(box2), ...flags };
41954
42557
  }
41955
42558
  function strayLampsOf(c, THREE) {
41956
42559
  c.strayLamps ?? (c.strayLamps = findStrayLamps(c, THREE));
@@ -42007,8 +42610,8 @@ var GameVehiclesThree = (() => {
42007
42610
  }
42008
42611
  var DOOR_SHELL_DEPTH = 0.09;
42009
42612
  var DOOR_SHELL_MAX_DEPTH = 0.25;
42010
- var WELD2 = 1e-5;
42011
- var cellOf = (v) => Math.round(v / WELD2);
42613
+ var WELD3 = 1e-5;
42614
+ var cellOf = (v) => Math.round(v / WELD3);
42012
42615
  function weld(positions) {
42013
42616
  const ids = new Int32Array(positions.length / 3);
42014
42617
  const points = [];
@@ -42019,7 +42622,7 @@ var GameVehiclesThree = (() => {
42019
42622
  for (let j = -1; j <= 1; j++)
42020
42623
  for (let k = -1; k <= 1; k++) {
42021
42624
  for (const id of cells.get(`${cx + i},${cy + j},${cz + k}`) ?? []) {
42022
- if (Math.abs(points[id * 3] - x) <= WELD2 && Math.abs(points[id * 3 + 1] - y) <= WELD2 && Math.abs(points[id * 3 + 2] - z) <= WELD2) return id;
42625
+ if (Math.abs(points[id * 3] - x) <= WELD3 && Math.abs(points[id * 3 + 1] - y) <= WELD3 && Math.abs(points[id * 3 + 2] - z) <= WELD3) return id;
42023
42626
  }
42024
42627
  }
42025
42628
  return void 0;
@@ -42145,7 +42748,7 @@ var GameVehiclesThree = (() => {
42145
42748
  const s = [...size].sort((a, b) => b - a);
42146
42749
  return s[0] * s[1];
42147
42750
  };
42148
- var boxOf = (z) => ({
42751
+ var boxOf2 = (z) => ({
42149
42752
  center: [(z.box.x0 + z.box.x1) / 2, (z.box.y0 + z.box.y1) / 2, (z.box.z0 + z.box.z1) / 2],
42150
42753
  size: [Math.max(0.02, z.box.x1 - z.box.x0), Math.max(0.02, z.box.y1 - z.box.y0), Math.max(0.02, z.box.z1 - z.box.z0)]
42151
42754
  });
@@ -42260,7 +42863,7 @@ var GameVehiclesThree = (() => {
42260
42863
  for (const z of zones) {
42261
42864
  let role = roleOfZone(z);
42262
42865
  if (z === hubZone) role = "frame";
42263
- const box2 = boxOf(z);
42866
+ const box2 = boxOf2(z);
42264
42867
  const area3 = areaOf(box2.size);
42265
42868
  const id = z.id;
42266
42869
  const label = String(z.name ?? id);
@@ -49677,8 +50280,8 @@ var GameVehiclesThree = (() => {
49677
50280
  state.charge = clamp3(state.charge + net * dt / 3600 / capacity, 0, 1);
49678
50281
  if (before >= crankCharge && state.charge < crankCharge && !running) events.push({ type: "battery_flat" });
49679
50282
  const work = running ? clamp3(0.15 + 0.85 * throttle * (driver.state.rpm / 6500), 0, 1) : 0;
49680
- const air = cooling.stopped + (cooling.fast - cooling.stopped) * clamp3(Math.abs(driver.state.u) / 27.8, 0, 1);
49681
- const cool = air * clamp3(radiator, 0.05, 1) * (running ? 1 + (controls.climate.on ? 0.15 : 0) : 1);
50283
+ const air2 = cooling.stopped + (cooling.fast - cooling.stopped) * clamp3(Math.abs(driver.state.u) / 27.8, 0, 1);
50284
+ const cool = air2 * clamp3(radiator, 0.05, 1) * (running ? 1 + (controls.climate.on ? 0.15 : 0) : 1);
49682
50285
  const opened = state.coolantC >= thermostat ? 1 : 0.15;
49683
50286
  state.coolantC += (heat * work - cool * opened * (state.coolantC - ambient)) * dt;
49684
50287
  state.coolantC = coolantC ?? Math.max(ambient, state.coolantC);
@@ -49740,767 +50343,219 @@ var GameVehiclesThree = (() => {
49740
50343
  }
49741
50344
  var GLOVEBOX = { id: "glovebox", slots: 6, capacityKg: 4, access: "cabin" };
49742
50345
  var trunkFor = (litres = 450) => ({ id: "trunk", slots: Math.max(4, Math.round(litres / 25)), capacityKg: Math.round(litres / 4), access: "lid" });
49743
- var weightOf = (stack) => stack.unitKg * stack.count;
49744
- function createVehicleStorage(options = {}) {
49745
- const compartments = [...options.compartments ?? [GLOVEBOX, trunkFor()]];
49746
- const slots = new Map(compartments.map((c) => [c.id, Array.from({ length: c.slots }, () => null)]));
49747
- const specOf = (id) => compartments.find((c) => c.id === id);
49748
- const load = (id) => (slots.get(id) ?? []).reduce((kg, s) => kg + (s ? weightOf(s) : 0), 0);
49749
- const reachable2 = (id, access) => {
49750
- const spec = specOf(id);
49751
- if (!spec) return false;
49752
- return spec.access === "lid" ? access.lid >= 0.5 : access.gloveboxOpen && (access.seated || access.frontDoorOpen);
49753
- };
49754
- const place = (id, stack) => {
49755
- const spec = specOf(id);
49756
- const list2 = slots.get(id);
49757
- if (!spec || !list2) return "missing";
49758
- if (load(id) + weightOf(stack) > spec.capacityKg + 1e-9) return "too_heavy";
49759
- const same = stack.data === void 0 ? list2.findIndex((s) => s !== null && s.itemId === stack.itemId && s.data === void 0) : -1;
49760
- if (same >= 0) {
49761
- const s = list2[same];
49762
- list2[same] = { ...s, count: s.count + stack.count };
49763
- return "ok";
49764
- }
49765
- const free = list2.indexOf(null);
49766
- if (free < 0) return "full";
49767
- list2[free] = { ...stack };
49768
- return "ok";
49769
- };
49770
- return {
49771
- compartments,
49772
- reachable: reachable2,
49773
- contents: (id) => [...slots.get(id) ?? []],
49774
- loadKg: (id) => id === void 0 ? compartments.reduce((kg, c) => kg + load(c.id), 0) : load(id),
49775
- put(id, stack, access) {
49776
- if (!specOf(id)) return "missing";
49777
- if (!reachable2(id, access)) return "shut";
49778
- return place(id, stack);
49779
- },
49780
- take(id, slot, access) {
49781
- const list2 = slots.get(id);
49782
- if (!list2 || !reachable2(id, access)) return null;
49783
- const stack = list2[slot] ?? null;
49784
- if (stack) list2[slot] = null;
49785
- return stack;
49786
- },
49787
- stock(id, stacks) {
49788
- return stacks.filter((s) => place(id, s) !== "ok");
49789
- },
49790
- clear() {
49791
- for (const list2 of slots.values()) list2.fill(null);
49792
- }
49793
- };
49794
- }
49795
- var clamp4 = (x, a, b) => Math.max(a, Math.min(b, x));
49796
- function createWindshieldFog(options = {}) {
49797
- const outside = options.outsideHumidity ?? 0.6;
49798
- const breath = options.breath ?? 4e-3;
49799
- const wet = options.wet ?? 2e-3;
49800
- const air = options.air ?? { shut: 2e-3, window: 0.05, climate: 0.01, demist: 0.06 };
49801
- const coldSpan = options.coldSpan ?? 15;
49802
- const rates = options.rates ?? { build: 0.05, clear: 0.03, demist: 0.25 };
49803
- const state = { humidity: outside, fog: 0 };
49804
- return {
49805
- state,
49806
- step({ dt, occupants, outsideC, cabinC, rain = 0, speed = 0, windows = 0, climate, engineWarm = 1 }) {
49807
- const exchange = air.shut + air.window * clamp4(windows, 0, 1) + (climate.on ? air.climate : 0) + (climate.demist ? air.demist : 0);
49808
- const source = breath * Math.max(0, occupants) + wet * clamp4(rain, 0, 1) * (occupants > 0 ? 1 : 0);
49809
- const towards = climate.on ? outside * 0.4 : outside;
49810
- state.humidity = clamp4(state.humidity + (source - exchange * (state.humidity - towards)) * dt, 0, 1);
49811
- const cold = Math.max(0, cabinC - outsideC) * (1 - 0.7 * clamp4(windows, 0, 1)) + 6 * clamp4(rain, 0, 1) + 2 * clamp4(speed / 27.8, 0, 1);
49812
- const warmed = climate.demist ? cold * (1 - 0.9 * clamp4(engineWarm, 0, 1)) : cold;
49813
- const clearUpTo = 1 - 0.5 * clamp4(warmed / coldSpan, 0, 1);
49814
- const target = clamp4((state.humidity - clearUpTo) * 6, 0, 1);
49815
- const down = climate.demist ? rates.demist * (0.3 + 0.7 * clamp4(engineWarm, 0, 1)) : rates.clear;
49816
- state.fog = target > state.fog ? Math.min(target, state.fog + rates.build * dt) : Math.max(target, state.fog - down * dt);
49817
- return state;
49818
- },
49819
- set(next) {
49820
- if (next.humidity !== void 0) state.humidity = clamp4(next.humidity, 0, 1);
49821
- if (next.fog !== void 0) state.fog = clamp4(next.fog, 0, 1);
49822
- }
49823
- };
49824
- }
49825
-
49826
- // src/collider-fit.ts
49827
- var FIT = 0.01;
49828
- var MIN_HALF2 = 5e-3;
49829
- var COARSEN_ABOVE = 60;
49830
- var COARSE_CELL = 8e-3;
49831
- var COARSE_MIN_TRIANGLES = 12;
49832
- var IDENTITY_AXES = [1, 0, 0, 0, 1, 0, 0, 0, 1];
49833
- var CELL_BIAS = 4096;
49834
- var CELL_SPAN = 8192;
49835
- var soupOf = () => ({ vertices: [], indices: [], placed: /* @__PURE__ */ new Map() });
49836
- var addTriangle = (soup, source, positions, corners, matrix) => {
49837
- let placed = soup.placed.get(source);
49838
- if (!placed) soup.placed.set(source, placed = /* @__PURE__ */ new Map());
49839
- for (const corner of corners) {
49840
- let at = placed.get(corner);
49841
- if (at === void 0) {
49842
- const x = positions[corner * 3], y = positions[corner * 3 + 1], z = positions[corner * 3 + 2];
49843
- at = soup.vertices.length / 3;
49844
- placed.set(corner, at);
49845
- soup.vertices.push(
49846
- matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12],
49847
- matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13],
49848
- matrix[2] * x + matrix[6] * y + matrix[10] * z + matrix[14]
49849
- );
49850
- }
49851
- soup.indices.push(at);
49852
- }
49853
- };
49854
- var cellKey = (x, y, z, cell) => ((Math.floor(x / cell) + CELL_BIAS) * CELL_SPAN + (Math.floor(y / cell) + CELL_BIAS)) * CELL_SPAN + (Math.floor(z / cell) + CELL_BIAS);
49855
- var coarsen = (soup) => {
49856
- const count2 = soup.vertices.length / 3;
49857
- const cells = /* @__PURE__ */ new Map();
49858
- const sums = [];
49859
- const counts = [];
49860
- const to = new Uint32Array(count2);
49861
- for (let i = 0; i < count2; i++) {
49862
- const x = soup.vertices[i * 3], y = soup.vertices[i * 3 + 1], z = soup.vertices[i * 3 + 2];
49863
- const key = cellKey(x, y, z, COARSE_CELL);
49864
- let at = cells.get(key);
49865
- if (at === void 0) {
49866
- at = counts.length;
49867
- cells.set(key, at);
49868
- counts.push(0);
49869
- sums.push(0, 0, 0);
49870
- }
49871
- to[i] = at;
49872
- counts[at] = counts[at] + 1;
49873
- sums[at * 3] = sums[at * 3] + x;
49874
- sums[at * 3 + 1] = sums[at * 3 + 1] + y;
49875
- sums[at * 3 + 2] = sums[at * 3 + 2] + z;
49876
- }
49877
- const best = new Float64Array(counts.length).fill(Infinity);
49878
- const vertices = new Array(counts.length * 3).fill(0);
49879
- for (let i = 0; i < count2; i++) {
49880
- const at = to[i];
49881
- const n = counts[at];
49882
- const x = soup.vertices[i * 3], y = soup.vertices[i * 3 + 1], z = soup.vertices[i * 3 + 2];
49883
- const d = (x - sums[at * 3] / n) ** 2 + (y - sums[at * 3 + 1] / n) ** 2 + (z - sums[at * 3 + 2] / n) ** 2;
49884
- if (d >= best[at]) continue;
49885
- best[at] = d;
49886
- vertices[at * 3] = x;
49887
- vertices[at * 3 + 1] = y;
49888
- vertices[at * 3 + 2] = z;
49889
- }
49890
- const indices = [];
49891
- const seen = /* @__PURE__ */ new Set();
49892
- const stride = counts.length;
49893
- for (let i = 0; i + 2 < soup.indices.length; i += 3) {
49894
- const a = to[soup.indices[i]], b = to[soup.indices[i + 1]], c = to[soup.indices[i + 2]];
49895
- if (a === b || b === c || a === c) continue;
49896
- const lo = Math.min(a, b, c), hi = Math.max(a, b, c);
49897
- const key = (lo * stride + (a + b + c - lo - hi)) * stride + hi;
49898
- if (seen.has(key)) continue;
49899
- seen.add(key);
49900
- indices.push(a, b, c);
49901
- }
49902
- return { vertices, indices, placed: /* @__PURE__ */ new Map() };
49903
- };
49904
- var axesOf = ([x, y, z, w]) => [
49905
- 1 - 2 * (y * y + z * z),
49906
- 2 * (x * y + z * w),
49907
- 2 * (x * z - y * w),
49908
- 2 * (x * y - z * w),
49909
- 1 - 2 * (x * x + z * z),
49910
- 2 * (y * z + x * w),
49911
- 2 * (x * z + y * w),
49912
- 2 * (y * z - x * w),
49913
- 1 - 2 * (x * x + y * y)
49914
- ];
49915
- var tightened = (points, box2) => {
49916
- const axes = axesOf(box2.rotation);
49917
- const low = [Infinity, Infinity, Infinity];
49918
- const high = [-Infinity, -Infinity, -Infinity];
49919
- for (let i = 0; i < points.length; i += 3) {
49920
- for (let k = 0; k < 3; k++) {
49921
- const t = points[i] * axes[k * 3] + points[i + 1] * axes[k * 3 + 1] + points[i + 2] * axes[k * 3 + 2];
49922
- if (t < low[k]) low[k] = t;
49923
- if (t > high[k]) high[k] = t;
49924
- }
49925
- }
49926
- const mid = [0, 1, 2].map((k) => (low[k] + high[k]) / 2);
49927
- const center = [0, 1, 2].map((k) => mid[0] * axes[k] + mid[1] * axes[3 + k] + mid[2] * axes[6 + k]);
49928
- const half = [0, 1, 2].map((k) => Math.max(MIN_HALF2, (high[k] - low[k]) / 2));
49929
- return { center, half, rotation: box2.rotation };
49930
- };
49931
- var isOneBox = (soup) => fitOrientedBoxes(soup.vertices, soup.indices).length <= 1;
49932
- var colliderOf = (id, key, soup) => {
49933
- const points = soup.vertices;
49934
- if (points.length < 9) return null;
49935
- const low = [Infinity, Infinity, Infinity];
49936
- const high = [-Infinity, -Infinity, -Infinity];
49937
- for (let i = 0; i < points.length; i += 3) {
49938
- for (let k = 0; k < 3; k++) {
49939
- const v = points[i + k];
49940
- if (v < low[k]) low[k] = v;
49941
- if (v > high[k]) high[k] = v;
49942
- }
49943
- }
49944
- const center = [(low[0] + high[0]) / 2, (low[1] + high[1]) / 2, (low[2] + high[2]) / 2];
49945
- const half = [(high[0] - low[0]) / 2, (high[1] - low[1]) / 2, (high[2] - low[2]) / 2];
49946
- const held = half.map((h) => Math.max(MIN_HALF2, h));
49947
- let oneBox;
49948
- const isHeldByOneBox = () => oneBox ?? (oneBox = isOneBox(soup));
49949
- if (hugs(points, { center, half, axes: IDENTITY_AXES, tolerance: [FIT, FIT, FIT] }) && isHeldByOneBox()) return { id, key, center, half: held, rotation: [0, 0, 0, 1] };
49950
- const turned = fitOrientedBox(points);
49951
- if (turned && hugs(points, { center: turned.center, half: turned.half, axes: axesOf(turned.rotation), tolerance: [FIT, FIT, FIT] }) && isHeldByOneBox()) return { id, key, ...tightened(points, turned) };
49952
- const coarse = soup.indices.length / 3 > COARSEN_ABOVE ? coarsen(soup) : soup;
49953
- const kept = coarse.indices.length >= COARSE_MIN_TRIANGLES * 3 ? coarse : soup;
49954
- return { id, key, center, half: held, rotation: [0, 0, 0, 1], mesh: { vertices: new Float32Array(kept.vertices), indices: new Uint32Array(kept.indices) } };
49955
- };
49956
-
49957
- // src/hull-geometry.ts
49958
- var PLANE_EPS = 1e-7;
49959
- var DIRECTIONS = (() => {
49960
- const out = [];
49961
- for (let x = -1; x <= 1; x++) for (let y = -1; y <= 1; y++) for (let z = -1; z <= 1; z++) if (x !== 0 || y !== 0 || z !== 0) out.push([x, y, z]);
49962
- return out;
49963
- })();
49964
- var faceOf = (p, a, b, c) => {
49965
- const ux = p[b * 3] - p[a * 3], uy = p[b * 3 + 1] - p[a * 3 + 1], uz = p[b * 3 + 2] - p[a * 3 + 2];
49966
- const wx = p[c * 3] - p[a * 3], wy = p[c * 3 + 1] - p[a * 3 + 1], wz = p[c * 3 + 2] - p[a * 3 + 2];
49967
- let nx = uy * wz - uz * wy, ny = uz * wx - ux * wz, nz = ux * wy - uy * wx;
49968
- const length = Math.hypot(nx, ny, nz) || 1;
49969
- nx /= length;
49970
- ny /= length;
49971
- nz /= length;
49972
- return { a, b, c, nx, ny, nz, d: nx * p[a * 3] + ny * p[a * 3 + 1] + nz * p[a * 3 + 2] };
49973
- };
49974
- var sideOf2 = (face, p, i) => face.nx * p[i * 3] + face.ny * p[i * 3 + 1] + face.nz * p[i * 3 + 2] - face.d;
49975
- var tetrahedronOf = (p, count2) => {
49976
- let a = 0;
49977
- for (let i = 1; i < count2; i++) if (p[i * 3] < p[a * 3]) a = i;
49978
- const farthest = (score) => {
49979
- let best = -1;
49980
- let bestScore = PLANE_EPS;
49981
- for (let i = 0; i < count2; i++) {
49982
- const s = score(i);
49983
- if (s > bestScore) [best, bestScore] = [i, s];
49984
- }
49985
- return best;
49986
- };
49987
- const b = farthest((i) => Math.hypot(p[i * 3] - p[a * 3], p[i * 3 + 1] - p[a * 3 + 1], p[i * 3 + 2] - p[a * 3 + 2]));
49988
- if (b < 0) return null;
49989
- const ux = p[b * 3] - p[a * 3], uy = p[b * 3 + 1] - p[a * 3 + 1], uz = p[b * 3 + 2] - p[a * 3 + 2];
49990
- const c = farthest((i) => {
49991
- const wx = p[i * 3] - p[a * 3], wy = p[i * 3 + 1] - p[a * 3 + 1], wz = p[i * 3 + 2] - p[a * 3 + 2];
49992
- return Math.hypot(uy * wz - uz * wy, uz * wx - ux * wz, ux * wy - uy * wx) / Math.hypot(ux, uy, uz);
49993
- });
49994
- if (c < 0) return null;
49995
- const base = faceOf(p, a, b, c);
49996
- const d = farthest((i) => Math.abs(sideOf2(base, p, i)));
49997
- return d < 0 ? null : [a, b, c, d];
49998
- };
49999
- var convexFaces = (points) => {
50000
- const count2 = Math.floor(points.length / 3);
50001
- if (count2 < 4) return null;
50002
- const corners = tetrahedronOf(points, count2);
50003
- if (!corners) return null;
50004
- const [a, b, c, d] = corners;
50005
- const inside = [0, 1, 2].map((k) => (points[a * 3 + k] + points[b * 3 + k] + points[c * 3 + k] + points[d * 3 + k]) / 4);
50006
- let faces = [];
50007
- const add2 = (i, j, k) => {
50008
- const face = faceOf(points, i, j, k);
50009
- const towardInside = face.nx * inside[0] + face.ny * inside[1] + face.nz * inside[2] - face.d;
50010
- faces.push(towardInside > 0 ? faceOf(points, i, k, j) : face);
50011
- };
50012
- add2(a, b, c);
50013
- add2(a, b, d);
50014
- add2(a, c, d);
50015
- add2(b, c, d);
50016
- for (let i = 0; i < count2; i++) {
50017
- if (i === a || i === b || i === c || i === d) continue;
50018
- const visible = faces.filter((face) => sideOf2(face, points, i) > PLANE_EPS);
50019
- if (visible.length === 0) continue;
50020
- const edges = /* @__PURE__ */ new Map();
50021
- const key = (from, to) => from * count2 + to;
50022
- for (const face of visible) for (const [from, to] of [[face.a, face.b], [face.b, face.c], [face.c, face.a]]) edges.set(key(from, to), [from, to]);
50023
- const kept = faces.filter((face) => !visible.includes(face));
50024
- for (const [from, to] of edges.values()) {
50025
- if (edges.has(key(to, from))) continue;
50026
- kept.push(faceOf(points, from, to, i));
50027
- }
50028
- faces = kept;
50029
- }
50030
- return faces.map((face) => [face.a, face.b, face.c]);
50031
- };
50032
- var hullVolume = (points, faces) => {
50033
- let sum = 0;
50034
- for (const [a, b, c] of faces) {
50035
- const ax = points[a * 3], ay = points[a * 3 + 1], az = points[a * 3 + 2];
50036
- const bx = points[b * 3], by = points[b * 3 + 1], bz = points[b * 3 + 2];
50037
- const cx = points[c * 3], cy = points[c * 3 + 1], cz = points[c * 3 + 2];
50038
- sum += ax * (by * cz - bz * cy) + ay * (bz * cx - bx * cz) + az * (bx * cy - by * cx);
50039
- }
50040
- return Math.abs(sum) / 6;
50041
- };
50042
- var reducePoints = (points, max) => {
50043
- const count2 = Math.floor(points.length / 3);
50044
- const picked = [];
50045
- const taken = /* @__PURE__ */ new Set();
50046
- const take = (i) => {
50047
- if (taken.has(i)) return;
50048
- taken.add(i);
50049
- picked.push(i);
50050
- };
50051
- for (const [dx, dy, dz] of DIRECTIONS) {
50052
- let best = 0;
50053
- let bestDot = -Infinity;
50054
- for (let i = 0; i < count2; i++) {
50055
- const dot2 = points[i * 3] * dx + points[i * 3 + 1] * dy + points[i * 3 + 2] * dz;
50056
- if (dot2 > bestDot) [best, bestDot] = [i, dot2];
50057
- }
50058
- take(best);
50059
- }
50060
- const away = new Float64Array(count2).fill(Infinity);
50061
- const refresh = (from) => {
50062
- for (let i = 0; i < count2; i++) {
50063
- const dist = (points[i * 3] - points[from * 3]) ** 2 + (points[i * 3 + 1] - points[from * 3 + 1]) ** 2 + (points[i * 3 + 2] - points[from * 3 + 2]) ** 2;
50064
- if (dist < away[i]) away[i] = dist;
50065
- }
50066
- };
50067
- for (const i of picked) refresh(i);
50068
- while (picked.length < Math.min(max, count2)) {
50069
- let far = -1;
50070
- let farDist = 0;
50071
- for (let i = 0; i < count2; i++) if (away[i] > farDist) [far, farDist] = [i, away[i]];
50072
- if (far < 0) break;
50073
- take(far);
50074
- refresh(far);
50075
- }
50076
- return picked.slice(0, max).flatMap((i) => [points[i * 3], points[i * 3 + 1], points[i * 3 + 2]]);
50077
- };
50078
-
50079
- // src/hull-excess.ts
50080
- var FLOATING_REACH = 0.05;
50081
- var FLOATING_AREA = 4e-3;
50082
- var STEPS = 3;
50083
- var CELL = 0.1;
50084
- var MAX_CELLS = 64;
50085
- var cellKey2 = (x, y, z) => ((x + 4096) * 8192 + (y + 4096)) * 8192 + (z + 4096);
50086
- var sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
50087
- var dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
50088
- var distanceSquared = (p, a, b, c) => {
50089
- const ab = sub(b, a), ac = sub(c, a), ap = sub(p, a);
50090
- const d1 = dot(ab, ap), d2 = dot(ac, ap);
50091
- let closest;
50092
- const at = (u, v) => [a[0] + ab[0] * u + ac[0] * v, a[1] + ab[1] * u + ac[1] * v, a[2] + ab[2] * u + ac[2] * v];
50093
- const bp = sub(p, b), d3 = dot(ab, bp), d4 = dot(ac, bp);
50094
- const cp = sub(p, c), d5 = dot(ab, cp), d6 = dot(ac, cp);
50095
- const vc = d1 * d4 - d3 * d2, vb = d5 * d2 - d1 * d6, va = d3 * d6 - d5 * d4;
50096
- if (d1 <= 0 && d2 <= 0) closest = a;
50097
- else if (d3 >= 0 && d4 <= d3) closest = b;
50098
- else if (vc <= 0 && d1 >= 0 && d3 <= 0) closest = at(d1 / (d1 - d3), 0);
50099
- else if (d6 >= 0 && d5 <= d6) closest = c;
50100
- else if (vb <= 0 && d2 >= 0 && d6 <= 0) closest = at(0, d2 / (d2 - d6));
50101
- else if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) closest = at(1 - (d4 - d3) / (d4 - d3 + (d5 - d6)), (d4 - d3) / (d4 - d3 + (d5 - d6)));
50102
- else {
50103
- const sum = va + vb + vc;
50104
- closest = at(vb / sum, vc / sum);
50105
- }
50106
- const d = sub(p, closest);
50107
- return dot(d, d);
50108
- };
50109
- var drawnIndexOf = (soup) => {
50110
- let built2 = null;
50111
- return { isNear: (x, y, z) => (built2 ?? (built2 = buildIndex(soup))).isNear(x, y, z) };
50112
- };
50113
- var buildIndex = (soup) => {
50114
- const triangles = soup.indices.length / 3;
50115
- const corner = new Float64Array(triangles * 9);
50116
- const boxes = new Float64Array(triangles * 6);
50117
- for (let t = 0; t < triangles; t++) {
50118
- for (let k = 0; k < 3; k++) {
50119
- const v = soup.indices[t * 3 + k] * 3;
50120
- for (let a = 0; a < 3; a++) corner[t * 9 + k * 3 + a] = soup.vertices[v + a];
50121
- }
50122
- for (let a = 0; a < 3; a++) {
50123
- const x = corner[t * 9 + a], y = corner[t * 9 + 3 + a], z = corner[t * 9 + 6 + a];
50124
- boxes[t * 6 + a] = Math.min(x, y, z) - FLOATING_REACH;
50125
- boxes[t * 6 + 3 + a] = Math.max(x, y, z) + FLOATING_REACH;
50126
- }
50127
- }
50128
- const cells = /* @__PURE__ */ new Map();
50129
- const wide = [];
50130
- for (let t = 0; t < triangles; t++) {
50131
- const o = t * 6;
50132
- const [x0, y0, z0, x1, y1, z1] = [0, 1, 2, 3, 4, 5].map((k) => Math.floor(boxes[o + k] / CELL));
50133
- if ((x1 - x0 + 1) * (y1 - y0 + 1) * (z1 - z0 + 1) > MAX_CELLS) {
50134
- wide.push(t);
50135
- continue;
50136
- }
50137
- for (let x = x0; x <= x1; x++) for (let y = y0; y <= y1; y++) for (let z = z0; z <= z1; z++) {
50138
- const key = cellKey2(x, y, z);
50139
- const list2 = cells.get(key);
50140
- if (list2) list2.push(t);
50141
- else cells.set(key, [t]);
50346
+ var weightOf = (stack) => stack.unitKg * stack.count;
50347
+ function createVehicleStorage(options = {}) {
50348
+ const compartments = [...options.compartments ?? [GLOVEBOX, trunkFor()]];
50349
+ const slots = new Map(compartments.map((c) => [c.id, Array.from({ length: c.slots }, () => null)]));
50350
+ const specOf = (id) => compartments.find((c) => c.id === id);
50351
+ const load = (id) => (slots.get(id) ?? []).reduce((kg, s) => kg + (s ? weightOf(s) : 0), 0);
50352
+ const reachable2 = (id, access) => {
50353
+ const spec = specOf(id);
50354
+ if (!spec) return false;
50355
+ return spec.access === "lid" ? access.lid >= 0.5 : access.gloveboxOpen && (access.seated || access.frontDoorOpen);
50356
+ };
50357
+ const place = (id, stack) => {
50358
+ const spec = specOf(id);
50359
+ const list2 = slots.get(id);
50360
+ if (!spec || !list2) return "missing";
50361
+ if (load(id) + weightOf(stack) > spec.capacityKg + 1e-9) return "too_heavy";
50362
+ const same = stack.data === void 0 ? list2.findIndex((s) => s !== null && s.itemId === stack.itemId && s.data === void 0) : -1;
50363
+ if (same >= 0) {
50364
+ const s = list2[same];
50365
+ list2[same] = { ...s, count: s.count + stack.count };
50366
+ return "ok";
50142
50367
  }
50143
- }
50144
- const isNearTriangle = (t, x, y, z) => {
50145
- const o = t * 6;
50146
- if (x < boxes[o] || y < boxes[o + 1] || z < boxes[o + 2] || x > boxes[o + 3] || y > boxes[o + 4] || z > boxes[o + 5]) return false;
50147
- const c = t * 9;
50148
- return distanceSquared([x, y, z], [corner[c], corner[c + 1], corner[c + 2]], [corner[c + 3], corner[c + 4], corner[c + 5]], [corner[c + 6], corner[c + 7], corner[c + 8]]) <= FLOATING_REACH * FLOATING_REACH;
50368
+ const free = list2.indexOf(null);
50369
+ if (free < 0) return "full";
50370
+ list2[free] = { ...stack };
50371
+ return "ok";
50149
50372
  };
50150
50373
  return {
50151
- isNear: (x, y, z) => {
50152
- for (const t of cells.get(cellKey2(Math.floor(x / CELL), Math.floor(y / CELL), Math.floor(z / CELL))) ?? []) if (isNearTriangle(t, x, y, z)) return true;
50153
- for (const t of wide) if (isNearTriangle(t, x, y, z)) return true;
50154
- return false;
50374
+ compartments,
50375
+ reachable: reachable2,
50376
+ contents: (id) => [...slots.get(id) ?? []],
50377
+ loadKg: (id) => id === void 0 ? compartments.reduce((kg, c) => kg + load(c.id), 0) : load(id),
50378
+ put(id, stack, access) {
50379
+ if (!specOf(id)) return "missing";
50380
+ if (!reachable2(id, access)) return "shut";
50381
+ return place(id, stack);
50382
+ },
50383
+ take(id, slot, access) {
50384
+ const list2 = slots.get(id);
50385
+ if (!list2 || !reachable2(id, access)) return null;
50386
+ const stack = list2[slot] ?? null;
50387
+ if (stack) list2[slot] = null;
50388
+ return stack;
50389
+ },
50390
+ stock(id, stacks) {
50391
+ return stacks.filter((s) => place(id, s) !== "ok");
50392
+ },
50393
+ clear() {
50394
+ for (const list2 of slots.values()) list2.fill(null);
50155
50395
  }
50156
50396
  };
50157
- };
50158
- var floatingAreaOf = (points, drawn) => {
50159
- const faces = convexFaces(points);
50160
- if (!faces) return 0;
50161
- const vertex = (i) => [points[i * 3], points[i * 3 + 1], points[i * 3 + 2]];
50162
- let floating = 0;
50163
- for (const [ia, ib, ic] of faces) {
50164
- const a = vertex(ia), b = vertex(ib), c = vertex(ic);
50165
- const ab = sub(b, a), ac = sub(c, a);
50166
- const area3 = Math.hypot(ab[1] * ac[2] - ab[2] * ac[1], ab[2] * ac[0] - ab[0] * ac[2], ab[0] * ac[1] - ab[1] * ac[0]) / 2;
50167
- let samples = 0, far = 0;
50168
- for (let i = 0; i <= STEPS; i++) {
50169
- for (let j = 0; i + j <= STEPS; j++) {
50170
- samples++;
50171
- const u = i / STEPS, v = j / STEPS;
50172
- if (!drawn.isNear(a[0] + ab[0] * u + ac[0] * v, a[1] + ab[1] * u + ac[1] * v, a[2] + ab[2] * u + ac[2] * v)) far++;
50173
- }
50397
+ }
50398
+ var clamp4 = (x, a, b) => Math.max(a, Math.min(b, x));
50399
+ function createWindshieldFog(options = {}) {
50400
+ const outside = options.outsideHumidity ?? 0.6;
50401
+ const breath = options.breath ?? 4e-3;
50402
+ const wet = options.wet ?? 2e-3;
50403
+ const air2 = options.air ?? { shut: 2e-3, window: 0.05, climate: 0.01, demist: 0.06 };
50404
+ const coldSpan = options.coldSpan ?? 15;
50405
+ const rates = options.rates ?? { build: 0.05, clear: 0.03, demist: 0.25 };
50406
+ const state = { humidity: outside, fog: 0 };
50407
+ return {
50408
+ state,
50409
+ step({ dt, occupants, outsideC, cabinC, rain = 0, speed = 0, windows = 0, climate, engineWarm = 1 }) {
50410
+ const exchange = air2.shut + air2.window * clamp4(windows, 0, 1) + (climate.on ? air2.climate : 0) + (climate.demist ? air2.demist : 0);
50411
+ const source = breath * Math.max(0, occupants) + wet * clamp4(rain, 0, 1) * (occupants > 0 ? 1 : 0);
50412
+ const towards = climate.on ? outside * 0.4 : outside;
50413
+ state.humidity = clamp4(state.humidity + (source - exchange * (state.humidity - towards)) * dt, 0, 1);
50414
+ const cold = Math.max(0, cabinC - outsideC) * (1 - 0.7 * clamp4(windows, 0, 1)) + 6 * clamp4(rain, 0, 1) + 2 * clamp4(speed / 27.8, 0, 1);
50415
+ const warmed = climate.demist ? cold * (1 - 0.9 * clamp4(engineWarm, 0, 1)) : cold;
50416
+ const clearUpTo = 1 - 0.5 * clamp4(warmed / coldSpan, 0, 1);
50417
+ const target = clamp4((state.humidity - clearUpTo) * 6, 0, 1);
50418
+ const down = climate.demist ? rates.demist * (0.3 + 0.7 * clamp4(engineWarm, 0, 1)) : rates.clear;
50419
+ state.fog = target > state.fog ? Math.min(target, state.fog + rates.build * dt) : Math.max(target, state.fog - down * dt);
50420
+ return state;
50421
+ },
50422
+ set(next) {
50423
+ if (next.humidity !== void 0) state.humidity = clamp4(next.humidity, 0, 1);
50424
+ if (next.fog !== void 0) state.fog = clamp4(next.fog, 0, 1);
50174
50425
  }
50175
- floating += area3 * far / samples;
50176
- }
50177
- return floating;
50178
- };
50426
+ };
50427
+ }
50179
50428
 
50180
- // src/hull-split.ts
50181
- var THIN_SECTION = 0.08;
50182
- var PROTRUSION_REACH = 0.03;
50183
- var THIN_VOLUME = 2e-4;
50184
- var BULK_BINS = 256;
50185
- var BULK_SHARE = 0.99;
50186
- var MIN_DIVISIBLE = 0.05;
50187
- var subSoup = (soup, triangles) => {
50188
- const moved = /* @__PURE__ */ new Map();
50189
- const vertices = [];
50190
- const indices = [];
50191
- for (const t of triangles) {
50192
- for (let k = 0; k < 3; k++) {
50193
- const v = soup.indices[t * 3 + k];
50194
- let at = moved.get(v);
50195
- if (at === void 0) {
50196
- at = vertices.length / 3;
50197
- moved.set(v, at);
50198
- vertices.push(soup.vertices[v * 3], soup.vertices[v * 3 + 1], soup.vertices[v * 3 + 2]);
50199
- }
50200
- indices.push(at);
50429
+ // src/collider-fit.ts
50430
+ var FIT = 0.01;
50431
+ var MIN_HALF2 = 5e-3;
50432
+ var COARSEN_ABOVE = 60;
50433
+ var COARSE_CELL = 8e-3;
50434
+ var COARSE_MIN_TRIANGLES = 12;
50435
+ var IDENTITY_AXES = [1, 0, 0, 0, 1, 0, 0, 0, 1];
50436
+ var CELL_BIAS = 4096;
50437
+ var CELL_SPAN = 8192;
50438
+ var soupOf = () => ({ vertices: [], indices: [], placed: /* @__PURE__ */ new Map() });
50439
+ var addTriangle = (soup, source, positions, corners, matrix) => {
50440
+ let placed = soup.placed.get(source);
50441
+ if (!placed) soup.placed.set(source, placed = /* @__PURE__ */ new Map());
50442
+ for (const corner of corners) {
50443
+ let at = placed.get(corner);
50444
+ if (at === void 0) {
50445
+ const x = positions[corner * 3], y = positions[corner * 3 + 1], z = positions[corner * 3 + 2];
50446
+ at = soup.vertices.length / 3;
50447
+ placed.set(corner, at);
50448
+ soup.vertices.push(
50449
+ matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12],
50450
+ matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13],
50451
+ matrix[2] * x + matrix[6] * y + matrix[10] * z + matrix[14]
50452
+ );
50201
50453
  }
50454
+ soup.indices.push(at);
50202
50455
  }
50203
- return { vertices, indices };
50204
50456
  };
50205
- var WELD3 = 1e-4;
50206
- var componentsOf = (soup) => {
50207
- const welded = /* @__PURE__ */ new Map();
50208
- const weldOf = (v) => {
50209
- const key = (Math.round(soup.vertices[v * 3] / WELD3) * 73856093 ^ Math.round(soup.vertices[v * 3 + 1] / WELD3) * 19349663 ^ Math.round(soup.vertices[v * 3 + 2] / WELD3) * 83492791) >>> 0;
50210
- let id = welded.get(key);
50211
- if (id === void 0) welded.set(key, id = welded.size);
50212
- return id;
50213
- };
50214
- const parent = [];
50215
- const rootOf = (v) => {
50216
- let root = v;
50217
- while (parent[root] !== root) root = parent[root];
50218
- for (let node = v; parent[node] !== root; ) [node, parent[node]] = [parent[node], root];
50219
- return root;
50220
- };
50221
- const corners = [];
50222
- for (let i = 0; i < soup.indices.length; i++) {
50223
- const id = weldOf(soup.indices[i]);
50224
- while (parent.length <= id) parent.push(parent.length);
50225
- corners.push(id);
50457
+ var cellKey2 = (x, y, z, cell) => ((Math.floor(x / cell) + CELL_BIAS) * CELL_SPAN + (Math.floor(y / cell) + CELL_BIAS)) * CELL_SPAN + (Math.floor(z / cell) + CELL_BIAS);
50458
+ var coarsen = (soup) => {
50459
+ const count2 = soup.vertices.length / 3;
50460
+ const cells = /* @__PURE__ */ new Map();
50461
+ const sums = [];
50462
+ const counts = [];
50463
+ const to = new Uint32Array(count2);
50464
+ for (let i = 0; i < count2; i++) {
50465
+ const x = soup.vertices[i * 3], y = soup.vertices[i * 3 + 1], z = soup.vertices[i * 3 + 2];
50466
+ const key = cellKey2(x, y, z, COARSE_CELL);
50467
+ let at = cells.get(key);
50468
+ if (at === void 0) {
50469
+ at = counts.length;
50470
+ cells.set(key, at);
50471
+ counts.push(0);
50472
+ sums.push(0, 0, 0);
50473
+ }
50474
+ to[i] = at;
50475
+ counts[at] = counts[at] + 1;
50476
+ sums[at * 3] = sums[at * 3] + x;
50477
+ sums[at * 3 + 1] = sums[at * 3 + 1] + y;
50478
+ sums[at * 3 + 2] = sums[at * 3 + 2] + z;
50226
50479
  }
50227
- for (let t = 0; t < corners.length; t += 3) {
50228
- parent[rootOf(corners[t + 1])] = rootOf(corners[t]);
50229
- parent[rootOf(corners[t + 2])] = rootOf(corners[t]);
50480
+ const best = new Float64Array(counts.length).fill(Infinity);
50481
+ const vertices = new Array(counts.length * 3).fill(0);
50482
+ for (let i = 0; i < count2; i++) {
50483
+ const at = to[i];
50484
+ const n = counts[at];
50485
+ const x = soup.vertices[i * 3], y = soup.vertices[i * 3 + 1], z = soup.vertices[i * 3 + 2];
50486
+ const d = (x - sums[at * 3] / n) ** 2 + (y - sums[at * 3 + 1] / n) ** 2 + (z - sums[at * 3 + 2] / n) ** 2;
50487
+ if (d >= best[at]) continue;
50488
+ best[at] = d;
50489
+ vertices[at * 3] = x;
50490
+ vertices[at * 3 + 1] = y;
50491
+ vertices[at * 3 + 2] = z;
50230
50492
  }
50231
- const groups = /* @__PURE__ */ new Map();
50232
- for (let t = 0; t < corners.length / 3; t++) {
50233
- const root = rootOf(corners[t * 3]);
50234
- const list2 = groups.get(root);
50235
- if (list2) list2.push(t);
50236
- else groups.set(root, [t]);
50493
+ const indices = [];
50494
+ const seen = /* @__PURE__ */ new Set();
50495
+ const stride = counts.length;
50496
+ for (let i = 0; i + 2 < soup.indices.length; i += 3) {
50497
+ const a = to[soup.indices[i]], b = to[soup.indices[i + 1]], c = to[soup.indices[i + 2]];
50498
+ if (a === b || b === c || a === c) continue;
50499
+ const lo = Math.min(a, b, c), hi = Math.max(a, b, c);
50500
+ const key = (lo * stride + (a + b + c - lo - hi)) * stride + hi;
50501
+ if (seen.has(key)) continue;
50502
+ seen.add(key);
50503
+ indices.push(a, b, c);
50237
50504
  }
50238
- return [...groups.values()];
50505
+ return { vertices, indices, placed: /* @__PURE__ */ new Map() };
50239
50506
  };
50240
- var boxOf2 = (soup) => {
50507
+ var axesOf = ([x, y, z, w]) => [
50508
+ 1 - 2 * (y * y + z * z),
50509
+ 2 * (x * y + z * w),
50510
+ 2 * (x * z - y * w),
50511
+ 2 * (x * y - z * w),
50512
+ 1 - 2 * (x * x + z * z),
50513
+ 2 * (y * z + x * w),
50514
+ 2 * (x * z + y * w),
50515
+ 2 * (y * z - x * w),
50516
+ 1 - 2 * (x * x + y * y)
50517
+ ];
50518
+ var tightened = (points, box2) => {
50519
+ const axes = axesOf(box2.rotation);
50241
50520
  const low = [Infinity, Infinity, Infinity];
50242
50521
  const high = [-Infinity, -Infinity, -Infinity];
50243
- for (let i = 0; i < soup.vertices.length; i += 3) {
50522
+ for (let i = 0; i < points.length; i += 3) {
50244
50523
  for (let k = 0; k < 3; k++) {
50245
- const value = soup.vertices[i + k];
50246
- if (value < low[k]) low[k] = value;
50247
- if (value > high[k]) high[k] = value;
50248
- }
50249
- }
50250
- return { low, high };
50251
- };
50252
- var volumeOf = (soup) => {
50253
- const points = reducePoints(soup.vertices, 64);
50254
- const faces = convexFaces(points);
50255
- return faces ? hullVolume(points, faces) : 0;
50256
- };
50257
- var AXES = [[0, 1], [0, -1], [1, 1], [1, -1], [2, 1], [2, -1]];
50258
- var tailOf = (soup) => {
50259
- const count2 = soup.indices.length / 3;
50260
- const areas = [];
50261
- const centres = [];
50262
- for (let t = 0; t < count2; t++) {
50263
- const [a, b, c] = [0, 1, 2].map((k) => soup.indices[t * 3 + k] * 3);
50264
- const v = soup.vertices;
50265
- const ux = v[b] - v[a], uy = v[b + 1] - v[a + 1], uz = v[b + 2] - v[a + 2], wx = v[c] - v[a], wy = v[c + 1] - v[a + 1], wz = v[c + 2] - v[a + 2];
50266
- areas.push(Math.hypot(uy * wz - uz * wy, uz * wx - ux * wz, ux * wy - uy * wx));
50267
- centres.push([(v[a] + v[b] + v[c]) / 3, (v[a + 1] + v[b + 1] + v[c + 1]) / 3, (v[a + 2] + v[b + 2] + v[c + 2]) / 3]);
50268
- }
50269
- const total = areas.reduce((sum, area3) => sum + area3, 0);
50270
- const tail = /* @__PURE__ */ new Set();
50271
- for (const [axis, sign2] of AXES) {
50272
- const values = centres.map((centre) => sign2 * centre[axis]);
50273
- let low = Infinity, high = -Infinity;
50274
- for (const value of values) {
50275
- if (value < low) low = value;
50276
- if (value > high) high = value;
50277
- }
50278
- const step = (high - low) / BULK_BINS || 1;
50279
- const area3 = new Float64Array(BULK_BINS + 1);
50280
- values.forEach((value, t) => {
50281
- area3[Math.floor((value - low) / step)] += areas[t];
50282
- });
50283
- let reached = 0, bin = 0;
50284
- while (bin < BULK_BINS && reached + area3[bin] < total * BULK_SHARE) reached += area3[bin++];
50285
- const bulk = low + (bin + 1) * step;
50286
- for (let t = 0; t < count2; t++) if (values[t] > bulk + PROTRUSION_REACH) tail.add(t);
50287
- }
50288
- return [...tail].sort((p, q) => p - q);
50289
- };
50290
- var protrusionsOf = (soup) => {
50291
- const taken = /* @__PURE__ */ new Set();
50292
- const out = [];
50293
- const add2 = (triangles, from) => {
50294
- out.push({ id: triangles[0], triangles, soup: from });
50295
- for (const t of triangles) taken.add(t);
50296
- };
50297
- const tail = tailOf(soup);
50298
- if (tail.length > 0) {
50299
- for (const group of componentsOf(subSoup(soup, tail))) {
50300
- const triangles = group.map((t) => tail[t]);
50301
- const part = subSoup(soup, triangles);
50302
- if (volumeOf(part) <= THIN_VOLUME) add2(triangles, part);
50524
+ const t = points[i] * axes[k * 3] + points[i + 1] * axes[k * 3 + 1] + points[i + 2] * axes[k * 3 + 2];
50525
+ if (t < low[k]) low[k] = t;
50526
+ if (t > high[k]) high[k] = t;
50303
50527
  }
50304
50528
  }
50305
- const parts = componentsOf(soup);
50306
- if (parts.length < 2) return out;
50307
- const soups = parts.map((triangles) => subSoup(soup, triangles));
50308
- const boxes = soups.map(boxOf2);
50309
- const isThin = boxes.map((box2) => box2.high.map((high, k) => high - box2.low[k]).sort((a, b) => a - b)[1] <= THIN_SECTION);
50310
- const thick = soups.filter((_, i) => !isThin[i]);
50311
- if (thick.length === 0) return out;
50312
- const bodyBox = boxOf2({ vertices: thick.flatMap((part) => part.vertices), indices: [] });
50313
- parts.forEach((triangles, i) => {
50314
- if (!isThin[i] || triangles.some((t) => taken.has(t))) return;
50315
- const box2 = boxes[i];
50316
- if ([0, 1, 2].some((k) => box2.high[k] > bodyBox.high[k] + PROTRUSION_REACH || box2.low[k] < bodyBox.low[k] - PROTRUSION_REACH)) add2(triangles, soups[i]);
50317
- });
50318
- return out;
50319
- };
50320
- var withoutProtrusions = (soup, protrusions) => {
50321
- const gone = new Set(protrusions.flatMap((protrusion) => protrusion.triangles));
50322
- return subSoup(soup, Array.from({ length: soup.indices.length / 3 }, (_, t) => t).filter((t) => !gone.has(t)));
50323
- };
50324
- var joined = (a, b) => ({ vertices: [...a.vertices, ...b.vertices], indices: [...a.indices, ...b.indices.map((i) => i + a.vertices.length / 3)] });
50325
- var unitsOf = (key, soup, taken) => {
50326
- if (!taken || taken.size === 0) return [{ key, soup }];
50327
- const off = protrusionsOf(soup).filter((protrusion) => taken.has(protrusion.id));
50328
- if (off.length === 0) return [{ key, soup }];
50329
- return [{ key, soup: withoutProtrusions(soup, off) }, ...off.map((protrusion) => ({ key: `${key}~${protrusion.id}`, soup: protrusion.soup }))];
50330
- };
50331
- var longestSide = (soup) => {
50332
- const centres = [];
50333
- for (let t = 0; t < soup.indices.length / 3; t++) {
50334
- for (let k = 0; k < 3; k++) centres.push((soup.vertices[soup.indices[t * 3] * 3 + k] + soup.vertices[soup.indices[t * 3 + 1] * 3 + k] + soup.vertices[soup.indices[t * 3 + 2] * 3 + k]) / 3);
50335
- }
50336
- const { low, high } = boxOf2({ vertices: centres, indices: [] });
50337
- let axis = 0;
50338
- for (const k of [1, 2]) if (high[k] - low[k] > high[axis] - low[axis]) axis = k;
50339
- return { axis, at: (low[axis] + high[axis]) / 2, length: high[axis] - low[axis] };
50340
- };
50341
- var cutSoup = (soup, axis, at) => {
50342
- const lo = [];
50343
- const hi = [];
50344
- for (let t = 0; t < soup.indices.length / 3; t++) {
50345
- const centre = (soup.vertices[soup.indices[t * 3] * 3 + axis] + soup.vertices[soup.indices[t * 3 + 1] * 3 + axis] + soup.vertices[soup.indices[t * 3 + 2] * 3 + axis]) / 3;
50346
- (centre < at ? lo : hi).push(t);
50347
- }
50348
- return [lo.length ? subSoup(soup, lo) : null, hi.length ? subSoup(soup, hi) : null];
50349
- };
50350
- var leavesOf = (key, soup, node, path = "") => {
50351
- if (!node) return [{ key: path ? `${key}:${path}` : key, path, soup }];
50352
- const [lo, hi] = cutSoup(soup, node.axis, node.at);
50353
- return [...lo ? leavesOf(key, lo, node.lo, `${path}0`) : [], ...hi ? leavesOf(key, hi, node.hi, `${path}1`) : []];
50354
- };
50355
-
50356
- // src/vehicle-hulls.ts
50357
- var MAX_HULL_POINTS = 64;
50358
- var FLAT_PAD = 25e-4;
50359
- var mainNormal = (soup) => {
50360
- const v = soup.vertices;
50361
- let best = [0, 1, 0];
50362
- let bestArea = 0;
50363
- for (let t = 0; t + 2 < soup.indices.length; t += 3) {
50364
- const a = soup.indices[t] * 3, b = soup.indices[t + 1] * 3, c = soup.indices[t + 2] * 3;
50365
- const ux = v[b] - v[a], uy = v[b + 1] - v[a + 1], uz = v[b + 2] - v[a + 2];
50366
- const wx = v[c] - v[a], wy = v[c + 1] - v[a + 1], wz = v[c + 2] - v[a + 2];
50367
- const cross = [uy * wz - uz * wy, uz * wx - ux * wz, ux * wy - uy * wx];
50368
- const area3 = Math.hypot(...cross);
50369
- if (area3 > bestArea) [best, bestArea] = [[cross[0] / area3, cross[1] / area3, cross[2] / area3], area3];
50370
- }
50371
- return best;
50372
- };
50373
- var spreadAlong = (points, axis) => {
50374
- let low = Infinity;
50375
- let high = -Infinity;
50376
- for (let i = 0; i < points.length; i += 3) {
50377
- const t = points[i] * axis[0] + points[i + 1] * axis[1] + points[i + 2] * axis[2];
50378
- if (t < low) low = t;
50379
- if (t > high) high = t;
50380
- }
50381
- return high - low;
50529
+ const mid = [0, 1, 2].map((k) => (low[k] + high[k]) / 2);
50530
+ const center = [0, 1, 2].map((k) => mid[0] * axes[k] + mid[1] * axes[3 + k] + mid[2] * axes[6 + k]);
50531
+ const half = [0, 1, 2].map((k) => Math.max(MIN_HALF2, (high[k] - low[k]) / 2));
50532
+ return { center, half, rotation: box2.rotation };
50382
50533
  };
50383
- var paddedAlong = (points, axis) => {
50384
- const out = [];
50534
+ var isOneBox = (soup) => fitOrientedBoxes(soup.vertices, soup.indices).length <= 1;
50535
+ var colliderOf = (id, key, soup) => {
50536
+ const points = soup.vertices;
50537
+ if (points.length < 9) return null;
50538
+ const low = [Infinity, Infinity, Infinity];
50539
+ const high = [-Infinity, -Infinity, -Infinity];
50385
50540
  for (let i = 0; i < points.length; i += 3) {
50386
- for (const sign2 of [-1, 1]) out.push(points[i] + sign2 * axis[0] * FLAT_PAD, points[i + 1] + sign2 * axis[1] * FLAT_PAD, points[i + 2] + sign2 * axis[2] * FLAT_PAD);
50387
- }
50388
- return out;
50389
- };
50390
- var acrossOf = (axis) => {
50391
- const pick = Math.abs(axis[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0];
50392
- const cross = [axis[1] * pick[2] - axis[2] * pick[1], axis[2] * pick[0] - axis[0] * pick[2], axis[0] * pick[1] - axis[1] * pick[0]];
50393
- const length = Math.hypot(...cross);
50394
- return [cross[0] / length, cross[1] / length, cross[2] / length];
50395
- };
50396
- var hullOf = (soup) => {
50397
- if (soup.vertices.length < 9) return null;
50398
- const reduced = reducePoints(soup.vertices, MAX_HULL_POINTS);
50399
- const normal = mainNormal(soup);
50400
- if (spreadAlong(reduced, normal) >= 2 * FLAT_PAD && convexFaces(reduced)) return reduced;
50401
- const thick = paddedAlong(reducePoints(reduced, MAX_HULL_POINTS / 2), normal);
50402
- if (convexFaces(thick)) return thick;
50403
- const lined = paddedAlong(paddedAlong(reducePoints(reduced, MAX_HULL_POINTS / 4), normal), acrossOf(normal));
50404
- return convexFaces(lined) ? lined : null;
50405
- };
50406
-
50407
- // src/hull-plan.ts
50408
- var newHullPlan = () => ({ cuts: /* @__PURE__ */ new Map(), taken: /* @__PURE__ */ new Map() });
50409
- var floatingOf = (soup, drawn) => {
50410
- const points = hullOf(soup);
50411
- return points ? floatingAreaOf(points, drawn) : 0;
50412
- };
50413
- var leafOf = (unit, path, soup, isDone, drawn) => {
50414
- const points = hullOf(soup);
50415
- return { unit, path, soup, points, floating: points ? floatingAreaOf(points, drawn) : 0, isDone, drawn };
50416
- };
50417
- var insertCut = (cuts, unit, path, node) => {
50418
- if (path === "") {
50419
- cuts.set(unit, node);
50420
- return;
50421
- }
50422
- let at = cuts.get(unit);
50423
- for (const step of path.slice(0, -1)) at = step === "0" ? at.lo : at.hi;
50424
- if (path.endsWith("0")) at.lo = node;
50425
- else at.hi = node;
50426
- };
50427
- var takeProtrusions = (leaf, room) => {
50428
- const all = protrusionsOf(leaf.soup);
50429
- const rest = withoutProtrusions(leaf.soup, all);
50430
- const base = floatingOf(rest, leaf.drawn);
50431
- const gains = all.map((protrusion) => ({ protrusion, gain: floatingOf(joined(rest, protrusion.soup), leaf.drawn) - base })).filter(({ gain }) => gain > FLOATING_AREA);
50432
- const taken = gains.sort((a, b) => b.gain - a.gain || a.protrusion.id - b.protrusion.id).slice(0, Math.max(0, room)).map(({ protrusion }) => protrusion);
50433
- const body = leafOf(leaf.unit, "", withoutProtrusions(leaf.soup, taken), true, leaf.drawn);
50434
- return { body, parts: taken.map((protrusion) => leafOf(`${leaf.unit}~${protrusion.id}`, "", protrusion.soup, true, leaf.drawn)), ids: taken.map((protrusion) => protrusion.id) };
50435
- };
50436
- var planDivision = (pieces, plan, maxHulls) => {
50437
- let leaves = pieces.map((piece) => leafOf(piece.key, "", piece.soup, false, drawnIndexOf(piece.soup)));
50438
- let hulls = leaves.filter((leaf) => leaf.points).length;
50439
- while (hulls < maxHulls) {
50440
- let worst = -1;
50441
- for (let i = 0; i < leaves.length; i++) {
50442
- const leaf2 = leaves[i];
50443
- if (leaf2.floating > FLOATING_AREA && (worst < 0 || leaf2.floating > leaves[worst].floating)) worst = i;
50444
- }
50445
- if (worst < 0) break;
50446
- const leaf = leaves[worst];
50447
- if (!leaf.isDone && leaf.path === "") {
50448
- const { body, parts, ids } = takeProtrusions(leaf, maxHulls - hulls);
50449
- if (ids.length > 0) plan.taken.set(leaf.unit, new Set(ids));
50450
- hulls += parts.filter((part) => part.points).length;
50451
- leaves = [...leaves.slice(0, worst), body, ...parts, ...leaves.slice(worst + 1)];
50452
- continue;
50453
- }
50454
- const { axis, at, length } = longestSide(leaf.soup);
50455
- const [lo, hi] = length < MIN_DIVISIBLE ? [null, null] : cutSoup(leaf.soup, axis, at);
50456
- if (!lo || !hi) {
50457
- leaves[worst] = { ...leaf, floating: 0 };
50458
- continue;
50541
+ for (let k = 0; k < 3; k++) {
50542
+ const v = points[i + k];
50543
+ if (v < low[k]) low[k] = v;
50544
+ if (v > high[k]) high[k] = v;
50459
50545
  }
50460
- insertCut(plan.cuts, leaf.unit, leaf.path, { axis, at, lo: null, hi: null });
50461
- const halves = [leafOf(leaf.unit, `${leaf.path}0`, lo, true, leaf.drawn), leafOf(leaf.unit, `${leaf.path}1`, hi, true, leaf.drawn)];
50462
- hulls += halves.filter((half) => half.points).length - 1;
50463
- leaves = [...leaves.slice(0, worst), ...halves, ...leaves.slice(worst + 1)];
50464
50546
  }
50465
- return leaves;
50466
- };
50467
-
50468
- // src/hull-plan-kind.ts
50469
- var solidHullsOf = (pieces) => {
50470
- const parts = /* @__PURE__ */ new Map();
50471
- for (const piece of pieces) {
50472
- let part = parts.get(piece.key);
50473
- if (!part) parts.set(piece.key, part = { vertices: [], indices: [] });
50474
- const offset = part.vertices.length / 3;
50475
- for (const value of piece.vertices) part.vertices.push(value);
50476
- for (const index of piece.indices) part.indices.push(index + offset);
50477
- }
50478
- return [...parts].map(([key, soup]) => ({ key, points: new Float32Array(hullOf(soup) ?? []) }));
50479
- };
50480
- var planHulls = (job) => {
50481
- const plan = newHullPlan();
50482
- const leaves = planDivision(job.pieces.map((piece) => ({ key: piece.key, soup: { vertices: Array.from(piece.vertices), indices: Array.from(piece.indices) } })), plan, job.maxHulls);
50483
- return {
50484
- cuts: [...plan.cuts],
50485
- taken: [...plan.taken].map(([unit, numbers]) => [unit, [...numbers]]),
50486
- solids: solidHullsOf(job.solids),
50487
- leaves: leaves.flatMap((leaf) => leaf.points ? [{ unit: leaf.unit, path: leaf.path, points: new Float32Array(leaf.points), vertices: Float64Array.from(leaf.soup.vertices) }] : [])
50488
- };
50489
- };
50490
- var WARMUP = {
50491
- pieces: [{ key: "roof#1", vertices: Float64Array.of(0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0.5, 1.4, 0.5), indices: Uint32Array.of(0, 1, 2, 0, 2, 3, 0, 1, 4) }],
50492
- solids: [{ key: "engine", vertices: Float64Array.of(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), indices: Uint32Array.of(0, 1, 2, 0, 1, 3) }],
50493
- maxHulls: 8
50547
+ const center = [(low[0] + high[0]) / 2, (low[1] + high[1]) / 2, (low[2] + high[2]) / 2];
50548
+ const half = [(high[0] - low[0]) / 2, (high[1] - low[1]) / 2, (high[2] - low[2]) / 2];
50549
+ const held = half.map((h) => Math.max(MIN_HALF2, h));
50550
+ let oneBox;
50551
+ const isHeldByOneBox = () => oneBox ?? (oneBox = isOneBox(soup));
50552
+ if (hugs(points, { center, half, axes: IDENTITY_AXES, tolerance: [FIT, FIT, FIT] }) && isHeldByOneBox()) return { id, key, center, half: held, rotation: [0, 0, 0, 1] };
50553
+ const turned = fitOrientedBox(points);
50554
+ if (turned && hugs(points, { center: turned.center, half: turned.half, axes: axesOf(turned.rotation), tolerance: [FIT, FIT, FIT] }) && isHeldByOneBox()) return { id, key, ...tightened(points, turned) };
50555
+ const coarse = soup.indices.length / 3 > COARSEN_ABOVE ? coarsen(soup) : soup;
50556
+ const kept = coarse.indices.length >= COARSE_MIN_TRIANGLES * 3 ? coarse : soup;
50557
+ return { id, key, center, half: held, rotation: [0, 0, 0, 1], mesh: { vertices: new Float32Array(kept.vertices), indices: new Uint32Array(kept.indices) } };
50494
50558
  };
50495
- var hullPlanKind = Object.freeze({
50496
- id: WORKER_KIND_ID.VEHICLE_HULL_PLAN,
50497
- kind: "task",
50498
- ...WORKER_KIND_DEFAULTS[WORKER_KIND_ID.VEHICLE_HULL_PLAN],
50499
- run: planHulls,
50500
- transferInput: (job) => [...job.pieces, ...job.solids].flatMap((piece) => [piece.vertices.buffer, piece.indices.buffer]),
50501
- transferOutput: (result) => [...result.leaves.flatMap((leaf) => [leaf.points.buffer, leaf.vertices.buffer]), ...result.solids.map((solid) => solid.points.buffer)],
50502
- warmup: WARMUP
50503
- });
50504
50559
 
50505
50560
  // src/colliders.ts
50506
50561
  var SHELL_ROLES2 = /* @__PURE__ */ new Set(["panel", "fender", "roof", "frame", "glass", "pillar", "door", "lid", "hood", "bumper"]);
@@ -50926,6 +50981,33 @@ var GameVehiclesThree = (() => {
50926
50981
  var vehicleColliders = (THREE, vehicle, frame) => createVehicleColliders(THREE, vehicle, frame).pieces();
50927
50982
  var vehicleHulls = (THREE, vehicle, frame) => createVehicleColliders(THREE, vehicle, frame, { hulls: true }).hulls();
50928
50983
 
50984
+ // src/hull-plan-cache.ts
50985
+ var createHullPlanCache = () => {
50986
+ const shared2 = /* @__PURE__ */ new Map();
50987
+ const flights = /* @__PURE__ */ new Map();
50988
+ let planned = 0, reused = 0;
50989
+ let isDisposed = false;
50990
+ return {
50991
+ get: (key) => shared2.get(key),
50992
+ set: (key, value) => {
50993
+ if (!isDisposed && !shared2.has(key)) shared2.set(key, value);
50994
+ },
50995
+ flight: (key) => flights.get(key),
50996
+ setFlight: (key, flight) => void (isDisposed || flights.set(key, flight)),
50997
+ clearFlight: (key) => void flights.delete(key),
50998
+ noteReused: () => void reused++,
50999
+ noteDivided: () => void planned++,
51000
+ stats: () => ({ models: shared2.size, planned, reused }),
51001
+ dispose: () => {
51002
+ isDisposed = true;
51003
+ shared2.clear();
51004
+ flights.clear();
51005
+ planned = 0;
51006
+ reused = 0;
51007
+ }
51008
+ };
51009
+ };
51010
+
50929
51011
  // src/vehicle-lod.ts
50930
51012
  var VEHICLE_LOD_DISTANCE = 14;
50931
51013
  var HIT_BATCH_VERTICES = 16384;
@@ -51183,6 +51265,578 @@ var GameVehiclesThree = (() => {
51183
51265
  };
51184
51266
  }
51185
51267
 
51268
+ // ../game-physics/dist/index.js
51269
+ var CONTACT_READ_STRIDE = 7;
51270
+ var KIT_WORLD = {
51271
+ fixedStep: 1 / 120,
51272
+ velocityIterations: 32,
51273
+ positionIterations: 2,
51274
+ sleepAfter: 0.5,
51275
+ sleepSpeed: 0.08,
51276
+ penetrationSlop: 2e-3,
51277
+ maxPushOut: 2e-3,
51278
+ slipSpeed: 0.02,
51279
+ contactReportSpeed: 0.5,
51280
+ maxContacts: 4096,
51281
+ maxBodies: 8192
51282
+ };
51283
+ var POSE = new Float64Array(7);
51284
+ var VELOCITY = new Float64Array(6);
51285
+ var POSE2 = new Float64Array(7);
51286
+ var GOLDEN_ANGLE = Math.PI * (1 + Math.sqrt(5));
51287
+ var isPhysicsServices = (value) => {
51288
+ if (typeof value !== "object" || value === null) return false;
51289
+ const candidate = value;
51290
+ return typeof candidate.corpses === "function" && typeof candidate.setInterest === "function" && typeof candidate.blast === "object" && typeof candidate.loop === "object" && typeof candidate.world === "object";
51291
+ };
51292
+
51293
+ // src/crash-parts-clamp.ts
51294
+ var PASSES = 8;
51295
+ var holdWithin = (old, next, slop) => {
51296
+ const faces = convexFaces(old);
51297
+ if (!faces) return next;
51298
+ const middle = [0, 1, 2].map((k) => {
51299
+ let sum = 0;
51300
+ for (let i = k; i < old.length; i += 3) sum += old[i];
51301
+ return sum / (old.length / 3);
51302
+ });
51303
+ const planes = faces.map(([a, b, c]) => {
51304
+ const ux = old[b * 3] - old[a * 3], uy = old[b * 3 + 1] - old[a * 3 + 1], uz = old[b * 3 + 2] - old[a * 3 + 2];
51305
+ const wx = old[c * 3] - old[a * 3], wy = old[c * 3 + 1] - old[a * 3 + 1], wz = old[c * 3 + 2] - old[a * 3 + 2];
51306
+ const nx = uy * wz - uz * wy, ny = uz * wx - ux * wz, nz = ux * wy - uy * wx;
51307
+ const length = Math.hypot(nx, ny, nz) || 1;
51308
+ const towardMiddle = nx * (middle[0] - old[a * 3]) + ny * (middle[1] - old[a * 3 + 1]) + nz * (middle[2] - old[a * 3 + 2]);
51309
+ const sign2 = (towardMiddle > 0 ? -1 : 1) / length;
51310
+ const normal = [nx * sign2, ny * sign2, nz * sign2];
51311
+ return { normal, offset: normal[0] * old[a * 3] + normal[1] * old[a * 3 + 1] + normal[2] * old[a * 3 + 2] + slop };
51312
+ });
51313
+ let out;
51314
+ for (let i = 0; i < next.length; i += 3) {
51315
+ const p = [next[i], next[i + 1], next[i + 2]];
51316
+ let moved = false;
51317
+ for (let pass = 0; pass < PASSES; pass++) {
51318
+ let clean = true;
51319
+ for (const { normal, offset } of planes) {
51320
+ const past = normal[0] * p[0] + normal[1] * p[1] + normal[2] * p[2] - offset;
51321
+ if (past <= 0) continue;
51322
+ p[0] = p[0] - normal[0] * past;
51323
+ p[1] = p[1] - normal[1] * past;
51324
+ p[2] = p[2] - normal[2] * past;
51325
+ moved = true;
51326
+ clean = false;
51327
+ }
51328
+ if (clean) break;
51329
+ }
51330
+ if (!moved) continue;
51331
+ out ?? (out = Float32Array.from(next));
51332
+ out[i] = p[0];
51333
+ out[i + 1] = p[1];
51334
+ out[i + 2] = p[2];
51335
+ }
51336
+ return out ?? next;
51337
+ };
51338
+
51339
+ // src/crash-parts-chassis.ts
51340
+ var HULL_SLOP = 2e-3;
51341
+ var convexOf = (points) => ({ kind: "convex", points });
51342
+ var createChassisHulls = (colliders, partIndexOf) => {
51343
+ let children = [];
51344
+ const shape = () => {
51345
+ const hulls = colliders.hulls();
51346
+ if (hulls.length === 0) throw new Error("crash parts: the car has no hulls yet (its plan is still in the worker: wait for `isHullPending()`)");
51347
+ children = hulls.map((hull, handle) => ({ handle, key: hull.key, partId: hull.id, partIndex: partIndexOf.get(hull.id) ?? -1, applied: hull.points, wanted: hull, isHeld: false }));
51348
+ return { kind: "compound", mutable: true, children: children.map((child) => ({ shape: convexOf(child.applied), position: [0, 0, 0], tag: child.partIndex })) };
51349
+ };
51350
+ const release = (world, chassis, partId) => {
51351
+ const mine = children.filter((child) => child.partId === partId);
51352
+ for (const child of mine) world.setChildShape(chassis, child.handle, null);
51353
+ children = children.filter((child) => child.partId !== partId);
51354
+ return mine.map((child) => child.applied);
51355
+ };
51356
+ const settle = (world, chassis, isTouching) => {
51357
+ const now = new Map(colliders.hulls().map((hull) => [hull.key, hull]));
51358
+ let remade = 0;
51359
+ let held = 0;
51360
+ const next = [];
51361
+ for (const child of children) {
51362
+ const hull = now.get(child.key);
51363
+ now.delete(child.key);
51364
+ if (!hull) {
51365
+ world.setChildShape(chassis, child.handle, null);
51366
+ continue;
51367
+ }
51368
+ next.push(child);
51369
+ if (hull === child.wanted && !child.isHeld) continue;
51370
+ const points = isTouching(child.applied) ? holdWithin(child.applied, hull.points, HULL_SLOP) : hull.points;
51371
+ child.wanted = hull;
51372
+ child.isHeld = points !== hull.points;
51373
+ if (child.isHeld) held++;
51374
+ if (points === child.applied) continue;
51375
+ world.setChildShape(chassis, child.handle, convexOf(points));
51376
+ child.applied = points;
51377
+ remade++;
51378
+ }
51379
+ children = next;
51380
+ return { remade, held, unplaced: now.size };
51381
+ };
51382
+ return { shape, release, settle, count: () => children.length, hasWork: () => colliders.isHullPending() || children.some((child) => child.isHeld) };
51383
+ };
51384
+
51385
+ // src/crash-parts-math.ts
51386
+ var MIN_INERTIA_PER_MASS = 1e-3;
51387
+ var rotateBy = (q, v) => {
51388
+ const [x, y, z, w] = q;
51389
+ const tx = 2 * (y * v[2] - z * v[1]);
51390
+ const ty = 2 * (z * v[0] - x * v[2]);
51391
+ const tz = 2 * (x * v[1] - y * v[0]);
51392
+ return [v[0] + w * tx + y * tz - z * ty, v[1] + w * ty + z * tx - x * tz, v[2] + w * tz + x * ty - y * tx];
51393
+ };
51394
+ var multiplyQuat = (a, b) => [
51395
+ a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1],
51396
+ a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0],
51397
+ a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3],
51398
+ a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2]
51399
+ ];
51400
+ var boxInertia = (mass, size) => [
51401
+ mass / 12 * (size[1] * size[1] + size[2] * size[2]),
51402
+ mass / 12 * (size[0] * size[0] + size[2] * size[2]),
51403
+ mass / 12 * (size[0] * size[0] + size[1] * size[1])
51404
+ ];
51405
+ var lever = (mass, d, k) => mass * (d[0] * d[0] + d[1] * d[1] + d[2] * d[2] - d[k] * d[k]);
51406
+ var withoutPart = (total, part) => {
51407
+ const mass = total.mass - part.mass;
51408
+ if (!(mass > 0)) throw new Error(`crash parts: a part of ${part.mass} kg cannot leave a body of ${total.mass} kg`);
51409
+ const centre = [0, 1, 2].map((k) => (total.mass * total.centre[k] - part.mass * part.centre[k]) / mass);
51410
+ const partOffset = [part.centre[0] - total.centre[0], part.centre[1] - total.centre[1], part.centre[2] - total.centre[2]];
51411
+ const shift = [centre[0] - total.centre[0], centre[1] - total.centre[1], centre[2] - total.centre[2]];
51412
+ const floor = mass * MIN_INERTIA_PER_MASS;
51413
+ const inertia = [0, 1, 2].map((k) => Math.max(floor, total.inertia[k] - (part.inertia[k] + lever(part.mass, partOffset, k)) - lever(mass, shift, k)));
51414
+ return { mass, centre, inertia };
51415
+ };
51416
+ var bodyMassOf = (parts) => {
51417
+ const mass = parts.reduce((sum, part) => sum + part.mass, 0);
51418
+ const centre = [0, 1, 2].map((k) => parts.reduce((sum, part) => sum + part.mass * part.box.center[k], 0) / mass);
51419
+ const inertia = [0, 1, 2].map((k) => parts.reduce((sum, part) => {
51420
+ const offset = [part.box.center[0] - centre[0], part.box.center[1] - centre[1], part.box.center[2] - centre[2]];
51421
+ return sum + boxInertia(part.mass, part.box.size)[k] + lever(part.mass, offset, k);
51422
+ }, 0));
51423
+ return { mass, centre, inertia };
51424
+ };
51425
+
51426
+ // src/crash-parts-bodies.ts
51427
+ var CLEAR_CHECK_STEPS = 30;
51428
+ var PUSH_OUT_PASSES = 3;
51429
+ var createPartBodies = (THREE, world, frame) => {
51430
+ const bodies = /* @__PURE__ */ new Map();
51431
+ const pose = new Float64Array(7);
51432
+ const speed = new Float64Array(6);
51433
+ const clearOut = [];
51434
+ const push = new Float64Array(3);
51435
+ const scratch2 = { box: new THREE.Box3(), corner: new THREE.Vector3(), position: new THREE.Vector3(), quaternion: new THREE.Quaternion(), parent: new THREE.Quaternion() };
51436
+ let steps = 0;
51437
+ let pushed = 0;
51438
+ const extentOf = (holder) => {
51439
+ holder.updateWorldMatrix(true, true);
51440
+ frame.updateWorldMatrix(true, false);
51441
+ const { box: box2, corner } = scratch2;
51442
+ box2.setFromObject(holder);
51443
+ const low = [Infinity, Infinity, Infinity];
51444
+ const high = [-Infinity, -Infinity, -Infinity];
51445
+ for (let k = 0; k < 8; k++) {
51446
+ corner.set(k & 1 ? box2.max.x : box2.min.x, k & 2 ? box2.max.y : box2.min.y, k & 4 ? box2.max.z : box2.min.z);
51447
+ frame.worldToLocal(corner);
51448
+ low[0] = Math.min(low[0], corner.x);
51449
+ low[1] = Math.min(low[1], corner.y);
51450
+ low[2] = Math.min(low[2], corner.z);
51451
+ high[0] = Math.max(high[0], corner.x);
51452
+ high[1] = Math.max(high[1], corner.y);
51453
+ high[2] = Math.max(high[2], corner.z);
51454
+ }
51455
+ return { centre: [(low[0] + high[0]) / 2, (low[1] + high[1]) / 2, (low[2] + high[2]) / 2], size: [high[0] - low[0], high[1] - low[1], high[2] - low[2]] };
51456
+ };
51457
+ const holderTurn = (holder) => {
51458
+ holder.getWorldQuaternion(scratch2.quaternion);
51459
+ frame.getWorldQuaternion(scratch2.parent);
51460
+ const turn = scratch2.parent.clone().invert().multiply(scratch2.quaternion);
51461
+ return [turn.x, turn.y, turn.z, turn.w];
51462
+ };
51463
+ const follower = (holder, offset) => ({ holder, offset, turn: holderTurn(holder) });
51464
+ const pushOutOfTheFixedWorld = (body) => {
51465
+ for (let pass = 0; pass < PUSH_OUT_PASSES; pass++) {
51466
+ const depth = world.penetration(body.id, push);
51467
+ if (depth <= 0) return;
51468
+ world.readPose(body.id, pose, 0);
51469
+ world.setPose(body.id, [pose[0] + push[0] * depth, pose[1] + push[1] * depth, pose[2] + push[2] * depth], [pose[3], pose[4], pose[5], pose[6]], true);
51470
+ pushed++;
51471
+ }
51472
+ };
51473
+ const create = ({ partIndex, mass, hulls, extent, holder, chassis, chassisMass }) => {
51474
+ world.readPose(chassis, pose, 0);
51475
+ world.readVelocity(chassis, speed, 0);
51476
+ const rotation = [pose[3], pose[4], pose[5], pose[6]];
51477
+ const lever2 = rotateBy(rotation, [extent.centre[0] - chassisMass.centre[0], extent.centre[1] - chassisMass.centre[1], extent.centre[2] - chassisMass.centre[2]]);
51478
+ const around = [speed[3], speed[4], speed[5]];
51479
+ const linear = [speed[0] + around[1] * lever2[2] - around[2] * lever2[1], speed[1] + around[2] * lever2[0] - around[0] * lever2[2], speed[2] + around[0] * lever2[1] - around[1] * lever2[0]];
51480
+ const origin = rotateBy(rotation, extent.centre);
51481
+ const shape = {
51482
+ kind: "compound",
51483
+ children: hulls.map((points) => ({ shape: { kind: "convex", points: shifted(points, extent.centre) }, position: [0, 0, 0], tag: partIndex }))
51484
+ };
51485
+ const id = world.createBody({
51486
+ shape,
51487
+ motion: "dynamic",
51488
+ mass,
51489
+ inertia: boxInertia(mass, extent.size),
51490
+ centreAtOrigin: true,
51491
+ continuous: true,
51492
+ layer: "debris",
51493
+ user: partIndex,
51494
+ position: [pose[0] + origin[0], pose[1] + origin[1], pose[2] + origin[2]],
51495
+ rotation,
51496
+ linearVelocity: linear,
51497
+ angularVelocity: around
51498
+ });
51499
+ const body = { id, partIndex, shape, extent, followers: [follower(holder, [0, 0, 0])], isIgnoring: true };
51500
+ world.ignorePair(id, chassis, true);
51501
+ pushOutOfTheFixedWorld(body);
51502
+ bodies.set(partIndex, body);
51503
+ return body;
51504
+ };
51505
+ const follow = (body, holder, extent) => {
51506
+ const base = body.extent.centre;
51507
+ body.followers.push(follower(holder, [extent.centre[0] - base[0], extent.centre[1] - base[1], extent.centre[2] - base[2]]));
51508
+ };
51509
+ const place = (body) => {
51510
+ world.readPose(body.id, pose, 0);
51511
+ const rotation = [pose[3], pose[4], pose[5], pose[6]];
51512
+ for (const { holder, offset, turn } of body.followers) {
51513
+ const at = rotateBy(rotation, offset);
51514
+ scratch2.position.set(pose[0] + at[0], pose[1] + at[1], pose[2] + at[2]);
51515
+ const turned = multiplyQuat(rotation, turn);
51516
+ const parent = holder.parent;
51517
+ if (parent) parent.worldToLocal(scratch2.position);
51518
+ holder.position.copy(scratch2.position);
51519
+ scratch2.quaternion.set(turned[0], turned[1], turned[2], turned[3]);
51520
+ if (parent) {
51521
+ parent.getWorldQuaternion(scratch2.parent);
51522
+ scratch2.quaternion.premultiply(scratch2.parent.invert());
51523
+ }
51524
+ holder.quaternion.copy(scratch2.quaternion);
51525
+ holder.updateMatrix();
51526
+ }
51527
+ };
51528
+ const release = (body, chassis) => {
51529
+ world.readPose(body.id, pose, 0);
51530
+ world.overlapShape({ kind: "box", half: [body.extent.size[0] / 2, body.extent.size[1] / 2, body.extent.size[2] / 2] }, [pose[0], pose[1], pose[2]], [pose[3], pose[4], pose[5], pose[6]], clearOut, { layers: ["vehicle"] });
51531
+ if (clearOut.includes(chassis)) return;
51532
+ world.ignorePair(body.id, chassis, false);
51533
+ body.isIgnoring = false;
51534
+ };
51535
+ return {
51536
+ extentOf,
51537
+ create,
51538
+ follow,
51539
+ bodies,
51540
+ pushedOut: () => pushed,
51541
+ step: (chassis) => {
51542
+ steps++;
51543
+ const check = steps % CLEAR_CHECK_STEPS === 0;
51544
+ for (const body of bodies.values()) {
51545
+ place(body);
51546
+ if (check && body.isIgnoring) release(body, chassis);
51547
+ }
51548
+ },
51549
+ dispose: () => {
51550
+ for (const body of bodies.values()) if (world.has(body.id)) world.removeBody(body.id);
51551
+ bodies.clear();
51552
+ }
51553
+ };
51554
+ };
51555
+ var shifted = (points, by) => {
51556
+ const out = new Float32Array(points.length);
51557
+ for (let i = 0; i < out.length; i += 3) {
51558
+ out[i] = points[i] - by[0];
51559
+ out[i + 1] = points[i + 1] - by[1];
51560
+ out[i + 2] = points[i + 2] - by[2];
51561
+ }
51562
+ return out;
51563
+ };
51564
+
51565
+ // src/crash-parts.ts
51566
+ var CONTACT_POINTS = 64;
51567
+ var SETTLE_STEPS = 30;
51568
+ var SETTLED_SPEED = 0.05;
51569
+ var TOUCH_MARGIN = 0.05;
51570
+ var createCrashParts = (options) => {
51571
+ const { THREE, world, vehicle, frame, colliders } = options;
51572
+ const parts = vehicle.model.parts;
51573
+ const partIndexOf = new Map(parts.map((part, index) => [part.id, index]));
51574
+ const chassisHulls = createChassisHulls(colliders, partIndexOf);
51575
+ const bodies = createPartBodies(THREE, world, frame);
51576
+ const pose = new Float64Array(7);
51577
+ const speed = new Float64Array(6);
51578
+ const touches = new Float32Array(CONTACT_READ_STRIDE * CONTACT_POINTS);
51579
+ const strongest = /* @__PURE__ */ new Map();
51580
+ let chassis;
51581
+ let current = options.mass;
51582
+ let calm = 0;
51583
+ let cooldown = 0;
51584
+ let isDirty = false;
51585
+ let released = 0;
51586
+ let settles = 0;
51587
+ let held = 0;
51588
+ let remade = 0;
51589
+ let unplaced = 0;
51590
+ let blows = 0;
51591
+ let events = 0;
51592
+ const hitParts = /* @__PURE__ */ new Set();
51593
+ const numbers = /* @__PURE__ */ new Map();
51594
+ const carried = (partIndex) => bodies.bodies.get(partIndex);
51595
+ const takePart = (part, partIndex, holder) => {
51596
+ const body = carried(partIndex);
51597
+ const extent = bodies.extentOf(holder);
51598
+ if (body) return bodies.follow(body, holder, extent);
51599
+ const hulls = chassisHulls.release(world, chassis, part.id);
51600
+ const solid = hulls.length > 0 ? hulls : [boxPoints(extent.size, extent.centre)];
51601
+ bodies.create({ partIndex, mass: part.mass, hulls: solid, extent, holder, chassis, chassisMass: current });
51602
+ const own = { mass: part.mass, centre: extent.centre, inertia: boxInertia(part.mass, extent.size) };
51603
+ numbers.set(part.id, own);
51604
+ current = withoutPart(current, own);
51605
+ world.setMassProperties(chassis, { mass: current.mass, inertia: current.inertia, centreOfMass: current.centre });
51606
+ released++;
51607
+ options.onPartLost?.(part);
51608
+ };
51609
+ const isTouching = (points) => {
51610
+ if (!chassis) return false;
51611
+ const count2 = world.readContacts(chassis, touches);
51612
+ if (count2 === 0) return false;
51613
+ world.readPose(chassis, pose, 0);
51614
+ let lowX = Infinity, lowY = Infinity, lowZ = Infinity;
51615
+ let highX = -Infinity, highY = -Infinity, highZ = -Infinity;
51616
+ for (let i = 0; i < points.length; i += 3) {
51617
+ const x = points[i], y = points[i + 1], z = points[i + 2];
51618
+ if (x < lowX) lowX = x;
51619
+ if (x > highX) highX = x;
51620
+ if (y < lowY) lowY = y;
51621
+ if (y > highY) highY = y;
51622
+ if (z < lowZ) lowZ = z;
51623
+ if (z > highZ) highZ = z;
51624
+ }
51625
+ const qx = -pose[3], qy = -pose[4], qz = -pose[5], qw = pose[6];
51626
+ for (let c = 0; c < count2; c++) {
51627
+ const at = c * CONTACT_READ_STRIDE;
51628
+ const vx = touches[at] - pose[0], vy = touches[at + 1] - pose[1], vz = touches[at + 2] - pose[2];
51629
+ const tx = 2 * (qy * vz - qz * vy);
51630
+ const ty = 2 * (qz * vx - qx * vz);
51631
+ const tz = 2 * (qx * vy - qy * vx);
51632
+ const x = vx + qw * tx + qy * tz - qz * ty;
51633
+ const y = vy + qw * ty + qz * tx - qx * tz;
51634
+ const z = vz + qw * tz + qx * ty - qy * tx;
51635
+ if (x >= lowX - TOUCH_MARGIN && x <= highX + TOUCH_MARGIN && y >= lowY - TOUCH_MARGIN && y <= highY + TOUCH_MARGIN && z >= lowZ - TOUCH_MARGIN && z <= highZ + TOUCH_MARGIN) return true;
51636
+ }
51637
+ return false;
51638
+ };
51639
+ const feedDamage = () => {
51640
+ const rows = world.contacts;
51641
+ strongest.clear();
51642
+ for (let i = 0; i < rows.count; i++) {
51643
+ const mine = rows.a[i] === chassis ? 0 : rows.b[i] === chassis ? 1 : -1;
51644
+ if (mine < 0) continue;
51645
+ const tag = mine === 0 ? rows.tagA[i] : rows.tagB[i];
51646
+ if (tag < 0 || tag >= parts.length) continue;
51647
+ const at = strongest.get(tag);
51648
+ if (at === void 0 || rows.approach[i] > rows.approach[at]) strongest.set(tag, i);
51649
+ }
51650
+ for (const [tag, i] of strongest) {
51651
+ const mine = rows.a[i] === chassis;
51652
+ const other = mine ? rows.b[i] : rows.a[i];
51653
+ const otherMass = world.has(other) ? world.massOf(other) : 0;
51654
+ const sign2 = mine ? 1 : -1;
51655
+ const part = parts[tag];
51656
+ const result = crashVehicle(vehicle, {
51657
+ point: [rows.point[i * 3], rows.point[i * 3 + 1], rows.point[i * 3 + 2]],
51658
+ direction: [sign2 * rows.normal[i * 3], sign2 * rows.normal[i * 3 + 1], sign2 * rows.normal[i * 3 + 2]],
51659
+ speed: rows.approach[i],
51660
+ massKg: current.mass,
51661
+ otherMassKg: otherMass > 0 ? otherMass : Infinity,
51662
+ contactWidth: Math.max(0.2, part.box.size[2]),
51663
+ source: part.id
51664
+ });
51665
+ blows++;
51666
+ events += result.events.length;
51667
+ hitParts.add(part.id);
51668
+ if (result.events.length > 0) {
51669
+ isDirty = true;
51670
+ cooldown = 0;
51671
+ }
51672
+ }
51673
+ };
51674
+ const settle = () => {
51675
+ world.readVelocity(chassis, speed, 0);
51676
+ const still = Math.hypot(speed[0], speed[1], speed[2]) < SETTLED_SPEED && Math.hypot(speed[3], speed[4], speed[5]) < SETTLED_SPEED;
51677
+ calm = still ? calm + 1 : 0;
51678
+ if (calm < SETTLE_STEPS || !(isDirty || chassisHulls.hasWork())) return;
51679
+ if (cooldown > 0) {
51680
+ cooldown--;
51681
+ return;
51682
+ }
51683
+ const done = chassisHulls.settle(world, chassis, isTouching);
51684
+ settles++;
51685
+ held += done.held;
51686
+ remade += done.remade;
51687
+ unplaced += done.unplaced;
51688
+ isDirty = done.held > 0 || colliders.isHullPending();
51689
+ cooldown = done.held > 0 && !colliders.isHullPending() ? SETTLE_STEPS : 0;
51690
+ };
51691
+ vehicle.setPartSink((part, holder) => {
51692
+ const partIndex = partIndexOf.get(part.id);
51693
+ if (chassis === void 0 || partIndex === void 0) return false;
51694
+ takePart(part, partIndex, holder);
51695
+ return true;
51696
+ });
51697
+ return {
51698
+ shape: () => chassisHulls.shape(),
51699
+ bind: (body) => {
51700
+ chassis = body;
51701
+ world.watchContacts(body, true);
51702
+ world.setMassProperties(body, { mass: current.mass, inertia: current.inertia, centreOfMass: current.centre });
51703
+ },
51704
+ step: () => {
51705
+ if (chassis === void 0) return;
51706
+ feedDamage();
51707
+ bodies.step(chassis);
51708
+ settle();
51709
+ },
51710
+ mass: () => current,
51711
+ partNumbers: () => numbers,
51712
+ partBodies: () => new Map([...bodies.bodies].map(([index, body]) => [parts[index].id, body.id])),
51713
+ stats: () => ({ released, pushedOut: bodies.pushedOut(), settles, remade, held, unplaced, blows, events, hitParts, children: chassisHulls.count() }),
51714
+ dispose: () => {
51715
+ vehicle.setPartSink(null);
51716
+ bodies.dispose();
51717
+ if (chassis !== void 0 && world.has(chassis)) world.watchContacts(chassis, false);
51718
+ }
51719
+ };
51720
+ };
51721
+ var boxPoints = (size, centre) => {
51722
+ const out = new Float32Array(24);
51723
+ for (let k = 0; k < 8; k++) {
51724
+ out[k * 3] = centre[0] + (k & 1 ? size[0] : -size[0]) / 2;
51725
+ out[k * 3 + 1] = centre[1] + (k & 2 ? size[1] : -size[1]) / 2;
51726
+ out[k * 3 + 2] = centre[2] + (k & 4 ? size[2] : -size[2]) / 2;
51727
+ }
51728
+ return out;
51729
+ };
51730
+
51731
+ // src/test-area/physical-car.ts
51732
+ var DEFAULT_HULL_CEILING = 550;
51733
+ var HALF_TURN = Math.SQRT1_2;
51734
+ var wheelChildOf = (size, center) => {
51735
+ const axis = size[0] <= size[1] && size[0] <= size[2] ? 0 : size[2] <= size[1] ? 2 : 1;
51736
+ const radius = Math.max(...size.filter((_, side2) => side2 !== axis)) / 2;
51737
+ const shape = { kind: "cylinder", halfHeight: size[axis] / 2, radius };
51738
+ if (axis === 1) return { shape, position: center };
51739
+ return { shape, position: center, rotation: axis === 0 ? [0, 0, HALF_TURN, HALF_TURN] : [HALF_TURN, 0, 0, HALF_TURN] };
51740
+ };
51741
+ var physicsServicesOf = (host) => host && isPhysicsServices(host.physics) ? host.physics : void 0;
51742
+ var physicalCarColliders = (THREE, vehicle, root, options) => createVehicleColliders(THREE, vehicle, root, {
51743
+ budget: options.budget,
51744
+ hulls: true,
51745
+ maxHulls: options.hullCeilingOf?.(options.fleetKey) ?? DEFAULT_HULL_CEILING,
51746
+ planCache: options.planCache,
51747
+ ...options.workers ? { workers: options.workers } : {}
51748
+ });
51749
+ var createPhysicalCar = ({ THREE, services, vehicle, root, colliders }) => {
51750
+ const { world } = services;
51751
+ const pose = new Float64Array(7);
51752
+ const matrix = new THREE.Matrix4();
51753
+ const parentInverse = new THREE.Matrix4();
51754
+ const position = new THREE.Vector3();
51755
+ const rotation = new THREE.Quaternion();
51756
+ const unusedScale = new THREE.Vector3();
51757
+ const wheelHandles = /* @__PURE__ */ new Map();
51758
+ let crash;
51759
+ let chassis;
51760
+ const withWheels = (hulls) => {
51761
+ if (hulls.kind !== "compound") return hulls;
51762
+ const tyres = vehicle.model.parts.filter((part) => part.role === "tyre");
51763
+ tyres.forEach((part, index) => wheelHandles.set(part.id, hulls.children.length + index));
51764
+ const inverse = new THREE.Matrix4().copy(root.matrixWorld).invert();
51765
+ const drawn = new THREE.Box3();
51766
+ const piece = new THREE.Box3();
51767
+ const centre = new THREE.Vector3();
51768
+ const size = new THREE.Vector3();
51769
+ const children = tyres.map((part) => {
51770
+ drawn.makeEmpty();
51771
+ for (const object2 of vehicle.objectsOf(part.id)) drawn.union(piece.setFromObject(object2).applyMatrix4(inverse));
51772
+ if (drawn.isEmpty()) return wheelChildOf(part.box.size, part.box.center);
51773
+ return wheelChildOf(drawn.getSize(size).toArray(), drawn.getCenter(centre).toArray());
51774
+ });
51775
+ return { ...hulls, children: [...hulls.children, ...children] };
51776
+ };
51777
+ const build = () => {
51778
+ if (!root.parent) return;
51779
+ colliders.pieces();
51780
+ if (colliders.isPending()) return;
51781
+ colliders.hulls();
51782
+ if (colliders.isHullPending()) return;
51783
+ root.updateWorldMatrix(true, false);
51784
+ root.matrixWorld.decompose(position, rotation, unusedScale);
51785
+ const mass = bodyMassOf(vehicle.model.parts);
51786
+ crash = createCrashParts({
51787
+ THREE,
51788
+ world,
51789
+ vehicle,
51790
+ frame: root,
51791
+ colliders,
51792
+ mass,
51793
+ onPartLost: (part) => {
51794
+ const handle = wheelHandles.get(part.id);
51795
+ if (handle !== void 0 && chassis !== void 0) world.setChildShape(chassis, handle, null);
51796
+ }
51797
+ });
51798
+ chassis = world.createBody({
51799
+ shape: withWheels(crash.shape()),
51800
+ motion: "dynamic",
51801
+ mass: mass.mass,
51802
+ inertia: mass.inertia,
51803
+ layer: "vehicle",
51804
+ user: 0,
51805
+ position: [position.x, position.y, position.z],
51806
+ rotation: [rotation.x, rotation.y, rotation.z, rotation.w]
51807
+ });
51808
+ crash.bind(chassis);
51809
+ };
51810
+ const follow = () => {
51811
+ world.readPose(chassis, pose, 0);
51812
+ matrix.compose(position.set(pose[0], pose[1], pose[2]), rotation.set(pose[3], pose[4], pose[5], pose[6]), unusedScale.set(1, 1, 1));
51813
+ root.parent.updateWorldMatrix(true, false);
51814
+ matrix.premultiply(parentInverse.copy(root.parent.matrixWorld).invert());
51815
+ matrix.decompose(root.position, root.quaternion, unusedScale);
51816
+ root.updateMatrixWorld(true);
51817
+ crash.step();
51818
+ };
51819
+ const stopPhase = services.loop.add({
51820
+ afterSteps: (_dt, frame) => {
51821
+ if (!chassis) return build();
51822
+ if (frame.steps > 0 && root.parent) follow();
51823
+ }
51824
+ }, "contacts");
51825
+ return {
51826
+ colliders: () => [],
51827
+ isBuilt: () => chassis !== void 0,
51828
+ chassis: () => chassis,
51829
+ parts: () => crash,
51830
+ dispose: () => {
51831
+ stopPhase();
51832
+ crash?.dispose();
51833
+ if (chassis !== void 0 && world.has(chassis)) world.removeBody(chassis);
51834
+ crash = void 0;
51835
+ chassis = void 0;
51836
+ }
51837
+ };
51838
+ };
51839
+
51186
51840
  // src/test-area/text.ts
51187
51841
  var scenarioIds = [
51188
51842
  "vehicles_9mm_windshield",
@@ -51610,7 +52264,7 @@ var GameVehiclesThree = (() => {
51610
52264
  var ZONE_COLOURS = { door: 5627221, hood: 14540083, lid: 14522675, bumper: 14505437, glass: 4500223, light: 16777215, wheel: 16742195 };
51611
52265
  var BODY_HEIGHT = 1.7;
51612
52266
  function createVehiclesTestModule(options = {}) {
51613
- const fleet = options.fleet ?? { colorFromSeed, fleetDims, installFleet, paintPalettes, paletteOf };
52267
+ const fleet = options.fleet ?? { colorFromSeed, fleetDims, hullCeilingOf: fleetHullCeilingOf, installFleet, paintPalettes, paletteOf };
51614
52268
  const locale = options.locale ?? "pt-BR";
51615
52269
  const text = TEXT[locale] ?? TEXT["pt-BR"];
51616
52270
  const keys = options.vehicles ?? DEFAULT_TEST_VEHICLES;
@@ -51624,6 +52278,8 @@ var GameVehiclesThree = (() => {
51624
52278
  const cabins = createCabinSmoke();
51625
52279
  const rainCovers = createVehicleRainCovers();
51626
52280
  let host = null;
52281
+ const physicalCars = /* @__PURE__ */ new Set();
52282
+ const planCache = createHullPlanCache();
51627
52283
  let three = null;
51628
52284
  let counter = 0;
51629
52285
  let helpersShown = "";
@@ -51694,9 +52350,25 @@ var GameVehiclesThree = (() => {
51694
52350
  const kit = r.userData.kit;
51695
52351
  const d = createVehicleDestructible(kit, r.userData.vehicle, { id, frame: root, name: text.items[itemKey] ?? key, creaseQueue, puddles: false });
51696
52352
  tapEffects(d);
51697
- const colliders = createVehicleColliders(kit.THREE, d, root, { budget: COLLIDER_BUDGET });
51698
- d.colliders = colliders.pieces;
51699
- d.collidersPending = colliders.isPending;
52353
+ const services = physicsServicesOf(host);
52354
+ if (services) {
52355
+ const colliders = physicalCarColliders(kit.THREE, d, root, { budget: COLLIDER_BUDGET, fleetKey: key, hullCeilingOf: fleet.hullCeilingOf, planCache, workers: host?.workers });
52356
+ const car = createPhysicalCar({ THREE: kit.THREE, services, vehicle: d, root, colliders });
52357
+ const disposeVehicle = d.dispose?.bind(d);
52358
+ d.dispose = () => {
52359
+ physicalCars.delete(car);
52360
+ car.dispose();
52361
+ disposeVehicle?.();
52362
+ };
52363
+ physicalCars.add(car);
52364
+ r.userData.physicalCar = car;
52365
+ d.colliders = car.colliders;
52366
+ d.collidersPending = () => false;
52367
+ } else {
52368
+ const colliders = createVehicleColliders(kit.THREE, d, root, { budget: COLLIDER_BUDGET });
52369
+ d.colliders = colliders.pieces;
52370
+ d.collidersPending = colliders.isPending;
52371
+ }
51700
52372
  const setPartPose = d.setPartPose?.bind(d);
51701
52373
  {
51702
52374
  const rests = new Map(d.describe().parts.map((part) => [part.id, part.rotation ?? [0, 0, 0]]));
@@ -52141,6 +52813,8 @@ var GameVehiclesThree = (() => {
52141
52813
  stopBlocker?.();
52142
52814
  stopCrease?.();
52143
52815
  stopLodBatch?.();
52816
+ for (const car of physicalCars) car.dispose();
52817
+ physicalCars.clear();
52144
52818
  cabins.clear(effects());
52145
52819
  rainCovers.clear();
52146
52820
  clearHelpers();
@@ -55167,482 +55841,6 @@ var GameVehiclesThree = (() => {
55167
55841
  function loadProvingModule(room, options) {
55168
55842
  return room.loadModule(createProvingModule(options));
55169
55843
  }
55170
-
55171
- // ../game-physics/dist/index.js
55172
- var CONTACT_READ_STRIDE = 7;
55173
- var KIT_WORLD = {
55174
- fixedStep: 1 / 120,
55175
- velocityIterations: 32,
55176
- positionIterations: 2,
55177
- sleepAfter: 0.5,
55178
- sleepSpeed: 0.08,
55179
- penetrationSlop: 2e-3,
55180
- maxPushOut: 2e-3,
55181
- slipSpeed: 0.02,
55182
- contactReportSpeed: 0.5,
55183
- maxContacts: 4096,
55184
- maxBodies: 8192
55185
- };
55186
- var POSE = new Float64Array(7);
55187
- var VELOCITY = new Float64Array(6);
55188
- var POSE2 = new Float64Array(7);
55189
- var GOLDEN_ANGLE = Math.PI * (1 + Math.sqrt(5));
55190
-
55191
- // src/crash-parts-clamp.ts
55192
- var PASSES = 8;
55193
- var holdWithin = (old, next, slop) => {
55194
- const faces = convexFaces(old);
55195
- if (!faces) return next;
55196
- const middle = [0, 1, 2].map((k) => {
55197
- let sum = 0;
55198
- for (let i = k; i < old.length; i += 3) sum += old[i];
55199
- return sum / (old.length / 3);
55200
- });
55201
- const planes = faces.map(([a, b, c]) => {
55202
- const ux = old[b * 3] - old[a * 3], uy = old[b * 3 + 1] - old[a * 3 + 1], uz = old[b * 3 + 2] - old[a * 3 + 2];
55203
- const wx = old[c * 3] - old[a * 3], wy = old[c * 3 + 1] - old[a * 3 + 1], wz = old[c * 3 + 2] - old[a * 3 + 2];
55204
- const nx = uy * wz - uz * wy, ny = uz * wx - ux * wz, nz = ux * wy - uy * wx;
55205
- const length = Math.hypot(nx, ny, nz) || 1;
55206
- const towardMiddle = nx * (middle[0] - old[a * 3]) + ny * (middle[1] - old[a * 3 + 1]) + nz * (middle[2] - old[a * 3 + 2]);
55207
- const sign2 = (towardMiddle > 0 ? -1 : 1) / length;
55208
- const normal = [nx * sign2, ny * sign2, nz * sign2];
55209
- return { normal, offset: normal[0] * old[a * 3] + normal[1] * old[a * 3 + 1] + normal[2] * old[a * 3 + 2] + slop };
55210
- });
55211
- let out;
55212
- for (let i = 0; i < next.length; i += 3) {
55213
- const p = [next[i], next[i + 1], next[i + 2]];
55214
- let moved = false;
55215
- for (let pass = 0; pass < PASSES; pass++) {
55216
- let clean = true;
55217
- for (const { normal, offset } of planes) {
55218
- const past = normal[0] * p[0] + normal[1] * p[1] + normal[2] * p[2] - offset;
55219
- if (past <= 0) continue;
55220
- p[0] = p[0] - normal[0] * past;
55221
- p[1] = p[1] - normal[1] * past;
55222
- p[2] = p[2] - normal[2] * past;
55223
- moved = true;
55224
- clean = false;
55225
- }
55226
- if (clean) break;
55227
- }
55228
- if (!moved) continue;
55229
- out ?? (out = Float32Array.from(next));
55230
- out[i] = p[0];
55231
- out[i + 1] = p[1];
55232
- out[i + 2] = p[2];
55233
- }
55234
- return out ?? next;
55235
- };
55236
-
55237
- // src/crash-parts-chassis.ts
55238
- var HULL_SLOP = 2e-3;
55239
- var convexOf = (points) => ({ kind: "convex", points });
55240
- var createChassisHulls = (colliders, partIndexOf) => {
55241
- let children = [];
55242
- const shape = () => {
55243
- const hulls = colliders.hulls();
55244
- if (hulls.length === 0) throw new Error("crash parts: the car has no hulls yet (its plan is still in the worker: wait for `isHullPending()`)");
55245
- children = hulls.map((hull, handle) => ({ handle, key: hull.key, partId: hull.id, partIndex: partIndexOf.get(hull.id) ?? -1, applied: hull.points, wanted: hull, isHeld: false }));
55246
- return { kind: "compound", mutable: true, children: children.map((child) => ({ shape: convexOf(child.applied), position: [0, 0, 0], tag: child.partIndex })) };
55247
- };
55248
- const release = (world, chassis, partId) => {
55249
- const mine = children.filter((child) => child.partId === partId);
55250
- for (const child of mine) world.setChildShape(chassis, child.handle, null);
55251
- children = children.filter((child) => child.partId !== partId);
55252
- return mine.map((child) => child.applied);
55253
- };
55254
- const settle = (world, chassis, isTouching) => {
55255
- const now = new Map(colliders.hulls().map((hull) => [hull.key, hull]));
55256
- let remade = 0;
55257
- let held = 0;
55258
- const next = [];
55259
- for (const child of children) {
55260
- const hull = now.get(child.key);
55261
- now.delete(child.key);
55262
- if (!hull) {
55263
- world.setChildShape(chassis, child.handle, null);
55264
- continue;
55265
- }
55266
- next.push(child);
55267
- if (hull === child.wanted && !child.isHeld) continue;
55268
- const points = isTouching(child.applied) ? holdWithin(child.applied, hull.points, HULL_SLOP) : hull.points;
55269
- child.wanted = hull;
55270
- child.isHeld = points !== hull.points;
55271
- if (child.isHeld) held++;
55272
- if (points === child.applied) continue;
55273
- world.setChildShape(chassis, child.handle, convexOf(points));
55274
- child.applied = points;
55275
- remade++;
55276
- }
55277
- children = next;
55278
- return { remade, held, unplaced: now.size };
55279
- };
55280
- return { shape, release, settle, count: () => children.length, hasWork: () => colliders.isHullPending() || children.some((child) => child.isHeld) };
55281
- };
55282
-
55283
- // src/crash-parts-math.ts
55284
- var MIN_INERTIA_PER_MASS = 1e-3;
55285
- var rotateBy = (q, v) => {
55286
- const [x, y, z, w] = q;
55287
- const tx = 2 * (y * v[2] - z * v[1]);
55288
- const ty = 2 * (z * v[0] - x * v[2]);
55289
- const tz = 2 * (x * v[1] - y * v[0]);
55290
- return [v[0] + w * tx + y * tz - z * ty, v[1] + w * ty + z * tx - x * tz, v[2] + w * tz + x * ty - y * tx];
55291
- };
55292
- var multiplyQuat = (a, b) => [
55293
- a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1],
55294
- a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0],
55295
- a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3],
55296
- a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2]
55297
- ];
55298
- var boxInertia = (mass, size) => [
55299
- mass / 12 * (size[1] * size[1] + size[2] * size[2]),
55300
- mass / 12 * (size[0] * size[0] + size[2] * size[2]),
55301
- mass / 12 * (size[0] * size[0] + size[1] * size[1])
55302
- ];
55303
- var lever = (mass, d, k) => mass * (d[0] * d[0] + d[1] * d[1] + d[2] * d[2] - d[k] * d[k]);
55304
- var withoutPart = (total, part) => {
55305
- const mass = total.mass - part.mass;
55306
- if (!(mass > 0)) throw new Error(`crash parts: a part of ${part.mass} kg cannot leave a body of ${total.mass} kg`);
55307
- const centre = [0, 1, 2].map((k) => (total.mass * total.centre[k] - part.mass * part.centre[k]) / mass);
55308
- const partOffset = [part.centre[0] - total.centre[0], part.centre[1] - total.centre[1], part.centre[2] - total.centre[2]];
55309
- const shift = [centre[0] - total.centre[0], centre[1] - total.centre[1], centre[2] - total.centre[2]];
55310
- const floor = mass * MIN_INERTIA_PER_MASS;
55311
- const inertia = [0, 1, 2].map((k) => Math.max(floor, total.inertia[k] - (part.inertia[k] + lever(part.mass, partOffset, k)) - lever(mass, shift, k)));
55312
- return { mass, centre, inertia };
55313
- };
55314
-
55315
- // src/crash-parts-bodies.ts
55316
- var CLEAR_CHECK_STEPS = 30;
55317
- var PUSH_OUT_PASSES = 3;
55318
- var createPartBodies = (THREE, world, frame) => {
55319
- const bodies = /* @__PURE__ */ new Map();
55320
- const pose = new Float64Array(7);
55321
- const speed = new Float64Array(6);
55322
- const clearOut = [];
55323
- const push = new Float64Array(3);
55324
- const scratch2 = { box: new THREE.Box3(), corner: new THREE.Vector3(), position: new THREE.Vector3(), quaternion: new THREE.Quaternion(), parent: new THREE.Quaternion() };
55325
- let steps = 0;
55326
- let pushed = 0;
55327
- const extentOf = (holder) => {
55328
- holder.updateWorldMatrix(true, true);
55329
- frame.updateWorldMatrix(true, false);
55330
- const { box: box2, corner } = scratch2;
55331
- box2.setFromObject(holder);
55332
- const low = [Infinity, Infinity, Infinity];
55333
- const high = [-Infinity, -Infinity, -Infinity];
55334
- for (let k = 0; k < 8; k++) {
55335
- corner.set(k & 1 ? box2.max.x : box2.min.x, k & 2 ? box2.max.y : box2.min.y, k & 4 ? box2.max.z : box2.min.z);
55336
- frame.worldToLocal(corner);
55337
- low[0] = Math.min(low[0], corner.x);
55338
- low[1] = Math.min(low[1], corner.y);
55339
- low[2] = Math.min(low[2], corner.z);
55340
- high[0] = Math.max(high[0], corner.x);
55341
- high[1] = Math.max(high[1], corner.y);
55342
- high[2] = Math.max(high[2], corner.z);
55343
- }
55344
- return { centre: [(low[0] + high[0]) / 2, (low[1] + high[1]) / 2, (low[2] + high[2]) / 2], size: [high[0] - low[0], high[1] - low[1], high[2] - low[2]] };
55345
- };
55346
- const holderTurn = (holder) => {
55347
- holder.getWorldQuaternion(scratch2.quaternion);
55348
- frame.getWorldQuaternion(scratch2.parent);
55349
- const turn = scratch2.parent.clone().invert().multiply(scratch2.quaternion);
55350
- return [turn.x, turn.y, turn.z, turn.w];
55351
- };
55352
- const follower = (holder, offset) => ({ holder, offset, turn: holderTurn(holder) });
55353
- const pushOutOfTheFixedWorld = (body) => {
55354
- for (let pass = 0; pass < PUSH_OUT_PASSES; pass++) {
55355
- const depth = world.penetration(body.id, push);
55356
- if (depth <= 0) return;
55357
- world.readPose(body.id, pose, 0);
55358
- world.setPose(body.id, [pose[0] + push[0] * depth, pose[1] + push[1] * depth, pose[2] + push[2] * depth], [pose[3], pose[4], pose[5], pose[6]], true);
55359
- pushed++;
55360
- }
55361
- };
55362
- const create = ({ partIndex, mass, hulls, extent, holder, chassis, chassisMass }) => {
55363
- world.readPose(chassis, pose, 0);
55364
- world.readVelocity(chassis, speed, 0);
55365
- const rotation = [pose[3], pose[4], pose[5], pose[6]];
55366
- const lever2 = rotateBy(rotation, [extent.centre[0] - chassisMass.centre[0], extent.centre[1] - chassisMass.centre[1], extent.centre[2] - chassisMass.centre[2]]);
55367
- const around = [speed[3], speed[4], speed[5]];
55368
- const linear = [speed[0] + around[1] * lever2[2] - around[2] * lever2[1], speed[1] + around[2] * lever2[0] - around[0] * lever2[2], speed[2] + around[0] * lever2[1] - around[1] * lever2[0]];
55369
- const origin = rotateBy(rotation, extent.centre);
55370
- const shape = {
55371
- kind: "compound",
55372
- children: hulls.map((points) => ({ shape: { kind: "convex", points: shifted(points, extent.centre) }, position: [0, 0, 0], tag: partIndex }))
55373
- };
55374
- const id = world.createBody({
55375
- shape,
55376
- motion: "dynamic",
55377
- mass,
55378
- inertia: boxInertia(mass, extent.size),
55379
- centreAtOrigin: true,
55380
- continuous: true,
55381
- layer: "debris",
55382
- user: partIndex,
55383
- position: [pose[0] + origin[0], pose[1] + origin[1], pose[2] + origin[2]],
55384
- rotation,
55385
- linearVelocity: linear,
55386
- angularVelocity: around
55387
- });
55388
- const body = { id, partIndex, shape, extent, followers: [follower(holder, [0, 0, 0])], isIgnoring: true };
55389
- world.ignorePair(id, chassis, true);
55390
- pushOutOfTheFixedWorld(body);
55391
- bodies.set(partIndex, body);
55392
- return body;
55393
- };
55394
- const follow = (body, holder, extent) => {
55395
- const base = body.extent.centre;
55396
- body.followers.push(follower(holder, [extent.centre[0] - base[0], extent.centre[1] - base[1], extent.centre[2] - base[2]]));
55397
- };
55398
- const place = (body) => {
55399
- world.readPose(body.id, pose, 0);
55400
- const rotation = [pose[3], pose[4], pose[5], pose[6]];
55401
- for (const { holder, offset, turn } of body.followers) {
55402
- const at = rotateBy(rotation, offset);
55403
- scratch2.position.set(pose[0] + at[0], pose[1] + at[1], pose[2] + at[2]);
55404
- const turned = multiplyQuat(rotation, turn);
55405
- const parent = holder.parent;
55406
- if (parent) parent.worldToLocal(scratch2.position);
55407
- holder.position.copy(scratch2.position);
55408
- scratch2.quaternion.set(turned[0], turned[1], turned[2], turned[3]);
55409
- if (parent) {
55410
- parent.getWorldQuaternion(scratch2.parent);
55411
- scratch2.quaternion.premultiply(scratch2.parent.invert());
55412
- }
55413
- holder.quaternion.copy(scratch2.quaternion);
55414
- holder.updateMatrix();
55415
- }
55416
- };
55417
- const release = (body, chassis) => {
55418
- world.readPose(body.id, pose, 0);
55419
- world.overlapShape({ kind: "box", half: [body.extent.size[0] / 2, body.extent.size[1] / 2, body.extent.size[2] / 2] }, [pose[0], pose[1], pose[2]], [pose[3], pose[4], pose[5], pose[6]], clearOut, { layers: ["vehicle"] });
55420
- if (clearOut.includes(chassis)) return;
55421
- world.ignorePair(body.id, chassis, false);
55422
- body.isIgnoring = false;
55423
- };
55424
- return {
55425
- extentOf,
55426
- create,
55427
- follow,
55428
- bodies,
55429
- pushedOut: () => pushed,
55430
- step: (chassis) => {
55431
- steps++;
55432
- const check = steps % CLEAR_CHECK_STEPS === 0;
55433
- for (const body of bodies.values()) {
55434
- place(body);
55435
- if (check && body.isIgnoring) release(body, chassis);
55436
- }
55437
- },
55438
- dispose: () => {
55439
- for (const body of bodies.values()) if (world.has(body.id)) world.removeBody(body.id);
55440
- bodies.clear();
55441
- }
55442
- };
55443
- };
55444
- var shifted = (points, by) => {
55445
- const out = new Float32Array(points.length);
55446
- for (let i = 0; i < out.length; i += 3) {
55447
- out[i] = points[i] - by[0];
55448
- out[i + 1] = points[i + 1] - by[1];
55449
- out[i + 2] = points[i + 2] - by[2];
55450
- }
55451
- return out;
55452
- };
55453
-
55454
- // src/crash-parts.ts
55455
- var CONTACT_POINTS = 64;
55456
- var SETTLE_STEPS = 30;
55457
- var SETTLED_SPEED = 0.05;
55458
- var TOUCH_MARGIN = 0.05;
55459
- var createCrashParts = (options) => {
55460
- const { THREE, world, vehicle, frame, colliders } = options;
55461
- const parts = vehicle.model.parts;
55462
- const partIndexOf = new Map(parts.map((part, index) => [part.id, index]));
55463
- const chassisHulls = createChassisHulls(colliders, partIndexOf);
55464
- const bodies = createPartBodies(THREE, world, frame);
55465
- const pose = new Float64Array(7);
55466
- const speed = new Float64Array(6);
55467
- const touches = new Float32Array(CONTACT_READ_STRIDE * CONTACT_POINTS);
55468
- const strongest = /* @__PURE__ */ new Map();
55469
- let chassis;
55470
- let current = options.mass;
55471
- let calm = 0;
55472
- let cooldown = 0;
55473
- let isDirty = false;
55474
- let released = 0;
55475
- let settles = 0;
55476
- let held = 0;
55477
- let remade = 0;
55478
- let unplaced = 0;
55479
- let blows = 0;
55480
- let events = 0;
55481
- const hitParts = /* @__PURE__ */ new Set();
55482
- const numbers = /* @__PURE__ */ new Map();
55483
- const carried = (partIndex) => bodies.bodies.get(partIndex);
55484
- const takePart = (part, partIndex, holder) => {
55485
- const body = carried(partIndex);
55486
- const extent = bodies.extentOf(holder);
55487
- if (body) return bodies.follow(body, holder, extent);
55488
- const hulls = chassisHulls.release(world, chassis, part.id);
55489
- const solid = hulls.length > 0 ? hulls : [boxPoints(extent.size, extent.centre)];
55490
- bodies.create({ partIndex, mass: part.mass, hulls: solid, extent, holder, chassis, chassisMass: current });
55491
- const own = { mass: part.mass, centre: extent.centre, inertia: boxInertia(part.mass, extent.size) };
55492
- numbers.set(part.id, own);
55493
- current = withoutPart(current, own);
55494
- world.setMassProperties(chassis, { mass: current.mass, inertia: current.inertia, centreOfMass: current.centre });
55495
- released++;
55496
- options.onPartLost?.(part);
55497
- };
55498
- const isTouching = (points) => {
55499
- if (!chassis) return false;
55500
- const count2 = world.readContacts(chassis, touches);
55501
- if (count2 === 0) return false;
55502
- world.readPose(chassis, pose, 0);
55503
- let lowX = Infinity, lowY = Infinity, lowZ = Infinity;
55504
- let highX = -Infinity, highY = -Infinity, highZ = -Infinity;
55505
- for (let i = 0; i < points.length; i += 3) {
55506
- const x = points[i], y = points[i + 1], z = points[i + 2];
55507
- if (x < lowX) lowX = x;
55508
- if (x > highX) highX = x;
55509
- if (y < lowY) lowY = y;
55510
- if (y > highY) highY = y;
55511
- if (z < lowZ) lowZ = z;
55512
- if (z > highZ) highZ = z;
55513
- }
55514
- const qx = -pose[3], qy = -pose[4], qz = -pose[5], qw = pose[6];
55515
- for (let c = 0; c < count2; c++) {
55516
- const at = c * CONTACT_READ_STRIDE;
55517
- const vx = touches[at] - pose[0], vy = touches[at + 1] - pose[1], vz = touches[at + 2] - pose[2];
55518
- const tx = 2 * (qy * vz - qz * vy);
55519
- const ty = 2 * (qz * vx - qx * vz);
55520
- const tz = 2 * (qx * vy - qy * vx);
55521
- const x = vx + qw * tx + qy * tz - qz * ty;
55522
- const y = vy + qw * ty + qz * tx - qx * tz;
55523
- const z = vz + qw * tz + qx * ty - qy * tx;
55524
- if (x >= lowX - TOUCH_MARGIN && x <= highX + TOUCH_MARGIN && y >= lowY - TOUCH_MARGIN && y <= highY + TOUCH_MARGIN && z >= lowZ - TOUCH_MARGIN && z <= highZ + TOUCH_MARGIN) return true;
55525
- }
55526
- return false;
55527
- };
55528
- const feedDamage = () => {
55529
- const rows = world.contacts;
55530
- strongest.clear();
55531
- for (let i = 0; i < rows.count; i++) {
55532
- const mine = rows.a[i] === chassis ? 0 : rows.b[i] === chassis ? 1 : -1;
55533
- if (mine < 0) continue;
55534
- const tag = mine === 0 ? rows.tagA[i] : rows.tagB[i];
55535
- if (tag < 0 || tag >= parts.length) continue;
55536
- const at = strongest.get(tag);
55537
- if (at === void 0 || rows.approach[i] > rows.approach[at]) strongest.set(tag, i);
55538
- }
55539
- for (const [tag, i] of strongest) {
55540
- const mine = rows.a[i] === chassis;
55541
- const other = mine ? rows.b[i] : rows.a[i];
55542
- const otherMass = world.has(other) ? world.massOf(other) : 0;
55543
- const sign2 = mine ? 1 : -1;
55544
- const part = parts[tag];
55545
- const result = crashVehicle(vehicle, {
55546
- point: [rows.point[i * 3], rows.point[i * 3 + 1], rows.point[i * 3 + 2]],
55547
- direction: [sign2 * rows.normal[i * 3], sign2 * rows.normal[i * 3 + 1], sign2 * rows.normal[i * 3 + 2]],
55548
- speed: rows.approach[i],
55549
- massKg: current.mass,
55550
- otherMassKg: otherMass > 0 ? otherMass : Infinity,
55551
- contactWidth: Math.max(0.2, part.box.size[2]),
55552
- source: part.id
55553
- });
55554
- blows++;
55555
- events += result.events.length;
55556
- hitParts.add(part.id);
55557
- if (result.events.length > 0) {
55558
- isDirty = true;
55559
- cooldown = 0;
55560
- }
55561
- }
55562
- };
55563
- const settle = () => {
55564
- world.readVelocity(chassis, speed, 0);
55565
- const still = Math.hypot(speed[0], speed[1], speed[2]) < SETTLED_SPEED && Math.hypot(speed[3], speed[4], speed[5]) < SETTLED_SPEED;
55566
- calm = still ? calm + 1 : 0;
55567
- if (calm < SETTLE_STEPS || !(isDirty || chassisHulls.hasWork())) return;
55568
- if (cooldown > 0) {
55569
- cooldown--;
55570
- return;
55571
- }
55572
- const done = chassisHulls.settle(world, chassis, isTouching);
55573
- settles++;
55574
- held += done.held;
55575
- remade += done.remade;
55576
- unplaced += done.unplaced;
55577
- isDirty = done.held > 0 || colliders.isHullPending();
55578
- cooldown = done.held > 0 && !colliders.isHullPending() ? SETTLE_STEPS : 0;
55579
- };
55580
- vehicle.setPartSink((part, holder) => {
55581
- const partIndex = partIndexOf.get(part.id);
55582
- if (chassis === void 0 || partIndex === void 0) return false;
55583
- takePart(part, partIndex, holder);
55584
- return true;
55585
- });
55586
- return {
55587
- shape: () => chassisHulls.shape(),
55588
- bind: (body) => {
55589
- chassis = body;
55590
- world.watchContacts(body, true);
55591
- world.setMassProperties(body, { mass: current.mass, inertia: current.inertia, centreOfMass: current.centre });
55592
- },
55593
- step: () => {
55594
- if (chassis === void 0) return;
55595
- feedDamage();
55596
- bodies.step(chassis);
55597
- settle();
55598
- },
55599
- mass: () => current,
55600
- partNumbers: () => numbers,
55601
- partBodies: () => new Map([...bodies.bodies].map(([index, body]) => [parts[index].id, body.id])),
55602
- stats: () => ({ released, pushedOut: bodies.pushedOut(), settles, remade, held, unplaced, blows, events, hitParts, children: chassisHulls.count() }),
55603
- dispose: () => {
55604
- vehicle.setPartSink(null);
55605
- bodies.dispose();
55606
- if (chassis !== void 0 && world.has(chassis)) world.watchContacts(chassis, false);
55607
- }
55608
- };
55609
- };
55610
- var boxPoints = (size, centre) => {
55611
- const out = new Float32Array(24);
55612
- for (let k = 0; k < 8; k++) {
55613
- out[k * 3] = centre[0] + (k & 1 ? size[0] : -size[0]) / 2;
55614
- out[k * 3 + 1] = centre[1] + (k & 2 ? size[1] : -size[1]) / 2;
55615
- out[k * 3 + 2] = centre[2] + (k & 4 ? size[2] : -size[2]) / 2;
55616
- }
55617
- return out;
55618
- };
55619
-
55620
- // src/hull-plan-cache.ts
55621
- var createHullPlanCache = () => {
55622
- const shared2 = /* @__PURE__ */ new Map();
55623
- const flights = /* @__PURE__ */ new Map();
55624
- let planned = 0, reused = 0;
55625
- let isDisposed = false;
55626
- return {
55627
- get: (key) => shared2.get(key),
55628
- set: (key, value) => {
55629
- if (!isDisposed && !shared2.has(key)) shared2.set(key, value);
55630
- },
55631
- flight: (key) => flights.get(key),
55632
- setFlight: (key, flight) => void (isDisposed || flights.set(key, flight)),
55633
- clearFlight: (key) => void flights.delete(key),
55634
- noteReused: () => void reused++,
55635
- noteDivided: () => void planned++,
55636
- stats: () => ({ models: shared2.size, planned, reused }),
55637
- dispose: () => {
55638
- isDisposed = true;
55639
- shared2.clear();
55640
- flights.clear();
55641
- planned = 0;
55642
- reused = 0;
55643
- }
55644
- };
55645
- };
55646
55844
  return __toCommonJS(index_exports);
55647
55845
  })();
55648
55846
  //# sourceMappingURL=index.global.js.map