@bendyline/molen-ambient 0.0.10 → 0.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/kernel.mjs CHANGED
@@ -1,8 +1,9 @@
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-D4HrizHN.mjs";
1
+ import { _ as KIND_SPEED, a as AmbientRole, b as featureDrafts, c as AMBIENT_OBSERVER_COMPONENT, d as registerAmbientSchema, f as TRANSPORT_NETWORK_EXAMPLE, g as wayDraft, h as documentRunways, i as AmbientObserver, l as AMBIENT_ROLE_COMPONENT, m as documentPois, n as AMBIENT_KINDS, o as AmbientState, p as TRANSPORT_NETWORK_FORMAT, r as AmbientAgent, s as AMBIENT_AGENT_COMPONENT, t as AMBIENT_ENTITY, u as AMBIENT_STATE_COMPONENT, v as classifyFeature, x as tilePois, y as clipPolyline } from "./components-vzvNQczG.mjs";
2
2
  import { createRng, dmath, lookRotation, quatRotateVec3, seedToInt } from "@bendyline/molen-kernel/determinism";
3
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";
4
+ import { deepMergeJson, getSchema, registerSchema, resolvePrefab, validateByKind } from "@bendyline/molen-schema";
5
+ import { z } from "zod";
6
+ import { PATH_SURFACE_LIFT, ROAD_SURFACE_LIFT, bridgeDeckHeightFn, isArterialRoad, lineSegmentIndex, sampleTerrainLine } from "@bendyline/molen-terrain/kernel";
6
7
  //#region src/kernel/agents/idm.ts
7
8
  /** Intelligent Driver Model: acceleration from speed, desired speed and the gap to a leader. */
8
9
  /**
@@ -957,7 +958,7 @@ function stepAircraft(ref, env) {
957
958
  //#endregion
958
959
  //#region src/kernel/graph/junctions.ts
959
960
  /**
960
- * Node groups → junctions and movements. A node group is a node plus the node it is stitched to
961
+ * Node groups → junctions and movements. A node group is a node plus the node it is stitched to
961
962
  * across a tile border. For every lane arriving at the group this computes its outgoing
962
963
  * movements (turn class, target lane, connector curve), trims lanes back from junction cores, and
963
964
  * builds the junction record: arms in angular order, a conflict matrix between arm-pair
@@ -1084,8 +1085,8 @@ var EndCache = class {
1084
1085
  return p;
1085
1086
  }
1086
1087
  };
1087
- function roadWeight(turn, target) {
1088
- 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);
1088
+ function roadWeight(turn, target, drivingSide) {
1089
+ return (turn === "straight" ? 3 : turn === drivingSide ? 2 : turn === "left" || turn === "right" ? 1.5 : turn === "merge" ? 2 : .05) * (target.kind === "service" || target.kind === "living" ? .25 : target.speed >= 15 ? 1.4 : 1);
1089
1090
  }
1090
1091
  const MAX_CONFLICT_ARMS = 8;
1091
1092
  /**
@@ -1141,9 +1142,9 @@ function buildJunction(store, id, group, arms, radius) {
1141
1142
  cx /= group.length;
1142
1143
  cz /= group.length;
1143
1144
  const n = arms.length;
1144
- const side = store.traffic === "right" ? 1 : -1;
1145
1145
  const rim = [];
1146
1146
  arms.forEach((arm, k) => {
1147
+ const side = arm.edge.drivingSide === "right" ? 1 : -1;
1147
1148
  const bx = arm.node.x + arm.dx * radius - cx;
1148
1149
  const bz = arm.node.z + arm.dz * radius - cz;
1149
1150
  const q = arm.edge.width / 4;
@@ -1212,13 +1213,20 @@ function buildJunction(store, id, group, arms, radius) {
1212
1213
  if (best >= 0) junctionArms[best].group = groups;
1213
1214
  groups++;
1214
1215
  }
1215
- 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");
1216
+ const major = arms.filter((a) => isArterialRoad(a.edge.kind, a.edge.width)).length;
1216
1217
  const minor = arms.filter((a) => a.edge.kind === "service" || a.edge.kind === "living" || a.edge.link).length;
1217
1218
  let signed = 0;
1218
- for (const sign of store.giveWayNear(cx, cz, radius + 20)) {
1219
+ for (const sign of store.giveWayNear(cx, cz, radius + 20, group[0]?.layer)) {
1219
1220
  const sx = sign.x - cx;
1220
1221
  const sz = sign.z - cz;
1221
1222
  const length = dmath.hypot(sx, sz);
1223
+ if (sign.allWay && length <= 4) {
1224
+ for (const arm of junctionArms) {
1225
+ if (!arm.yields) signed++;
1226
+ arm.yields = true;
1227
+ }
1228
+ continue;
1229
+ }
1222
1230
  let best;
1223
1231
  let bestDot = Number.NEGATIVE_INFINITY;
1224
1232
  for (const arm of junctionArms) {
@@ -1234,8 +1242,8 @@ function buildJunction(store, id, group, arms, radius) {
1234
1242
  }
1235
1243
  }
1236
1244
  let control = "none";
1237
- if (groups >= 2 && (n >= 4 && major || store.signalNear(cx, cz, radius + 20))) control = "signal";
1238
- else if (minor > 0 && minor < n || signed > 0 && signed < n) control = "yield";
1245
+ if (groups >= 2 && (store.signalNear(cx, cz, radius + 20, group[0]?.layer) || n >= 4 && major >= 4 && signed === 0)) control = "signal";
1246
+ else if (minor > 0 && minor < n || signed > 0) control = "yield";
1239
1247
  return {
1240
1248
  id,
1241
1249
  x: cx,
@@ -1295,8 +1303,8 @@ function movement(cache, from, to, turn, weight, junction, key, crosses) {
1295
1303
  }
1296
1304
  function buildRoadMovements(store, cache, arms, junction) {
1297
1305
  const n = arms.length;
1298
- const left = store.traffic === "left";
1299
1306
  arms.forEach((inArm, i) => {
1307
+ const left = inArm.edge.drivingSide === "left";
1300
1308
  const incoming = lanesAt(store, inArm, "road", true);
1301
1309
  const nIn = incoming.length;
1302
1310
  for (const lane of incoming) {
@@ -1327,11 +1335,11 @@ function buildRoadMovements(store, cache, arms, junction) {
1327
1335
  else if (turn !== nearSide && inner) target = outgoing[0];
1328
1336
  if (target === void 0) return;
1329
1337
  const moveTurn = inArm.edge.link && turn === "straight" ? "merge" : turn;
1330
- const move = movement(cache, lane, target, moveTurn, roadWeight(moveTurn, outArm.edge), n >= 3 ? junction : void 0, i * n + o);
1338
+ const move = movement(cache, lane, target, moveTurn, roadWeight(moveTurn, outArm.edge, inArm.edge.drivingSide), n >= 3 ? junction : void 0, i * n + o);
1331
1339
  if (move !== void 0) moves.push(move);
1332
1340
  });
1333
1341
  if (moves.length === 0) for (const f of fallback) {
1334
- 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);
1342
+ const move = movement(cache, lane, f.lane, f.turn, roadWeight(f.turn, store.edge(f.lane.edge) ?? inArm.edge, inArm.edge.drivingSide), n >= 3 ? junction : void 0, i * n + f.o);
1335
1343
  if (move !== void 0) moves.push(move);
1336
1344
  }
1337
1345
  if (moves.length === 0) {
@@ -1925,17 +1933,17 @@ var TransportNetwork = class {
1925
1933
  deleteJunction(id) {
1926
1934
  this.junctions.delete(id);
1927
1935
  }
1928
- signalNear(x, z, radius) {
1929
- return this.controlsNear(x, z, radius, "traffic_signals").length > 0;
1936
+ signalNear(x, z, radius, layer = 0) {
1937
+ return this.controlsNear(x, z, radius, "traffic_signals", layer).length > 0;
1930
1938
  }
1931
- giveWayNear(x, z, radius) {
1932
- return this.controlsNear(x, z, radius, "give_way");
1939
+ giveWayNear(x, z, radius, layer = 0) {
1940
+ return this.controlsNear(x, z, radius, "give_way", layer);
1933
1941
  }
1934
- controlsNear(x, z, radius, kind) {
1942
+ controlsNear(x, z, radius, kind, layer) {
1935
1943
  const cx = dmath.floor(x / 64);
1936
1944
  const cz = dmath.floor(z / 64);
1937
1945
  const found = [];
1938
- 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);
1946
+ 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 && (poi.layer ?? 0) === layer && dmath.hypot(poi.x - x, poi.z - z) <= radius) found.push(poi);
1939
1947
  return found;
1940
1948
  }
1941
1949
  /** Whether a tile key is registered. */
@@ -1977,6 +1985,7 @@ var TransportNetwork = class {
1977
1985
  registerTile(input) {
1978
1986
  if (this.tiles.has(input.key)) this.unregisterTile(input.key);
1979
1987
  const { drafts, runways } = featureDrafts(input, { tunnels: this.tunnels });
1988
+ for (const draft of drafts) draft.drivingSide = input.drivingSide ?? this.traffic;
1980
1989
  const pois = tilePois(input.pois, input.origin, input.tileSize);
1981
1990
  const rect = [
1982
1991
  input.origin[0],
@@ -2030,7 +2039,10 @@ var TransportNetwork = class {
2030
2039
  /** Add a transport-network document's ways, stations, signals and aerodromes. */
2031
2040
  addDocument(doc) {
2032
2041
  for (const way of doc.ways) {
2033
- const draft = wayDraft(way);
2042
+ const draft = wayDraft({
2043
+ ...way,
2044
+ drivingSide: way.drivingSide ?? doc.drivingSide ?? this.traffic
2045
+ });
2034
2046
  if (draft !== void 0) this.docDrafts.push(draft);
2035
2047
  }
2036
2048
  this.docPois.push(...documentPois(doc));
@@ -2157,6 +2169,7 @@ var TransportNetwork = class {
2157
2169
  tunnel: draft.tunnel,
2158
2170
  link: draft.link,
2159
2171
  oneway: draft.oneway,
2172
+ drivingSide: draft.drivingSide ?? this.traffic,
2160
2173
  lanes: [],
2161
2174
  ...draft.name !== void 0 ? { name: draft.name } : {}
2162
2175
  };
@@ -2193,7 +2206,7 @@ var TransportNetwork = class {
2193
2206
  this.version++;
2194
2207
  }
2195
2208
  createLanes(edge, draft, sidewalks) {
2196
- const side = this.traffic === "right" ? 1 : -1;
2209
+ const side = edge.drivingSide === "right" ? 1 : -1;
2197
2210
  const make = (code, cls, dir, index, offset, lift = 0) => {
2198
2211
  const id = `${edge.id}>${code}`;
2199
2212
  const lane = {
@@ -3271,16 +3284,16 @@ function spawnOne(ctx, kind) {
3271
3284
  if (lane === void 0) continue;
3272
3285
  const seq = ctx.state.nextSeq;
3273
3286
  const seed = fmix32(seq ^ env.seed);
3274
- const available = kind === "boat" ? types.filter((t) => (t.waterway ?? "channel") === edge.kind && t.width <= edge.width / (edge.oneway ? 1 : 2) && t.length + 2 < lane.length) : types;
3275
- if (kind === "boat" && available.length === 0) continue;
3287
+ const s = laneCoordinate(lane, edge, span.d0 + rng.next() * (span.d1 - span.d0));
3288
+ const sample = sampleLaneBody(lane, edge, s, laneSample());
3289
+ const available = kind === "car" && env.carsAt ? env.carsAt(sample.x, sample.z) : kind === "boat" ? types.filter((t) => (t.waterway ?? "channel") === edge.kind && t.width <= edge.width / (edge.oneway ? 1 : 2) && t.length + 2 < lane.length) : types;
3290
+ if ((kind === "boat" || kind === "car") && available.length === 0) continue;
3276
3291
  const vehicle = kind === "pedestrian" ? void 0 : pickWeighted(available, unit01(seed, 10));
3277
3292
  const length = kind === "pedestrian" ? .5 : vehicle?.length ?? 4.5;
3278
3293
  const width = kind === "pedestrian" ? .5 : vehicle?.width ?? 1.8;
3279
3294
  const cars = kind === "train" ? dmath.max(1, vehicle?.cars ?? 2) : 1;
3280
3295
  const behind = kind === "train" ? (cars - 1) * (length + 1) : 0;
3281
- const s = laneCoordinate(lane, edge, span.d0 + rng.next() * (span.d1 - span.d0));
3282
3296
  if (s < behind + length / 2 + 1 || s > lane.length - length / 2 - 1) continue;
3283
- const sample = sampleLaneBody(lane, edge, s, laneSample());
3284
3297
  const dx = sample.x - observer.x;
3285
3298
  const dz = sample.z - observer.z;
3286
3299
  const distance = dmath.hypot(dx, dz);
@@ -3609,7 +3622,8 @@ function installAmbient(world, options = {}) {
3609
3622
  types,
3610
3623
  templates,
3611
3624
  seed,
3612
- ground
3625
+ ground,
3626
+ ...options.carsAt ? { carsAt: options.carsAt } : {}
3613
3627
  };
3614
3628
  const removed = despawnAgents(w, env, observer);
3615
3629
  const counters = {
@@ -3898,6 +3912,127 @@ function cloneMap(map) {
3898
3912
  return JSON.parse(JSON.stringify(map));
3899
3913
  }
3900
3914
  //#endregion
3915
+ //#region src/kernel/fleet.ts
3916
+ /** Small, geometry-free market profiles. Weights are visual priors, not sales statistics. */
3917
+ const weights = z.record(z.string().min(1), z.number().finite().nonnegative());
3918
+ const fleetCatalogSchema = z.strictObject({
3919
+ format: z.literal("molen/fleet-catalog@1"),
3920
+ id: z.string().min(1),
3921
+ version: z.number().int().positive(),
3922
+ description: z.string(),
3923
+ fallback: z.string().min(1),
3924
+ regions: z.record(z.string(), z.string().min(1)),
3925
+ profiles: z.array(z.strictObject({
3926
+ id: z.string().min(1),
3927
+ title: z.string().min(1),
3928
+ extends: z.string().optional(),
3929
+ weights
3930
+ })).min(1)
3931
+ });
3932
+ function seedOf(value) {
3933
+ let seed = 2166136261;
3934
+ for (let i = 0; i < value.length; i++) seed = Math.imul(seed ^ value.charCodeAt(i), 16777619);
3935
+ return fmix32(seed);
3936
+ }
3937
+ function createFleetLibrary(documents, available, maxModels = 16) {
3938
+ if (!Number.isInteger(maxModels) || maxModels < 1 || maxModels > 128) throw new Error("Fleet maxModels must be an integer from 1 to 128");
3939
+ const profiles = /* @__PURE__ */ new Map();
3940
+ const regions = /* @__PURE__ */ new Map();
3941
+ let fallback;
3942
+ for (const raw of documents) {
3943
+ const doc = fleetCatalogSchema.parse(raw);
3944
+ fallback ??= doc.fallback;
3945
+ for (const profile of doc.profiles) {
3946
+ if (profiles.has(profile.id)) throw new Error(`Duplicate fleet profile: ${profile.id}`);
3947
+ profiles.set(profile.id, profile);
3948
+ }
3949
+ for (const [region, profile] of Object.entries(doc.regions)) {
3950
+ if (regions.has(region)) throw new Error(`Duplicate fleet region: ${region}`);
3951
+ regions.set(region, profile);
3952
+ }
3953
+ }
3954
+ const resolved = /* @__PURE__ */ new Map();
3955
+ const resolve = (id, visiting = /* @__PURE__ */ new Set()) => {
3956
+ const cached = resolved.get(id);
3957
+ if (cached) return cached;
3958
+ const profile = profiles.get(id);
3959
+ if (!profile) throw new Error(`Unknown fleet profile: ${id}`);
3960
+ if (visiting.has(id)) throw new Error(`Cyclic fleet inheritance: ${id}`);
3961
+ visiting.add(id);
3962
+ const result = {
3963
+ ...profile.extends ? resolve(profile.extends, visiting) : {},
3964
+ ...profile.weights
3965
+ };
3966
+ visiting.delete(id);
3967
+ resolved.set(id, result);
3968
+ return result;
3969
+ };
3970
+ for (const id of profiles.keys()) resolve(id);
3971
+ for (const id of regions.values()) resolve(id);
3972
+ if (!fallback) throw new Error("A fleet catalog needs a fallback");
3973
+ resolve(fallback);
3974
+ const mixes = /* @__PURE__ */ new Map();
3975
+ const select = (region) => {
3976
+ const profile = region && regions.get(region) || fallback;
3977
+ const cached = mixes.get(profile);
3978
+ if (cached) return cached;
3979
+ const pool = Object.entries(resolve(profile)).filter(([id, weight]) => weight > 0 && available.has(id)).sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1));
3980
+ const chosen = pool.splice(0, Math.min(4, maxModels));
3981
+ const seed = seedOf(profile);
3982
+ while (pool.length && chosen.length < maxModels) {
3983
+ let draw = unit01(seed, chosen.length) * pool.reduce((sum, [, weight]) => sum + weight, 0);
3984
+ let at = 0;
3985
+ while (at < pool.length - 1 && draw >= (pool[at]?.[1] ?? 0)) draw -= pool[at++]?.[1] ?? 0;
3986
+ chosen.push(...pool.splice(at, 1));
3987
+ }
3988
+ const mix = {
3989
+ profile,
3990
+ weights: new Map(chosen)
3991
+ };
3992
+ mixes.set(profile, mix);
3993
+ return mix;
3994
+ };
3995
+ return {
3996
+ regions,
3997
+ select
3998
+ };
3999
+ }
4000
+ function registerFleetSchema() {
4001
+ if (getSchema("fleet-catalog")) return;
4002
+ registerSchema("fleet-catalog", fleetCatalogSchema, {
4003
+ id: "molen/fleet-catalog@1",
4004
+ title: "Regional vehicle fleet",
4005
+ description: "Shared vehicle IDs with inherited regional spawn weights and a global fallback.",
4006
+ docsRef: "guide/regional-fleets.md",
4007
+ examples: [{
4008
+ format: "molen/fleet-catalog@1",
4009
+ id: "example.fleet",
4010
+ version: 1,
4011
+ description: "Illustrative visual mixture",
4012
+ fallback: "global",
4013
+ regions: {},
4014
+ profiles: [{
4015
+ id: "global",
4016
+ title: "Global",
4017
+ weights: { "example.car": 1 }
4018
+ }]
4019
+ }],
4020
+ validate(data) {
4021
+ try {
4022
+ createFleetLibrary([data], /* @__PURE__ */ new Set());
4023
+ return [];
4024
+ } catch (error) {
4025
+ return [{
4026
+ path: "",
4027
+ code: "invalid_fleet",
4028
+ message: error.message
4029
+ }];
4030
+ }
4031
+ }
4032
+ });
4033
+ }
4034
+ registerFleetSchema();
4035
+ //#endregion
3901
4036
  //#region src/kernel/graph/export.ts
3902
4037
  /** Export a built network as a molen/transport-network@1 document (the bake op's output). */
3903
4038
  const round = (v) => dmath.round(v * 100) / 100;
@@ -3930,6 +4065,7 @@ function networkToDocument(network, meta = {}, options = {}) {
3930
4065
  lanes: roadLanes,
3931
4066
  oneway: edge.oneway
3932
4067
  } : {},
4068
+ ...(edge.class === "road" || edge.class === "walk") && edge.drivingSide !== network.traffic ? { drivingSide: edge.drivingSide } : {},
3933
4069
  ...edge.class === "water" ? {
3934
4070
  oneway: edge.oneway,
3935
4071
  speed: edge.speed
@@ -3974,7 +4110,186 @@ function networkToDocument(network, meta = {}, options = {}) {
3974
4110
  };
3975
4111
  }
3976
4112
  //#endregion
4113
+ //#region src/kernel/wildlife.ts
4114
+ /** Bounded, fixed-step ambient wildlife. No global randomness, timers, geography or renderer. */
4115
+ const WILDLIFE_TICK_RATE = 20;
4116
+ const WILDLIFE_CELL_METERS = 96;
4117
+ function suitable(species, habitat) {
4118
+ return habitat?.safe === true && Number.isFinite(habitat.height) && (species.motion === "fly" || (species.motion === "swim" ? habitat.water : !habitat.water));
4119
+ }
4120
+ function heightFor(species, habitat) {
4121
+ return habitat.height + (species.motion === "fly" ? species.clearance : species.motion === "swim" ? -species.clearance : 0);
4122
+ }
4123
+ /** Stable world-grid candidates. Adding an unrelated species does not reroll an existing one. */
4124
+ function wildlifeCandidates(world, observer, budget, tick = 0) {
4125
+ const radius = Math.max(0, Math.min(2e3, budget.radius));
4126
+ const density = dmath.clamp(budget.density, 0, 1);
4127
+ const limit = Math.max(0, Math.min(256, Math.floor(budget.animals)));
4128
+ if (limit === 0 || density === 0 || !observer.every(Number.isFinite)) return [];
4129
+ const size = 96;
4130
+ const found = [];
4131
+ for (let row = Math.floor((observer[2] - radius) / size); row <= Math.floor((observer[2] + radius) / size); row++) for (let column = Math.floor((observer[0] - radius) / size); column <= Math.floor((observer[0] + radius) / size); column++) {
4132
+ const choices = world.choices((column + .5) * size, (row + .5) * size);
4133
+ for (const choice of choices) {
4134
+ const species = choice.species;
4135
+ const id = `${species.id}@${species.version}/${column}/${row}`;
4136
+ const seed = fnv1a(id);
4137
+ if (unit01(seed, 0) >= Math.min(1, choice.density * size * size / 1e6) * density) continue;
4138
+ const x = q4((column + .15 + unit01(seed, 1) * .7) * size);
4139
+ const z = q4((row + .15 + unit01(seed, 2) * .7) * size);
4140
+ const distance = (x - observer[0]) ** 2 + (z - observer[2]) ** 2;
4141
+ if (distance > radius * radius) continue;
4142
+ const actual = world.choices(x, z).find((entry) => entry.species.id === species.id);
4143
+ if (actual === void 0 || unit01(seed, 0) >= Math.min(1, actual.density * size * size / 1e6) * density) continue;
4144
+ const habitat = world.habitat(x, z, species.margin);
4145
+ if (!suitable(species, habitat) || !actual.habitats.includes(habitat.kind)) continue;
4146
+ const y = heightFor(species, habitat);
4147
+ if ((y - observer[1]) ** 2 + distance > radius * radius) continue;
4148
+ found.push({
4149
+ distance,
4150
+ agent: {
4151
+ id,
4152
+ species: species.id,
4153
+ seed,
4154
+ anchor: [x, z],
4155
+ position: [
4156
+ x,
4157
+ q4(y),
4158
+ z
4159
+ ],
4160
+ target: [x, z],
4161
+ heading: unit01(seed, 3) * dmath.PI * 2,
4162
+ speed: 0,
4163
+ since: tick,
4164
+ nextDecision: tick,
4165
+ decisions: 0,
4166
+ phase: unit01(seed, 4)
4167
+ }
4168
+ });
4169
+ }
4170
+ }
4171
+ return found.sort((a, b) => a.distance - b.distance || (a.agent.id < b.agent.id ? -1 : 1)).slice(0, limit).map(({ agent }) => agent);
4172
+ }
4173
+ /** Advance one 1/20-second step. A host can snapshot these plain records without hidden state. */
4174
+ function stepWildlife(agents, speciesById, world, tick) {
4175
+ const next = [];
4176
+ for (const previous of agents) {
4177
+ const species = speciesById.get(previous.species);
4178
+ if (species === void 0) continue;
4179
+ const start = world.habitat(previous.position[0], previous.position[2], species.margin);
4180
+ const currentChoice = world.choices(previous.position[0], previous.position[2]).find((choice) => choice.species.id === species.id);
4181
+ if (!suitable(species, start) || currentChoice === void 0 || !currentChoice.habitats.includes(start.kind)) continue;
4182
+ const agent = {
4183
+ ...previous,
4184
+ position: [...previous.position],
4185
+ target: [...previous.target]
4186
+ };
4187
+ if (tick >= agent.nextDecision) {
4188
+ const stream = 10 + agent.decisions++ * 4;
4189
+ const angle = unit01(agent.seed, stream) * dmath.PI * 2;
4190
+ const radius = species.roam * dmath.sqrt(unit01(agent.seed, stream + 1));
4191
+ agent.target = species.motion !== "fly" && species.motion !== "swim" && unit01(agent.seed, stream + 2) < species.rest ? [agent.position[0], agent.position[2]] : [q4(agent.anchor[0] + dmath.cos(angle) * radius), q4(agent.anchor[1] + dmath.sin(angle) * radius)];
4192
+ agent.nextDecision = tick + Math.floor((4 + unit01(agent.seed, stream + 3) * 8) * 20);
4193
+ agent.since = tick;
4194
+ }
4195
+ const dx = agent.target[0] - agent.position[0];
4196
+ const dz = agent.target[1] - agent.position[2];
4197
+ const distance = dmath.sqrt(dx * dx + dz * dz);
4198
+ const travel = Math.min(distance, species.speed / 20);
4199
+ agent.speed = 0;
4200
+ if (distance > .01) {
4201
+ const x = q4(agent.position[0] + dx / distance * travel);
4202
+ const z = q4(agent.position[2] + dz / distance * travel);
4203
+ const steps = Math.max(1, Math.ceil(travel / Math.max(.1, species.margin)));
4204
+ let destination;
4205
+ for (let i = 1; i <= steps; i++) {
4206
+ const sx = agent.position[0] + (x - agent.position[0]) * i / steps;
4207
+ const sz = agent.position[2] + (z - agent.position[2]) * i / steps;
4208
+ const habitat = world.habitat(sx, sz, species.margin);
4209
+ const choice = world.choices(sx, sz).find((entry) => entry.species.id === species.id);
4210
+ if (!suitable(species, habitat) || choice === void 0 || !choice.habitats.includes(habitat.kind)) {
4211
+ destination = void 0;
4212
+ break;
4213
+ }
4214
+ destination = habitat;
4215
+ }
4216
+ if (destination !== void 0) {
4217
+ agent.position = [
4218
+ x,
4219
+ q4(heightFor(species, destination)),
4220
+ z
4221
+ ];
4222
+ agent.heading = dmath.atan2(dx, dz);
4223
+ agent.speed = q4(travel * 20);
4224
+ agent.phase = q4((agent.phase + travel / Math.max(.1, species.body.length)) % 1);
4225
+ } else agent.nextDecision = tick + 1;
4226
+ } else if (species.motion === "fly" || species.motion === "swim") agent.nextDecision = tick + 1;
4227
+ next.push(agent);
4228
+ }
4229
+ return next;
4230
+ }
4231
+ //#endregion
4232
+ //#region src/kernel/wildlife-types.ts
4233
+ /** Data-only animal silhouettes and habitat populations. Content owns species and range facts. */
4234
+ const WILDLIFE_FAMILIES = [
4235
+ "ungulate",
4236
+ "canid",
4237
+ "feline",
4238
+ "rodent",
4239
+ "lagomorph",
4240
+ "hopper",
4241
+ "elephant",
4242
+ "bird",
4243
+ "reptile",
4244
+ "fish",
4245
+ "insect"
4246
+ ];
4247
+ const id = z.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$/);
4248
+ const color = z.string().regex(/^#[0-9a-fA-F]{6}$/);
4249
+ const wildlifeSpeciesSchema = z.strictObject({
4250
+ id,
4251
+ version: z.int().positive(),
4252
+ title: z.string().min(1),
4253
+ taxon: z.string().min(1).optional(),
4254
+ range: z.string().min(1).optional(),
4255
+ winterColor: color.optional(),
4256
+ inactiveInWinter: z.boolean().optional(),
4257
+ body: z.strictObject({
4258
+ family: z.enum(WILDLIFE_FAMILIES),
4259
+ height: z.number().min(.01).max(7),
4260
+ length: z.number().min(.01).max(12),
4261
+ width: z.number().min(.005).max(5),
4262
+ color,
4263
+ accent: color,
4264
+ details: z.array(z.enum([
4265
+ "antlers",
4266
+ "horns",
4267
+ "long-neck",
4268
+ "bushy-tail",
4269
+ "stripes",
4270
+ "spots",
4271
+ "wader",
4272
+ "waterfowl",
4273
+ "raptor",
4274
+ "parrot",
4275
+ "long-tail"
4276
+ ]))
4277
+ }),
4278
+ motion: z.enum([
4279
+ "walk",
4280
+ "hop",
4281
+ "fly",
4282
+ "swim",
4283
+ "crawl"
4284
+ ]),
4285
+ speed: z.number().min(.01).max(30),
4286
+ roam: z.number().min(1).max(200),
4287
+ clearance: z.number().min(0).max(80),
4288
+ rest: z.number().min(0).max(1),
4289
+ margin: z.number().min(.02).max(8)
4290
+ }).refine((species) => species.taxon === void 0 === (species.range === void 0), { message: "Named wildlife taxa require an attributed range; unnamed functional groups omit both." });
4291
+ //#endregion
3977
4292
  //#region src/kernel.ts
3978
4293
  registerAmbientSchema();
3979
4294
  //#endregion
3980
- 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 };
4295
+ 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, WILDLIFE_CELL_METERS, WILDLIFE_FAMILIES, WILDLIFE_TICK_RATE, agentRotation, agentSample, allRed, ambientCapability, ambientOf, ambientScriptApi, chooseNext, classifyFeature, clipPolyline, createFleetLibrary, edgeHeight, featureDrafts, fleetCatalogSchema, fmix32, idmAcceleration, installAmbient, laneCoordinate, laneEdgeDistance, laneSample, mergePolicy, networkToDocument, pickWeighted, planarSplit, policyForBudget, pseudoAngle, registerAmbientSchema, registerFleetSchema, sampleConnector, sampleLaneBody, signalColor, signalTiming, stepAgents, stepWildlife, stoppingDistance, unit01, walkBack, wildlifeCandidates, wildlifeSpeciesSchema };
@@ -0,0 +1,87 @@
1
+ import { z } from "zod";
2
+
3
+ //#region src/kernel/wildlife-types.d.ts
4
+ declare const WILDLIFE_FAMILIES: readonly ["ungulate", "canid", "feline", "rodent", "lagomorph", "hopper", "elephant", "bird", "reptile", "fish", "insect"];
5
+ type WildlifeFamily = (typeof WILDLIFE_FAMILIES)[number];
6
+ type WildlifeMotion = "walk" | "hop" | "fly" | "swim" | "crawl";
7
+ interface WildlifeSpecies {
8
+ id: string;
9
+ version: number;
10
+ title: string;
11
+ /** Omitted for functional habitat groups that make no precise species claim. */
12
+ taxon?: string;
13
+ /** Identifier in an attributed range document. Named taxa require a range at the Earth binding. */
14
+ range?: string;
15
+ /** Coarse seasonal appearance/activity; not a weather or migration model. */
16
+ winterColor?: string;
17
+ inactiveInWinter?: boolean;
18
+ body: {
19
+ family: WildlifeFamily; /** Meters: standing height, nose-to-rump length, torso width. Wings and tails may extend them. */
20
+ height: number;
21
+ length: number;
22
+ width: number;
23
+ color: string;
24
+ accent: string;
25
+ details: Array<"antlers" | "horns" | "long-neck" | "bushy-tail" | "stripes" | "spots" | "wader" | "waterfowl" | "raptor" | "parrot" | "long-tail">;
26
+ };
27
+ motion: WildlifeMotion;
28
+ /** Meters per second. This is ambient travel, not maximum running speed. */
29
+ speed: number;
30
+ /** Maximum travel from the stable spawn anchor in meters. */
31
+ roam: number;
32
+ /** Height above ground/water for flight; depth below the surface for swimming. */
33
+ clearance: number;
34
+ /** Probability of resting at a target. Flying/swimming animals keep moving. */
35
+ rest: number;
36
+ /** Body-size clearance from obstacles, meters. */
37
+ margin: number;
38
+ }
39
+ /** Already selected by the host's regional/range resolver. Density is a visual population prior. */
40
+ interface WildlifeChoice {
41
+ species: WildlifeSpecies;
42
+ density: number;
43
+ habitats: readonly string[];
44
+ }
45
+ interface WildlifeHabitat {
46
+ /** Actual mapped surface, not potential vegetation from a biome map. */
47
+ kind: string;
48
+ height: number;
49
+ water: boolean;
50
+ /** False on roads, buildings, steep terrain, or insufficiently known terrain. */
51
+ safe: boolean;
52
+ }
53
+ declare const wildlifeSpeciesSchema: z.ZodType<WildlifeSpecies>;
54
+ //#endregion
55
+ //#region src/kernel/wildlife.d.ts
56
+ declare const WILDLIFE_TICK_RATE = 20;
57
+ declare const WILDLIFE_CELL_METERS = 96;
58
+ interface WildlifeAgent {
59
+ id: string;
60
+ species: string;
61
+ seed: number;
62
+ anchor: [number, number];
63
+ position: [number, number, number];
64
+ target: [number, number];
65
+ heading: number;
66
+ speed: number;
67
+ since: number;
68
+ nextDecision: number;
69
+ decisions: number;
70
+ phase: number;
71
+ }
72
+ interface WildlifeWorld {
73
+ choices(x: number, z: number): readonly WildlifeChoice[];
74
+ habitat(x: number, z: number, margin: number): WildlifeHabitat | undefined;
75
+ }
76
+ interface WildlifeBudget {
77
+ animals: number;
78
+ radius: number;
79
+ /** 0..1 stable thinning. Changing quality keeps existing candidate identities. */
80
+ density: number;
81
+ }
82
+ /** Stable world-grid candidates. Adding an unrelated species does not reroll an existing one. */
83
+ declare function wildlifeCandidates(world: WildlifeWorld, observer: readonly [number, number, number], budget: WildlifeBudget, tick?: number): WildlifeAgent[];
84
+ /** Advance one 1/20-second step. A host can snapshot these plain records without hidden state. */
85
+ declare function stepWildlife(agents: readonly WildlifeAgent[], speciesById: ReadonlyMap<string, WildlifeSpecies>, world: WildlifeWorld, tick: number): WildlifeAgent[];
86
+ //#endregion
87
+ export { WildlifeWorld as a, WILDLIFE_FAMILIES as c, WildlifeHabitat as d, WildlifeMotion as f, WildlifeBudget as i, WildlifeChoice as l, wildlifeSpeciesSchema as m, WILDLIFE_TICK_RATE as n, stepWildlife as o, WildlifeSpecies as p, WildlifeAgent as r, wildlifeCandidates as s, WILDLIFE_CELL_METERS as t, WildlifeFamily as u };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bendyline/molen-ambient",
3
- "version": "0.0.10",
3
+ "version": "0.0.12",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -41,15 +41,15 @@
41
41
  "dist"
42
42
  ],
43
43
  "dependencies": {
44
- "zod": "^4.6.5",
45
- "@bendyline/molen-figures": "0.0.9",
46
- "@bendyline/molen-schema": "0.0.7",
47
- "@bendyline/molen-kernel": "0.0.7",
48
- "@bendyline/molen-terrain": "0.0.10"
44
+ "@bendyline/molen-figures": "0.0.10",
45
+ "@bendyline/molen-kernel": "0.0.8",
46
+ "@bendyline/molen-schema": "0.0.8",
47
+ "@bendyline/molen-terrain": "0.0.12",
48
+ "zod": "^4.6.5"
49
49
  },
50
50
  "peerDependencies": {
51
- "three": ">=0.184.0 <0.187.0",
52
- "@bendyline/molen-client": "0.0.9"
51
+ "@bendyline/molen-client": "0.0.10",
52
+ "three": ">=0.184.0 <0.187.0"
53
53
  },
54
54
  "peerDependenciesMeta": {
55
55
  "@bendyline/molen-client": {
@@ -60,14 +60,14 @@
60
60
  }
61
61
  },
62
62
  "devDependencies": {
63
+ "@bendyline/molen-client": "0.0.10",
63
64
  "@biomejs/biome": "^2.5.0",
64
65
  "@types/three": "0.184.0",
65
66
  "fast-check": "^3.23.2",
66
67
  "three": "0.184.0",
67
68
  "tsdown": "^0.22.2",
68
69
  "typescript": "^6.0.3",
69
- "vitest": "^5.0.1",
70
- "@bendyline/molen-client": "0.0.9"
70
+ "vitest": "^5.0.1"
71
71
  },
72
72
  "scripts": {
73
73
  "build": "tsdown",