@bendyline/molen-ambient 0.0.3

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.
@@ -0,0 +1,3804 @@
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-CupqU6fR.mjs";
2
+ import { createRng, dmath, lookRotation, quatRotateVec3, seedToInt } from "@bendyline/molen-kernel/determinism";
3
+ import { Transform, componentHandle } from "@bendyline/molen-kernel/world";
4
+ import { deepMergeJson, resolvePrefab, validateByKind } from "@bendyline/molen-schema";
5
+ import { PATH_SURFACE_LIFT, ROAD_SURFACE_LIFT, bridgeDeckHeightFn, lineSegmentIndex, sampleTerrainLine } from "@bendyline/molen-terrain/kernel";
6
+ //#region src/kernel/agents/idm.ts
7
+ /** Intelligent Driver Model: acceleration from speed, desired speed and the gap to a leader. */
8
+ /**
9
+ * IDM acceleration. `gap` is the bumper-to-bumper distance to the leader (Infinity when free),
10
+ * `dv` the closing speed (own speed minus the leader's).
11
+ */
12
+ function idmAcceleration(v, v0, gap, dv, p) {
13
+ const ratio = v0 > .01 ? v / v0 : 2;
14
+ const r2 = ratio * ratio;
15
+ const free = 1 - r2 * r2;
16
+ if (!Number.isFinite(gap)) return p.accel * free;
17
+ const desired = p.gap + dmath.max(0, v * p.headway + v * dv / (2 * dmath.sqrt(p.accel * p.brake)));
18
+ const g = dmath.max(gap, .01);
19
+ const interaction = desired / g * (desired / g);
20
+ return p.accel * (free - interaction);
21
+ }
22
+ /** Distance needed to stop from speed `v` at deceleration `b`. */
23
+ function stoppingDistance(v, b) {
24
+ return v * v / (2 * b);
25
+ }
26
+ //#endregion
27
+ //#region src/kernel/ids.ts
28
+ /** Small deterministic hashes and seeded draws shared by the graph and the agents. */
29
+ /** FNV-1a 32-bit hash of a string. */
30
+ function fnv1a(text) {
31
+ let h = 2166136261;
32
+ for (let i = 0; i < text.length; i++) {
33
+ h ^= text.charCodeAt(i);
34
+ h = Math.imul(h, 16777619);
35
+ }
36
+ return h >>> 0;
37
+ }
38
+ /** Short base-36 hash of a string (up to 7 characters). */
39
+ function shortHash(text) {
40
+ return fnv1a(text).toString(36);
41
+ }
42
+ /** murmur3 finalizer: a full-avalanche 32-bit mix. */
43
+ function fmix32(x) {
44
+ let h = x | 0;
45
+ h = Math.imul(h ^ h >>> 16, 2246822507);
46
+ h = Math.imul(h ^ h >>> 13, 3266489909);
47
+ return (h ^ h >>> 16) >>> 0;
48
+ }
49
+ /** Independent stateless draw in [0, 1) for a (seed, stream) pair. */
50
+ function unit01(seed, stream) {
51
+ return fmix32((seed | 0) ^ Math.imul((stream | 0) + 1, 2654435761)) / 4294967296;
52
+ }
53
+ /** Quantize to 1e-4 so stored state equals the state the next tick reads. */
54
+ function q4(value) {
55
+ return Math.round(value * 1e4) / 1e4;
56
+ }
57
+ //#endregion
58
+ //#region src/kernel/agents/signals.ts
59
+ const AMBER_SECONDS = 3;
60
+ const ALL_RED_SECONDS = 2;
61
+ /** Timing for a signalised junction: 18–30 s green per phase group, seeded by the junction id. */
62
+ function signalTiming(junction, tickRate) {
63
+ const seed = fnv1a(junction.id);
64
+ const greenTicks = [];
65
+ for (let g = 0; g < junction.groups; g++) greenTicks.push(Math.round((18 + 12 * unit01(seed, g + 1)) * tickRate));
66
+ const phase = Math.round(5 * tickRate);
67
+ let cycleTicks = 0;
68
+ for (const green of greenTicks) cycleTicks += green + phase;
69
+ return {
70
+ cycleTicks,
71
+ offsetTicks: Math.floor(unit01(seed, 0) * cycleTicks),
72
+ greenTicks
73
+ };
74
+ }
75
+ /** The colour shown to arms of phase group `group` at `tick`. */
76
+ function signalColor(junction, group, tick, tickRate, timing = signalTiming(junction, tickRate)) {
77
+ if (junction.control !== "signal" || timing.cycleTicks <= 0) return "green";
78
+ const amber = Math.round(AMBER_SECONDS * tickRate);
79
+ const allRed = Math.round(ALL_RED_SECONDS * tickRate);
80
+ let t = (tick + timing.offsetTicks) % timing.cycleTicks;
81
+ for (let g = 0; g < timing.greenTicks.length; g++) {
82
+ const green = timing.greenTicks[g];
83
+ if (t < green) return g === group ? "green" : "red";
84
+ t -= green;
85
+ if (t < amber) return g === group ? "amber" : "red";
86
+ t -= amber;
87
+ if (t < allRed) return "red";
88
+ t -= allRed;
89
+ }
90
+ return "red";
91
+ }
92
+ /** Whether every group is red at `tick` (the all-red clearance interval). */
93
+ function allRed(junction, tick, tickRate, timing = signalTiming(junction, tickRate)) {
94
+ for (let g = 0; g < junction.groups; g++) if (signalColor(junction, g, tick, tickRate, timing) !== "red") return false;
95
+ return true;
96
+ }
97
+ //#endregion
98
+ //#region src/kernel/graph/sample.ts
99
+ /**
100
+ * Positions along lanes. A lane's `s` runs from 0 at its (trimmed) start to `length` at its end;
101
+ * negative `s` lies on the connector curve that led onto the lane from the previous lane, so an
102
+ * agent turning through a junction core follows a smooth arc instead of jumping between lanes.
103
+ */
104
+ /** Edge-path distance of lane coordinate `s` (clamped to the lane). */
105
+ function laneEdgeDistance(lane, edge, s) {
106
+ const clamped = dmath.clamp(s, 0, lane.length);
107
+ return lane.dir === 1 ? lane.trimStart + clamped : edge.path.length - lane.trimStart - clamped;
108
+ }
109
+ /** Lane coordinate of edge-path distance `d`. */
110
+ function laneCoordinate(lane, edge, d) {
111
+ return lane.dir === 1 ? d - lane.trimStart : edge.path.length - d - lane.trimStart;
112
+ }
113
+ /** Height of the edge surface at an edge-path distance. */
114
+ function edgeHeight(edge, d) {
115
+ const path = edge.path;
116
+ const i = lineSegmentIndex(path, d);
117
+ const d0 = path.distances[i] ?? 0;
118
+ const d1 = path.distances[i + 1] ?? d0;
119
+ const y0 = edge.ys[i] ?? 0;
120
+ const y1 = edge.ys[i + 1] ?? y0;
121
+ const t = d1 > d0 ? dmath.clamp((d - d0) / (d1 - d0), 0, 1) : 0;
122
+ return y0 + (y1 - y0) * t;
123
+ }
124
+ /** Sample a lane at `s` within [0, length], writing into `out`. */
125
+ function sampleLaneBody(lane, edge, s, out) {
126
+ const d = laneEdgeDistance(lane, edge, s);
127
+ const p = sampleTerrainLine(edge.path, d, lane.dir * lane.offset);
128
+ out.x = p.x;
129
+ out.z = p.z;
130
+ out.dx = p.dx * lane.dir;
131
+ out.dz = p.dz * lane.dir;
132
+ out.y = edgeHeight(edge, d) + lane.lift;
133
+ out.grade = (edgeHeight(edge, dmath.clamp(d + lane.dir * 2, 0, edge.path.length)) - edgeHeight(edge, dmath.clamp(d - lane.dir * 2, 0, edge.path.length))) / 4;
134
+ return out;
135
+ }
136
+ /** Point and tangent on a movement's connector at arc-length fraction `t` in [0, 1]. */
137
+ function sampleConnector(move, t, out) {
138
+ const u = dmath.clamp(t, 0, 1);
139
+ const a = (1 - u) * (1 - u);
140
+ const b = 2 * (1 - u) * u;
141
+ const c = u * u;
142
+ out.x = a * move.p0[0] + b * move.p1[0] + c * move.p2[0];
143
+ out.y = a * move.p0[1] + b * move.p1[1] + c * move.p2[1];
144
+ out.z = a * move.p0[2] + b * move.p1[2] + c * move.p2[2];
145
+ let dx = 2 * (1 - u) * (move.p1[0] - move.p0[0]) + 2 * u * (move.p2[0] - move.p1[0]);
146
+ let dz = 2 * (1 - u) * (move.p1[2] - move.p0[2]) + 2 * u * (move.p2[2] - move.p1[2]);
147
+ const dy = 2 * (1 - u) * (move.p1[1] - move.p0[1]) + 2 * u * (move.p2[1] - move.p1[1]);
148
+ const length = dmath.hypot(dx, dz);
149
+ if (length > 1e-9) {
150
+ dx /= length;
151
+ dz /= length;
152
+ out.grade = dy / length;
153
+ } else {
154
+ dx = move.p2[0] - move.p0[0];
155
+ dz = move.p2[2] - move.p0[2];
156
+ const l = dmath.hypot(dx, dz) || 1;
157
+ dx /= l;
158
+ dz /= l;
159
+ out.grade = 0;
160
+ }
161
+ out.dx = dx;
162
+ out.dz = dz;
163
+ return out;
164
+ }
165
+ /** Arc length of a quadratic Bezier (8-chord approximation). */
166
+ function connectorLength(p0, p1, p2) {
167
+ let total = 0;
168
+ let px = p0[0];
169
+ let pz = p0[2];
170
+ for (let i = 1; i <= 8; i++) {
171
+ const u = i / 8;
172
+ const a = (1 - u) * (1 - u);
173
+ const b = 2 * (1 - u) * u;
174
+ const c = u * u;
175
+ const x = a * p0[0] + b * p1[0] + c * p2[0];
176
+ const z = a * p0[2] + b * p1[2] + c * p2[2];
177
+ total += dmath.hypot(x - px, z - pz);
178
+ px = x;
179
+ pz = z;
180
+ }
181
+ return total;
182
+ }
183
+ /** A fresh sample record. */
184
+ function laneSample() {
185
+ return {
186
+ x: 0,
187
+ y: 0,
188
+ z: 0,
189
+ dx: 0,
190
+ dz: 1,
191
+ grade: 0
192
+ };
193
+ }
194
+ //#endregion
195
+ //#region src/kernel/agents/step.ts
196
+ /**
197
+ * The per-tick agent step. Everything it needs is rebuilt from components each tick (lane
198
+ * occupancy, junction grants, armed crossings), so world state plus the network fully determine
199
+ * the next tick and a keyframe restores exactly.
200
+ *
201
+ * Order: gather → occupancy → armed crossings → junction grants → cars → pedestrians → trains
202
+ * (leads, then their cars) → aircraft → write changed agents and transforms.
203
+ */
204
+ const TURN_SPEED = {
205
+ left: 7,
206
+ right: 5.5,
207
+ uturn: 3,
208
+ merge: 12,
209
+ straight: 99
210
+ };
211
+ const timings = /* @__PURE__ */ new WeakMap();
212
+ function timingOf(junction, tickRate) {
213
+ let timing = timings.get(junction);
214
+ if (timing === void 0) {
215
+ timing = signalTiming(junction, tickRate);
216
+ timings.set(junction, timing);
217
+ }
218
+ return timing;
219
+ }
220
+ /** Pick the next lane at a lane's end (seeded by the agent and its hop count). */
221
+ function chooseNext(lane, seed, hops) {
222
+ const moves = lane.next;
223
+ if (moves.length === 0) return void 0;
224
+ if (moves.length === 1) return moves[0].to;
225
+ let total = 0;
226
+ for (const move of moves) total += move.weight;
227
+ let target = unit01(seed, 1e3 + hops) * total;
228
+ for (const move of moves) {
229
+ target -= move.weight;
230
+ if (target < 0) return move.to;
231
+ }
232
+ return moves[moves.length - 1].to;
233
+ }
234
+ /** Where an agent is: its lane body, or the connector curve into its lane. */
235
+ function agentSample(net, agent, out) {
236
+ if (agent.air !== void 0) {
237
+ const air = agent.air;
238
+ const t = air.length > 0 ? dmath.clamp(agent.s / air.length, 0, 1) : 0;
239
+ out.x = air.x + air.dx * agent.s;
240
+ out.z = air.z + air.dz * agent.s;
241
+ out.y = air.y0 + (air.y1 - air.y0) * t;
242
+ out.dx = air.dx;
243
+ out.dz = air.dz;
244
+ out.grade = air.length > 0 ? (air.y1 - air.y0) / air.length : 0;
245
+ return out;
246
+ }
247
+ const lane = net.lane(agent.lane);
248
+ if (lane === void 0) return void 0;
249
+ const edge = net.edge(lane.edge);
250
+ if (edge === void 0) return void 0;
251
+ if (agent.s < 0) {
252
+ const move = net.movement(agent.prev, agent.lane);
253
+ if (move !== void 0 && move.length > 0) return sampleConnector(move, (agent.s + move.length) / move.length, out);
254
+ return sampleLaneBody(lane, edge, 0, out);
255
+ }
256
+ return sampleLaneBody(lane, edge, agent.s, out);
257
+ }
258
+ /** Rotation for an agent facing along a sample (with pitch unless flat). */
259
+ function agentRotation(sample, pitch) {
260
+ return lookRotation([
261
+ sample.dx,
262
+ pitch ? sample.grade : 0,
263
+ sample.dz
264
+ ]);
265
+ }
266
+ /** Advance every ambient agent one tick. */
267
+ function stepAgents(world, env) {
268
+ const { net } = env;
269
+ const refs = [];
270
+ for (const [id, a] of world.query(AmbientAgent)) {
271
+ const lane = a.air === void 0 ? net.lane(a.lane) : void 0;
272
+ refs.push({
273
+ id,
274
+ a,
275
+ w: { ...a },
276
+ lane,
277
+ edge: lane !== void 0 ? net.edge(lane.edge) : void 0,
278
+ slot: 0,
279
+ teleport: false
280
+ });
281
+ }
282
+ const occupancy = /* @__PURE__ */ new Map();
283
+ for (const ref of refs) {
284
+ if (ref.lane === void 0) continue;
285
+ const list = occupancy.get(ref.lane.id);
286
+ if (list === void 0) occupancy.set(ref.lane.id, [ref]);
287
+ else list.push(ref);
288
+ }
289
+ for (const list of occupancy.values()) {
290
+ list.sort((x, y) => x.a.s - y.a.s || (x.id < y.id ? -1 : x.id > y.id ? 1 : 0));
291
+ list.forEach((ref, i) => {
292
+ ref.slot = i;
293
+ });
294
+ }
295
+ const armed = /* @__PURE__ */ new Set();
296
+ const crossingArms = /* @__PURE__ */ new Map();
297
+ for (const ref of refs) {
298
+ const { a, lane, edge } = ref;
299
+ if (lane === void 0 || edge === void 0) continue;
300
+ if (a.kind === "pedestrian") {
301
+ if (a.s < 0) {
302
+ const move = net.movement(a.prev, a.lane);
303
+ if (move?.junction !== void 0 && move.crosses !== void 0) {
304
+ let arms = crossingArms.get(move.junction);
305
+ if (arms === void 0) {
306
+ arms = /* @__PURE__ */ new Set();
307
+ crossingArms.set(move.junction, arms);
308
+ }
309
+ for (const k of move.crosses) arms.add(k);
310
+ }
311
+ }
312
+ if (edge.kind === "crossing") for (const c of net.crossingsOf(edge.id)) armed.add(c.id);
313
+ } else if (a.kind === "train") {
314
+ const d = laneEdgeDistance(lane, edge, a.s);
315
+ for (const c of net.crossingsOf(edge.id)) if (c.kind === "level-crossing" && dmath.abs(d - c.otherS) < 90) armed.add(c.id);
316
+ }
317
+ }
318
+ const granted = junctionGrants(refs, crossingArms, env);
319
+ const consistSize = /* @__PURE__ */ new Map();
320
+ for (const ref of refs) if (ref.a.consist !== void 0) consistSize.set(ref.a.consist, (consistSize.get(ref.a.consist) ?? 0) + 1);
321
+ for (const ref of refs) {
322
+ if (ref.lane === void 0 || ref.edge === void 0) continue;
323
+ if (ref.a.kind === "car") stepRoad(ref, occupancy, granted, armed, env);
324
+ else if (ref.a.kind === "pedestrian") stepWalker(ref, occupancy, env);
325
+ else if (ref.a.kind === "train" && ref.a.consist === void 0) stepTrainLead(ref, occupancy, env, consistSize.get(ref.id) ?? 0);
326
+ }
327
+ const byId = /* @__PURE__ */ new Map();
328
+ for (const ref of refs) byId.set(ref.id, ref);
329
+ for (const ref of refs) {
330
+ if (ref.a.kind !== "train" || ref.a.consist === void 0) continue;
331
+ const lead = byId.get(ref.a.consist);
332
+ if (lead !== void 0) placeTrainCar(ref, lead, env);
333
+ }
334
+ for (const ref of refs) if (ref.a.air !== void 0) stepAircraft(ref, env);
335
+ const sample = laneSample();
336
+ for (const ref of refs) {
337
+ const { a, w } = ref;
338
+ w.s = q4(w.s);
339
+ w.speed = q4(w.speed);
340
+ if (!agentChanged(a, w) && !ref.teleport) continue;
341
+ world.set(ref.id, AmbientAgent, w);
342
+ if (agentSample(net, w, sample) === void 0) continue;
343
+ const current = world.get(ref.id, Transform);
344
+ const pos = [
345
+ q4(sample.x),
346
+ q4(sample.y),
347
+ q4(sample.z)
348
+ ];
349
+ const rot = agentRotation(sample, w.kind !== "pedestrian");
350
+ const next = {
351
+ pos,
352
+ rot: [
353
+ q4(rot[0]),
354
+ q4(rot[1]),
355
+ q4(rot[2]),
356
+ q4(rot[3])
357
+ ],
358
+ ...current?.scale !== void 0 ? { scale: current.scale } : {},
359
+ ...ref.teleport ? { teleport: true } : {}
360
+ };
361
+ world.set(ref.id, Transform, next);
362
+ }
363
+ }
364
+ function agentChanged(a, w) {
365
+ return a.s !== w.s || a.speed !== w.speed || a.lane !== w.lane || a.state !== w.state || a.next !== w.next || a.prev !== w.prev || a.served !== w.served || a.hidden !== w.hidden || a.trail !== w.trail;
366
+ }
367
+ function setState(w, state, tick) {
368
+ if (w.state !== state) {
369
+ w.state = state;
370
+ w.since = tick;
371
+ }
372
+ }
373
+ /** Move to the next lane(s) while `s` runs past the lane end. */
374
+ function advanceLanes(ref, env) {
375
+ const { net } = env;
376
+ const w = ref.w;
377
+ let lane = ref.lane;
378
+ for (let guard = 0; guard < 8 && w.s >= lane.length; guard++) {
379
+ if (w.next === void 0) {
380
+ w.s = lane.length;
381
+ w.speed = 0;
382
+ return;
383
+ }
384
+ const move = net.movement(lane.id, w.next);
385
+ const nextLane = net.lane(w.next);
386
+ if (move === void 0 || nextLane === void 0) {
387
+ delete w.next;
388
+ w.s = lane.length;
389
+ w.speed = 0;
390
+ return;
391
+ }
392
+ w.s = w.s - lane.length - move.length;
393
+ if (w.kind === "train" && w.consist === void 0) w.trail = [lane.id, ...w.trail ?? []].slice(0, 6);
394
+ w.prev = lane.id;
395
+ w.lane = nextLane.id;
396
+ w.hops += 1;
397
+ const chosen = chooseNext(nextLane, w.seed, w.hops);
398
+ if (chosen === void 0) delete w.next;
399
+ else w.next = chosen;
400
+ lane = nextLane;
401
+ ref.lane = nextLane;
402
+ ref.edge = net.edge(nextLane.edge);
403
+ if (ref.edge !== void 0) if (ref.edge.tunnel) w.hidden = true;
404
+ else delete w.hidden;
405
+ }
406
+ }
407
+ function junctionGrants(refs, crossingArms, env) {
408
+ const { net, policy } = env;
409
+ const occupied = /* @__PURE__ */ new Map();
410
+ const approaches = /* @__PURE__ */ new Map();
411
+ for (const ref of refs) {
412
+ const { a, lane } = ref;
413
+ if (a.kind !== "car" || lane === void 0) continue;
414
+ if (a.s < 0) {
415
+ const inMove = net.movement(a.prev, a.lane);
416
+ if (inMove?.junction !== void 0) {
417
+ const list = occupied.get(inMove.junction);
418
+ if (list === void 0) occupied.set(inMove.junction, [inMove.key]);
419
+ else list.push(inMove.key);
420
+ }
421
+ }
422
+ if (a.next === void 0) continue;
423
+ const move = net.movement(a.lane, a.next);
424
+ if (move?.junction === void 0) continue;
425
+ const distance = lane.length - a.s - a.length / 2;
426
+ if (distance > stoppingDistance(a.speed, policy.driver.brake) + a.speed * 2 + 6) continue;
427
+ const committed = distance < stoppingDistance(a.speed, policy.driver.brake * 1.6) - .2;
428
+ const inEdge = ref.edge;
429
+ const minor = inEdge !== void 0 && (inEdge.kind === "service" || inEdge.kind === "living" || inEdge.link);
430
+ const list = approaches.get(move.junction);
431
+ const entry = {
432
+ ref,
433
+ move,
434
+ distance,
435
+ committed,
436
+ minor
437
+ };
438
+ if (list === void 0) approaches.set(move.junction, [entry]);
439
+ else list.push(entry);
440
+ }
441
+ const granted = /* @__PURE__ */ new Set();
442
+ const deadlockTicks = policy.deadlockSeconds * env.tickRate;
443
+ for (const id of [...approaches.keys()].sort()) {
444
+ const junction = net.junction(id);
445
+ const list = approaches.get(id);
446
+ if (junction === void 0) {
447
+ for (const entry of list) granted.add(entry.ref.id);
448
+ continue;
449
+ }
450
+ const n = junction.arms.length;
451
+ const keys = n * n;
452
+ const inside = occupied.get(id) ?? [];
453
+ const taken = [...inside];
454
+ const walkers = crossingArms.get(id);
455
+ const timing = junction.control === "signal" ? timingOf(junction, env.tickRate) : void 0;
456
+ const penalty = junction.control === "yield" ? 25 : 0;
457
+ const gives = (x) => x.minor || junction.arms[dmath.floor(x.move.key / n)]?.yields === true ? penalty : 0;
458
+ list.sort((x, y) => Number(y.committed) - Number(x.committed) || x.distance + gives(x) - (y.distance + gives(y)) || (x.ref.id < y.ref.id ? -1 : 1));
459
+ const conflictsWith = (set, key) => {
460
+ for (const other of set) if (junction.conflicts[other * keys + key] === 1) return true;
461
+ return false;
462
+ };
463
+ for (const entry of list) {
464
+ const key = entry.move.key;
465
+ const inArm = dmath.floor(key / n);
466
+ const outArm = key % n;
467
+ if (entry.committed) {
468
+ granted.add(entry.ref.id);
469
+ taken.push(key);
470
+ continue;
471
+ }
472
+ let signalOk = true;
473
+ if (timing !== void 0) {
474
+ const arm = junction.arms[inArm];
475
+ signalOk = arm !== void 0 && signalColor(junction, arm.group, env.tick, env.tickRate, timing) === "green";
476
+ }
477
+ const blocked = walkers !== void 0 && (walkers.has(outArm) || walkers.has(inArm));
478
+ let ok = signalOk && !blocked && !conflictsWith(taken, key);
479
+ if (!ok && signalOk && !blocked && entry.ref.a.state === "wait" && env.tick - entry.ref.a.since > deadlockTicks && !conflictsWith(inside, key)) ok = true;
480
+ if (ok) {
481
+ granted.add(entry.ref.id);
482
+ taken.push(key);
483
+ }
484
+ }
485
+ }
486
+ return granted;
487
+ }
488
+ function leaderOnLane(ref, occupancy) {
489
+ const list = occupancy.get(ref.a.lane);
490
+ if (list === void 0) return void 0;
491
+ return list[ref.slot + 1];
492
+ }
493
+ function firstOnLane(laneId, occupancy) {
494
+ return occupancy.get(laneId)?.[0];
495
+ }
496
+ function stepRoad(ref, occupancy, granted, armed, env) {
497
+ const { net, policy, dt } = env;
498
+ const { a, w } = ref;
499
+ const lane = ref.lane;
500
+ const edge = ref.edge;
501
+ const p = policy.driver;
502
+ const factor = .88 + .24 * unit01(a.seed, 1);
503
+ let v0 = edge.speed * factor;
504
+ const remaining = lane.length - a.s;
505
+ const move = a.next !== void 0 ? net.movement(a.lane, a.next) : void 0;
506
+ if (move !== void 0 && remaining < 35) v0 = dmath.min(v0, (TURN_SPEED[move.turn] ?? 99) + dmath.max(0, remaining - 8) * .3);
507
+ if (a.s < 0) {
508
+ const inMove = net.movement(a.prev, a.lane);
509
+ if (inMove !== void 0) v0 = dmath.min(v0, TURN_SPEED[inMove.turn] ?? 99);
510
+ }
511
+ if (a.s >= 0 && remaining > 4) {
512
+ const here = sampleLaneBody(lane, edge, a.s, scratchA);
513
+ const hx = here.dx;
514
+ const hz = here.dz;
515
+ const ahead = sampleLaneBody(lane, edge, dmath.min(lane.length, a.s + 12), scratchB);
516
+ const dot = dmath.clamp(hx * ahead.dx + hz * ahead.dz, -1, 1);
517
+ if (dot < .995) {
518
+ const angle = dmath.acos(dot);
519
+ const radius = 12 / dmath.max(angle, .001);
520
+ v0 = dmath.min(v0, dmath.sqrt(2.5 * radius));
521
+ }
522
+ }
523
+ let gap = Number.POSITIVE_INFINITY;
524
+ let leaderSpeed = 0;
525
+ let hardLimit = Number.POSITIVE_INFINITY;
526
+ const leader = leaderOnLane(ref, occupancy);
527
+ if (leader !== void 0) {
528
+ gap = leader.a.s - a.s - (leader.a.length + a.length) / 2;
529
+ leaderSpeed = leader.a.speed;
530
+ hardLimit = leader.a.s - (leader.a.length + a.length) / 2 - .3;
531
+ } else if (a.next === void 0 || move === void 0) {
532
+ gap = remaining - a.length / 2;
533
+ hardLimit = lane.length;
534
+ } else if (move.junction !== void 0 && !granted.has(ref.id)) {
535
+ gap = remaining - a.length / 2 - .5;
536
+ hardLimit = dmath.max(a.s, lane.length - a.length / 2 - .2);
537
+ } else {
538
+ const next = firstOnLane(a.next, occupancy);
539
+ if (next !== void 0) {
540
+ gap = remaining + move.length + next.a.s - (next.a.length + a.length) / 2;
541
+ leaderSpeed = next.a.speed;
542
+ }
543
+ }
544
+ for (const stop of lane.stops) {
545
+ if (!armed.has(stop.id)) continue;
546
+ const ahead = laneCoordinate(lane, edge, stop.d) - a.s - a.length / 2;
547
+ if (ahead < -.5 || ahead > 60) continue;
548
+ const g = ahead - 3;
549
+ if (g < gap) {
550
+ gap = g;
551
+ leaderSpeed = 0;
552
+ }
553
+ }
554
+ if (env.solids.length > 0) {
555
+ const here = agentSample(net, a, scratchA);
556
+ if (here !== void 0) for (const solid of env.solids) {
557
+ const rx = solid.x - here.x;
558
+ const rz = solid.z - here.z;
559
+ const forward = rx * here.dx + rz * here.dz;
560
+ if (forward <= 0 || forward > 40) continue;
561
+ if (dmath.abs(rx * here.dz - rz * here.dx) > a.width / 2 + solid.radius + .3) continue;
562
+ const g = forward - a.length / 2 - solid.radius;
563
+ if (g < gap) {
564
+ gap = g;
565
+ leaderSpeed = 0;
566
+ }
567
+ }
568
+ }
569
+ const accel = idmAcceleration(a.speed, v0, gap, a.speed - leaderSpeed, p);
570
+ let v = dmath.max(0, a.speed + accel * dt);
571
+ let s = a.s + v * dt;
572
+ if (s > hardLimit) {
573
+ s = dmath.max(a.s, hardLimit);
574
+ v = dmath.min(v, leaderSpeed);
575
+ }
576
+ w.s = s;
577
+ w.speed = v;
578
+ advanceLanes(ref, env);
579
+ setState(w, w.speed < .1 ? "wait" : "move", env.tick);
580
+ }
581
+ const scratchA = laneSample();
582
+ const scratchB = laneSample();
583
+ /** Whether a pedestrian may start across a crossing movement or a mapped crossing. */
584
+ function crossingClear(move, occupancy, env, walkerSpeed) {
585
+ const { net } = env;
586
+ const nextLane = net.lane(move.to);
587
+ const nextEdge = nextLane !== void 0 ? net.edge(nextLane.edge) : void 0;
588
+ if (nextEdge?.kind === "crossing") {
589
+ for (const c of net.crossingsOf(nextEdge.id)) {
590
+ if (c.kind !== "crossing") continue;
591
+ const road = net.edge(c.road);
592
+ if (road === void 0) continue;
593
+ const reach = 15 + road.speed * 1.5 * walkerSpeed / 1.4;
594
+ for (const laneId of road.lanes) {
595
+ const lane = net.lane(laneId);
596
+ if (lane === void 0 || lane.class !== "road") continue;
597
+ for (const car of occupancy.get(laneId) ?? []) {
598
+ const d = laneEdgeDistance(lane, road, car.a.s);
599
+ const ahead = lane.dir === 1 ? c.roadS - d : d - c.roadS;
600
+ if (ahead > -3 && ahead < reach && (car.a.speed > .5 || ahead < 4)) return false;
601
+ }
602
+ }
603
+ }
604
+ return true;
605
+ }
606
+ if (move.crosses === void 0 || move.junction === void 0) return true;
607
+ const junction = net.junction(move.junction);
608
+ if (junction === void 0) return true;
609
+ if (junction.control === "signal") {
610
+ const timing = timingOf(junction, env.tickRate);
611
+ if (allRed(junction, env.tick, env.tickRate, timing)) return false;
612
+ for (const k of move.crosses) {
613
+ const arm = junction.arms[k];
614
+ if (arm === void 0) continue;
615
+ if (signalColor(junction, arm.group, env.tick, env.tickRate, timing) !== "red") return false;
616
+ }
617
+ }
618
+ for (const k of move.crosses) {
619
+ const arm = junction.arms[k];
620
+ if (arm === void 0) continue;
621
+ const edge = net.edge(arm.edge);
622
+ if (edge === void 0) continue;
623
+ for (const laneId of edge.lanes) {
624
+ const lane = net.lane(laneId);
625
+ if (lane === void 0 || lane.class !== "road") continue;
626
+ for (const car of occupancy.get(laneId) ?? []) if (lane.end === arm.node) {
627
+ const remaining = lane.length - car.a.s;
628
+ if (remaining < 15 + car.a.speed * 1.5 && (car.a.speed > .5 || remaining < 3)) return false;
629
+ } else if (lane.start === arm.node && car.a.s < 2) return false;
630
+ }
631
+ }
632
+ return true;
633
+ }
634
+ function stepWalker(ref, occupancy, env) {
635
+ const { net, dt, tick, tickRate } = env;
636
+ const { a, w } = ref;
637
+ const lane = ref.lane;
638
+ const edge = ref.edge;
639
+ const pace = 1.15 + .5 * unit01(a.seed, 2);
640
+ if (a.state === "idle") {
641
+ const idleTicks = (3 + 15 * unit01(a.seed, 3e3 + a.hops)) * tickRate;
642
+ if (tick - a.since < idleTicks) {
643
+ w.speed = 0;
644
+ return;
645
+ }
646
+ setState(w, "move", tick);
647
+ }
648
+ let v = pace;
649
+ const leader = leaderOnLane(ref, occupancy);
650
+ if (leader !== void 0) {
651
+ const gap = leader.a.s - a.s;
652
+ if (gap < .6) v = 0;
653
+ else if (gap < 1.4) v = dmath.min(v, leader.a.speed);
654
+ }
655
+ const s = a.s + v * dt;
656
+ for (const stop of lane.stops) {
657
+ if (stop.kind !== "bus" || a.served === stop.id) continue;
658
+ const at = laneCoordinate(lane, edge, stop.d);
659
+ if (a.s <= at && s >= at) {
660
+ w.served = stop.id;
661
+ if (unit01(a.seed, fnv1a(stop.id)) < .35) {
662
+ w.s = at;
663
+ w.speed = 0;
664
+ setState(w, "idle", tick);
665
+ return;
666
+ }
667
+ }
668
+ }
669
+ if (s >= lane.length && a.next !== void 0) {
670
+ const move = net.movement(a.lane, a.next);
671
+ if (move !== void 0 && !crossingClear(move, occupancy, env, pace)) {
672
+ w.s = dmath.max(a.s, lane.length);
673
+ w.speed = 0;
674
+ setState(w, "wait", tick);
675
+ return;
676
+ }
677
+ }
678
+ w.s = s;
679
+ w.speed = v;
680
+ const hops = w.hops;
681
+ advanceLanes(ref, env);
682
+ if (w.hops !== hops && unit01(a.seed, 5e3 + w.hops) < .05) {
683
+ setState(w, "idle", tick);
684
+ w.speed = 0;
685
+ return;
686
+ }
687
+ setState(w, v < .05 ? "wait" : "move", tick);
688
+ }
689
+ function stepTrainLead(ref, occupancy, env, cars) {
690
+ const { net, policy, dt, tick, tickRate } = env;
691
+ const { a, w } = ref;
692
+ const lane = ref.lane;
693
+ const edge = ref.edge;
694
+ const p = policy.rail;
695
+ if (a.state === "dwell") {
696
+ const terminus = a.served === `terminus:${a.lane}`;
697
+ const station = terminus ? void 0 : lane.stops.find((stop) => stop.id === a.served);
698
+ const dwellTicks = (terminus ? 30 : station?.dwell ?? 20 + 20 * unit01(a.seed, 7e3 + a.hops)) * tickRate;
699
+ if (tick - a.since < dwellTicks) {
700
+ w.speed = 0;
701
+ return;
702
+ }
703
+ setState(w, "move", tick);
704
+ if (terminus) {
705
+ ref.teleport = true;
706
+ reverseConsist(ref, env, cars);
707
+ return;
708
+ }
709
+ }
710
+ const v0 = edge.speed * (.92 + .08 * unit01(a.seed, 1));
711
+ const remaining = lane.length - a.s;
712
+ let gap = Number.POSITIVE_INFINITY;
713
+ let leaderSpeed = 0;
714
+ const leader = leaderOnLane(ref, occupancy);
715
+ if (leader !== void 0) {
716
+ gap = leader.a.s - a.s - (leader.a.length + a.length) / 2;
717
+ leaderSpeed = leader.a.speed;
718
+ } else if (a.next !== void 0) {
719
+ const next = firstOnLane(a.next, occupancy);
720
+ const move = net.movement(a.lane, a.next);
721
+ if (next !== void 0 && move !== void 0) {
722
+ gap = remaining + move.length + next.a.s - (next.a.length + a.length) / 2;
723
+ leaderSpeed = next.a.speed;
724
+ }
725
+ }
726
+ for (const laneId of edge.lanes) {
727
+ if (laneId === lane.id) continue;
728
+ for (const other of occupancy.get(laneId) ?? []) {
729
+ const g = laneCoordinate(lane, edge, laneEdgeDistance(net.lane(laneId), edge, other.a.s)) - a.s - (other.a.length + a.length) / 2 - 20;
730
+ if (g > -a.length && g < gap) {
731
+ gap = dmath.max(.01, g);
732
+ leaderSpeed = 0;
733
+ }
734
+ }
735
+ }
736
+ let stationAt;
737
+ for (const stop of lane.stops) {
738
+ if (stop.kind !== "station" || stop.id === a.served) continue;
739
+ const at = laneCoordinate(lane, edge, stop.d);
740
+ if (at < a.s - 1) continue;
741
+ if (stationAt === void 0 || at < stationAt.at) stationAt = {
742
+ at,
743
+ id: stop.id
744
+ };
745
+ }
746
+ if (stationAt !== void 0) {
747
+ const g = stationAt.at - a.s + p.gap;
748
+ if (g < gap) {
749
+ gap = g;
750
+ leaderSpeed = 0;
751
+ }
752
+ }
753
+ const terminus = a.next === void 0 || net.movement(a.lane, a.next)?.turn === "uturn";
754
+ if (terminus) {
755
+ const g = remaining - a.length / 2 - 1 + p.gap;
756
+ if (g < gap) {
757
+ gap = g;
758
+ leaderSpeed = 0;
759
+ }
760
+ }
761
+ const accel = idmAcceleration(a.speed, v0, gap, a.speed - leaderSpeed, p);
762
+ const v = dmath.max(0, a.speed + accel * dt);
763
+ w.speed = v;
764
+ w.s = a.s + v * dt;
765
+ if (stationAt !== void 0 && dmath.abs(stationAt.at - w.s) < 1.5 && v < .4) {
766
+ w.speed = 0;
767
+ w.served = stationAt.id;
768
+ setState(w, "dwell", tick);
769
+ return;
770
+ }
771
+ if (terminus && remaining - a.length / 2 < 3 && v < .3) {
772
+ w.speed = 0;
773
+ w.served = `terminus:${a.lane}`;
774
+ setState(w, "dwell", tick);
775
+ return;
776
+ }
777
+ if (terminus) w.s = dmath.min(w.s, lane.length - a.length / 2);
778
+ advanceLanes(ref, env);
779
+ setState(w, w.speed < .1 ? "wait" : "move", tick);
780
+ }
781
+ /** Step back `distance` metres from a lane position along the lead's trail. */
782
+ function walkBack(net, laneId, s, prev, trail, distance) {
783
+ let current = laneId;
784
+ let pos = s;
785
+ let before = prev;
786
+ let index = 0;
787
+ let remaining = distance;
788
+ for (let guard = 0; guard < 12; guard++) {
789
+ const move = net.movement(before, current);
790
+ const floor = -(move?.length ?? 0);
791
+ if (pos - remaining >= floor || before === void 0 || move === void 0) return {
792
+ lane: current,
793
+ s: dmath.max(floor, pos - remaining),
794
+ ...before !== void 0 ? { prev: before } : {}
795
+ };
796
+ remaining -= pos - floor;
797
+ const back = net.lane(before);
798
+ if (back === void 0) return {
799
+ lane: current,
800
+ s: floor,
801
+ prev: before
802
+ };
803
+ current = before;
804
+ pos = back.length;
805
+ index++;
806
+ before = trail[index];
807
+ }
808
+ return {
809
+ lane: current,
810
+ s: pos,
811
+ ...before !== void 0 ? { prev: before } : {}
812
+ };
813
+ }
814
+ function placeTrainCar(ref, lead, env) {
815
+ const { w } = ref;
816
+ const spacing = (ref.a.length + lead.w.length) / 2 + 1;
817
+ const back = walkBack(env.net, lead.w.lane, lead.w.s, lead.w.prev, lead.w.trail ?? [], spacing * (ref.a.carIndex ?? 1));
818
+ w.lane = back.lane;
819
+ w.s = back.s;
820
+ if (back.prev !== void 0) w.prev = back.prev;
821
+ else delete w.prev;
822
+ w.speed = lead.w.speed;
823
+ w.state = lead.w.state;
824
+ w.since = lead.w.since;
825
+ if (lead.teleport) ref.teleport = true;
826
+ const lane = env.net.lane(back.lane);
827
+ if ((lane !== void 0 ? env.net.edge(lane.edge) : void 0)?.tunnel === true) w.hidden = true;
828
+ else delete w.hidden;
829
+ }
830
+ function reverseLane(net, laneId) {
831
+ const lane = net.lane(laneId);
832
+ if (lane === void 0) return void 0;
833
+ const edge = net.edge(lane.edge);
834
+ if (edge === void 0) return void 0;
835
+ for (const id of edge.lanes) {
836
+ const other = net.lane(id);
837
+ if (other !== void 0 && other.class === lane.class && other.dir !== lane.dir) return other;
838
+ }
839
+ }
840
+ /** Turn a consist around at a terminus: the tail becomes the head, travelling back. */
841
+ function reverseConsist(ref, env, cars) {
842
+ const { net } = env;
843
+ const w = ref.w;
844
+ const chain = [w.lane, ...w.trail ?? []];
845
+ const tail = walkBack(net, w.lane, w.s, w.prev, w.trail ?? [], cars * (w.length + 1));
846
+ const tailIndex = dmath.max(0, chain.indexOf(tail.lane));
847
+ const headLane = reverseLane(net, tail.lane);
848
+ if (headLane === void 0) return;
849
+ const trail = [];
850
+ for (let i = tailIndex - 1; i >= 0; i--) {
851
+ const reversed = reverseLane(net, chain[i]);
852
+ if (reversed !== void 0) trail.push(reversed.id);
853
+ }
854
+ w.lane = headLane.id;
855
+ w.s = headLane.length - dmath.max(0, tail.s);
856
+ w.trail = trail;
857
+ if (trail[0] !== void 0) w.prev = trail[0];
858
+ else delete w.prev;
859
+ w.hops += 1;
860
+ const chosen = chooseNext(headLane, w.seed, w.hops);
861
+ if (chosen === void 0) delete w.next;
862
+ else w.next = chosen;
863
+ ref.lane = headLane;
864
+ ref.edge = net.edge(headLane.edge);
865
+ delete w.served;
866
+ }
867
+ function stepAircraft(ref, env) {
868
+ const { w } = ref;
869
+ w.s = ref.a.s + ref.a.speed * env.dt;
870
+ setState(w, "move", env.tick);
871
+ }
872
+ //#endregion
873
+ //#region src/kernel/graph/junctions.ts
874
+ /**
875
+ * Node groups → junctions and movements. A node group is a node plus the node it is stitched to
876
+ * across a tile border. For every lane arriving at the group this computes its outgoing
877
+ * movements (turn class, target lane, connector curve), trims lanes back from junction cores, and
878
+ * builds the junction record: arms in angular order, a conflict matrix between arm-pair
879
+ * movements, a control type and signal phase groups.
880
+ */
881
+ /** Monotone stand-in for atan2 in [0, 4): orders directions without transcendental math. */
882
+ function pseudoAngle(dx, dz) {
883
+ const sum = dmath.abs(dx) + dmath.abs(dz);
884
+ if (sum === 0) return 0;
885
+ const p = dx / sum;
886
+ return dz >= 0 ? 1 - p : 3 + p;
887
+ }
888
+ function armDirection(edge, atStart) {
889
+ const path = edge.path;
890
+ const reach = dmath.min(8, path.length / 2);
891
+ const points = path.points;
892
+ const origin = atStart ? points[0] : points[points.length - 1];
893
+ let target = origin;
894
+ if (atStart) for (let i = 1; i < points.length; i++) {
895
+ target = points[i];
896
+ if (path.distances[i] >= reach) break;
897
+ }
898
+ else for (let i = points.length - 2; i >= 0; i--) {
899
+ target = points[i];
900
+ if (path.length - path.distances[i] >= reach) break;
901
+ }
902
+ const dx = target[0] - origin[0];
903
+ const dz = target[1] - origin[1];
904
+ const length = dmath.hypot(dx, dz) || 1;
905
+ return [dx / length, dz / length];
906
+ }
907
+ function armsOf(store, group, cls) {
908
+ const arms = [];
909
+ for (const node of group) for (const edgeId of node.edges) {
910
+ const edge = store.edge(edgeId);
911
+ if (edge === void 0) continue;
912
+ let hasClass = false;
913
+ for (const laneId of edge.lanes) if (store.lane(laneId)?.class === cls) {
914
+ hasClass = true;
915
+ break;
916
+ }
917
+ if (!hasClass) continue;
918
+ for (const atStart of [true, false]) {
919
+ if ((atStart ? edge.from : edge.to) !== node.id) continue;
920
+ if (arms.some((a) => a.edge === edge && a.atStart === atStart)) continue;
921
+ const [dx, dz] = armDirection(edge, atStart);
922
+ arms.push({
923
+ edge,
924
+ node,
925
+ atStart,
926
+ dx,
927
+ dz
928
+ });
929
+ }
930
+ }
931
+ arms.sort((a, b) => pseudoAngle(a.dx, a.dz) - pseudoAngle(b.dx, b.dz) || (a.edge.id < b.edge.id ? -1 : a.edge.id > b.edge.id ? 1 : 0) || Number(a.atStart) - Number(b.atStart));
932
+ return arms;
933
+ }
934
+ function lanesAt(store, arm, cls, incoming) {
935
+ const out = [];
936
+ for (const id of arm.edge.lanes) {
937
+ const lane = store.lane(id);
938
+ if (lane === void 0 || lane.class !== cls) continue;
939
+ if ((arm.atStart ? lane.dir === -1 : lane.dir === 1) === incoming) out.push(lane);
940
+ }
941
+ out.sort((a, b) => a.index - b.index || (a.id < b.id ? -1 : 1));
942
+ return out;
943
+ }
944
+ function classifyTurn(inDx, inDz, outDx, outDz) {
945
+ const dot = inDx * outDx + inDz * outDz;
946
+ const cross = inDx * outDz - inDz * outDx;
947
+ if (dot > .7) return "straight";
948
+ if (dot < -.9) return "uturn";
949
+ return cross > 0 ? "right" : "left";
950
+ }
951
+ function segmentsCross(ax, az, bx, bz, cx, cz, dx, dz) {
952
+ const rx = bx - ax;
953
+ const rz = bz - az;
954
+ const sx = dx - cx;
955
+ const sz = dz - cz;
956
+ const denom = rx * sz - rz * sx;
957
+ if (dmath.abs(denom) < 1e-12) return false;
958
+ const wx = cx - ax;
959
+ const wz = cz - az;
960
+ const t = (wx * sz - wz * sx) / denom;
961
+ const u = (wx * rz - wz * rx) / denom;
962
+ return t > 0 && t < 1 && u > 0 && u < 1;
963
+ }
964
+ /** Lane end/start samples for one rebuild (every connector at a node reuses them). */
965
+ var EndCache = class {
966
+ store;
967
+ ends = /* @__PURE__ */ new Map();
968
+ starts = /* @__PURE__ */ new Map();
969
+ scratch = laneSample();
970
+ constructor(store) {
971
+ this.store = store;
972
+ }
973
+ take(lane, s) {
974
+ const edge = this.store.edge(lane.edge);
975
+ if (edge === void 0) return void 0;
976
+ const p = sampleLaneBody(lane, edge, s, this.scratch);
977
+ return {
978
+ x: p.x,
979
+ y: p.y,
980
+ z: p.z,
981
+ dx: p.dx,
982
+ dz: p.dz
983
+ };
984
+ }
985
+ end(lane) {
986
+ let p = this.ends.get(lane.id);
987
+ if (p === void 0) {
988
+ p = this.take(lane, lane.length);
989
+ if (p !== void 0) this.ends.set(lane.id, p);
990
+ }
991
+ return p;
992
+ }
993
+ start(lane) {
994
+ let p = this.starts.get(lane.id);
995
+ if (p === void 0) {
996
+ p = this.take(lane, 0);
997
+ if (p !== void 0) this.starts.set(lane.id, p);
998
+ }
999
+ return p;
1000
+ }
1001
+ };
1002
+ function roadWeight(turn, target) {
1003
+ return (turn === "straight" ? 3 : turn === "right" ? 2 : turn === "left" ? 1.5 : turn === "merge" ? 2 : .05) * (target.kind === "service" || target.kind === "living" ? .25 : target.speed >= 15 ? 1.4 : 1);
1004
+ }
1005
+ const MAX_CONFLICT_ARMS = 8;
1006
+ /**
1007
+ * Rebuild trims, movements and the junction record for a node group. Call it for every group
1008
+ * whose incident edges or stitching changed.
1009
+ */
1010
+ function rebuildNodeGroup(store, nodeIds) {
1011
+ const group = nodeIds.map((id) => store.node(id)).filter((n) => n !== void 0);
1012
+ if (group.length === 0) return;
1013
+ const groupIds = new Set(group.map((n) => n.id));
1014
+ const junctionId = [...groupIds].sort()[0];
1015
+ for (const id of groupIds) if (id !== junctionId) store.deleteJunction(id);
1016
+ const roadArms = armsOf(store, group, "road");
1017
+ const isJunction = roadArms.length >= 3;
1018
+ let maxWidth = 0;
1019
+ for (const arm of roadArms) maxWidth = dmath.max(maxWidth, arm.edge.width);
1020
+ const radius = isJunction ? dmath.min(18, maxWidth / 2 + 1.5) : 0;
1021
+ const touched = /* @__PURE__ */ new Set();
1022
+ for (const node of group) for (const edgeId of node.edges) {
1023
+ const edge = store.edge(edgeId);
1024
+ if (edge !== void 0) touched.add(edge);
1025
+ }
1026
+ for (const edge of touched) {
1027
+ const trim = edge.class === "road" ? dmath.min(radius, edge.path.length * .45) : 0;
1028
+ for (const laneId of edge.lanes) {
1029
+ const lane = store.lane(laneId);
1030
+ if (lane === void 0) continue;
1031
+ const startHere = groupIds.has(lane.dir === 1 ? edge.from : edge.to);
1032
+ const endHere = groupIds.has(lane.dir === 1 ? edge.to : edge.from);
1033
+ if (startHere) lane.trimStart = trim;
1034
+ if (endHere) lane.trimEnd = trim;
1035
+ lane.length = dmath.max(.1, edge.path.length - lane.trimStart - lane.trimEnd);
1036
+ }
1037
+ }
1038
+ let junction;
1039
+ if (isJunction) {
1040
+ junction = buildJunction(store, junctionId, group, roadArms, radius);
1041
+ store.setJunction(junction);
1042
+ } else store.deleteJunction(junctionId);
1043
+ const cache = new EndCache(store);
1044
+ buildRoadMovements(store, cache, roadArms, junction);
1045
+ buildRailMovements(store, cache, armsOf(store, group, "rail"));
1046
+ buildWalkMovements(store, cache, armsOf(store, group, "walk"), roadArms, junction, maxWidth);
1047
+ }
1048
+ function buildJunction(store, id, group, arms, radius) {
1049
+ let cx = 0;
1050
+ let cz = 0;
1051
+ for (const node of group) {
1052
+ cx += node.x;
1053
+ cz += node.z;
1054
+ }
1055
+ cx /= group.length;
1056
+ cz /= group.length;
1057
+ const n = arms.length;
1058
+ const side = store.traffic === "right" ? 1 : -1;
1059
+ const rim = [];
1060
+ arms.forEach((arm, k) => {
1061
+ const bx = arm.node.x + arm.dx * radius - cx;
1062
+ const bz = arm.node.z + arm.dz * radius - cz;
1063
+ const q = arm.edge.width / 4;
1064
+ rim.push({
1065
+ angle: pseudoAngle(bx + side * arm.dz * q, bz - side * arm.dx * q),
1066
+ arm: k,
1067
+ exit: false
1068
+ });
1069
+ rim.push({
1070
+ angle: pseudoAngle(bx - side * arm.dz * q, bz + side * arm.dx * q),
1071
+ arm: k,
1072
+ exit: true
1073
+ });
1074
+ });
1075
+ rim.sort((a, b) => a.angle - b.angle || a.arm - b.arm || Number(a.exit) - Number(b.exit));
1076
+ const entryPos = new Array(n).fill(0);
1077
+ const exitPos = new Array(n).fill(0);
1078
+ rim.forEach((p, i) => {
1079
+ if (p.exit) exitPos[p.arm] = i;
1080
+ else entryPos[p.arm] = i;
1081
+ });
1082
+ const m = rim.length;
1083
+ const between = (x, a, b) => x !== a && (x - a + m) % m < (b - a + m) % m;
1084
+ const keys = n * n;
1085
+ const conflicts = new Uint8Array(keys * keys);
1086
+ const capped = n > MAX_CONFLICT_ARMS;
1087
+ for (let i1 = 0; i1 < n; i1++) for (let o1 = 0; o1 < n; o1++) for (let i2 = 0; i2 < n; i2++) for (let o2 = 0; o2 < n; o2++) {
1088
+ const a = i1 * n + o1;
1089
+ const b = i2 * n + o2;
1090
+ let conflict;
1091
+ if (i1 === i2) conflict = false;
1092
+ else if (capped || o1 === o2 || i1 === o1 || i2 === o2) conflict = true;
1093
+ else {
1094
+ const p = entryPos[i1];
1095
+ const q = exitPos[o1];
1096
+ conflict = between(entryPos[i2], p, q) !== between(exitPos[o2], p, q);
1097
+ }
1098
+ conflicts[a * keys + b] = conflict ? 1 : 0;
1099
+ }
1100
+ const junctionArms = arms.map((arm) => ({
1101
+ edge: arm.edge.id,
1102
+ node: arm.node.id,
1103
+ dx: arm.dx,
1104
+ dz: arm.dz,
1105
+ width: arm.edge.width,
1106
+ kind: arm.edge.kind,
1107
+ link: arm.edge.link,
1108
+ group: -1
1109
+ }));
1110
+ let groups = 0;
1111
+ for (let i = 0; i < n; i++) {
1112
+ const arm = junctionArms[i];
1113
+ if (arm.group >= 0) continue;
1114
+ arm.group = groups;
1115
+ let best = -1;
1116
+ let bestDot = -.7;
1117
+ for (let j = i + 1; j < n; j++) {
1118
+ const other = junctionArms[j];
1119
+ if (other.group >= 0) continue;
1120
+ const dot = arm.dx * other.dx + arm.dz * other.dz;
1121
+ if (dot < bestDot) {
1122
+ bestDot = dot;
1123
+ best = j;
1124
+ }
1125
+ }
1126
+ if (best >= 0) junctionArms[best].group = groups;
1127
+ groups++;
1128
+ }
1129
+ const major = arms.some((a) => a.edge.width >= 10 || a.edge.kind === "trunk" || a.edge.kind === "primary" || a.edge.kind === "secondary" || a.edge.kind === "tertiary");
1130
+ const minor = arms.filter((a) => a.edge.kind === "service" || a.edge.kind === "living" || a.edge.link).length;
1131
+ let signed = 0;
1132
+ for (const sign of store.giveWayNear(cx, cz, radius + 20)) {
1133
+ const sx = sign.x - cx;
1134
+ const sz = sign.z - cz;
1135
+ const length = dmath.hypot(sx, sz);
1136
+ let best;
1137
+ let bestDot = Number.NEGATIVE_INFINITY;
1138
+ for (const arm of junctionArms) {
1139
+ const dot = length > 1e-6 ? (arm.dx * sx + arm.dz * sz) / length : 0;
1140
+ if (dot > bestDot) {
1141
+ bestDot = dot;
1142
+ best = arm;
1143
+ }
1144
+ }
1145
+ if (best !== void 0 && best.yields !== true) {
1146
+ best.yields = true;
1147
+ signed++;
1148
+ }
1149
+ }
1150
+ let control = "none";
1151
+ if (groups >= 2 && (n >= 4 && major || store.signalNear(cx, cz, radius + 20))) control = "signal";
1152
+ else if (minor > 0 && minor < n || signed > 0 && signed < n) control = "yield";
1153
+ return {
1154
+ id,
1155
+ x: cx,
1156
+ z: cz,
1157
+ nodes: group.map((node) => node.id),
1158
+ arms: junctionArms,
1159
+ control,
1160
+ radius,
1161
+ conflicts,
1162
+ groups
1163
+ };
1164
+ }
1165
+ function movement(cache, from, to, turn, weight, junction, key, crosses) {
1166
+ const a = cache.end(from);
1167
+ const b = cache.start(to);
1168
+ if (a === void 0 || b === void 0) return void 0;
1169
+ const wx = b.x - a.x;
1170
+ const wz = b.z - a.z;
1171
+ const span = dmath.hypot(wx, wz);
1172
+ const cross = a.dx * b.dz - a.dz * b.dx;
1173
+ let p1 = [
1174
+ (a.x + b.x) / 2,
1175
+ (a.y + b.y) / 2,
1176
+ (a.z + b.z) / 2
1177
+ ];
1178
+ if (dmath.abs(cross) > .05 && span > .01) {
1179
+ const t = (wx * b.dz - wz * b.dx) / cross;
1180
+ if (t > 0 && t < span * 2) p1 = [
1181
+ a.x + a.dx * t,
1182
+ (a.y + b.y) / 2,
1183
+ a.z + a.dz * t
1184
+ ];
1185
+ }
1186
+ const p0 = [
1187
+ a.x,
1188
+ a.y,
1189
+ a.z
1190
+ ];
1191
+ const p2 = [
1192
+ b.x,
1193
+ b.y,
1194
+ b.z
1195
+ ];
1196
+ const move = {
1197
+ to: to.id,
1198
+ turn,
1199
+ key,
1200
+ weight,
1201
+ p0,
1202
+ p1,
1203
+ p2,
1204
+ length: span < 1e-4 ? 0 : connectorLength(p0, p1, p2)
1205
+ };
1206
+ if (junction !== void 0) move.junction = junction.id;
1207
+ if (crosses !== void 0 && crosses.length > 0) move.crosses = crosses;
1208
+ return move;
1209
+ }
1210
+ function buildRoadMovements(store, cache, arms, junction) {
1211
+ const n = arms.length;
1212
+ const left = store.traffic === "left";
1213
+ arms.forEach((inArm, i) => {
1214
+ const incoming = lanesAt(store, inArm, "road", true);
1215
+ const nIn = incoming.length;
1216
+ for (const lane of incoming) {
1217
+ const moves = [];
1218
+ const inDx = -inArm.dx;
1219
+ const inDz = -inArm.dz;
1220
+ const fallback = [];
1221
+ arms.forEach((outArm, o) => {
1222
+ if (outArm === inArm) return;
1223
+ const outgoing = lanesAt(store, outArm, "road", false);
1224
+ const k = outgoing.length;
1225
+ if (k === 0) return;
1226
+ let turn = classifyTurn(inDx, inDz, outArm.dx, outArm.dz);
1227
+ if (turn === "uturn") return;
1228
+ if (n === 2) turn = "straight";
1229
+ const nearest = outgoing[dmath.min(lane.index, k - 1)];
1230
+ fallback.push({
1231
+ lane: nearest,
1232
+ turn,
1233
+ o
1234
+ });
1235
+ const outer = lane.index === nIn - 1;
1236
+ const inner = lane.index === 0;
1237
+ const nearSide = left ? "left" : "right";
1238
+ let target;
1239
+ if (turn === "straight") target = nearest;
1240
+ else if (turn === nearSide && outer) target = outgoing[k - 1];
1241
+ else if (turn !== nearSide && inner) target = outgoing[0];
1242
+ if (target === void 0) return;
1243
+ const moveTurn = inArm.edge.link && turn === "straight" ? "merge" : turn;
1244
+ const move = movement(cache, lane, target, moveTurn, roadWeight(moveTurn, outArm.edge), n >= 3 ? junction : void 0, i * n + o);
1245
+ if (move !== void 0) moves.push(move);
1246
+ });
1247
+ if (moves.length === 0) for (const f of fallback) {
1248
+ const move = movement(cache, lane, f.lane, f.turn, roadWeight(f.turn, store.edge(f.lane.edge) ?? inArm.edge), n >= 3 ? junction : void 0, i * n + f.o);
1249
+ if (move !== void 0) moves.push(move);
1250
+ }
1251
+ if (moves.length === 0) {
1252
+ const back = lanesAt(store, inArm, "road", false)[0];
1253
+ if (back !== void 0) {
1254
+ const move = movement(cache, lane, back, "uturn", .05, void 0, i * n + i);
1255
+ if (move !== void 0) moves.push(move);
1256
+ }
1257
+ }
1258
+ lane.next = moves;
1259
+ }
1260
+ });
1261
+ }
1262
+ function buildRailMovements(store, cache, arms) {
1263
+ for (const inArm of arms) for (const lane of lanesAt(store, inArm, "rail", true)) {
1264
+ const moves = [];
1265
+ for (const outArm of arms) {
1266
+ if (outArm === inArm) continue;
1267
+ const dot = -inArm.dx * outArm.dx + -inArm.dz * outArm.dz;
1268
+ if (dot < .3) continue;
1269
+ for (const target of lanesAt(store, outArm, "rail", false)) {
1270
+ const move = movement(cache, lane, target, "straight", dot > .9 ? 1 : .5, void 0, 0);
1271
+ if (move !== void 0) moves.push(move);
1272
+ }
1273
+ }
1274
+ if (moves.length === 0) {
1275
+ const back = lanesAt(store, inArm, "rail", false)[0];
1276
+ if (back !== void 0) {
1277
+ const move = movement(cache, lane, back, "uturn", 1, void 0, 0);
1278
+ if (move !== void 0) moves.push(move);
1279
+ }
1280
+ }
1281
+ lane.next = moves;
1282
+ }
1283
+ }
1284
+ function buildWalkMovements(store, cache, arms, roadArms, junction, maxRoadWidth) {
1285
+ const reach = junction !== void 0 ? maxRoadWidth + 6 : 3.5;
1286
+ const radius = junction?.radius ?? 0;
1287
+ const outgoing = /* @__PURE__ */ new Map();
1288
+ for (const arm of arms) outgoing.set(arm, lanesAt(store, arm, "walk", false));
1289
+ for (const inArm of arms) for (const lane of lanesAt(store, inArm, "walk", true)) {
1290
+ const edge = store.edge(lane.edge);
1291
+ const end = cache.end(lane);
1292
+ if (edge === void 0 || end === void 0) continue;
1293
+ const ex = end.x;
1294
+ const ez = end.z;
1295
+ const moves = [];
1296
+ let reverse;
1297
+ let reverseDistance = Number.POSITIVE_INFINITY;
1298
+ for (const outArm of arms) for (const target of outgoing.get(outArm) ?? []) {
1299
+ const start = cache.start(target);
1300
+ if (start === void 0) continue;
1301
+ const distance = dmath.hypot(start.x - ex, start.z - ez);
1302
+ const sameSide = edge.class !== "road" || dmath.sign(target.dir * target.offset) === dmath.sign(lane.dir * lane.offset);
1303
+ if (outArm === inArm && sameSide) {
1304
+ if (distance < reverseDistance) {
1305
+ reverseDistance = distance;
1306
+ reverse = target;
1307
+ }
1308
+ continue;
1309
+ }
1310
+ if (distance > reach) continue;
1311
+ const crosses = [];
1312
+ roadArms.forEach((roadArm, k) => {
1313
+ const tip = radius + roadArm.edge.width + 2;
1314
+ if (segmentsCross(ex, ez, start.x, start.z, roadArm.node.x, roadArm.node.z, roadArm.node.x + roadArm.dx * tip, roadArm.node.z + roadArm.dz * tip)) crosses.push(k);
1315
+ });
1316
+ if (crosses.length > 1) continue;
1317
+ if (crosses.length > 0 && junction === void 0) continue;
1318
+ const move = movement(cache, lane, target, classifyTurn(-inArm.dx, -inArm.dz, outArm.dx, outArm.dz), crosses.length > 0 ? .6 : 1, crosses.length > 0 ? junction : void 0, crosses[0] ?? 0, crosses);
1319
+ if (move !== void 0) moves.push(move);
1320
+ }
1321
+ if (moves.length === 0 && reverse !== void 0) {
1322
+ const move = movement(cache, lane, reverse, "uturn", .05, void 0, 0);
1323
+ if (move !== void 0) moves.push(move);
1324
+ }
1325
+ lane.next = moves;
1326
+ }
1327
+ }
1328
+ //#endregion
1329
+ //#region src/kernel/graph/planar.ts
1330
+ /**
1331
+ * Planar split: turn overlapping drafts into a node/edge graph. Drafts of one class are cut where
1332
+ * they share a vertex (any grade: a shared map vertex is a real connection), where they cross at
1333
+ * the same grade (same layer, neither on a bridge nor in a tunnel), and where one ends on
1334
+ * another (T-junctions). Nearby split points snap into one node. Work is bounded per tile.
1335
+ */
1336
+ const CELL = 32;
1337
+ /** Numeric cell key: unique while |cell z| < 2^26 (any Web Mercator coordinate at 0.6 m cells). */
1338
+ const KEY_SPAN = 134217728;
1339
+ function cellKey(x, z) {
1340
+ return x * KEY_SPAN + z;
1341
+ }
1342
+ const CLASS_INDEX = {
1343
+ road: 0,
1344
+ rail: 1,
1345
+ walk: 2,
1346
+ air: 3
1347
+ };
1348
+ /** Cumulative distances of a polyline. */
1349
+ function cumulative(points) {
1350
+ const out = [0];
1351
+ let total = 0;
1352
+ for (let i = 1; i < points.length; i++) {
1353
+ const a = points[i - 1];
1354
+ const b = points[i];
1355
+ total += dmath.hypot(b[0] - a[0], b[1] - a[1]);
1356
+ out.push(total);
1357
+ }
1358
+ return out;
1359
+ }
1360
+ function sameGrade(a, b) {
1361
+ return a.layer === b.layer && !a.bridge && !b.bridge && !a.tunnel && !b.tunnel;
1362
+ }
1363
+ /** Split drafts into pieces between nodes. Drafts only connect within their class. */
1364
+ function planarSplit(drafts, options = {}) {
1365
+ const snap = options.snap ?? .6;
1366
+ const maxSegments = options.maxSegments ?? 6e3;
1367
+ const maxComparisons = options.maxComparisons ?? 12e4;
1368
+ const distances = drafts.map((d) => cumulative(d.points));
1369
+ const cuts = drafts.map((_, i) => [0, distances[i].at(-1)]);
1370
+ const segments = [];
1371
+ const cells = /* @__PURE__ */ new Map();
1372
+ let degraded = false;
1373
+ drafts.forEach((draft, d) => {
1374
+ const dist = distances[d];
1375
+ for (let i = 1; i < draft.points.length; i++) {
1376
+ if (segments.length >= maxSegments) {
1377
+ degraded = true;
1378
+ return;
1379
+ }
1380
+ const a = draft.points[i - 1];
1381
+ const b = draft.points[i];
1382
+ const length = dist[i] - dist[i - 1];
1383
+ if (length <= 1e-9) continue;
1384
+ const index = segments.length;
1385
+ segments.push({
1386
+ draft: d,
1387
+ index: i - 1,
1388
+ ax: a[0],
1389
+ az: a[1],
1390
+ bx: b[0],
1391
+ bz: b[1],
1392
+ length,
1393
+ start: dist[i - 1]
1394
+ });
1395
+ const x0 = dmath.floor((dmath.min(a[0], b[0]) - snap) / CELL);
1396
+ const x1 = dmath.floor((dmath.max(a[0], b[0]) + snap) / CELL);
1397
+ const z0 = dmath.floor((dmath.min(a[1], b[1]) - snap) / CELL);
1398
+ const z1 = dmath.floor((dmath.max(a[1], b[1]) + snap) / CELL);
1399
+ for (let x = x0; x <= x1; x++) for (let z = z0; z <= z1; z++) {
1400
+ const key = cellKey(x, z);
1401
+ const list = cells.get(key);
1402
+ if (list === void 0) cells.set(key, [index]);
1403
+ else list.push(index);
1404
+ }
1405
+ }
1406
+ });
1407
+ const seen = /* @__PURE__ */ new Set();
1408
+ let comparisons = 0;
1409
+ const n = segments.length;
1410
+ const cellKeys = [...cells.keys()].sort((a, b) => a - b);
1411
+ search: for (const key of cellKeys) {
1412
+ const list = cells.get(key);
1413
+ for (let i = 0; i < list.length; i++) {
1414
+ const s1 = segments[list[i]];
1415
+ const d1 = drafts[s1.draft];
1416
+ for (let j = i + 1; j < list.length; j++) {
1417
+ const s2 = segments[list[j]];
1418
+ if (s1.draft === s2.draft) continue;
1419
+ const d2 = drafts[s2.draft];
1420
+ if (d1.class !== d2.class) continue;
1421
+ const lo = dmath.min(list[i], list[j]);
1422
+ const hi = dmath.max(list[i], list[j]);
1423
+ const pair = lo * n + hi;
1424
+ if (seen.has(pair)) continue;
1425
+ seen.add(pair);
1426
+ if (++comparisons > maxComparisons) {
1427
+ degraded = true;
1428
+ break search;
1429
+ }
1430
+ intersect(s1, s2, d1, d2, snap, cuts);
1431
+ }
1432
+ }
1433
+ }
1434
+ const nodes = [];
1435
+ const nodeCells = [
1436
+ /* @__PURE__ */ new Map(),
1437
+ /* @__PURE__ */ new Map(),
1438
+ /* @__PURE__ */ new Map(),
1439
+ /* @__PURE__ */ new Map()
1440
+ ];
1441
+ const nodeAt = (x, z, draft) => {
1442
+ const cx = dmath.floor(x / snap);
1443
+ const cz = dmath.floor(z / snap);
1444
+ const classCells = nodeCells[CLASS_INDEX[draft.class]];
1445
+ let best = -1;
1446
+ let bestDistance = snap;
1447
+ for (let ox = -1; ox <= 1; ox++) for (let oz = -1; oz <= 1; oz++) {
1448
+ const list = classCells.get(cellKey(cx + ox, cz + oz));
1449
+ if (list === void 0) continue;
1450
+ for (const id of list) {
1451
+ const node = nodes[id];
1452
+ const distance = dmath.hypot(node.x - x, node.z - z);
1453
+ if (distance < bestDistance) {
1454
+ bestDistance = distance;
1455
+ best = id;
1456
+ }
1457
+ }
1458
+ }
1459
+ if (best >= 0) return best;
1460
+ const id = nodes.length;
1461
+ nodes.push({
1462
+ x,
1463
+ z,
1464
+ layer: draft.layer,
1465
+ class: draft.class
1466
+ });
1467
+ const key = cellKey(cx, cz);
1468
+ const list = classCells.get(key);
1469
+ if (list === void 0) classCells.set(key, [id]);
1470
+ else list.push(id);
1471
+ return id;
1472
+ };
1473
+ const pieces = [];
1474
+ drafts.forEach((draft, d) => {
1475
+ const dist = distances[d];
1476
+ const total = dist.at(-1);
1477
+ const sorted = [...new Set(cuts[d].map((c) => dmath.clamp(c, 0, total)))].sort((a, b) => a - b);
1478
+ const stops = [];
1479
+ for (const s of sorted) {
1480
+ const p = pointAt(draft.points, dist, s);
1481
+ const node = nodeAt(p[0], p[1], draft);
1482
+ const last = stops[stops.length - 1];
1483
+ if (last !== void 0 && last.node === node && s - last.s < 1) continue;
1484
+ stops.push({
1485
+ s,
1486
+ node
1487
+ });
1488
+ }
1489
+ for (let i = 1; i < stops.length; i++) {
1490
+ const a = stops[i - 1];
1491
+ const b = stops[i];
1492
+ const sliced = slice(draft.points, dist, a.s, b.s, draft.heights);
1493
+ const from = nodes[a.node];
1494
+ const to = nodes[b.node];
1495
+ sliced.points[0] = [from.x, from.z];
1496
+ sliced.points[sliced.points.length - 1] = [to.x, to.z];
1497
+ pieces.push({
1498
+ draft: d,
1499
+ from: a.node,
1500
+ to: b.node,
1501
+ points: sliced.points,
1502
+ ...sliced.heights !== void 0 ? { heights: sliced.heights } : {}
1503
+ });
1504
+ }
1505
+ });
1506
+ return {
1507
+ nodes,
1508
+ pieces,
1509
+ degraded
1510
+ };
1511
+ }
1512
+ function intersect(s1, s2, d1, d2, snap, cuts) {
1513
+ const rx = s1.bx - s1.ax;
1514
+ const rz = s1.bz - s1.az;
1515
+ const qx = s2.bx - s2.ax;
1516
+ const qz = s2.bz - s2.az;
1517
+ const denom = rx * qz - rz * qx;
1518
+ const tEps = snap / s1.length;
1519
+ const uEps = snap / s2.length;
1520
+ const last1 = s1.index === d1.points.length - 2;
1521
+ const last2 = s2.index === d2.points.length - 2;
1522
+ if (dmath.abs(denom) > 1e-9 * s1.length * s2.length) {
1523
+ const wx = s2.ax - s1.ax;
1524
+ const wz = s2.az - s1.az;
1525
+ const t = (wx * qz - wz * qx) / denom;
1526
+ const u = (wx * rz - wz * rx) / denom;
1527
+ if (t < -tEps || t > 1 + tEps || u < -uEps || u > 1 + uEps) {
1528
+ endpointProjections(s1, s2, d1, d2, snap, cuts);
1529
+ return;
1530
+ }
1531
+ const tc = dmath.clamp(t, 0, 1);
1532
+ const uc = dmath.clamp(u, 0, 1);
1533
+ const atVertex1 = t <= tEps || t >= 1 - tEps;
1534
+ const atVertex2 = u <= uEps || u >= 1 - uEps;
1535
+ if (t < 0 && !(s1.index === 0) || t > 1 && !last1) {
1536
+ if (!(atVertex1 && atVertex2)) return;
1537
+ }
1538
+ if (u < 0 && !(s2.index === 0) || u > 1 && !last2) {
1539
+ if (!(atVertex1 && atVertex2)) return;
1540
+ }
1541
+ if (!(atVertex1 && atVertex2) && !sameGrade(d1, d2)) return;
1542
+ cuts[s1.draft].push(s1.start + tc * s1.length);
1543
+ cuts[s2.draft].push(s2.start + uc * s2.length);
1544
+ return;
1545
+ }
1546
+ endpointProjections(s1, s2, d1, d2, snap, cuts);
1547
+ }
1548
+ /** Near-parallel or near-miss segments: connect a draft end that lies on the other segment. */
1549
+ function endpointProjections(s1, s2, d1, d2, snap, cuts) {
1550
+ const tryEnd = (end, other, atStart) => {
1551
+ const px = atStart ? end.ax : end.bx;
1552
+ const pz = atStart ? end.az : end.bz;
1553
+ const ox = other.bx - other.ax;
1554
+ const oz = other.bz - other.az;
1555
+ const t = dmath.clamp(((px - other.ax) * ox + (pz - other.az) * oz) / other.length ** 2, 0, 1);
1556
+ const cx = other.ax + ox * t;
1557
+ const cz = other.az + oz * t;
1558
+ if (dmath.hypot(px - cx, pz - cz) > snap) return;
1559
+ cuts[end.draft].push(atStart ? end.start : end.start + end.length);
1560
+ cuts[other.draft].push(other.start + t * other.length);
1561
+ };
1562
+ const oneOrOther = (a, da, b, db) => {
1563
+ if (!sameGrade(da, db)) return;
1564
+ if (a.index === 0) tryEnd(a, b, true);
1565
+ if (a.index === da.points.length - 2) tryEnd(a, b, false);
1566
+ };
1567
+ oneOrOther(s1, d1, s2, d2);
1568
+ oneOrOther(s2, d2, s1, d1);
1569
+ }
1570
+ function pointAt(points, dist, s) {
1571
+ let i = 1;
1572
+ while (i < dist.length - 1 && dist[i] < s) i++;
1573
+ const a = points[i - 1];
1574
+ const b = points[i];
1575
+ const d0 = dist[i - 1];
1576
+ const len = dist[i] - d0;
1577
+ const t = len > 0 ? dmath.clamp((s - d0) / len, 0, 1) : 0;
1578
+ return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t];
1579
+ }
1580
+ function slice(points, dist, s0, s1, heights) {
1581
+ const out = [pointAt(points, dist, s0)];
1582
+ const hs = heights !== void 0 ? [heightAt(heights, dist, s0)] : void 0;
1583
+ for (let i = 1; i < points.length - 1; i++) {
1584
+ const d = dist[i];
1585
+ if (d > s0 + 1e-6 && d < s1 - 1e-6) {
1586
+ out.push([...points[i]]);
1587
+ hs?.push(heights?.[i]);
1588
+ }
1589
+ }
1590
+ out.push(pointAt(points, dist, s1));
1591
+ hs?.push(heightAt(heights, dist, s1));
1592
+ return hs !== void 0 ? {
1593
+ points: out,
1594
+ heights: hs
1595
+ } : { points: out };
1596
+ }
1597
+ function heightAt(heights, dist, s) {
1598
+ let i = 1;
1599
+ while (i < dist.length - 1 && dist[i] < s) i++;
1600
+ const d0 = dist[i - 1];
1601
+ const len = dist[i] - d0;
1602
+ const t = len > 0 ? dmath.clamp((s - d0) / len, 0, 1) : 0;
1603
+ return heights[i - 1] + (heights[i] - heights[i - 1]) * t;
1604
+ }
1605
+ //#endregion
1606
+ //#region src/kernel/graph/spatial.ts
1607
+ /**
1608
+ * A uniform-grid index over edge spans: which pieces of which edges lie in each 64 m cell, and
1609
+ * how many lane-metres of each class a cell holds. Spawners draw candidate positions from it and
1610
+ * size their targets by the lane-kilometres near the observer.
1611
+ */
1612
+ const GRID_CELL = 64;
1613
+ const CLASSES = [
1614
+ "road",
1615
+ "rail",
1616
+ "walk",
1617
+ "air"
1618
+ ];
1619
+ var LaneGrid = class {
1620
+ cells = /* @__PURE__ */ new Map();
1621
+ edgeCells = /* @__PURE__ */ new Map();
1622
+ /** Bumped on every change; lets callers cache derived sums. */
1623
+ version = 0;
1624
+ insert(edge, laneCounts) {
1625
+ this.remove(edge.id);
1626
+ const path = edge.path;
1627
+ const pieces = dmath.max(1, dmath.ceil(path.length / (64 / 2)));
1628
+ const step = path.length / pieces;
1629
+ const touched = [];
1630
+ for (let i = 0; i < pieces; i++) {
1631
+ const d0 = i * step;
1632
+ const d1 = i === pieces - 1 ? path.length : (i + 1) * step;
1633
+ const mid = (d0 + d1) / 2;
1634
+ const k = lineSegmentIndex(path, mid);
1635
+ const a = path.points[k];
1636
+ const b = path.points[k + 1] ?? a;
1637
+ const s0 = path.distances[k];
1638
+ const s1 = path.distances[k + 1] ?? s0;
1639
+ const t = s1 > s0 ? (mid - s0) / (s1 - s0) : 0;
1640
+ const x = a[0] + (b[0] - a[0]) * t;
1641
+ const z = a[1] + (b[1] - a[1]) * t;
1642
+ const key = `${dmath.floor(x / 64)}/${dmath.floor(z / 64)}`;
1643
+ let cell = this.cells.get(key);
1644
+ if (cell === void 0) {
1645
+ cell = {
1646
+ spans: [],
1647
+ meters: {
1648
+ road: 0,
1649
+ rail: 0,
1650
+ walk: 0,
1651
+ air: 0
1652
+ }
1653
+ };
1654
+ this.cells.set(key, cell);
1655
+ }
1656
+ cell.spans.push({
1657
+ edge: edge.id,
1658
+ d0,
1659
+ d1,
1660
+ x,
1661
+ z
1662
+ });
1663
+ const meters = {
1664
+ road: 0,
1665
+ rail: 0,
1666
+ walk: 0,
1667
+ air: 0
1668
+ };
1669
+ for (const cls of CLASSES) {
1670
+ const m = (d1 - d0) * laneCounts[cls];
1671
+ cell.meters[cls] += m;
1672
+ meters[cls] = m;
1673
+ }
1674
+ touched.push({
1675
+ key,
1676
+ meters
1677
+ });
1678
+ }
1679
+ this.edgeCells.set(edge.id, touched);
1680
+ this.version++;
1681
+ }
1682
+ remove(edgeId) {
1683
+ const touched = this.edgeCells.get(edgeId);
1684
+ if (touched === void 0) return;
1685
+ for (const { key, meters } of touched) {
1686
+ const cell = this.cells.get(key);
1687
+ if (cell === void 0) continue;
1688
+ cell.spans = cell.spans.filter((span) => span.edge !== edgeId);
1689
+ for (const cls of CLASSES) cell.meters[cls] = dmath.max(0, cell.meters[cls] - meters[cls]);
1690
+ if (cell.spans.length === 0) this.cells.delete(key);
1691
+ }
1692
+ this.edgeCells.delete(edgeId);
1693
+ this.version++;
1694
+ }
1695
+ /** Visit cells overlapping the disc of radius `r`, in a deterministic order. */
1696
+ *cellsNear(x, z, r) {
1697
+ const x0 = dmath.floor((x - r) / 64);
1698
+ const x1 = dmath.floor((x + r) / 64);
1699
+ const z0 = dmath.floor((z - r) / 64);
1700
+ const z1 = dmath.floor((z + r) / 64);
1701
+ for (let cz = z0; cz <= z1; cz++) for (let cx = x0; cx <= x1; cx++) {
1702
+ const cell = this.cells.get(`${cx}/${cz}`);
1703
+ if (cell === void 0) continue;
1704
+ const nx = dmath.clamp(x, cx * 64, (cx + 1) * 64);
1705
+ const nz = dmath.clamp(z, cz * 64, (cz + 1) * 64);
1706
+ if (dmath.hypot(nx - x, nz - z) > r) continue;
1707
+ yield cell;
1708
+ }
1709
+ }
1710
+ /** Lane-metres of a class in cells overlapping the disc. */
1711
+ laneMeters(x, z, r, cls) {
1712
+ let total = 0;
1713
+ for (const cell of this.cellsNear(x, z, r)) total += cell.meters[cls];
1714
+ return total;
1715
+ }
1716
+ /** Spans whose midpoint lies in the annulus [rMin, rMax]. */
1717
+ spansWithin(x, z, rMin, rMax) {
1718
+ const out = [];
1719
+ for (const cell of this.cellsNear(x, z, rMax)) for (const span of cell.spans) {
1720
+ const d = dmath.hypot(span.x - x, span.z - z);
1721
+ if (d >= rMin && d <= rMax) out.push(span);
1722
+ }
1723
+ return out;
1724
+ }
1725
+ /** Distinct edge ids with a span within `r` (span midpoints, padded by half a span). */
1726
+ edgesNear(x, z, r) {
1727
+ const seen = /* @__PURE__ */ new Set();
1728
+ const out = [];
1729
+ for (const cell of this.cellsNear(x, z, r + 64 / 2)) for (const span of cell.spans) {
1730
+ if (seen.has(span.edge)) continue;
1731
+ if (dmath.hypot(span.x - x, span.z - z) > r + (span.d1 - span.d0) / 2 + 1) continue;
1732
+ seen.add(span.edge);
1733
+ out.push(span.edge);
1734
+ }
1735
+ return out;
1736
+ }
1737
+ clear() {
1738
+ this.cells.clear();
1739
+ this.edgeCells.clear();
1740
+ this.version++;
1741
+ }
1742
+ };
1743
+ //#endregion
1744
+ //#region src/kernel/graph/network.ts
1745
+ /**
1746
+ * TransportNetwork: the registry of nodes, edges, lanes and junctions built from tiles,
1747
+ * documents and script polylines. Tiles register and unregister as the host streams them;
1748
+ * border nodes stitch to their neighbours so lanes continue across tile edges.
1749
+ *
1750
+ * The network is derived data outside world state (like the worldgen index): agents store lane
1751
+ * ids, and a keyframe restores correctly into any world whose network was built from the same
1752
+ * inputs.
1753
+ */
1754
+ const DOC_TILE = "*";
1755
+ const SIDEWALK_LIFT = .14;
1756
+ const SIDEWALK_KINDS = new Set([
1757
+ "primary",
1758
+ "secondary",
1759
+ "tertiary",
1760
+ "street",
1761
+ "living"
1762
+ ]);
1763
+ var TransportNetwork = class {
1764
+ traffic;
1765
+ grid = new LaneGrid();
1766
+ tunnels;
1767
+ ground;
1768
+ classes;
1769
+ nodes = /* @__PURE__ */ new Map();
1770
+ edges = /* @__PURE__ */ new Map();
1771
+ lanes = /* @__PURE__ */ new Map();
1772
+ junctions = /* @__PURE__ */ new Map();
1773
+ tiles = /* @__PURE__ */ new Map();
1774
+ borders = /* @__PURE__ */ new Map();
1775
+ crossings = /* @__PURE__ */ new Map();
1776
+ crossingsByEdge = /* @__PURE__ */ new Map();
1777
+ signalCells = /* @__PURE__ */ new Map();
1778
+ docDrafts = [];
1779
+ docPois = [];
1780
+ docRunways = [];
1781
+ docSidewalks = false;
1782
+ /** Bumped whenever lanes appear, disappear or change. */
1783
+ version = 0;
1784
+ constructor(options = {}) {
1785
+ this.traffic = options.traffic ?? "right";
1786
+ this.tunnels = options.tunnels ?? "hidden";
1787
+ this.ground = options.ground ?? (() => 0);
1788
+ this.classes = new Set(options.classes ?? [
1789
+ "road",
1790
+ "rail",
1791
+ "walk",
1792
+ "air"
1793
+ ]);
1794
+ }
1795
+ /** Change which lane classes are built (applies to tiles registered afterwards). */
1796
+ setClasses(classes) {
1797
+ this.classes = new Set(classes);
1798
+ }
1799
+ /** Whether a lane class is being built. */
1800
+ builds(cls) {
1801
+ return this.classes.has(cls);
1802
+ }
1803
+ node(id) {
1804
+ return this.nodes.get(id);
1805
+ }
1806
+ edge(id) {
1807
+ return this.edges.get(id);
1808
+ }
1809
+ lane(id) {
1810
+ return this.lanes.get(id);
1811
+ }
1812
+ junction(id) {
1813
+ return this.junctions.get(id);
1814
+ }
1815
+ setJunction(junction) {
1816
+ this.junctions.set(junction.id, junction);
1817
+ }
1818
+ deleteJunction(id) {
1819
+ this.junctions.delete(id);
1820
+ }
1821
+ signalNear(x, z, radius) {
1822
+ return this.controlsNear(x, z, radius, "traffic_signals").length > 0;
1823
+ }
1824
+ giveWayNear(x, z, radius) {
1825
+ return this.controlsNear(x, z, radius, "give_way");
1826
+ }
1827
+ controlsNear(x, z, radius, kind) {
1828
+ const cx = dmath.floor(x / 64);
1829
+ const cz = dmath.floor(z / 64);
1830
+ const found = [];
1831
+ for (let ox = -1; ox <= 1; ox++) for (let oz = -1; oz <= 1; oz++) for (const poi of this.signalCells.get(`${cx + ox}/${cz + oz}`) ?? []) if (poi.kind === kind && dmath.hypot(poi.x - x, poi.z - z) <= radius) found.push(poi);
1832
+ return found;
1833
+ }
1834
+ /** Whether a tile key is registered. */
1835
+ hasTile(key) {
1836
+ return this.tiles.has(key);
1837
+ }
1838
+ tileKeys() {
1839
+ return [...this.tiles.keys()];
1840
+ }
1841
+ /** Every lane id (registration order). */
1842
+ laneIds() {
1843
+ return this.lanes.keys();
1844
+ }
1845
+ junctionList() {
1846
+ return this.junctions.values();
1847
+ }
1848
+ runways() {
1849
+ const out = [];
1850
+ for (const tile of this.tiles.values()) out.push(...tile.runways);
1851
+ return out;
1852
+ }
1853
+ /** Aerodrome POIs (and runway midpoints) across registered tiles. */
1854
+ aerodromes() {
1855
+ const out = [];
1856
+ for (const tile of this.tiles.values()) for (const poi of tile.pois) if (poi.kind === "aerodrome") out.push(poi);
1857
+ return out;
1858
+ }
1859
+ crossingsOf(edgeId) {
1860
+ return this.crossingsByEdge.get(edgeId) ?? [];
1861
+ }
1862
+ /** The movement from `from` onto `to`, if one exists. */
1863
+ movement(from, to) {
1864
+ if (from === void 0) return void 0;
1865
+ const lane = this.lanes.get(from);
1866
+ if (lane === void 0) return void 0;
1867
+ for (const move of lane.next) if (move.to === to) return move;
1868
+ }
1869
+ /** Build and add one map tile (replacing a previous registration under the same key). */
1870
+ registerTile(input) {
1871
+ if (this.tiles.has(input.key)) this.unregisterTile(input.key);
1872
+ const { drafts, runways } = featureDrafts(input, { tunnels: this.tunnels });
1873
+ const pois = tilePois(input.pois, input.origin, input.tileSize);
1874
+ const rect = [
1875
+ input.origin[0],
1876
+ input.origin[1],
1877
+ input.origin[0] + input.tileSize,
1878
+ input.origin[1] + input.tileSize
1879
+ ];
1880
+ this.addTile(input.key, drafts, pois, runways, input.heightAt ?? this.ground, input.sidewalks !== false, rect);
1881
+ }
1882
+ /** Remove a tile: its edges, lanes and nodes; stitched neighbours become open ends again. */
1883
+ unregisterTile(key) {
1884
+ const tile = this.tiles.get(key);
1885
+ if (tile === void 0) return;
1886
+ const partners = [];
1887
+ for (const nodeId of tile.nodes) {
1888
+ const node = this.nodes.get(nodeId);
1889
+ if (node?.link !== void 0) {
1890
+ const partner = this.nodes.get(node.link);
1891
+ if (partner !== void 0) {
1892
+ partner.link = void 0;
1893
+ partners.push(partner.id);
1894
+ }
1895
+ }
1896
+ }
1897
+ for (const edgeId of tile.edges) {
1898
+ const edge = this.edges.get(edgeId);
1899
+ if (edge === void 0) continue;
1900
+ for (const laneId of edge.lanes) this.lanes.delete(laneId);
1901
+ this.grid.remove(edgeId);
1902
+ this.edges.delete(edgeId);
1903
+ this.crossingsByEdge.delete(edgeId);
1904
+ }
1905
+ for (const id of tile.crossings) this.crossings.delete(id);
1906
+ for (const nodeId of tile.nodes) {
1907
+ const node = this.nodes.get(nodeId);
1908
+ if (node === void 0) continue;
1909
+ this.junctions.delete(nodeId);
1910
+ if (node.border) {
1911
+ const key = borderKey(node);
1912
+ const list = this.borders.get(key)?.filter((id) => id !== nodeId) ?? [];
1913
+ if (list.length === 0) this.borders.delete(key);
1914
+ else this.borders.set(key, list);
1915
+ }
1916
+ this.nodes.delete(nodeId);
1917
+ }
1918
+ for (const poi of tile.pois) this.removeSignal(poi);
1919
+ this.tiles.delete(key);
1920
+ for (const id of partners) rebuildNodeGroup(this, [id]);
1921
+ this.version++;
1922
+ }
1923
+ /** Add a transport-network document's ways, stations, signals and aerodromes. */
1924
+ addDocument(doc) {
1925
+ for (const way of doc.ways) {
1926
+ const draft = wayDraft(way);
1927
+ if (draft !== void 0) this.docDrafts.push(draft);
1928
+ }
1929
+ this.docPois.push(...documentPois(doc));
1930
+ this.docRunways.push(...documentRunways(doc));
1931
+ if (doc.sidewalks === true) this.docSidewalks = true;
1932
+ this.rebuildDocTile();
1933
+ }
1934
+ /** Add one polyline (scripts); returns the id of the first edge it produced, if any. */
1935
+ addPolyline(line) {
1936
+ const draft = wayDraft({
1937
+ ...line,
1938
+ class: line.class
1939
+ });
1940
+ if (draft === void 0) return void 0;
1941
+ this.docDrafts.push(draft);
1942
+ const before = new Set(this.tiles.get(DOC_TILE)?.edges ?? []);
1943
+ this.rebuildDocTile();
1944
+ return this.tiles.get(DOC_TILE)?.edges.find((id) => !before.has(id));
1945
+ }
1946
+ rebuildDocTile() {
1947
+ if (this.tiles.has(DOC_TILE)) this.unregisterTile(DOC_TILE);
1948
+ this.addTile(DOC_TILE, this.docDrafts.map((d) => ({
1949
+ ...d,
1950
+ points: d.points.map((p) => [p[0], p[1]])
1951
+ })), [...this.docPois], [...this.docRunways], this.ground, this.docSidewalks, void 0);
1952
+ }
1953
+ addTile(key, allDrafts, pois, runwaySegments, heightAt, sidewalksWanted, rect) {
1954
+ const drafts = allDrafts.filter((d) => this.classes.has(d.class) || d.class === "road" && this.classes.has("walk"));
1955
+ const sidewalks = sidewalksWanted && this.classes.has("walk");
1956
+ const split = planarSplit(drafts);
1957
+ const record = {
1958
+ key,
1959
+ nodes: [],
1960
+ edges: [],
1961
+ pois,
1962
+ runways: runwaySegments.map((r) => ({
1963
+ tile: key,
1964
+ ax: r.a[0],
1965
+ az: r.a[1],
1966
+ bx: r.b[0],
1967
+ bz: r.b[1],
1968
+ y: heightAt((r.a[0] + r.b[0]) / 2, (r.a[1] + r.b[1]) / 2)
1969
+ })),
1970
+ crossings: [],
1971
+ degraded: split.degraded,
1972
+ ...rect !== void 0 ? { rect } : {}
1973
+ };
1974
+ this.tiles.set(key, record);
1975
+ for (const poi of pois) this.addSignal(poi);
1976
+ const nodeIds = split.nodes.map((node) => {
1977
+ const base = `${key}@${shortHash(`${node.class}:${q(node.x)},${q(node.z)}`)}`;
1978
+ let id = base;
1979
+ for (let i = 1; this.nodes.has(id); i++) id = `${base}.${i}`;
1980
+ const onBorder = rect !== void 0 && (dmath.abs(node.x - rect[0]) < .01 || dmath.abs(node.x - rect[2]) < .01 || dmath.abs(node.z - rect[1]) < .01 || dmath.abs(node.z - rect[3]) < .01);
1981
+ const created = {
1982
+ id,
1983
+ x: node.x,
1984
+ z: node.z,
1985
+ layer: node.layer,
1986
+ edges: [],
1987
+ tile: key,
1988
+ border: onBorder,
1989
+ class: node.class
1990
+ };
1991
+ this.nodes.set(id, created);
1992
+ record.nodes.push(id);
1993
+ return id;
1994
+ });
1995
+ const walkSegments = sidewalks ? segmentIndex(drafts.filter((d) => d.class === "walk")) : void 0;
1996
+ const gradeRoad = /* @__PURE__ */ new Set();
1997
+ for (const piece of split.pieces) {
1998
+ const draft = drafts[piece.draft];
1999
+ if (!draft.bridge && !draft.tunnel) {
2000
+ gradeRoad.add(piece.from);
2001
+ gradeRoad.add(piece.to);
2002
+ }
2003
+ }
2004
+ for (const piece of split.pieces) {
2005
+ const draft = drafts[piece.draft];
2006
+ const from = nodeIds[piece.from];
2007
+ const to = nodeIds[piece.to];
2008
+ const dense = densify(piece.points, piece.heights, 8);
2009
+ const path = linePath(dense.points);
2010
+ if (path.length < .05) continue;
2011
+ const lift = draft.class === "walk" ? draft.kind === "crossing" ? ROAD_SURFACE_LIFT + .01 : PATH_SURFACE_LIFT : ROAD_SURFACE_LIFT;
2012
+ const ys = new Float64Array(path.points.length);
2013
+ if (dense.heights !== void 0) dense.heights.forEach((h, i) => {
2014
+ ys[i] = h;
2015
+ });
2016
+ else if (draft.bridge) {
2017
+ const deck = bridgeDeckHeightFn(path, heightAt, {
2018
+ ...draft.deckElevation !== void 0 ? { deckElevation: draft.deckElevation } : {},
2019
+ clearance: draft.class === "walk" ? 3 : 6,
2020
+ approachLift: lift,
2021
+ connects: [gradeRoad.has(piece.from), gradeRoad.has(piece.to)],
2022
+ ...draft.bridgeConnections !== void 0 ? { connections: draft.bridgeConnections } : {}
2023
+ });
2024
+ path.points.forEach((p, i) => {
2025
+ ys[i] = deck(p[0], p[1]);
2026
+ });
2027
+ } else path.points.forEach((p, i) => {
2028
+ ys[i] = heightAt(p[0], p[1]) + lift;
2029
+ });
2030
+ const first = path.points[0];
2031
+ const last = path.points[path.points.length - 1];
2032
+ const base = `${key}#${shortHash(`${draft.class}:${draft.kind}:${q(first[0])},${q(first[1])}:${q(last[0])},${q(last[1])}:${q(path.length)}`)}`;
2033
+ let id = base;
2034
+ for (let i = 1; this.edges.has(id); i++) id = `${base}.${i}`;
2035
+ const edge = {
2036
+ id,
2037
+ tile: key,
2038
+ class: draft.class,
2039
+ kind: draft.kind,
2040
+ from,
2041
+ to,
2042
+ path,
2043
+ ys,
2044
+ width: draft.width,
2045
+ speed: draft.speed ?? KIND_SPEED[draft.kind] * (draft.link ? .7 : 1),
2046
+ layer: draft.layer,
2047
+ bridge: draft.bridge,
2048
+ tunnel: draft.tunnel,
2049
+ link: draft.link,
2050
+ oneway: draft.oneway,
2051
+ lanes: [],
2052
+ ...draft.name !== void 0 ? { name: draft.name } : {}
2053
+ };
2054
+ const inferSidewalks = walkSegments !== void 0 && draft.class === "road" && SIDEWALK_KINDS.has(draft.kind) && !draft.tunnel && !nearWalk(walkSegments, path, draft.width / 2 + 4);
2055
+ this.createLanes(edge, draft, inferSidewalks);
2056
+ this.edges.set(id, edge);
2057
+ record.edges.push(id);
2058
+ this.nodes.get(from).edges.push(id);
2059
+ if (to !== from) this.nodes.get(to).edges.push(id);
2060
+ const counts = {
2061
+ road: 0,
2062
+ rail: 0,
2063
+ walk: 0,
2064
+ air: 0
2065
+ };
2066
+ for (const laneId of edge.lanes) counts[this.lanes.get(laneId).class]++;
2067
+ this.grid.insert(edge, counts);
2068
+ }
2069
+ const groups = /* @__PURE__ */ new Set();
2070
+ for (const nodeId of record.nodes) {
2071
+ const node = this.nodes.get(nodeId);
2072
+ if (node.edges.length === 0) continue;
2073
+ if (node.border) this.stitch(node);
2074
+ groups.add(node.link !== void 0 && node.link < node.id ? node.link : node.id);
2075
+ }
2076
+ for (const root of [...groups].sort()) {
2077
+ const node = this.nodes.get(root);
2078
+ if (node === void 0) continue;
2079
+ rebuildNodeGroup(this, node.link !== void 0 ? [node.id, node.link] : [node.id]);
2080
+ }
2081
+ this.addStops(record);
2082
+ this.addCrossings(record);
2083
+ this.version++;
2084
+ }
2085
+ createLanes(edge, draft, sidewalks) {
2086
+ const side = this.traffic === "right" ? 1 : -1;
2087
+ const make = (code, cls, dir, index, offset, lift = 0) => {
2088
+ const id = `${edge.id}>${code}`;
2089
+ const lane = {
2090
+ id,
2091
+ edge: edge.id,
2092
+ class: cls,
2093
+ dir,
2094
+ index,
2095
+ offset,
2096
+ trimStart: 0,
2097
+ trimEnd: 0,
2098
+ length: edge.path.length,
2099
+ lift,
2100
+ start: dir === 1 ? edge.from : edge.to,
2101
+ end: dir === 1 ? edge.to : edge.from,
2102
+ next: [],
2103
+ stops: []
2104
+ };
2105
+ this.lanes.set(id, lane);
2106
+ edge.lanes.push(id);
2107
+ };
2108
+ if (draft.class === "road") {
2109
+ const total = draft.lanes;
2110
+ const width = draft.width / total;
2111
+ if (draft.oneway) for (let i = 0; i < total; i++) make(`f${i}`, "road", 1, i, side * (i - (total - 1) / 2) * width);
2112
+ else {
2113
+ const forward = dmath.max(1, dmath.ceil(total / 2));
2114
+ const backward = dmath.max(1, total - forward);
2115
+ const w = draft.width / (forward + backward);
2116
+ for (let i = 0; i < forward; i++) make(`f${i}`, "road", 1, i, side * (i + .5) * w);
2117
+ for (let i = 0; i < backward; i++) make(`b${i}`, "road", -1, i, side * (i + .5) * w);
2118
+ }
2119
+ if (sidewalks) {
2120
+ const o = draft.width / 2 + 1.1;
2121
+ make("sr+", "walk", 1, 0, o + side * .35, SIDEWALK_LIFT);
2122
+ make("sr-", "walk", -1, 0, -(o - side * .35), SIDEWALK_LIFT);
2123
+ make("sl+", "walk", 1, 1, -o + side * .35, SIDEWALK_LIFT);
2124
+ make("sl-", "walk", -1, 1, o + side * .35, SIDEWALK_LIFT);
2125
+ }
2126
+ } else if (draft.class === "rail") {
2127
+ make("f0", "rail", 1, 0, 0);
2128
+ make("b0", "rail", -1, 0, 0);
2129
+ } else if (draft.class === "walk") {
2130
+ const o = dmath.min(.45, draft.width / 4) * side;
2131
+ make("f0", "walk", 1, 0, o);
2132
+ make("b0", "walk", -1, 0, o);
2133
+ }
2134
+ }
2135
+ stitch(node) {
2136
+ const own = borderKey(node);
2137
+ const candidates = [...this.borders.get(own) ?? []];
2138
+ let best;
2139
+ let bestDistance = 1.01;
2140
+ const consider = (ids, limit) => {
2141
+ for (const id of ids) {
2142
+ const other = this.nodes.get(id);
2143
+ if (other === void 0 || other.tile === node.tile || other.link !== void 0) continue;
2144
+ const d = dmath.hypot(other.x - node.x, other.z - node.z);
2145
+ if (d < limit && (best === void 0 || d < bestDistance || d === bestDistance && id < best.id)) {
2146
+ best = other;
2147
+ bestDistance = d;
2148
+ }
2149
+ }
2150
+ };
2151
+ consider(candidates, 1.01);
2152
+ if (best === void 0) {
2153
+ bestDistance = 2.01;
2154
+ const [cls, layer] = own.split("/");
2155
+ const bx = dmath.round(node.x);
2156
+ const bz = dmath.round(node.z);
2157
+ 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);
2158
+ }
2159
+ const list = this.borders.get(own);
2160
+ if (list === void 0) this.borders.set(own, [node.id]);
2161
+ else list.push(node.id);
2162
+ const partner = best;
2163
+ if (partner !== void 0) {
2164
+ node.link = partner.id;
2165
+ partner.link = node.id;
2166
+ }
2167
+ }
2168
+ addSignal(poi) {
2169
+ if (poi.kind !== "traffic_signals" && poi.kind !== "give_way") return;
2170
+ const key = `${dmath.floor(poi.x / 64)}/${dmath.floor(poi.z / 64)}`;
2171
+ const list = this.signalCells.get(key);
2172
+ if (list === void 0) this.signalCells.set(key, [poi]);
2173
+ else list.push(poi);
2174
+ }
2175
+ removeSignal(poi) {
2176
+ if (poi.kind !== "traffic_signals" && poi.kind !== "give_way") return;
2177
+ const key = `${dmath.floor(poi.x / 64)}/${dmath.floor(poi.z / 64)}`;
2178
+ const list = this.signalCells.get(key)?.filter((p) => p !== poi) ?? [];
2179
+ if (list.length === 0) this.signalCells.delete(key);
2180
+ else this.signalCells.set(key, list);
2181
+ }
2182
+ /** Project stations onto rail lanes and bus stops onto footways. */
2183
+ addStops(record) {
2184
+ const own = new Set(record.edges);
2185
+ record.pois.forEach((poi, i) => {
2186
+ const wantRail = poi.kind === "station" || poi.kind === "tram_stop";
2187
+ const wantWalk = poi.kind === "bus_stop";
2188
+ if (!wantRail && !wantWalk) return;
2189
+ const reach = wantRail ? 25 : 12;
2190
+ let best;
2191
+ for (const edgeId of this.grid.edgesNear(poi.x, poi.z, reach)) {
2192
+ if (!own.has(edgeId)) continue;
2193
+ const edge = this.edges.get(edgeId);
2194
+ if (!edge.lanes.some((l) => this.lanes.get(l)?.class === (wantRail ? "rail" : "walk"))) continue;
2195
+ const hit = projectOnPath(edge.path, poi.x, poi.z);
2196
+ if (hit.distance <= reach && (best === void 0 || hit.distance < best.distance)) best = {
2197
+ edge,
2198
+ d: hit.d,
2199
+ distance: hit.distance
2200
+ };
2201
+ }
2202
+ if (best === void 0) return;
2203
+ const stop = {
2204
+ d: best.d,
2205
+ kind: wantRail ? "station" : "bus",
2206
+ id: `${record.key}:${poi.kind}:${i}`,
2207
+ ...poi.dwell !== void 0 ? { dwell: poi.dwell } : {}
2208
+ };
2209
+ for (const laneId of best.edge.lanes) {
2210
+ const lane = this.lanes.get(laneId);
2211
+ if (lane.class === (wantRail ? "rail" : "walk")) lane.stops.push(stop);
2212
+ }
2213
+ });
2214
+ }
2215
+ /** Record where footway crossings and railways cross roads at grade. */
2216
+ addCrossings(record) {
2217
+ const edges = record.edges.map((id) => this.edges.get(id));
2218
+ const roads = edges.filter((e) => e.class === "road" && !e.bridge && !e.tunnel);
2219
+ const others = edges.filter((e) => (e.kind === "crossing" || e.class === "rail") && !e.bridge && !e.tunnel);
2220
+ if (roads.length === 0 || others.length === 0) return;
2221
+ const roadIndex = segmentIndexOfPaths(roads.map((e) => e.path));
2222
+ for (const other of others) {
2223
+ const path = other.path;
2224
+ for (let i = 1; i < path.points.length; i++) {
2225
+ const a = path.points[i - 1];
2226
+ const b = path.points[i];
2227
+ for (const hit of roadIndex.crossing(a, b)) {
2228
+ const road = roads[hit.path];
2229
+ if (road.layer !== other.layer) continue;
2230
+ const otherS = path.distances[i - 1] + hit.t * (path.distances[i] - path.distances[i - 1]);
2231
+ const id = `${record.key}:x${fnv1a(`${road.id}|${other.id}|${q(hit.roadS)}`).toString(36)}`;
2232
+ if (this.crossings.has(id)) continue;
2233
+ const kind = other.class === "rail" ? "level-crossing" : "crossing";
2234
+ const crossing = {
2235
+ id,
2236
+ tile: record.key,
2237
+ kind,
2238
+ road: road.id,
2239
+ roadS: hit.roadS,
2240
+ other: other.id,
2241
+ otherS
2242
+ };
2243
+ this.crossings.set(id, crossing);
2244
+ record.crossings.push(id);
2245
+ for (const edgeId of [road.id, other.id]) {
2246
+ const list = this.crossingsByEdge.get(edgeId);
2247
+ if (list === void 0) this.crossingsByEdge.set(edgeId, [crossing]);
2248
+ else list.push(crossing);
2249
+ }
2250
+ for (const laneId of road.lanes) {
2251
+ const lane = this.lanes.get(laneId);
2252
+ if (lane.class === "road") lane.stops.push({
2253
+ d: hit.roadS,
2254
+ kind,
2255
+ id
2256
+ });
2257
+ }
2258
+ }
2259
+ }
2260
+ }
2261
+ }
2262
+ /** Sample a lane body at `s` (clamped to the lane). */
2263
+ sampleLane(laneId, s, out = laneSample()) {
2264
+ const lane = this.lanes.get(laneId);
2265
+ if (lane === void 0) return void 0;
2266
+ const edge = this.edges.get(lane.edge);
2267
+ if (edge === void 0) return void 0;
2268
+ return sampleLaneBody(lane, edge, s, out);
2269
+ }
2270
+ /** The nearest lane of a class to a point, with the lane coordinate of the closest point. */
2271
+ laneAt(x, z, opts = {}) {
2272
+ const radius = opts.radius ?? 20;
2273
+ let best;
2274
+ const sample = laneSample();
2275
+ for (const edgeId of this.grid.edgesNear(x, z, radius)) {
2276
+ const edge = this.edges.get(edgeId);
2277
+ const hit = projectOnPath(edge.path, x, z);
2278
+ if (hit.distance > radius + edge.width) continue;
2279
+ for (const laneId of edge.lanes) {
2280
+ const lane = this.lanes.get(laneId);
2281
+ if (opts.class !== void 0 && lane.class !== opts.class) continue;
2282
+ const s = dmath.clamp(laneCoordinate(lane, edge, hit.d), 0, lane.length);
2283
+ sampleLaneBody(lane, edge, s, sample);
2284
+ const distance = dmath.hypot(sample.x - x, sample.z - z);
2285
+ if (distance <= radius && (best === void 0 || distance < best.distance)) best = {
2286
+ lane: laneId,
2287
+ s,
2288
+ distance
2289
+ };
2290
+ }
2291
+ }
2292
+ return best;
2293
+ }
2294
+ stats() {
2295
+ const laneKm = {
2296
+ road: 0,
2297
+ rail: 0,
2298
+ walk: 0,
2299
+ air: 0
2300
+ };
2301
+ for (const lane of this.lanes.values()) laneKm[lane.class] += lane.length / 1e3;
2302
+ let signals = 0;
2303
+ for (const junction of this.junctions.values()) if (junction.control === "signal") signals++;
2304
+ let degradedTiles = 0;
2305
+ for (const tile of this.tiles.values()) if (tile.degraded) degradedTiles++;
2306
+ return {
2307
+ tiles: this.tiles.size,
2308
+ nodes: this.nodes.size,
2309
+ edges: this.edges.size,
2310
+ lanes: this.lanes.size,
2311
+ junctions: this.junctions.size,
2312
+ signals,
2313
+ laneKm,
2314
+ degradedTiles
2315
+ };
2316
+ }
2317
+ /** Drop everything. */
2318
+ clear() {
2319
+ for (const key of [...this.tiles.keys()]) this.unregisterTile(key);
2320
+ this.docDrafts.length = 0;
2321
+ this.docPois.length = 0;
2322
+ this.docRunways.length = 0;
2323
+ this.docSidewalks = false;
2324
+ this.grid.clear();
2325
+ this.version++;
2326
+ }
2327
+ /** Every edge, for export (`networkToDocument`). */
2328
+ edgeList() {
2329
+ return this.edges.values();
2330
+ }
2331
+ };
2332
+ function q(value) {
2333
+ return dmath.round(value * 10);
2334
+ }
2335
+ function borderKey(node) {
2336
+ return `${node.class}/${node.layer}/${dmath.round(node.x)}/${dmath.round(node.z)}`;
2337
+ }
2338
+ function linePath(points) {
2339
+ const distances = cumulative(points);
2340
+ return {
2341
+ points,
2342
+ distances,
2343
+ length: distances[distances.length - 1]
2344
+ };
2345
+ }
2346
+ /** Insert vertices so no segment exceeds `spacing` (heights interpolate along). */
2347
+ function densify(points, heights, spacing) {
2348
+ const out = [[...points[0]]];
2349
+ const hs = heights !== void 0 ? [heights[0]] : void 0;
2350
+ for (let i = 1; i < points.length; i++) {
2351
+ const a = points[i - 1];
2352
+ const b = points[i];
2353
+ const length = dmath.hypot(b[0] - a[0], b[1] - a[1]);
2354
+ if (length < 1e-4) continue;
2355
+ const steps = dmath.max(1, dmath.ceil(length / spacing));
2356
+ for (let k = 1; k <= steps; k++) {
2357
+ const t = k / steps;
2358
+ out.push(k === steps ? [b[0], b[1]] : [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]);
2359
+ if (hs !== void 0 && heights !== void 0) {
2360
+ const h0 = heights[i - 1];
2361
+ const h1 = heights[i];
2362
+ hs.push(h0 + (h1 - h0) * t);
2363
+ }
2364
+ }
2365
+ }
2366
+ return hs !== void 0 ? {
2367
+ points: out,
2368
+ heights: hs
2369
+ } : { points: out };
2370
+ }
2371
+ /** Closest point on a path: its path distance and the planar distance to it. */
2372
+ function projectOnPath(path, x, z) {
2373
+ let bestD = 0;
2374
+ let best = Number.POSITIVE_INFINITY;
2375
+ for (let i = 1; i < path.points.length; i++) {
2376
+ const a = path.points[i - 1];
2377
+ const b = path.points[i];
2378
+ const dx = b[0] - a[0];
2379
+ const dz = b[1] - a[1];
2380
+ const len2 = dx * dx + dz * dz;
2381
+ const t = len2 > 0 ? dmath.clamp(((x - a[0]) * dx + (z - a[1]) * dz) / len2, 0, 1) : 0;
2382
+ const px = a[0] + dx * t;
2383
+ const pz = a[1] + dz * t;
2384
+ const distance = dmath.hypot(px - x, pz - z);
2385
+ if (distance < best) {
2386
+ best = distance;
2387
+ bestD = path.distances[i - 1] + t * (path.distances[i] - path.distances[i - 1]);
2388
+ }
2389
+ }
2390
+ return {
2391
+ d: bestD,
2392
+ distance: best
2393
+ };
2394
+ }
2395
+ function segmentIndex(drafts) {
2396
+ const cells = /* @__PURE__ */ new Map();
2397
+ for (const draft of drafts) for (let i = 1; i < draft.points.length; i++) {
2398
+ const a = draft.points[i - 1];
2399
+ const b = draft.points[i];
2400
+ const seg = {
2401
+ ax: a[0],
2402
+ az: a[1],
2403
+ bx: b[0],
2404
+ bz: b[1]
2405
+ };
2406
+ const x0 = dmath.floor(dmath.min(a[0], b[0]) / 32);
2407
+ const x1 = dmath.floor(dmath.max(a[0], b[0]) / 32);
2408
+ const z0 = dmath.floor(dmath.min(a[1], b[1]) / 32);
2409
+ const z1 = dmath.floor(dmath.max(a[1], b[1]) / 32);
2410
+ for (let x = x0; x <= x1; x++) for (let z = z0; z <= z1; z++) {
2411
+ const key = `${x}/${z}`;
2412
+ const list = cells.get(key);
2413
+ if (list === void 0) cells.set(key, [seg]);
2414
+ else list.push(seg);
2415
+ }
2416
+ }
2417
+ return cells;
2418
+ }
2419
+ /** Whether any walk segment lies within `reach` of the path at 25/50/75 %. */
2420
+ function nearWalk(cells, path, reach) {
2421
+ for (const fraction of [
2422
+ .25,
2423
+ .5,
2424
+ .75
2425
+ ]) {
2426
+ const target = path.length * fraction;
2427
+ let i = 1;
2428
+ while (i < path.distances.length - 1 && path.distances[i] < target) i++;
2429
+ const a = path.points[i - 1];
2430
+ const b = path.points[i];
2431
+ const d0 = path.distances[i - 1];
2432
+ const d1 = path.distances[i];
2433
+ const t = d1 > d0 ? (target - d0) / (d1 - d0) : 0;
2434
+ const x = a[0] + (b[0] - a[0]) * t;
2435
+ const z = a[1] + (b[1] - a[1]) * t;
2436
+ const cx = dmath.floor(x / 32);
2437
+ const cz = dmath.floor(z / 32);
2438
+ for (let ox = -1; ox <= 1; ox++) for (let oz = -1; oz <= 1; oz++) for (const seg of cells.get(`${cx + ox}/${cz + oz}`) ?? []) {
2439
+ const dx = seg.bx - seg.ax;
2440
+ const dz = seg.bz - seg.az;
2441
+ const len2 = dx * dx + dz * dz;
2442
+ const u = len2 > 0 ? dmath.clamp(((x - seg.ax) * dx + (z - seg.az) * dz) / len2, 0, 1) : 0;
2443
+ if (dmath.hypot(seg.ax + dx * u - x, seg.az + dz * u - z) <= reach) return true;
2444
+ }
2445
+ }
2446
+ return false;
2447
+ }
2448
+ /** Segment grid over several paths for crossing detection. */
2449
+ function segmentIndexOfPaths(paths) {
2450
+ const cells = /* @__PURE__ */ new Map();
2451
+ paths.forEach((path, p) => {
2452
+ for (let i = 1; i < path.points.length; i++) {
2453
+ const a = path.points[i - 1];
2454
+ const b = path.points[i];
2455
+ const x0 = dmath.floor(dmath.min(a[0], b[0]) / 32);
2456
+ const x1 = dmath.floor(dmath.max(a[0], b[0]) / 32);
2457
+ const z0 = dmath.floor(dmath.min(a[1], b[1]) / 32);
2458
+ const z1 = dmath.floor(dmath.max(a[1], b[1]) / 32);
2459
+ for (let x = x0; x <= x1; x++) for (let z = z0; z <= z1; z++) {
2460
+ const key = `${x}/${z}`;
2461
+ const list = cells.get(key);
2462
+ if (list === void 0) cells.set(key, [{
2463
+ path: p,
2464
+ i
2465
+ }]);
2466
+ else list.push({
2467
+ path: p,
2468
+ i
2469
+ });
2470
+ }
2471
+ }
2472
+ });
2473
+ return { crossing(a, b) {
2474
+ const out = [];
2475
+ const seen = /* @__PURE__ */ new Set();
2476
+ const x0 = dmath.floor(dmath.min(a[0], b[0]) / 32);
2477
+ const x1 = dmath.floor(dmath.max(a[0], b[0]) / 32);
2478
+ const z0 = dmath.floor(dmath.min(a[1], b[1]) / 32);
2479
+ const z1 = dmath.floor(dmath.max(a[1], b[1]) / 32);
2480
+ for (let x = x0; x <= x1; x++) for (let z = z0; z <= z1; z++) for (const ref of cells.get(`${x}/${z}`) ?? []) {
2481
+ const key = `${ref.path}:${ref.i}`;
2482
+ if (seen.has(key)) continue;
2483
+ seen.add(key);
2484
+ const path = paths[ref.path];
2485
+ const c = path.points[ref.i - 1];
2486
+ const d = path.points[ref.i];
2487
+ const rx = b[0] - a[0];
2488
+ const rz = b[1] - a[1];
2489
+ const sx = d[0] - c[0];
2490
+ const sz = d[1] - c[1];
2491
+ const denom = rx * sz - rz * sx;
2492
+ if (dmath.abs(denom) < 1e-12) continue;
2493
+ const wx = c[0] - a[0];
2494
+ const wz = c[1] - a[1];
2495
+ const t = (wx * sz - wz * sx) / denom;
2496
+ const u = (wx * rz - wz * rx) / denom;
2497
+ if (t < 0 || t > 1 || u < 0 || u > 1) continue;
2498
+ const s0 = path.distances[ref.i - 1];
2499
+ const s1 = path.distances[ref.i];
2500
+ out.push({
2501
+ path: ref.path,
2502
+ roadS: s0 + u * (s1 - s0),
2503
+ t
2504
+ });
2505
+ }
2506
+ return out;
2507
+ } };
2508
+ }
2509
+ //#endregion
2510
+ //#region src/kernel/spawn/policy.ts
2511
+ const DEFAULT_POLICY = {
2512
+ spawnEveryTicks: 6,
2513
+ spawnBudget: 4,
2514
+ forwardConeCos: .82,
2515
+ forwardConeReach: 150,
2516
+ stuckSeconds: 90,
2517
+ deadlockSeconds: 20,
2518
+ car: {
2519
+ enabled: true,
2520
+ near: 60,
2521
+ far: 350,
2522
+ keep: 450,
2523
+ perLaneKm: 12,
2524
+ max: 200
2525
+ },
2526
+ pedestrian: {
2527
+ enabled: false,
2528
+ near: 25,
2529
+ far: 140,
2530
+ keep: 180,
2531
+ perLaneKm: 25,
2532
+ max: 60
2533
+ },
2534
+ train: {
2535
+ enabled: false,
2536
+ near: 150,
2537
+ far: 1200,
2538
+ keep: 1500,
2539
+ perLaneKm: .4,
2540
+ max: 2
2541
+ },
2542
+ aircraft: {
2543
+ enabled: false,
2544
+ near: 800,
2545
+ far: 5e3,
2546
+ keep: 6e3,
2547
+ perLaneKm: 0,
2548
+ max: 4
2549
+ },
2550
+ driver: {
2551
+ accel: 1.6,
2552
+ brake: 2.8,
2553
+ gap: 2,
2554
+ headway: 1.3
2555
+ },
2556
+ rail: {
2557
+ accel: .5,
2558
+ brake: .9,
2559
+ gap: 8,
2560
+ headway: 6
2561
+ }
2562
+ };
2563
+ /** Merge overrides into a policy (plain objects merge; other values replace). */
2564
+ function mergePolicy(base, ...overrides) {
2565
+ let out = base;
2566
+ for (const override of overrides) {
2567
+ if (override === void 0) continue;
2568
+ out = mergeObject(out, override);
2569
+ }
2570
+ return out;
2571
+ }
2572
+ function mergeObject(base, patch) {
2573
+ const out = { ...base };
2574
+ for (const [key, value] of Object.entries(patch)) {
2575
+ if (value === void 0) continue;
2576
+ const current = out[key];
2577
+ if (value !== null && typeof value === "object" && !Array.isArray(value) && current !== null && typeof current === "object" && !Array.isArray(current)) out[key] = mergeObject(current, value);
2578
+ else out[key] = value;
2579
+ }
2580
+ return out;
2581
+ }
2582
+ /** A policy with a host budget's caps and ring sizes applied. */
2583
+ function policyForBudget(policy, budget) {
2584
+ const scale = budget.radius !== void 0 ? budget.radius / policy.car.far : 1;
2585
+ const walkScale = budget.pedestrianRadius !== void 0 ? budget.pedestrianRadius / policy.pedestrian.far : 1;
2586
+ const ring = (c, cap, factor) => ({
2587
+ ...c,
2588
+ ...cap !== void 0 ? {
2589
+ max: cap,
2590
+ enabled: c.enabled && cap > 0
2591
+ } : {},
2592
+ ...factor !== 1 ? {
2593
+ near: Math.min(c.near, c.near * factor),
2594
+ far: c.far * factor,
2595
+ keep: c.keep * factor
2596
+ } : {}
2597
+ });
2598
+ return {
2599
+ ...policy,
2600
+ car: ring(policy.car, budget.cars, scale),
2601
+ pedestrian: ring(policy.pedestrian, budget.pedestrians, walkScale),
2602
+ train: ring(policy.train, budget.trains, scale),
2603
+ aircraft: ring(policy.aircraft, budget.aircraft, 1)
2604
+ };
2605
+ }
2606
+ //#endregion
2607
+ //#region src/kernel/templates.ts
2608
+ /** Common real-world car body colours, weighted by repetition. */
2609
+ const CAR_COLORS = [
2610
+ "#f2f2f0",
2611
+ "#f2f2f0",
2612
+ "#f2f2f0",
2613
+ "#1c1d21",
2614
+ "#1c1d21",
2615
+ "#1c1d21",
2616
+ "#8d9196",
2617
+ "#8d9196",
2618
+ "#b9bcbf",
2619
+ "#b9bcbf",
2620
+ "#2f4f86",
2621
+ "#8c1f1f",
2622
+ "#3f5a3c",
2623
+ "#6b4a2e",
2624
+ "#c9b48a"
2625
+ ];
2626
+ const DEFAULT_TYPES = {
2627
+ car: [
2628
+ {
2629
+ id: "proxy.sedan",
2630
+ length: 4.6,
2631
+ width: 1.8,
2632
+ height: 1.45,
2633
+ weight: 3
2634
+ },
2635
+ {
2636
+ id: "proxy.suv",
2637
+ length: 4.8,
2638
+ width: 1.9,
2639
+ height: 1.75,
2640
+ weight: 2
2641
+ },
2642
+ {
2643
+ id: "proxy.compact",
2644
+ length: 4,
2645
+ width: 1.75,
2646
+ height: 1.45,
2647
+ weight: 2
2648
+ },
2649
+ {
2650
+ id: "proxy.van",
2651
+ length: 5.2,
2652
+ width: 2,
2653
+ height: 2.1,
2654
+ weight: 1
2655
+ }
2656
+ ],
2657
+ train: [{
2658
+ id: "proxy.rail",
2659
+ length: 27,
2660
+ width: 2.65,
2661
+ height: 3.6,
2662
+ cars: 2,
2663
+ colors: ["#e8e6de"]
2664
+ }],
2665
+ aircraft: [{
2666
+ id: "proxy.airliner",
2667
+ length: 38,
2668
+ width: 36,
2669
+ height: 12,
2670
+ cruise: 110
2671
+ }],
2672
+ pedestrian: [
2673
+ {
2674
+ preset: "human.adult",
2675
+ weight: 7
2676
+ },
2677
+ {
2678
+ preset: "human.elder",
2679
+ weight: 1.5
2680
+ },
2681
+ {
2682
+ preset: "human.child",
2683
+ weight: 1.5
2684
+ }
2685
+ ]
2686
+ };
2687
+ /** Weighted pick from a list using a stateless draw. */
2688
+ function pickWeighted(list, u) {
2689
+ let total = 0;
2690
+ for (const item of list) total += item.weight ?? 1;
2691
+ if (total <= 0) return list[0];
2692
+ let target = u * total;
2693
+ for (const item of list) {
2694
+ target -= item.weight ?? 1;
2695
+ if (target < 0) return item;
2696
+ }
2697
+ return list[list.length - 1];
2698
+ }
2699
+ const ADULTS = [
2700
+ {
2701
+ height: 1.62,
2702
+ build: -.2,
2703
+ skin: "#f1d3bd",
2704
+ hair: "#3b2a20",
2705
+ top: "#2f3b52",
2706
+ bottom: "#1f1f24"
2707
+ },
2708
+ {
2709
+ height: 1.78,
2710
+ build: .2,
2711
+ skin: "#c68b62",
2712
+ hair: "#1f1a17",
2713
+ top: "#e8e6de",
2714
+ bottom: "#2f3b52"
2715
+ },
2716
+ {
2717
+ height: 1.7,
2718
+ build: 0,
2719
+ skin: "#6c4430",
2720
+ hair: "#1f1a17",
2721
+ top: "#6b2f2f",
2722
+ bottom: "#8a8f96"
2723
+ },
2724
+ {
2725
+ height: 1.84,
2726
+ build: .4,
2727
+ skin: "#e0b597",
2728
+ hair: "#a8793f",
2729
+ top: "#2f5a3b",
2730
+ bottom: "#c9b48a"
2731
+ },
2732
+ {
2733
+ height: 1.58,
2734
+ build: -.4,
2735
+ skin: "#9b6645",
2736
+ hair: "#1f1a17",
2737
+ top: "#3b6ea5",
2738
+ bottom: "#1f1f24"
2739
+ },
2740
+ {
2741
+ height: 1.74,
2742
+ build: .1,
2743
+ skin: "#f1d3bd",
2744
+ hair: "#d8c29a",
2745
+ top: "#1f1f24",
2746
+ bottom: "#2f3b52"
2747
+ },
2748
+ {
2749
+ height: 1.66,
2750
+ build: .3,
2751
+ skin: "#4a2e21",
2752
+ hair: "#1f1a17",
2753
+ top: "#b0553a",
2754
+ bottom: "#1f1f24"
2755
+ },
2756
+ {
2757
+ height: 1.8,
2758
+ build: -.1,
2759
+ skin: "#e0b597",
2760
+ hair: "#6b4a2e",
2761
+ top: "#8a8f96",
2762
+ bottom: "#1f1f24"
2763
+ },
2764
+ {
2765
+ height: 1.68,
2766
+ build: 0,
2767
+ skin: "#c68b62",
2768
+ hair: "#3b2a20",
2769
+ top: "#5a3b6b",
2770
+ bottom: "#8a8f96"
2771
+ },
2772
+ {
2773
+ height: 1.76,
2774
+ build: .5,
2775
+ skin: "#f1d3bd",
2776
+ hair: "#9a9a9a",
2777
+ top: "#2f3b52",
2778
+ bottom: "#c9b48a"
2779
+ },
2780
+ {
2781
+ height: 1.6,
2782
+ build: .2,
2783
+ skin: "#9b6645",
2784
+ hair: "#3b2a20",
2785
+ top: "#e8e6de",
2786
+ bottom: "#3b6ea5"
2787
+ },
2788
+ {
2789
+ height: 1.72,
2790
+ build: -.3,
2791
+ skin: "#6c4430",
2792
+ hair: "#1f1a17",
2793
+ top: "#2f5a3b",
2794
+ bottom: "#1f1f24"
2795
+ }
2796
+ ];
2797
+ const ELDERS = [
2798
+ {
2799
+ height: 1.64,
2800
+ build: .2,
2801
+ skin: "#f1d3bd",
2802
+ hair: "#c8c8c4",
2803
+ top: "#8a8f96",
2804
+ bottom: "#2f3b52"
2805
+ },
2806
+ {
2807
+ height: 1.72,
2808
+ build: .3,
2809
+ skin: "#c68b62",
2810
+ hair: "#e6e6e2",
2811
+ top: "#6b4a2e",
2812
+ bottom: "#1f1f24"
2813
+ },
2814
+ {
2815
+ height: 1.58,
2816
+ build: 0,
2817
+ skin: "#6c4430",
2818
+ hair: "#b8b8b4",
2819
+ top: "#5a3b6b",
2820
+ bottom: "#8a8f96"
2821
+ }
2822
+ ];
2823
+ const CHILDREN = [
2824
+ {
2825
+ height: 1.2,
2826
+ build: 0,
2827
+ skin: "#f1d3bd",
2828
+ hair: "#a8793f",
2829
+ top: "#b0553a",
2830
+ bottom: "#2f3b52"
2831
+ },
2832
+ {
2833
+ height: 1.35,
2834
+ build: -.2,
2835
+ skin: "#9b6645",
2836
+ hair: "#1f1a17",
2837
+ top: "#3b6ea5",
2838
+ bottom: "#1f1f24"
2839
+ },
2840
+ {
2841
+ height: 1.28,
2842
+ build: .1,
2843
+ skin: "#e0b597",
2844
+ hair: "#3b2a20",
2845
+ top: "#2f5a3b",
2846
+ bottom: "#c9b48a"
2847
+ }
2848
+ ];
2849
+ function outfitFor(preset, seed) {
2850
+ const list = preset === "human.child" ? CHILDREN : preset === "human.elder" ? ELDERS : ADULTS;
2851
+ return list[Math.floor(unit01(seed, 40) * list.length)];
2852
+ }
2853
+ /** Built-in templates: vehicles render through `ambient-vehicle`, pedestrians as figures. */
2854
+ const DEFAULT_TEMPLATES = {
2855
+ car: (agent) => ({ renderable: {
2856
+ kind: "ambient-vehicle",
2857
+ ref: agent.type
2858
+ } }),
2859
+ train: (agent) => ({ renderable: {
2860
+ kind: "ambient-vehicle",
2861
+ ref: agent.type
2862
+ } }),
2863
+ aircraft: (agent) => ({ renderable: {
2864
+ kind: "ambient-vehicle",
2865
+ ref: agent.type
2866
+ } }),
2867
+ pedestrian: (agent) => {
2868
+ const outfit = outfitFor(agent.type, agent.seed);
2869
+ return {
2870
+ figure: {
2871
+ preset: agent.type,
2872
+ height: outfit.height,
2873
+ build: outfit.build,
2874
+ palette: {
2875
+ skin: outfit.skin,
2876
+ hair: outfit.hair,
2877
+ top: outfit.top,
2878
+ bottom: outfit.bottom
2879
+ },
2880
+ facing: "manual",
2881
+ speedSource: "transform"
2882
+ },
2883
+ renderable: {
2884
+ kind: "figure",
2885
+ ref: "procedural"
2886
+ }
2887
+ };
2888
+ }
2889
+ };
2890
+ //#endregion
2891
+ //#region src/kernel/spawn/spawner.ts
2892
+ /**
2893
+ * Observer-driven spawning and cleanup. Agents appear on lanes in a ring around the observer
2894
+ * (outside a near radius and, close by, outside the view cone) until each class reaches its
2895
+ * density target, and are removed once they are beyond the keep radius, stuck out of sight, or
2896
+ * their lane's tile has gone.
2897
+ */
2898
+ const SPAWN_WEIGHT = {
2899
+ motorway: .45,
2900
+ trunk: .7,
2901
+ service: .2,
2902
+ living: .3
2903
+ };
2904
+ const LANE_CLASS = {
2905
+ car: "road",
2906
+ pedestrian: "walk",
2907
+ train: "rail"
2908
+ };
2909
+ /** Resolve the observer from state, an entity, or the first `ambientObserver` entity. */
2910
+ function resolveObserver(world, state) {
2911
+ const fromEntity = (id) => {
2912
+ const t = world.get(id, Transform);
2913
+ if (t === void 0) return void 0;
2914
+ const f = quatRotateVec3(t.rot, [
2915
+ 0,
2916
+ 0,
2917
+ 1
2918
+ ]);
2919
+ const length = dmath.hypot(f[0], f[2]);
2920
+ const settings = world.get(id, AmbientObserver);
2921
+ return {
2922
+ x: t.pos[0],
2923
+ y: t.pos[1],
2924
+ z: t.pos[2],
2925
+ ...length > 1e-6 ? {
2926
+ fx: f[0] / length,
2927
+ fz: f[2] / length
2928
+ } : {},
2929
+ density: settings?.density ?? 1,
2930
+ ...settings?.radius !== void 0 ? { radius: settings.radius } : {},
2931
+ ...settings?.despawnRadius !== void 0 ? { keep: settings.despawnRadius } : {}
2932
+ };
2933
+ };
2934
+ const observer = state?.observer;
2935
+ if (observer?.entity !== void 0) return fromEntity(observer.entity);
2936
+ if (observer?.pos !== void 0) return {
2937
+ x: observer.pos[0],
2938
+ y: observer.pos[1],
2939
+ z: observer.pos[2],
2940
+ ...observer.forward !== void 0 ? {
2941
+ fx: observer.forward[0],
2942
+ fz: observer.forward[1]
2943
+ } : {},
2944
+ density: 1
2945
+ };
2946
+ const first = world.query(AmbientObserver, Transform).first();
2947
+ return first !== void 0 ? fromEntity(first[0]) : void 0;
2948
+ }
2949
+ /** The policy with an observer entity's car radius overrides applied. */
2950
+ function observerPolicy(policy, observer) {
2951
+ if (observer?.radius === void 0 && observer?.keep === void 0) return policy;
2952
+ const far = observer.radius ?? policy.car.far;
2953
+ const keep = dmath.max(far, observer.keep ?? (observer.radius !== void 0 ? far * 1.3 : policy.car.keep));
2954
+ return {
2955
+ ...policy,
2956
+ car: {
2957
+ ...policy.car,
2958
+ near: dmath.min(policy.car.near, far * .2),
2959
+ far,
2960
+ keep
2961
+ }
2962
+ };
2963
+ }
2964
+ function classPolicy(policy, kind) {
2965
+ return policy[kind];
2966
+ }
2967
+ /** Remove agents that left the ring, lost their lane, or finished their corridor. */
2968
+ function despawnAgents(world, env, observer) {
2969
+ const { net, policy, tick, tickRate } = env;
2970
+ const leads = /* @__PURE__ */ new Set();
2971
+ const doomed = /* @__PURE__ */ new Set();
2972
+ for (const [id, a] of world.query(AmbientAgent)) if (a.consist === void 0) leads.add(id);
2973
+ const over = {
2974
+ car: [],
2975
+ pedestrian: [],
2976
+ train: [],
2977
+ aircraft: []
2978
+ };
2979
+ for (const [id, a, t] of world.query(AmbientAgent, Transform)) {
2980
+ if (a.consist !== void 0) {
2981
+ if (!leads.has(a.consist)) doomed.add(id);
2982
+ continue;
2983
+ }
2984
+ if (observer !== void 0) over[a.kind].push({
2985
+ id,
2986
+ distance: dmath.hypot(t.pos[0] - observer.x, t.pos[2] - observer.z)
2987
+ });
2988
+ if (a.air !== void 0) {
2989
+ if (a.s >= a.air.length) doomed.add(id);
2990
+ } else if (net.lane(a.lane) === void 0) {
2991
+ doomed.add(id);
2992
+ continue;
2993
+ }
2994
+ if (observer === void 0) continue;
2995
+ const c = classPolicy(policy, a.kind);
2996
+ const distance = dmath.hypot(t.pos[0] - observer.x, t.pos[2] - observer.z);
2997
+ if (distance > c.keep) {
2998
+ doomed.add(id);
2999
+ continue;
3000
+ }
3001
+ if (distance <= c.near) continue;
3002
+ const stuck = a.state === "wait" && tick - a.since > policy.stuckSeconds * tickRate;
3003
+ const lane = net.lane(a.lane);
3004
+ const deadEnd = a.air === void 0 && a.kind !== "train" && a.next === void 0 && lane !== void 0 && a.s >= lane.length - .6;
3005
+ if (stuck || deadEnd) doomed.add(id);
3006
+ }
3007
+ for (const kind of AMBIENT_KINDS) {
3008
+ const c = classPolicy(policy, kind);
3009
+ const cap = c.enabled ? c.max : 0;
3010
+ const live = over[kind].filter((x) => !doomed.has(x.id));
3011
+ if (live.length <= cap) continue;
3012
+ live.sort((x, y) => y.distance - x.distance || (x.id < y.id ? -1 : 1));
3013
+ let trim = dmath.min(4, live.length - cap);
3014
+ for (const x of live) {
3015
+ if (trim <= 0) break;
3016
+ if (x.distance <= c.near && c.enabled) continue;
3017
+ doomed.add(x.id);
3018
+ trim--;
3019
+ }
3020
+ }
3021
+ for (const [id, a] of world.query(AmbientAgent)) if (a.consist !== void 0 && doomed.has(a.consist)) doomed.add(id);
3022
+ for (const id of [...doomed].sort()) world.destroy(id);
3023
+ return doomed.size;
3024
+ }
3025
+ /** Spawn toward each class's density target, within the per-run budget. */
3026
+ function spawnAgents(world, env, observer, state) {
3027
+ const { policy, tick } = env;
3028
+ const rng = createRng(`${env.seed}:ambient:${tick}`);
3029
+ const counts = {
3030
+ car: 0,
3031
+ pedestrian: 0,
3032
+ train: 0,
3033
+ aircraft: 0
3034
+ };
3035
+ const occupancy = /* @__PURE__ */ new Map();
3036
+ for (const [, a] of world.query(AmbientAgent)) {
3037
+ if (a.consist === void 0) counts[a.kind]++;
3038
+ if (a.air !== void 0) continue;
3039
+ const list = occupancy.get(a.lane);
3040
+ if (list === void 0) occupancy.set(a.lane, [a.s]);
3041
+ else list.push(a.s);
3042
+ }
3043
+ const ctx = {
3044
+ world,
3045
+ env,
3046
+ observer,
3047
+ rng,
3048
+ occupancy,
3049
+ state
3050
+ };
3051
+ const targets = {};
3052
+ for (const kind of AMBIENT_KINDS) targets[kind] = target(ctx, kind);
3053
+ let budget = policy.spawnBudget;
3054
+ for (let round = 0; round < policy.spawnBudget && budget > 0; round++) {
3055
+ let any = false;
3056
+ for (const kind of AMBIENT_KINDS) {
3057
+ if (budget <= 0) break;
3058
+ if (counts[kind] >= targets[kind]) continue;
3059
+ any = true;
3060
+ if (spawnOne(ctx, kind)) {
3061
+ counts[kind]++;
3062
+ budget--;
3063
+ }
3064
+ }
3065
+ if (!any) break;
3066
+ }
3067
+ }
3068
+ function target(ctx, kind) {
3069
+ const c = classPolicy(ctx.env.policy, kind);
3070
+ if (!c.enabled || c.max <= 0) return 0;
3071
+ if (kind === "aircraft") return c.max;
3072
+ const meters = ctx.env.net.grid.laneMeters(ctx.observer.x, ctx.observer.z, c.far, LANE_CLASS[kind]);
3073
+ const wanted = meters / 1e3 * c.perLaneKm * ctx.observer.density;
3074
+ if (kind === "train" && meters > 400) return dmath.min(c.max, dmath.max(1, dmath.round(wanted)));
3075
+ return dmath.min(c.max, dmath.round(wanted));
3076
+ }
3077
+ function spawnOne(ctx, kind) {
3078
+ if (kind === "aircraft") return spawnAircraft(ctx);
3079
+ const { env, observer, rng } = ctx;
3080
+ const { net } = env;
3081
+ const c = classPolicy(env.policy, kind);
3082
+ const cls = LANE_CLASS[kind];
3083
+ const spans = net.grid.spansWithin(observer.x, observer.z, c.near, c.far);
3084
+ const weights = [];
3085
+ const edges = [];
3086
+ let total = 0;
3087
+ for (const span of spans) {
3088
+ const edge = net.edge(span.edge);
3089
+ let lanes = 0;
3090
+ for (const id of edge.lanes) if (net.lane(id)?.class === cls) lanes++;
3091
+ let w = lanes * (span.d1 - span.d0);
3092
+ if (kind === "car") w *= SPAWN_WEIGHT[edge.kind] ?? 1;
3093
+ weights.push(w);
3094
+ edges.push(edge);
3095
+ total += w;
3096
+ }
3097
+ if (total <= 0) return false;
3098
+ const types = env.types[kind === "pedestrian" ? "pedestrian" : kind];
3099
+ for (let attempt = 0; attempt < 6; attempt++) {
3100
+ let pick = rng.next() * total;
3101
+ let index = 0;
3102
+ while (index < weights.length - 1 && pick >= weights[index]) {
3103
+ pick -= weights[index];
3104
+ index++;
3105
+ }
3106
+ const span = spans[index];
3107
+ const edge = edges[index];
3108
+ if (span === void 0 || edge === void 0) continue;
3109
+ const candidates = edge.lanes.map((id) => net.lane(id)).filter((l) => l !== void 0 && l.class === cls);
3110
+ const lane = candidates[rng.int(candidates.length)];
3111
+ if (lane === void 0) continue;
3112
+ const seq = ctx.state.nextSeq;
3113
+ const seed = fmix32(seq ^ env.seed);
3114
+ const vehicle = kind === "pedestrian" ? void 0 : pickWeighted(types, unit01(seed, 10));
3115
+ const length = kind === "pedestrian" ? .5 : vehicle?.length ?? 4.5;
3116
+ const width = kind === "pedestrian" ? .5 : vehicle?.width ?? 1.8;
3117
+ const cars = kind === "train" ? dmath.max(1, vehicle?.cars ?? 2) : 1;
3118
+ const behind = kind === "train" ? (cars - 1) * (length + 1) : 0;
3119
+ const s = laneCoordinate(lane, edge, span.d0 + rng.next() * (span.d1 - span.d0));
3120
+ if (s < behind + length / 2 + 1 || s > lane.length - length / 2 - 1) continue;
3121
+ const sample = sampleLaneBody(lane, edge, s, laneSample());
3122
+ const dx = sample.x - observer.x;
3123
+ const dz = sample.z - observer.z;
3124
+ const distance = dmath.hypot(dx, dz);
3125
+ if (distance < c.near || distance > c.far) continue;
3126
+ const coneReach = Math.min(c.far * .6, env.policy.forwardConeReach);
3127
+ if (observer.fx !== void 0 && observer.fz !== void 0 && distance < coneReach) {
3128
+ if ((dx * observer.fx + dz * observer.fz) / dmath.max(distance, 1e-6) > env.policy.forwardConeCos) continue;
3129
+ }
3130
+ const minGap = kind === "train" ? 250 : kind === "pedestrian" ? 2.5 : length + env.policy.driver.gap + 8;
3131
+ const clearLanes = kind === "train" ? edge.lanes : [lane.id];
3132
+ let clear = true;
3133
+ for (const id of clearLanes) for (const other of ctx.occupancy.get(id) ?? []) if (dmath.abs(other - s) < minGap + behind) clear = false;
3134
+ if (!clear) continue;
3135
+ createLaneAgent(ctx, kind, lane, edge, s, seed, vehicle, length, width, cars);
3136
+ return true;
3137
+ }
3138
+ return false;
3139
+ }
3140
+ function nextSeqId(ctx, kind) {
3141
+ for (;;) {
3142
+ const seq = ctx.state.nextSeq++;
3143
+ const id = `ambient:${kind}:${seq}`;
3144
+ if (!ctx.world.exists(id)) return {
3145
+ id,
3146
+ seq
3147
+ };
3148
+ }
3149
+ }
3150
+ function createLaneAgent(ctx, kind, lane, edge, s, seed, vehicle, length, width, cars) {
3151
+ const { env } = ctx;
3152
+ const { id } = nextSeqId(ctx, kind);
3153
+ const type = kind === "pedestrian" ? pickWeighted(env.types.pedestrian, unit01(seed, 10))?.preset ?? "human.adult" : vehicle?.id ?? "proxy";
3154
+ const palette = vehicle?.colors ?? (kind === "car" ? CAR_COLORS : void 0);
3155
+ const color = palette !== void 0 && palette.length > 0 ? palette[dmath.floor(unit01(seed, 11) * palette.length)] : void 0;
3156
+ const speed = kind === "pedestrian" ? 1.15 + .5 * unit01(seed, 2) : kind === "train" ? edge.speed * .5 : dmath.min(edge.speed * .7, vehicle?.cruise ?? edge.speed);
3157
+ const next = chooseNext(lane, seed, 0);
3158
+ const agent = {
3159
+ kind,
3160
+ type,
3161
+ ...color !== void 0 ? { color } : {},
3162
+ lane: lane.id,
3163
+ s: q4(s),
3164
+ speed: q4(speed),
3165
+ ...next !== void 0 ? { next } : {},
3166
+ seed,
3167
+ length,
3168
+ width,
3169
+ state: "move",
3170
+ since: env.tick,
3171
+ hops: 0,
3172
+ ...edge.tunnel ? { hidden: true } : {},
3173
+ ...kind === "train" ? { trail: [] } : {},
3174
+ spawnedTick: env.tick
3175
+ };
3176
+ spawnWithTemplate(ctx, id, agent);
3177
+ if (kind === "train") for (let k = 1; k < cars; k++) {
3178
+ const back = walkBack(env.net, lane.id, s, void 0, [], k * (length + 1));
3179
+ const { id: carId } = nextSeqId(ctx, kind);
3180
+ spawnWithTemplate(ctx, carId, {
3181
+ ...agent,
3182
+ lane: back.lane,
3183
+ s: q4(back.s),
3184
+ consist: id,
3185
+ carIndex: k,
3186
+ seed: fmix32(seed + k)
3187
+ });
3188
+ }
3189
+ ctx.occupancy.set(lane.id, [...ctx.occupancy.get(lane.id) ?? [], s]);
3190
+ }
3191
+ function spawnWithTemplate(ctx, id, agent) {
3192
+ const { env, world } = ctx;
3193
+ const sample = agentSample(env.net, agent, laneSample());
3194
+ if (sample === void 0) return;
3195
+ const rot = agentRotation(sample, agent.kind !== "pedestrian");
3196
+ const transform = {
3197
+ pos: [
3198
+ q4(sample.x),
3199
+ q4(sample.y),
3200
+ q4(sample.z)
3201
+ ],
3202
+ rot: [
3203
+ q4(rot[0]),
3204
+ q4(rot[1]),
3205
+ q4(rot[2]),
3206
+ q4(rot[3])
3207
+ ],
3208
+ teleport: true
3209
+ };
3210
+ const template = env.templates[agent.kind];
3211
+ const extra = template?.({
3212
+ id,
3213
+ kind: agent.kind,
3214
+ type: agent.type,
3215
+ seed: agent.seed,
3216
+ ...agent.color !== void 0 ? { color: agent.color } : {}
3217
+ });
3218
+ const scale = (extra?.transform)?.scale;
3219
+ if (scale !== void 0) transform.scale = scale;
3220
+ world.spawnRaw({
3221
+ ...extra ?? {},
3222
+ ambientAgent: agent,
3223
+ transform
3224
+ }, id);
3225
+ ctx.state.spawned++;
3226
+ }
3227
+ function spawnAircraft(ctx) {
3228
+ const { env, observer, rng } = ctx;
3229
+ const c = env.policy.aircraft;
3230
+ const types = env.types.aircraft;
3231
+ const seed = fmix32(ctx.state.nextSeq ^ env.seed ^ 1515870810);
3232
+ const vehicle = pickWeighted(types, unit01(seed, 10));
3233
+ const length = vehicle?.length ?? 38;
3234
+ const width = vehicle?.width ?? 36;
3235
+ let corridor;
3236
+ let speed = vehicle?.cruise ?? 75 + 55 * rng.next();
3237
+ const runways = env.net.runways().filter((r) => dmath.hypot((r.ax + r.bx) / 2 - observer.x, (r.az + r.bz) / 2 - observer.z) < 6e3);
3238
+ if (runways.length > 0 && rng.next() < .4) {
3239
+ const runway = runways[rng.int(runways.length)];
3240
+ const flip = rng.next() < .5;
3241
+ const ax = flip ? runway.bx : runway.ax;
3242
+ const az = flip ? runway.bz : runway.az;
3243
+ const bx = flip ? runway.ax : runway.bx;
3244
+ const bz = flip ? runway.az : runway.bz;
3245
+ const len = dmath.hypot(bx - ax, bz - az) || 1;
3246
+ const dx = (bx - ax) / len;
3247
+ const dz = (bz - az) / len;
3248
+ if (rng.next() < .5) {
3249
+ const tx = ax + dx * 300;
3250
+ const tz = az + dz * 300;
3251
+ corridor = {
3252
+ x: tx - dx * 1e4,
3253
+ z: tz - dz * 1e4,
3254
+ dx,
3255
+ dz,
3256
+ y0: runway.y + 524,
3257
+ y1: runway.y + 4,
3258
+ length: 1e4
3259
+ };
3260
+ speed = 70;
3261
+ } else {
3262
+ corridor = {
3263
+ x: ax + dx * 900,
3264
+ z: az + dz * 900,
3265
+ dx,
3266
+ dz,
3267
+ y0: runway.y + 25,
3268
+ y1: runway.y + 1400,
3269
+ length: 12e3
3270
+ };
3271
+ speed = 80;
3272
+ }
3273
+ } else {
3274
+ const heading = rng.next() * dmath.TAU;
3275
+ const dx = dmath.sin(heading);
3276
+ const dz = dmath.cos(heading);
3277
+ const offset = (rng.next() - .5) * c.far;
3278
+ const cx = observer.x - dz * offset;
3279
+ const cz = observer.z + dx * offset;
3280
+ const altitude = env.ground(cx, cz) + 450 * (1 + rng.int(3));
3281
+ corridor = {
3282
+ x: cx - dx * c.far,
3283
+ z: cz - dz * c.far,
3284
+ dx,
3285
+ dz,
3286
+ y0: altitude,
3287
+ y1: altitude,
3288
+ length: c.far * 2
3289
+ };
3290
+ }
3291
+ const { id } = nextSeqId(ctx, "aircraft");
3292
+ spawnWithTemplate(ctx, id, {
3293
+ kind: "aircraft",
3294
+ type: vehicle?.id ?? "proxy.airliner",
3295
+ ...vehicle?.colors?.[0] !== void 0 ? { color: vehicle.colors[0] } : {},
3296
+ lane: "",
3297
+ s: 0,
3298
+ speed: q4(speed),
3299
+ seed,
3300
+ length,
3301
+ width,
3302
+ state: "move",
3303
+ since: env.tick,
3304
+ hops: 0,
3305
+ air: {
3306
+ x: q4(corridor.x),
3307
+ z: q4(corridor.z),
3308
+ dx: q4(corridor.dx),
3309
+ dz: q4(corridor.dz),
3310
+ y0: q4(corridor.y0),
3311
+ y1: q4(corridor.y1),
3312
+ length: corridor.length
3313
+ },
3314
+ spawnedTick: env.tick
3315
+ });
3316
+ return true;
3317
+ }
3318
+ /** Seed integer for a world seed plus an optional salt. */
3319
+ function ambientSeed(seed, salt) {
3320
+ return seedToInt(salt !== void 0 ? `${seed}:${salt}` : `${seed}:ambient`);
3321
+ }
3322
+ //#endregion
3323
+ //#region src/kernel/install.ts
3324
+ /**
3325
+ * `installAmbient(world)`: the capability entry point. Registers the transport network on the
3326
+ * world (outside world state), the `ambient-spawn` and `ambient-agents` physics systems, the
3327
+ * `ambient.observer` and `ambient.policy` commands, and returns the handle hosts and scripts use.
3328
+ */
3329
+ const handles = /* @__PURE__ */ new WeakMap();
3330
+ const Mounted = componentHandle("mounted");
3331
+ const Collider = componentHandle("collider");
3332
+ function checkObserverPayload(payload) {
3333
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) return {
3334
+ ok: false,
3335
+ message: "ambient.observer payload must be an object"
3336
+ };
3337
+ const p = payload;
3338
+ if (p.clear === true) return { ok: true };
3339
+ if (typeof p.entity === "string" && p.entity.length > 0) return { ok: true };
3340
+ const pos = p.pos;
3341
+ if (!Array.isArray(pos) || pos.length !== 3 || !pos.every((v) => typeof v === "number" && Number.isFinite(v))) return {
3342
+ ok: false,
3343
+ message: "ambient.observer needs pos: [x, y, z], entity: \"<id>\", or clear: true"
3344
+ };
3345
+ const forward = p.forward;
3346
+ if (forward !== void 0 && (!Array.isArray(forward) || forward.length !== 2 || !forward.every((v) => typeof v === "number" && Number.isFinite(v)))) return {
3347
+ ok: false,
3348
+ message: "ambient.observer forward must be [x, z]"
3349
+ };
3350
+ return { ok: true };
3351
+ }
3352
+ function checkPolicyPayload(payload) {
3353
+ return payload !== null && typeof payload === "object" && !Array.isArray(payload) ? { ok: true } : {
3354
+ ok: false,
3355
+ message: "ambient.policy payload must be an object of policy overrides"
3356
+ };
3357
+ }
3358
+ /** Install the ambient systems (idempotent per world) and return the handle. */
3359
+ function installAmbient(world, options = {}) {
3360
+ const existing = handles.get(world);
3361
+ if (existing !== void 0) return existing;
3362
+ const ground = options.ground ?? (() => 0);
3363
+ const network = new TransportNetwork({
3364
+ traffic: options.traffic ?? "right",
3365
+ tunnels: options.tunnels ?? "hidden",
3366
+ ground
3367
+ });
3368
+ const classes = new Set(options.classes ?? ["car"]);
3369
+ network.setClasses([
3370
+ ...classes.has("car") ? ["road"] : [],
3371
+ ...classes.has("pedestrian") ? ["walk"] : [],
3372
+ ...classes.has("train") ? ["rail"] : []
3373
+ ]);
3374
+ const base = mergePolicy(DEFAULT_POLICY, {
3375
+ car: { enabled: classes.has("car") },
3376
+ pedestrian: { enabled: classes.has("pedestrian") },
3377
+ train: { enabled: classes.has("train") },
3378
+ aircraft: { enabled: classes.has("aircraft") }
3379
+ }, options.policy);
3380
+ const types = {
3381
+ ...DEFAULT_TYPES,
3382
+ ...options.types
3383
+ };
3384
+ for (const kind of [
3385
+ "car",
3386
+ "train",
3387
+ "aircraft",
3388
+ "pedestrian"
3389
+ ]) if (types[kind].length === 0) types[kind] = DEFAULT_TYPES[kind];
3390
+ const templates = {};
3391
+ for (const kind of AMBIENT_KINDS) templates[kind] = options.templates?.[kind] !== void 0 ? options.templates[kind] ?? null : DEFAULT_TEMPLATES[kind];
3392
+ const seed = ambientSeed(options.seed ?? "ambient");
3393
+ const yieldToDriven = options.yieldToDriven ?? true;
3394
+ let budget = {};
3395
+ let solids = [];
3396
+ const pending = [];
3397
+ if (!world.exists("$ambient")) world.spawnRaw({ ambientState: {
3398
+ nextSeq: 0,
3399
+ spawned: 0,
3400
+ despawned: 0
3401
+ } }, AMBIENT_ENTITY);
3402
+ let cachedFor;
3403
+ let cachedBudget;
3404
+ let cached = base;
3405
+ const effectivePolicy = () => {
3406
+ const overrides = world.get(AMBIENT_ENTITY, AmbientState)?.policy;
3407
+ if (overrides !== cachedFor || budget !== cachedBudget) {
3408
+ cached = policyForBudget(mergePolicy(base, overrides), budget);
3409
+ cachedFor = overrides;
3410
+ cachedBudget = budget;
3411
+ }
3412
+ return cached;
3413
+ };
3414
+ const flush = () => {
3415
+ for (const change of pending.splice(0)) if (change.op === "add") network.registerTile(change.tile);
3416
+ else network.unregisterTile(change.key);
3417
+ };
3418
+ const writeState = (patch) => {
3419
+ const next = {
3420
+ ...world.get("$ambient", AmbientState) ?? {
3421
+ nextSeq: 0,
3422
+ spawned: 0,
3423
+ despawned: 0
3424
+ },
3425
+ ...patch
3426
+ };
3427
+ for (const key of Object.keys(patch)) if (patch[key] === void 0) delete next[key];
3428
+ world.set(AMBIENT_ENTITY, AmbientState, next);
3429
+ };
3430
+ world.addSystem((w, ctx) => {
3431
+ flush();
3432
+ const state = w.get(AMBIENT_ENTITY, AmbientState);
3433
+ const observer = resolveObserver(w, state);
3434
+ const policy = observerPolicy(effectivePolicy(), observer);
3435
+ const env = {
3436
+ net: network,
3437
+ policy,
3438
+ tick: ctx.tick,
3439
+ tickRate: w.tickRate,
3440
+ types,
3441
+ templates,
3442
+ seed,
3443
+ ground
3444
+ };
3445
+ const removed = despawnAgents(w, env, observer);
3446
+ const counters = {
3447
+ nextSeq: state?.nextSeq ?? 0,
3448
+ spawned: state?.spawned ?? 0
3449
+ };
3450
+ if (observer !== void 0 && ctx.tick % dmath.max(1, policy.spawnEveryTicks) === 0) spawnAgents(w, env, observer, counters);
3451
+ if (removed > 0 || counters.nextSeq !== (state?.nextSeq ?? 0)) writeState({
3452
+ nextSeq: counters.nextSeq,
3453
+ spawned: counters.spawned,
3454
+ despawned: (state?.despawned ?? 0) + removed
3455
+ });
3456
+ }, {
3457
+ phase: "physics",
3458
+ name: "ambient-spawn",
3459
+ priority: -10
3460
+ });
3461
+ world.addSystem((w, ctx) => {
3462
+ const driven = [...solids];
3463
+ const watcher = w.get(AMBIENT_ENTITY, AmbientState)?.observer?.entity;
3464
+ const watched = watcher !== void 0 ? w.get(watcher, Transform) : void 0;
3465
+ if (watcher !== void 0 && watched !== void 0) {
3466
+ const radius = w.get(watcher, Collider)?.radius;
3467
+ driven.push({
3468
+ x: watched.pos[0],
3469
+ z: watched.pos[2],
3470
+ radius: typeof radius === "number" ? radius : 1
3471
+ });
3472
+ }
3473
+ if (yieldToDriven) for (const [, mounted] of w.query(Mounted)) {
3474
+ const vehicle = typeof mounted.vehicle === "string" ? mounted.vehicle : void 0;
3475
+ const t = vehicle !== void 0 ? w.get(vehicle, Transform) : void 0;
3476
+ if (t !== void 0) driven.push({
3477
+ x: t.pos[0],
3478
+ z: t.pos[2],
3479
+ radius: 2.6
3480
+ });
3481
+ }
3482
+ stepAgents(w, {
3483
+ net: network,
3484
+ policy: effectivePolicy(),
3485
+ tick: ctx.tick,
3486
+ tickRate: w.tickRate,
3487
+ dt: ctx.dt,
3488
+ solids: driven
3489
+ });
3490
+ }, {
3491
+ phase: "physics",
3492
+ name: "ambient-agents",
3493
+ priority: 0
3494
+ });
3495
+ world.registerCommand("ambient.observer", (w, command) => {
3496
+ const p = command.payload;
3497
+ const tick = w.tick;
3498
+ if (p.clear === true) writeState({ observer: void 0 });
3499
+ else if (typeof p.entity === "string") writeState({ observer: {
3500
+ entity: p.entity,
3501
+ setAtTick: tick
3502
+ } });
3503
+ else writeState({ observer: {
3504
+ pos: p.pos,
3505
+ ...Array.isArray(p.forward) ? { forward: p.forward } : {},
3506
+ setAtTick: tick
3507
+ } });
3508
+ }, { validatePayload: checkObserverPayload });
3509
+ world.registerCommand("ambient.policy", (w, command) => {
3510
+ writeState({ policy: mergePolicy(w.get("$ambient", AmbientState)?.policy ?? {}, command.payload) });
3511
+ }, { validatePayload: checkPolicyPayload });
3512
+ const sample = laneSample();
3513
+ const handle = {
3514
+ world,
3515
+ network,
3516
+ registerTile(tile) {
3517
+ pending.push({
3518
+ op: "add",
3519
+ tile
3520
+ });
3521
+ },
3522
+ unregisterTile(key) {
3523
+ pending.push({
3524
+ op: "remove",
3525
+ key
3526
+ });
3527
+ },
3528
+ flush,
3529
+ addDocument(doc) {
3530
+ network.addDocument(doc);
3531
+ },
3532
+ addPolyline(line) {
3533
+ network.addPolyline(line);
3534
+ },
3535
+ setObserver(observer) {
3536
+ if (observer === null) writeState({ observer: void 0 });
3537
+ else if ("entity" in observer) writeState({ observer: {
3538
+ entity: observer.entity,
3539
+ setAtTick: world.tick
3540
+ } });
3541
+ else writeState({ observer: {
3542
+ pos: [
3543
+ observer.pos[0],
3544
+ observer.pos[1],
3545
+ observer.pos[2]
3546
+ ],
3547
+ ...observer.forward !== void 0 ? { forward: [observer.forward[0], observer.forward[1]] } : {},
3548
+ setAtTick: world.tick
3549
+ } });
3550
+ },
3551
+ setPolicy(policy) {
3552
+ writeState({ policy: mergePolicy(world.get("$ambient", AmbientState)?.policy ?? {}, policy) });
3553
+ },
3554
+ setBudget(next) {
3555
+ budget = { ...next };
3556
+ },
3557
+ setSolids(next) {
3558
+ solids = [...next];
3559
+ },
3560
+ policy: effectivePolicy,
3561
+ stats() {
3562
+ const agents = {
3563
+ car: 0,
3564
+ pedestrian: 0,
3565
+ train: 0,
3566
+ aircraft: 0
3567
+ };
3568
+ let waiting = 0;
3569
+ for (const [, a] of world.query(AmbientAgent)) {
3570
+ agents[a.kind]++;
3571
+ if (a.state === "wait") waiting++;
3572
+ }
3573
+ const state = world.get(AMBIENT_ENTITY, AmbientState);
3574
+ return {
3575
+ network: network.stats(),
3576
+ agents,
3577
+ waiting,
3578
+ spawned: state?.spawned ?? 0,
3579
+ despawned: state?.despawned ?? 0,
3580
+ pendingTiles: pending.length
3581
+ };
3582
+ },
3583
+ laneAt: (x, z, opts) => network.laneAt(x, z, opts),
3584
+ laneSample: (lane, s) => network.sampleLane(lane, s, laneSample()),
3585
+ agentsNear(x, z, radius, kind) {
3586
+ const out = [];
3587
+ for (const [id, a, t] of world.query(AmbientAgent, Transform)) {
3588
+ if (kind !== void 0 && a.kind !== kind) continue;
3589
+ if (dmath.hypot(t.pos[0] - x, t.pos[2] - z) <= radius) out.push(id);
3590
+ }
3591
+ return out;
3592
+ },
3593
+ blocks(box, except) {
3594
+ const cos = dmath.cos(box.yaw);
3595
+ const sin = dmath.sin(box.yaw);
3596
+ for (const [id, a] of world.query(AmbientAgent)) {
3597
+ if (id === except || a.kind !== "car" && a.kind !== "train") continue;
3598
+ const at = agentSample(network, a, sample);
3599
+ if (at === void 0) continue;
3600
+ const reach = dmath.hypot(box.halfSize[0], box.halfSize[2]) + a.length / 2 + 1;
3601
+ if (dmath.hypot(at.x - box.center[0], at.z - box.center[2]) > reach) continue;
3602
+ if (dmath.abs(at.y + .8 - box.center[1]) > box.halfSize[1] + .8) continue;
3603
+ const ax = [
3604
+ [sin, cos],
3605
+ [cos, -sin],
3606
+ [at.dx, at.dz],
3607
+ [at.dz, -at.dx]
3608
+ ];
3609
+ const ox = at.x - box.center[0];
3610
+ const oz = at.z - box.center[2];
3611
+ let separated = false;
3612
+ for (const [nx, nz] of ax) if (dmath.abs(ox * nx + oz * nz) > box.halfSize[2] * dmath.abs(sin * nx + cos * nz) + box.halfSize[0] * dmath.abs(cos * nx - sin * nz) + (a.length / 2 * dmath.abs(at.dx * nx + at.dz * nz) + a.width / 2 * dmath.abs(at.dz * nx - at.dx * nz))) {
3613
+ separated = true;
3614
+ break;
3615
+ }
3616
+ if (!separated) return true;
3617
+ }
3618
+ return false;
3619
+ },
3620
+ despawnAll(kind) {
3621
+ for (const [id, a] of world.query(AmbientAgent)) if (kind === void 0 || a.kind === kind) world.destroy(id);
3622
+ },
3623
+ dispose() {
3624
+ world.removeSystem("ambient-spawn");
3625
+ world.removeSystem("ambient-agents");
3626
+ for (const [id] of world.query(AmbientAgent)) world.destroy(id);
3627
+ if (world.exists("$ambient")) world.destroy(AMBIENT_ENTITY);
3628
+ network.clear();
3629
+ handles.delete(world);
3630
+ }
3631
+ };
3632
+ handles.set(world, handle);
3633
+ return handle;
3634
+ }
3635
+ /** The ambient handle installed on a world, if any. */
3636
+ function ambientOf(world) {
3637
+ return handles.get(world);
3638
+ }
3639
+ //#endregion
3640
+ //#region src/kernel/script-api.ts
3641
+ /** The script-api namespace for ambient life (`molen.ambient.*`); pass via `buildWorld` capabilities. */
3642
+ function ambientScriptApi(handle) {
3643
+ return {
3644
+ stats: () => handle.stats(),
3645
+ setObserver: (target) => handle.setObserver(typeof target === "string" ? { entity: target } : target),
3646
+ setPolicy: (policy) => handle.setPolicy(policy),
3647
+ laneAt: (x, z, opts) => handle.laneAt(x, z, opts),
3648
+ laneSample: (lane, s) => {
3649
+ const sample = handle.laneSample(lane, s);
3650
+ return sample === void 0 ? void 0 : {
3651
+ pos: [
3652
+ sample.x,
3653
+ sample.y,
3654
+ sample.z
3655
+ ],
3656
+ dir: [sample.dx, sample.dz],
3657
+ grade: sample.grade
3658
+ };
3659
+ },
3660
+ agentsNear: (x, z, radius, kind) => handle.agentsNear(x, z, radius, kind),
3661
+ addRoad: (points, opts = {}) => handle.addPolyline({
3662
+ ...opts,
3663
+ class: "road",
3664
+ points
3665
+ }),
3666
+ addPolyline: (line) => handle.addPolyline(line),
3667
+ despawnAll: (kind) => handle.despawnAll(kind)
3668
+ };
3669
+ }
3670
+ //#endregion
3671
+ //#region src/kernel/capability.ts
3672
+ /** Build-world capability hook: `buildWorld(scene, setup, { capabilities: [ambientCapability()] })`. */
3673
+ function ambientCapability(opts = {}) {
3674
+ return (world, manifest) => {
3675
+ const block = manifest.ambient;
3676
+ if (block === void 0) return void 0;
3677
+ const templates = { ...opts.templates };
3678
+ for (const [kind, prefab] of Object.entries(block.templates ?? {})) {
3679
+ const components = resolvePrefab(manifest, prefab);
3680
+ templates[kind] = (agent) => {
3681
+ const base = cloneMap(components);
3682
+ const builtIn = opts.templates?.[kind];
3683
+ return builtIn ? deepMergeJson(builtIn(agent), base) : base;
3684
+ };
3685
+ }
3686
+ const density = block.density ?? {};
3687
+ const car = {
3688
+ ...density.car !== void 0 ? { perLaneKm: density.car } : {},
3689
+ ...block.radius !== void 0 ? {
3690
+ far: block.radius,
3691
+ near: Math.min(block.radius * .2, 60)
3692
+ } : {},
3693
+ ...block.despawnRadius !== void 0 ? { keep: block.despawnRadius } : block.radius !== void 0 ? { keep: block.radius * 1.3 } : {}
3694
+ };
3695
+ const handle = installAmbient(world, {
3696
+ ...opts,
3697
+ traffic: block.drivingSide ?? "right",
3698
+ classes: block.classes ?? ["car"],
3699
+ seed: `${manifest.seed ?? 0}:${block.seedSalt ?? "ambient"}`,
3700
+ templates,
3701
+ policy: {
3702
+ ...opts.policy,
3703
+ car: {
3704
+ ...opts.policy?.car,
3705
+ ...car
3706
+ },
3707
+ ...density.pedestrian !== void 0 ? { pedestrian: { perLaneKm: density.pedestrian } } : {},
3708
+ ...density.train !== void 0 ? { train: { perLaneKm: density.train } } : {},
3709
+ ...density.aircraft !== void 0 ? { aircraft: { max: density.aircraft } } : {}
3710
+ }
3711
+ });
3712
+ const network = resolveNetwork(block.network, opts.networks);
3713
+ if (network !== void 0) handle.addDocument(network);
3714
+ if (block.observer !== void 0) handle.setObserver({ entity: block.observer });
3715
+ return { ambient: ambientScriptApi(handle) };
3716
+ };
3717
+ }
3718
+ function resolveNetwork(network, networks) {
3719
+ if (network === void 0) return void 0;
3720
+ const doc = typeof network === "string" ? networks?.[network] : network;
3721
+ if (doc === void 0) throw new Error(`ambient.network "${String(network)}" was not provided: load the document and pass it as networks["${String(network)}"]`);
3722
+ const result = validateByKind("transport-network", doc);
3723
+ if (!result.ok) throw new Error(result.formatted);
3724
+ return result.value;
3725
+ }
3726
+ function cloneMap(map) {
3727
+ return JSON.parse(JSON.stringify(map));
3728
+ }
3729
+ //#endregion
3730
+ //#region src/kernel/graph/export.ts
3731
+ /** Export a built network as a molen/transport-network@1 document (the bake op's output). */
3732
+ const round = (v) => dmath.round(v * 100) / 100;
3733
+ function subclassOf(edge) {
3734
+ if (edge.class === "rail") return edge.kind === "tram" ? "tram" : "rail";
3735
+ if (edge.class === "walk") return edge.kind === "crossing" ? "crossing" : void 0;
3736
+ return edge.kind === "living" ? "living_street" : edge.kind === "street" ? "residential" : edge.kind;
3737
+ }
3738
+ /** Every road, rail and path edge as a way (with surface heights), plus stations and signals. */
3739
+ function networkToDocument(network, meta = {}, options = {}) {
3740
+ const heights = options.heights !== false;
3741
+ const ways = [];
3742
+ const stations = [];
3743
+ const seenStations = /* @__PURE__ */ new Set();
3744
+ for (const edge of network.edgeList()) {
3745
+ if (edge.class === "air") continue;
3746
+ let roadLanes = 0;
3747
+ for (const id of edge.lanes) if (network.lane(id)?.class === "road") roadLanes++;
3748
+ const subclass = subclassOf(edge);
3749
+ ways.push({
3750
+ id: edge.id,
3751
+ class: edge.class === "walk" ? "path" : edge.class,
3752
+ ...subclass !== void 0 ? { subclass } : {},
3753
+ points: edge.path.points.map((p, i) => heights ? [
3754
+ round(p[0]),
3755
+ round(edge.ys[i] ?? 0),
3756
+ round(p[1])
3757
+ ] : [round(p[0]), round(p[1])]),
3758
+ ...edge.class === "road" ? {
3759
+ lanes: roadLanes,
3760
+ oneway: edge.oneway
3761
+ } : {},
3762
+ width: round(edge.width),
3763
+ ...edge.layer !== 0 ? { layer: edge.layer } : {},
3764
+ ...edge.bridge ? { bridge: true } : {},
3765
+ ...edge.tunnel ? { tunnel: true } : {},
3766
+ ...edge.name !== void 0 ? { name: edge.name } : {}
3767
+ });
3768
+ for (const id of edge.lanes) {
3769
+ const lane = network.lane(id);
3770
+ for (const stop of lane?.stops ?? []) {
3771
+ if (stop.kind !== "station" || seenStations.has(stop.id)) continue;
3772
+ seenStations.add(stop.id);
3773
+ const sample = network.sampleLane(id, lane === void 0 ? 0 : stop.d - lane.trimStart);
3774
+ if (sample !== void 0) stations.push({
3775
+ id: stop.id,
3776
+ at: [round(sample.x), round(sample.z)],
3777
+ kind: "rail"
3778
+ });
3779
+ }
3780
+ }
3781
+ }
3782
+ const signals = [];
3783
+ for (const junction of network.junctionList()) if (junction.control === "signal") signals.push({
3784
+ at: [round(junction.x), round(junction.z)],
3785
+ kind: "light"
3786
+ });
3787
+ else for (const arm of junction.arms) if (arm.yields === true) signals.push({
3788
+ at: [round(junction.x + arm.dx * (junction.radius + 4)), round(junction.z + arm.dz * (junction.radius + 4))],
3789
+ kind: "yield"
3790
+ });
3791
+ return {
3792
+ format: TRANSPORT_NETWORK_FORMAT,
3793
+ ...meta,
3794
+ drivingSide: network.traffic,
3795
+ ways,
3796
+ ...stations.length > 0 ? { stations } : {},
3797
+ ...signals.length > 0 ? { signals } : {}
3798
+ };
3799
+ }
3800
+ //#endregion
3801
+ //#region src/kernel.ts
3802
+ registerAmbientSchema();
3803
+ //#endregion
3804
+ export { AMBIENT_AGENT_COMPONENT, AMBIENT_ENTITY, AMBIENT_KINDS, AMBIENT_OBSERVER_COMPONENT, AMBIENT_ROLE_COMPONENT, AMBIENT_STATE_COMPONENT, AmbientAgent, AmbientObserver, AmbientRole, AmbientState, CAR_COLORS, DEFAULT_POLICY, DEFAULT_TEMPLATES, DEFAULT_TYPES, GRID_CELL, KIND_SPEED, LaneGrid, TRANSPORT_NETWORK_EXAMPLE, TRANSPORT_NETWORK_FORMAT, TransportNetwork, agentRotation, agentSample, allRed, ambientCapability, ambientOf, ambientScriptApi, chooseNext, classifyFeature, clipPolyline, edgeHeight, featureDrafts, fmix32, idmAcceleration, installAmbient, laneCoordinate, laneEdgeDistance, laneSample, mergePolicy, networkToDocument, pickWeighted, planarSplit, policyForBudget, pseudoAngle, registerAmbientSchema, sampleConnector, sampleLaneBody, signalColor, signalTiming, stepAgents, stoppingDistance, unit01, walkBack };