roamwright 0.61.25 → 0.61.27

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,374 @@
1
+ /**
2
+ * Troop director rendering binding: raises scene hosts into instanced crowd batches, mounts,
3
+ * herds, wagons, carried standards, and ballistic volley shafts, stepping formations and effects
4
+ * each frame with zero per-frame allocations.
5
+ * @module
6
+ */
7
+
8
+ import * as THREE from 'three';
9
+ import { mulberry32 } from '../math/random.js';
10
+ import { clamp } from '../math/scalar.js';
11
+ import {
12
+ TROOP_ARMED_KINDS,
13
+ TROOP_DUST_DEFAULTS,
14
+ TROOP_RANGED_NAME,
15
+ TROOP_SADDLE,
16
+ TROOP_SEEN_FROM,
17
+ TROOP_TEAM,
18
+ TROOP_UNSEEN,
19
+ applyTroopCue,
20
+ musterTroop,
21
+ refreshTroopOpponents,
22
+ standTroop,
23
+ stepTroopMember,
24
+ } from '../motion/troop-director.js';
25
+ import { TROOP_VOLLEY_DEFAULTS } from '../motion/troop-volleys.js';
26
+ import { createTroopVolleys } from './troop-volleys.js';
27
+
28
+ const _tint = new THREE.Color();
29
+
30
+ /**
31
+ * Creates a troop director bound to a world's crowd batches, mounts, herds, wagons, standards,
32
+ * camera, clock, visibility checks, and effect/foley hooks.
33
+ *
34
+ * @param {object} config
35
+ * @param {number} [config.seed=1] World seed used to derive deterministic per-set troop and volley PRNGs.
36
+ * @param {{ position: { x: number, z: number } }} config.camera Active camera for sight, LOD and dust range checks.
37
+ * @param {() => number} config.getTime Returns elapsed simulation time in seconds.
38
+ * @param {() => boolean} [config.getShadowsEnabled] Returns true when directional sun shadows are enabled.
39
+ * @param {() => number} [config.getCrowdShare] Returns `[0, 1]` quality multiplier for visible mounted/beast counts.
40
+ * @param {() => number} [config.getFxShare] Returns `[0, 1]` particle-effect budget share.
41
+ * @param {(x: number, y: number, z: number, r: number, nearOnly?: boolean, casts?: boolean) => boolean} [config.inView] Frustum visibility predicate.
42
+ * @param {(x: number, y: number, z: number, r: number) => boolean} [config.shadowCasts] Shadow-frustum inclusion predicate.
43
+ * @param {(list: object[], tones: number[], cx: number, cz: number, near: number, kind: string, bodyId: string|undefined, spaceId: string) => object} config.addCrowd Registers a human troop into crowd batches.
44
+ * @param {(bodyId: string|undefined, troop: object) => [number, number]|null|undefined} [config.standardOf] Resolves `[fieldHex, edgeHex]` for a troop's standard.
45
+ * @param {(mesh: THREE.Object3D) => Promise<void>} [config.warmShaders] Async shader warmer for volley meshes.
46
+ * @param {() => THREE.Material} [config.volleyMaterial] Tinted material factory for volley shafts.
47
+ * @param {((group: THREE.Object3D, n: number, lances: number) => object)|null} [config.makeMounts] Horse and lance instancing builder (`createTroopMounts`).
48
+ * @param {((group: THREE.Object3D, n: number) => object)|null} [config.makeHerd] Cattle/ox instancing builder (`createTroopMounts`).
49
+ * @param {((group: THREE.Object3D, n: number, rng: () => number) => object)|null} [config.makeWagons] Wagon instancing builder (`createTroopMounts`).
50
+ * @param {((group: THREE.Object3D, troops: object[]) => object)|null} [config.makeStandards] Carried standard builder (`createTroopStandards`).
51
+ * @param {((x: number, y: number, z: number, puffs: number, size: number, speed: number) => void)|null} [config.onDust] Localized battle/fall dust callback.
52
+ * @param {((x: number, y: number, z: number, count: number) => void)|null} [config.onVolley] Volley launch foley callback.
53
+ * @param {((x: number, y: number, z: number, intensity: number) => void)|null} [config.onClash] Ongoing scrimmage battle-din foley callback.
54
+ * @param {Set<string>} [config.armedKinds] Crowd kinds defaulting to `'ready'` stance.
55
+ * @param {RegExp} [config.rangedPattern] Pattern identifying ranged troop names.
56
+ * @param {number} [config.seenFrom=900] Default sight distance in metres for a raised host.
57
+ * @param {number} [config.saddle=1.2] Mounted rider seat height in metres.
58
+ * @param {{ ahead: number, apart: number }} [config.team] Wagon ox-team offsets in metres.
59
+ * @param {number} [config.unseen=-1] Hidden `home` sentinel.
60
+ * @returns {{ raiseHost: Function, cue: Function, resetHost: Function, resetAll: Function, hostTroop: Function, getHost: Function }}
61
+ */
62
+ export function createTroopDirector({
63
+ seed = 1,
64
+ camera,
65
+ getTime,
66
+ getShadowsEnabled = () => true,
67
+ getCrowdShare = () => 1,
68
+ getFxShare = () => 1,
69
+ inView = () => true,
70
+ shadowCasts = () => true,
71
+ addCrowd,
72
+ standardOf = (_bodyId, troop) => troop?.spec?.standard || null,
73
+ warmShaders = () => Promise.resolve(),
74
+ volleyMaterial = () => new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.9 }),
75
+ makeMounts = null,
76
+ makeHerd = null,
77
+ makeWagons = null,
78
+ makeStandards = null,
79
+ onDust = null,
80
+ onVolley = null,
81
+ onClash = null,
82
+ armedKinds = TROOP_ARMED_KINDS,
83
+ rangedPattern = TROOP_RANGED_NAME,
84
+ seenFrom = TROOP_SEEN_FROM,
85
+ saddle = TROOP_SADDLE,
86
+ team = TROOP_TEAM,
87
+ unseen = TROOP_UNSEEN,
88
+ }) {
89
+ const hosts = new Map();
90
+ const dustViewDist = TROOP_DUST_DEFAULTS.viewDist;
91
+ const dustViewDist2 = dustViewDist * dustViewDist;
92
+ const fallDustDist2 = TROOP_DUST_DEFAULTS.fallDist * TROOP_DUST_DEFAULTS.fallDist;
93
+ const volleyViewDist2 = TROOP_VOLLEY_DEFAULTS.viewDist * TROOP_VOLLEY_DEFAULTS.viewDist;
94
+ const clashFoleyInterval = TROOP_DUST_DEFAULTS.clashFoleyInterval;
95
+ const standOptions = { saddle, armedKinds, unseen };
96
+ const cueOptions = { armedKinds, unseen };
97
+
98
+ function raiseHost(sp, setId, entries, near = seenFrom) {
99
+ const rng = mulberry32(seed * 131 + setId.length * 17 + setId.charCodeAt(0)),
100
+ volleyRng = mulberry32(seed * 197 + setId.length * 31 + setId.charCodeAt(0)),
101
+ host = { troops: {}, opponentsDirty: true },
102
+ troops = [],
103
+ bodies = new Set();
104
+ let cx = 0,
105
+ cz = 0,
106
+ riders = 0,
107
+ lancers = 0,
108
+ cattle = 0,
109
+ wagons = 0;
110
+
111
+ for (let ei = 0; ei < entries.length; ei++) {
112
+ const entry = entries[ei];
113
+ const ox = entry.originX,
114
+ oz = entry.originZ;
115
+ cx = ox;
116
+ cz = oz;
117
+ for (const name in entry.troops) {
118
+ const spec = entry.troops[name],
119
+ face = spec.face || [spec.at[0], spec.at[1] + 1],
120
+ hasStandard = !spec.beast && !!standardOf(spec.body, { spec }),
121
+ mustered = musterTroop(spec, rng, { hasStandard }),
122
+ troop = {
123
+ name,
124
+ spec,
125
+ list: mustered.list,
126
+ wide: mustered.wide,
127
+ loose: mustered.loose,
128
+ halfWidth: mustered.halfWidth,
129
+ ranks: mustered.ranks,
130
+ files: mustered.files,
131
+ rankNorms: mustered.rankNorms,
132
+ edgeNorms: mustered.edgeNorms,
133
+ ranged: rangedPattern.test(name),
134
+ at: { x: ox + spec.at[0], z: oz + spec.at[1] },
135
+ yaw: Math.atan2(face[0] - spec.at[0], face[1] - spec.at[1]),
136
+ facing: 0,
137
+ cx: 0,
138
+ cz: 0,
139
+ busy: false,
140
+ fighting: false,
141
+ visible: !spec.hide,
142
+ engageDepth: 0,
143
+ volleyTarget: null,
144
+ nextVolleyAt: 0,
145
+ nextDustAt: 0,
146
+ dustCursor: 0,
147
+ phase: rng() * 6.28,
148
+ };
149
+ host.troops[name] = troop;
150
+ troops.push(troop);
151
+ if (!spec.beast && spec.body) bodies.add(spec.body);
152
+ if (spec.mounted || spec.beast === 'horse') riders += spec.n;
153
+ if (spec.lance) lancers += spec.n;
154
+ if (spec.beast === 'cattle') cattle += spec.n;
155
+ if (spec.beast === 'wagon') {
156
+ wagons += spec.n;
157
+ cattle += spec.n * 2;
158
+ }
159
+ }
160
+ }
161
+
162
+ for (let i = 0; i < troops.length; i++) {
163
+ const troop = troops[i];
164
+ standTroop(troop, standOptions);
165
+ if (!troop.spec.beast) {
166
+ addCrowd(troop.list, troop.spec.tones, cx, cz, near, troop.spec.kind, troop.spec.body, sp.id);
167
+ } else {
168
+ for (let j = 0; j < troop.list.length; j++) {
169
+ troop.list[j].c1 = _tint.setHex(troop.spec.tones[troop.list[j].coat % troop.spec.tones.length]).clone();
170
+ }
171
+ }
172
+ }
173
+
174
+ const group = new THREE.Group();
175
+ sp.group.add(group);
176
+ const mounts = riders && makeMounts ? makeMounts(group, riders, lancers) : null,
177
+ herd = cattle && makeHerd ? makeHerd(group, cattle) : null,
178
+ train = wagons && makeWagons ? makeWagons(group, wagons, rng) : null,
179
+ standards = makeStandards ? makeStandards(group, troops) : null,
180
+ volleys =
181
+ bodies.size >= 2
182
+ ? createTroopVolleys({
183
+ group,
184
+ material: volleyMaterial,
185
+ warmShaders,
186
+ inView,
187
+ camera,
188
+ getFxShare,
189
+ onDust,
190
+ onVolley,
191
+ saddle,
192
+ unseen,
193
+ })
194
+ : null,
195
+ // Hold mounted riders unseen until their horses' shaders compile so nobody floats in midair.
196
+ heldBack = mounts ? troops.flatMap(troop => (troop.spec.mounted ? troop.list.filter(g => g.home === undefined) : [])) : [];
197
+ for (let i = 0; i < heldBack.length; i++) heldBack[i].home = unseen;
198
+
199
+ hosts.set(setId, host);
200
+ host.reset = () => {
201
+ for (let i = 0; i < troops.length; i++) standTroop(troops[i], standOptions);
202
+ volleys?.reset();
203
+ host.opponentsDirty = true;
204
+ };
205
+
206
+ let wasSeen = false,
207
+ nextClashFoleyAt = 0,
208
+ frameNearCamera = false;
209
+
210
+ function handleFallLand(x, z) {
211
+ if (frameNearCamera && getFxShare() > 0 && onDust) {
212
+ const dx = x - camera.position.x,
213
+ dz = z - camera.position.z;
214
+ if (dx * dx + dz * dz < fallDustDist2) onDust(x, sp.ground(x, z) + 0.1, z, 2, 0.75, 0.7);
215
+ }
216
+ }
217
+
218
+ return dt => {
219
+ const t = getTime(),
220
+ camX = camera.position.x,
221
+ camZ = camera.position.z,
222
+ seen = Math.hypot(camX - cx, camZ - cz) < near;
223
+ if (!seen && !wasSeen) return;
224
+ wasSeen = seen;
225
+ if (heldBack.length && mounts.ready()) {
226
+ for (let i = 0; i < heldBack.length; i++)
227
+ if (heldBack[i].home === unseen) {
228
+ heldBack[i].home = undefined;
229
+ heldBack[i].out = -1;
230
+ }
231
+ heldBack.length = 0;
232
+ }
233
+ if (host.opponentsDirty) {
234
+ refreshTroopOpponents(troops);
235
+ host.opponentsDirty = false;
236
+ }
237
+ mounts?.begin();
238
+ herd?.begin();
239
+ train?.begin();
240
+ let clashX = 0,
241
+ clashZ = 0,
242
+ clashWeight = 0;
243
+ frameNearCamera = Math.hypot(camX - cx, camZ - cz) < dustViewDist + 140;
244
+ const shadowsOn = getShadowsEnabled(),
245
+ fxShare = getFxShare(),
246
+ crowdShare = getCrowdShare();
247
+
248
+ for (let ti = 0; ti < troops.length; ti++) {
249
+ const troop = troops[ti],
250
+ { spec, list } = troop;
251
+ let speedSum = 0,
252
+ movingCount = 0;
253
+ if (troop.busy) {
254
+ let busy = false;
255
+ const engageDepth = troop.engageDepth;
256
+ for (let i = 0; i < list.length; i++) {
257
+ const g = list[i];
258
+ if (stepTroopMember(g, t, dt, engageDepth, handleFallLand)) busy = true;
259
+ if (g.speed > 0.5 && !g.fall) {
260
+ speedSum += g.speed;
261
+ movingCount++;
262
+ }
263
+ }
264
+ troop.busy = busy;
265
+ if (troop.fighting) {
266
+ clashX += troop.cx * list.length;
267
+ clashZ += troop.cz * list.length;
268
+ clashWeight += list.length;
269
+ }
270
+ }
271
+ // Localized kicked-up battle dust under charging mounts, rushing infantry, and active scrimmage lines.
272
+ if (seen && fxShare > 0 && onDust && troop.visible && t >= troop.nextDustAt) {
273
+ const avgSpeed = movingCount > 0 ? speedSum / movingCount : 0;
274
+ const dusty = troop.fighting || (spec.mounted && avgSpeed > 2.4) || avgSpeed > 2.1;
275
+ if (dusty) {
276
+ troop.nextDustAt = t + (spec.mounted ? 0.14 : 0.18) + (ti % 3) * 0.03;
277
+ const span = troop.fighting ? Math.min(list.length, troop.wide * 2) : list.length;
278
+ if (span > 0) {
279
+ troop.dustCursor = (troop.dustCursor + 7) % span;
280
+ const g = list[troop.dustCursor];
281
+ if (g && !g.fall && g.home !== unseen) {
282
+ const dx = g.ax - camX,
283
+ dz = g.az - camZ;
284
+ if (dx * dx + dz * dz < dustViewDist2) {
285
+ const y = sp.ground(g.ax, g.az);
286
+ if (inView(g.ax, y + 1, g.az, 3, false, false)) {
287
+ const puffs = spec.mounted ? 4 : 3,
288
+ puffSize = spec.mounted ? 2.5 : troop.fighting ? 2.1 : 1.75,
289
+ puffSpeed = spec.mounted ? 1.85 : 1.35;
290
+ onDust(g.ax, y + 0.16, g.az, puffs, puffSize, puffSpeed);
291
+ }
292
+ }
293
+ }
294
+ }
295
+ }
296
+ }
297
+ // Procedural arrow/javelin volleys arcing between opposing ranks or skirmishers.
298
+ if (seen && volleys && troop.volleyTarget && troop.visible && t >= troop.nextVolleyAt) {
299
+ const dx = troop.cx - camX,
300
+ dz = troop.cz - camZ;
301
+ if (dx * dx + dz * dz < volleyViewDist2) {
302
+ volleys.launch(troop, troop.volleyTarget, sp, t, volleyRng);
303
+ }
304
+ troop.nextVolleyAt = t + (troop.ranged ? 1.35 : 1.9) + volleyRng() * 1.1;
305
+ }
306
+ if (!seen || !(spec.mounted || spec.beast)) continue;
307
+ const count = Math.ceil(list.length * crowdShare);
308
+ for (let i = 0; i < count; i++) {
309
+ const g = list[i];
310
+ if (g.home === unseen) continue;
311
+ if (g.ax !== g.hgx || g.az !== g.hgz) {
312
+ g.hgx = g.ax;
313
+ g.hgz = g.az;
314
+ g.hy = sp.ground(g.ax, g.az);
315
+ }
316
+ const y = g.hy,
317
+ casts = shadowsOn && shadowCasts(g.ax, y + 1, g.az, 2.6);
318
+ if (!inView(g.ax, y + 1, g.az, 2.6, false, casts)) continue;
319
+ if (spec.beast === 'cattle') herd?.beast(g.ax, y, g.az, g.yaw, g.speed, g.travel, g.c1, g.s, casts);
320
+ else if (spec.beast === 'wagon') {
321
+ const fx = Math.sin(g.yaw),
322
+ fz = Math.cos(g.yaw);
323
+ train?.wagon(g.ax, y, g.az, g.yaw, g.travel, casts);
324
+ for (let side = -1; side <= 1; side += 2) {
325
+ const ox = g.ax + fx * team.ahead + fz * team.apart * side,
326
+ oz = g.az + fz * team.ahead - fx * team.apart * side;
327
+ herd?.beast(ox, sp.ground(ox, oz), oz, g.yaw, g.speed, g.travel + side * 0.3, g.c1, 1, casts);
328
+ }
329
+ } else if (mounts) {
330
+ mounts.horse(g.ax, y, g.az, g.yaw, g.speed, g.travel + g.ph, g.coat, g.s, g.fall || 0, casts);
331
+ if (spec.mounted) {
332
+ g.lift = saddle * (1 - 0.8 * Math.abs(g.fall || 0)) + mounts.seat.rise;
333
+ g.rock = mounts.seat.lean;
334
+ }
335
+ if (spec.lance && !g.fall) mounts.lance(g.ax, y + g.lift, g.az, g.yaw, g.speed, casts);
336
+ }
337
+ }
338
+ }
339
+ if (seen && clashWeight > 0 && t >= nextClashFoleyAt) {
340
+ nextClashFoleyAt = t + clashFoleyInterval;
341
+ if (onClash) {
342
+ const mx = clashX / clashWeight,
343
+ mz = clashZ / clashWeight;
344
+ onClash(mx, sp.ground(mx, mz) + 1.4, mz, clamp(clashWeight / 160, 0.25, 1));
345
+ }
346
+ }
347
+ mounts?.end();
348
+ herd?.end();
349
+ train?.end();
350
+ if (seen) {
351
+ standards?.draw(sp);
352
+ volleys?.draw(t, sp);
353
+ }
354
+ };
355
+ }
356
+
357
+ function cue(setId, step, anchor) {
358
+ const host = hosts.get(setId);
359
+ if (host) applyTroopCue(host, step, anchor, getTime(), cueOptions);
360
+ }
361
+
362
+ function resetHost(setId) {
363
+ hosts.get(setId)?.reset();
364
+ }
365
+
366
+ function resetAll() {
367
+ for (const host of hosts.values()) host.reset();
368
+ }
369
+
370
+ const hostTroop = (setId, name) => hosts.get(setId)?.troops[name]?.list;
371
+ const getHost = setId => hosts.get(setId) ?? null;
372
+
373
+ return { raiseHost, cue, resetHost, resetAll, hostTroop, getHost };
374
+ }
@@ -0,0 +1,326 @@
1
+ /**
2
+ * Instanced troop mounts, baggage cattle herds, lances, and ox-drawn wagons: pre-baked stride
3
+ * moments cast on worker pools with a synchronous fallback, near/far LOD skin switching,
4
+ * shadowed/unshadowed instance pairs, and rider seat-bounce/lean readouts.
5
+ * @module
6
+ */
7
+
8
+ import * as THREE from 'three';
9
+ import { NO_ANIMAL_OPTIONS } from '../geometry/animal-options.js';
10
+ import { geometryView } from '../geometry/builder.js';
11
+ import { placeAt, placeBankedAt, placement } from '../geometry/placement.js';
12
+ import { sstep } from '../math/scalar.js';
13
+ import { troopArrays } from '../motion/animal-troop-cast.js';
14
+ import { riderLean } from '../motion/figure-mount.js';
15
+ import { poseBinder } from './crowd-herd.js';
16
+
17
+ /**
18
+ * Default horse pace tiers: `[maxSpeed, posedSpeed, moments]` in metres per second and frames per stride
19
+ * (walk, trot, and canter).
20
+ */
21
+ export const TROOP_HORSE_PACES = [
22
+ [2.4, 1.6, 8],
23
+ [5.2, 3.6, 8],
24
+ [Infinity, 7, 8],
25
+ ];
26
+
27
+ /** Default horse coat tint palette (scaled by 1.5 over the pale base coat). */
28
+ export const TROOP_HORSE_COATS = [0x6a4630, 0x2e2622, 0xa8937a, 0x7a4e2c, 0xc8c2b6, 0x4a3424, 0x8a6a48].map(hex =>
29
+ new THREE.Color(hex).multiplyScalar(1.5),
30
+ );
31
+
32
+ /** Default troop mount and draft beast casting specifications. */
33
+ export const TROOP_MOUNT_KINDS = {
34
+ horse: {
35
+ input: { beast: 'horse', paces: TROOP_HORSE_PACES.map(([, speed, moments]) => [speed, moments]) },
36
+ upTo: TROOP_HORSE_PACES.map(p => p[0]),
37
+ still: 0.3,
38
+ },
39
+ ox: {
40
+ input: { beast: 'ox', paces: [[1.1, 8]] },
41
+ upTo: [Infinity],
42
+ still: 0.15,
43
+ },
44
+ };
45
+
46
+ const DEFAULT_LANCE_LENGTH = 3.3; // metres
47
+ const DEFAULT_LANCE_GRIP = 1.15; // metres from butt to rider's hand
48
+ const DEFAULT_NEAR_BEAST = 45; // metres within which a beast uses its middle-detail skin
49
+ const DEFAULT_NEAR_MOST = 64; // maximum beasts drawn per stride moment in the middle-detail skin
50
+ const DEFAULT_CAST_COST = 4; // worker pool cost weight for a troop pose cast
51
+ const DEFAULT_LANCE_COLOR = new THREE.Color(0xc9b48a);
52
+ const _white = new THREE.Color(1, 1, 1);
53
+ const _place = placement();
54
+
55
+ function bindCast(arrays) {
56
+ const bind = poseBinder(arrays);
57
+ return {
58
+ stand: bind(arrays.stand),
59
+ standRise: arrays.standRise,
60
+ fallen: arrays.fallen && bind(arrays.fallen),
61
+ paces: arrays.paces.map(({ stride, frames, rises, pitches, phases }) => ({
62
+ stride,
63
+ frames: frames.map(bind),
64
+ rises,
65
+ pitches,
66
+ phases,
67
+ })),
68
+ };
69
+ }
70
+
71
+ function instancedMesh(geo, mat, n, group, casts = true) {
72
+ const mesh = new THREE.InstancedMesh(geometryView(geo), mat, n);
73
+ mesh.frustumCulled = false;
74
+ mesh.castShadow = casts;
75
+ mesh.receiveShadow = true;
76
+ mesh.count = 0;
77
+ mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
78
+ mesh.setColorAt(0, _white);
79
+ mesh.instanceColor.setUsage(THREE.DynamicDrawUsage);
80
+ group.add(mesh);
81
+ return mesh;
82
+ }
83
+
84
+ function flushMesh(mesh) {
85
+ const count = mesh.count;
86
+ mesh.visible = count > 0;
87
+ if (!count) return;
88
+ mesh.instanceMatrix.clearUpdateRanges();
89
+ mesh.instanceMatrix.addUpdateRange(0, count * 16);
90
+ mesh.instanceColor.clearUpdateRanges();
91
+ mesh.instanceColor.addUpdateRange(0, count * 3);
92
+ mesh.instanceMatrix.needsUpdate = true;
93
+ mesh.instanceColor.needsUpdate = true;
94
+ }
95
+
96
+ /**
97
+ * Creates a page-scoped troop beast, mount, lance, and wagon instancing factory with shared worker-backed
98
+ * pose casts and near/far LOD skin switching.
99
+ *
100
+ * @param {object} [options]
101
+ * @param {import('../geometry/animal-options.js').AnimalKitOptions} [options.animals] Animal kit builds and troop saddle/coat tuning.
102
+ * @param {() => boolean} [options.pooled] Returns true when a worker pool is active.
103
+ * @param {(job: string, input: object, transfer?: any[], signal?: any, cost?: number) => Promise<object>} [options.run] Worker pool runner.
104
+ * @param {string} [options.job='host poses'] Worker job name used to cast troop beast pose arrays.
105
+ * @param {{ position: { x: number, z: number } }} [options.camera] Active camera for near/far skin selection.
106
+ * @param {(mesh: THREE.Object3D) => Promise<void>} [options.warmShaders] Async shader warmer run before exposing a skin.
107
+ * @param {() => THREE.Material} [options.figureMaterial] Tinted material factory for horse and cattle instanced meshes.
108
+ * @param {() => THREE.Material} [options.woodMaterial] Tinted material factory for cavalry lance instanced meshes.
109
+ * @param {(group: THREE.Object3D, n: number, kind: string, rng: () => number) => object} [options.makeVehicles] Moving vehicle builder (`createVehicleTrains`).
110
+ * @param {THREE.Color[]} [options.coats] Horse coat tint palette indexed by `coat % coats.length`.
111
+ * @param {number} [options.nearDistance=45] Distance in metres within which beasts use the middle-detail skin.
112
+ * @param {number} [options.nearLimit=64] Maximum beasts per pose moment in the middle-detail skin.
113
+ * @param {number} [options.castCost=4] Worker-pool scheduling cost weight per beast skin cast.
114
+ * @param {number} [options.lanceLength=3.3] Cavalry lance shaft length in metres.
115
+ * @param {number} [options.lanceGrip=1.15] Height along the lance from butt to rider's hand in metres.
116
+ * @param {THREE.Color} [options.lanceColor] Ash shaft instance colour.
117
+ * @param {boolean} [options.lanceVertexColors=true] Attach white vertex colours to lance geometry before creating mesh views.
118
+ * @returns {{ makeMounts: Function, makeHerd: Function, makeWagons: Function, orderBeasts: Function }}
119
+ */
120
+ export function createTroopMounts({
121
+ animals = NO_ANIMAL_OPTIONS,
122
+ pooled = () => false,
123
+ run = null,
124
+ job = 'host poses',
125
+ camera = { position: { x: 0, z: 0 } },
126
+ warmShaders = () => Promise.resolve(),
127
+ figureMaterial = () => new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.9 }),
128
+ woodMaterial = () => new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.9 }),
129
+ makeVehicles = null,
130
+ coats = TROOP_HORSE_COATS,
131
+ nearDistance = DEFAULT_NEAR_BEAST,
132
+ nearLimit = DEFAULT_NEAR_MOST,
133
+ castCost = DEFAULT_CAST_COST,
134
+ lanceLength = DEFAULT_LANCE_LENGTH,
135
+ lanceGrip = DEFAULT_LANCE_GRIP,
136
+ lanceColor = DEFAULT_LANCE_COLOR,
137
+ lanceVertexColors = true,
138
+ } = {}) {
139
+ const horseKind = TROOP_MOUNT_KINDS.horse;
140
+ const oxKind = TROOP_MOUNT_KINDS.ox;
141
+ const casts = new Map();
142
+ const nearDist2 = nearDistance * nearDistance;
143
+
144
+ function castOf(kind, q, now = false) {
145
+ const key = kind.input.beast + q;
146
+ let cast = casts.get(key);
147
+ if (!cast) {
148
+ cast = { pending: pooled() && !!run, poses: null, done: null };
149
+ casts.set(key, cast);
150
+ cast.done = cast.pending
151
+ ? run(job, { ...kind.input, q }, [], null, castCost)
152
+ .then(arrays => (cast.poses ??= bindCast(arrays)))
153
+ .catch(() => {})
154
+ .finally(() => (cast.pending = false))
155
+ : Promise.resolve();
156
+ }
157
+ if (!cast.poses && now && !cast.pending) cast.poses = bindCast(troopArrays({ ...kind.input, q }, animals));
158
+ return cast.poses;
159
+ }
160
+
161
+ function orderBeasts() {
162
+ castOf(horseKind, 1);
163
+ castOf(oxKind, 1);
164
+ castOf(horseKind, 0);
165
+ castOf(oxKind, 0);
166
+ return Promise.all([casts.get('horse0').done, casts.get('ox0').done]);
167
+ }
168
+
169
+ function beastsOf(kind, group, n, name) {
170
+ const hide = figureMaterial(),
171
+ skins = [undefined, undefined], // far (0) and middle (1): null while warming
172
+ all = [],
173
+ back = { rise: 0, pitch: 0, ph: 0 };
174
+ castOf(kind, 1);
175
+ const skin = q => {
176
+ if (skins[q] !== undefined) return skins[q];
177
+ const poses = castOf(kind, q, q === 0);
178
+ if (!poses) return null;
179
+ const cap = q ? Math.min(n, nearLimit) : n;
180
+ const make = (geo, castsShadow) => {
181
+ const mesh = instancedMesh(geo, hide, cap, group, castsShadow);
182
+ mesh.name = castsShadow ? name : name + '-unshadowed';
183
+ mesh.visible = false;
184
+ all.push(mesh);
185
+ return mesh;
186
+ };
187
+ const draw = geo => [make(geo, false), make(geo, true)];
188
+ const set = {
189
+ stand: draw(poses.stand),
190
+ standRise: poses.standRise,
191
+ fallen: poses.fallen && draw(poses.fallen),
192
+ paces: poses.paces.map(pace => ({ ...pace, moments: pace.frames.map(draw) })),
193
+ };
194
+ skins[q] = null;
195
+ warmShaders(set.stand[1]).then(() => (skins[q] = set));
196
+ return null;
197
+ };
198
+ const moment = (set, speed, travel, size, down) => {
199
+ back.pitch = back.ph = 0;
200
+ back.rise = down ? 0 : set.standRise;
201
+ if (down) return set.fallen;
202
+ if (speed <= kind.still) return set.stand;
203
+ const pace = set.paces[kind.upTo.findIndex(top => speed < top)],
204
+ strides = travel / (pace.stride * size),
205
+ k = Math.floor((strides - Math.floor(strides)) * pace.moments.length);
206
+ back.rise = pace.rises[k];
207
+ back.pitch = pace.pitches[k];
208
+ back.ph = pace.phases[k];
209
+ return pace.moments[k];
210
+ };
211
+ skin(0);
212
+ return {
213
+ back,
214
+ ready: () => !!skin(0),
215
+ begin() {
216
+ for (let i = 0; i < all.length; i++) all[i].count = 0;
217
+ },
218
+ meshFor(x, z, speed, travel, size, down, castsShadow = true) {
219
+ const dx = x - camera.position.x,
220
+ dz = z - camera.position.z,
221
+ near = dx * dx + dz * dz < nearDist2 && skin(1);
222
+ if (near) {
223
+ const pair = moment(near, speed, travel, size, down),
224
+ mesh = pair?.[castsShadow ? 1 : 0];
225
+ if (mesh && mesh.count < mesh.instanceMatrix.count) return mesh;
226
+ }
227
+ const far = skin(0);
228
+ return far ? moment(far, speed, travel, size, down)?.[castsShadow ? 1 : 0] : null;
229
+ },
230
+ end() {
231
+ for (let i = 0; i < all.length; i++) flushMesh(all[i]);
232
+ },
233
+ };
234
+ }
235
+
236
+ function makeMounts(group, n, lances = 0) {
237
+ const horses = beastsOf(horseKind, group, n, 'host-horses'),
238
+ shaft = new THREE.CylinderGeometry(0.014, 0.02, lanceLength, 5).translate(0, lanceLength / 2 - lanceGrip, 0),
239
+ white = new Float32Array(shaft.attributes.position.count * 3).fill(1);
240
+ if (lanceVertexColors) shaft.setAttribute('color', new THREE.BufferAttribute(white, 3));
241
+ const lanceMat = woodMaterial(),
242
+ lance = lances ? [instancedMesh(shaft, lanceMat, lances, group, false), instancedMesh(shaft, lanceMat, lances, group, true)] : null;
243
+ if (!lanceVertexColors) shaft.setAttribute('color', new THREE.BufferAttribute(white, 3));
244
+ const seat = { rise: 0, lean: 0 },
245
+ back = horses.back;
246
+ return {
247
+ seat,
248
+ ready: horses.ready,
249
+ begin() {
250
+ horses.begin();
251
+ if (lance) {
252
+ lance[0].count = 0;
253
+ lance[1].count = 0;
254
+ }
255
+ },
256
+ horse(x, y, z, yaw, speed, travel, coat, size, down, castsShadow = true) {
257
+ const mesh = horses.meshFor(x, z, speed, travel, size, down, castsShadow);
258
+ if (!mesh) return;
259
+ _place.x = x;
260
+ _place.y = y + 0.25 * Math.abs(down);
261
+ _place.z = z;
262
+ _place.s = size;
263
+ _place.ry = yaw;
264
+ _place.rx = 0;
265
+ if (down) {
266
+ _place.rz = 1.45 * down;
267
+ placeBankedAt(mesh.instanceMatrix.array, mesh.count * 16, _place);
268
+ } else {
269
+ placeAt(mesh.instanceMatrix.array, mesh.count * 16, _place);
270
+ }
271
+ mesh.setColorAt(mesh.count++, coats[coat % coats.length]);
272
+ seat.rise = back.rise * size;
273
+ seat.lean = speed > horseKind.still && !down ? riderLean(back.ph, back.pitch, speed) : 0;
274
+ },
275
+ lance(x, y, z, yaw, speed, castsShadow = true) {
276
+ const mesh = lance[castsShadow ? 1 : 0],
277
+ tilt = 0.1 + 1.32 * sstep(3.6, 6.2, speed),
278
+ c = Math.cos(yaw),
279
+ s = Math.sin(yaw);
280
+ _place.x = x + 0.34 * c + 0.2 * s;
281
+ _place.y = y + 0.62;
282
+ _place.z = z - 0.34 * s + 0.2 * c;
283
+ _place.s = 1;
284
+ _place.ry = yaw;
285
+ _place.rx = tilt;
286
+ placeAt(mesh.instanceMatrix.array, mesh.count * 16, _place);
287
+ mesh.setColorAt(mesh.count++, lanceColor);
288
+ },
289
+ end() {
290
+ horses.end();
291
+ if (lance) {
292
+ flushMesh(lance[0]);
293
+ flushMesh(lance[1]);
294
+ }
295
+ },
296
+ };
297
+ }
298
+
299
+ function makeHerd(group, n) {
300
+ const oxen = beastsOf(oxKind, group, n, 'host-cattle');
301
+ return {
302
+ begin: oxen.begin,
303
+ beast(x, y, z, yaw, speed, travel, tint, size, castsShadow = true) {
304
+ const mesh = oxen.meshFor(x, z, speed, travel, size, 0, castsShadow);
305
+ if (!mesh) return;
306
+ _place.x = x;
307
+ _place.y = y;
308
+ _place.z = z;
309
+ _place.s = size;
310
+ _place.ry = yaw;
311
+ _place.rx = 0;
312
+ placeAt(mesh.instanceMatrix.array, mesh.count * 16, _place);
313
+ mesh.setColorAt(mesh.count++, tint);
314
+ },
315
+ end: oxen.end,
316
+ };
317
+ }
318
+
319
+ function makeWagons(group, n, rng) {
320
+ if (!makeVehicles) throw new Error('createTroopMounts: makeVehicles is required for makeWagons');
321
+ const wagons = makeVehicles(group, n, 'wagon', rng);
322
+ return { begin: wagons.begin, wagon: wagons.vehicle, end: wagons.end };
323
+ }
324
+
325
+ return { makeHerd, makeMounts, makeWagons, orderBeasts };
326
+ }