@bendyline/molen-ambient 0.0.12 → 0.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/kernel.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import { _ as KIND_SPEED, a as AmbientRole, b as featureDrafts, c as AMBIENT_OBSERVER_COMPONENT, d as registerAmbientSchema, f as TRANSPORT_NETWORK_EXAMPLE, g as wayDraft, h as documentRunways, i as AmbientObserver, l as AMBIENT_ROLE_COMPONENT, m as documentPois, n as AMBIENT_KINDS, o as AmbientState, p as TRANSPORT_NETWORK_FORMAT, r as AmbientAgent, s as AMBIENT_AGENT_COMPONENT, t as AMBIENT_ENTITY, u as AMBIENT_STATE_COMPONENT, v as classifyFeature, x as tilePois, y as clipPolyline } from "./components-vzvNQczG.mjs";
1
+ import { _ as KIND_SPEED, a as AmbientRole, b as featureDrafts, c as AMBIENT_OBSERVER_COMPONENT, d as registerAmbientSchema, f as TRANSPORT_NETWORK_EXAMPLE, g as wayDraft, h as documentRunways, i as AmbientObserver, l as AMBIENT_ROLE_COMPONENT, m as documentPois, n as AMBIENT_KINDS, o as AmbientState, p as TRANSPORT_NETWORK_FORMAT, r as AmbientAgent, s as AMBIENT_AGENT_COMPONENT, t as AMBIENT_ENTITY, u as AMBIENT_STATE_COMPONENT, v as classifyFeature, x as tilePois, y as clipPolyline } from "./components-DJINUkXK.mjs";
2
2
  import { createRng, dmath, lookRotation, quatRotateVec3, seedToInt } from "@bendyline/molen-kernel/determinism";
3
- import { Transform, componentHandle } from "@bendyline/molen-kernel/world";
4
- import { deepMergeJson, getSchema, registerSchema, resolvePrefab, validateByKind } from "@bendyline/molen-schema";
3
+ import { Transform, componentHandle, isBoostMode } from "@bendyline/molen-kernel/world";
4
+ import { boostSpeedMultiplier, deepMergeJson, getSchema, registerSchema, resolvePrefab, validateByKind } from "@bendyline/molen-schema";
5
5
  import { z } from "zod";
6
6
  import { PATH_SURFACE_LIFT, ROAD_SURFACE_LIFT, bridgeDeckHeightFn, isArterialRoad, lineSegmentIndex, sampleTerrainLine } from "@bendyline/molen-terrain/kernel";
7
7
  //#region src/kernel/agents/idm.ts
@@ -277,13 +277,45 @@ function agentRotation(sample, pitch) {
277
277
  ]);
278
278
  }
279
279
  /** Advance every ambient agent one tick. */
280
- function stepAgents(world, env) {
280
+ function stepAgents(world, environment) {
281
+ const boosted = isBoostMode(world);
282
+ const scale = boostSpeedMultiplier(boosted);
283
+ const policy = environment.policy;
284
+ const env = {
285
+ ...environment,
286
+ speedScale: scale,
287
+ policy: scale === 1 ? policy : {
288
+ ...policy,
289
+ driver: {
290
+ ...policy.driver,
291
+ accel: policy.driver.accel * scale,
292
+ brake: policy.driver.brake * scale
293
+ },
294
+ rail: {
295
+ ...policy.rail,
296
+ accel: policy.rail.accel * scale,
297
+ brake: policy.rail.brake * scale
298
+ },
299
+ marine: {
300
+ ...policy.marine,
301
+ accel: policy.marine.accel * scale,
302
+ brake: policy.marine.brake * scale
303
+ }
304
+ }
305
+ };
281
306
  const { net } = env;
282
307
  const refs = [];
283
- for (const [id, a] of world.query(AmbientAgent)) {
308
+ for (const [id, original] of world.query(AmbientAgent)) {
309
+ const a = {
310
+ ...original,
311
+ speed: original.speed * scale / boostSpeedMultiplier(original.boosted)
312
+ };
313
+ if (boosted) a.boosted = true;
314
+ else delete a.boosted;
284
315
  const lane = a.air === void 0 ? net.lane(a.lane) : void 0;
285
316
  refs.push({
286
317
  id,
318
+ original,
287
319
  a,
288
320
  w: { ...a },
289
321
  lane,
@@ -348,10 +380,10 @@ function stepAgents(world, env) {
348
380
  for (const ref of refs) if (ref.a.air !== void 0) stepAircraft(ref, env);
349
381
  const sample = laneSample();
350
382
  for (const ref of refs) {
351
- const { a, w } = ref;
383
+ const { w } = ref;
352
384
  w.s = q4(w.s);
353
385
  w.speed = q4(w.speed);
354
- if (!agentChanged(a, w) && !ref.teleport) continue;
386
+ if (!agentChanged(ref.original, w) && ref.original.boosted === w.boosted && !ref.teleport) continue;
355
387
  world.set(ref.id, AmbientAgent, w);
356
388
  if (agentSample(net, w, sample) === void 0) continue;
357
389
  const current = world.get(ref.id, Transform);
@@ -426,7 +458,7 @@ function junctionGrants(refs, crossingArms, env) {
426
458
  for (const ref of refs) {
427
459
  const { a, lane } = ref;
428
460
  if (a.kind !== "car" || lane === void 0) continue;
429
- if (a.s < 0) {
461
+ if (a.s < 0 || (env.speedScale ?? 1) > 1 && a.s < a.length / 2) {
430
462
  const inMove = net.movement(a.prev, a.lane);
431
463
  if (inMove?.junction !== void 0) {
432
464
  const list = occupied.get(inMove.junction);
@@ -479,7 +511,8 @@ function junctionGrants(refs, crossingArms, env) {
479
511
  const key = entry.move.key;
480
512
  const inArm = dmath.floor(key / n);
481
513
  const outArm = key % n;
482
- if (entry.committed) {
514
+ const boostConflict = (env.speedScale ?? 1) > 1 && taken.some((other) => other !== key);
515
+ if (entry.committed && !boostConflict) {
483
516
  granted.add(entry.ref.id);
484
517
  taken.push(key);
485
518
  continue;
@@ -490,8 +523,8 @@ function junctionGrants(refs, crossingArms, env) {
490
523
  signalOk = arm !== void 0 && signalColor(junction, arm.group, env.tick, env.tickRate, timing) === "green";
491
524
  }
492
525
  const blocked = walkers !== void 0 && (walkers.has(outArm) || walkers.has(inArm));
493
- let ok = signalOk && !blocked && !conflictsWith(taken, key);
494
- if (!ok && signalOk && !blocked && entry.ref.a.state === "wait" && env.tick - entry.ref.a.since > deadlockTicks && !conflictsWith(inside, key)) ok = true;
526
+ let ok = signalOk && !blocked && !boostConflict && !conflictsWith(taken, key);
527
+ if (!ok && signalOk && !blocked && entry.ref.a.state === "wait" && env.tick - entry.ref.a.since > deadlockTicks && !boostConflict && !conflictsWith(inside, key)) ok = true;
495
528
  if (ok) {
496
529
  granted.add(entry.ref.id);
497
530
  taken.push(key);
@@ -572,7 +605,7 @@ function stepRoad(ref, occupancy, granted, armed, env) {
572
605
  const rx = solid.x - here.x;
573
606
  const rz = solid.z - here.z;
574
607
  const forward = rx * here.dx + rz * here.dz;
575
- if (forward <= 0 || forward > 40) continue;
608
+ if (forward <= 0 || forward > 40 * (env.speedScale ?? 1)) continue;
576
609
  if (dmath.abs(rx * here.dz - rz * here.dx) > a.width / 2 + solid.radius + .3) continue;
577
610
  const g = forward - a.length / 2 - solid.radius;
578
611
  if (g < gap) {
@@ -581,7 +614,7 @@ function stepRoad(ref, occupancy, granted, armed, env) {
581
614
  }
582
615
  }
583
616
  }
584
- const accel = idmAcceleration(a.speed, v0, gap, a.speed - leaderSpeed, p);
617
+ const accel = idmAcceleration(a.speed, v0 * (env.speedScale ?? 1), gap, a.speed - leaderSpeed, p);
585
618
  let v = dmath.max(0, a.speed + accel * dt);
586
619
  let s = a.s + v * dt;
587
620
  if (s > hardLimit) {
@@ -651,7 +684,7 @@ function stepWalker(ref, occupancy, env) {
651
684
  const { a, w } = ref;
652
685
  const lane = ref.lane;
653
686
  const edge = ref.edge;
654
- const pace = 1.15 + .5 * unit01(a.seed, 2);
687
+ const pace = (1.15 + .5 * unit01(a.seed, 2)) * (env.speedScale ?? 1);
655
688
  if (a.state === "idle") {
656
689
  const idleTicks = (3 + 15 * unit01(a.seed, 3e3 + a.hops)) * tickRate;
657
690
  if (tick - a.since < idleTicks) {
@@ -722,7 +755,7 @@ function stepTrainLead(ref, occupancy, env, cars) {
722
755
  return;
723
756
  }
724
757
  }
725
- const v0 = edge.speed * (.92 + .08 * unit01(a.seed, 1));
758
+ const v0 = edge.speed * (.92 + .08 * unit01(a.seed, 1)) * (env.speedScale ?? 1);
726
759
  const remaining = lane.length - a.s;
727
760
  let gap = Number.POSITIVE_INFINITY;
728
761
  let leaderSpeed = 0;
@@ -936,7 +969,7 @@ function stepVessel(ref, occupancy, env) {
936
969
  leaderSpeed = 0;
937
970
  limit = dmath.min(limit, dock.at);
938
971
  }
939
- const accel = idmAcceleration(a.speed, v0, gap, a.speed - leaderSpeed, p);
972
+ const accel = idmAcceleration(a.speed, v0 * (env.speedScale ?? 1), gap, a.speed - leaderSpeed, p);
940
973
  w.speed = dmath.max(0, a.speed + accel * dt);
941
974
  w.s = dmath.min(a.s + w.speed * dt, dmath.max(a.s, limit));
942
975
  if (w.s >= limit) w.speed = dmath.min(w.speed, leaderSpeed);
@@ -1729,7 +1762,9 @@ const CLASSES = [
1729
1762
  "water"
1730
1763
  ];
1731
1764
  var LaneGrid = class {
1732
- cells = /* @__PURE__ */ new Map();
1765
+ /** Rows by cell z, then cells by cell x: integer keys, no string per probed cell. */
1766
+ rows = /* @__PURE__ */ new Map();
1767
+ cellCount = 0;
1733
1768
  edgeCells = /* @__PURE__ */ new Map();
1734
1769
  /** Bumped on every change; lets callers cache derived sums. */
1735
1770
  version = 0;
@@ -1751,8 +1786,14 @@ var LaneGrid = class {
1751
1786
  const t = s1 > s0 ? (mid - s0) / (s1 - s0) : 0;
1752
1787
  const x = a[0] + (b[0] - a[0]) * t;
1753
1788
  const z = a[1] + (b[1] - a[1]) * t;
1754
- const key = `${dmath.floor(x / 64)}/${dmath.floor(z / 64)}`;
1755
- let cell = this.cells.get(key);
1789
+ const cx = dmath.floor(x / 64);
1790
+ const cz = dmath.floor(z / 64);
1791
+ let row = this.rows.get(cz);
1792
+ if (row === void 0) {
1793
+ row = /* @__PURE__ */ new Map();
1794
+ this.rows.set(cz, row);
1795
+ }
1796
+ let cell = row.get(cx);
1756
1797
  if (cell === void 0) {
1757
1798
  cell = {
1758
1799
  spans: [],
@@ -1764,10 +1805,13 @@ var LaneGrid = class {
1764
1805
  water: 0
1765
1806
  }
1766
1807
  };
1767
- this.cells.set(key, cell);
1808
+ row.set(cx, cell);
1809
+ this.cellCount++;
1768
1810
  }
1769
1811
  cell.spans.push({
1770
1812
  edge: edge.id,
1813
+ ref: edge,
1814
+ lanes: laneCounts,
1771
1815
  d0,
1772
1816
  d1,
1773
1817
  x,
@@ -1786,7 +1830,8 @@ var LaneGrid = class {
1786
1830
  meters[cls] = m;
1787
1831
  }
1788
1832
  touched.push({
1789
- key,
1833
+ cx,
1834
+ cz,
1790
1835
  meters
1791
1836
  });
1792
1837
  }
@@ -1794,32 +1839,84 @@ var LaneGrid = class {
1794
1839
  this.version++;
1795
1840
  }
1796
1841
  remove(edgeId) {
1797
- const touched = this.edgeCells.get(edgeId);
1798
- if (touched === void 0) return;
1799
- for (const { key, meters } of touched) {
1800
- const cell = this.cells.get(key);
1801
- if (cell === void 0) continue;
1802
- cell.spans = cell.spans.filter((span) => span.edge !== edgeId);
1803
- for (const cls of CLASSES) cell.meters[cls] = dmath.max(0, cell.meters[cls] - meters[cls]);
1804
- if (cell.spans.length === 0) this.cells.delete(key);
1842
+ this.removeAll([edgeId]);
1843
+ }
1844
+ /**
1845
+ * Remove edges together, each touched cell's spans filtered once: a tile's edges share its
1846
+ * cells, and filtering a dense city cell again for each of its edges held a frame 5 ms as the
1847
+ * tile left.
1848
+ */
1849
+ removeAll(edgeIds) {
1850
+ const gone = /* @__PURE__ */ new Set();
1851
+ const cells = /* @__PURE__ */ new Map();
1852
+ for (const edgeId of edgeIds) {
1853
+ const touched = this.edgeCells.get(edgeId);
1854
+ if (touched === void 0) continue;
1855
+ gone.add(edgeId);
1856
+ for (const { cx, cz, meters } of touched) {
1857
+ const row = this.rows.get(cz);
1858
+ const cell = row?.get(cx);
1859
+ if (row === void 0 || cell === void 0) continue;
1860
+ for (const cls of CLASSES) cell.meters[cls] = dmath.max(0, cell.meters[cls] - meters[cls]);
1861
+ cells.set(cell, {
1862
+ row,
1863
+ cx,
1864
+ cz
1865
+ });
1866
+ }
1867
+ this.edgeCells.delete(edgeId);
1868
+ }
1869
+ if (gone.size === 0) return;
1870
+ for (const [cell, { row, cx, cz }] of cells) {
1871
+ cell.spans = cell.spans.filter((span) => !gone.has(span.edge));
1872
+ if (cell.spans.length === 0) {
1873
+ row.delete(cx);
1874
+ this.cellCount--;
1875
+ if (row.size === 0) this.rows.delete(cz);
1876
+ }
1805
1877
  }
1806
- this.edgeCells.delete(edgeId);
1807
1878
  this.version++;
1808
1879
  }
1809
- /** Visit cells overlapping the disc of radius `r`, in a deterministic order. */
1810
- *cellsNear(x, z, r) {
1880
+ /**
1881
+ * Cells overlapping the disc of radius `r`, in row-major order (z, then x, ascending). A train
1882
+ * or boat ring spans thousands of mostly empty cells: probing each one cost a fast flight
1883
+ * several milliseconds per spawner run, so a disc larger than the populated grid walks the
1884
+ * populated cells instead and sorts the matches into the same order.
1885
+ */
1886
+ cellsNear(x, z, r) {
1811
1887
  const x0 = dmath.floor((x - r) / 64);
1812
1888
  const x1 = dmath.floor((x + r) / 64);
1813
1889
  const z0 = dmath.floor((z - r) / 64);
1814
1890
  const z1 = dmath.floor((z + r) / 64);
1815
- for (let cz = z0; cz <= z1; cz++) for (let cx = x0; cx <= x1; cx++) {
1816
- const cell = this.cells.get(`${cx}/${cz}`);
1817
- if (cell === void 0) continue;
1891
+ const within = (cx, cz) => {
1818
1892
  const nx = dmath.clamp(x, cx * 64, (cx + 1) * 64);
1819
1893
  const nz = dmath.clamp(z, cz * 64, (cz + 1) * 64);
1820
- if (dmath.hypot(nx - x, nz - z) > r) continue;
1821
- yield cell;
1894
+ return dmath.hypot(nx - x, nz - z) <= r;
1895
+ };
1896
+ const out = [];
1897
+ if ((x1 - x0 + 1) * (z1 - z0 + 1) <= this.cellCount) {
1898
+ for (let cz = z0; cz <= z1; cz++) {
1899
+ const row = this.rows.get(cz);
1900
+ if (row === void 0) continue;
1901
+ for (let cx = x0; cx <= x1; cx++) {
1902
+ const cell = row.get(cx);
1903
+ if (cell !== void 0 && within(cx, cz)) out.push(cell);
1904
+ }
1905
+ }
1906
+ return out;
1907
+ }
1908
+ const found = [];
1909
+ for (const [cz, row] of this.rows) {
1910
+ if (cz < z0 || cz > z1) continue;
1911
+ for (const [cx, cell] of row) if (cx >= x0 && cx <= x1 && within(cx, cz)) found.push({
1912
+ cx,
1913
+ cz,
1914
+ cell
1915
+ });
1822
1916
  }
1917
+ found.sort((a, b) => a.cz - b.cz || a.cx - b.cx);
1918
+ for (const entry of found) out.push(entry.cell);
1919
+ return out;
1823
1920
  }
1824
1921
  /** Lane-metres of a class in cells overlapping the disc. */
1825
1922
  laneMeters(x, z, r, cls) {
@@ -1849,7 +1946,8 @@ var LaneGrid = class {
1849
1946
  return out;
1850
1947
  }
1851
1948
  clear() {
1852
- this.cells.clear();
1949
+ this.rows.clear();
1950
+ this.cellCount = 0;
1853
1951
  this.edgeCells.clear();
1854
1952
  this.version++;
1855
1953
  }
@@ -1883,8 +1981,14 @@ var TransportNetwork = class {
1883
1981
  nodes = /* @__PURE__ */ new Map();
1884
1982
  edges = /* @__PURE__ */ new Map();
1885
1983
  lanes = /* @__PURE__ */ new Map();
1984
+ /** Each edge's lane count per class (see lanesOfClass), kept with its lanes. */
1985
+ classLanes = /* @__PURE__ */ new Map();
1886
1986
  junctions = /* @__PURE__ */ new Map();
1887
1987
  tiles = /* @__PURE__ */ new Map();
1988
+ /**
1989
+ * Border nodes by class and layer, then by rounded position (see borderCell): stitching probes
1990
+ * the 25 positions around each new border node, and a string key for each was most of it.
1991
+ */
1888
1992
  borders = /* @__PURE__ */ new Map();
1889
1993
  crossings = /* @__PURE__ */ new Map();
1890
1994
  crossingsByEdge = /* @__PURE__ */ new Map();
@@ -1924,6 +2028,13 @@ var TransportNetwork = class {
1924
2028
  lane(id) {
1925
2029
  return this.lanes.get(id);
1926
2030
  }
2031
+ /**
2032
+ * How many of an edge's lanes are of `cls`. A city's spawn ring is tens of thousands of spans,
2033
+ * and looking up every lane of each one held a spawning tick near 10 ms.
2034
+ */
2035
+ lanesOfClass(edgeId, cls) {
2036
+ return this.classLanes.get(edgeId)?.[cls] ?? 0;
2037
+ }
1927
2038
  junction(id) {
1928
2039
  return this.junctions.get(id);
1929
2040
  }
@@ -1961,9 +2072,12 @@ var TransportNetwork = class {
1961
2072
  return this.junctions.values();
1962
2073
  }
1963
2074
  runways() {
1964
- const out = [];
1965
- for (const tile of this.tiles.values()) out.push(...tile.runways);
1966
- return out;
2075
+ const unique = /* @__PURE__ */ new Map();
2076
+ for (const tile of this.tiles.values()) for (const runway of tile.runways) {
2077
+ const ends = [`${Math.round(runway.ax)},${Math.round(runway.az)}`, `${Math.round(runway.bx)},${Math.round(runway.bz)}`].sort();
2078
+ unique.set(ends.join("/"), runway);
2079
+ }
2080
+ return [...unique.values()];
1967
2081
  }
1968
2082
  /** Aerodrome POIs (and runway midpoints) across registered tiles. */
1969
2083
  aerodromes() {
@@ -1986,8 +2100,13 @@ var TransportNetwork = class {
1986
2100
  if (this.tiles.has(input.key)) this.unregisterTile(input.key);
1987
2101
  const { drafts, runways } = featureDrafts(input, { tunnels: this.tunnels });
1988
2102
  for (const draft of drafts) draft.drivingSide = input.drivingSide ?? this.traffic;
1989
- const pois = tilePois(input.pois, input.origin, input.tileSize);
1990
- const rect = [
2103
+ const pois = tilePois(input.pois, input.origin, input.tileSize, input.bounds);
2104
+ const rect = input.bounds ? [
2105
+ input.bounds[0],
2106
+ input.bounds[1],
2107
+ input.bounds[2],
2108
+ input.bounds[3]
2109
+ ] : [
1991
2110
  input.origin[0],
1992
2111
  input.origin[1],
1993
2112
  input.origin[0] + input.tileSize,
@@ -2010,24 +2129,32 @@ var TransportNetwork = class {
2010
2129
  }
2011
2130
  }
2012
2131
  }
2132
+ const gone = [];
2013
2133
  for (const edgeId of tile.edges) {
2014
2134
  const edge = this.edges.get(edgeId);
2015
2135
  if (edge === void 0) continue;
2016
2136
  for (const laneId of edge.lanes) this.lanes.delete(laneId);
2017
- this.grid.remove(edgeId);
2137
+ this.classLanes.delete(edgeId);
2138
+ gone.push(edgeId);
2018
2139
  this.edges.delete(edgeId);
2019
2140
  this.crossingsByEdge.delete(edgeId);
2020
2141
  }
2142
+ this.grid.removeAll(gone);
2021
2143
  for (const id of tile.crossings) this.crossings.delete(id);
2022
2144
  for (const nodeId of tile.nodes) {
2023
2145
  const node = this.nodes.get(nodeId);
2024
2146
  if (node === void 0) continue;
2025
2147
  this.junctions.delete(nodeId);
2026
2148
  if (node.border) {
2027
- const key = borderKey(node);
2028
- const list = this.borders.get(key)?.filter((id) => id !== nodeId) ?? [];
2029
- if (list.length === 0) this.borders.delete(key);
2030
- else this.borders.set(key, list);
2149
+ const group = borderGroup(node);
2150
+ const cells = this.borders.get(group);
2151
+ const cell = borderCell(dmath.round(node.x), dmath.round(node.z));
2152
+ const list = cells?.get(cell)?.filter((id) => id !== nodeId) ?? [];
2153
+ if (list.length > 0) cells?.set(cell, list);
2154
+ else {
2155
+ cells?.delete(cell);
2156
+ if (cells?.size === 0) this.borders.delete(group);
2157
+ }
2031
2158
  }
2032
2159
  this.nodes.delete(nodeId);
2033
2160
  }
@@ -2133,12 +2260,13 @@ var TransportNetwork = class {
2133
2260
  ys[i] = h;
2134
2261
  });
2135
2262
  else if (draft.class === "water") ys.fill(0);
2136
- else if (draft.bridge || draft.bridgeConnections?.length) {
2263
+ else if (draft.bridge || draft.bridgeConnections?.length || draft.bridgeApproachProfile?.length) {
2137
2264
  const deck = bridgeDeckHeightFn(path, heightAt, {
2138
2265
  ...draft.deckElevation !== void 0 ? { deckElevation: draft.deckElevation } : {},
2139
2266
  clearance: draft.class === "walk" ? 3 : 6,
2140
2267
  approachLift: lift,
2141
2268
  groundApproach: !draft.bridge,
2269
+ approachProfile: draft.bridgeApproachProfile,
2142
2270
  connects: [gradeRoad.has(piece.from), gradeRoad.has(piece.to)],
2143
2271
  ...draft.bridgeConnections !== void 0 ? { connections: draft.bridgeConnections } : {}
2144
2272
  });
@@ -2227,6 +2355,12 @@ var TransportNetwork = class {
2227
2355
  };
2228
2356
  this.lanes.set(id, lane);
2229
2357
  edge.lanes.push(id);
2358
+ let counts = this.classLanes.get(edge.id);
2359
+ if (counts === void 0) {
2360
+ counts = {};
2361
+ this.classLanes.set(edge.id, counts);
2362
+ }
2363
+ counts[cls] = (counts[cls] ?? 0) + 1;
2230
2364
  };
2231
2365
  if (draft.class === "road") {
2232
2366
  const total = draft.lanes;
@@ -2259,8 +2393,15 @@ var TransportNetwork = class {
2259
2393
  }
2260
2394
  }
2261
2395
  stitch(node) {
2262
- const own = borderKey(node);
2263
- const candidates = [...this.borders.get(own) ?? []];
2396
+ const group = borderGroup(node);
2397
+ let cells = this.borders.get(group);
2398
+ if (cells === void 0) {
2399
+ cells = /* @__PURE__ */ new Map();
2400
+ this.borders.set(group, cells);
2401
+ }
2402
+ const bx = dmath.round(node.x);
2403
+ const bz = dmath.round(node.z);
2404
+ const own = borderCell(bx, bz);
2264
2405
  let best;
2265
2406
  let bestDistance = 1.01;
2266
2407
  const consider = (ids, limit) => {
@@ -2274,16 +2415,13 @@ var TransportNetwork = class {
2274
2415
  }
2275
2416
  }
2276
2417
  };
2277
- consider(candidates, 1.01);
2418
+ consider(cells.get(own) ?? [], 1.01);
2278
2419
  if (best === void 0) {
2279
2420
  bestDistance = 2.01;
2280
- const [cls, layer] = own.split("/");
2281
- const bx = dmath.round(node.x);
2282
- const bz = dmath.round(node.z);
2283
- for (let ox = -2; ox <= 2; ox++) for (let oz = -2; oz <= 2; oz++) consider(this.borders.get(`${cls}/${layer}/${bx + ox}/${bz + oz}`) ?? [], 2.01);
2421
+ for (let ox = -2; ox <= 2; ox++) for (let oz = -2; oz <= 2; oz++) consider(cells.get(borderCell(bx + ox, bz + oz)) ?? [], 2.01);
2284
2422
  }
2285
- const list = this.borders.get(own);
2286
- if (list === void 0) this.borders.set(own, [node.id]);
2423
+ const list = cells.get(own);
2424
+ if (list === void 0) cells.set(own, [node.id]);
2287
2425
  else list.push(node.id);
2288
2426
  const partner = best;
2289
2427
  if (partner !== void 0) {
@@ -2420,6 +2558,16 @@ var TransportNetwork = class {
2420
2558
  }
2421
2559
  return best;
2422
2560
  }
2561
+ /** The network's sizes, without the walks `stats()` makes. */
2562
+ sizes() {
2563
+ return {
2564
+ tiles: this.tiles.size,
2565
+ nodes: this.nodes.size,
2566
+ edges: this.edges.size,
2567
+ lanes: this.lanes.size,
2568
+ junctions: this.junctions.size
2569
+ };
2570
+ }
2423
2571
  stats() {
2424
2572
  const laneKm = {
2425
2573
  road: 0,
@@ -2462,8 +2610,12 @@ var TransportNetwork = class {
2462
2610
  function q(value) {
2463
2611
  return dmath.round(value * 10);
2464
2612
  }
2465
- function borderKey(node) {
2466
- return `${node.class}/${node.layer}/${dmath.round(node.x)}/${dmath.round(node.z)}`;
2613
+ function borderGroup(node) {
2614
+ return `${node.class}/${node.layer}`;
2615
+ }
2616
+ /** A rounded border position as one number: exact for metres within 33,000 km of the origin. */
2617
+ function borderCell(x, z) {
2618
+ return (x + 2 ** 25) * 2 ** 26 + (z + 2 ** 25);
2467
2619
  }
2468
2620
  function linePath(points) {
2469
2621
  const distances = cumulative(points);
@@ -3219,7 +3371,8 @@ function spawnAgents(world, env, observer, state) {
3219
3371
  observer,
3220
3372
  rng,
3221
3373
  occupancy,
3222
- state
3374
+ state,
3375
+ candidates: /* @__PURE__ */ new Map()
3223
3376
  };
3224
3377
  const targets = {};
3225
3378
  for (const kind of AMBIENT_KINDS) targets[kind] = target(ctx, kind);
@@ -3247,9 +3400,10 @@ function target(ctx, kind) {
3247
3400
  if (kind === "train" && meters > 400) return dmath.min(c.max, dmath.max(1, dmath.round(wanted)));
3248
3401
  return dmath.min(c.max, dmath.round(wanted));
3249
3402
  }
3250
- function spawnOne(ctx, kind) {
3251
- if (kind === "aircraft") return spawnAircraft(ctx);
3252
- const { env, observer, rng } = ctx;
3403
+ function spawnCandidates(ctx, kind) {
3404
+ const cached = ctx.candidates.get(kind);
3405
+ if (cached !== void 0) return cached;
3406
+ const { env, observer } = ctx;
3253
3407
  const { net } = env;
3254
3408
  const c = classPolicy(env.policy, kind);
3255
3409
  const cls = LANE_CLASS[kind];
@@ -3258,15 +3412,29 @@ function spawnOne(ctx, kind) {
3258
3412
  const edges = [];
3259
3413
  let total = 0;
3260
3414
  for (const span of spans) {
3261
- const edge = net.edge(span.edge);
3262
- let lanes = 0;
3263
- for (const id of edge.lanes) if (net.lane(id)?.class === cls) lanes++;
3264
- let w = lanes * (span.d1 - span.d0);
3415
+ const edge = span.ref;
3416
+ let w = span.lanes[cls] * (span.d1 - span.d0);
3265
3417
  if (kind === "car") w *= SPAWN_WEIGHT[edge.kind] ?? 1;
3266
3418
  weights.push(w);
3267
3419
  edges.push(edge);
3268
3420
  total += w;
3269
3421
  }
3422
+ const candidates = {
3423
+ spans,
3424
+ edges,
3425
+ weights,
3426
+ total
3427
+ };
3428
+ ctx.candidates.set(kind, candidates);
3429
+ return candidates;
3430
+ }
3431
+ function spawnOne(ctx, kind) {
3432
+ if (kind === "aircraft") return spawnAircraft(ctx);
3433
+ const { env, observer, rng } = ctx;
3434
+ const { net } = env;
3435
+ const c = classPolicy(env.policy, kind);
3436
+ const cls = LANE_CLASS[kind];
3437
+ const { spans, edges, weights, total } = spawnCandidates(ctx, kind);
3270
3438
  if (total <= 0) return false;
3271
3439
  const types = env.types[kind === "pedestrian" ? "pedestrian" : kind];
3272
3440
  for (let attempt = 0; attempt < 6; attempt++) {
@@ -3413,8 +3581,8 @@ function spawnAircraft(ctx) {
3413
3581
  const width = vehicle?.width ?? 36;
3414
3582
  let corridor;
3415
3583
  let speed = vehicle?.cruise ?? 75 + 55 * rng.next();
3416
- const runways = env.net.runways().filter((r) => dmath.hypot((r.ax + r.bx) / 2 - observer.x, (r.az + r.bz) / 2 - observer.z) < 6e3);
3417
- if (runways.length > 0 && rng.next() < .4) {
3584
+ const runways = env.net.runways().filter((r) => dmath.hypot((r.ax + r.bx) / 2 - observer.x, (r.az + r.bz) / 2 - observer.z) < 6e3 && dmath.hypot(r.bx - r.ax, r.bz - r.az) >= dmath.max(350, length * 35));
3585
+ if (runways.length > 0 && rng.next() < .85) {
3418
3586
  const runway = runways[rng.int(runways.length)];
3419
3587
  const flip = rng.next() < .5;
3420
3588
  const ax = flip ? runway.bx : runway.ax;
@@ -3597,6 +3765,43 @@ function installAmbient(world, options = {}) {
3597
3765
  for (const change of pending.splice(0)) if (change.op === "add") network.registerTile(change.tile);
3598
3766
  else network.unregisterTile(change.key);
3599
3767
  };
3768
+ const perTick = options.registrationsPerTick ?? Number.POSITIVE_INFINITY;
3769
+ const removalsPerTick = options.removalsPerTick ?? Number.POSITIVE_INFINITY;
3770
+ /**
3771
+ * The tick's share of the queue, in queue order: up to `removalsPerTick` removals and up to
3772
+ * `perTick` registrations. Removals do not wait behind registrations (a key's own queued
3773
+ * registration was cancelled when its removal was queued, so the two never meet), but a key's
3774
+ * registration does wait behind its own removal when that is left for a later tick.
3775
+ */
3776
+ const flushTick = () => {
3777
+ if (perTick === Number.POSITIVE_INFINITY && removalsPerTick === Number.POSITIVE_INFINITY) {
3778
+ flush();
3779
+ return;
3780
+ }
3781
+ let added = 0;
3782
+ let removed = 0;
3783
+ let write = 0;
3784
+ let held;
3785
+ for (const change of pending) {
3786
+ const key = change.op === "add" ? change.tile.key : change.key;
3787
+ if (held?.has(key) !== true) {
3788
+ if (change.op === "remove" && removed < removalsPerTick) {
3789
+ removed++;
3790
+ network.unregisterTile(change.key);
3791
+ continue;
3792
+ }
3793
+ if (change.op === "add" && added < perTick) {
3794
+ added++;
3795
+ network.registerTile(change.tile);
3796
+ continue;
3797
+ }
3798
+ }
3799
+ held ??= /* @__PURE__ */ new Set();
3800
+ held.add(key);
3801
+ pending[write++] = change;
3802
+ }
3803
+ pending.length = write;
3804
+ };
3600
3805
  const writeState = (patch) => {
3601
3806
  const next = {
3602
3807
  ...world.get("$ambient", AmbientState) ?? {
@@ -3610,7 +3815,7 @@ function installAmbient(world, options = {}) {
3610
3815
  world.set(AMBIENT_ENTITY, AmbientState, next);
3611
3816
  };
3612
3817
  world.addSystem((w, ctx) => {
3613
- flush();
3818
+ flushTick();
3614
3819
  const state = w.get(AMBIENT_ENTITY, AmbientState);
3615
3820
  const observer = resolveObserver(w, state);
3616
3821
  const policy = observerPolicy(effectivePolicy(), observer);
@@ -3703,6 +3908,10 @@ function installAmbient(world, options = {}) {
3703
3908
  });
3704
3909
  },
3705
3910
  unregisterTile(key) {
3911
+ for (let i = pending.length - 1; i >= 0; i--) {
3912
+ const change = pending[i];
3913
+ if (change?.op === "add" && change.tile.key === key) pending.splice(i, 1);
3914
+ }
3706
3915
  pending.push({
3707
3916
  op: "remove",
3708
3917
  key
@@ -4263,7 +4472,10 @@ const wildlifeSpeciesSchema = z.strictObject({
4263
4472
  accent: color,
4264
4473
  details: z.array(z.enum([
4265
4474
  "antlers",
4475
+ "palmate",
4266
4476
  "horns",
4477
+ "straight-horns",
4478
+ "mane",
4267
4479
  "long-neck",
4268
4480
  "bushy-tail",
4269
4481
  "stripes",
@@ -22,7 +22,7 @@ interface WildlifeSpecies {
22
22
  width: number;
23
23
  color: string;
24
24
  accent: string;
25
- details: Array<"antlers" | "horns" | "long-neck" | "bushy-tail" | "stripes" | "spots" | "wader" | "waterfowl" | "raptor" | "parrot" | "long-tail">;
25
+ details: Array<"antlers" | "palmate" | "horns" | "straight-horns" | "mane" | "long-neck" | "bushy-tail" | "stripes" | "spots" | "wader" | "waterfowl" | "raptor" | "parrot" | "long-tail">;
26
26
  };
27
27
  motion: WildlifeMotion;
28
28
  /** Meters per second. This is ambient travel, not maximum running speed. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bendyline/molen-ambient",
3
- "version": "0.0.12",
3
+ "version": "0.0.13",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -41,14 +41,14 @@
41
41
  "dist"
42
42
  ],
43
43
  "dependencies": {
44
- "@bendyline/molen-figures": "0.0.10",
45
- "@bendyline/molen-kernel": "0.0.8",
46
- "@bendyline/molen-schema": "0.0.8",
47
- "@bendyline/molen-terrain": "0.0.12",
44
+ "@bendyline/molen-figures": "0.0.11",
45
+ "@bendyline/molen-kernel": "0.0.9",
46
+ "@bendyline/molen-schema": "0.0.9",
47
+ "@bendyline/molen-terrain": "0.0.13",
48
48
  "zod": "^4.6.5"
49
49
  },
50
50
  "peerDependencies": {
51
- "@bendyline/molen-client": "0.0.10",
51
+ "@bendyline/molen-client": "0.0.11",
52
52
  "three": ">=0.184.0 <0.187.0"
53
53
  },
54
54
  "peerDependenciesMeta": {
@@ -60,7 +60,7 @@
60
60
  }
61
61
  },
62
62
  "devDependencies": {
63
- "@bendyline/molen-client": "0.0.10",
63
+ "@bendyline/molen-client": "0.0.11",
64
64
  "@biomejs/biome": "^2.5.0",
65
65
  "@types/three": "0.184.0",
66
66
  "fast-check": "^3.23.2",