roamwright 0.61.26 → 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,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
+ }
@@ -0,0 +1,259 @@
1
+ /**
2
+ * Carried troop standards: instanced pole and flag meshes built per faction/body, tracked into
3
+ * the standard-bearer's posed right fist while standing or riding, and toppled flat onto sloped
4
+ * terrain when the bearer falls.
5
+ * @module
6
+ */
7
+
8
+ import * as THREE from 'three';
9
+ import { placement } from '../geometry/placement.js';
10
+ import { C } from '../geometry/primitives.js';
11
+ import { mulberry32 } from '../math/random.js';
12
+ import { lerp } from '../math/scalar.js';
13
+ import { BEARER_POLE, crowdHold, holdAt } from '../motion/crowd-hold.js';
14
+
15
+ /** Default carried standard dimensions in metres: pole height `h`, flag length `L`, and flag depth `hh`. */
16
+ export const STANDARD_CARRIED = { h: 4.4, L: 1.7, hh: 1.0 };
17
+
18
+ /** Metres the pole extends below the standard's origin foot (`propStandard`). */
19
+ export const STANDARD_BELOW = 0.3;
20
+
21
+ /** Metres from the pole's butt up to the bearer's fist unless ground clearance intervenes. */
22
+ export const STANDARD_GRIP_UP = 1.0;
23
+
24
+ /** Minimum metres above ground for the butt of a pole held low (seated or kneeling bearer). */
25
+ export const STANDARD_CLEAR = 0.02;
26
+
27
+ /** Residual flag fold scale when a dropped standard lies flat on the ground. */
28
+ export const STANDARD_LAID_FLAT = 0.3;
29
+
30
+ const _m = new THREE.Matrix4();
31
+ const _place = placement();
32
+
33
+ function showInstanced(mesh) {
34
+ mesh.visible = mesh.count > 0;
35
+ if (mesh.count) mesh.instanceMatrix.needsUpdate = true;
36
+ }
37
+
38
+ /**
39
+ * Computes the column-major 4x4 transform matrix of an upright standard held in a bearer's fist.
40
+ * Aligns the pole along the grip axis `(h.ax, h.ay, h.az)` through `(h.x, h.y, h.z)` with its
41
+ * flag trailing behind the bearer's facing `yaw`.
42
+ *
43
+ * @param {Float32Array|number[]} e Destination 16-element column-major matrix array.
44
+ * @param {{ x: number, y: number, z: number, ax: number, ay: number, az: number, floor: number }} h Bearer hold record.
45
+ * @param {number} yaw Bearer facing angle in radians.
46
+ * @param {boolean} mounted True when the bearer is mounted on a horse (no ground clamp on pole butt).
47
+ * @param {object} [options]
48
+ * @param {number} [options.below=0.3] Pole length below standard foot (metres).
49
+ * @param {number} [options.gripUp=1.0] Distance from pole butt to fist (metres).
50
+ * @param {number} [options.clear=0.02] Minimum clearance above `h.floor` when on foot (metres).
51
+ * @returns {Float32Array|number[]} The populated `e` array.
52
+ */
53
+ export function poleInFistMatrix(e, h, yaw, mounted, { below = STANDARD_BELOW, gripUp = STANDARD_GRIP_UP, clear = STANDARD_CLEAR } = {}) {
54
+ const ux = h.ax,
55
+ uy = h.ay,
56
+ uz = h.az;
57
+ let gripBelow = gripUp;
58
+ if (!mounted && uy > 0.5) gripBelow = Math.min(gripBelow, Math.max(0, (h.y - h.floor - clear) / uy));
59
+ const foot = below - gripBelow;
60
+ // Behind the bearer, projected perpendicular to the pole axis so the flag trails rearward.
61
+ let bx = -Math.sin(yaw),
62
+ bz = -Math.cos(yaw);
63
+ const along = bx * ux + bz * uz;
64
+ let px = bx - ux * along,
65
+ py = -uy * along,
66
+ pz = bz - uz * along;
67
+ const n = Math.sqrt(px * px + py * py + pz * pz) || 1;
68
+ px /= n;
69
+ py /= n;
70
+ pz /= n;
71
+ bx = py * uz - pz * uy;
72
+ bz = px * uy - py * ux;
73
+ const by = pz * ux - px * uz;
74
+ e[0] = px;
75
+ e[1] = py;
76
+ e[2] = pz;
77
+ e[3] = 0;
78
+ e[4] = ux;
79
+ e[5] = uy;
80
+ e[6] = uz;
81
+ e[7] = 0;
82
+ e[8] = bx;
83
+ e[9] = by;
84
+ e[10] = bz;
85
+ e[11] = 0;
86
+ e[12] = h.x + ux * foot;
87
+ e[13] = h.y + uy * foot;
88
+ e[14] = h.z + uz * foot;
89
+ e[15] = 1;
90
+ return e;
91
+ }
92
+
93
+ /**
94
+ * Computes the column-major 4x4 transform matrix of a standard toppling to the bearer's right and
95
+ * settling along sloped ground as the bearer falls (`fall` in `(0, 1]`).
96
+ *
97
+ * @param {Float32Array|number[]} e Destination 16-element column-major matrix array.
98
+ * @param {{ x: number, y: number, z: number }} h Upright bearer grip position (`holdAt`).
99
+ * @param {{ dir: number, mounted?: boolean }} g Bearer crowd figure record.
100
+ * @param {(x: number, z: number) => number} groundAt Ground height sampler in metres.
101
+ * @param {number} fall Fall progress in `[0, 1]`.
102
+ * @param {object} [options]
103
+ * @param {{ h: number }} [options.carried] Carried standard dimensions (`h` pole height above foot).
104
+ * @param {number} [options.below=0.3] Pole length below standard foot (metres).
105
+ * @param {number} [options.gripUp=1.0] Distance from pole butt to fist while held (metres).
106
+ * @param {number} [options.clear=0.02] Ground clearance of butt while held on foot (metres).
107
+ * @param {number} [options.laidFlat=0.3] Residual flag fold scale once lying flat.
108
+ * @returns {Float32Array|number[]} The populated `e` array.
109
+ */
110
+ export function poleDroppedMatrix(
111
+ e,
112
+ h,
113
+ g,
114
+ groundAt,
115
+ fall,
116
+ {
117
+ carried = STANDARD_CARRIED,
118
+ below = STANDARD_BELOW,
119
+ gripUp = STANDARD_GRIP_UP,
120
+ clear = STANDARD_CLEAR,
121
+ laidFlat = STANDARD_LAID_FLAT,
122
+ } = {},
123
+ ) {
124
+ const c = Math.cos(g.dir),
125
+ d = Math.sin(g.dir),
126
+ long = carried.h + below,
127
+ floor = groundAt(h.x, h.z),
128
+ middle = groundAt(h.x + (c * long) / 2, h.z - (d * long) / 2),
129
+ end = groundAt(h.x + c * long, h.z - d * long),
130
+ over = fall * (Math.PI / 2 - Math.atan2(end - floor, long)),
131
+ s = Math.sin(over),
132
+ k = Math.cos(over),
133
+ flat = lerp(1, laidFlat, fall),
134
+ held = g.mounted ? h.y - gripUp : Math.max(floor + clear, h.y - gripUp),
135
+ butt = lerp(held, Math.max(floor, middle - (end - floor) / 2) + BEARER_POLE, fall);
136
+ // Kit +x points behind the bearer, +y along the pole toppling right, and +z flattens as it lands.
137
+ e[0] = -d;
138
+ e[1] = 0;
139
+ e[2] = -c;
140
+ e[3] = 0;
141
+ e[4] = c * s;
142
+ e[5] = k;
143
+ e[6] = -d * s;
144
+ e[7] = 0;
145
+ e[8] = c * k * flat;
146
+ e[9] = -s * flat;
147
+ e[10] = -d * k * flat;
148
+ e[11] = 0;
149
+ e[12] = h.x + e[4] * below;
150
+ e[13] = butt + e[5] * below;
151
+ e[14] = h.z + e[6] * below;
152
+ e[15] = 1;
153
+ return e;
154
+ }
155
+
156
+ /**
157
+ * Creates a carried troop-standards factory bound to a world's house kit, instanced kit meshes,
158
+ * standard prop builder, frame counter, and faction standard colour lookup.
159
+ *
160
+ * @param {object} config
161
+ * @param {() => object} config.kitNew Creates a new house-kit builder container (`createHouseKit`).
162
+ * @param {Function} config.kitAt Places a prop builder into a house-kit container at a local transform.
163
+ * @param {(kit: object, count: number, parent: THREE.Object3D) => THREE.InstancedMesh[]} config.kitInstanced Builds instanced meshes from a kit (`createHouseKitMeshes`).
164
+ * @param {Function} config.propStandard Standard prop geometry builder (`createProps`).
165
+ * @param {() => number} [config.getFrame] Returns the current render frame index for comparing against `held.frame`.
166
+ * @param {(bodyId: string|undefined, troop: object) => [number, number]|null|undefined} [config.standardOf] Resolves `[fieldHex, edgeHex]` for a troop; defaults to `troop.spec.standard`.
167
+ * @param {{ h: number, L: number, hh: number }} [config.carried] Carried standard pole and flag dimensions (metres).
168
+ * @param {number} [config.below=0.3] Pole length below standard foot (metres).
169
+ * @param {number} [config.gripUp=1.0] Distance from pole butt to fist (metres).
170
+ * @param {number} [config.clear=0.02] Ground clearance of butt when held low (metres).
171
+ * @param {number} [config.laidFlat=0.3] Residual flag fold scale when dropped flat.
172
+ * @param {string} [config.meshName='host-standards'] Name assigned to generated standard meshes.
173
+ * @returns {{ makeStandards: (group: THREE.Object3D, troops: object[]) => { draw: (spaceOrGround: object|Function) => void, bearers: object[], meshes: THREE.InstancedMesh[] } }}
174
+ */
175
+ export function createTroopStandards({
176
+ kitNew,
177
+ kitAt,
178
+ kitInstanced,
179
+ propStandard,
180
+ getFrame = () => 0,
181
+ standardOf = (_bodyId, troop) => troop?.spec?.standard || null,
182
+ carried = STANDARD_CARRIED,
183
+ below = STANDARD_BELOW,
184
+ gripUp = STANDARD_GRIP_UP,
185
+ clear = STANDARD_CLEAR,
186
+ laidFlat = STANDARD_LAID_FLAT,
187
+ meshName = 'host-standards',
188
+ }) {
189
+ const poleOptions = { carried, below, gripUp, clear, laidFlat };
190
+
191
+ function makeStandards(group, troops) {
192
+ const kinds = new Map(),
193
+ all = [],
194
+ bearers = [];
195
+ for (const troop of troops) {
196
+ const id = troop.spec.body,
197
+ flag = standardOf(id, troop);
198
+ if (!flag || troop.spec.beast) continue;
199
+ const key = id ?? `${flag[0]}:${flag[1]}`;
200
+ if (!kinds.has(key)) {
201
+ const kit = kitNew(),
202
+ n = id
203
+ ? troops.filter(t => t.spec.body === id).length
204
+ : troops.filter(t => {
205
+ const f = standardOf(t.spec.body, t);
206
+ return !t.spec.beast && f && (t.spec.body ?? `${f[0]}:${f[1]}`) === key;
207
+ }).length;
208
+ kitAt(
209
+ kit,
210
+ 0,
211
+ 0,
212
+ 0,
213
+ 0,
214
+ false,
215
+ (B, R) => propStandard(B, R, carried.h, carried.L, carried.hh, C(flag[0]), C(flag[1]), 2 * BEARER_POLE),
216
+ mulberry32(n),
217
+ );
218
+ const meshes = kitInstanced(kit, n, group);
219
+ for (const mesh of meshes) mesh.name = meshName;
220
+ kinds.set(key, meshes);
221
+ all.push(...meshes);
222
+ }
223
+ const wide = troop.spec.wide || Math.ceil(Math.sqrt(troop.spec.n * 2)),
224
+ g = troop.list[Math.min(troop.list.length - 1, (wide - 1) >> 1)];
225
+ g.held = crowdHold();
226
+ bearers.push({ meshes: kinds.get(key), g });
227
+ }
228
+ return {
229
+ bearers,
230
+ meshes: all,
231
+ draw(spaceOrGround) {
232
+ const groundAt = typeof spaceOrGround === 'function' ? spaceOrGround : spaceOrGround.ground;
233
+ const frame = getFrame();
234
+ for (let i = 0; i < all.length; i++) all[i].count = 0;
235
+ for (let b = 0; b < bearers.length; b++) {
236
+ const { meshes, g } = bearers[b],
237
+ h = g.held;
238
+ if (g.home === -1) continue;
239
+ const fall = Math.abs(g.fall || 0);
240
+ if (fall || h.frame !== frame) {
241
+ _place.x = g.ax;
242
+ _place.z = g.az;
243
+ _place.y = groundAt(g.ax, g.az) + g.lift;
244
+ _place.s = g.s;
245
+ _place.ry = g.dir;
246
+ _place.rx = 0;
247
+ holdAt(g, _place, false);
248
+ }
249
+ if (fall) poleDroppedMatrix(_m.elements, h, g, groundAt, fall, poleOptions);
250
+ else poleInFistMatrix(_m.elements, h, g.dir, g.mounted, poleOptions);
251
+ for (let i = 0; i < meshes.length; i++) meshes[i].setMatrixAt(meshes[i].count++, _m);
252
+ }
253
+ for (let i = 0; i < all.length; i++) showInstanced(all[i]);
254
+ },
255
+ };
256
+ }
257
+
258
+ return { makeStandards };
259
+ }