roamwright 0.61.11 → 0.61.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.
@@ -8,6 +8,7 @@ import { longFlierArrays } from 'roamwright/geometry/flier-long-body.js';
8
8
  import { drawPerchedCorvid } from 'roamwright/geometry/flier-corvid-wings.js';
9
9
  import { soaringBirdGeometry } from 'roamwright/geometry/flier-soaring-bird.js';
10
10
  import { corvidPose } from 'roamwright/motion/flier-corvid-pose.js';
11
+ import { createLampSwarmFlight } from 'roamwright/motion/flier-lamp-swarm.js';
11
12
  import { BIRD_LOOKS } from 'roamwright/rendering/flier-bird-looks.js';
12
13
  import { createCorvidFigure } from 'roamwright/rendering/flier-corvid-figure.js';
13
14
  import { createLongFlierCompany } from 'roamwright/rendering/flier-long-body-company.js';
@@ -128,8 +129,19 @@ const PALE_MOTH = {
128
129
  hind: [0.92, 0.9, 0.84],
129
130
  };
130
131
  const shapeOf = createFlierShapes({ build: kind => flierArrays(kind === 'pale' ? mothShape(PALE_MOTH) : mothShape()) });
132
+ const lampAnchors = new Float32Array(3);
133
+ const lampMoths = createSwarm({ shape: shapeOf('moth'), time, count: 48, manner: 'hover', anchors: lampAnchors, random });
134
+ const updateLampMoths = createLampSwarmFlight({
135
+ swarm: lampMoths,
136
+ anchors: lampAnchors,
137
+ points: [{ x: lampPos.x, y: lampTopY + 0.12, z: lampPos.z }],
138
+ count: 1,
139
+ reach: 120,
140
+ dark: 0.2,
141
+ glow: 1.0,
142
+ tint: [0.95, 0.72, 0.38],
143
+ });
131
144
  const swarms = [
132
- createSwarm({ shape: shapeOf('moth'), time, count: 48, manner: 'hover', anchors: [lampPos.x, lampTopY, lampPos.z], random }),
133
145
  createSwarm({
134
146
  shape: shapeOf('pale'),
135
147
  wings: { beat: 6, swing: 0.8, cup: 0.15 },
@@ -151,8 +163,8 @@ const swarms = [
151
163
  bow: [1, 0],
152
164
  }),
153
165
  ];
166
+ worldGroup.add(lampMoths.mesh);
154
167
  for (const swarm of swarms) worldGroup.add(swarm.mesh);
155
- swarms[0].glow.setRGB(0.75, 0.56, 0.3);
156
168
 
157
169
  // Foreground animated corvid on a low stone, plus three perched corvids on the crag ledges.
158
170
  const figureMaterial = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.52 });
@@ -260,6 +272,7 @@ const rig = createOrbitCamera({
260
272
  const clock = new THREE.Timer();
261
273
  function stepFliers(dt, t) {
262
274
  time.value = t;
275
+ updateLampMoths(camera.position.x, camera.position.y, camera.position.z, t, 0.8);
263
276
  for (const swarm of swarms) swarm.update(t);
264
277
  for (const [flock, [x, y, z], radius, height] of flocks) flock.update(x, y, z, radius, height, t, 8);
265
278
  actor.pose = t % 24 > 19 ? 'fly' : 'stand';
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Road-over-river bridge crossing planner: finds where road polylines cross an outflow or named stream, computes each bridge's
3
+ * centre, elevation, orientation, and span frame, and emits walkable deck records so roads can ride cleanly over the decks.
4
+ * Worker-safe arithmetic only (no Three.js dependency).
5
+ * @module
6
+ */
7
+
8
+ function nearestDistance(point, polyline) {
9
+ let bestSq = 1e9;
10
+ for (let i = 0; i < polyline.length; i++) {
11
+ const q = polyline[i],
12
+ dSq = (q[0] - point[0]) ** 2 + (q[1] - point[1]) ** 2;
13
+ if (dSq < bestSq) bestSq = dSq;
14
+ }
15
+ return Math.sqrt(bestSq);
16
+ }
17
+
18
+ /**
19
+ * Computes a bridge frame at `road[index]`, oriented along the local road tangent and lifted above the higher bank, and
20
+ * optionally appends a walkable deck record to `decks`.
21
+ *
22
+ * @param {Array<[number, number]>} road Sampled road polyline `[x, z]` in metres.
23
+ * @param {number} index Crossing vertex index along `road`.
24
+ * @param {number} len Bridge span length along the road in metres.
25
+ * @param {number} halfWidth Walkable deck half-width across the road in metres.
26
+ * @param {(x: number, z: number) => number} ground Terrain elevation sampler in metres.
27
+ * @param {object} [options]
28
+ * @param {number} [options.tangentSpan=10] Vertex offset each side of `index` used to measure road tangent.
29
+ * @param {number} [options.lift=0.12] Deck clearance above the higher abutment ground height in metres.
30
+ * @param {Array<object> | null} [options.decks=null] Optional deck list to append `{ x, z, hx, hz, c, s, y }` into.
31
+ * @returns {{ x: number, z: number, y: number, len: number, rot: number, dx: number, dz: number, px: number, pz: number }}
32
+ */
33
+ export function planBridgeFrame(road, index, len, halfWidth, ground, { tangentSpan = 10, lift = 0.12, decks = null } = {}) {
34
+ const p = road[index],
35
+ a = road[Math.max(0, index - tangentSpan)],
36
+ b = road[Math.min(road.length - 1, index + tangentSpan)];
37
+ let dx = b[0] - a[0],
38
+ dz = b[1] - a[1];
39
+ const l = Math.hypot(dx, dz);
40
+ dx /= l;
41
+ dz /= l;
42
+ const y = Math.max(ground(p[0] - (dx * len) / 2, p[1] - (dz * len) / 2), ground(p[0] + (dx * len) / 2, p[1] + (dz * len) / 2)) + lift,
43
+ rot = Math.atan2(-dz, dx);
44
+ if (decks) decks.push({ x: p[0], z: p[1], hx: len / 2, hz: halfWidth, c: Math.cos(rot), s: Math.sin(rot), y });
45
+ return { x: p[0], z: p[1], y, len, rot, dx, dz, px: -dz, pz: dx };
46
+ }
47
+
48
+ /**
49
+ * Plans the main outflow bridge (where the primary road crosses the outflow channel) and smaller bridges wherever any road
50
+ * crosses a named stream within `streamThreshold` metres.
51
+ *
52
+ * @param {object} options
53
+ * @param {Array<{ fine: Array<[number, number]>, w: number }>} options.roads Sampled road networks.
54
+ * @param {Array<{ kind: string, name?: string, fine: Array<[number, number]>, w: number }>} options.rivers Sampled rivers and streams.
55
+ * @param {(x: number, z: number) => number} options.ground Terrain elevation sampler in metres.
56
+ * @param {Array<object> | null} [options.decks=null] Optional walkable deck array populated in crossing order.
57
+ * @param {number} [options.primaryRoad=0] Road index carrying the main outflow bridge.
58
+ * @param {number} [options.outflowLength=46] Span length of the main outflow bridge in metres.
59
+ * @param {number} [options.outflowHalfWidth=3.3] Deck half-width of the main outflow bridge in metres.
60
+ * @param {number} [options.streamThreshold=2] Maximum crossing distance in metres for a stream bridge.
61
+ * @param {number} [options.streamSpanMargin=10] Extra span beyond stream width in metres.
62
+ * @param {number} [options.streamDeckMargin=0.6] Extra walkable deck half-width beyond road half-width in metres.
63
+ * @param {number} [options.streamWidthMargin=0.4] Extra masonry half-width beyond road half-width in metres.
64
+ * @param {number} [options.tangentSpan=10] Vertex step for local tangent estimation.
65
+ * @param {number} [options.lift=0.12] Deck lift above the higher bank in metres.
66
+ * @returns {{ bridge: object | null, bridges: Array<object> }}
67
+ */
68
+ export function planRoadBridges({
69
+ roads,
70
+ rivers,
71
+ ground,
72
+ decks = null,
73
+ primaryRoad = 0,
74
+ outflowLength = 46,
75
+ outflowHalfWidth = 3.3,
76
+ streamThreshold = 2,
77
+ streamSpanMargin = 10,
78
+ streamDeckMargin = 0.6,
79
+ streamWidthMargin = 0.4,
80
+ tangentSpan = 10,
81
+ lift = 0.12,
82
+ }) {
83
+ const frameOpts = { tangentSpan, lift, decks },
84
+ outflow = rivers.find(r => r.kind === 'outflow')?.fine;
85
+ let bridge = null;
86
+ if (outflow && roads[primaryRoad]?.fine?.length) {
87
+ const road = roads[primaryRoad].fine;
88
+ let bi = 0,
89
+ bd = 1e9;
90
+ for (let i = 0; i < road.length; i++) {
91
+ const d = nearestDistance(road[i], outflow);
92
+ if (d < bd) {
93
+ bd = d;
94
+ bi = i;
95
+ }
96
+ }
97
+ bridge = planBridgeFrame(road, bi, outflowLength, outflowHalfWidth, ground, frameOpts);
98
+ }
99
+
100
+ const bridges = [];
101
+ for (let ri = 0; ri < rivers.length; ri++) {
102
+ const river = rivers[ri];
103
+ if (river.kind !== 'stream' || !river.name) continue;
104
+ for (let k = 0; k < roads.length; k++) {
105
+ const r = roads[k],
106
+ road = r.fine;
107
+ let bi = -1,
108
+ bd = streamThreshold;
109
+ for (let i = 0; i < road.length; i++) {
110
+ const d = nearestDistance(road[i], river.fine);
111
+ if (d < bd) {
112
+ bd = d;
113
+ bi = i;
114
+ }
115
+ }
116
+ if (bi >= 0) {
117
+ bridges.push({
118
+ ...planBridgeFrame(road, bi, river.w + streamSpanMargin, r.w / 2 + streamDeckMargin, ground, frameOpts),
119
+ w: r.w / 2 + streamWidthMargin,
120
+ river: river.w,
121
+ });
122
+ }
123
+ }
124
+ }
125
+
126
+ return { bridge, bridges };
127
+ }
package/index.js CHANGED
@@ -56,6 +56,7 @@ export { SPRING_COLOURS, SPRING_HEAD, planSpringRocks, planSprings, springFrame,
56
56
  export { meshSprings } from './rendering/stream-springs.js';
57
57
  export { planShoreReeds } from './geometry/shore-reeds.js';
58
58
  export { roadRibbon } from './geometry/road-ribbon.js';
59
+ export { planBridgeFrame, planRoadBridges } from './geometry/road-bridges.js';
59
60
  export { layRoads } from './rendering/road-ribbons.js';
60
61
  export { createRoadTraffic, ROAD_TRAFFIC } from './motion/road-traffic.js';
61
62
  export { createFieldSurvey, FIELD_SURVEY, FIELD_USE } from './geometry/field-survey.js';
@@ -155,12 +156,16 @@ export { caninePose } from './motion/animal-canine-bearing.js';
155
156
  export { catPose } from './motion/animal-cat-bearing.js';
156
157
  export { herdArrays } from './motion/animal-herd-cast.js';
157
158
  export { createFlierShapes, createSwarm, FLY_WINGS } from './rendering/flier-swarm.js';
159
+ export { CARPET_LEVELS, canineStrideSteps, createCanineStrideCast, createCarpetSwarm } from './rendering/flier-carpet.js';
158
160
  export { FLY_LOOK, flyShape } from './geometry/flier-shapes.js';
159
161
  export { BEETLE_LOOK, RAT_LOOK, beetleGeometry, ratGeometry } from './geometry/crawl-shapes.js';
160
162
  export { createCrawlFlight } from './motion/flier-swarm-flight.js';
163
+ export { CARPET_DEFAULTS, createCarpetFlight } from './motion/flier-carpet-flight.js';
164
+ export { createLampSwarmFlight, pickNearestAnchors } from './motion/flier-lamp-swarm.js';
161
165
  export { createEchelonFlight, createEchelonPatrol } from './motion/flier-flight-echelon.js';
162
166
  export { createLandAirFlight, fitGridSpots } from './motion/flier-flight-air.js';
163
167
  export { bindFlockOrbit, createFlockCloud, pickHearthSites } from './motion/flier-flight-roost.js';
168
+ export { updateNearGroups } from './rendering/detail-range.js';
164
169
  export { createPenFlocks, packPenAnimals } from './rendering/pen-flocks.js';
165
170
  export { createLongFlierCompany } from './rendering/flier-long-body-company.js';
166
171
  export { createCorvidFigure } from './rendering/flier-corvid-figure.js';
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Flowing ground-carpet swarm motion: hundreds of small creatures pouring along a heading in a tapered carpet over arbitrary
3
+ * terrain, weaving laterally, climbing over one another in the thick of the tide, optionally trailing and milling behind a
4
+ * moving lead, and bucketing each creature into its distance level of detail and stride moment.
5
+ * Worker-safe arithmetic only (no Three.js dependency) and zero per-frame allocations.
6
+ * @module
7
+ */
8
+
9
+ import { createHash } from '../math/random.js';
10
+
11
+ const DEFAULT_HASH = createHash(0);
12
+
13
+ /**
14
+ * Default carpet swarm dimensions and motion parameters (metres and seconds).
15
+ */
16
+ export const CARPET_DEFAULTS = Object.freeze({
17
+ length: 22,
18
+ width: 13,
19
+ behind: 0.3,
20
+ pace: [1.6, 1.8],
21
+ mill: 0.35,
22
+ swerve: 0.25,
23
+ climbing: 0.22,
24
+ climb: 0.05,
25
+ });
26
+
27
+ /**
28
+ * Builds a zero-allocation carpet-flow placer for `count` creatures distributed across distance LOD levels and stride moments.
29
+ *
30
+ * @param {object} options
31
+ * @param {number} options.count Total creature instances in the carpet.
32
+ * @param {number} [options.spread=1] Scales carpet length, width, and internal running pace.
33
+ * @param {number} [options.size=1] Uniform creature scale applied to each instance matrix.
34
+ * @param {number} [options.stride=1] Metres covered per full stride cycle at unit scale.
35
+ * @param {number} [options.moments=1] Number of baked stride frames per LOD level.
36
+ * @param {number[]} [options.reach=[0]] Distance thresholds in metres where each LOD level starts.
37
+ * @param {number} [options.length=22] Base carpet length along its heading in metres.
38
+ * @param {number} [options.width=13] Base carpet width across its heading in metres.
39
+ * @param {number} [options.behind=0.3] Share of carpet length that the carpet centre trails behind a lead.
40
+ * @param {[number, number]} [options.pace=[1.6, 1.8]] Base and random extra speed through the carpet in metres per second.
41
+ * @param {number} [options.mill=0.35] Share of running pace retained when the lead stands still.
42
+ * @param {number} [options.swerve=0.25] Lateral weave amplitude in metres.
43
+ * @param {number} [options.climbing=0.22] Share of creatures climbing over others in the dense core.
44
+ * @param {number} [options.climb=0.05] Vertical lift of climbing creatures in metres.
45
+ * @param {(a: number, b: number, salt: number) => number} [options.hash] Deterministic `[0, 1)` 2D hash function.
46
+ * @returns {{ place: (t: number, x0: number, z0: number, yaw: number, ground: (x: number, z: number) => number, eyeX: number, eyeZ: number, matrices: Float32Array[][], counts: Int32Array[], speed?: number | null) => void }}
47
+ */
48
+ export function createCarpetFlight({
49
+ count,
50
+ spread = 1,
51
+ size = 1,
52
+ stride = 1,
53
+ moments = 1,
54
+ reach = [0],
55
+ length = CARPET_DEFAULTS.length,
56
+ width = CARPET_DEFAULTS.width,
57
+ behind = CARPET_DEFAULTS.behind,
58
+ pace = CARPET_DEFAULTS.pace,
59
+ mill = CARPET_DEFAULTS.mill,
60
+ swerve = CARPET_DEFAULTS.swerve,
61
+ climbing = CARPET_DEFAULTS.climbing,
62
+ climb = CARPET_DEFAULTS.climb,
63
+ hash = DEFAULT_HASH,
64
+ }) {
65
+ const reachSq = Float32Array.from(reach, r => r * r),
66
+ levelCount = reachSq.length,
67
+ carpetLength = length * spread,
68
+ carpetWidth = width * spread,
69
+ paceBase = pace[0],
70
+ paceRange = pace[1];
71
+
72
+ function place(t, x0, z0, yaw, ground, eyeX, eyeZ, matrices, counts, speed = null) {
73
+ const fx = Math.sin(yaw),
74
+ fz = Math.cos(yaw),
75
+ led = speed !== null,
76
+ cx = led ? x0 - fx * carpetLength * behind : x0,
77
+ cz = led ? z0 - fz * carpetLength * behind : z0,
78
+ keep = led ? Math.min(1, mill + speed / 4) : 1;
79
+
80
+ for (let l = 0; l < levelCount; l++) {
81
+ const row = counts[l];
82
+ for (let k = 0; k < moments; k++) row[k] = 0;
83
+ }
84
+
85
+ for (let i = 0; i < count; i++) {
86
+ const paceI = (paceBase + paceRange * hash(i, 3, 931)) * spread * keep,
87
+ runs = (((hash(i, 1, 932) * carpetLength + t * paceI) % carpetLength) + carpetLength) % carpetLength,
88
+ along = runs - carpetLength / 2,
89
+ thin = 1 - Math.abs(along) / (carpetLength / 2),
90
+ weave = t * (1.1 + hash(i, 6, 936)) + i,
91
+ across = (hash(i, 2, 933) - 0.5) * carpetWidth * (0.25 + 0.75 * Math.sqrt(thin)) + Math.sin(weave) * swerve,
92
+ x = cx + fx * along + fz * across,
93
+ z = cz + fz * along - fx * across,
94
+ grow = (0.85 + 0.35 * hash(i, 4, 934)) * Math.min(1, thin * 6),
95
+ over = hash(i, 5, 935) < climbing ? climb * Math.min(1, thin * 2) : 0,
96
+ ahead = (led ? speed : 0) + paceI,
97
+ swerveAngle = Math.atan2(swerve * (1.1 + hash(i, 6, 936)) * Math.cos(weave), Math.max(0.5, ahead)),
98
+ strideLen = stride * size * grow || 1,
99
+ moment = Math.floor(((((hash(i, 7, 937) + (t * ahead) / strideLen) % 1) + 1) % 1) * moments) % moments,
100
+ dx = x - eyeX,
101
+ dz = z - eyeZ,
102
+ d = dx * dx + dz * dz;
103
+
104
+ let l = 0;
105
+ while (l + 1 < levelCount && d >= reachSq[l + 1]) l++;
106
+
107
+ const idx = counts[l][moment]++,
108
+ m = matrices[l][moment],
109
+ o = idx * 16,
110
+ s = size * grow,
111
+ half = (yaw + swerveAngle) * 0.5,
112
+ qy = Math.sin(half),
113
+ qw = Math.cos(half),
114
+ y2 = qy + qy,
115
+ yy = qy * y2,
116
+ wy = qw * y2,
117
+ // Match Three.js Matrix4.compose(pos, quat, scale) pure-Y rotation signed zero so Float32 bytes stay bit-identical.
118
+ yz = qy * 0 - qw * 0;
119
+ m[o] = (1 - yy) * s;
120
+ m[o + 1] = 0;
121
+ m[o + 2] = (0 - wy) * s;
122
+ m[o + 3] = 0;
123
+ m[o + 4] = yz * s;
124
+ m[o + 5] = s;
125
+ m[o + 6] = 0;
126
+ m[o + 7] = 0;
127
+ m[o + 8] = wy * s;
128
+ m[o + 9] = yz * s;
129
+ m[o + 10] = (1 - yy) * s;
130
+ m[o + 11] = 0;
131
+ m[o + 12] = x;
132
+ m[o + 13] = ground(x, z) + over;
133
+ m[o + 14] = z;
134
+ m[o + 15] = 1;
135
+ }
136
+ }
137
+
138
+ return { place };
139
+ }
@@ -21,13 +21,32 @@ import { lerp, sstep } from '../math/scalar.js';
21
21
  * @param {number} [options.airspeed=0] Optional constant airspeed in metres per second.
22
22
  * @param {() => number} options.elapsed World clock in seconds.
23
23
  * @param {() => number} options.frame Monotonic frame counter.
24
+ * @param {number} [options.showNear=Infinity] Optional maximum metres from `lens` within which the flock updates and draws
25
+ * (beyond this distance `mesh.count` is zeroed while `onBeforeRender` keeps polling so the flock returns when approached).
26
+ * @param {{ position: { x: number, y: number, z: number } } | null} [options.lens=null] Camera checked against `showNear`.
24
27
  * @returns {object} The flock's mesh.
25
28
  */
26
- export function bindFlockOrbit(flock, { x, y, z, radius, height, timeScale = 1, airspeed = 0, elapsed, frame }) {
29
+ export function bindFlockOrbit(
30
+ flock,
31
+ { x, y, z, radius, height, timeScale = 1, airspeed = 0, elapsed, frame, showNear = Infinity, lens = null },
32
+ ) {
33
+ const nearSq = Number.isFinite(showNear) && lens ? showNear * showNear : Infinity,
34
+ fullCount = flock.birds?.length ?? flock.mesh.count;
27
35
  flock.mesh.onBeforeRender = () => {
28
36
  const current = frame();
29
37
  if (flock.f !== current) {
30
38
  flock.f = current;
39
+ if (nearSq < Infinity) {
40
+ const at = lens.position,
41
+ dx = x - at.x,
42
+ dy = y - at.y,
43
+ dz = z - at.z;
44
+ if (dx * dx + dy * dy + dz * dz > nearSq) {
45
+ flock.mesh.count = 0;
46
+ return;
47
+ }
48
+ flock.mesh.count = fullCount;
49
+ }
31
50
  if (airspeed > 0) flock.update(x, y, z, radius, height, elapsed() * timeScale, airspeed);
32
51
  else flock.update(x, y, z, radius, height, elapsed() * timeScale);
33
52
  }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Night-time insect swarms orbiting the nearest light points (street lamps, lanterns, torches) within reach of the viewer.
3
+ * Worker-safe arithmetic only (no Three.js dependency) and zero per-frame allocations.
4
+ * @module
5
+ */
6
+
7
+ /**
8
+ * Picks up to `count` nearest points within `reach` metres of `(cx, cy, cz)`, ordered nearest first, and writes their
9
+ * lowered anchor coordinates `(x, y - drop, z)` into `anchors` (wrapping slots modulo `found` when fewer than `count` points
10
+ * lie in range). Returns how many points were found within `reach`.
11
+ *
12
+ * @param {number} cx Viewer x coordinate in metres.
13
+ * @param {number} cy Viewer y coordinate in metres.
14
+ * @param {number} cz Viewer z coordinate in metres.
15
+ * @param {Array<{ x: number, y: number, z: number }>} points Candidate light positions.
16
+ * @param {object} options
17
+ * @param {number} options.count Maximum number of active anchor slots.
18
+ * @param {number} options.reach Maximum 3D distance in metres from the viewer.
19
+ * @param {number} [options.drop=0.12] Vertical offset below each point in metres (e.g. from lamp head to lantern panes).
20
+ * @param {Float32Array} options.anchors Destination anchor buffer (`length >= count * 3`).
21
+ * @param {Int32Array} options.near Scratch index buffer (`length >= count`).
22
+ * @param {Float32Array} options.nearD Scratch squared-distance buffer (`length >= count`).
23
+ * @returns {number} Number of points found within `reach`.
24
+ */
25
+ export function pickNearestAnchors(cx, cy, cz, points, { count, reach, drop = 0.12, anchors, near, nearD }) {
26
+ const reachSq = reach * reach;
27
+ let found = 0;
28
+ for (let i = 0; i < points.length; i++) {
29
+ const p = points[i],
30
+ d = (p.x - cx) ** 2 + (p.y - cy) ** 2 + (p.z - cz) ** 2;
31
+ if (d > reachSq || (found === count && d >= nearD[count - 1])) continue;
32
+ let k = Math.min(found, count - 1);
33
+ while (k > 0 && nearD[k - 1] > d) {
34
+ near[k] = near[k - 1];
35
+ nearD[k] = nearD[k - 1];
36
+ k--;
37
+ }
38
+ near[k] = i;
39
+ nearD[k] = d;
40
+ if (found < count) found++;
41
+ }
42
+ if (!points.length) return 0;
43
+ // Each slot past the lights found shares the nearest ones again so the whole swarm stays busy around the active lanterns.
44
+ for (let k = 0; k < count; k++) {
45
+ const p = points[near[found ? k % found : 0]];
46
+ anchors[k * 3] = p.x;
47
+ anchors[k * 3 + 1] = p.y - drop;
48
+ anchors[k * 3 + 2] = p.z;
49
+ }
50
+ return found;
51
+ }
52
+
53
+ /**
54
+ * Per-frame controller for a swarm hovering around the nearest lit lamps at night: hides during daylight, periodically refits
55
+ * its anchor buffer to the nearest light points within `reach`, scales the swarm's caught lamp glow by darkness, and advances
56
+ * the swarm's motion. Zero per-frame allocations.
57
+ *
58
+ * @param {object} options
59
+ * @param {{ mesh: { visible: boolean }, update: (t: number) => void, glow: { setRGB: (r: number, g: number, b: number) => unknown } }} options.swarm
60
+ * Hover swarm created by `createSwarm`.
61
+ * @param {Float32Array} options.anchors Anchor buffer shared with `swarm` (`count * 3` floats).
62
+ * @param {Array<{ x: number, y: number, z: number }> | (() => Array<{ x: number, y: number, z: number }>)} options.points
63
+ * Light positions (or a getter returning the live array).
64
+ * @param {number} [options.count=12] Maximum number of lit anchors served at once.
65
+ * @param {number} [options.reach=60] Metres from the viewer within which lamps carry a swarm.
66
+ * @param {number} [options.refit=0.5] Seconds between re-selecting the nearest lamps.
67
+ * @param {number} [options.dark=0.3] Minimum night factor (`0..1`) before the swarm appears.
68
+ * @param {number} [options.drop=0.12] Metres below each lamp point that the swarm orbits.
69
+ * @param {number} [options.glow=1.1] Share of the lamp tint caught by each flier at full night.
70
+ * @param {[number, number, number]} [options.tint=[1, 0.85, 0.55]] Linear RGB lamp colour.
71
+ * @returns {(cx: number, cy: number, cz: number, t: number, night: number) => void}
72
+ */
73
+ export function createLampSwarmFlight({
74
+ swarm,
75
+ anchors,
76
+ points,
77
+ count = 12,
78
+ reach = 60,
79
+ refit = 0.5,
80
+ dark = 0.3,
81
+ drop = 0.12,
82
+ glow = 1.1,
83
+ tint = [1, 0.85, 0.55],
84
+ }) {
85
+ const near = new Int32Array(count),
86
+ nearD = new Float32Array(count),
87
+ pickOpts = { count, reach, drop, anchors, near, nearD };
88
+ let lastRefit = -1;
89
+
90
+ return function updateLampSwarm(cx, cy, cz, t, night) {
91
+ const list = typeof points === 'function' ? points() : points;
92
+ if (night < dark || !list.length) {
93
+ swarm.mesh.visible = false;
94
+ return;
95
+ }
96
+ if (t - lastRefit > refit || t < lastRefit) {
97
+ lastRefit = t;
98
+ swarm.mesh.visible = pickNearestAnchors(cx, cy, cz, list, pickOpts) > 0;
99
+ }
100
+ if (!swarm.mesh.visible) return;
101
+ const scale = glow * night;
102
+ swarm.glow.setRGB(tint[0] * scale, tint[1] * scale, tint[2] * scale);
103
+ swarm.update(t);
104
+ };
105
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "roamwright",
3
- "version": "0.61.11",
3
+ "version": "0.61.12",
4
4
  "description": "A procedural worldbuilding engine built on top of Three.js. Generate landscapes with rivers and changing weather, animate crowds, and explore on foot or in flight.",
5
5
  "keywords": [
6
6
  "threejs",
@@ -27,3 +27,25 @@ export function detailLevel(d2, previous, lens, near, medium, light, nearLensCap
27
27
  if (withinDetailRange(d2, previous >= 2, Math.min(lens, mediumLensCap), medium)) return 2;
28
28
  return withinDetailRange(d2, previous >= 1, lens, light) ? 1 : 0;
29
29
  }
30
+
31
+ /**
32
+ * Shows each near-detail group entry within its `range` of `eye` (and not nearer than optional `from`), lazily invoking
33
+ * `entry.raise()` the first time an unbuilt entry enters range, and toggling optional `entry.far` inversely.
34
+ * Uses 3D distance when `entry.y` is defined and 2D horizontal distance otherwise. Zero per-frame allocations.
35
+ *
36
+ * @param {Array<{ x: number, z: number, range: number, y?: number, from?: number, group?: { visible: boolean } | null, far?: { visible: boolean } | null, raise?: (() => { visible: boolean }) | null }>} groups
37
+ * @param {{ x: number, y: number, z: number }} eye Camera or viewer position in metres.
38
+ */
39
+ export function updateNearGroups(groups, eye) {
40
+ const ex = eye.x,
41
+ ey = eye.y,
42
+ ez = eye.z;
43
+ for (let i = 0; i < groups.length; i++) {
44
+ const entry = groups[i],
45
+ d = Math.hypot(ex - entry.x, ez - entry.z, entry.y === undefined ? 0 : ey - entry.y),
46
+ shown = d < entry.range && !(d < entry.from);
47
+ if (shown && entry.raise) [entry.group, entry.raise] = [entry.raise(), null];
48
+ if (entry.group) entry.group.visible = shown;
49
+ if (entry.far) entry.far.visible = !shown;
50
+ }
51
+ }
@@ -0,0 +1,232 @@
1
+ /**
2
+ * Multi-LOD instanced carpet swarms (flowing tides of rats, ants, snakes, spiders or other small ground creatures) and
3
+ * stepped stride casting for quadruped swarm creatures so sets raised live never hold a frame.
4
+ * @module
5
+ */
6
+
7
+ import * as THREE from 'three';
8
+ import { canineBodies } from '../geometry/animal-canine-body.js';
9
+ import { gathered } from '../geometry/grid-gather.js';
10
+ import { castBeast } from '../motion/animal-bearing.js';
11
+ import { caninePose } from '../motion/animal-canine-bearing.js';
12
+ import { createCarpetFlight } from '../motion/flier-carpet-flight.js';
13
+ import { buildCanine } from './animal-canine-figure.js';
14
+
15
+ /**
16
+ * Default distance LOD levels for a cast quadruped carpet swarm: full skin close up (casting shadows), then progressively
17
+ * grid-gathered meshes further off.
18
+ */
19
+ export const CARPET_LEVELS = Object.freeze([
20
+ { from: 0, grid: 0, shadow: true },
21
+ { from: 4, grid: 0.22, shadow: false },
22
+ { from: 9, grid: 0.34, shadow: false },
23
+ ]);
24
+
25
+ /**
26
+ * Generator that bakes a canine/rodent gallop into `moments` still geometries across `levels` LOD grids, yielding after each
27
+ * heavy step (settling, timing, each stride moment, each LOD gather) so callers can give frames back between steps.
28
+ * Stepped or run synchronously, it produces the exact same geometries and stride length.
29
+ *
30
+ * @param {object} options
31
+ * @param {object} options.look Canine/rodent look passed to `canineBodies` and `buildCanine`.
32
+ * @param {THREE.Material} options.material Material bound to the temporary rigged mesh during casting.
33
+ * @param {import('../geometry/animal-options.js').AnimalKitOptions} [options.options] Animal kit options.
34
+ * @param {number} [options.moments=6] Number of stride phases to bake.
35
+ * @param {number} [options.run=2.3] Gallop speed in leg lengths per second.
36
+ * @param {number} [options.step=1/240] Simulation timestep in seconds.
37
+ * @param {number} [options.settle=720] Simulation steps per settling / timing pass.
38
+ * @param {number} [options.seed=0.37] Actor phase seed.
39
+ * @param {Array<{ from: number, grid: number, shadow: boolean }>} [options.levels=CARPET_LEVELS] LOD grid specs.
40
+ * @returns {Generator<void, { levels: THREE.BufferGeometry[][], stride: number }, void>}
41
+ */
42
+ export function* canineStrideSteps({
43
+ look,
44
+ material,
45
+ options,
46
+ moments = 6,
47
+ run = 2.3,
48
+ step = 1 / 240,
49
+ settle = 720,
50
+ seed = 0.37,
51
+ levels = CARPET_LEVELS,
52
+ }) {
53
+ const rigSet = buildCanine(look, material, options, canineBodies(look, 0, undefined, options)),
54
+ rig = rigSet.rig,
55
+ body = rigSet.lo,
56
+ actor = { rig, pose: 'idle', seed, x: 0, y: 0, z: 0, yaw: 0, group: rigSet.group, fixY: 0, cur: null },
57
+ speed = run * rig.leg * rigSet.group.scale.y,
58
+ frames = [];
59
+ let t = 0,
60
+ turned = 0;
61
+
62
+ const advance = () => {
63
+ const ph = rig.ph;
64
+ actor.z += speed * step;
65
+ t += step;
66
+ rigSet.group.position.z = actor.z;
67
+ caninePose(actor, step, t, null);
68
+ rigSet.group.updateMatrixWorld(true);
69
+ turned += (rig.ph - ph + 1) % 1;
70
+ };
71
+
72
+ for (let i = 0; i < settle; i++) advance();
73
+ yield;
74
+ turned = 0;
75
+ for (let i = 0; i < settle; i++) advance();
76
+ yield;
77
+ const stride = (speed * settle * step) / turned;
78
+
79
+ for (let k = 0; k < moments; k++) {
80
+ const ahead = () => (rig.ph - k / moments + 1.5) % 1 >= 0.5;
81
+ for (let guard = 0; guard < 2400 && ahead(); guard++) advance();
82
+ for (let guard = 0; guard < 2400 && !ahead(); guard++) advance();
83
+ frames.push(castBeast({ mesh: body, far: body.geometry }));
84
+ yield;
85
+ }
86
+
87
+ const bakedLevels = [];
88
+ for (const l of levels) {
89
+ bakedLevels.push(l.grid ? frames.map(f => gathered(f, l.grid)) : frames);
90
+ yield;
91
+ }
92
+ return { levels: bakedLevels, stride: stride / rigSet.group.scale.y };
93
+ }
94
+
95
+ /**
96
+ * Creates a cached, lazily-baked quadruped stride cast supporting both synchronous `get()` and frame-yielding
97
+ * `inTurns(breathe)` (sharing one in-flight promise so concurrent sets never bake twice).
98
+ *
99
+ * @param {object} config Options forwarded to {@link canineStrideSteps} (`material` may be a getter function).
100
+ * @returns {{ get: () => { levels: THREE.BufferGeometry[][], stride: number }, inTurns: (breathe: () => Promise<void>) => Promise<void> }}
101
+ */
102
+ export function createCanineStrideCast(config) {
103
+ let cached = null,
104
+ casting = null;
105
+ const resolveConfig = () => (typeof config.material === 'function' ? { ...config, material: config.material() } : config);
106
+
107
+ function get() {
108
+ if (cached) return cached;
109
+ const steps = canineStrideSteps(resolveConfig());
110
+ for (;;) {
111
+ const { value, done } = steps.next();
112
+ if (done) return (cached = value);
113
+ }
114
+ }
115
+
116
+ async function inTurns(breathe) {
117
+ if (cached) return;
118
+ if (casting) return casting;
119
+ casting = (async () => {
120
+ const steps = canineStrideSteps(resolveConfig());
121
+ await breathe();
122
+ for (;;) {
123
+ const { value, done } = steps.next();
124
+ if (done) {
125
+ cached = value;
126
+ return;
127
+ }
128
+ await breathe();
129
+ }
130
+ })();
131
+ await casting;
132
+ }
133
+
134
+ return { get, inTurns };
135
+ }
136
+
137
+ /**
138
+ * Builds a flowing carpet swarm of `count` creatures backed by one `InstancedMesh` per `(LOD level, stride moment)` inside a
139
+ * hidden `THREE.Group`. Supports both animated multi-LOD stride casts (`run`) and single static creature geometries
140
+ * (`geometry`). Zero per-frame allocations inside `flow`.
141
+ *
142
+ * @param {object} options
143
+ * @param {THREE.Object3D | null} [options.parent=null] Optional parent group to attach the swarm group to.
144
+ * @param {number} options.count Number of creatures in the swarm.
145
+ * @param {{ levels: THREE.BufferGeometry[][], stride: number } | null} [options.run=null] Baked stride levels and stride length.
146
+ * @param {THREE.BufferGeometry | null} [options.geometry=null] Single static geometry (overrides `run` when supplied).
147
+ * @param {THREE.Material} options.material Instanced material shared across all level/moment meshes.
148
+ * @param {{ position: { x: number, z: number } }} options.camera Camera used to choose each creature's LOD level.
149
+ * @param {number} [options.size=1] Uniform scale of each creature.
150
+ * @param {number} [options.spread=1] Scales carpet length, width, and creature speed through the carpet.
151
+ * @param {Array<{ from: number, shadow: boolean }>} [options.levels=CARPET_LEVELS] LOD thresholds and shadow flags.
152
+ * @param {(a: number, b: number, salt: number) => number} [options.hash] Deterministic `[0, 1)` 2D hash function.
153
+ * @param {number} [options.length] Base carpet length in metres.
154
+ * @param {number} [options.width] Base carpet width in metres.
155
+ * @param {number} [options.behind] Share of carpet length trailing a lead.
156
+ * @param {[number, number]} [options.pace] Running speed `[base, range]` in metres per second.
157
+ * @param {number} [options.mill] Pace share when the lead stands still.
158
+ * @param {number} [options.swerve] Lateral weave amplitude in metres.
159
+ * @param {number} [options.climbing] Share of climbing creatures.
160
+ * @param {number} [options.climb] Climb lift in metres.
161
+ * @returns {{ mesh: THREE.Group, flow: (t: number, x0: number, z0: number, yaw: number, ground: (x: number, z: number) => number, speed?: number | null) => void, update: Function }}
162
+ */
163
+ export function createCarpetSwarm({
164
+ parent = null,
165
+ count,
166
+ run = null,
167
+ geometry = null,
168
+ material,
169
+ camera,
170
+ size = 1,
171
+ spread = 1,
172
+ levels = CARPET_LEVELS,
173
+ hash,
174
+ length,
175
+ width,
176
+ behind,
177
+ pace,
178
+ mill,
179
+ swerve,
180
+ climbing,
181
+ climb,
182
+ }) {
183
+ const activeRun = geometry ? { levels: [[geometry]], stride: 1 } : run,
184
+ mesh = new THREE.Group(),
185
+ meshes = activeRun.levels.map((frames, k) =>
186
+ frames.map(geo => {
187
+ const m = new THREE.InstancedMesh(geo, material, count);
188
+ m.frustumCulled = false;
189
+ m.castShadow = levels[k]?.shadow ?? false;
190
+ mesh.add(m);
191
+ return m;
192
+ }),
193
+ ),
194
+ moments = meshes[0].length,
195
+ reach = meshes.map((_, k) => levels[k]?.from ?? 0),
196
+ matrices = meshes.map(row => row.map(m => m.instanceMatrix.array)),
197
+ counts = meshes.map(() => new Int32Array(moments)),
198
+ flight = createCarpetFlight({
199
+ count,
200
+ spread,
201
+ size,
202
+ stride: activeRun.stride,
203
+ moments,
204
+ reach,
205
+ ...(hash ? { hash } : {}),
206
+ ...(length !== undefined ? { length } : {}),
207
+ ...(width !== undefined ? { width } : {}),
208
+ ...(behind !== undefined ? { behind } : {}),
209
+ ...(pace !== undefined ? { pace } : {}),
210
+ ...(mill !== undefined ? { mill } : {}),
211
+ ...(swerve !== undefined ? { swerve } : {}),
212
+ ...(climbing !== undefined ? { climbing } : {}),
213
+ ...(climb !== undefined ? { climb } : {}),
214
+ });
215
+
216
+ mesh.visible = false;
217
+ if (parent) parent.add(mesh);
218
+
219
+ function flow(t, x0, z0, yaw, ground, speed = null) {
220
+ flight.place(t, x0, z0, yaw, ground, camera.position.x, camera.position.z, matrices, counts, speed);
221
+ for (let l = 0; l < meshes.length; l++) {
222
+ const row = meshes[l],
223
+ c = counts[l];
224
+ for (let k = 0; k < moments; k++) {
225
+ row[k].count = c[k];
226
+ row[k].instanceMatrix.needsUpdate = true;
227
+ }
228
+ }
229
+ }
230
+
231
+ return { mesh, flow, update: flow };
232
+ }
@@ -158,6 +158,8 @@ export function plumage(hex, least = 0.035) {
158
158
  * @param {number} [options.lensClear=5] Wingspans a bird keeps from the lens: nearer, one bird would fill the picture.
159
159
  * @param {object} [options.calls] Now and then one bird calls: { sound(x, y, z, loudness), heard: metres within which it is heard
160
160
  * (80), gap: [least, most] seconds between calls (4, 12) }.
161
+ * @param {number} [options.showNear=Infinity] Maximum distance in metres from `lens` within which `update()` draws and updates
162
+ * the flock; beyond this distance the mesh is hidden and matrix updates are skipped.
161
163
  * @param {string} [options.key] Told apart from other flock materials (`customProgramCacheKey`).
162
164
  */
163
165
  export function createFlock({
@@ -172,6 +174,7 @@ export function createFlock({
172
174
  least = 0.035,
173
175
  lensClear = 5,
174
176
  calls,
177
+ showNear = Infinity,
175
178
  key = look ? 'bird' : 'plain',
176
179
  }) {
177
180
  const bird = !!look,
@@ -229,7 +232,19 @@ export function createFlock({
229
232
  wob: random() * TAU,
230
233
  beat: 1, // how hard it beats now, eased towards what its climb or fall asks
231
234
  });
232
- return flockFlight({ mesh, birds, flap, size, lens, bird, soar: bird && look.soar, silent: !bird || look.silent, calls, lensClear });
235
+ return flockFlight({
236
+ mesh,
237
+ birds,
238
+ flap,
239
+ size,
240
+ lens,
241
+ bird,
242
+ soar: bird && look.soar,
243
+ silent: !bird || look.silent,
244
+ calls,
245
+ lensClear,
246
+ showNear,
247
+ });
233
248
  }
234
249
 
235
250
  const GRAVITY = 9.8, // metres a second a second
@@ -240,10 +255,11 @@ const GRAVITY = 9.8, // metres a second a second
240
255
  BOB_RATE = 0.3, // radians a second of that rise and fall
241
256
  SOAR_BEAT = 0.12; // how hard a soaring bird beats at most
242
257
 
243
- function flockFlight({ mesh, birds, flap, size, lens, bird, soar, silent, calls, lensClear }) {
258
+ function flockFlight({ mesh, birds, flap, size, lens, bird, soar, silent, calls, lensClear, showNear = Infinity }) {
244
259
  const n = birds.length,
245
260
  place = placement(),
246
261
  clear = lensClear * SPAN * size, // metres
262
+ nearSq = Number.isFinite(showNear) ? showNear * showNear : Infinity,
247
263
  heard = calls?.heard ?? 80,
248
264
  gap = calls?.gap ?? [4, 12];
249
265
  let last = null,
@@ -284,6 +300,17 @@ function flockFlight({ mesh, birds, flap, size, lens, bird, soar, silent, calls,
284
300
  // metres a second, flies every bird at about that pace however wide the flock wheels; without it each bird keeps a turn of its
285
301
  // own, so that a wider circle is flown faster.
286
302
  update(cx, cy, cz, radius, height, t, airspeed = 0) {
303
+ if (nearSq < Infinity) {
304
+ const at = lens.position,
305
+ dx = cx - at.x,
306
+ dy = cy - at.y,
307
+ dz = cz - at.z;
308
+ if (dx * dx + dy * dy + dz * dz > nearSq) {
309
+ mesh.visible = false;
310
+ return;
311
+ }
312
+ mesh.visible = true;
313
+ }
287
314
  const first = last === null,
288
315
  deltaSeconds = first ? 0 : Math.min(0.1, Math.max(0, t - last)),
289
316
  bob = Math.min(BOB, BOB_SHARE * height);