@adatechnology/game-render-three 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -19,6 +19,14 @@ numbers fixed after boot.
19
19
  - `createFog(THREE, scene, { stable: true })`: `clear()` leaves a neutral linear fog (near 6.0e4, far 6.4e4) instead of `null`.
20
20
  - `createGeometryPool()` / `createMaterialPool()`: keys, use counts, `retain`/`register`, `own` for per-frame materials, `trim` at load
21
21
  points, and a development warning when a pooled resource is disposed directly.
22
+ - `createStaticBatcher(THREE, root, options)`: draws the still meshes of an object as one batch per material. The merge copies typed arrays
23
+ (positions and normals through the mesh matrix, the rest as stored) and allocates nothing per mesh frame.
24
+ - `createStaticBatchQueue({ id })` (spec 010): one `DeferredQueue` per **owner**, not per batcher, rotating between the batchers that join it with
25
+ `createStaticBatcher(THREE, root, { queue })`. One unit is one chunk (`maxVertices`); no chunk is cut by vertex. The owner registers
26
+ `queue.deferredQueue()` with the frame budget using its id from `DEFERRED_QUEUE_ID` and the options from `DEFERRED_PRIORITY`
27
+ (`budget.register(queue.deferredQueue(), DEFERRED_PRIORITY[id])`). Not registered, each batcher drains the queue in its own `update` with
28
+ `budgetMs` (default all at once, through `drainDetached`). Only the merge waits: `update()` still releases a changed mesh every frame. A batcher
29
+ leaves the queue in `dispose()`. A batcher given `queue` merges its first chunks in `update()`, not in the call.
22
30
 
23
31
  ```ts
24
32
  import * as THREE from 'three'
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import * as three from 'three';
2
2
  import { Group, Object3D, HemisphereLight, Scene, Camera, WebGLRenderTarget, Fog, FogExp2, Material, Texture, BufferGeometry, Mesh } from 'three';
3
+ import { DeferredQueue } from '@adatechnology/game-contracts';
3
4
 
4
5
  /** The one name of the three.js namespace in the kit. Packages narrow it with Pick<ThreeLib, ...>. */
5
6
  type ThreeLib = typeof three;
@@ -417,11 +418,42 @@ declare function createFramePacer(context: FramePacerContext | null, options?: F
417
418
 
418
419
  /** The layer a batched mesh is moved to: no camera draws it, a raycaster that enables every layer still finds it. */
419
420
  declare const BATCHED_LAYER = 30;
421
+ /** What a batcher gives its queue: the chunks still to merge. One unit is one chunk (at most `maxVertices` vertices). */
422
+ type StaticBatchWork = {
423
+ pendingUnits(): number;
424
+ /** Merges the next chunk. */
425
+ runUnit(): void;
426
+ /** Merges every chunk left. */
427
+ finishAll(): void;
428
+ };
429
+ type StaticBatchQueue = {
430
+ /** The queue for a frame budget (`budget.register`); asking for it changes nothing. Its `id` is the one given to `createStaticBatchQueue`. */
431
+ deferredQueue(): DeferredQueue;
432
+ /** A batcher joins (`createStaticBatcher` does it for the `queue` option); returns the function that takes it out. */
433
+ join(work: StaticBatchWork): () => void;
434
+ /** Whether a budget registered the queue: from then on the batchers leave their chunks to it instead of merging in `update`. */
435
+ isAttached(): boolean;
436
+ };
437
+ type StaticBatchQueueOptions = {
438
+ /** Default `DEFERRED_QUEUE_ID.STATIC_BATCH`; an owner passes its own id from `DEFERRED_QUEUE_ID`. */
439
+ readonly id?: string;
440
+ };
441
+ /**
442
+ * One queue for every batcher of an owner (the room, the animals area, one house), run round robin over the batchers with chunks waiting so the
443
+ * first one does not take the whole budget. Until a budget attaches it, each batcher keeps merging in its own `update`, as before.
444
+ */
445
+ declare function createStaticBatchQueue({ id }?: StaticBatchQueueOptions): StaticBatchQueue;
420
446
  type StaticBatcherOptions = {
421
447
  /** Which meshes may be batched (default every shown mesh with one material and no instancing, skinning or morphing). */
422
448
  readonly include?: (mesh: Mesh) => boolean;
423
- /** Milliseconds of merging per `update` (default all at once, in the call): batches are made a material at a time over the next frames. */
449
+ /** Milliseconds of merging per `update` (default all at once, in the call): batches are made a chunk at a time over the next frames. Used only while no budget has registered `queue`. */
424
450
  readonly budgetMs?: number;
451
+ /**
452
+ * The owner's queue: the chunks are merged by it, within the frame budget it is registered with, instead of in `update` (see `createStaticBatchQueue`).
453
+ * Not registered with any budget, the batcher drains it in `update` with `budgetMs` (default all at once), so nothing becomes asynchronous by a host's absence;
454
+ * the first merge is then in the first `update`, not in the call.
455
+ */
456
+ readonly queue?: StaticBatchQueue;
425
457
  /**
426
458
  * The meshes move on their own (a body posed bone by bone): each batch is skinned to its meshes, so a mesh carries its part of the batch
427
459
  * wherever it goes, and only a new geometry, material, dent or hiding gives it its own draw back.
@@ -434,6 +466,18 @@ type StaticBatcherOptions = {
434
466
  readonly materialKey?: (material: Material) => string;
435
467
  /** Called with each batch as it is made and the meshes it draws (to mark where it comes from, for one). */
436
468
  readonly onBatch?: (batch: Mesh, meshes: readonly Mesh[]) => void;
469
+ /**
470
+ * Batches only the shadow: the meshes keep drawing on their own in the camera's pass and stop casting while batched, and each batch is drawn
471
+ * only into the shadow maps (positions only, one batch per side the depth pass draws, whatever the material). A mesh whose shadow needs its
472
+ * own material (a cut-out map, clipping planes, displacement, a custom depth material, wireframe) is left casting on its own. A mesh that
473
+ * changes casts its own shadow again, of its new shape, the frame it changes.
474
+ */
475
+ readonly shadowOnly?: boolean;
476
+ /**
477
+ * The most vertices one batch holds (default unbounded; 65535 with `shadowOnly`): a larger group is split, in the order of the tree, so each
478
+ * batch is merged within one `update` of a budget and is culled by the shadow camera by its own part of the object.
479
+ */
480
+ readonly maxVertices?: number;
437
481
  };
438
482
  type StaticBatcherStats = {
439
483
  readonly batches: number;
@@ -459,4 +503,4 @@ type StaticBatcher = {
459
503
  */
460
504
  declare function createStaticBatcher(THREE: ThreeLib, root: Object3D, options?: StaticBatcherOptions): StaticBatcher;
461
505
 
462
- export { BATCHED_LAYER, type EffectWarmup, type FogController, type FogOptions, type FogState, type FramePacer, type FramePacerContext, type FramePacerOptions, type GeometryPool, LIGHT_PRIORITY, type LightBudget, type LightBudgetOptions, type LightBudgetStats, type LightCheck, type LightHandle, type LightKind, type LightLease, type LightPatch, type LightRequest, type LightSource, type LinearRgb, type MaterialAnchors, type MaterialPool, type MaterialPoolOptions, NEUTRAL_FOG_FAR, NEUTRAL_FOG_NEAR, type ProgramWarmup, type PropertiesReader, type RenderPools, type RendererState, type SealOptions, type SourceHandle, type StaticBatcher, type StaticBatcherOptions, type StaticBatcherStats, type ThreeForLights, type ThreeLib, type WarmupContext, type WarmupOptions, type WarmupProbe, type WarmupRenderer, type WarmupReport, createFog, createFramePacer, createGeometryPool, createLightBudget, createMaterialAnchors, createMaterialPool, createProgramWarmup, createStaticBatcher, geometryKey, isLightBudget, isNeutralFog, isRenderPools, materialKey, programKeysOf, shadowCasterProbes, spriteProbes };
506
+ export { BATCHED_LAYER, type EffectWarmup, type FogController, type FogOptions, type FogState, type FramePacer, type FramePacerContext, type FramePacerOptions, type GeometryPool, LIGHT_PRIORITY, type LightBudget, type LightBudgetOptions, type LightBudgetStats, type LightCheck, type LightHandle, type LightKind, type LightLease, type LightPatch, type LightRequest, type LightSource, type LinearRgb, type MaterialAnchors, type MaterialPool, type MaterialPoolOptions, NEUTRAL_FOG_FAR, NEUTRAL_FOG_NEAR, type ProgramWarmup, type PropertiesReader, type RenderPools, type RendererState, type SealOptions, type SourceHandle, type StaticBatchQueue, type StaticBatchQueueOptions, type StaticBatchWork, type StaticBatcher, type StaticBatcherOptions, type StaticBatcherStats, type ThreeForLights, type ThreeLib, type WarmupContext, type WarmupOptions, type WarmupProbe, type WarmupRenderer, type WarmupReport, createFog, createFramePacer, createGeometryPool, createLightBudget, createMaterialAnchors, createMaterialPool, createProgramWarmup, createStaticBatchQueue, createStaticBatcher, geometryKey, isLightBudget, isNeutralFog, isRenderPools, materialKey, programKeysOf, shadowCasterProbes, spriteProbes };
package/dist/index.js CHANGED
@@ -1156,8 +1156,57 @@ function createFramePacer(context, options = {}) {
1156
1156
  }
1157
1157
 
1158
1158
  // src/static-batcher.ts
1159
+ import { DEFERRED_QUEUE_ID, drainDetached } from "@adatechnology/game-contracts";
1159
1160
  var BATCHED_LAYER = 30;
1160
1161
  var MATRIX_EPSILON = 1e-6;
1162
+ function createStaticBatchQueue({ id = DEFERRED_QUEUE_ID.STATIC_BATCH } = {}) {
1163
+ const members = [];
1164
+ let cursor = 0;
1165
+ let attached = false;
1166
+ const deferred = {
1167
+ id,
1168
+ pending() {
1169
+ let units = 0;
1170
+ for (const work of members) units += work.pendingUnits();
1171
+ return units;
1172
+ },
1173
+ run(deadline, clock) {
1174
+ let ran = 0;
1175
+ let skipped = 0;
1176
+ while (members.length > 0 && skipped < members.length) {
1177
+ if (ran > 0 && clock() >= deadline) break;
1178
+ const work = members[cursor % members.length];
1179
+ cursor = (cursor + 1) % members.length;
1180
+ if (work.pendingUnits() > 0) {
1181
+ work.runUnit();
1182
+ ran++;
1183
+ skipped = 0;
1184
+ } else skipped++;
1185
+ }
1186
+ return ran;
1187
+ },
1188
+ flush() {
1189
+ for (const work of [...members]) work.finishAll();
1190
+ },
1191
+ attach() {
1192
+ attached = true;
1193
+ },
1194
+ detach() {
1195
+ attached = false;
1196
+ }
1197
+ };
1198
+ return {
1199
+ deferredQueue: () => deferred,
1200
+ isAttached: () => attached,
1201
+ join(work) {
1202
+ members.push(work);
1203
+ return () => {
1204
+ const at = members.indexOf(work);
1205
+ if (at >= 0) members.splice(at, 1);
1206
+ };
1207
+ }
1208
+ };
1209
+ }
1161
1210
  var ATTRIBUTES = ["position", "normal", "uv", "color"];
1162
1211
  var isShown = (object, root) => {
1163
1212
  for (let node = object; node; node = node.parent) {
@@ -1172,43 +1221,91 @@ var isBatchable = (mesh) => {
1172
1221
  const geometry = mesh.geometry;
1173
1222
  return geometry.attributes.position !== void 0 && Object.keys(geometry.morphAttributes).length === 0;
1174
1223
  };
1175
- var signatureOf = (mesh, materialKey2) => {
1224
+ var signatureOf = (mesh, materialKey2, shadowOnly) => {
1225
+ if (shadowOnly) return shadowSideKey(mesh.material);
1176
1226
  const { attributes } = mesh.geometry;
1177
1227
  const present = ATTRIBUTES.filter((name) => attributes[name] !== void 0).map((name) => `${name}${attributes[name].itemSize}`);
1178
1228
  return `${materialKey2(mesh.material)}|${present.join(",")}|${mesh.castShadow ? 1 : 0}${mesh.receiveShadow ? 1 : 0}`;
1179
1229
  };
1180
1230
  var uuidOf = (material) => material.uuid;
1181
- var sameMatrix = (a, b) => a.elements.every((value, index) => Math.abs(value - b.elements[index]) < MATRIX_EPSILON);
1231
+ var castsPlainShadow = (mesh) => {
1232
+ const material = mesh.material;
1233
+ const custom = mesh;
1234
+ if (!mesh.castShadow || !material.visible || custom.customDepthMaterial || custom.customDistanceMaterial) return false;
1235
+ if (material.wireframe === true || (material.clippingPlanes?.length ?? 0) > 0) return false;
1236
+ if (material.displacementMap && material.displacementScale !== 0) return false;
1237
+ return !(material.alphaTest > 0 && (material.map || material.alphaMap));
1238
+ };
1239
+ var shadowSideKey = (material) => `${material.side}|${material.shadowSide ?? ""}`;
1240
+ var sameMatrix = (a, b) => {
1241
+ const left = a.elements;
1242
+ const right = b.elements;
1243
+ for (let at = 0; at < 16; at++) if (Math.abs(left[at] - right[at]) >= MATRIX_EPSILON) return false;
1244
+ return true;
1245
+ };
1182
1246
  function createStaticBatcher(THREE, root, options = {}) {
1183
1247
  const include = options.include ?? (() => true);
1184
- const follow = options.followMeshes === true;
1248
+ const shadowOnly = options.shadowOnly === true;
1249
+ const follow = options.followMeshes === true && !shadowOnly;
1185
1250
  root.updateMatrixWorld(true);
1186
1251
  const inverse = new THREE.Matrix4().copy(root.matrixWorld).invert();
1252
+ const materialKey2 = options.materialKey ?? uuidOf;
1187
1253
  const groups = /* @__PURE__ */ new Map();
1188
1254
  root.traverse((object) => {
1189
1255
  const mesh = object;
1190
- if (!mesh.isMesh || !isShown(mesh, root) || !isBatchable(mesh) || !include(mesh)) return;
1191
- const key = signatureOf(mesh, options.materialKey ?? uuidOf);
1192
- groups.set(key, [...groups.get(key) ?? [], mesh]);
1256
+ if (!mesh.isMesh || !isShown(mesh, root) || !isBatchable(mesh) || shadowOnly && !castsPlainShadow(mesh) || !include(mesh)) return;
1257
+ const key = signatureOf(mesh, materialKey2, shadowOnly);
1258
+ const waiting = groups.get(key);
1259
+ if (waiting) waiting.push(mesh);
1260
+ else groups.set(key, [mesh]);
1193
1261
  });
1194
1262
  const group = new THREE.Group();
1195
1263
  group.name = "static-batches";
1196
1264
  const sources = [];
1197
- const pending = [...groups.values()].filter((meshes) => meshes.length >= 2);
1198
- const mergeSome = (deadline) => {
1199
- while (pending.length > 0) {
1200
- const meshes = pending.shift();
1201
- if (meshes.every((mesh) => isShown(mesh, root))) sources.push(...mergeGroup(THREE, { meshes, inverse: new THREE.Matrix4().copy(root.matrixWorld).invert(), group, follow, onBatch: options.onBatch }));
1202
- if (performance.now() >= deadline) return;
1265
+ const maxVertices = options.maxVertices ?? (shadowOnly ? 65535 : Number.POSITIVE_INFINITY);
1266
+ const chunks = (meshes) => {
1267
+ const out = [[]];
1268
+ let vertices = 0;
1269
+ for (const mesh of meshes) {
1270
+ const count = mesh.geometry.attributes.position.count;
1271
+ if (vertices + count > maxVertices && out[out.length - 1].length > 0) {
1272
+ out.push([]);
1273
+ vertices = 0;
1274
+ }
1275
+ ;
1276
+ out[out.length - 1].push(mesh);
1277
+ vertices += count;
1203
1278
  }
1279
+ return out;
1280
+ };
1281
+ const pending = [...groups.entries()].flatMap(([key, meshes]) => chunks(meshes).map((chunk) => [key, chunk])).filter(([, meshes]) => meshes.length >= 2);
1282
+ const groupedMasks = /* @__PURE__ */ new Map();
1283
+ for (const [, meshes] of pending) for (const mesh of meshes) groupedMasks.set(mesh, mesh.layers.mask);
1284
+ const isUnchanged = (mesh, key) => isShown(mesh, root) && include(mesh) && isBatchable(mesh) && (!shadowOnly || castsPlainShadow(mesh)) && mesh.layers.mask === groupedMasks.get(mesh) && signatureOf(mesh, materialKey2, shadowOnly) === key;
1285
+ const mergeNext = () => {
1286
+ const [key, meshes] = pending.shift();
1287
+ const still = meshes.filter((mesh) => isUnchanged(mesh, key));
1288
+ for (const mesh of meshes) groupedMasks.delete(mesh);
1289
+ if (still.length < 2) return;
1290
+ inverse.copy(root.matrixWorld).invert();
1291
+ for (const source of mergeGroup(THREE, { meshes: still, inverse, group, follow, shadowOnly, onBatch: options.onBatch })) sources.push(source);
1204
1292
  };
1205
- if (options.budgetMs === void 0) mergeSome(Number.POSITIVE_INFINITY);
1293
+ const queue = options.queue ?? createStaticBatchQueue();
1294
+ const leaveQueue = queue.join({
1295
+ pendingUnits: () => pending.length,
1296
+ runUnit: mergeNext,
1297
+ finishAll() {
1298
+ while (pending.length > 0) mergeNext();
1299
+ }
1300
+ });
1301
+ if (options.budgetMs === void 0 && options.queue === void 0) while (pending.length > 0) mergeNext();
1206
1302
  root.add(group);
1207
1303
  const scratch = new THREE.Matrix4();
1208
1304
  let released = 0;
1209
1305
  const release = (source) => {
1210
1306
  source.released = true;
1211
- source.mesh.layers.mask = source.mask;
1307
+ if (shadowOnly) source.mesh.castShadow = source.castShadow;
1308
+ else source.mesh.layers.mask = source.mask;
1212
1309
  const { index } = source.batch;
1213
1310
  const first = index.array[source.start];
1214
1311
  for (let at = source.start; at < source.start + source.count; at++) index.array[at] = first;
@@ -1228,7 +1325,7 @@ function createStaticBatcher(THREE, root, options = {}) {
1228
1325
  return {
1229
1326
  group,
1230
1327
  update() {
1231
- if (pending.length > 0) mergeSome(performance.now() + (options.budgetMs ?? Number.POSITIVE_INFINITY));
1328
+ if (pending.length > 0 && !queue.isAttached()) drainDetached(queue.deferredQueue(), options.budgetMs ?? Number.POSITIVE_INFINITY);
1232
1329
  const before = released;
1233
1330
  inverse.copy(root.matrixWorld).invert();
1234
1331
  for (const source of sources) if (!source.released && hasChanged(source)) release(source);
@@ -1236,31 +1333,41 @@ function createStaticBatcher(THREE, root, options = {}) {
1236
1333
  },
1237
1334
  stats: () => ({ batches: group.children.length, batched: sources.filter((source) => !source.released).length, released }),
1238
1335
  dispose() {
1239
- for (const source of sources) if (!source.released) source.mesh.layers.mask = source.mask;
1336
+ for (const source of sources) {
1337
+ if (source.released) continue;
1338
+ if (shadowOnly) source.mesh.castShadow = source.castShadow;
1339
+ else source.mesh.layers.mask = source.mask;
1340
+ }
1341
+ leaveQueue();
1342
+ pending.length = 0;
1343
+ groupedMasks.clear();
1240
1344
  group.removeFromParent();
1241
1345
  for (const child of group.children) {
1242
1346
  ;
1243
1347
  child.geometry.dispose();
1348
+ if (shadowOnly) child.material.dispose();
1244
1349
  child.skeleton?.dispose();
1245
1350
  }
1246
1351
  }
1247
1352
  };
1248
1353
  }
1249
- function copyAttribute(name, attribute, target, offset, matrix, normalMatrix) {
1354
+ var isPlain = (attribute) => !attribute.isInterleavedBufferAttribute && !attribute.normalized;
1355
+ function copyAttribute(name, attribute, target, offset, matrix) {
1250
1356
  const size = attribute.itemSize;
1357
+ const count = attribute.count;
1251
1358
  const source = attribute.array;
1252
- const flat = !attribute.isInterleavedBufferAttribute && source.length === attribute.count * size;
1359
+ const plain = isPlain(attribute);
1253
1360
  if (name !== "position" && name !== "normal") {
1254
- if (flat) target.set(source, offset * size);
1255
- else for (let at = 0; at < attribute.count; at++) for (let k = 0; k < size; k++) target[(offset + at) * size + k] = attribute.getComponent(at, k);
1361
+ if (!attribute.isInterleavedBufferAttribute && source.length === count * size) target.set(source, offset * size);
1362
+ else for (let at = 0; at < count; at++) for (let k = 0; k < size; k++) target[(offset + at) * size + k] = attribute.getComponent(at, k);
1256
1363
  return;
1257
1364
  }
1258
- const e = (name === "position" ? matrix : normalMatrix).elements;
1365
+ const e = matrix.elements;
1259
1366
  const isNormal = name === "normal";
1260
- for (let at = 0; at < attribute.count; at++) {
1261
- const x = attribute.getX(at);
1262
- const y = attribute.getY(at);
1263
- const z = attribute.getZ(at);
1367
+ for (let at = 0; at < count; at++) {
1368
+ const x = plain ? source[at * size] : attribute.getX(at);
1369
+ const y = plain ? source[at * size + 1] : attribute.getY(at);
1370
+ const z = plain ? source[at * size + 2] : attribute.getZ(at);
1264
1371
  const out = (offset + at) * 3;
1265
1372
  if (isNormal) {
1266
1373
  const nx = e[0] * x + e[3] * y + e[6] * z;
@@ -1296,11 +1403,23 @@ function skinnedBatch(THREE, merged, material, meshes) {
1296
1403
  mesh.frustumCulled = false;
1297
1404
  return mesh;
1298
1405
  }
1299
- function mergeGroup(THREE, { meshes, inverse: rootInverse, group, follow, onBatch }) {
1406
+ function shadowBatch(THREE, merged, like) {
1407
+ const material = new THREE.MeshBasicMaterial({ colorWrite: false, depthWrite: false, side: like.side });
1408
+ material.shadowSide = like.shadowSide;
1409
+ material.name = "shadow-batch";
1410
+ const mesh = new THREE.Mesh(merged, material);
1411
+ merged.setDrawRange(0, -1);
1412
+ mesh.onBeforeShadow = () => merged.setDrawRange(0, Number.POSITIVE_INFINITY);
1413
+ mesh.onAfterShadow = () => merged.setDrawRange(0, -1);
1414
+ mesh.castShadow = true;
1415
+ mesh.receiveShadow = false;
1416
+ return mesh;
1417
+ }
1418
+ function mergeGroup(THREE, { meshes, inverse: rootInverse, group, follow, shadowOnly, onBatch }) {
1300
1419
  const identity = new THREE.Matrix4();
1301
1420
  const inverse = follow ? identity : rootInverse;
1302
1421
  const first = meshes[0];
1303
- const names = ATTRIBUTES.filter((name) => first.geometry.attributes[name] !== void 0);
1422
+ const names = shadowOnly ? ["position"] : ATTRIBUTES.filter((name) => first.geometry.attributes[name] !== void 0);
1304
1423
  const pieces = meshes.map((mesh2) => {
1305
1424
  const local = new THREE.Matrix4().multiplyMatrices(inverse, mesh2.matrixWorld);
1306
1425
  const vertices = mesh2.geometry.attributes.position.count;
@@ -1310,14 +1429,14 @@ function mergeGroup(THREE, { meshes, inverse: rootInverse, group, follow, onBatc
1310
1429
  const totalVertices = pieces.reduce((sum, piece) => sum + piece.vertices, 0);
1311
1430
  const totalIndices = pieces.reduce((sum, piece) => sum + piece.indexCount, 0);
1312
1431
  const merged = new THREE.BufferGeometry();
1313
- const normalMatrix = new THREE.Matrix3();
1432
+ const normalMatrices = names.includes("normal") ? pieces.map((piece) => new THREE.Matrix3().getNormalMatrix(follow ? identity : piece.local)) : [];
1314
1433
  for (const name of names) {
1315
1434
  const size = first.geometry.attributes[name].itemSize;
1316
1435
  const array = new Float32Array(totalVertices * size);
1317
1436
  let offset = 0;
1318
- for (const piece of pieces) {
1319
- const matrix = follow ? identity : piece.local;
1320
- copyAttribute(name, piece.mesh.geometry.attributes[name], array, offset, matrix, normalMatrix.getNormalMatrix(matrix));
1437
+ for (const [at, piece] of pieces.entries()) {
1438
+ const matrix = name === "normal" ? normalMatrices[at] : follow ? identity : piece.local;
1439
+ copyAttribute(name, piece.mesh.geometry.attributes[name], array, offset, matrix);
1321
1440
  offset += piece.vertices;
1322
1441
  }
1323
1442
  merged.setAttribute(name, new THREE.BufferAttribute(array, size));
@@ -1325,10 +1444,12 @@ function mergeGroup(THREE, { meshes, inverse: rootInverse, group, follow, onBatc
1325
1444
  const indexArray = totalVertices > 65535 ? new Uint32Array(totalIndices) : new Uint16Array(totalIndices);
1326
1445
  const indexAttribute = new THREE.BufferAttribute(indexArray, 1);
1327
1446
  merged.setIndex(indexAttribute);
1328
- const mesh = follow ? skinnedBatch(THREE, merged, first.material, meshes) : new THREE.Mesh(merged, first.material);
1329
- mesh.name = `batch:${first.material.name || first.material.type}`;
1330
- mesh.castShadow = first.castShadow;
1331
- mesh.receiveShadow = first.receiveShadow;
1447
+ const mesh = shadowOnly ? shadowBatch(THREE, merged, first.material) : follow ? skinnedBatch(THREE, merged, first.material, meshes) : new THREE.Mesh(merged, first.material);
1448
+ mesh.name = shadowOnly ? `shadow-batch:${shadowSideKey(first.material)}` : `batch:${first.material.name || first.material.type}`;
1449
+ if (!shadowOnly) {
1450
+ mesh.castShadow = first.castShadow;
1451
+ mesh.receiveShadow = first.receiveShadow;
1452
+ }
1332
1453
  mesh.raycast = () => void 0;
1333
1454
  merged.computeBoundingBox();
1334
1455
  merged.computeBoundingSphere();
@@ -1340,8 +1461,10 @@ function mergeGroup(THREE, { meshes, inverse: rootInverse, group, follow, onBatc
1340
1461
  let indexOffset = 0;
1341
1462
  for (const piece of pieces) {
1342
1463
  const index = piece.mesh.geometry.index;
1343
- if (index) for (let at = 0; at < piece.indexCount; at++) indexArray[indexOffset + at] = index.getX(at) + vertexOffset;
1344
- else for (let at = 0; at < piece.indexCount; at++) indexArray[indexOffset + at] = at + vertexOffset;
1464
+ if (index) {
1465
+ const indices = index.array;
1466
+ for (let at = 0; at < piece.indexCount; at++) indexArray[indexOffset + at] = indices[at] + vertexOffset;
1467
+ } else for (let at = 0; at < piece.indexCount; at++) indexArray[indexOffset + at] = at + vertexOffset;
1345
1468
  sources.push({
1346
1469
  mesh: piece.mesh,
1347
1470
  geometry: piece.mesh.geometry,
@@ -1350,12 +1473,14 @@ function mergeGroup(THREE, { meshes, inverse: rootInverse, group, follow, onBatc
1350
1473
  local: piece.local,
1351
1474
  world: piece.mesh.matrixWorld.clone(),
1352
1475
  mask: piece.mesh.layers.mask,
1476
+ castShadow: piece.mesh.castShadow,
1353
1477
  batch,
1354
1478
  start: indexOffset,
1355
1479
  count: piece.indexCount,
1356
1480
  released: false
1357
1481
  });
1358
- piece.mesh.layers.set(BATCHED_LAYER);
1482
+ if (shadowOnly) piece.mesh.castShadow = false;
1483
+ else piece.mesh.layers.set(BATCHED_LAYER);
1359
1484
  vertexOffset += piece.vertices;
1360
1485
  indexOffset += piece.indexCount;
1361
1486
  }
@@ -1373,6 +1498,7 @@ export {
1373
1498
  createMaterialAnchors,
1374
1499
  createMaterialPool,
1375
1500
  createProgramWarmup,
1501
+ createStaticBatchQueue,
1376
1502
  createStaticBatcher,
1377
1503
  geometryKey,
1378
1504
  isLightBudget,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lights/slots.ts","../src/lights/arbiter.ts","../src/fog.ts","../src/lights/scene-state.ts","../src/lights/budget.ts","../src/lights/types.ts","../src/lights/guard.ts","../src/program-key.ts","../src/pools/anchors.ts","../src/probes.ts","../src/warmup.ts","../src/pools/pooled.ts","../src/pools/geometry.ts","../src/pools/material.ts","../src/pools/render-pools.ts","../src/frame-pacer.ts","../src/static-batcher.ts"],"sourcesContent":["import type { Group, Object3D, PointLight, SpotLight } from 'three'\n\nimport type { LightKind, LightPatch, LinearRgb, ThreeForLights } from './types'\n\nconst PARKED_Y = -50\nconst DEFAULT_DECAY = 2\nconst DEFAULT_ANGLE = Math.PI / 3\nconst POSITION_EPSILON = 1e-6\n\nexport type Vec3 = [number, number, number]\n\nexport type LightValues = {\n color: number | LinearRgb\n intensity: number\n distance: number\n decay: number\n position: Vec3\n target: Vec3 | undefined\n angle: number\n penumbra: number\n}\n\n/** Whoever owns a slot: a request, a source or a lease. */\nexport interface Holder {\n readonly kind: 'request' | 'source' | 'lease'\n readonly owner: string\n readonly lightKind: LightKind\n priority: number\n urgent: boolean\n values: LightValues\n slot: Slot | null\n alive: boolean\n onLost: (() => void) | undefined\n /** Sources only. */\n follow: Object3D | undefined\n shadow: boolean\n wanted: boolean\n distance: number\n /** Sources only: `values` with the world position and direction of `follow` of this frame. */\n resolved: LightValues\n}\n\nexport interface Slot {\n readonly index: number\n readonly kind: LightKind\n readonly shadow: boolean\n readonly light: PointLight | SpotLight\n holder: Holder | null\n pending: Holder | null\n leased: boolean\n /** 0..1 multiplier on the holder's intensity. */\n fade: number\n fadeTarget: number\n fadeOutMs: number\n baseIntensity: number\n lastPosition: Vec3\n}\n\nexport function createValues(base: Partial<LightValues> & Pick<LightValues, 'color' | 'intensity' | 'distance' | 'position'>): LightValues {\n return {\n decay: DEFAULT_DECAY,\n target: undefined,\n angle: DEFAULT_ANGLE,\n penumbra: 0,\n ...base,\n position: [...base.position],\n }\n}\n\nexport function mergeValues(values: LightValues, patch: LightPatch): void {\n if (patch.color !== undefined) values.color = patch.color\n if (patch.intensity !== undefined) values.intensity = patch.intensity\n if (patch.distance !== undefined) values.distance = patch.distance\n if (patch.decay !== undefined) values.decay = patch.decay\n if (patch.position !== undefined) values.position = [...patch.position]\n if (patch.target !== undefined) values.target = [...patch.target]\n if (patch.angle !== undefined) values.angle = patch.angle\n if (patch.penumbra !== undefined) values.penumbra = patch.penumbra\n}\n\nexport type ShadowSettings = { readonly bias?: number; readonly normalBias?: number; readonly near?: number }\n\nexport function createSlots(THREE: ThreeForLights, group: Group, kind: LightKind, count: number, shadows: number, mapSize: number, settings: ShadowSettings = {}): Slot[] {\n const slots: Slot[] = []\n for (let index = 0; index < count; index++) {\n const light = kind === 'point' ? new THREE.PointLight(0xffffff, 0, 0, DEFAULT_DECAY) : new THREE.SpotLight(0xffffff, 0, 0, DEFAULT_ANGLE, 0, DEFAULT_DECAY)\n light.position.set(0, PARKED_Y, 0)\n light.layers.enableAll()\n const shadow = index < shadows\n if (shadow) {\n light.castShadow = true\n light.shadow.autoUpdate = false\n light.shadow.mapSize.set(mapSize, mapSize)\n if (settings.bias !== undefined) light.shadow.bias = settings.bias\n if (settings.normalBias !== undefined) light.shadow.normalBias = settings.normalBias\n if (settings.near !== undefined) light.shadow.camera.near = settings.near\n }\n group.add(light)\n if ('target' in light) group.add(light.target)\n slots.push({ index, kind, shadow, light, holder: null, pending: null, leased: false, fade: 0, fadeTarget: 0, fadeOutMs: 0, baseIntensity: 0, lastPosition: [0, PARKED_Y, 0] })\n }\n return slots\n}\n\nexport function isFree(slot: Slot): boolean {\n return !slot.leased && slot.holder === null && slot.pending === null\n}\n\nexport function applyIntensity(slot: Slot): void {\n slot.light.intensity = slot.baseIntensity * slot.fade\n}\n\nexport function markShadow(slot: Slot): void {\n if (slot.shadow) slot.light.shadow.needsUpdate = true\n}\n\nexport function writeLight(THREE: ThreeForLights, slot: Slot, values: LightValues): void {\n const { light } = slot\n if (typeof values.color === 'number') light.color.set(values.color)\n else light.color.setRGB(values.color[0], values.color[1], values.color[2], THREE.LinearSRGBColorSpace)\n light.distance = values.distance\n light.decay = values.decay\n const [x, y, z] = values.position\n light.position.set(x, y, z)\n if ('angle' in light) {\n light.angle = values.angle\n light.penumbra = values.penumbra\n const [tx, ty, tz] = values.target ?? [x, y - 1, z]\n light.target.position.set(tx, ty, tz)\n }\n const last = slot.lastPosition\n if (slot.shadow && (Math.abs(last[0] - x) > POSITION_EPSILON || Math.abs(last[1] - y) > POSITION_EPSILON || Math.abs(last[2] - z) > POSITION_EPSILON)) markShadow(slot)\n slot.lastPosition = [x, y, z]\n slot.baseIntensity = values.intensity\n applyIntensity(slot)\n}\n\n/** The holder's writes apply from now on; its light fades in (requests that cut a victim start at full). */\nexport function install(THREE: ThreeForLights, slot: Slot, holder: Holder, startAtFull: boolean): void {\n slot.holder = holder\n slot.pending = null\n slot.fade = startAtFull ? 1 : 0\n slot.fadeTarget = 1\n holder.slot = slot\n markShadow(slot)\n writeLight(THREE, slot, holder.values)\n}\n\n/** Drops the holder: the light keeps its last values and fades to 0 (at once with `fadeOutMs` 0). */\nexport function vacate(slot: Slot, fadeOutMs: number): void {\n slot.holder = null\n slot.fadeTarget = 0\n slot.fadeOutMs = fadeOutMs\n if (fadeOutMs <= 0) {\n slot.fade = 0\n applyIntensity(slot)\n }\n}\n\nexport function stepFade(slot: Slot, dtSeconds: number, fadeInMs: number): void {\n if (slot.fade < slot.fadeTarget) {\n slot.fade = fadeInMs <= 0 ? slot.fadeTarget : Math.min(slot.fadeTarget, slot.fade + (dtSeconds * 1000) / fadeInMs)\n } else if (slot.fade > slot.fadeTarget) {\n slot.fade = slot.fadeOutMs <= 0 ? slot.fadeTarget : Math.max(slot.fadeTarget, slot.fade - (dtSeconds * 1000) / slot.fadeOutMs)\n }\n applyIntensity(slot)\n}\n","import { type Holder, type Slot, install, isFree, stepFade, vacate } from './slots'\nimport type { LightKind, ThreeForLights } from './types'\n\nexport type ArbiterCore = {\n readonly THREE: ThreeForLights\n readonly slots: Record<LightKind, readonly Slot[]>\n readonly urgentReserve: number\n readonly fadeMs: number\n readonly hysteresis: number\n preempted: number\n refused: number\n}\n\n/** The slots requests and sources compete for: not leased, and shadow slots only on their own pass. */\nexport function poolOf(core: ArbiterCore, kind: LightKind, shadow: boolean): Slot[] {\n return core.slots[kind].filter((slot) => !slot.leased && slot.shadow === shadow)\n}\n\nfunction contribution(holder: Holder): number {\n return holder.values.intensity / Math.max(1, holder.distance) ** 2\n}\n\n/** Lowest priority first; on a tie, the smallest perceived contribution. */\nfunction isWeaker(a: Holder, b: Holder): boolean {\n if (a.priority !== b.priority) return a.priority < b.priority\n return contribution(a) < contribution(b)\n}\n\nfunction pickFree(slots: readonly Slot[]): Slot | undefined {\n let best: Slot | undefined\n for (const slot of slots) if (isFree(slot) && (best === undefined || slot.fade < best.fade)) best = slot\n return best\n}\n\n/** Gives a free slot to the holder: at once when its light is dark or the holder is urgent, else after the slot finishes fading out. */\nfunction place(core: ArbiterCore, slot: Slot, holder: Holder): void {\n holder.slot = slot\n if (slot.fade > 0 && !holder.urgent) {\n slot.pending = holder\n slot.fadeTarget = 0\n return\n }\n install(core.THREE, slot, holder, holder.kind === 'request')\n}\n\n/** Takes the slot from its holder; a request is told and dies, a source goes back to the queue. */\nfunction evict(core: ArbiterCore, slot: Slot, challenger: Holder, cut: boolean): void {\n const victim = slot.holder\n if (victim === null) return\n victim.slot = null\n if (victim.kind === 'request') {\n victim.alive = false\n victim.onLost?.()\n }\n core.preempted++\n vacate(slot, cut ? 0 : core.fadeMs)\n if (cut) {\n install(core.THREE, slot, challenger, true)\n return\n }\n slot.pending = challenger\n challenger.slot = slot\n}\n\nfunction weakestHolder(slots: readonly Slot[]): Slot | undefined {\n let weakest: Slot | undefined\n for (const slot of slots) {\n if (slot.holder === null || slot.pending !== null) continue\n if (weakest === undefined || isWeaker(slot.holder, weakest.holder as Holder)) weakest = slot\n }\n return weakest\n}\n\n/** Slots free to a holder that has no right to the urgent reserve. */\nfunction freeBeyondReserve(core: ArbiterCore, pool: readonly Slot[], reserve: number): Slot | undefined {\n const free = pool.filter(isFree)\n return free.length > reserve ? pickFree(pool) : undefined\n}\n\nexport function admitRequest(core: ArbiterCore, holder: Holder): boolean {\n const pool = poolOf(core, holder.lightKind, false)\n const reserve = holder.lightKind === 'point' ? core.urgentReserve : 0\n const free = holder.urgent ? pickFree(pool) : freeBeyondReserve(core, pool, reserve)\n if (free !== undefined) {\n place(core, free, holder)\n return true\n }\n const victim = weakestHolder(pool)\n if (victim === undefined || (victim.holder as Holder).priority >= holder.priority) {\n core.refused++\n return false\n }\n evict(core, victim, holder, holder.urgent)\n return true\n}\n\nfunction beats(challenger: Holder, incumbent: Holder, hysteresis: number): boolean {\n if (challenger.priority !== incumbent.priority) return challenger.priority > incumbent.priority\n return challenger.distance < incumbent.distance * (1 - hysteresis)\n}\n\nfunction bestFirst(a: Holder, b: Holder): number {\n return b.priority - a.priority || a.distance - b.distance\n}\n\n/** Hands the pool's slots to the wanted sources: best first, an incumbent only yields to a clearly better challenger. */\nexport function arbitrateSources(core: ArbiterCore, pool: readonly Slot[], sources: readonly Holder[], reserve: number): void {\n for (const slot of pool) {\n const holder = slot.holder\n if (slot.pending?.kind === 'source' && !slot.pending.wanted) {\n slot.pending.slot = null\n slot.pending = null\n }\n if (holder?.kind === 'source' && !holder.wanted) {\n holder.slot = null\n vacate(slot, core.fadeMs)\n }\n }\n const challengers = sources.filter((source) => source.wanted && source.slot === null).sort(bestFirst)\n for (const challenger of challengers) {\n const free = freeBeyondReserve(core, pool, reserve)\n if (free !== undefined) {\n place(core, free, challenger)\n continue\n }\n const incumbentSlots = pool.filter((slot) => slot.holder?.kind === 'source')\n let worst: Slot | undefined\n for (const slot of incumbentSlots) {\n if (slot.pending !== null) continue\n if (worst === undefined || bestFirst(slot.holder as Holder, worst.holder as Holder) > 0) worst = slot\n }\n if (worst === undefined || !beats(challenger, worst.holder as Holder, core.hysteresis)) break\n evict(core, worst, challenger, false)\n }\n}\n\nexport function stepSlots(core: ArbiterCore, dtSeconds: number): void {\n for (const kind of ['point', 'spot'] as const) {\n for (const slot of core.slots[kind]) {\n stepFade(slot, dtSeconds, core.fadeMs)\n if (slot.pending !== null && slot.fade <= 0) install(core.THREE, slot, slot.pending, false)\n }\n }\n}\n","import type { Fog, FogBase, FogExp2, Scene } from 'three'\n\nimport type { ThreeLib } from './three-lib'\n\n/** Both exact in half precision (multiples of 32 under 65 504), so the neutral fog survives a `mediump` fragment shader. */\nexport const NEUTRAL_FOG_NEAR = 6.0e4\nexport const NEUTRAL_FOG_FAR = 6.4e4\n\nexport interface FogOptions {\n /** `clear()` leaves a neutral linear Fog instead of `null`: the fog presence and type never change, so no program recompiles. */\n readonly stable?: boolean\n /** Colour of the neutral fog. Default 0x000000. */\n readonly color?: number\n}\n\nexport interface FogController {\n useLinear(color: number, near: number, far: number): Fog\n useExp2(color: number, density: number): FogExp2\n /** Back to no fog: the original fog (or `null`); when `stable`, the host's own linear fog or the neutral one, never `null`. */\n clear(): void\n}\n\nfunction isLinearFog(fog: FogBase | null): fog is Fog {\n return (fog as Partial<Fog> | null)?.isFog === true\n}\n\nfunction isExp2Fog(fog: FogBase | null): fog is FogExp2 {\n return (fog as Partial<FogExp2> | null)?.isFogExp2 === true\n}\n\nexport function isNeutralFog(fog: unknown): boolean {\n const candidate = fog as Partial<Fog> | null | undefined\n return candidate?.isFog === true && candidate.near === NEUTRAL_FOG_NEAR && candidate.far === NEUTRAL_FOG_FAR\n}\n\n/** Writes into the scene's existing fog object when its type matches, as the weather layer does, so nothing is reallocated per change. */\nexport function createFog(THREE: Pick<ThreeLib, 'Fog' | 'FogExp2'>, scene: Scene, options: FogOptions = {}): FogController {\n const original = scene.fog\n const hostLinear = isLinearFog(original) ? { color: original.color.getHex(), near: original.near, far: original.far } : undefined\n const resting = hostLinear ?? { color: options.color ?? 0, near: NEUTRAL_FOG_NEAR, far: NEUTRAL_FOG_FAR }\n return {\n useLinear(color, near, far) {\n const current = scene.fog\n if (isLinearFog(current)) {\n current.color.set(color)\n current.near = near\n current.far = far\n return current\n }\n const fog = new THREE.Fog(color, near, far)\n scene.fog = fog\n return fog\n },\n useExp2(color, density) {\n const current = scene.fog\n if (isExp2Fog(current)) {\n current.color.set(color)\n current.density = density\n return current\n }\n const fog = new THREE.FogExp2(color, density)\n scene.fog = fog\n return fog\n },\n clear() {\n if (options.stable !== true) {\n scene.fog = original\n return\n }\n const current = scene.fog\n if (isLinearFog(current)) {\n current.color.set(resting.color)\n current.near = resting.near\n current.far = resting.far\n return\n }\n scene.fog = new THREE.Fog(resting.color, resting.near, resting.far)\n },\n }\n}\n","import type { Object3D, Scene } from 'three'\n\nimport { NEUTRAL_FOG_NEAR } from '../fog'\nimport type { FogState, LightCheck, RendererState, SealOptions } from './types'\n\ntype Flags = Record<string, unknown>\ntype Counter = { count: number; shadows: number }\n\nconst LIGHT_FLAGS = [\n ['point', 'isPointLight'],\n ['spot', 'isSpotLight'],\n ['hemi', 'isHemisphereLight'],\n ['dir', 'isDirectionalLight'],\n ['ambient', 'isAmbientLight'],\n ['rect', 'isRectAreaLight'],\n] as const\n\n/** The visible lights the way the renderer collects them: they decide the shader's light counts. */\nexport function lightSignature(scene: Object3D): string {\n const counters: Record<string, Counter> = {}\n for (const [name] of LIGHT_FLAGS) counters[name] = { count: 0, shadows: 0 }\n scene.traverseVisible((object) => {\n const flags = object as unknown as Flags\n for (const [name, flag] of LIGHT_FLAGS) {\n if (flags[flag] !== true) continue\n const counter = counters[name] as Counter\n counter.count++\n if ((flags as { castShadow?: boolean }).castShadow === true) counter.shadows++\n }\n })\n return LIGHT_FLAGS.map(([name]) => `${name}:${(counters[name] as Counter).count}/${(counters[name] as Counter).shadows}`).join(' ')\n}\n\nexport function fogStateOf(scene: Scene): FogState {\n const fog = scene.fog as Flags | null\n if (fog === null) return 'none'\n return fog.isFogExp2 === true ? 'exp2' : 'linear'\n}\n\n/** Every PointLight/SpotLight under `scene` that is not under `group`, as a path of child indices. */\nexport function findStrays(scene: Object3D, group: Object3D): string[] {\n const strays: string[] = []\n const visit = (object: Object3D, path: string): void => {\n if (object === group) return\n const flags = object as unknown as Flags\n if (flags.isPointLight === true || flags.isSpotLight === true) strays.push(`${path}${object.name === '' ? object.type : object.name}`)\n object.children.forEach((child, index) => visit(child, `${path}${index}/`))\n }\n visit(scene, '')\n return strays\n}\n\nexport type Sealed = {\n readonly lights: string\n readonly environment: string\n readonly toneMapping: number\n readonly outputColorSpace: string\n readonly targetColorSpace: string\n readonly shadowMapType: number\n readonly fogStates: readonly FogState[]\n readonly cameras: SealOptions['cameras']\n readonly target: SealOptions['target']\n}\n\nfunction environmentOf(scene: Scene): string {\n return scene.environment === null ? 'none' : `texture:${scene.environment.mapping}`\n}\n\nfunction targetColorSpaceOf(target: SealOptions['target']): string {\n return target ? target.texture.colorSpace : 'canvas'\n}\n\nexport function captureSealed(renderer: RendererState, scene: Scene, options: SealOptions): Sealed {\n return {\n lights: lightSignature(scene),\n environment: environmentOf(scene),\n toneMapping: renderer.toneMapping,\n outputColorSpace: renderer.outputColorSpace,\n targetColorSpace: targetColorSpaceOf(options.target),\n shadowMapType: renderer.shadowMap.type,\n fogStates: options.fogStates ?? [fogStateOf(scene)],\n cameras: options.cameras,\n target: options.target,\n }\n}\n\ntype Described = {\n readonly lights: string\n readonly fog: string\n readonly environment: string\n readonly toneMapping: number\n readonly outputColorSpace: string\n readonly targetColorSpace: string\n readonly shadowMapType: number\n}\n\nfunction describe(state: Described): string {\n const { lights, fog, environment, toneMapping, outputColorSpace, targetColorSpace, shadowMapType } = state\n return `${lights} | fog:${fog} env:${environment} tone:${toneMapping} out:${outputColorSpace}/${targetColorSpace} shadow:${shadowMapType}`\n}\n\nfunction farBeyondNeutralFog(scene: Scene, sealed: Sealed): boolean {\n const fog = scene.fog as { isFog?: boolean; near?: number } | null\n if (fog?.isFog !== true || fog.near !== NEUTRAL_FOG_NEAR) return false\n return (sealed.cameras ?? []).some((camera) => ((camera as unknown as { far?: number }).far ?? 0) >= NEUTRAL_FOG_NEAR)\n}\n\nexport function checkSealed(sealed: Sealed | null, renderer: RendererState, scene: Scene, group: Object3D): LightCheck {\n const strays = findStrays(scene, group)\n const lights = lightSignature(scene)\n if (sealed === null) return { ok: strays.length === 0, expected: lights, actual: lights, strays }\n const fog = fogStateOf(scene)\n const fogAllowed = sealed.fogStates.includes(fog)\n const expected = describe({ ...sealed, fog: fogAllowed ? fog : sealed.fogStates.join('|') })\n const actual = describe({\n lights,\n fog,\n environment: environmentOf(scene),\n toneMapping: renderer.toneMapping,\n outputColorSpace: renderer.outputColorSpace,\n targetColorSpace: targetColorSpaceOf(sealed.target),\n shadowMapType: renderer.shadowMap.type,\n })\n const ok = strays.length === 0 && expected === actual && !farBeyondNeutralFog(scene, sealed)\n return { ok, expected, actual, strays }\n}\n","import type { HemisphereLight, Object3D, Scene } from 'three'\n\nimport { type ArbiterCore, admitRequest, arbitrateSources, poolOf, stepSlots } from './arbiter'\nimport { type Sealed, captureSealed, checkSealed } from './scene-state'\nimport { type Holder, type Slot, type Vec3, createSlots, createValues, isFree, markShadow, mergeValues, vacate, writeLight } from './slots'\nimport type {\n LightBudget,\n LightBudgetOptions,\n LightHandle,\n LightKind,\n LightLease,\n LightPatch,\n LightRequest,\n LightSource,\n RendererState,\n SourceHandle,\n ThreeForLights,\n} from './types'\n\nconst DEFAULTS = { point: 16, spot: 4, pointShadows: 2, spotShadows: 0, shadowMapSize: 512, urgentReserve: 2, fadeMs: 120, hysteresis: 0.15, hemisphere: 0 }\nconst ZERO: Vec3 = [0, 0, 0]\nconst ALL_LAYERS_MASK = -1\n\nfunction newHolder(kind: Holder['kind'], lightKind: LightKind, request: LightRequest | LightSource, urgent: boolean): Holder {\n return {\n kind,\n owner: request.owner,\n lightKind,\n priority: request.priority,\n urgent,\n values: createValues({ color: request.color, intensity: request.intensity, distance: request.distance, position: [...request.position], ...optional(request) }),\n slot: null,\n alive: true,\n onLost: undefined,\n follow: undefined,\n shadow: false,\n wanted: true,\n distance: 0,\n resolved: createValues({ color: request.color, intensity: 0, distance: 0, position: ZERO }),\n }\n}\n\nfunction optional(request: LightRequest | LightSource): Partial<Holder['values']> {\n const values: Partial<Holder['values']> = {}\n if (request.decay !== undefined) values.decay = request.decay\n if (request.target !== undefined) values.target = [...request.target]\n if (request.angle !== undefined) values.angle = request.angle\n if (request.penumbra !== undefined) values.penumbra = request.penumbra\n return values\n}\n\nfunction isAttached(object: Object3D, root: Object3D): boolean {\n for (let node: Object3D | null = object; node !== null; node = node.parent) if (node === root) return true\n return false\n}\n\nexport function createLightBudget(THREE: ThreeForLights, scene: Object3D, options: LightBudgetOptions = {}): LightBudget {\n const opts = { ...DEFAULTS, ...options }\n const pointShadows = Math.min(opts.pointShadows, opts.point)\n const spotShadows = Math.min(opts.spotShadows, opts.spot)\n const group = new THREE.Group()\n group.name = 'light-budget'\n const core: ArbiterCore = {\n THREE,\n slots: {\n point: createSlots(THREE, group, 'point', opts.point, pointShadows, opts.shadowMapSize, options.shadowSettings),\n spot: createSlots(THREE, group, 'spot', opts.spot, spotShadows, opts.shadowMapSize, options.shadowSettings),\n },\n urgentReserve: opts.urgentReserve,\n fadeMs: opts.fadeMs,\n hysteresis: opts.hysteresis,\n preempted: 0,\n refused: 0,\n }\n const hemispheres: HemisphereLight[] = []\n for (let index = 0; index < opts.hemisphere; index++) {\n const light = new THREE.HemisphereLight(0xffffff, 0xffffff, 0)\n light.layers.enableAll()\n group.add(light)\n hemispheres.push(light)\n }\n scene.add(group)\n scene.children.splice(scene.children.indexOf(group), 1)\n scene.children.unshift(group)\n\n const sources = new Set<Holder>()\n const world = new THREE.Vector3()\n const direction = new THREE.Vector3()\n let sealed: Sealed | null = null\n let leasedHemispheres = 0\n\n const allSlots = (): Slot[] => [...core.slots.point, ...core.slots.spot]\n\n function writeHolder(holder: Holder): void {\n if (holder.slot !== null && holder.slot.holder === holder) writeLight(THREE, holder.slot, holder.values)\n }\n\n function makeHandle(holder: Holder, release: ((fadeMs: number | undefined) => void) | null): LightHandle {\n return {\n get slot() {\n return holder.slot?.index ?? -1\n },\n kind: holder.lightKind,\n get alive() {\n return holder.alive\n },\n update(patch: LightPatch) {\n if (!holder.alive) return\n mergeValues(holder.values, patch)\n writeHolder(holder)\n },\n release(releaseOptions) {\n if (!holder.alive || release === null) return\n holder.alive = false\n release(releaseOptions?.fadeMs)\n },\n }\n }\n\n function dropHolder(holder: Holder, fadeMs: number): void {\n const slot = holder.slot\n holder.slot = null\n if (slot === null) return\n if (slot.pending === holder) slot.pending = null\n else if (slot.holder === holder) vacate(slot, fadeMs)\n }\n\n function resolveSource(holder: Holder, focus: readonly [number, number, number]): void {\n const { follow, values, resolved } = holder\n holder.wanted = values.intensity > 0\n if (follow === undefined) {\n holder.distance = Math.hypot(values.position[0] - focus[0], values.position[1] - focus[1], values.position[2] - focus[2])\n Object.assign(resolved, values)\n return\n }\n holder.wanted = holder.wanted && isAttached(follow, scene)\n if (!holder.wanted) return\n follow.getWorldPosition(world)\n const [ox, oy, oz] = values.position\n if (ox !== 0 || oy !== 0 || oz !== 0) world.set(ox, oy, oz).applyMatrix4(follow.matrixWorld)\n const axis = follow.matrixWorld.elements\n direction.set(-(axis[8] as number), -(axis[9] as number), -(axis[10] as number))\n holder.distance = Math.hypot(world.x - focus[0], world.y - focus[1], world.z - focus[2])\n Object.assign(resolved, values)\n resolved.position = [world.x, world.y, world.z]\n resolved.target = values.target ?? [world.x + direction.x, world.y + direction.y, world.z + direction.z]\n }\n\n return {\n group,\n sizes: { point: opts.point, spot: opts.spot, pointShadows, spotShadows },\n acquire(request) {\n const holder = newHolder('request', request.kind ?? 'point', request, request.urgent === true)\n holder.onLost = request.onLost\n if (!admitRequest(core, holder)) return null\n return makeHandle(holder, (fadeMs) => dropHolder(holder, fadeMs ?? opts.fadeMs))\n },\n addSource(source) {\n const holder = newHolder('source', source.kind ?? 'point', source, false)\n holder.follow = source.follow\n holder.shadow = source.shadow === true\n sources.add(holder)\n return {\n get slot() {\n return holder.slot !== null && holder.slot.holder === holder ? holder.slot.index : -1\n },\n update(patch: Partial<LightSource>) {\n mergeValues(holder.values, patch)\n if (patch.priority !== undefined) holder.priority = patch.priority\n if ('follow' in patch) holder.follow = patch.follow\n if (holder.follow === undefined) writeHolder(holder)\n },\n remove() {\n holder.alive = false\n holder.wanted = false\n sources.delete(holder)\n dropHolder(holder, opts.fadeMs)\n },\n } satisfies SourceHandle\n },\n lease({ owner, point, shadows = 0 }) {\n const shadowSlots = core.slots.point.filter((slot) => slot.shadow && isFree(slot))\n const plainSlots = core.slots.point.filter((slot) => !slot.shadow && isFree(slot))\n if (shadowSlots.length < shadows || plainSlots.length < point - shadows) return null\n const taken = [...shadowSlots.slice(0, shadows), ...plainSlots.slice(0, point - shadows)]\n const holders = taken.map((slot) => {\n const holder = newHolder('lease', 'point', { owner, priority: Number.POSITIVE_INFINITY, color: 0xffffff, intensity: 0, distance: 0, position: ZERO }, false)\n slot.leased = true\n slot.holder = holder\n slot.fade = 1\n slot.fadeTarget = 1\n holder.slot = slot\n markShadow(slot)\n return holder\n })\n const handles = holders.map((holder) => makeHandle(holder, null))\n return {\n handles,\n invalidateShadow(index) {\n for (const [at, holder] of holders.entries()) if ((index === undefined || index === at) && holder.slot !== null) markShadow(holder.slot)\n },\n release() {\n for (const holder of holders) {\n const slot = holder.slot\n holder.alive = false\n holder.slot = null\n if (slot === null) continue\n slot.leased = false\n slot.holder = null\n vacate(slot, 0)\n }\n },\n } satisfies LightLease\n },\n leaseHemisphere() {\n const light = hemispheres[leasedHemispheres]\n if (light === undefined) return null\n leasedHemispheres++\n return light\n },\n present(focus, dtSeconds) {\n for (const holder of sources) resolveSource(holder, focus)\n for (const kind of ['point', 'spot'] as const) {\n const reserve = kind === 'point' ? core.urgentReserve : 0\n const kindSources = [...sources].filter((holder) => holder.lightKind === kind)\n arbitrateSources(core, poolOf(core, kind, true), kindSources.filter((holder) => holder.shadow), 0)\n arbitrateSources(core, poolOf(core, kind, false), kindSources.filter((holder) => !holder.shadow), reserve)\n }\n stepSlots(core, dtSeconds)\n for (const holder of sources) if (holder.wanted && holder.slot?.holder === holder) writeLight(THREE, holder.slot, holder.resolved)\n },\n seal(renderer, scene, sealOptions = {}) {\n sealed = captureSealed(renderer, scene, sealOptions)\n },\n check(renderer: RendererState, checkedScene: Scene) {\n const result = checkSealed(sealed, renderer, checkedScene, group)\n const layersIntact = allSlots().every((slot) => slot.light.visible && slot.light.layers.mask === ALL_LAYERS_MASK)\n const isFirst = checkedScene.children[0] === group\n if (!layersIntact) return { ...result, ok: false, actual: `${result.actual} | budget lights hidden or off a layer` }\n return isFirst ? result : { ...result, ok: false, actual: `${result.actual} | budget group is not the first child of the scene` }\n },\n stats() {\n const slots = allSlots()\n return {\n lit: slots.filter((slot) => slot.light.intensity > 0).length,\n free: slots.filter(isFree).length,\n leased: slots.filter((slot) => slot.leased).length,\n sources: sources.size,\n sourcesWithoutSlot: [...sources].filter((holder) => holder.wanted && holder.slot === null).length,\n preempted: core.preempted,\n refused: core.refused,\n }\n },\n dispose() {\n group.removeFromParent()\n for (const slot of allSlots()) slot.light.dispose()\n sources.clear()\n },\n }\n}\n","import type { Camera, Group, HemisphereLight, Object3D, Scene, WebGLRenderTarget } from 'three'\n\nimport type { ThreeLib } from '../three-lib'\n\nexport type LightKind = 'point' | 'spot'\nexport type LinearRgb = readonly [number, number, number]\nexport type FogState = 'none' | 'linear' | 'exp2'\nexport type ThreeForLights = Pick<\n ThreeLib,\n 'Group' | 'PointLight' | 'SpotLight' | 'HemisphereLight' | 'Object3D' | 'Vector3' | 'Color' | 'LinearSRGBColorSpace'\n>\n/** What the budget reads of a renderer: a structural subset, so a fake works in Node. */\nexport type RendererState = {\n readonly toneMapping: number\n readonly outputColorSpace: string\n readonly shadowMap: { readonly type: number }\n}\n\nexport interface LightBudgetOptions {\n /** Point lights created at boot. Default 16. */\n readonly point?: number\n /** Spot lights created at boot. Default 4. */\n readonly spot?: number\n /** How many of the point lights cast shadows (cube maps). Default 2. Fixed for the life of the budget. */\n readonly pointShadows?: number\n /** How many of the spot lights cast shadows. Default 0. */\n readonly spotShadows?: number\n /** Shadow map size of the shadow slots. Default 512. */\n readonly shadowMapSize?: number\n /** Bias, normal bias and camera near plane of the shadow slots. Defaults: three.js's (0, 0, 0.5). The house's room lights use -0.0012, 0.05 and 0.12. */\n readonly shadowSettings?: { readonly bias?: number; readonly normalBias?: number; readonly near?: number }\n /** Point slots only `urgent` requests may take while others are free. Default 2. */\n readonly urgentReserve?: number\n /** Milliseconds a light fades out when a source loses its slot, and fades in when it gets one. Default 120. */\n readonly fadeMs?: number\n /** A source keeps its slot until a challenger of the same priority is this much closer (0.15 = 15%). Default 0.15. */\n readonly hysteresis?: number\n /** HemisphereLights created at boot for adapters that flash the sky; leased with `leaseHemisphere`. Default 0. */\n readonly hemisphere?: number\n}\n\n/** A light that lives as long as the request: a blast, a rocket in flight, a muzzle flash, a flare in the hand. */\nexport interface LightRequest {\n readonly owner: string\n readonly kind?: LightKind\n /** Higher wins a slot; see LIGHT_PRIORITY. */\n readonly priority: number\n /** Hex (sRGB, like `new Color(hex)`) or linear RGB. */\n readonly color: number | LinearRgb\n readonly intensity: number\n readonly distance: number\n readonly decay?: number\n readonly position: readonly [number, number, number]\n /** Spot only. */\n readonly target?: readonly [number, number, number]\n readonly angle?: number\n readonly penumbra?: number\n /** Takes a slot at once: cuts the lowest victim instead of fading it, and may use the urgent reserve. */\n readonly urgent?: boolean\n /** Called once when a higher priority took the slot; the handle is dead from then on. */\n readonly onLost?: () => void\n}\n\nexport type LightPatch = Partial<Pick<LightRequest, 'color' | 'intensity' | 'distance' | 'decay' | 'position' | 'target' | 'angle' | 'penumbra'>>\n\nexport interface LightHandle {\n /** Index of this light among the scene's point (or spot) lights in the shader; stable while the handle lives. */\n readonly slot: number\n readonly kind: LightKind\n readonly alive: boolean\n update(patch: LightPatch): void\n /** Gives the slot back; with fadeMs the light fades first. Idempotent. */\n release(options?: { readonly fadeMs?: number }): void\n}\n\n/** A light that exists in the world for a long time and competes for a slot every frame: a lamp, a street light, a headlight. */\nexport interface LightSource extends Omit<LightRequest, 'urgent' | 'onLost'> {\n /** Wants a shadow slot; a shadow source competes for shadow slots only. */\n readonly shadow?: boolean\n /**\n * The object the light sits on. Its world position (and, for a spot, its world -z as the direction when `target` is absent) is read\n * once per `present`; `position` is then an offset in its local space. A source whose `follow` left the scene counts as off.\n */\n readonly follow?: Object3D\n}\n\nexport interface SourceHandle {\n /** Slot now, or -1 while it has none (its light is not drawn). */\n readonly slot: number\n update(patch: Partial<LightSource>): void\n remove(): void\n}\n\n/** Slots a client keeps for itself for good: the room lights of a house (their masks are indexed by slot). */\nexport interface LightLease {\n readonly handles: readonly LightHandle[]\n /** Redraws the shadow map of one leased slot (`handles[index]`), or of all of them, on the next render: the walls it shades changed. */\n invalidateShadow(index?: number): void\n release(): void\n}\n\nexport interface SealOptions {\n /** Fog states the game will switch between at run time. Default: only the state at seal time. */\n readonly fogStates?: readonly FogState[]\n /** Cameras whose `far` must stay under the neutral fog's near (read at every `check`). */\n readonly cameras?: readonly Camera[]\n /** Where the game really draws; its colour space is part of the sealed state. */\n readonly target?: WebGLRenderTarget | null\n}\n\nexport interface LightCheck {\n readonly ok: boolean\n readonly expected: string\n readonly actual: string\n /** Paths of PointLight/SpotLight found outside the budget's group. */\n readonly strays: readonly string[]\n}\n\nexport interface LightBudgetStats {\n readonly lit: number\n readonly free: number\n readonly leased: number\n readonly sources: number\n readonly sourcesWithoutSlot: number\n readonly preempted: number\n readonly refused: number\n}\n\nexport interface LightBudget {\n /** The group holding every light; first child of the scene. Never hidden, never removed while the budget lives. */\n readonly group: Group\n readonly sizes: { readonly point: number; readonly spot: number; readonly pointShadows: number; readonly spotShadows: number }\n acquire(request: LightRequest): LightHandle | null\n addSource(source: LightSource): SourceHandle\n /** Takes `point` slots (of which `shadows` shadow slots) for good. null when not enough unleased slots remain. */\n lease(options: { readonly owner: string; readonly point: number; readonly shadows?: number }): LightLease | null\n /** Takes one of the boot HemisphereLights for good. null when none is left. Its intensity starts at 0. */\n leaseHemisphere(owner: string): HemisphereLight | null\n /** Once per frame, with the camera (or the player) as focus. `dtSeconds` is real time: fades do not stop in pause. */\n present(focus: readonly [number, number, number], dtSeconds: number): void\n /** After this, any change in the program-key state of the scene is a bug and `check()` reports it. */\n seal(renderer: RendererState, scene: Scene, options?: SealOptions): void\n check(renderer: RendererState, scene: Scene): LightCheck\n stats(): LightBudgetStats\n dispose(): void\n}\n\nexport const LIGHT_PRIORITY = {\n blast: 900,\n rocket: 800,\n muzzle: 750,\n fire: 600,\n flare: 500,\n headlight: 400,\n weaponLight: 400,\n lamp: 200,\n street: 150,\n} as const\n","import type { LightBudget } from './types'\n\n/** For adapters that receive the budget as `unknown` through the host (the contract does not know three). */\nexport function isLightBudget(value: unknown): value is LightBudget {\n const candidate = value as Partial<LightBudget> | null | undefined\n return typeof candidate === 'object' && candidate !== null && typeof candidate.acquire === 'function' && typeof candidate.addSource === 'function' && typeof candidate.lease === 'function' && typeof candidate.present === 'function'\n}\n","import type { Material } from 'three'\n\n/** What `programKeysOf` reads of a renderer: `properties` is internal to three r160 and may be absent in another version. */\nexport type PropertiesReader = { readonly properties?: { get(object: object): unknown } }\n\n/**\n * Every program cache key three linked for `material` (one per state it was drawn in: fog type, shadow, light counts). Reads three's\n * internal `properties.get(material).programs` Map (r160). `[]` for a material never drawn; `undefined` when this three does not have\n * that internal, which sends the pools to their conservative mode.\n */\nexport function programKeysOf(renderer: PropertiesReader, material: Material): readonly string[] | undefined {\n const properties = renderer.properties\n if (typeof properties?.get !== 'function') return undefined\n const programs = (properties.get(material) as { programs?: unknown } | undefined)?.programs\n if (programs === undefined) return []\n if (!(programs instanceof Map)) return undefined\n return [...programs.keys()].map(String)\n}\n","import type { Material } from 'three'\n\nimport { type PropertiesReader, programKeysOf } from '../program-key'\n\n/** Materials kept alive and never disposed, one per program family: what keeps a program linked once its users are gone. */\nexport interface MaterialAnchors {\n /**\n * Keeps `material` if any of its program keys has no anchor yet; returns true when it was kept (the caller must then not dispose it).\n * A material whose keys are all covered returns false and may be disposed. A material never drawn is not kept.\n */\n offer(material: Material): boolean\n readonly size: number\n /** Where program keys are read from. Until bound (or when three has no readable keys) every offered material is kept. */\n bind(renderer: PropertiesReader): void\n}\n\nexport function createMaterialAnchors(renderer?: PropertiesReader): MaterialAnchors {\n const anchors = new Set<Material>()\n let reader = renderer\n\n function coveredKeys(): Set<string> {\n const covered = new Set<string>()\n if (reader === undefined) return covered\n for (const anchor of anchors) for (const key of programKeysOf(reader, anchor) ?? []) covered.add(key)\n return covered\n }\n\n return {\n get size() {\n return anchors.size\n },\n bind(next) {\n reader = next\n },\n offer(material) {\n if (anchors.has(material)) return true\n const keys = reader === undefined ? undefined : programKeysOf(reader, material)\n if (keys === undefined) {\n anchors.add(material)\n return true\n }\n if (keys.length === 0) return false\n const covered = coveredKeys()\n if (keys.every((key) => covered.has(key))) return false\n anchors.add(material)\n return true\n },\n }\n}\n","import type { Object3D } from 'three'\n\nimport type { ThreeLib } from './three-lib'\nimport type { WarmupProbe } from './warmup-types'\n\n/** The sprite probes the room builds by hand today: one sprite material with fog and one without. */\nexport function spriteProbes(THREE: Pick<ThreeLib, 'Group' | 'Sprite' | 'SpriteMaterial' | 'DataTexture'>): WarmupProbe {\n return {\n id: 'sprite',\n build() {\n const group = new THREE.Group()\n const texture = new THREE.DataTexture(new Uint8Array([255, 255, 255, 255]), 1, 1)\n texture.needsUpdate = true\n const materials = [true, false].map((fog) => new THREE.SpriteMaterial({ map: texture, fog, transparent: true }))\n for (const material of materials) group.add(new THREE.Sprite(material))\n return { group, materials, dispose: () => texture.dispose() }\n },\n }\n}\n\nconst SHADOW_PROBE_SIDES = ['FrontSide', 'BackSide', 'DoubleSide'] as const\n\n/**\n * Shadow casters drawn into every shadow map at load: a lit material with and without a map, on each side, plain and instanced. three r160 links the\n * depth (directional, spot) and distance (point) programs only in the shadow pass (`compile` never does), keyed by the caster's map and side. And the\n * shadow pass draws every caster with one shared depth material whose program it picks again only when the caster switches between plain and\n * instanced (or skinned, batched): a textured caster drawn right after a plain one keeps the plain program, and the `USE_MAP` one links later, in play,\n * the first time a textured wall follows an instanced caster (the debris of a blast). Each probe here follows a caster of the other kind, so every\n * variant is picked and linked at load.\n */\nexport function shadowCasterProbes(\n THREE: Pick<ThreeLib, 'Group' | 'Mesh' | 'InstancedMesh' | 'MeshLambertMaterial' | 'DataTexture' | 'BufferGeometry' | 'BufferAttribute' | (typeof SHADOW_PROBE_SIDES)[number]>,\n): WarmupProbe {\n return {\n id: 'shadow-casters',\n build() {\n const group = new THREE.Group()\n const texture = new THREE.DataTexture(new Uint8Array([255, 255, 255, 255]), 1, 1)\n texture.needsUpdate = true\n const geometry = new THREE.BufferGeometry()\n geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array([0, 0, 0, 0.001, 0, 0, 0, 0.001, 0]), 3))\n geometry.setAttribute('uv', new THREE.BufferAttribute(new Float32Array([0, 0, 1, 0, 0, 1]), 2))\n const materials = SHADOW_PROBE_SIDES.flatMap((side) => [undefined, texture].map((map) => new THREE.MeshLambertMaterial({ side: THREE[side], ...(map ? { map } : {}) })))\n const instanced: Array<InstanceType<typeof THREE.InstancedMesh>> = []\n for (const material of materials) {\n // instanced, then plain: the shadow pass picks the depth program again for each, with this material's map and side\n const batch = new THREE.InstancedMesh(geometry, material, 1)\n instanced.push(batch)\n for (const caster of [batch, new THREE.Mesh(geometry, material)]) {\n caster.castShadow = true\n caster.receiveShadow = true\n // inside every shadow camera, wherever the lights are\n caster.frustumCulled = false\n group.add(caster)\n }\n }\n return {\n group,\n materials,\n dispose() {\n // the instance matrices are buffers of their own\n for (const batch of instanced) batch.dispose()\n geometry.dispose()\n texture.dispose()\n },\n }\n },\n }\n}\n\nexport function hasMissingDistanceMaterial(root: Object3D): string | undefined {\n let found: string | undefined\n root.traverse((object) => {\n const mesh = object as { isInstancedMesh?: boolean; castShadow?: boolean; customDepthMaterial?: unknown; customDistanceMaterial?: unknown }\n if (found === undefined && mesh.isInstancedMesh === true && mesh.castShadow === true && mesh.customDepthMaterial && !mesh.customDistanceMaterial) found = object.name || object.type\n })\n return found\n}\n","import type { BufferGeometry, Camera, Material, Object3D, Scene } from 'three'\n\nimport { fogStateOf, lightSignature } from './lights/scene-state'\nimport type { FogState } from './lights/types'\nimport { createMaterialAnchors } from './pools/anchors'\nimport { hasMissingDistanceMaterial } from './probes'\nimport type { ThreeLib } from './three-lib'\nimport type { EffectWarmup, ProgramWarmup, WarmupContext, WarmupOptions, WarmupProbe, WarmupReport, WarmupRenderer } from './warmup-types'\n\nconst EFFECT_STEP_SECONDS = 1 / 50\nconst DEFAULT_EFFECT_FRAMES = 3\nconst WARM_FOG_DENSITY = 0.01\nconst WARM_FOG_FAR = 100\n\ntype LinkCounter = { count: number }\ntype BuiltProbe = { readonly probe: WarmupProbe; readonly built: ReturnType<WarmupProbe['build']> }\n\nfunction register<TItem>(items: Set<TItem>, item: TItem): () => void {\n items.add(item)\n return () => void items.delete(item)\n}\n\nfunction countLinks(context: WarmupContext, counters: WeakMap<WarmupContext, LinkCounter>): void {\n const existing = counters.get(context)\n if (existing !== undefined) {\n existing.count = 0\n return\n }\n const counter: LinkCounter = { count: 0 }\n counters.set(context, counter)\n const original = context.linkProgram.bind(context)\n context.linkProgram = (program) => {\n counter.count++\n original(program)\n }\n}\n\nfunction failedProgram(renderer: WarmupRenderer): string | undefined {\n for (const program of renderer.info.programs ?? []) {\n const diagnostics = (program as { diagnostics?: { runnable?: boolean; programLog?: string } }).diagnostics\n if (diagnostics?.runnable === false) return diagnostics.programLog ?? 'program failed to link'\n }\n return undefined\n}\n\n/**\n * Finishes every program the renderer holds: three.js links a program when a material first compiles, but reads its link status, its logs and its\n * uniform locations only on the program's first draw (`getUniforms`), and that read waits for the driver to end the link: ~7 ms a program on the\n * RTX 5070 laptop, 43 ms for the six shadow-receiving programs the horde chain's first blast drew for the first time (perf.mjs, 2026-11-03).\n * A program linked here and drawn only in play (a hidden part of a vehicle, an effect of another area) pays that at load instead.\n */\nfunction finishPrograms(renderer: WarmupRenderer): number {\n let finished = 0\n for (const program of renderer.info.programs ?? []) {\n const linked = program as { getUniforms?: () => unknown; getAttributes?: () => unknown }\n if (typeof linked.getUniforms !== 'function') continue\n linked.getUniforms()\n linked.getAttributes?.()\n finished++\n }\n return finished\n}\n\nexport function createProgramWarmup(THREE: Pick<ThreeLib, 'Group' | 'Sprite' | 'SpriteMaterial' | 'DataTexture' | 'Fog' | 'FogExp2' | 'Mesh' | 'Points' | 'LineSegments' | 'BufferGeometry' | 'BufferAttribute'>): ProgramWarmup {\n const probes = new Set<WarmupProbe>()\n const effects = new Set<EffectWarmup>()\n const textures = new Set<Parameters<WarmupRenderer['initTexture']>[0]>()\n const anchors = createMaterialAnchors()\n const linkCounters = new WeakMap<WarmupContext, LinkCounter>()\n\n function setFog(scene: Scene, state: FogState): void {\n const color = scene.fog?.color.getHex() ?? 0\n if (state === 'none') scene.fog = null\n else if (state === 'linear' && (scene.fog as { isFog?: boolean } | null)?.isFog !== true) scene.fog = new THREE.Fog(color, 1, WARM_FOG_FAR)\n else if (state === 'exp2' && (scene.fog as { isFogExp2?: boolean } | null)?.isFogExp2 !== true) scene.fog = new THREE.FogExp2(color, WARM_FOG_DENSITY)\n }\n\n function draw(renderer: WarmupRenderer, scene: Scene, camera: Camera, target: WarmupOptions['target']): void {\n renderer.setRenderTarget(target ?? null)\n renderer.compile(scene, camera)\n renderer.render(scene, camera)\n }\n\n /**\n * Hides every drawable of the scene outside `root` and returns the undo. An object with a light under it stays: the lights are what the programs\n * are keyed by, and hiding one would warm programs for a light count the game never draws.\n */\n function drawOnly(scene: Scene, root: Object3D): () => void {\n const hidden: Object3D[] = []\n const visit = (object: Object3D): void => {\n if (object === root || !object.visible) return\n const drawable = object as Object3D & { isMesh?: boolean; isPoints?: boolean; isLine?: boolean; isSprite?: boolean }\n if (drawable.isMesh === true || drawable.isPoints === true || drawable.isLine === true || drawable.isSprite === true) {\n if (!holdsLight(object) && !holdsObject(object, root)) {\n object.visible = false\n hidden.push(object)\n return\n }\n }\n for (const child of object.children) visit(child)\n }\n for (const child of scene.children) visit(child)\n return () => hidden.forEach((object) => (object.visible = true))\n }\n\n function holdsLight(object: Object3D): boolean {\n let found = false\n object.traverse((each) => {\n if ((each as { isLight?: boolean }).isLight === true) found = true\n })\n return found\n }\n\n function holdsObject(object: Object3D, target: Object3D): boolean {\n for (let at: Object3D | null = target; at !== null; at = at.parent) if (at === object) return true\n return false\n }\n\n function playEffect(renderer: WarmupRenderer, scene: Scene, camera: Camera, effect: EffectWarmup, target: WarmupOptions['target']): void {\n const root = effect.root?.()\n const restore = root === null || root === undefined ? (): void => undefined : drawOnly(scene, root)\n try {\n playFrames(renderer, scene, camera, effect, target)\n } finally {\n restore()\n }\n }\n\n function playFrames(renderer: WarmupRenderer, scene: Scene, camera: Camera, effect: EffectWarmup, target: WarmupOptions['target']): void {\n effect.play()\n try {\n for (let frame = 0; frame < (effect.frames ?? DEFAULT_EFFECT_FRAMES); frame++) {\n effect.step(EFFECT_STEP_SECONDS)\n renderer.setRenderTarget(target ?? null)\n renderer.render(scene, camera)\n }\n } finally {\n effect.stop()\n }\n }\n\n /** One object per material, of the kind its program is for, each a single triangle: drawn once so that the program is used, not only linked. */\n function materialsProbe(materials: readonly Material[]): BuiltProbe {\n const geometry = new THREE.BufferGeometry()\n geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array([0, 0, 0, 0.001, 0, 0, 0, 0.001, 0]), 3))\n const group = new THREE.Group()\n for (const material of materials) group.add(drawableOf(material, geometry))\n return { probe: { id: 'materials', build: () => ({ group, materials: [], dispose: () => geometry.dispose() }) }, built: { group, materials: [], dispose: () => geometry.dispose() } }\n }\n\n function drawableOf(material: Material, geometry: BufferGeometry): Object3D {\n const flags = material as { isSpriteMaterial?: boolean; isPointsMaterial?: boolean; isLineBasicMaterial?: boolean }\n const object: Object3D =\n flags.isSpriteMaterial === true ? new THREE.Sprite(material as never)\n : flags.isPointsMaterial === true ? new THREE.Points(geometry, material)\n : flags.isLineBasicMaterial === true ? new THREE.LineSegments(geometry, material)\n : new THREE.Mesh(geometry, material)\n object.frustumCulled = false\n return object\n }\n\n function buildProbes(materials: readonly Material[] | undefined): BuiltProbe[] {\n const built = [...probes].map((probe) => ({ probe, built: probe.build() }))\n if (materials !== undefined && materials.length > 0) built.push(materialsProbe(materials))\n return built\n }\n\n function addProbes(scene: Scene, built: readonly BuiltProbe[]): void {\n for (const { probe, built: item } of built) {\n const missing = hasMissingDistanceMaterial(item.group)\n if (missing !== undefined) throw new Error(`warmup probe \"${probe.id}\": instanced mesh \"${missing}\" casts shadows with a customDepthMaterial but no customDistanceMaterial`)\n scene.add(item.group)\n }\n }\n\n function removeProbes(scene: Scene, built: readonly BuiltProbe[]): void {\n for (const { built: item } of built) {\n scene.remove(item.group)\n item.dispose()\n for (const material of item.materials) anchors.offer(material)\n }\n }\n\n function drawStates(renderer: WarmupRenderer, scene: Scene, camera: Camera, states: readonly FogState[], options: WarmupOptions): void {\n states.forEach((state, index) => {\n setFog(scene, state)\n // the depth and distance programs carry no fog: every caster once, in the first state, is enough\n const restoreCasters = index === 0 && options.shadowCasters !== 'visible' ? drawEveryCaster(scene) : (): void => undefined\n try {\n draw(renderer, scene, camera, options.target)\n } finally {\n restoreCasters()\n }\n })\n }\n\n /**\n * Turns off frustum culling of every shadow caster and returns the undo: three r160 links a caster's depth (or distance) program only when the\n * shadow pass draws it, and that pass culls by the light's shadow camera. A caster outside it at load (the sun's box follows the player) would\n * link its program the first time it enters the box, in play.\n */\n function drawEveryCaster(scene: Scene): () => void {\n const culled: Object3D[] = []\n scene.traverse((object) => {\n if (object.castShadow && object.frustumCulled) {\n object.frustumCulled = false\n culled.push(object)\n }\n })\n return () => culled.forEach((object) => (object.frustumCulled = true))\n }\n\n /** Makes every instanced batch draw at least once: three skips an empty instanced batch, and a driver finishes a program's state on its first real draw (a 200 ms stall). Returns the undo. */\n function forceDraws(scene: Scene): () => void {\n const undo: Array<() => void> = []\n scene.traverse((object) => {\n const drawable = object as Object3D & { isInstancedMesh?: boolean; count?: number; geometry?: { isInstancedBufferGeometry?: boolean; instanceCount?: number } }\n const { geometry } = drawable\n if (geometry?.isInstancedBufferGeometry === true && geometry.instanceCount === 0) {\n geometry.instanceCount = 1\n undo.push(() => (geometry.instanceCount = 0))\n }\n if (drawable.isInstancedMesh === true && drawable.count === 0) {\n drawable.count = 1\n undo.push(() => (drawable.count = 0))\n }\n })\n return () => undo.forEach((restore) => restore())\n }\n\n return {\n anchors,\n register: (probe) => register(probes, probe),\n registerEffect: (effect) => register(effects, effect),\n registerTexture: (texture) => register(textures, texture),\n warmUp(renderer, scene, camera, options = {}): WarmupReport {\n const started = performance.now()\n const { lights, target } = options\n anchors.bind(renderer)\n const originalFog = scene.fog\n const states = options.fogStates ?? [fogStateOf(scene)]\n lights?.seal(renderer, scene, { fogStates: options.fogStates, cameras: [camera], target })\n scene.traverse((object) => {\n const light = object as { castShadow?: boolean; shadow?: { needsUpdate: boolean } }\n if (light.castShadow === true && light.shadow !== undefined) light.shadow.needsUpdate = true\n })\n const built = buildProbes(options.materials)\n let restoreDraws = (): void => undefined\n try {\n addProbes(scene, built)\n restoreDraws = forceDraws(scene)\n drawStates(renderer, scene, camera, states, options)\n scene.fog = originalFog\n for (const effect of effects) playEffect(renderer, scene, camera, effect, target)\n for (const texture of textures) renderer.initTexture(texture)\n } finally {\n restoreDraws()\n scene.fog = originalFog\n removeProbes(scene, built)\n }\n // also what lets failedProgram see a broken link: three only fills `diagnostics` on the first use\n finishPrograms(renderer)\n const context = renderer.getContext()\n const uniformVectors = Number(context.getParameter(context.MAX_FRAGMENT_UNIFORM_VECTORS))\n const failure = failedProgram(renderer)\n if (failure !== undefined) {\n throw new Error(`a shader program failed to link (MAX_FRAGMENT_UNIFORM_VECTORS ${uniformVectors}, lights: ${lightSignature(scene)}): ${failure}`)\n }\n countLinks(context, linkCounters)\n // the GPU process is still working through all of the above: wait here, at load, or the first upload of play stalls on it\n if (context.RGBA !== undefined && context.UNSIGNED_BYTE !== undefined) context.readPixels?.(0, 0, 1, 1, context.RGBA, context.UNSIGNED_BYTE, new Uint8Array(4))\n return {\n programs: renderer.info.programs?.length ?? 0,\n geometries: renderer.info.memory.geometries,\n textures: renderer.info.memory.textures,\n milliseconds: performance.now() - started,\n lightSignature: lightSignature(scene),\n uniformVectors,\n anchors: anchors.size,\n }\n },\n linkedSince(renderer) {\n return linkCounters.get(renderer.getContext())?.count ?? 0\n },\n }\n}\n","const POOLED = '__pooled'\n\ntype Disposable = { dispose(): void; userData: Record<string, unknown> }\n\nfunction isDevelopment(): boolean {\n return typeof process === 'undefined' || process.env.NODE_ENV !== 'production'\n}\n\n/** Marks a pool resource and, in development, warns when something disposes it directly instead of releasing it to the pool. */\nexport function markPooled(resource: Disposable, key: string, owner: string): { disposeForPool(): void } {\n resource.userData[POOLED] = key\n const original = resource.dispose.bind(resource)\n let fromPool = false\n if (isDevelopment()) {\n resource.dispose = () => {\n if (!fromPool) console.warn(`[game-render-three] ${owner} \"${key}\" was disposed directly; release it to its pool instead`)\n original()\n }\n }\n return {\n disposeForPool() {\n fromPool = true\n original()\n fromPool = false\n },\n }\n}\n\nexport function pooledKey(resource: { userData: Record<string, unknown> }): string | undefined {\n const key = resource.userData[POOLED]\n return typeof key === 'string' ? key : undefined\n}\n\n/** A number as a short stable string, rounded to `step`. */\nexport function roundedNumber(value: number, step: number): string {\n return String(Number((Math.round(value / step) * step).toFixed(6)))\n}\n","import type { BufferGeometry } from 'three'\n\nimport { markPooled, pooledKey, roundedNumber } from './pooled'\n\nexport interface GeometryPool {\n /** The geometry for `key`, built once with `build`. Counts one use. */\n acquire(key: string, build: () => BufferGeometry): BufferGeometry\n release(geometry: BufferGeometry): void\n /** Never disposed while the pool lives (unit shapes, effect geometries warmed at load). */\n retain(key: string): void\n /** Disposes unretained geometries with no use, oldest first, keeping at most `keep` idle ones. Only at load points, never in play. */\n trim(keep?: number): number\n stats(): { readonly entries: number; readonly retained: number; readonly inUse: number }\n dispose(): void\n}\n\ntype Entry = { geometry: BufferGeometry; uses: number; retained: boolean; idleSince: number; disposeForPool(): void }\n\nconst DEFAULT_KEY_STEP = 1e-3\n\n/** Builds a key from a kind and its numbers, rounded to `step`, so near-equal sizes share one geometry. */\nexport function geometryKey(kind: string, params: readonly number[], step: number = DEFAULT_KEY_STEP): string {\n return [kind, ...params.map((value) => roundedNumber(value, step))].join('|')\n}\n\nexport function createGeometryPool(): GeometryPool {\n const entries = new Map<string, Entry>()\n let clock = 0\n\n function disposeEntry(key: string, entry: Entry): void {\n entries.delete(key)\n entry.disposeForPool()\n }\n\n return {\n acquire(key, build) {\n let entry = entries.get(key)\n if (entry === undefined) {\n const geometry = build()\n entry = { geometry, uses: 0, retained: false, idleSince: 0, ...markPooled(geometry, key, 'geometry') }\n entries.set(key, entry)\n }\n entry.uses++\n return entry.geometry\n },\n release(geometry) {\n const key = pooledKey(geometry)\n const entry = key === undefined ? undefined : entries.get(key)\n if (entry === undefined || entry.uses === 0) return\n entry.uses--\n if (entry.uses === 0) entry.idleSince = ++clock\n },\n retain(key) {\n const entry = entries.get(key)\n if (entry !== undefined) entry.retained = true\n },\n trim(keep = 0) {\n const idle = [...entries].filter(([, entry]) => entry.uses === 0 && !entry.retained).sort((a, b) => a[1].idleSince - b[1].idleSince)\n const excess = idle.slice(0, Math.max(0, idle.length - keep))\n for (const [key, entry] of excess) disposeEntry(key, entry)\n return excess.length\n },\n stats() {\n const all = [...entries.values()]\n return { entries: all.length, retained: all.filter((entry) => entry.retained).length, inUse: all.filter((entry) => entry.uses > 0).length }\n },\n dispose() {\n for (const [key, entry] of [...entries]) disposeEntry(key, entry)\n },\n }\n}\n","import type { Material } from 'three'\n\nimport type { PropertiesReader } from '../program-key'\nimport { type MaterialAnchors, createMaterialAnchors } from './anchors'\nimport { markPooled, pooledKey, roundedNumber } from './pooled'\n\nexport interface MaterialPool {\n /**\n * The material for `key`, built once. Shared: callers must not change it. Per-instance variety goes into instance attributes, not\n * into new materials.\n */\n acquire<TMaterial extends Material>(key: string, build: () => TMaterial): TMaterial\n release(material: Material): void\n /** Declares a variant that must never be disposed (its program stays linked). Effects register theirs at load. */\n register<TMaterial extends Material>(key: string, build: () => TMaterial): TMaterial\n /**\n * A material the caller owns and changes per frame (a puff's opacity): not shared. On `release` the first one of its program family is\n * handed to the anchors, so disposing the others never frees the program.\n */\n own<TMaterial extends Material>(build: () => TMaterial): TMaterial\n /** The materials declared with `register`: the ones that must never be disposed and whose programs the warmup draws once. */\n registeredMaterials?(): readonly Material[]\n /** Disposes unregistered materials with no use, oldest first, keeping at most `keep` idle ones; a family's anchor is kept alive. */\n trim(keep?: number): number\n stats(): { readonly entries: number; readonly registered: number; readonly inUse: number; readonly families: number }\n /**\n * The end of the pool: disposes every material it made, in use or not, registered or anchored (the guarantee that a program stays linked\n * holds while the pool lives, not after it). The anchors object itself is not touched, and the pool is empty and usable again afterwards.\n */\n dispose(): void\n}\n\nexport type MaterialPoolOptions = { readonly anchors?: MaterialAnchors; readonly renderer?: PropertiesReader }\n\ntype Entry = { material: Material; uses: number; registered: boolean; idleSince: number; disposeForPool(): void }\n\nconst DEFAULT_KEY_STEP = 1e-3\n\n/** Key from the material class and every parameter that changes its look, sorted, numbers rounded. */\nexport function materialKey(type: string, params: Readonly<Record<string, unknown>>): string {\n const parts = Object.keys(params)\n .sort()\n .map((name) => {\n const value = params[name]\n return `${name}=${typeof value === 'number' ? roundedNumber(value, DEFAULT_KEY_STEP) : JSON.stringify(value)}`\n })\n return [type, ...parts].join('|')\n}\n\nexport function createMaterialPool(options: MaterialPoolOptions = {}): MaterialPool {\n const anchors = options.anchors ?? createMaterialAnchors()\n if (options.renderer !== undefined) anchors.bind(options.renderer)\n const entries = new Map<string, Entry>()\n const owned = new Map<Material, () => void>()\n let clock = 0\n\n function createEntry(key: string, material: Material, registered: boolean): Entry {\n const entry: Entry = { material, uses: 0, registered, idleSince: 0, ...markPooled(material, key, 'material') }\n entries.set(key, entry)\n return entry\n }\n\n /** Disposes the material unless it is the anchor of a program family. */\n function retire(material: Material, disposeForPool: () => void): boolean {\n if (anchors.offer(material)) return false\n disposeForPool()\n return true\n }\n\n return {\n acquire(key, build) {\n const entry = entries.get(key) ?? createEntry(key, build(), false)\n entry.uses++\n return entry.material as ReturnType<typeof build>\n },\n register(key, build) {\n const entry = entries.get(key) ?? createEntry(key, build(), true)\n entry.registered = true\n return entry.material as ReturnType<typeof build>\n },\n own(build) {\n const material = build()\n owned.set(material, markPooled(material, 'own', 'material').disposeForPool)\n return material\n },\n release(material) {\n const disposeOwned = owned.get(material)\n if (disposeOwned !== undefined) {\n owned.delete(material)\n retire(material, disposeOwned)\n return\n }\n const key = pooledKey(material)\n const entry = key === undefined ? undefined : entries.get(key)\n if (entry === undefined || entry.uses === 0) return\n entry.uses--\n if (entry.uses === 0) entry.idleSince = ++clock\n },\n trim(keep = 0) {\n const idle = [...entries].filter(([, entry]) => entry.uses === 0 && !entry.registered).sort((a, b) => a[1].idleSince - b[1].idleSince)\n let disposed = 0\n for (const [key, entry] of idle.slice(0, Math.max(0, idle.length - keep))) {\n entries.delete(key)\n if (retire(entry.material, entry.disposeForPool)) disposed++\n }\n return disposed\n },\n registeredMaterials() {\n return [...entries.values()].filter((entry) => entry.registered).map((entry) => entry.material)\n },\n stats() {\n const all = [...entries.values()]\n return {\n entries: all.length,\n registered: all.filter((entry) => entry.registered).length,\n inUse: all.filter((entry) => entry.uses > 0).length,\n families: anchors.size,\n }\n },\n dispose() {\n for (const entry of entries.values()) entry.disposeForPool()\n for (const disposeOwned of owned.values()) disposeOwned()\n entries.clear()\n owned.clear()\n },\n }\n}\n","import type { GeometryPool } from './geometry'\nimport type { MaterialPool } from './material'\n\n/** The pools a host lends its adapters (`host.pools`): geometries and materials that outlive the effect that asked for them. */\nexport interface RenderPools {\n readonly geometries: GeometryPool\n readonly materials: MaterialPool\n}\n\n/** For adapters that receive the pools as `unknown` through the host (the contract does not know three). */\nexport function isRenderPools(value: unknown): value is RenderPools {\n const candidate = value as Partial<RenderPools> | null | undefined\n return typeof candidate === 'object' && candidate !== null && typeof candidate.geometries?.acquire === 'function' && typeof candidate.materials?.acquire === 'function'\n}\n","/** The part of a WebGL2 context the pacer reads; the renderer's `getContext()` satisfies it. */\nexport type FramePacerContext = {\n readonly SYNC_GPU_COMMANDS_COMPLETE: number\n readonly TIMEOUT_EXPIRED: number\n fenceSync(condition: number, flags: number): WebGLSync | null\n clientWaitSync(sync: WebGLSync, flags: number, timeout: number): number\n deleteSync(sync: WebGLSync | null): void\n flush(): void\n}\n\nexport type FramePacerOptions = {\n /** Most frames in a row the pacer may hold back before it lets one through (default 3), so a stuck fence cannot freeze the picture. */\n readonly maxSkips?: number\n /** Frames the GPU may be behind before a draw is held back (default 2). The browser reports a fence only some 20 ms after the GPU finished it, so 1 would cap every GPU at one frame per report. */\n readonly framesInFlight?: number\n}\n\nexport type FramePacer = {\n /** True when fewer than `framesInFlight` drawn frames are unfinished: draw this frame. False: the GPU is too far behind, skip the draw and keep simulating. */\n ready(): boolean\n /** Fences the frame just drawn; call it right after the render. */\n submitted(): void\n /** Draws held back so far. */\n readonly skipped: number\n dispose(): void\n}\n\nconst DEFAULT_MAX_SKIPS = 3\nconst DEFAULT_FRAMES_IN_FLIGHT = 2\n\n/**\n * Keeps the GPU a few frames behind the CPU at most. A frame loop that draws as fast as it can (no vsync, as the perf runs do, or a slow GPU) fills the driver's queue and\n * then blocks in the compositor for the length of the whole queue: a run of 5 ms frames and a 150 ms one. Holding back the draw while the last frame is unfinished spends that\n * time on the next simulation step instead, and the longest frame is the GPU's own. A context without fences (WebGL1) is never held back.\n */\nexport function createFramePacer(context: FramePacerContext | null, options: FramePacerOptions = {}): FramePacer {\n const maxSkips = options.maxSkips ?? DEFAULT_MAX_SKIPS\n const framesInFlight = options.framesInFlight ?? DEFAULT_FRAMES_IN_FLIGHT\n const fences: WebGLSync[] = []\n let skippedInRow = 0\n let skipped = 0\n const dropOldest = (): void => {\n const oldest = fences.shift()\n if (oldest && context) context.deleteSync(oldest)\n }\n return {\n ready() {\n if (!context) return true\n while (fences.length > 0 && context.clientWaitSync(fences[0] as WebGLSync, 0, 0) !== context.TIMEOUT_EXPIRED) dropOldest()\n if (fences.length >= framesInFlight && skippedInRow < maxSkips) {\n skippedInRow++\n skipped++\n return false\n }\n skippedInRow = 0\n if (fences.length >= framesInFlight) dropOldest()\n return true\n },\n submitted() {\n if (!context || typeof context.fenceSync !== 'function') return\n const fence = context.fenceSync(context.SYNC_GPU_COMMANDS_COMPLETE, 0)\n if (fence) fences.push(fence)\n context.flush()\n },\n get skipped() {\n return skipped\n },\n dispose() {\n while (fences.length > 0) dropOldest()\n },\n }\n}\n","import type { Bone, BufferAttribute, BufferGeometry, Material, Matrix3, Matrix4, Mesh, Object3D, SkinnedMesh } from 'three'\n\nimport type { ThreeLib } from './three-lib'\n\n/** The layer a batched mesh is moved to: no camera draws it, a raycaster that enables every layer still finds it. */\nexport const BATCHED_LAYER = 30\n\nconst MATRIX_EPSILON = 1e-6\n\nexport type StaticBatcherOptions = {\n /** Which meshes may be batched (default every shown mesh with one material and no instancing, skinning or morphing). */\n readonly include?: (mesh: Mesh) => boolean\n /** Milliseconds of merging per `update` (default all at once, in the call): batches are made a material at a time over the next frames. */\n readonly budgetMs?: number\n /**\n * The meshes move on their own (a body posed bone by bone): each batch is skinned to its meshes, so a mesh carries its part of the batch\n * wherever it goes, and only a new geometry, material, dent or hiding gives it its own draw back.\n */\n readonly followMeshes?: boolean\n /**\n * What tells materials apart for batching (default each material by itself, its `uuid`). Meshes whose materials give the same key are drawn in one batch with the\n * first one's material, so a key must be the same only for materials that draw the same (copies of one material with equal settings).\n */\n readonly materialKey?: (material: Material) => string\n /** Called with each batch as it is made and the meshes it draws (to mark where it comes from, for one). */\n readonly onBatch?: (batch: Mesh, meshes: readonly Mesh[]) => void\n}\n\nexport type StaticBatcherStats = { readonly batches: number; readonly batched: number; readonly released: number }\n\nexport type StaticBatcher = {\n /** The batch meshes, a child of the root. */\n readonly group: Object3D\n /**\n * Gives back to its own draw every batched mesh that changed since the batch was made (moved, dented, hidden, given another geometry or\n * material); returns how many it released. Call it once per frame, before the render.\n */\n update(): number\n stats(): StaticBatcherStats\n /** Every mesh draws on its own again and the batches are disposed. */\n dispose(): void\n}\n\ntype Source = {\n readonly mesh: Mesh\n readonly geometry: BufferGeometry\n readonly material: Material\n readonly version: number\n readonly local: Matrix4\n /** The mesh's world matrix when last seen unchanged: equal again, nothing moved and the local check is skipped. */\n readonly world: Matrix4\n readonly mask: number\n readonly batch: Batch\n readonly start: number\n readonly count: number\n released: boolean\n}\n\ntype Batch = { readonly mesh: Mesh; live: number; readonly index: { array: ArrayLike<number> & { [n: number]: number }; needsUpdate: boolean } }\n\nconst ATTRIBUTES = ['position', 'normal', 'uv', 'color'] as const\n\n/** Visible all the way up to `root`; a mesh no longer under it (its model was rebuilt) is not shown. */\nconst isShown = (object: Object3D, root: Object3D): boolean => {\n for (let node: Object3D | null = object; node; node = node.parent) {\n if (node === root) return true\n if (!node.visible) return false\n }\n return false\n}\n\nconst isBatchable = (mesh: Mesh): boolean => {\n const flags = mesh as Mesh & { isInstancedMesh?: boolean; isSkinnedMesh?: boolean }\n if (flags.isInstancedMesh === true || flags.isSkinnedMesh === true || Array.isArray(mesh.material)) return false\n const geometry = mesh.geometry\n return geometry.attributes.position !== undefined && Object.keys(geometry.morphAttributes).length === 0\n}\n\nconst signatureOf = (mesh: Mesh, materialKey: (material: Material) => string): string => {\n const { attributes } = mesh.geometry\n const present = ATTRIBUTES.filter((name) => attributes[name] !== undefined).map((name) => `${name}${attributes[name]!.itemSize}`)\n return `${materialKey(mesh.material as Material)}|${present.join(',')}|${mesh.castShadow ? 1 : 0}${mesh.receiveShadow ? 1 : 0}`\n}\n\nconst uuidOf = (material: Material): string => material.uuid\n\nconst sameMatrix = (a: Matrix4, b: Matrix4): boolean => a.elements.every((value, index) => Math.abs(value - (b.elements[index] as number)) < MATRIX_EPSILON)\n\n/**\n * Draws the still, undamaged meshes of an object (a vehicle, a piece of furniture) as one batch per material, and gives each mesh its own draw\n * back the moment it changes. The meshes stay where they are: what hits, dents or cuts them works on them as before, they only leave the\n * camera's layer while batched.\n */\nexport function createStaticBatcher(THREE: ThreeLib, root: Object3D, options: StaticBatcherOptions = {}): StaticBatcher {\n const include = options.include ?? (() => true)\n const follow = options.followMeshes === true\n root.updateMatrixWorld(true)\n const inverse = new THREE.Matrix4().copy(root.matrixWorld).invert()\n const groups = new Map<string, Mesh[]>()\n root.traverse((object) => {\n const mesh = object as Mesh\n if (!mesh.isMesh || !isShown(mesh, root) || !isBatchable(mesh) || !include(mesh)) return\n const key = signatureOf(mesh, options.materialKey ?? uuidOf)\n groups.set(key, [...(groups.get(key) ?? []), mesh])\n })\n const group = new THREE.Group()\n group.name = 'static-batches'\n const sources: Source[] = []\n const pending = [...groups.values()].filter((meshes) => meshes.length >= 2)\n const mergeSome = (deadline: number): void => {\n while (pending.length > 0) {\n const meshes = pending.shift() as Mesh[]\n // a mesh that changed while it waited is left to draw on its own\n if (meshes.every((mesh) => isShown(mesh, root))) sources.push(...mergeGroup(THREE, { meshes, inverse: new THREE.Matrix4().copy(root.matrixWorld).invert(), group, follow, onBatch: options.onBatch }))\n if (performance.now() >= deadline) return\n }\n }\n if (options.budgetMs === undefined) mergeSome(Number.POSITIVE_INFINITY)\n root.add(group)\n const scratch = new THREE.Matrix4()\n let released = 0\n\n const release = (source: Source): void => {\n source.released = true\n source.mesh.layers.mask = source.mask\n const { index } = source.batch\n const first = index.array[source.start] as number\n for (let at = source.start; at < source.start + source.count; at++) index.array[at] = first\n index.needsUpdate = true\n // a batch whose meshes all draw on their own again is an empty draw: it leaves the screen\n if (--source.batch.live === 0) source.batch.mesh.visible = false\n released++\n }\n const hasChanged = (source: Source): boolean => {\n const { mesh } = source\n if (mesh.geometry !== source.geometry || mesh.material !== source.material || !isShown(mesh, root)) return true\n if ((mesh.geometry.attributes.position as BufferAttribute).version !== source.version) return true\n if (follow || sameMatrix(mesh.matrixWorld, source.world)) return false\n if (!sameMatrix(scratch.multiplyMatrices(inverse, mesh.matrixWorld), source.local)) return true\n // the whole object moved, the mesh did not move within it\n source.world.copy(mesh.matrixWorld)\n return false\n }\n\n return {\n group,\n update() {\n if (pending.length > 0) mergeSome(performance.now() + (options.budgetMs ?? Number.POSITIVE_INFINITY))\n const before = released\n inverse.copy(root.matrixWorld).invert()\n for (const source of sources) if (!source.released && hasChanged(source)) release(source)\n return released - before\n },\n stats: () => ({ batches: group.children.length, batched: sources.filter((source) => !source.released).length, released }),\n dispose() {\n for (const source of sources) if (!source.released) source.mesh.layers.mask = source.mask\n group.removeFromParent()\n for (const child of group.children) {\n ;(child as Mesh).geometry.dispose()\n ;(child as SkinnedMesh).skeleton?.dispose()\n }\n },\n }\n}\n\n/** Copies `attribute` into `target` at `offset` vertices: positions through `matrix`, normals through its normal matrix, the rest as they are. */\nfunction copyAttribute(name: string, attribute: BufferAttribute, target: Float32Array, offset: number, matrix: Matrix4, normalMatrix: Matrix3): void {\n const size = attribute.itemSize\n const source = attribute.array as ArrayLike<number>\n const flat = !(attribute as { isInterleavedBufferAttribute?: boolean }).isInterleavedBufferAttribute && source.length === attribute.count * size\n if (name !== 'position' && name !== 'normal') {\n if (flat) target.set(source as Float32Array, offset * size)\n else for (let at = 0; at < attribute.count; at++) for (let k = 0; k < size; k++) target[(offset + at) * size + k] = attribute.getComponent(at, k)\n return\n }\n const e = (name === 'position' ? matrix : normalMatrix).elements\n const isNormal = name === 'normal'\n for (let at = 0; at < attribute.count; at++) {\n const x = attribute.getX(at)\n const y = attribute.getY(at)\n const z = attribute.getZ(at)\n const out = (offset + at) * 3\n if (isNormal) {\n const nx = e[0]! * x + e[3]! * y + e[6]! * z\n const ny = e[1]! * x + e[4]! * y + e[7]! * z\n const nz = e[2]! * x + e[5]! * y + e[8]! * z\n const length = Math.hypot(nx, ny, nz) || 1\n target[out] = nx / length\n target[out + 1] = ny / length\n target[out + 2] = nz / length\n } else {\n target[out] = e[0]! * x + e[4]! * y + e[8]! * z + e[12]!\n target[out + 1] = e[1]! * x + e[5]! * y + e[9]! * z + e[13]!\n target[out + 2] = e[2]! * x + e[6]! * y + e[10]! * z + e[14]!\n }\n }\n}\n\ntype MergeGroupParams = {\n readonly meshes: readonly Mesh[]\n readonly inverse: Matrix4\n readonly group: Object3D\n readonly follow: boolean\n readonly onBatch: StaticBatcherOptions['onBatch']\n}\n\n/** A skinned batch whose bone `n` is mesh `n` itself (no inverse, no bind offset): every vertex lands where its own mesh puts it. */\nfunction skinnedBatch(THREE: ThreeLib, merged: BufferGeometry, material: Material, meshes: readonly Mesh[]): Mesh {\n const vertices = (merged.attributes.position as BufferAttribute).count\n const skinIndex = new Uint16Array(vertices * 4)\n const skinWeight = new Float32Array(vertices * 4)\n let at = 0\n meshes.forEach((mesh, bone) => {\n for (let k = 0; k < (mesh.geometry.attributes.position as BufferAttribute).count; k++, at++) {\n skinIndex[at * 4] = bone\n skinWeight[at * 4] = 1\n }\n })\n merged.setAttribute('skinIndex', new THREE.BufferAttribute(skinIndex, 4))\n merged.setAttribute('skinWeight', new THREE.BufferAttribute(skinWeight, 4))\n const mesh = new THREE.SkinnedMesh(merged, material)\n const identities = meshes.map(() => new THREE.Matrix4())\n mesh.bind(new THREE.Skeleton(meshes as unknown as Bone[], identities), new THREE.Matrix4())\n // the parts move apart as the body is posed: the rest-pose bounds would cull the moved ones\n mesh.frustumCulled = false\n return mesh\n}\n\nfunction mergeGroup(THREE: ThreeLib, { meshes, inverse: rootInverse, group, follow, onBatch }: MergeGroupParams): Source[] {\n const identity = new THREE.Matrix4()\n const inverse = follow ? identity : rootInverse\n const first = meshes[0] as Mesh\n const names = ATTRIBUTES.filter((name) => first.geometry.attributes[name] !== undefined)\n const pieces = meshes.map((mesh) => {\n const local = new THREE.Matrix4().multiplyMatrices(inverse, mesh.matrixWorld)\n const vertices = (mesh.geometry.attributes.position as BufferAttribute).count\n const indexCount = mesh.geometry.index ? mesh.geometry.index.count : vertices\n return { mesh, local, vertices, indexCount }\n })\n const totalVertices = pieces.reduce((sum, piece) => sum + piece.vertices, 0)\n const totalIndices = pieces.reduce((sum, piece) => sum + piece.indexCount, 0)\n const merged = new THREE.BufferGeometry()\n const normalMatrix = new THREE.Matrix3()\n for (const name of names) {\n const size = first.geometry.attributes[name]!.itemSize\n const array = new Float32Array(totalVertices * size)\n let offset = 0\n for (const piece of pieces) {\n const matrix = follow ? identity : piece.local\n copyAttribute(name, piece.mesh.geometry.attributes[name] as BufferAttribute, array, offset, matrix, normalMatrix.getNormalMatrix(matrix))\n offset += piece.vertices\n }\n merged.setAttribute(name, new THREE.BufferAttribute(array, size))\n }\n const indexArray = totalVertices > 65535 ? new Uint32Array(totalIndices) : new Uint16Array(totalIndices)\n const indexAttribute = new THREE.BufferAttribute(indexArray, 1)\n merged.setIndex(indexAttribute)\n const mesh = follow ? skinnedBatch(THREE, merged, first.material as Material, meshes) : new THREE.Mesh(merged, first.material)\n mesh.name = `batch:${(first.material as Material).name || (first.material as Material).type}`\n mesh.castShadow = first.castShadow\n mesh.receiveShadow = first.receiveShadow\n mesh.raycast = () => undefined\n merged.computeBoundingBox()\n merged.computeBoundingSphere()\n group.add(mesh)\n onBatch?.(mesh, meshes)\n const batch: Batch = { mesh, live: pieces.length, index: indexAttribute as unknown as Batch['index'] }\n const sources: Source[] = []\n let vertexOffset = 0\n let indexOffset = 0\n for (const piece of pieces) {\n const index = piece.mesh.geometry.index\n if (index) for (let at = 0; at < piece.indexCount; at++) indexArray[indexOffset + at] = index.getX(at) + vertexOffset\n else for (let at = 0; at < piece.indexCount; at++) indexArray[indexOffset + at] = at + vertexOffset\n sources.push({\n mesh: piece.mesh,\n geometry: piece.mesh.geometry,\n material: piece.mesh.material as Material,\n version: (piece.mesh.geometry.attributes.position as BufferAttribute).version,\n local: piece.local,\n world: piece.mesh.matrixWorld.clone(),\n mask: piece.mesh.layers.mask,\n batch,\n start: indexOffset,\n count: piece.indexCount,\n released: false,\n })\n piece.mesh.layers.set(BATCHED_LAYER)\n vertexOffset += piece.vertices\n indexOffset += piece.indexCount\n }\n return sources\n}\n"],"mappings":";AAIA,IAAM,WAAW;AACjB,IAAM,gBAAgB;AACtB,IAAM,gBAAgB,KAAK,KAAK;AAChC,IAAM,mBAAmB;AAmDlB,SAAS,aAAa,MAA8G;AACzI,SAAO;AAAA,IACL,OAAO;AAAA,IACP,QAAQ;AA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,SAAS;AAClC,QAAI,MAAO,UAAS,KAAK,GAAG,KAAK,MAAM,YAAY,KAAM,YAAW,cAAc,EAAE,IAAI,MAAM,KAAK,EAAE,IAAI;AAAA,QACpG,UAAS,KAAK,GAAG,KAAK,MAAM,YAAY,KAAM,YAAW,cAAc,EAAE,IAAI,KAAK;AACvF,YAAQ,KAAK;AAAA,MACX,MAAM,MAAM;AAAA,MACZ,UAAU,MAAM,KAAK;AAAA,MACrB,UAAU,MAAM,KAAK;AAAA,MACrB,SAAU,MAAM,KAAK,SAAS,WAAW,SAA6B;AAAA,MACtE,OAAO,MAAM;AAAA,MACb,OAAO,MAAM,KAAK,YAAY,MAAM;AAAA,MACpC,MAAM,MAAM,KAAK,OAAO;AAAA,MACxB;AAAA,MACA,OAAO;AAAA,MACP,OAAO,MAAM;AAAA,MACb,UAAU;AAAA,IACZ,CAAC;AACD,UAAM,KAAK,OAAO,IAAI,aAAa;AACnC,oBAAgB,MAAM;AACtB,mBAAe,MAAM;AAAA,EACvB;AACA,SAAO;AACT;","names":["scene","DEFAULT_KEY_STEP","materialKey","mesh"]}
1
+ {"version":3,"sources":["../src/lights/slots.ts","../src/lights/arbiter.ts","../src/fog.ts","../src/lights/scene-state.ts","../src/lights/budget.ts","../src/lights/types.ts","../src/lights/guard.ts","../src/program-key.ts","../src/pools/anchors.ts","../src/probes.ts","../src/warmup.ts","../src/pools/pooled.ts","../src/pools/geometry.ts","../src/pools/material.ts","../src/pools/render-pools.ts","../src/frame-pacer.ts","../src/static-batcher.ts"],"sourcesContent":["import type { Group, Object3D, PointLight, SpotLight } from 'three'\n\nimport type { LightKind, LightPatch, LinearRgb, ThreeForLights } from './types'\n\nconst PARKED_Y = -50\nconst DEFAULT_DECAY = 2\nconst DEFAULT_ANGLE = Math.PI / 3\nconst POSITION_EPSILON = 1e-6\n\nexport type Vec3 = [number, number, number]\n\nexport type LightValues = {\n color: number | LinearRgb\n intensity: number\n distance: number\n decay: number\n position: Vec3\n target: Vec3 | undefined\n angle: number\n penumbra: number\n}\n\n/** Whoever owns a slot: a request, a source or a lease. */\nexport interface Holder {\n readonly kind: 'request' | 'source' | 'lease'\n readonly owner: string\n readonly lightKind: LightKind\n priority: number\n urgent: boolean\n values: LightValues\n slot: Slot | null\n alive: boolean\n onLost: (() => void) | undefined\n /** Sources only. */\n follow: Object3D | undefined\n shadow: boolean\n wanted: boolean\n distance: number\n /** Sources only: `values` with the world position and direction of `follow` of this frame. */\n resolved: LightValues\n}\n\nexport interface Slot {\n readonly index: number\n readonly kind: LightKind\n readonly shadow: boolean\n readonly light: PointLight | SpotLight\n holder: Holder | null\n pending: Holder | null\n leased: boolean\n /** 0..1 multiplier on the holder's intensity. */\n fade: number\n fadeTarget: number\n fadeOutMs: number\n baseIntensity: number\n lastPosition: Vec3\n}\n\nexport function createValues(base: Partial<LightValues> & Pick<LightValues, 'color' | 'intensity' | 'distance' | 'position'>): LightValues {\n return {\n decay: DEFAULT_DECAY,\n target: undefined,\n angle: DEFAULT_ANGLE,\n penumbra: 0,\n ...base,\n position: [...base.position],\n }\n}\n\nexport function mergeValues(values: LightValues, patch: LightPatch): void {\n if (patch.color !== undefined) values.color = patch.color\n if (patch.intensity !== undefined) values.intensity = patch.intensity\n if (patch.distance !== undefined) values.distance = patch.distance\n if (patch.decay !== undefined) values.decay = patch.decay\n if (patch.position !== undefined) values.position = [...patch.position]\n if (patch.target !== undefined) values.target = [...patch.target]\n if (patch.angle !== undefined) values.angle = patch.angle\n if (patch.penumbra !== undefined) values.penumbra = patch.penumbra\n}\n\nexport type ShadowSettings = { readonly bias?: number; readonly normalBias?: number; readonly near?: number }\n\nexport function createSlots(THREE: ThreeForLights, group: Group, kind: LightKind, count: number, shadows: number, mapSize: number, settings: ShadowSettings = {}): Slot[] {\n const slots: Slot[] = []\n for (let index = 0; index < count; index++) {\n const light = kind === 'point' ? new THREE.PointLight(0xffffff, 0, 0, DEFAULT_DECAY) : new THREE.SpotLight(0xffffff, 0, 0, DEFAULT_ANGLE, 0, DEFAULT_DECAY)\n light.position.set(0, PARKED_Y, 0)\n light.layers.enableAll()\n const shadow = index < shadows\n if (shadow) {\n light.castShadow = true\n light.shadow.autoUpdate = false\n light.shadow.mapSize.set(mapSize, mapSize)\n if (settings.bias !== undefined) light.shadow.bias = settings.bias\n if (settings.normalBias !== undefined) light.shadow.normalBias = settings.normalBias\n if (settings.near !== undefined) light.shadow.camera.near = settings.near\n }\n group.add(light)\n if ('target' in light) group.add(light.target)\n slots.push({ index, kind, shadow, light, holder: null, pending: null, leased: false, fade: 0, fadeTarget: 0, fadeOutMs: 0, baseIntensity: 0, lastPosition: [0, PARKED_Y, 0] })\n }\n return slots\n}\n\nexport function isFree(slot: Slot): boolean {\n return !slot.leased && slot.holder === null && slot.pending === null\n}\n\nexport function applyIntensity(slot: Slot): void {\n slot.light.intensity = slot.baseIntensity * slot.fade\n}\n\nexport function markShadow(slot: Slot): void {\n if (slot.shadow) slot.light.shadow.needsUpdate = true\n}\n\nexport function writeLight(THREE: ThreeForLights, slot: Slot, values: LightValues): void {\n const { light } = slot\n if (typeof values.color === 'number') light.color.set(values.color)\n else light.color.setRGB(values.color[0], values.color[1], values.color[2], THREE.LinearSRGBColorSpace)\n light.distance = values.distance\n light.decay = values.decay\n const [x, y, z] = values.position\n light.position.set(x, y, z)\n if ('angle' in light) {\n light.angle = values.angle\n light.penumbra = values.penumbra\n const [tx, ty, tz] = values.target ?? [x, y - 1, z]\n light.target.position.set(tx, ty, tz)\n }\n const last = slot.lastPosition\n if (slot.shadow && (Math.abs(last[0] - x) > POSITION_EPSILON || Math.abs(last[1] - y) > POSITION_EPSILON || Math.abs(last[2] - z) > POSITION_EPSILON)) markShadow(slot)\n slot.lastPosition = [x, y, z]\n slot.baseIntensity = values.intensity\n applyIntensity(slot)\n}\n\n/** The holder's writes apply from now on; its light fades in (requests that cut a victim start at full). */\nexport function install(THREE: ThreeForLights, slot: Slot, holder: Holder, startAtFull: boolean): void {\n slot.holder = holder\n slot.pending = null\n slot.fade = startAtFull ? 1 : 0\n slot.fadeTarget = 1\n holder.slot = slot\n markShadow(slot)\n writeLight(THREE, slot, holder.values)\n}\n\n/** Drops the holder: the light keeps its last values and fades to 0 (at once with `fadeOutMs` 0). */\nexport function vacate(slot: Slot, fadeOutMs: number): void {\n slot.holder = null\n slot.fadeTarget = 0\n slot.fadeOutMs = fadeOutMs\n if (fadeOutMs <= 0) {\n slot.fade = 0\n applyIntensity(slot)\n }\n}\n\nexport function stepFade(slot: Slot, dtSeconds: number, fadeInMs: number): void {\n if (slot.fade < slot.fadeTarget) {\n slot.fade = fadeInMs <= 0 ? slot.fadeTarget : Math.min(slot.fadeTarget, slot.fade + (dtSeconds * 1000) / fadeInMs)\n } else if (slot.fade > slot.fadeTarget) {\n slot.fade = slot.fadeOutMs <= 0 ? slot.fadeTarget : Math.max(slot.fadeTarget, slot.fade - (dtSeconds * 1000) / slot.fadeOutMs)\n }\n applyIntensity(slot)\n}\n","import { type Holder, type Slot, install, isFree, stepFade, vacate } from './slots'\nimport type { LightKind, ThreeForLights } from './types'\n\nexport type ArbiterCore = {\n readonly THREE: ThreeForLights\n readonly slots: Record<LightKind, readonly Slot[]>\n readonly urgentReserve: number\n readonly fadeMs: number\n readonly hysteresis: number\n preempted: number\n refused: number\n}\n\n/** The slots requests and sources compete for: not leased, and shadow slots only on their own pass. */\nexport function poolOf(core: ArbiterCore, kind: LightKind, shadow: boolean): Slot[] {\n return core.slots[kind].filter((slot) => !slot.leased && slot.shadow === shadow)\n}\n\nfunction contribution(holder: Holder): number {\n return holder.values.intensity / Math.max(1, holder.distance) ** 2\n}\n\n/** Lowest priority first; on a tie, the smallest perceived contribution. */\nfunction isWeaker(a: Holder, b: Holder): boolean {\n if (a.priority !== b.priority) return a.priority < b.priority\n return contribution(a) < contribution(b)\n}\n\nfunction pickFree(slots: readonly Slot[]): Slot | undefined {\n let best: Slot | undefined\n for (const slot of slots) if (isFree(slot) && (best === undefined || slot.fade < best.fade)) best = slot\n return best\n}\n\n/** Gives a free slot to the holder: at once when its light is dark or the holder is urgent, else after the slot finishes fading out. */\nfunction place(core: ArbiterCore, slot: Slot, holder: Holder): void {\n holder.slot = slot\n if (slot.fade > 0 && !holder.urgent) {\n slot.pending = holder\n slot.fadeTarget = 0\n return\n }\n install(core.THREE, slot, holder, holder.kind === 'request')\n}\n\n/** Takes the slot from its holder; a request is told and dies, a source goes back to the queue. */\nfunction evict(core: ArbiterCore, slot: Slot, challenger: Holder, cut: boolean): void {\n const victim = slot.holder\n if (victim === null) return\n victim.slot = null\n if (victim.kind === 'request') {\n victim.alive = false\n victim.onLost?.()\n }\n core.preempted++\n vacate(slot, cut ? 0 : core.fadeMs)\n if (cut) {\n install(core.THREE, slot, challenger, true)\n return\n }\n slot.pending = challenger\n challenger.slot = slot\n}\n\nfunction weakestHolder(slots: readonly Slot[]): Slot | undefined {\n let weakest: Slot | undefined\n for (const slot of slots) {\n if (slot.holder === null || slot.pending !== null) continue\n if (weakest === undefined || isWeaker(slot.holder, weakest.holder as Holder)) weakest = slot\n }\n return weakest\n}\n\n/** Slots free to a holder that has no right to the urgent reserve. */\nfunction freeBeyondReserve(core: ArbiterCore, pool: readonly Slot[], reserve: number): Slot | undefined {\n const free = pool.filter(isFree)\n return free.length > reserve ? pickFree(pool) : undefined\n}\n\nexport function admitRequest(core: ArbiterCore, holder: Holder): boolean {\n const pool = poolOf(core, holder.lightKind, false)\n const reserve = holder.lightKind === 'point' ? core.urgentReserve : 0\n const free = holder.urgent ? pickFree(pool) : freeBeyondReserve(core, pool, reserve)\n if (free !== undefined) {\n place(core, free, holder)\n return true\n }\n const victim = weakestHolder(pool)\n if (victim === undefined || (victim.holder as Holder).priority >= holder.priority) {\n core.refused++\n return false\n }\n evict(core, victim, holder, holder.urgent)\n return true\n}\n\nfunction beats(challenger: Holder, incumbent: Holder, hysteresis: number): boolean {\n if (challenger.priority !== incumbent.priority) return challenger.priority > incumbent.priority\n return challenger.distance < incumbent.distance * (1 - hysteresis)\n}\n\nfunction bestFirst(a: Holder, b: Holder): number {\n return b.priority - a.priority || a.distance - b.distance\n}\n\n/** Hands the pool's slots to the wanted sources: best first, an incumbent only yields to a clearly better challenger. */\nexport function arbitrateSources(core: ArbiterCore, pool: readonly Slot[], sources: readonly Holder[], reserve: number): void {\n for (const slot of pool) {\n const holder = slot.holder\n if (slot.pending?.kind === 'source' && !slot.pending.wanted) {\n slot.pending.slot = null\n slot.pending = null\n }\n if (holder?.kind === 'source' && !holder.wanted) {\n holder.slot = null\n vacate(slot, core.fadeMs)\n }\n }\n const challengers = sources.filter((source) => source.wanted && source.slot === null).sort(bestFirst)\n for (const challenger of challengers) {\n const free = freeBeyondReserve(core, pool, reserve)\n if (free !== undefined) {\n place(core, free, challenger)\n continue\n }\n const incumbentSlots = pool.filter((slot) => slot.holder?.kind === 'source')\n let worst: Slot | undefined\n for (const slot of incumbentSlots) {\n if (slot.pending !== null) continue\n if (worst === undefined || bestFirst(slot.holder as Holder, worst.holder as Holder) > 0) worst = slot\n }\n if (worst === undefined || !beats(challenger, worst.holder as Holder, core.hysteresis)) break\n evict(core, worst, challenger, false)\n }\n}\n\nexport function stepSlots(core: ArbiterCore, dtSeconds: number): void {\n for (const kind of ['point', 'spot'] as const) {\n for (const slot of core.slots[kind]) {\n stepFade(slot, dtSeconds, core.fadeMs)\n if (slot.pending !== null && slot.fade <= 0) install(core.THREE, slot, slot.pending, false)\n }\n }\n}\n","import type { Fog, FogBase, FogExp2, Scene } from 'three'\n\nimport type { ThreeLib } from './three-lib'\n\n/** Both exact in half precision (multiples of 32 under 65 504), so the neutral fog survives a `mediump` fragment shader. */\nexport const NEUTRAL_FOG_NEAR = 6.0e4\nexport const NEUTRAL_FOG_FAR = 6.4e4\n\nexport interface FogOptions {\n /** `clear()` leaves a neutral linear Fog instead of `null`: the fog presence and type never change, so no program recompiles. */\n readonly stable?: boolean\n /** Colour of the neutral fog. Default 0x000000. */\n readonly color?: number\n}\n\nexport interface FogController {\n useLinear(color: number, near: number, far: number): Fog\n useExp2(color: number, density: number): FogExp2\n /** Back to no fog: the original fog (or `null`); when `stable`, the host's own linear fog or the neutral one, never `null`. */\n clear(): void\n}\n\nfunction isLinearFog(fog: FogBase | null): fog is Fog {\n return (fog as Partial<Fog> | null)?.isFog === true\n}\n\nfunction isExp2Fog(fog: FogBase | null): fog is FogExp2 {\n return (fog as Partial<FogExp2> | null)?.isFogExp2 === true\n}\n\nexport function isNeutralFog(fog: unknown): boolean {\n const candidate = fog as Partial<Fog> | null | undefined\n return candidate?.isFog === true && candidate.near === NEUTRAL_FOG_NEAR && candidate.far === NEUTRAL_FOG_FAR\n}\n\n/** Writes into the scene's existing fog object when its type matches, as the weather layer does, so nothing is reallocated per change. */\nexport function createFog(THREE: Pick<ThreeLib, 'Fog' | 'FogExp2'>, scene: Scene, options: FogOptions = {}): FogController {\n const original = scene.fog\n const hostLinear = isLinearFog(original) ? { color: original.color.getHex(), near: original.near, far: original.far } : undefined\n const resting = hostLinear ?? { color: options.color ?? 0, near: NEUTRAL_FOG_NEAR, far: NEUTRAL_FOG_FAR }\n return {\n useLinear(color, near, far) {\n const current = scene.fog\n if (isLinearFog(current)) {\n current.color.set(color)\n current.near = near\n current.far = far\n return current\n }\n const fog = new THREE.Fog(color, near, far)\n scene.fog = fog\n return fog\n },\n useExp2(color, density) {\n const current = scene.fog\n if (isExp2Fog(current)) {\n current.color.set(color)\n current.density = density\n return current\n }\n const fog = new THREE.FogExp2(color, density)\n scene.fog = fog\n return fog\n },\n clear() {\n if (options.stable !== true) {\n scene.fog = original\n return\n }\n const current = scene.fog\n if (isLinearFog(current)) {\n current.color.set(resting.color)\n current.near = resting.near\n current.far = resting.far\n return\n }\n scene.fog = new THREE.Fog(resting.color, resting.near, resting.far)\n },\n }\n}\n","import type { Object3D, Scene } from 'three'\n\nimport { NEUTRAL_FOG_NEAR } from '../fog'\nimport type { FogState, LightCheck, RendererState, SealOptions } from './types'\n\ntype Flags = Record<string, unknown>\ntype Counter = { count: number; shadows: number }\n\nconst LIGHT_FLAGS = [\n ['point', 'isPointLight'],\n ['spot', 'isSpotLight'],\n ['hemi', 'isHemisphereLight'],\n ['dir', 'isDirectionalLight'],\n ['ambient', 'isAmbientLight'],\n ['rect', 'isRectAreaLight'],\n] as const\n\n/** The visible lights the way the renderer collects them: they decide the shader's light counts. */\nexport function lightSignature(scene: Object3D): string {\n const counters: Record<string, Counter> = {}\n for (const [name] of LIGHT_FLAGS) counters[name] = { count: 0, shadows: 0 }\n scene.traverseVisible((object) => {\n const flags = object as unknown as Flags\n for (const [name, flag] of LIGHT_FLAGS) {\n if (flags[flag] !== true) continue\n const counter = counters[name] as Counter\n counter.count++\n if ((flags as { castShadow?: boolean }).castShadow === true) counter.shadows++\n }\n })\n return LIGHT_FLAGS.map(([name]) => `${name}:${(counters[name] as Counter).count}/${(counters[name] as Counter).shadows}`).join(' ')\n}\n\nexport function fogStateOf(scene: Scene): FogState {\n const fog = scene.fog as Flags | null\n if (fog === null) return 'none'\n return fog.isFogExp2 === true ? 'exp2' : 'linear'\n}\n\n/** Every PointLight/SpotLight under `scene` that is not under `group`, as a path of child indices. */\nexport function findStrays(scene: Object3D, group: Object3D): string[] {\n const strays: string[] = []\n const visit = (object: Object3D, path: string): void => {\n if (object === group) return\n const flags = object as unknown as Flags\n if (flags.isPointLight === true || flags.isSpotLight === true) strays.push(`${path}${object.name === '' ? object.type : object.name}`)\n object.children.forEach((child, index) => visit(child, `${path}${index}/`))\n }\n visit(scene, '')\n return strays\n}\n\nexport type Sealed = {\n readonly lights: string\n readonly environment: string\n readonly toneMapping: number\n readonly outputColorSpace: string\n readonly targetColorSpace: string\n readonly shadowMapType: number\n readonly fogStates: readonly FogState[]\n readonly cameras: SealOptions['cameras']\n readonly target: SealOptions['target']\n}\n\nfunction environmentOf(scene: Scene): string {\n return scene.environment === null ? 'none' : `texture:${scene.environment.mapping}`\n}\n\nfunction targetColorSpaceOf(target: SealOptions['target']): string {\n return target ? target.texture.colorSpace : 'canvas'\n}\n\nexport function captureSealed(renderer: RendererState, scene: Scene, options: SealOptions): Sealed {\n return {\n lights: lightSignature(scene),\n environment: environmentOf(scene),\n toneMapping: renderer.toneMapping,\n outputColorSpace: renderer.outputColorSpace,\n targetColorSpace: targetColorSpaceOf(options.target),\n shadowMapType: renderer.shadowMap.type,\n fogStates: options.fogStates ?? [fogStateOf(scene)],\n cameras: options.cameras,\n target: options.target,\n }\n}\n\ntype Described = {\n readonly lights: string\n readonly fog: string\n readonly environment: string\n readonly toneMapping: number\n readonly outputColorSpace: string\n readonly targetColorSpace: string\n readonly shadowMapType: number\n}\n\nfunction describe(state: Described): string {\n const { lights, fog, environment, toneMapping, outputColorSpace, targetColorSpace, shadowMapType } = state\n return `${lights} | fog:${fog} env:${environment} tone:${toneMapping} out:${outputColorSpace}/${targetColorSpace} shadow:${shadowMapType}`\n}\n\nfunction farBeyondNeutralFog(scene: Scene, sealed: Sealed): boolean {\n const fog = scene.fog as { isFog?: boolean; near?: number } | null\n if (fog?.isFog !== true || fog.near !== NEUTRAL_FOG_NEAR) return false\n return (sealed.cameras ?? []).some((camera) => ((camera as unknown as { far?: number }).far ?? 0) >= NEUTRAL_FOG_NEAR)\n}\n\nexport function checkSealed(sealed: Sealed | null, renderer: RendererState, scene: Scene, group: Object3D): LightCheck {\n const strays = findStrays(scene, group)\n const lights = lightSignature(scene)\n if (sealed === null) return { ok: strays.length === 0, expected: lights, actual: lights, strays }\n const fog = fogStateOf(scene)\n const fogAllowed = sealed.fogStates.includes(fog)\n const expected = describe({ ...sealed, fog: fogAllowed ? fog : sealed.fogStates.join('|') })\n const actual = describe({\n lights,\n fog,\n environment: environmentOf(scene),\n toneMapping: renderer.toneMapping,\n outputColorSpace: renderer.outputColorSpace,\n targetColorSpace: targetColorSpaceOf(sealed.target),\n shadowMapType: renderer.shadowMap.type,\n })\n const ok = strays.length === 0 && expected === actual && !farBeyondNeutralFog(scene, sealed)\n return { ok, expected, actual, strays }\n}\n","import type { HemisphereLight, Object3D, Scene } from 'three'\n\nimport { type ArbiterCore, admitRequest, arbitrateSources, poolOf, stepSlots } from './arbiter'\nimport { type Sealed, captureSealed, checkSealed } from './scene-state'\nimport { type Holder, type Slot, type Vec3, createSlots, createValues, isFree, markShadow, mergeValues, vacate, writeLight } from './slots'\nimport type {\n LightBudget,\n LightBudgetOptions,\n LightHandle,\n LightKind,\n LightLease,\n LightPatch,\n LightRequest,\n LightSource,\n RendererState,\n SourceHandle,\n ThreeForLights,\n} from './types'\n\nconst DEFAULTS = { point: 16, spot: 4, pointShadows: 2, spotShadows: 0, shadowMapSize: 512, urgentReserve: 2, fadeMs: 120, hysteresis: 0.15, hemisphere: 0 }\nconst ZERO: Vec3 = [0, 0, 0]\nconst ALL_LAYERS_MASK = -1\n\nfunction newHolder(kind: Holder['kind'], lightKind: LightKind, request: LightRequest | LightSource, urgent: boolean): Holder {\n return {\n kind,\n owner: request.owner,\n lightKind,\n priority: request.priority,\n urgent,\n values: createValues({ color: request.color, intensity: request.intensity, distance: request.distance, position: [...request.position], ...optional(request) }),\n slot: null,\n alive: true,\n onLost: undefined,\n follow: undefined,\n shadow: false,\n wanted: true,\n distance: 0,\n resolved: createValues({ color: request.color, intensity: 0, distance: 0, position: ZERO }),\n }\n}\n\nfunction optional(request: LightRequest | LightSource): Partial<Holder['values']> {\n const values: Partial<Holder['values']> = {}\n if (request.decay !== undefined) values.decay = request.decay\n if (request.target !== undefined) values.target = [...request.target]\n if (request.angle !== undefined) values.angle = request.angle\n if (request.penumbra !== undefined) values.penumbra = request.penumbra\n return values\n}\n\nfunction isAttached(object: Object3D, root: Object3D): boolean {\n for (let node: Object3D | null = object; node !== null; node = node.parent) if (node === root) return true\n return false\n}\n\nexport function createLightBudget(THREE: ThreeForLights, scene: Object3D, options: LightBudgetOptions = {}): LightBudget {\n const opts = { ...DEFAULTS, ...options }\n const pointShadows = Math.min(opts.pointShadows, opts.point)\n const spotShadows = Math.min(opts.spotShadows, opts.spot)\n const group = new THREE.Group()\n group.name = 'light-budget'\n const core: ArbiterCore = {\n THREE,\n slots: {\n point: createSlots(THREE, group, 'point', opts.point, pointShadows, opts.shadowMapSize, options.shadowSettings),\n spot: createSlots(THREE, group, 'spot', opts.spot, spotShadows, opts.shadowMapSize, options.shadowSettings),\n },\n urgentReserve: opts.urgentReserve,\n fadeMs: opts.fadeMs,\n hysteresis: opts.hysteresis,\n preempted: 0,\n refused: 0,\n }\n const hemispheres: HemisphereLight[] = []\n for (let index = 0; index < opts.hemisphere; index++) {\n const light = new THREE.HemisphereLight(0xffffff, 0xffffff, 0)\n light.layers.enableAll()\n group.add(light)\n hemispheres.push(light)\n }\n scene.add(group)\n scene.children.splice(scene.children.indexOf(group), 1)\n scene.children.unshift(group)\n\n const sources = new Set<Holder>()\n const world = new THREE.Vector3()\n const direction = new THREE.Vector3()\n let sealed: Sealed | null = null\n let leasedHemispheres = 0\n\n const allSlots = (): Slot[] => [...core.slots.point, ...core.slots.spot]\n\n function writeHolder(holder: Holder): void {\n if (holder.slot !== null && holder.slot.holder === holder) writeLight(THREE, holder.slot, holder.values)\n }\n\n function makeHandle(holder: Holder, release: ((fadeMs: number | undefined) => void) | null): LightHandle {\n return {\n get slot() {\n return holder.slot?.index ?? -1\n },\n kind: holder.lightKind,\n get alive() {\n return holder.alive\n },\n update(patch: LightPatch) {\n if (!holder.alive) return\n mergeValues(holder.values, patch)\n writeHolder(holder)\n },\n release(releaseOptions) {\n if (!holder.alive || release === null) return\n holder.alive = false\n release(releaseOptions?.fadeMs)\n },\n }\n }\n\n function dropHolder(holder: Holder, fadeMs: number): void {\n const slot = holder.slot\n holder.slot = null\n if (slot === null) return\n if (slot.pending === holder) slot.pending = null\n else if (slot.holder === holder) vacate(slot, fadeMs)\n }\n\n function resolveSource(holder: Holder, focus: readonly [number, number, number]): void {\n const { follow, values, resolved } = holder\n holder.wanted = values.intensity > 0\n if (follow === undefined) {\n holder.distance = Math.hypot(values.position[0] - focus[0], values.position[1] - focus[1], values.position[2] - focus[2])\n Object.assign(resolved, values)\n return\n }\n holder.wanted = holder.wanted && isAttached(follow, scene)\n if (!holder.wanted) return\n follow.getWorldPosition(world)\n const [ox, oy, oz] = values.position\n if (ox !== 0 || oy !== 0 || oz !== 0) world.set(ox, oy, oz).applyMatrix4(follow.matrixWorld)\n const axis = follow.matrixWorld.elements\n direction.set(-(axis[8] as number), -(axis[9] as number), -(axis[10] as number))\n holder.distance = Math.hypot(world.x - focus[0], world.y - focus[1], world.z - focus[2])\n Object.assign(resolved, values)\n resolved.position = [world.x, world.y, world.z]\n resolved.target = values.target ?? [world.x + direction.x, world.y + direction.y, world.z + direction.z]\n }\n\n return {\n group,\n sizes: { point: opts.point, spot: opts.spot, pointShadows, spotShadows },\n acquire(request) {\n const holder = newHolder('request', request.kind ?? 'point', request, request.urgent === true)\n holder.onLost = request.onLost\n if (!admitRequest(core, holder)) return null\n return makeHandle(holder, (fadeMs) => dropHolder(holder, fadeMs ?? opts.fadeMs))\n },\n addSource(source) {\n const holder = newHolder('source', source.kind ?? 'point', source, false)\n holder.follow = source.follow\n holder.shadow = source.shadow === true\n sources.add(holder)\n return {\n get slot() {\n return holder.slot !== null && holder.slot.holder === holder ? holder.slot.index : -1\n },\n update(patch: Partial<LightSource>) {\n mergeValues(holder.values, patch)\n if (patch.priority !== undefined) holder.priority = patch.priority\n if ('follow' in patch) holder.follow = patch.follow\n if (holder.follow === undefined) writeHolder(holder)\n },\n remove() {\n holder.alive = false\n holder.wanted = false\n sources.delete(holder)\n dropHolder(holder, opts.fadeMs)\n },\n } satisfies SourceHandle\n },\n lease({ owner, point, shadows = 0 }) {\n const shadowSlots = core.slots.point.filter((slot) => slot.shadow && isFree(slot))\n const plainSlots = core.slots.point.filter((slot) => !slot.shadow && isFree(slot))\n if (shadowSlots.length < shadows || plainSlots.length < point - shadows) return null\n const taken = [...shadowSlots.slice(0, shadows), ...plainSlots.slice(0, point - shadows)]\n const holders = taken.map((slot) => {\n const holder = newHolder('lease', 'point', { owner, priority: Number.POSITIVE_INFINITY, color: 0xffffff, intensity: 0, distance: 0, position: ZERO }, false)\n slot.leased = true\n slot.holder = holder\n slot.fade = 1\n slot.fadeTarget = 1\n holder.slot = slot\n markShadow(slot)\n return holder\n })\n const handles = holders.map((holder) => makeHandle(holder, null))\n return {\n handles,\n invalidateShadow(index) {\n for (const [at, holder] of holders.entries()) if ((index === undefined || index === at) && holder.slot !== null) markShadow(holder.slot)\n },\n release() {\n for (const holder of holders) {\n const slot = holder.slot\n holder.alive = false\n holder.slot = null\n if (slot === null) continue\n slot.leased = false\n slot.holder = null\n vacate(slot, 0)\n }\n },\n } satisfies LightLease\n },\n leaseHemisphere() {\n const light = hemispheres[leasedHemispheres]\n if (light === undefined) return null\n leasedHemispheres++\n return light\n },\n present(focus, dtSeconds) {\n for (const holder of sources) resolveSource(holder, focus)\n for (const kind of ['point', 'spot'] as const) {\n const reserve = kind === 'point' ? core.urgentReserve : 0\n const kindSources = [...sources].filter((holder) => holder.lightKind === kind)\n arbitrateSources(core, poolOf(core, kind, true), kindSources.filter((holder) => holder.shadow), 0)\n arbitrateSources(core, poolOf(core, kind, false), kindSources.filter((holder) => !holder.shadow), reserve)\n }\n stepSlots(core, dtSeconds)\n for (const holder of sources) if (holder.wanted && holder.slot?.holder === holder) writeLight(THREE, holder.slot, holder.resolved)\n },\n seal(renderer, scene, sealOptions = {}) {\n sealed = captureSealed(renderer, scene, sealOptions)\n },\n check(renderer: RendererState, checkedScene: Scene) {\n const result = checkSealed(sealed, renderer, checkedScene, group)\n const layersIntact = allSlots().every((slot) => slot.light.visible && slot.light.layers.mask === ALL_LAYERS_MASK)\n const isFirst = checkedScene.children[0] === group\n if (!layersIntact) return { ...result, ok: false, actual: `${result.actual} | budget lights hidden or off a layer` }\n return isFirst ? result : { ...result, ok: false, actual: `${result.actual} | budget group is not the first child of the scene` }\n },\n stats() {\n const slots = allSlots()\n return {\n lit: slots.filter((slot) => slot.light.intensity > 0).length,\n free: slots.filter(isFree).length,\n leased: slots.filter((slot) => slot.leased).length,\n sources: sources.size,\n sourcesWithoutSlot: [...sources].filter((holder) => holder.wanted && holder.slot === null).length,\n preempted: core.preempted,\n refused: core.refused,\n }\n },\n dispose() {\n group.removeFromParent()\n for (const slot of allSlots()) slot.light.dispose()\n sources.clear()\n },\n }\n}\n","import type { Camera, Group, HemisphereLight, Object3D, Scene, WebGLRenderTarget } from 'three'\n\nimport type { ThreeLib } from '../three-lib'\n\nexport type LightKind = 'point' | 'spot'\nexport type LinearRgb = readonly [number, number, number]\nexport type FogState = 'none' | 'linear' | 'exp2'\nexport type ThreeForLights = Pick<\n ThreeLib,\n 'Group' | 'PointLight' | 'SpotLight' | 'HemisphereLight' | 'Object3D' | 'Vector3' | 'Color' | 'LinearSRGBColorSpace'\n>\n/** What the budget reads of a renderer: a structural subset, so a fake works in Node. */\nexport type RendererState = {\n readonly toneMapping: number\n readonly outputColorSpace: string\n readonly shadowMap: { readonly type: number }\n}\n\nexport interface LightBudgetOptions {\n /** Point lights created at boot. Default 16. */\n readonly point?: number\n /** Spot lights created at boot. Default 4. */\n readonly spot?: number\n /** How many of the point lights cast shadows (cube maps). Default 2. Fixed for the life of the budget. */\n readonly pointShadows?: number\n /** How many of the spot lights cast shadows. Default 0. */\n readonly spotShadows?: number\n /** Shadow map size of the shadow slots. Default 512. */\n readonly shadowMapSize?: number\n /** Bias, normal bias and camera near plane of the shadow slots. Defaults: three.js's (0, 0, 0.5). The house's room lights use -0.0012, 0.05 and 0.12. */\n readonly shadowSettings?: { readonly bias?: number; readonly normalBias?: number; readonly near?: number }\n /** Point slots only `urgent` requests may take while others are free. Default 2. */\n readonly urgentReserve?: number\n /** Milliseconds a light fades out when a source loses its slot, and fades in when it gets one. Default 120. */\n readonly fadeMs?: number\n /** A source keeps its slot until a challenger of the same priority is this much closer (0.15 = 15%). Default 0.15. */\n readonly hysteresis?: number\n /** HemisphereLights created at boot for adapters that flash the sky; leased with `leaseHemisphere`. Default 0. */\n readonly hemisphere?: number\n}\n\n/** A light that lives as long as the request: a blast, a rocket in flight, a muzzle flash, a flare in the hand. */\nexport interface LightRequest {\n readonly owner: string\n readonly kind?: LightKind\n /** Higher wins a slot; see LIGHT_PRIORITY. */\n readonly priority: number\n /** Hex (sRGB, like `new Color(hex)`) or linear RGB. */\n readonly color: number | LinearRgb\n readonly intensity: number\n readonly distance: number\n readonly decay?: number\n readonly position: readonly [number, number, number]\n /** Spot only. */\n readonly target?: readonly [number, number, number]\n readonly angle?: number\n readonly penumbra?: number\n /** Takes a slot at once: cuts the lowest victim instead of fading it, and may use the urgent reserve. */\n readonly urgent?: boolean\n /** Called once when a higher priority took the slot; the handle is dead from then on. */\n readonly onLost?: () => void\n}\n\nexport type LightPatch = Partial<Pick<LightRequest, 'color' | 'intensity' | 'distance' | 'decay' | 'position' | 'target' | 'angle' | 'penumbra'>>\n\nexport interface LightHandle {\n /** Index of this light among the scene's point (or spot) lights in the shader; stable while the handle lives. */\n readonly slot: number\n readonly kind: LightKind\n readonly alive: boolean\n update(patch: LightPatch): void\n /** Gives the slot back; with fadeMs the light fades first. Idempotent. */\n release(options?: { readonly fadeMs?: number }): void\n}\n\n/** A light that exists in the world for a long time and competes for a slot every frame: a lamp, a street light, a headlight. */\nexport interface LightSource extends Omit<LightRequest, 'urgent' | 'onLost'> {\n /** Wants a shadow slot; a shadow source competes for shadow slots only. */\n readonly shadow?: boolean\n /**\n * The object the light sits on. Its world position (and, for a spot, its world -z as the direction when `target` is absent) is read\n * once per `present`; `position` is then an offset in its local space. A source whose `follow` left the scene counts as off.\n */\n readonly follow?: Object3D\n}\n\nexport interface SourceHandle {\n /** Slot now, or -1 while it has none (its light is not drawn). */\n readonly slot: number\n update(patch: Partial<LightSource>): void\n remove(): void\n}\n\n/** Slots a client keeps for itself for good: the room lights of a house (their masks are indexed by slot). */\nexport interface LightLease {\n readonly handles: readonly LightHandle[]\n /** Redraws the shadow map of one leased slot (`handles[index]`), or of all of them, on the next render: the walls it shades changed. */\n invalidateShadow(index?: number): void\n release(): void\n}\n\nexport interface SealOptions {\n /** Fog states the game will switch between at run time. Default: only the state at seal time. */\n readonly fogStates?: readonly FogState[]\n /** Cameras whose `far` must stay under the neutral fog's near (read at every `check`). */\n readonly cameras?: readonly Camera[]\n /** Where the game really draws; its colour space is part of the sealed state. */\n readonly target?: WebGLRenderTarget | null\n}\n\nexport interface LightCheck {\n readonly ok: boolean\n readonly expected: string\n readonly actual: string\n /** Paths of PointLight/SpotLight found outside the budget's group. */\n readonly strays: readonly string[]\n}\n\nexport interface LightBudgetStats {\n readonly lit: number\n readonly free: number\n readonly leased: number\n readonly sources: number\n readonly sourcesWithoutSlot: number\n readonly preempted: number\n readonly refused: number\n}\n\nexport interface LightBudget {\n /** The group holding every light; first child of the scene. Never hidden, never removed while the budget lives. */\n readonly group: Group\n readonly sizes: { readonly point: number; readonly spot: number; readonly pointShadows: number; readonly spotShadows: number }\n acquire(request: LightRequest): LightHandle | null\n addSource(source: LightSource): SourceHandle\n /** Takes `point` slots (of which `shadows` shadow slots) for good. null when not enough unleased slots remain. */\n lease(options: { readonly owner: string; readonly point: number; readonly shadows?: number }): LightLease | null\n /** Takes one of the boot HemisphereLights for good. null when none is left. Its intensity starts at 0. */\n leaseHemisphere(owner: string): HemisphereLight | null\n /** Once per frame, with the camera (or the player) as focus. `dtSeconds` is real time: fades do not stop in pause. */\n present(focus: readonly [number, number, number], dtSeconds: number): void\n /** After this, any change in the program-key state of the scene is a bug and `check()` reports it. */\n seal(renderer: RendererState, scene: Scene, options?: SealOptions): void\n check(renderer: RendererState, scene: Scene): LightCheck\n stats(): LightBudgetStats\n dispose(): void\n}\n\nexport const LIGHT_PRIORITY = {\n blast: 900,\n rocket: 800,\n muzzle: 750,\n fire: 600,\n flare: 500,\n headlight: 400,\n weaponLight: 400,\n lamp: 200,\n street: 150,\n} as const\n","import type { LightBudget } from './types'\n\n/** For adapters that receive the budget as `unknown` through the host (the contract does not know three). */\nexport function isLightBudget(value: unknown): value is LightBudget {\n const candidate = value as Partial<LightBudget> | null | undefined\n return typeof candidate === 'object' && candidate !== null && typeof candidate.acquire === 'function' && typeof candidate.addSource === 'function' && typeof candidate.lease === 'function' && typeof candidate.present === 'function'\n}\n","import type { Material } from 'three'\n\n/** What `programKeysOf` reads of a renderer: `properties` is internal to three r160 and may be absent in another version. */\nexport type PropertiesReader = { readonly properties?: { get(object: object): unknown } }\n\n/**\n * Every program cache key three linked for `material` (one per state it was drawn in: fog type, shadow, light counts). Reads three's\n * internal `properties.get(material).programs` Map (r160). `[]` for a material never drawn; `undefined` when this three does not have\n * that internal, which sends the pools to their conservative mode.\n */\nexport function programKeysOf(renderer: PropertiesReader, material: Material): readonly string[] | undefined {\n const properties = renderer.properties\n if (typeof properties?.get !== 'function') return undefined\n const programs = (properties.get(material) as { programs?: unknown } | undefined)?.programs\n if (programs === undefined) return []\n if (!(programs instanceof Map)) return undefined\n return [...programs.keys()].map(String)\n}\n","import type { Material } from 'three'\n\nimport { type PropertiesReader, programKeysOf } from '../program-key'\n\n/** Materials kept alive and never disposed, one per program family: what keeps a program linked once its users are gone. */\nexport interface MaterialAnchors {\n /**\n * Keeps `material` if any of its program keys has no anchor yet; returns true when it was kept (the caller must then not dispose it).\n * A material whose keys are all covered returns false and may be disposed. A material never drawn is not kept.\n */\n offer(material: Material): boolean\n readonly size: number\n /** Where program keys are read from. Until bound (or when three has no readable keys) every offered material is kept. */\n bind(renderer: PropertiesReader): void\n}\n\nexport function createMaterialAnchors(renderer?: PropertiesReader): MaterialAnchors {\n const anchors = new Set<Material>()\n let reader = renderer\n\n function coveredKeys(): Set<string> {\n const covered = new Set<string>()\n if (reader === undefined) return covered\n for (const anchor of anchors) for (const key of programKeysOf(reader, anchor) ?? []) covered.add(key)\n return covered\n }\n\n return {\n get size() {\n return anchors.size\n },\n bind(next) {\n reader = next\n },\n offer(material) {\n if (anchors.has(material)) return true\n const keys = reader === undefined ? undefined : programKeysOf(reader, material)\n if (keys === undefined) {\n anchors.add(material)\n return true\n }\n if (keys.length === 0) return false\n const covered = coveredKeys()\n if (keys.every((key) => covered.has(key))) return false\n anchors.add(material)\n return true\n },\n }\n}\n","import type { Object3D } from 'three'\n\nimport type { ThreeLib } from './three-lib'\nimport type { WarmupProbe } from './warmup-types'\n\n/** The sprite probes the room builds by hand today: one sprite material with fog and one without. */\nexport function spriteProbes(THREE: Pick<ThreeLib, 'Group' | 'Sprite' | 'SpriteMaterial' | 'DataTexture'>): WarmupProbe {\n return {\n id: 'sprite',\n build() {\n const group = new THREE.Group()\n const texture = new THREE.DataTexture(new Uint8Array([255, 255, 255, 255]), 1, 1)\n texture.needsUpdate = true\n const materials = [true, false].map((fog) => new THREE.SpriteMaterial({ map: texture, fog, transparent: true }))\n for (const material of materials) group.add(new THREE.Sprite(material))\n return { group, materials, dispose: () => texture.dispose() }\n },\n }\n}\n\nconst SHADOW_PROBE_SIDES = ['FrontSide', 'BackSide', 'DoubleSide'] as const\n\n/**\n * Shadow casters drawn into every shadow map at load: a lit material with and without a map, on each side, plain and instanced. three r160 links the\n * depth (directional, spot) and distance (point) programs only in the shadow pass (`compile` never does), keyed by the caster's map and side. And the\n * shadow pass draws every caster with one shared depth material whose program it picks again only when the caster switches between plain and\n * instanced (or skinned, batched): a textured caster drawn right after a plain one keeps the plain program, and the `USE_MAP` one links later, in play,\n * the first time a textured wall follows an instanced caster (the debris of a blast). Each probe here follows a caster of the other kind, so every\n * variant is picked and linked at load.\n */\nexport function shadowCasterProbes(\n THREE: Pick<ThreeLib, 'Group' | 'Mesh' | 'InstancedMesh' | 'MeshLambertMaterial' | 'DataTexture' | 'BufferGeometry' | 'BufferAttribute' | (typeof SHADOW_PROBE_SIDES)[number]>,\n): WarmupProbe {\n return {\n id: 'shadow-casters',\n build() {\n const group = new THREE.Group()\n const texture = new THREE.DataTexture(new Uint8Array([255, 255, 255, 255]), 1, 1)\n texture.needsUpdate = true\n const geometry = new THREE.BufferGeometry()\n geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array([0, 0, 0, 0.001, 0, 0, 0, 0.001, 0]), 3))\n geometry.setAttribute('uv', new THREE.BufferAttribute(new Float32Array([0, 0, 1, 0, 0, 1]), 2))\n const materials = SHADOW_PROBE_SIDES.flatMap((side) => [undefined, texture].map((map) => new THREE.MeshLambertMaterial({ side: THREE[side], ...(map ? { map } : {}) })))\n const instanced: Array<InstanceType<typeof THREE.InstancedMesh>> = []\n for (const material of materials) {\n // instanced, then plain: the shadow pass picks the depth program again for each, with this material's map and side\n const batch = new THREE.InstancedMesh(geometry, material, 1)\n instanced.push(batch)\n for (const caster of [batch, new THREE.Mesh(geometry, material)]) {\n caster.castShadow = true\n caster.receiveShadow = true\n // inside every shadow camera, wherever the lights are\n caster.frustumCulled = false\n group.add(caster)\n }\n }\n return {\n group,\n materials,\n dispose() {\n // the instance matrices are buffers of their own\n for (const batch of instanced) batch.dispose()\n geometry.dispose()\n texture.dispose()\n },\n }\n },\n }\n}\n\nexport function hasMissingDistanceMaterial(root: Object3D): string | undefined {\n let found: string | undefined\n root.traverse((object) => {\n const mesh = object as { isInstancedMesh?: boolean; castShadow?: boolean; customDepthMaterial?: unknown; customDistanceMaterial?: unknown }\n if (found === undefined && mesh.isInstancedMesh === true && mesh.castShadow === true && mesh.customDepthMaterial && !mesh.customDistanceMaterial) found = object.name || object.type\n })\n return found\n}\n","import type { BufferGeometry, Camera, Material, Object3D, Scene } from 'three'\n\nimport { fogStateOf, lightSignature } from './lights/scene-state'\nimport type { FogState } from './lights/types'\nimport { createMaterialAnchors } from './pools/anchors'\nimport { hasMissingDistanceMaterial } from './probes'\nimport type { ThreeLib } from './three-lib'\nimport type { EffectWarmup, ProgramWarmup, WarmupContext, WarmupOptions, WarmupProbe, WarmupReport, WarmupRenderer } from './warmup-types'\n\nconst EFFECT_STEP_SECONDS = 1 / 50\nconst DEFAULT_EFFECT_FRAMES = 3\nconst WARM_FOG_DENSITY = 0.01\nconst WARM_FOG_FAR = 100\n\ntype LinkCounter = { count: number }\ntype BuiltProbe = { readonly probe: WarmupProbe; readonly built: ReturnType<WarmupProbe['build']> }\n\nfunction register<TItem>(items: Set<TItem>, item: TItem): () => void {\n items.add(item)\n return () => void items.delete(item)\n}\n\nfunction countLinks(context: WarmupContext, counters: WeakMap<WarmupContext, LinkCounter>): void {\n const existing = counters.get(context)\n if (existing !== undefined) {\n existing.count = 0\n return\n }\n const counter: LinkCounter = { count: 0 }\n counters.set(context, counter)\n const original = context.linkProgram.bind(context)\n context.linkProgram = (program) => {\n counter.count++\n original(program)\n }\n}\n\nfunction failedProgram(renderer: WarmupRenderer): string | undefined {\n for (const program of renderer.info.programs ?? []) {\n const diagnostics = (program as { diagnostics?: { runnable?: boolean; programLog?: string } }).diagnostics\n if (diagnostics?.runnable === false) return diagnostics.programLog ?? 'program failed to link'\n }\n return undefined\n}\n\n/**\n * Finishes every program the renderer holds: three.js links a program when a material first compiles, but reads its link status, its logs and its\n * uniform locations only on the program's first draw (`getUniforms`), and that read waits for the driver to end the link: ~7 ms a program on the\n * RTX 5070 laptop, 43 ms for the six shadow-receiving programs the horde chain's first blast drew for the first time (perf.mjs, 2026-11-03).\n * A program linked here and drawn only in play (a hidden part of a vehicle, an effect of another area) pays that at load instead.\n */\nfunction finishPrograms(renderer: WarmupRenderer): number {\n let finished = 0\n for (const program of renderer.info.programs ?? []) {\n const linked = program as { getUniforms?: () => unknown; getAttributes?: () => unknown }\n if (typeof linked.getUniforms !== 'function') continue\n linked.getUniforms()\n linked.getAttributes?.()\n finished++\n }\n return finished\n}\n\nexport function createProgramWarmup(THREE: Pick<ThreeLib, 'Group' | 'Sprite' | 'SpriteMaterial' | 'DataTexture' | 'Fog' | 'FogExp2' | 'Mesh' | 'Points' | 'LineSegments' | 'BufferGeometry' | 'BufferAttribute'>): ProgramWarmup {\n const probes = new Set<WarmupProbe>()\n const effects = new Set<EffectWarmup>()\n const textures = new Set<Parameters<WarmupRenderer['initTexture']>[0]>()\n const anchors = createMaterialAnchors()\n const linkCounters = new WeakMap<WarmupContext, LinkCounter>()\n\n function setFog(scene: Scene, state: FogState): void {\n const color = scene.fog?.color.getHex() ?? 0\n if (state === 'none') scene.fog = null\n else if (state === 'linear' && (scene.fog as { isFog?: boolean } | null)?.isFog !== true) scene.fog = new THREE.Fog(color, 1, WARM_FOG_FAR)\n else if (state === 'exp2' && (scene.fog as { isFogExp2?: boolean } | null)?.isFogExp2 !== true) scene.fog = new THREE.FogExp2(color, WARM_FOG_DENSITY)\n }\n\n function draw(renderer: WarmupRenderer, scene: Scene, camera: Camera, target: WarmupOptions['target']): void {\n renderer.setRenderTarget(target ?? null)\n renderer.compile(scene, camera)\n renderer.render(scene, camera)\n }\n\n /**\n * Hides every drawable of the scene outside `root` and returns the undo. An object with a light under it stays: the lights are what the programs\n * are keyed by, and hiding one would warm programs for a light count the game never draws.\n */\n function drawOnly(scene: Scene, root: Object3D): () => void {\n const hidden: Object3D[] = []\n const visit = (object: Object3D): void => {\n if (object === root || !object.visible) return\n const drawable = object as Object3D & { isMesh?: boolean; isPoints?: boolean; isLine?: boolean; isSprite?: boolean }\n if (drawable.isMesh === true || drawable.isPoints === true || drawable.isLine === true || drawable.isSprite === true) {\n if (!holdsLight(object) && !holdsObject(object, root)) {\n object.visible = false\n hidden.push(object)\n return\n }\n }\n for (const child of object.children) visit(child)\n }\n for (const child of scene.children) visit(child)\n return () => hidden.forEach((object) => (object.visible = true))\n }\n\n function holdsLight(object: Object3D): boolean {\n let found = false\n object.traverse((each) => {\n if ((each as { isLight?: boolean }).isLight === true) found = true\n })\n return found\n }\n\n function holdsObject(object: Object3D, target: Object3D): boolean {\n for (let at: Object3D | null = target; at !== null; at = at.parent) if (at === object) return true\n return false\n }\n\n function playEffect(renderer: WarmupRenderer, scene: Scene, camera: Camera, effect: EffectWarmup, target: WarmupOptions['target']): void {\n const root = effect.root?.()\n const restore = root === null || root === undefined ? (): void => undefined : drawOnly(scene, root)\n try {\n playFrames(renderer, scene, camera, effect, target)\n } finally {\n restore()\n }\n }\n\n function playFrames(renderer: WarmupRenderer, scene: Scene, camera: Camera, effect: EffectWarmup, target: WarmupOptions['target']): void {\n effect.play()\n try {\n for (let frame = 0; frame < (effect.frames ?? DEFAULT_EFFECT_FRAMES); frame++) {\n effect.step(EFFECT_STEP_SECONDS)\n renderer.setRenderTarget(target ?? null)\n renderer.render(scene, camera)\n }\n } finally {\n effect.stop()\n }\n }\n\n /** One object per material, of the kind its program is for, each a single triangle: drawn once so that the program is used, not only linked. */\n function materialsProbe(materials: readonly Material[]): BuiltProbe {\n const geometry = new THREE.BufferGeometry()\n geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array([0, 0, 0, 0.001, 0, 0, 0, 0.001, 0]), 3))\n const group = new THREE.Group()\n for (const material of materials) group.add(drawableOf(material, geometry))\n return { probe: { id: 'materials', build: () => ({ group, materials: [], dispose: () => geometry.dispose() }) }, built: { group, materials: [], dispose: () => geometry.dispose() } }\n }\n\n function drawableOf(material: Material, geometry: BufferGeometry): Object3D {\n const flags = material as { isSpriteMaterial?: boolean; isPointsMaterial?: boolean; isLineBasicMaterial?: boolean }\n const object: Object3D =\n flags.isSpriteMaterial === true ? new THREE.Sprite(material as never)\n : flags.isPointsMaterial === true ? new THREE.Points(geometry, material)\n : flags.isLineBasicMaterial === true ? new THREE.LineSegments(geometry, material)\n : new THREE.Mesh(geometry, material)\n object.frustumCulled = false\n return object\n }\n\n function buildProbes(materials: readonly Material[] | undefined): BuiltProbe[] {\n const built = [...probes].map((probe) => ({ probe, built: probe.build() }))\n if (materials !== undefined && materials.length > 0) built.push(materialsProbe(materials))\n return built\n }\n\n function addProbes(scene: Scene, built: readonly BuiltProbe[]): void {\n for (const { probe, built: item } of built) {\n const missing = hasMissingDistanceMaterial(item.group)\n if (missing !== undefined) throw new Error(`warmup probe \"${probe.id}\": instanced mesh \"${missing}\" casts shadows with a customDepthMaterial but no customDistanceMaterial`)\n scene.add(item.group)\n }\n }\n\n function removeProbes(scene: Scene, built: readonly BuiltProbe[]): void {\n for (const { built: item } of built) {\n scene.remove(item.group)\n item.dispose()\n for (const material of item.materials) anchors.offer(material)\n }\n }\n\n function drawStates(renderer: WarmupRenderer, scene: Scene, camera: Camera, states: readonly FogState[], options: WarmupOptions): void {\n states.forEach((state, index) => {\n setFog(scene, state)\n // the depth and distance programs carry no fog: every caster once, in the first state, is enough\n const restoreCasters = index === 0 && options.shadowCasters !== 'visible' ? drawEveryCaster(scene) : (): void => undefined\n try {\n draw(renderer, scene, camera, options.target)\n } finally {\n restoreCasters()\n }\n })\n }\n\n /**\n * Turns off frustum culling of every shadow caster and returns the undo: three r160 links a caster's depth (or distance) program only when the\n * shadow pass draws it, and that pass culls by the light's shadow camera. A caster outside it at load (the sun's box follows the player) would\n * link its program the first time it enters the box, in play.\n */\n function drawEveryCaster(scene: Scene): () => void {\n const culled: Object3D[] = []\n scene.traverse((object) => {\n if (object.castShadow && object.frustumCulled) {\n object.frustumCulled = false\n culled.push(object)\n }\n })\n return () => culled.forEach((object) => (object.frustumCulled = true))\n }\n\n /** Makes every instanced batch draw at least once: three skips an empty instanced batch, and a driver finishes a program's state on its first real draw (a 200 ms stall). Returns the undo. */\n function forceDraws(scene: Scene): () => void {\n const undo: Array<() => void> = []\n scene.traverse((object) => {\n const drawable = object as Object3D & { isInstancedMesh?: boolean; count?: number; geometry?: { isInstancedBufferGeometry?: boolean; instanceCount?: number } }\n const { geometry } = drawable\n if (geometry?.isInstancedBufferGeometry === true && geometry.instanceCount === 0) {\n geometry.instanceCount = 1\n undo.push(() => (geometry.instanceCount = 0))\n }\n if (drawable.isInstancedMesh === true && drawable.count === 0) {\n drawable.count = 1\n undo.push(() => (drawable.count = 0))\n }\n })\n return () => undo.forEach((restore) => restore())\n }\n\n return {\n anchors,\n register: (probe) => register(probes, probe),\n registerEffect: (effect) => register(effects, effect),\n registerTexture: (texture) => register(textures, texture),\n warmUp(renderer, scene, camera, options = {}): WarmupReport {\n const started = performance.now()\n const { lights, target } = options\n anchors.bind(renderer)\n const originalFog = scene.fog\n const states = options.fogStates ?? [fogStateOf(scene)]\n lights?.seal(renderer, scene, { fogStates: options.fogStates, cameras: [camera], target })\n scene.traverse((object) => {\n const light = object as { castShadow?: boolean; shadow?: { needsUpdate: boolean } }\n if (light.castShadow === true && light.shadow !== undefined) light.shadow.needsUpdate = true\n })\n const built = buildProbes(options.materials)\n let restoreDraws = (): void => undefined\n try {\n addProbes(scene, built)\n restoreDraws = forceDraws(scene)\n drawStates(renderer, scene, camera, states, options)\n scene.fog = originalFog\n for (const effect of effects) playEffect(renderer, scene, camera, effect, target)\n for (const texture of textures) renderer.initTexture(texture)\n } finally {\n restoreDraws()\n scene.fog = originalFog\n removeProbes(scene, built)\n }\n // also what lets failedProgram see a broken link: three only fills `diagnostics` on the first use\n finishPrograms(renderer)\n const context = renderer.getContext()\n const uniformVectors = Number(context.getParameter(context.MAX_FRAGMENT_UNIFORM_VECTORS))\n const failure = failedProgram(renderer)\n if (failure !== undefined) {\n throw new Error(`a shader program failed to link (MAX_FRAGMENT_UNIFORM_VECTORS ${uniformVectors}, lights: ${lightSignature(scene)}): ${failure}`)\n }\n countLinks(context, linkCounters)\n // the GPU process is still working through all of the above: wait here, at load, or the first upload of play stalls on it\n if (context.RGBA !== undefined && context.UNSIGNED_BYTE !== undefined) context.readPixels?.(0, 0, 1, 1, context.RGBA, context.UNSIGNED_BYTE, new Uint8Array(4))\n return {\n programs: renderer.info.programs?.length ?? 0,\n geometries: renderer.info.memory.geometries,\n textures: renderer.info.memory.textures,\n milliseconds: performance.now() - started,\n lightSignature: lightSignature(scene),\n uniformVectors,\n anchors: anchors.size,\n }\n },\n linkedSince(renderer) {\n return linkCounters.get(renderer.getContext())?.count ?? 0\n },\n }\n}\n","const POOLED = '__pooled'\n\ntype Disposable = { dispose(): void; userData: Record<string, unknown> }\n\nfunction isDevelopment(): boolean {\n return typeof process === 'undefined' || process.env.NODE_ENV !== 'production'\n}\n\n/** Marks a pool resource and, in development, warns when something disposes it directly instead of releasing it to the pool. */\nexport function markPooled(resource: Disposable, key: string, owner: string): { disposeForPool(): void } {\n resource.userData[POOLED] = key\n const original = resource.dispose.bind(resource)\n let fromPool = false\n if (isDevelopment()) {\n resource.dispose = () => {\n if (!fromPool) console.warn(`[game-render-three] ${owner} \"${key}\" was disposed directly; release it to its pool instead`)\n original()\n }\n }\n return {\n disposeForPool() {\n fromPool = true\n original()\n fromPool = false\n },\n }\n}\n\nexport function pooledKey(resource: { userData: Record<string, unknown> }): string | undefined {\n const key = resource.userData[POOLED]\n return typeof key === 'string' ? key : undefined\n}\n\n/** A number as a short stable string, rounded to `step`. */\nexport function roundedNumber(value: number, step: number): string {\n return String(Number((Math.round(value / step) * step).toFixed(6)))\n}\n","import type { BufferGeometry } from 'three'\n\nimport { markPooled, pooledKey, roundedNumber } from './pooled'\n\nexport interface GeometryPool {\n /** The geometry for `key`, built once with `build`. Counts one use. */\n acquire(key: string, build: () => BufferGeometry): BufferGeometry\n release(geometry: BufferGeometry): void\n /** Never disposed while the pool lives (unit shapes, effect geometries warmed at load). */\n retain(key: string): void\n /** Disposes unretained geometries with no use, oldest first, keeping at most `keep` idle ones. Only at load points, never in play. */\n trim(keep?: number): number\n stats(): { readonly entries: number; readonly retained: number; readonly inUse: number }\n dispose(): void\n}\n\ntype Entry = { geometry: BufferGeometry; uses: number; retained: boolean; idleSince: number; disposeForPool(): void }\n\nconst DEFAULT_KEY_STEP = 1e-3\n\n/** Builds a key from a kind and its numbers, rounded to `step`, so near-equal sizes share one geometry. */\nexport function geometryKey(kind: string, params: readonly number[], step: number = DEFAULT_KEY_STEP): string {\n return [kind, ...params.map((value) => roundedNumber(value, step))].join('|')\n}\n\nexport function createGeometryPool(): GeometryPool {\n const entries = new Map<string, Entry>()\n let clock = 0\n\n function disposeEntry(key: string, entry: Entry): void {\n entries.delete(key)\n entry.disposeForPool()\n }\n\n return {\n acquire(key, build) {\n let entry = entries.get(key)\n if (entry === undefined) {\n const geometry = build()\n entry = { geometry, uses: 0, retained: false, idleSince: 0, ...markPooled(geometry, key, 'geometry') }\n entries.set(key, entry)\n }\n entry.uses++\n return entry.geometry\n },\n release(geometry) {\n const key = pooledKey(geometry)\n const entry = key === undefined ? undefined : entries.get(key)\n if (entry === undefined || entry.uses === 0) return\n entry.uses--\n if (entry.uses === 0) entry.idleSince = ++clock\n },\n retain(key) {\n const entry = entries.get(key)\n if (entry !== undefined) entry.retained = true\n },\n trim(keep = 0) {\n const idle = [...entries].filter(([, entry]) => entry.uses === 0 && !entry.retained).sort((a, b) => a[1].idleSince - b[1].idleSince)\n const excess = idle.slice(0, Math.max(0, idle.length - keep))\n for (const [key, entry] of excess) disposeEntry(key, entry)\n return excess.length\n },\n stats() {\n const all = [...entries.values()]\n return { entries: all.length, retained: all.filter((entry) => entry.retained).length, inUse: all.filter((entry) => entry.uses > 0).length }\n },\n dispose() {\n for (const [key, entry] of [...entries]) disposeEntry(key, entry)\n },\n }\n}\n","import type { Material } from 'three'\n\nimport type { PropertiesReader } from '../program-key'\nimport { type MaterialAnchors, createMaterialAnchors } from './anchors'\nimport { markPooled, pooledKey, roundedNumber } from './pooled'\n\nexport interface MaterialPool {\n /**\n * The material for `key`, built once. Shared: callers must not change it. Per-instance variety goes into instance attributes, not\n * into new materials.\n */\n acquire<TMaterial extends Material>(key: string, build: () => TMaterial): TMaterial\n release(material: Material): void\n /** Declares a variant that must never be disposed (its program stays linked). Effects register theirs at load. */\n register<TMaterial extends Material>(key: string, build: () => TMaterial): TMaterial\n /**\n * A material the caller owns and changes per frame (a puff's opacity): not shared. On `release` the first one of its program family is\n * handed to the anchors, so disposing the others never frees the program.\n */\n own<TMaterial extends Material>(build: () => TMaterial): TMaterial\n /** The materials declared with `register`: the ones that must never be disposed and whose programs the warmup draws once. */\n registeredMaterials?(): readonly Material[]\n /** Disposes unregistered materials with no use, oldest first, keeping at most `keep` idle ones; a family's anchor is kept alive. */\n trim(keep?: number): number\n stats(): { readonly entries: number; readonly registered: number; readonly inUse: number; readonly families: number }\n /**\n * The end of the pool: disposes every material it made, in use or not, registered or anchored (the guarantee that a program stays linked\n * holds while the pool lives, not after it). The anchors object itself is not touched, and the pool is empty and usable again afterwards.\n */\n dispose(): void\n}\n\nexport type MaterialPoolOptions = { readonly anchors?: MaterialAnchors; readonly renderer?: PropertiesReader }\n\ntype Entry = { material: Material; uses: number; registered: boolean; idleSince: number; disposeForPool(): void }\n\nconst DEFAULT_KEY_STEP = 1e-3\n\n/** Key from the material class and every parameter that changes its look, sorted, numbers rounded. */\nexport function materialKey(type: string, params: Readonly<Record<string, unknown>>): string {\n const parts = Object.keys(params)\n .sort()\n .map((name) => {\n const value = params[name]\n return `${name}=${typeof value === 'number' ? roundedNumber(value, DEFAULT_KEY_STEP) : JSON.stringify(value)}`\n })\n return [type, ...parts].join('|')\n}\n\nexport function createMaterialPool(options: MaterialPoolOptions = {}): MaterialPool {\n const anchors = options.anchors ?? createMaterialAnchors()\n if (options.renderer !== undefined) anchors.bind(options.renderer)\n const entries = new Map<string, Entry>()\n const owned = new Map<Material, () => void>()\n let clock = 0\n\n function createEntry(key: string, material: Material, registered: boolean): Entry {\n const entry: Entry = { material, uses: 0, registered, idleSince: 0, ...markPooled(material, key, 'material') }\n entries.set(key, entry)\n return entry\n }\n\n /** Disposes the material unless it is the anchor of a program family. */\n function retire(material: Material, disposeForPool: () => void): boolean {\n if (anchors.offer(material)) return false\n disposeForPool()\n return true\n }\n\n return {\n acquire(key, build) {\n const entry = entries.get(key) ?? createEntry(key, build(), false)\n entry.uses++\n return entry.material as ReturnType<typeof build>\n },\n register(key, build) {\n const entry = entries.get(key) ?? createEntry(key, build(), true)\n entry.registered = true\n return entry.material as ReturnType<typeof build>\n },\n own(build) {\n const material = build()\n owned.set(material, markPooled(material, 'own', 'material').disposeForPool)\n return material\n },\n release(material) {\n const disposeOwned = owned.get(material)\n if (disposeOwned !== undefined) {\n owned.delete(material)\n retire(material, disposeOwned)\n return\n }\n const key = pooledKey(material)\n const entry = key === undefined ? undefined : entries.get(key)\n if (entry === undefined || entry.uses === 0) return\n entry.uses--\n if (entry.uses === 0) entry.idleSince = ++clock\n },\n trim(keep = 0) {\n const idle = [...entries].filter(([, entry]) => entry.uses === 0 && !entry.registered).sort((a, b) => a[1].idleSince - b[1].idleSince)\n let disposed = 0\n for (const [key, entry] of idle.slice(0, Math.max(0, idle.length - keep))) {\n entries.delete(key)\n if (retire(entry.material, entry.disposeForPool)) disposed++\n }\n return disposed\n },\n registeredMaterials() {\n return [...entries.values()].filter((entry) => entry.registered).map((entry) => entry.material)\n },\n stats() {\n const all = [...entries.values()]\n return {\n entries: all.length,\n registered: all.filter((entry) => entry.registered).length,\n inUse: all.filter((entry) => entry.uses > 0).length,\n families: anchors.size,\n }\n },\n dispose() {\n for (const entry of entries.values()) entry.disposeForPool()\n for (const disposeOwned of owned.values()) disposeOwned()\n entries.clear()\n owned.clear()\n },\n }\n}\n","import type { GeometryPool } from './geometry'\nimport type { MaterialPool } from './material'\n\n/** The pools a host lends its adapters (`host.pools`): geometries and materials that outlive the effect that asked for them. */\nexport interface RenderPools {\n readonly geometries: GeometryPool\n readonly materials: MaterialPool\n}\n\n/** For adapters that receive the pools as `unknown` through the host (the contract does not know three). */\nexport function isRenderPools(value: unknown): value is RenderPools {\n const candidate = value as Partial<RenderPools> | null | undefined\n return typeof candidate === 'object' && candidate !== null && typeof candidate.geometries?.acquire === 'function' && typeof candidate.materials?.acquire === 'function'\n}\n","/** The part of a WebGL2 context the pacer reads; the renderer's `getContext()` satisfies it. */\nexport type FramePacerContext = {\n readonly SYNC_GPU_COMMANDS_COMPLETE: number\n readonly TIMEOUT_EXPIRED: number\n fenceSync(condition: number, flags: number): WebGLSync | null\n clientWaitSync(sync: WebGLSync, flags: number, timeout: number): number\n deleteSync(sync: WebGLSync | null): void\n flush(): void\n}\n\nexport type FramePacerOptions = {\n /** Most frames in a row the pacer may hold back before it lets one through (default 3), so a stuck fence cannot freeze the picture. */\n readonly maxSkips?: number\n /** Frames the GPU may be behind before a draw is held back (default 2). The browser reports a fence only some 20 ms after the GPU finished it, so 1 would cap every GPU at one frame per report. */\n readonly framesInFlight?: number\n}\n\nexport type FramePacer = {\n /** True when fewer than `framesInFlight` drawn frames are unfinished: draw this frame. False: the GPU is too far behind, skip the draw and keep simulating. */\n ready(): boolean\n /** Fences the frame just drawn; call it right after the render. */\n submitted(): void\n /** Draws held back so far. */\n readonly skipped: number\n dispose(): void\n}\n\nconst DEFAULT_MAX_SKIPS = 3\nconst DEFAULT_FRAMES_IN_FLIGHT = 2\n\n/**\n * Keeps the GPU a few frames behind the CPU at most. A frame loop that draws as fast as it can (no vsync, as the perf runs do, or a slow GPU) fills the driver's queue and\n * then blocks in the compositor for the length of the whole queue: a run of 5 ms frames and a 150 ms one. Holding back the draw while the last frame is unfinished spends that\n * time on the next simulation step instead, and the longest frame is the GPU's own. A context without fences (WebGL1) is never held back.\n */\nexport function createFramePacer(context: FramePacerContext | null, options: FramePacerOptions = {}): FramePacer {\n const maxSkips = options.maxSkips ?? DEFAULT_MAX_SKIPS\n const framesInFlight = options.framesInFlight ?? DEFAULT_FRAMES_IN_FLIGHT\n const fences: WebGLSync[] = []\n let skippedInRow = 0\n let skipped = 0\n const dropOldest = (): void => {\n const oldest = fences.shift()\n if (oldest && context) context.deleteSync(oldest)\n }\n return {\n ready() {\n if (!context) return true\n while (fences.length > 0 && context.clientWaitSync(fences[0] as WebGLSync, 0, 0) !== context.TIMEOUT_EXPIRED) dropOldest()\n if (fences.length >= framesInFlight && skippedInRow < maxSkips) {\n skippedInRow++\n skipped++\n return false\n }\n skippedInRow = 0\n if (fences.length >= framesInFlight) dropOldest()\n return true\n },\n submitted() {\n if (!context || typeof context.fenceSync !== 'function') return\n const fence = context.fenceSync(context.SYNC_GPU_COMMANDS_COMPLETE, 0)\n if (fence) fences.push(fence)\n context.flush()\n },\n get skipped() {\n return skipped\n },\n dispose() {\n while (fences.length > 0) dropOldest()\n },\n }\n}\n","import { DEFERRED_QUEUE_ID, drainDetached } from '@adatechnology/game-contracts'\nimport type { DeferredQueue } from '@adatechnology/game-contracts'\nimport type { Bone, BufferAttribute, BufferGeometry, Material, Matrix3, Matrix4, Mesh, Object3D, SkinnedMesh } from 'three'\n\nimport type { ThreeLib } from './three-lib'\n\n/** The layer a batched mesh is moved to: no camera draws it, a raycaster that enables every layer still finds it. */\nexport const BATCHED_LAYER = 30\n\nconst MATRIX_EPSILON = 1e-6\n\n/** What a batcher gives its queue: the chunks still to merge. One unit is one chunk (at most `maxVertices` vertices). */\nexport type StaticBatchWork = {\n pendingUnits(): number\n /** Merges the next chunk. */\n runUnit(): void\n /** Merges every chunk left. */\n finishAll(): void\n}\n\nexport type StaticBatchQueue = {\n /** The queue for a frame budget (`budget.register`); asking for it changes nothing. Its `id` is the one given to `createStaticBatchQueue`. */\n deferredQueue(): DeferredQueue\n /** A batcher joins (`createStaticBatcher` does it for the `queue` option); returns the function that takes it out. */\n join(work: StaticBatchWork): () => void\n /** Whether a budget registered the queue: from then on the batchers leave their chunks to it instead of merging in `update`. */\n isAttached(): boolean\n}\n\nexport type StaticBatchQueueOptions = {\n /** Default `DEFERRED_QUEUE_ID.STATIC_BATCH`; an owner passes its own id from `DEFERRED_QUEUE_ID`. */\n readonly id?: string\n}\n\n/**\n * One queue for every batcher of an owner (the room, the animals area, one house), run round robin over the batchers with chunks waiting so the\n * first one does not take the whole budget. Until a budget attaches it, each batcher keeps merging in its own `update`, as before.\n */\nexport function createStaticBatchQueue({ id = DEFERRED_QUEUE_ID.STATIC_BATCH }: StaticBatchQueueOptions = {}): StaticBatchQueue {\n const members: StaticBatchWork[] = []\n let cursor = 0\n let attached = false\n const deferred: DeferredQueue = {\n id,\n pending() {\n let units = 0\n for (const work of members) units += work.pendingUnits()\n return units\n },\n run(deadline, clock) {\n let ran = 0\n let skipped = 0\n while (members.length > 0 && skipped < members.length) {\n if (ran > 0 && clock() >= deadline) break\n const work = members[cursor % members.length] as StaticBatchWork\n cursor = (cursor + 1) % members.length\n if (work.pendingUnits() > 0) {\n work.runUnit()\n ran++\n skipped = 0\n } else skipped++\n }\n return ran\n },\n flush() {\n for (const work of [...members]) work.finishAll()\n },\n attach() {\n attached = true\n },\n detach() {\n attached = false\n },\n }\n return {\n deferredQueue: () => deferred,\n isAttached: () => attached,\n join(work) {\n members.push(work)\n return () => {\n const at = members.indexOf(work)\n if (at >= 0) members.splice(at, 1)\n }\n },\n }\n}\n\nexport type StaticBatcherOptions = {\n /** Which meshes may be batched (default every shown mesh with one material and no instancing, skinning or morphing). */\n readonly include?: (mesh: Mesh) => boolean\n /** Milliseconds of merging per `update` (default all at once, in the call): batches are made a chunk at a time over the next frames. Used only while no budget has registered `queue`. */\n readonly budgetMs?: number\n /**\n * The owner's queue: the chunks are merged by it, within the frame budget it is registered with, instead of in `update` (see `createStaticBatchQueue`).\n * Not registered with any budget, the batcher drains it in `update` with `budgetMs` (default all at once), so nothing becomes asynchronous by a host's absence;\n * the first merge is then in the first `update`, not in the call.\n */\n readonly queue?: StaticBatchQueue\n /**\n * The meshes move on their own (a body posed bone by bone): each batch is skinned to its meshes, so a mesh carries its part of the batch\n * wherever it goes, and only a new geometry, material, dent or hiding gives it its own draw back.\n */\n readonly followMeshes?: boolean\n /**\n * What tells materials apart for batching (default each material by itself, its `uuid`). Meshes whose materials give the same key are drawn in one batch with the\n * first one's material, so a key must be the same only for materials that draw the same (copies of one material with equal settings).\n */\n readonly materialKey?: (material: Material) => string\n /** Called with each batch as it is made and the meshes it draws (to mark where it comes from, for one). */\n readonly onBatch?: (batch: Mesh, meshes: readonly Mesh[]) => void\n /**\n * Batches only the shadow: the meshes keep drawing on their own in the camera's pass and stop casting while batched, and each batch is drawn\n * only into the shadow maps (positions only, one batch per side the depth pass draws, whatever the material). A mesh whose shadow needs its\n * own material (a cut-out map, clipping planes, displacement, a custom depth material, wireframe) is left casting on its own. A mesh that\n * changes casts its own shadow again, of its new shape, the frame it changes.\n */\n readonly shadowOnly?: boolean\n /**\n * The most vertices one batch holds (default unbounded; 65535 with `shadowOnly`): a larger group is split, in the order of the tree, so each\n * batch is merged within one `update` of a budget and is culled by the shadow camera by its own part of the object.\n */\n readonly maxVertices?: number\n}\n\nexport type StaticBatcherStats = { readonly batches: number; readonly batched: number; readonly released: number }\n\nexport type StaticBatcher = {\n /** The batch meshes, a child of the root. */\n readonly group: Object3D\n /**\n * Gives back to its own draw every batched mesh that changed since the batch was made (moved, dented, hidden, given another geometry or\n * material); returns how many it released. Call it once per frame, before the render.\n */\n update(): number\n stats(): StaticBatcherStats\n /** Every mesh draws on its own again and the batches are disposed. */\n dispose(): void\n}\n\ntype Source = {\n readonly mesh: Mesh\n readonly geometry: BufferGeometry\n readonly material: Material\n readonly version: number\n readonly local: Matrix4\n /** The mesh's world matrix when last seen unchanged: equal again, nothing moved and the local check is skipped. */\n readonly world: Matrix4\n readonly mask: number\n /** `shadowOnly`: whether the mesh cast before it was batched. */\n readonly castShadow: boolean\n readonly batch: Batch\n readonly start: number\n readonly count: number\n released: boolean\n}\n\ntype Batch = { readonly mesh: Mesh; live: number; readonly index: { array: ArrayLike<number> & { [n: number]: number }; needsUpdate: boolean } }\n\nconst ATTRIBUTES = ['position', 'normal', 'uv', 'color'] as const\n\n/** Visible all the way up to `root`; a mesh no longer under it (its model was rebuilt) is not shown. */\nconst isShown = (object: Object3D, root: Object3D): boolean => {\n for (let node: Object3D | null = object; node; node = node.parent) {\n if (node === root) return true\n if (!node.visible) return false\n }\n return false\n}\n\nconst isBatchable = (mesh: Mesh): boolean => {\n const flags = mesh as Mesh & { isInstancedMesh?: boolean; isSkinnedMesh?: boolean }\n if (flags.isInstancedMesh === true || flags.isSkinnedMesh === true || Array.isArray(mesh.material)) return false\n const geometry = mesh.geometry\n return geometry.attributes.position !== undefined && Object.keys(geometry.morphAttributes).length === 0\n}\n\nconst signatureOf = (mesh: Mesh, materialKey: (material: Material) => string, shadowOnly: boolean): string => {\n if (shadowOnly) return shadowSideKey(mesh.material as Material)\n const { attributes } = mesh.geometry\n const present = ATTRIBUTES.filter((name) => attributes[name] !== undefined).map((name) => `${name}${attributes[name]!.itemSize}`)\n return `${materialKey(mesh.material as Material)}|${present.join(',')}|${mesh.castShadow ? 1 : 0}${mesh.receiveShadow ? 1 : 0}`\n}\n\nconst uuidOf = (material: Material): string => material.uuid\n\ntype DepthLike = Material & { map?: unknown; alphaMap?: unknown; displacementMap?: unknown; displacementScale?: number; wireframe?: boolean }\n\n/** The depth pass draws this mesh with the light's plain depth material: nothing of its material but the side changes its shadow (WebGLShadowMap's `getDepthMaterial`). */\nconst castsPlainShadow = (mesh: Mesh): boolean => {\n const material = mesh.material as DepthLike\n const custom = mesh as Mesh & { customDepthMaterial?: Material; customDistanceMaterial?: Material }\n if (!mesh.castShadow || !material.visible || custom.customDepthMaterial || custom.customDistanceMaterial) return false\n if (material.wireframe === true || (material.clippingPlanes?.length ?? 0) > 0) return false\n if (material.displacementMap && material.displacementScale !== 0) return false\n return !(material.alphaTest > 0 && (material.map || material.alphaMap))\n}\n\n/** The sides the depth pass draws a material with: batches of the shadow are made one per pair. */\nconst shadowSideKey = (material: Material): string => `${material.side}|${material.shadowSide ?? ''}`\n\nconst sameMatrix = (a: Matrix4, b: Matrix4): boolean => {\n const left = a.elements\n const right = b.elements\n for (let at = 0; at < 16; at++) if (Math.abs((left[at] as number) - (right[at] as number)) >= MATRIX_EPSILON) return false\n return true\n}\n\n/**\n * Draws the still, undamaged meshes of an object (a vehicle, a piece of furniture) as one batch per material, and gives each mesh its own draw\n * back the moment it changes. The meshes stay where they are: what hits, dents or cuts them works on them as before, they only leave the\n * camera's layer while batched.\n */\nexport function createStaticBatcher(THREE: ThreeLib, root: Object3D, options: StaticBatcherOptions = {}): StaticBatcher {\n const include = options.include ?? (() => true)\n const shadowOnly = options.shadowOnly === true\n const follow = options.followMeshes === true && !shadowOnly\n root.updateMatrixWorld(true)\n const inverse = new THREE.Matrix4().copy(root.matrixWorld).invert()\n const materialKey = options.materialKey ?? uuidOf\n const groups = new Map<string, Mesh[]>()\n root.traverse((object) => {\n const mesh = object as Mesh\n if (!mesh.isMesh || !isShown(mesh, root) || !isBatchable(mesh) || (shadowOnly && !castsPlainShadow(mesh)) || !include(mesh)) return\n const key = signatureOf(mesh, materialKey, shadowOnly)\n const waiting = groups.get(key)\n if (waiting) waiting.push(mesh)\n else groups.set(key, [mesh])\n })\n const group = new THREE.Group()\n group.name = 'static-batches'\n const sources: Source[] = []\n const maxVertices = options.maxVertices ?? (shadowOnly ? 65535 : Number.POSITIVE_INFINITY)\n const chunks = (meshes: Mesh[]): Mesh[][] => {\n const out: Mesh[][] = [[]]\n let vertices = 0\n for (const mesh of meshes) {\n const count = (mesh.geometry.attributes.position as BufferAttribute).count\n if (vertices + count > maxVertices && (out[out.length - 1] as Mesh[]).length > 0) {\n out.push([])\n vertices = 0\n }\n ;(out[out.length - 1] as Mesh[]).push(mesh)\n vertices += count\n }\n return out\n }\n const pending = [...groups.entries()].flatMap(([key, meshes]) => chunks(meshes).map((chunk) => [key, chunk] as [string, Mesh[]])).filter(([, meshes]) => meshes.length >= 2)\n // the layers each waiting mesh had when grouped: one whose layers changed before its group is merged (another drawer took it) is not merged\n const groupedMasks = new Map<Mesh, number>()\n for (const [, meshes] of pending) for (const mesh of meshes) groupedMasks.set(mesh, mesh.layers.mask)\n /**\n * Still as it was grouped: shown, included, the same layers and the same signature (a material swapped or a colour attribute added since would be merged under the\n * group's material, or copied from an attribute the group does not have; with `shadowOnly`, a shadow that now needs its own material).\n */\n const isUnchanged = (mesh: Mesh, key: string): boolean =>\n isShown(mesh, root) && include(mesh) && isBatchable(mesh) && (!shadowOnly || castsPlainShadow(mesh)) && mesh.layers.mask === groupedMasks.get(mesh) && signatureOf(mesh, materialKey, shadowOnly) === key\n const mergeNext = (): void => {\n const [key, meshes] = pending.shift() as [string, Mesh[]]\n // a mesh that changed while it waited is left as it is; the rest of its group is merged\n const still = meshes.filter((mesh) => isUnchanged(mesh, key))\n for (const mesh of meshes) groupedMasks.delete(mesh)\n if (still.length < 2) return\n inverse.copy(root.matrixWorld).invert()\n for (const source of mergeGroup(THREE, { meshes: still, inverse, group, follow, shadowOnly, onBatch: options.onBatch })) sources.push(source)\n }\n const queue = options.queue ?? createStaticBatchQueue()\n const leaveQueue = queue.join({\n pendingUnits: () => pending.length,\n runUnit: mergeNext,\n finishAll() {\n while (pending.length > 0) mergeNext()\n },\n })\n // nobody asked for the merge to wait: made in the call, as ever\n if (options.budgetMs === undefined && options.queue === undefined) while (pending.length > 0) mergeNext()\n root.add(group)\n const scratch = new THREE.Matrix4()\n let released = 0\n\n const release = (source: Source): void => {\n source.released = true\n if (shadowOnly) source.mesh.castShadow = source.castShadow\n else source.mesh.layers.mask = source.mask\n const { index } = source.batch\n const first = index.array[source.start] as number\n for (let at = source.start; at < source.start + source.count; at++) index.array[at] = first\n index.needsUpdate = true\n // a batch whose meshes all draw on their own again is an empty draw: it leaves the screen\n if (--source.batch.live === 0) source.batch.mesh.visible = false\n released++\n }\n const hasChanged = (source: Source): boolean => {\n const { mesh } = source\n if (mesh.geometry !== source.geometry || mesh.material !== source.material || !isShown(mesh, root)) return true\n if ((mesh.geometry.attributes.position as BufferAttribute).version !== source.version) return true\n if (follow || sameMatrix(mesh.matrixWorld, source.world)) return false\n if (!sameMatrix(scratch.multiplyMatrices(inverse, mesh.matrixWorld), source.local)) return true\n // the whole object moved, the mesh did not move within it\n source.world.copy(mesh.matrixWorld)\n return false\n }\n\n return {\n group,\n update() {\n if (pending.length > 0 && !queue.isAttached()) drainDetached(queue.deferredQueue(), options.budgetMs ?? Number.POSITIVE_INFINITY)\n const before = released\n inverse.copy(root.matrixWorld).invert()\n for (const source of sources) if (!source.released && hasChanged(source)) release(source)\n return released - before\n },\n stats: () => ({ batches: group.children.length, batched: sources.filter((source) => !source.released).length, released }),\n dispose() {\n for (const source of sources) {\n if (source.released) continue\n if (shadowOnly) source.mesh.castShadow = source.castShadow\n else source.mesh.layers.mask = source.mask\n }\n leaveQueue()\n pending.length = 0\n groupedMasks.clear()\n group.removeFromParent()\n for (const child of group.children) {\n ;(child as Mesh).geometry.dispose()\n if (shadowOnly) ((child as Mesh).material as Material).dispose()\n ;(child as SkinnedMesh).skeleton?.dispose()\n }\n },\n }\n}\n\n/** Whether the attribute's array is read as it is stored: no interleaving, no normalization (`getX` would then return the same numbers as the array). */\nconst isPlain = (attribute: BufferAttribute): boolean => !(attribute as { isInterleavedBufferAttribute?: boolean }).isInterleavedBufferAttribute && !attribute.normalized\n\n/** Copies `attribute` into `target` at `offset` vertices: positions through `matrix`, normals through its normal matrix, the rest as they are. */\nfunction copyAttribute(name: string, attribute: BufferAttribute, target: Float32Array, offset: number, matrix: Matrix4 | Matrix3): void {\n const size = attribute.itemSize\n const count = attribute.count\n const source = attribute.array as ArrayLike<number>\n const plain = isPlain(attribute)\n if (name !== 'position' && name !== 'normal') {\n if (!(attribute as { isInterleavedBufferAttribute?: boolean }).isInterleavedBufferAttribute && source.length === count * size) target.set(source as Float32Array, offset * size)\n else for (let at = 0; at < count; at++) for (let k = 0; k < size; k++) target[(offset + at) * size + k] = attribute.getComponent(at, k)\n return\n }\n const e = matrix.elements\n const isNormal = name === 'normal'\n for (let at = 0; at < count; at++) {\n const x = plain ? (source[at * size] as number) : attribute.getX(at)\n const y = plain ? (source[at * size + 1] as number) : attribute.getY(at)\n const z = plain ? (source[at * size + 2] as number) : attribute.getZ(at)\n const out = (offset + at) * 3\n if (isNormal) {\n const nx = e[0]! * x + e[3]! * y + e[6]! * z\n const ny = e[1]! * x + e[4]! * y + e[7]! * z\n const nz = e[2]! * x + e[5]! * y + e[8]! * z\n const length = Math.hypot(nx, ny, nz) || 1\n target[out] = nx / length\n target[out + 1] = ny / length\n target[out + 2] = nz / length\n } else {\n target[out] = e[0]! * x + e[4]! * y + e[8]! * z + e[12]!\n target[out + 1] = e[1]! * x + e[5]! * y + e[9]! * z + e[13]!\n target[out + 2] = e[2]! * x + e[6]! * y + e[10]! * z + e[14]!\n }\n }\n}\n\ntype MergeGroupParams = {\n readonly meshes: readonly Mesh[]\n readonly inverse: Matrix4\n readonly group: Object3D\n readonly follow: boolean\n readonly shadowOnly: boolean\n readonly onBatch: StaticBatcherOptions['onBatch']\n}\n\n/** A skinned batch whose bone `n` is mesh `n` itself (no inverse, no bind offset): every vertex lands where its own mesh puts it. */\nfunction skinnedBatch(THREE: ThreeLib, merged: BufferGeometry, material: Material, meshes: readonly Mesh[]): Mesh {\n const vertices = (merged.attributes.position as BufferAttribute).count\n const skinIndex = new Uint16Array(vertices * 4)\n const skinWeight = new Float32Array(vertices * 4)\n let at = 0\n meshes.forEach((mesh, bone) => {\n for (let k = 0; k < (mesh.geometry.attributes.position as BufferAttribute).count; k++, at++) {\n skinIndex[at * 4] = bone\n skinWeight[at * 4] = 1\n }\n })\n merged.setAttribute('skinIndex', new THREE.BufferAttribute(skinIndex, 4))\n merged.setAttribute('skinWeight', new THREE.BufferAttribute(skinWeight, 4))\n const mesh = new THREE.SkinnedMesh(merged, material)\n const identities = meshes.map(() => new THREE.Matrix4())\n mesh.bind(new THREE.Skeleton(meshes as unknown as Bone[], identities), new THREE.Matrix4())\n // the parts move apart as the body is posed: the rest-pose bounds would cull the moved ones\n mesh.frustumCulled = false\n return mesh\n}\n\n/**\n * A batch drawn only into the shadow maps. The camera's pass and the shadow pass both skip a mesh by the same tests (visible, layers, its\n * material's `visible`), so the batch is left in the camera's pass with an empty draw range (three returns before the draw call) and given its\n * whole range only around its own shadow draws.\n */\nfunction shadowBatch(THREE: ThreeLib, merged: BufferGeometry, like: Material): Mesh {\n const material = new THREE.MeshBasicMaterial({ colorWrite: false, depthWrite: false, side: like.side })\n material.shadowSide = like.shadowSide\n material.name = 'shadow-batch'\n const mesh = new THREE.Mesh(merged, material)\n merged.setDrawRange(0, -1)\n mesh.onBeforeShadow = () => merged.setDrawRange(0, Number.POSITIVE_INFINITY)\n mesh.onAfterShadow = () => merged.setDrawRange(0, -1)\n mesh.castShadow = true\n mesh.receiveShadow = false\n return mesh\n}\n\nfunction mergeGroup(THREE: ThreeLib, { meshes, inverse: rootInverse, group, follow, shadowOnly, onBatch }: MergeGroupParams): Source[] {\n const identity = new THREE.Matrix4()\n const inverse = follow ? identity : rootInverse\n const first = meshes[0] as Mesh\n // the depth pass reads positions only\n const names = shadowOnly ? (['position'] as const) : ATTRIBUTES.filter((name) => first.geometry.attributes[name] !== undefined)\n const pieces = meshes.map((mesh) => {\n const local = new THREE.Matrix4().multiplyMatrices(inverse, mesh.matrixWorld)\n const vertices = (mesh.geometry.attributes.position as BufferAttribute).count\n const indexCount = mesh.geometry.index ? mesh.geometry.index.count : vertices\n return { mesh, local, vertices, indexCount }\n })\n const totalVertices = pieces.reduce((sum, piece) => sum + piece.vertices, 0)\n const totalIndices = pieces.reduce((sum, piece) => sum + piece.indexCount, 0)\n const merged = new THREE.BufferGeometry()\n const normalMatrices = (names as readonly string[]).includes('normal') ? pieces.map((piece) => new THREE.Matrix3().getNormalMatrix(follow ? identity : piece.local)) : []\n for (const name of names) {\n const size = first.geometry.attributes[name]!.itemSize\n const array = new Float32Array(totalVertices * size)\n let offset = 0\n for (const [at, piece] of pieces.entries()) {\n const matrix = name === 'normal' ? (normalMatrices[at] as Matrix3) : follow ? identity : piece.local\n copyAttribute(name, piece.mesh.geometry.attributes[name] as BufferAttribute, array, offset, matrix)\n offset += piece.vertices\n }\n merged.setAttribute(name, new THREE.BufferAttribute(array, size))\n }\n const indexArray = totalVertices > 65535 ? new Uint32Array(totalIndices) : new Uint16Array(totalIndices)\n const indexAttribute = new THREE.BufferAttribute(indexArray, 1)\n merged.setIndex(indexAttribute)\n const mesh = shadowOnly ? shadowBatch(THREE, merged, first.material as Material) : follow ? skinnedBatch(THREE, merged, first.material as Material, meshes) : new THREE.Mesh(merged, first.material)\n mesh.name = shadowOnly ? `shadow-batch:${shadowSideKey(first.material as Material)}` : `batch:${(first.material as Material).name || (first.material as Material).type}`\n if (!shadowOnly) {\n mesh.castShadow = first.castShadow\n mesh.receiveShadow = first.receiveShadow\n }\n mesh.raycast = () => undefined\n merged.computeBoundingBox()\n merged.computeBoundingSphere()\n group.add(mesh)\n onBatch?.(mesh, meshes)\n const batch: Batch = { mesh, live: pieces.length, index: indexAttribute as unknown as Batch['index'] }\n const sources: Source[] = []\n let vertexOffset = 0\n let indexOffset = 0\n for (const piece of pieces) {\n const index = piece.mesh.geometry.index\n if (index) {\n const indices = index.array as ArrayLike<number>\n for (let at = 0; at < piece.indexCount; at++) indexArray[indexOffset + at] = (indices[at] as number) + vertexOffset\n }\n else for (let at = 0; at < piece.indexCount; at++) indexArray[indexOffset + at] = at + vertexOffset\n sources.push({\n mesh: piece.mesh,\n geometry: piece.mesh.geometry,\n material: piece.mesh.material as Material,\n version: (piece.mesh.geometry.attributes.position as BufferAttribute).version,\n local: piece.local,\n world: piece.mesh.matrixWorld.clone(),\n mask: piece.mesh.layers.mask,\n castShadow: piece.mesh.castShadow,\n batch,\n start: indexOffset,\n count: piece.indexCount,\n released: false,\n })\n if (shadowOnly) piece.mesh.castShadow = false\n else piece.mesh.layers.set(BATCHED_LAYER)\n vertexOffset += piece.vertices\n indexOffset += piece.indexCount\n }\n return sources\n}\n"],"mappings":";AAIA,IAAM,WAAW;AACjB,IAAM,gBAAgB;AACtB,IAAM,gBAAgB,KAAK,KAAK;AAChC,IAAM,mBAAmB;AAmDlB,SAAS,aAAa,MAA8G;AACzI,SAAO;AAAA,IACL,OAAO;AAAA,IACP,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,UAAU;AAAA,IACV,GAAG;AAAA,IACH,UAAU,CAAC,GAAG,KAAK,QAAQ;AAAA,EAC7B;AACF;AAEO,SAAS,YAAY,QAAqB,OAAyB;AACxE,MAAI,MAAM,UAAU,OAAW,QAAO,QAAQ,MAAM;AACpD,MAAI,MAAM,cAAc,OAAW,QAAO,YAAY,MAAM;AAC5D,MAAI,MAAM,aAAa,OAAW,QAAO,WAAW,MAAM;AAC1D,MAAI,MAAM,UAAU,OAAW,QAAO,QAAQ,MAAM;AACpD,MAAI,MAAM,aAAa,OAAW,QAAO,WAAW,CAAC,GAAG,M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AO;AACT,YAAM,UAAU,MAAM;AACtB,eAAS,KAAK,GAAG,KAAK,MAAM,YAAY,KAAM,YAAW,cAAc,EAAE,IAAK,QAAQ,EAAE,IAAe;AAAA,IACzG,MACK,UAAS,KAAK,GAAG,KAAK,MAAM,YAAY,KAAM,YAAW,cAAc,EAAE,IAAI,KAAK;AACvF,YAAQ,KAAK;AAAA,MACX,MAAM,MAAM;AAAA,MACZ,UAAU,MAAM,KAAK;AAAA,MACrB,UAAU,MAAM,KAAK;AAAA,MACrB,SAAU,MAAM,KAAK,SAAS,WAAW,SAA6B;AAAA,MACtE,OAAO,MAAM;AAAA,MACb,OAAO,MAAM,KAAK,YAAY,MAAM;AAAA,MACpC,MAAM,MAAM,KAAK,OAAO;AAAA,MACxB,YAAY,MAAM,KAAK;AAAA,MACvB;AAAA,MACA,OAAO;AAAA,MACP,OAAO,MAAM;AAAA,MACb,UAAU;AAAA,IACZ,CAAC;AACD,QAAI,WAAY,OAAM,KAAK,aAAa;AAAA,QACnC,OAAM,KAAK,OAAO,IAAI,aAAa;AACxC,oBAAgB,MAAM;AACtB,mBAAe,MAAM;AAAA,EACvB;AACA,SAAO;AACT;","names":["scene","DEFAULT_KEY_STEP","materialKey","mesh"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adatechnology/game-render-three",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "license": "MIT",
5
5
  "description": "Owner of the GPU-facing state of a three.js game: the one ThreeLib type, a LightBudget with a fixed number of lights (slots, priority, fades), a ProgramWarmup that links every shader program at load and keeps it linked, and geometry and material pools.",
6
6
  "keywords": [
@@ -37,6 +37,9 @@
37
37
  "peerDependencies": {
38
38
  "three": "^0.160.0"
39
39
  },
40
+ "dependencies": {
41
+ "@adatechnology/game-contracts": "^0.37.0"
42
+ },
40
43
  "devDependencies": {
41
44
  "@types/node": "^22.10.7",
42
45
  "@types/three": "^0.160.0",