@expofp/renderer 3.49.2 → 3.50.0

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.
@@ -106,6 +106,11 @@ export declare class SquareDataTexture extends DataTexture {
106
106
  * @default Infinity
107
107
  */
108
108
  maxUpdateCalls: number;
109
+ /**
110
+ * Counts every write, partial ones included, so a reader can tell the data changed. `version`
111
+ * cannot: it moves only for a full upload.
112
+ */
113
+ revision: number;
109
114
  /** Format/type conversion helper, built on first upload. */
110
115
  protected _utils: WebGLUtils | null;
111
116
  /** Whether any row has been marked since the last upload. */
@@ -83,6 +83,11 @@ export class SquareDataTexture extends DataTexture {
83
83
  * @default Infinity
84
84
  */
85
85
  maxUpdateCalls = Infinity;
86
+ /**
87
+ * Counts every write, partial ones included, so a reader can tell the data changed. `version`
88
+ * cannot: it moves only for a full upload.
89
+ */
90
+ revision = 0;
86
91
  /** Format/type conversion helper, built on first upload. */
87
92
  _utils = null;
88
93
  /** Whether any row has been marked since the last upload. */
@@ -159,6 +164,7 @@ export class SquareDataTexture extends DataTexture {
159
164
  */
160
165
  enqueueUpdate(index) {
161
166
  this._needsUpdate = true;
167
+ this.revision++;
162
168
  if (!this.partialUpdate)
163
169
  return;
164
170
  const elementsPerRow = this.image.width / this._pixelsPerInstance;
@@ -79,6 +79,11 @@ export declare class InstancedMeshImpl extends Mesh<BufferGeometry, Material | M
79
79
  perObjectFrustumCulled: boolean;
80
80
  /** Whether instances are depth-sorted (via {@link customSort}) before drawing. */
81
81
  sortObjects: boolean;
82
+ /**
83
+ * Whether the mesh draws into the shadow map a given shadow camera renders. `null` draws into
84
+ * every map. A declined pass draws zero instances.
85
+ */
86
+ shadowFilter: ((shadowCamera: Camera) => boolean) | null;
82
87
  /** Bounding box enclosing every instance; nulled on mutation and recomputed on demand. */
83
88
  boundingBox: Box3 | null;
84
89
  /** Bounding sphere enclosing every instance; nulled on mutation and recomputed on demand. */
@@ -69,6 +69,11 @@ export class InstancedMeshImpl extends Mesh {
69
69
  perObjectFrustumCulled = true;
70
70
  /** Whether instances are depth-sorted (via {@link customSort}) before drawing. */
71
71
  sortObjects = false;
72
+ /**
73
+ * Whether the mesh draws into the shadow map a given shadow camera renders. `null` draws into
74
+ * every map. A declined pass draws zero instances.
75
+ */
76
+ shadowFilter = null;
72
77
  /** Bounding box enclosing every instance; nulled on mutation and recomputed on demand. */
73
78
  boundingBox = null;
74
79
  /** Bounding sphere enclosing every instance; nulled on mutation and recomputed on demand. */
@@ -397,6 +402,8 @@ export class InstancedMeshImpl extends Mesh {
397
402
  }
398
403
  onBeforeShadow(renderer, scene, camera, shadowCamera, geometry, depthMaterial, group) {
399
404
  this.onBeforeRender(renderer, scene, shadowCamera, geometry, depthMaterial, group);
405
+ if (this.shadowFilter && !this.shadowFilter(shadowCamera))
406
+ this.count = 0;
400
407
  }
401
408
  onAfterShadow(renderer, scene, camera, shadowCamera, geometry, depthMaterial, group) {
402
409
  this.onAfterRender(renderer, scene, shadowCamera, geometry, depthMaterial, group);
@@ -291,6 +291,11 @@ export declare abstract class SlotContainer<R, M extends SlotMesh = SlotMesh, T
291
291
  * mesh a rebuilt member list instead.
292
292
  */
293
293
  protected applyOrder(): void;
294
+ /**
295
+ * Every claimed slot and the def it draws, for a container that rewrites them all at once.
296
+ * @returns The live claims, keyed by slot.
297
+ */
298
+ protected claims(): ReadonlyMap<number, RenderableDef>;
294
299
  /**
295
300
  * The slot a def holds, for an order pass walking the layer's defs.
296
301
  * @param def - The def to look up.
@@ -300,6 +300,13 @@ export class SlotContainer {
300
300
  this.dimmedBySlot[slot] = isDimmed(def.dim, this.layerDimmed);
301
301
  }
302
302
  }
303
+ /**
304
+ * Every claimed slot and the def it draws, for a container that rewrites them all at once.
305
+ * @returns The live claims, keyed by slot.
306
+ */
307
+ claims() {
308
+ return this.defBySlot;
309
+ }
303
310
  /**
304
311
  * The slot a def holds, for an order pass walking the layer's defs.
305
312
  * @param def - The def to look up.
@@ -12,7 +12,7 @@ import { applySunShadowCatcher, SHADOW_FROM_VIEW, SUN_SHADOW_STRENGTH, } from '.
12
12
  import { setDefaultModelOpacity } from '../models/model-opacity';
13
13
  import { useLightingGui } from './lighting-gui';
14
14
  import { hasLitMaterial, loadStudioEnvironment, markEnvironmentPending, orientEnvironment, STUDIO_HDRI_URL, } from './studio-environment';
15
- import { aimSun, CATCHER_ELEVATION, CATCHER_RENDER_ORDER, enableShadowMaps, fitShadowCamera, hasVisibleCaster, SHADOW_MAP_SIZE, SHADOW_RADIUS, } from './sun-shadow-map';
15
+ import { aimSun, CATCHER_ELEVATION, CATCHER_RENDER_ORDER, enableShadowMaps, fitShadowCamera, hasVisibleCaster, SHADOW_MAP_SIZE, SHADOW_RADIUS, syncMovingSun, } from './sun-shadow-map';
16
16
  const logger = createLogger('lighting');
17
17
  /**
18
18
  * Scene lighting: a hemisphere fill along the plan's up axis, and a warm directional light at a
@@ -57,11 +57,13 @@ export function Lighting(props) {
57
57
  const appliedRef = useRef({ sky: '', ground: '', directional: '' });
58
58
  const catcherRef = useRef(null);
59
59
  const sunRef = useRef(null);
60
+ const movingSunRef = useRef(null);
60
61
  const get = useThree((state) => state.get);
61
62
  const [studio, setStudio] = useState(null);
62
63
  useLayoutEffect(() => {
63
64
  directionalRef.current.target = targetRef.current;
64
65
  sunRef.current.target = targetRef.current;
66
+ movingSunRef.current.target = targetRef.current;
65
67
  }, []);
66
68
  // The studio HDRI, prefiltered once, plus its irradiance for the roof pin. It loads once the scene
67
69
  // holds a lit material, so a plan of flat 2D content skips the download.
@@ -121,11 +123,14 @@ export function Lighting(props) {
121
123
  const casting = settings.sunShadow.enabled && hasVisibleCaster(scene);
122
124
  sun.castShadow = casting;
123
125
  catcherRef.current.visible = casting;
124
- if (!casting)
126
+ if (!casting) {
127
+ syncMovingSun(movingSunRef.current, sun, false);
125
128
  return;
129
+ }
126
130
  // Fitted here, after camera-controls has moved the camera, so a fast zoom is measured with the
127
131
  // camera this frame draws with.
128
132
  fitShadowCamera(sun, scene, space, catcherRef.current, camera);
133
+ syncMovingSun(movingSunRef.current, sun, hasVisibleCaster(scene, true));
129
134
  sun.shadow.updateMatrices(sun);
130
135
  _cameraWorld.copy(camera.matrixWorldInverse).invert();
131
136
  SHADOW_FROM_VIEW.value.multiplyMatrices(sun.shadow.matrix, _cameraWorld);
@@ -264,7 +269,7 @@ export function Lighting(props) {
264
269
  strength / Math.max(Math.sin(degToRad(settings.sunShadow.elevationDegrees)), 0.05);
265
270
  }
266
271
  });
267
- return (_jsxs(_Fragment, { children: [_jsx("hemisphereLight", { ref: fillRef, color: LIGHT_DEFAULTS.skyColor, groundColor: LIGHT_DEFAULTS.groundColor, intensity: DEFAULT_INTENSITIES.hemisphereIntensity * Math.PI }), _jsx("directionalLight", { ref: directionalRef, color: LIGHT_DEFAULTS.directionalColor, intensity: DEFAULT_INTENSITIES.directionalIntensity * Math.PI }), _jsx("object3D", { ref: targetRef }), _jsx("directionalLight", { ref: sunRef, intensity: 0 }), _jsxs("mesh", { ref: catcherRef, position: [0, 0, CATCHER_ELEVATION], receiveShadow: true, renderOrder: CATCHER_RENDER_ORDER, raycast: () => null, visible: false, children: [_jsx("planeGeometry", { args: [1, 1] }), _jsx("shadowMaterial", { color: "#000000", depthWrite: false, onBeforeCompile: applySunShadowCatcher })] })] }));
272
+ return (_jsxs(_Fragment, { children: [_jsx("hemisphereLight", { ref: fillRef, color: LIGHT_DEFAULTS.skyColor, groundColor: LIGHT_DEFAULTS.groundColor, intensity: DEFAULT_INTENSITIES.hemisphereIntensity * Math.PI }), _jsx("directionalLight", { ref: directionalRef, color: LIGHT_DEFAULTS.directionalColor, intensity: DEFAULT_INTENSITIES.directionalIntensity * Math.PI }), _jsx("object3D", { ref: targetRef }), _jsx("directionalLight", { ref: sunRef, intensity: 0 }), _jsx("directionalLight", { ref: movingSunRef, intensity: 0 }), _jsxs("mesh", { ref: catcherRef, position: [0, 0, CATCHER_ELEVATION], receiveShadow: true, renderOrder: CATCHER_RENDER_ORDER, raycast: () => null, visible: false, children: [_jsx("planeGeometry", { args: [1, 1] }), _jsx("shadowMaterial", { color: "#000000", depthWrite: false, onBeforeCompile: applySunShadowCatcher })] })] }));
268
273
  }
269
274
  /**
270
275
  * A fresh rig from the defaults, its nested groups copied too, so each mount owns its own.
@@ -1,4 +1,5 @@
1
1
  import { type Camera, type DirectionalLight, type Mesh, type Scene, Vector3, type WebGLRenderer } from 'three';
2
+ import { type InstancedMeshImpl } from '../../core/instanced/InstancedMesh';
2
3
  import { type Space } from '../../space/Space';
3
4
  import { type LightSettings } from './Lighting';
4
5
  /**
@@ -44,11 +45,29 @@ export declare function fitShadowCamera(light: DirectionalLight, scene: Scene, s
44
45
  /**
45
46
  * Whether any visible mesh casts the sun's shadow.
46
47
  * @param scene - The scene.
48
+ * @param moving - Counts only casters routed to the moving map when `true`.
47
49
  * @returns Whether one does.
48
50
  */
49
- export declare function hasVisibleCaster(scene: Scene): boolean;
51
+ export declare function hasVisibleCaster(scene: Scene, moving?: boolean): boolean;
52
+ /**
53
+ * Sends a caster's shadow to one of the two maps. A moving caster draws only into the moving sun's
54
+ * map, which redraws every frame, so the still map does not have to.
55
+ * @param mesh - The caster.
56
+ * @param moving - Whether it moves on its own, frame to frame.
57
+ */
58
+ export declare function routeShadow(mesh: InstancedMeshImpl, moving: boolean): void;
59
+ /**
60
+ * Makes `moving` the sun for moving casters: the same direction, fit and filtering as `sun`, so one
61
+ * lookup matrix reads both maps, and a redraw each frame while it casts.
62
+ * @param moving - The moving casters' sun.
63
+ * @param sun - The still sun, already fitted for this frame.
64
+ * @param casting - Whether any moving caster is visible.
65
+ */
66
+ export declare function syncMovingSun(moving: DirectionalLight, sun: DirectionalLight, casting: boolean): void;
50
67
  /** The shadow map's width and height, in texels: about 64 MB of depth. */
51
68
  export declare const SHADOW_MAP_SIZE = 4096;
69
+ /** The moving casters' shadow map's width and height, in texels. */
70
+ export declare const MOVING_SHADOW_MAP_SIZE = 2048;
52
71
  /** The shadow lookup's spread, in texels. */
53
72
  export declare const SHADOW_RADIUS = 2;
54
73
  /**
@@ -89,16 +89,63 @@ export function fitShadowCamera(light, scene, space, catcher, viewCamera) {
89
89
  /**
90
90
  * Whether any visible mesh casts the sun's shadow.
91
91
  * @param scene - The scene.
92
+ * @param moving - Counts only casters routed to the moving map when `true`.
92
93
  * @returns Whether one does.
93
94
  */
94
- export function hasVisibleCaster(scene) {
95
+ export function hasVisibleCaster(scene, moving = false) {
95
96
  let found = false;
96
97
  scene.traverseVisible((object) => {
97
- if (!found && object.isMesh && object.castShadow)
98
+ if (found || !object.isMesh || !object.castShadow)
99
+ return;
100
+ if (!moving || isMovingCaster(object))
98
101
  found = true;
99
102
  });
100
103
  return found;
101
104
  }
105
+ /**
106
+ * Sends a caster's shadow to one of the two maps. A moving caster draws only into the moving sun's
107
+ * map, which redraws every frame, so the still map does not have to.
108
+ * @param mesh - The caster.
109
+ * @param moving - Whether it moves on its own, frame to frame.
110
+ */
111
+ export function routeShadow(mesh, moving) {
112
+ mesh.userData[MOVING_CASTER] = moving;
113
+ mesh.shadowFilter = (shadowCamera) => (shadowCamera.userData[MOVING_CASTER] === true) === moving;
114
+ }
115
+ /**
116
+ * Makes `moving` the sun for moving casters: the same direction, fit and filtering as `sun`, so one
117
+ * lookup matrix reads both maps, and a redraw each frame while it casts.
118
+ * @param moving - The moving casters' sun.
119
+ * @param sun - The still sun, already fitted for this frame.
120
+ * @param casting - Whether any moving caster is visible.
121
+ */
122
+ export function syncMovingSun(moving, sun, casting) {
123
+ moving.castShadow = casting;
124
+ if (!casting)
125
+ return;
126
+ moving.shadow.autoUpdate = false;
127
+ moving.position.copy(sun.position);
128
+ moving.shadow.camera.copy(sun.shadow.camera);
129
+ moving.shadow.camera.userData[MOVING_CASTER] = true;
130
+ // Smaller than the still map: clearing and storing a full-size depth map every frame is most of
131
+ // what the moving pass costs. The radius stays in texels, because a spread under one texel shows
132
+ // the larger texels as steps; the moving shadow is softer instead.
133
+ moving.shadow.mapSize.set(MOVING_SHADOW_MAP_SIZE, MOVING_SHADOW_MAP_SIZE);
134
+ moving.shadow.radius = sun.shadow.radius;
135
+ // Both biases are sized to a texel, and the moving map's texels are larger.
136
+ const texelRatio = sun.shadow.mapSize.x / MOVING_SHADOW_MAP_SIZE;
137
+ moving.shadow.bias = sun.shadow.bias * texelRatio;
138
+ moving.shadow.normalBias = sun.shadow.normalBias * texelRatio;
139
+ moving.shadow.needsUpdate = true;
140
+ }
141
+ /**
142
+ * Whether a caster draws into the moving map; see {@link routeShadow}.
143
+ * @param object - The caster.
144
+ * @returns Whether it does.
145
+ */
146
+ function isMovingCaster(object) {
147
+ return object.userData[MOVING_CASTER] === true;
148
+ }
102
149
  /**
103
150
  * Collects the visible casters into `_casters`, and describes the sun and what each caster shows.
104
151
  * Cheap to build every frame, so the heavier steps run only when it changes.
@@ -114,7 +161,12 @@ function readCasters(light, scene) {
114
161
  if (!mesh.isMesh || !mesh.castShadow)
115
162
  return;
116
163
  _casters.push(mesh);
117
- signature += `|${mesh.id}:${mesh.matrixWorld.elements.join(',')}:${instanceSignature(mesh)}`;
164
+ // A moving caster's place changes every frame and its own map follows it, so the still map
165
+ // notes only that it exists.
166
+ if (isMovingCaster(mesh))
167
+ signature += `|${mesh.id}`;
168
+ else
169
+ signature += `|${mesh.id}:${mesh.matrixWorld.elements.join(',')}:${instanceSignature(mesh)}`;
118
170
  });
119
171
  return signature;
120
172
  }
@@ -275,7 +327,7 @@ function instanceSignature(mesh) {
275
327
  if (instanced.getVisibleAt(id))
276
328
  visible = (visible * 31 + id + 1) | 0;
277
329
  }
278
- return `${instanced.instancesCount}/${visible}/${instanced.matricesTexture?.version ?? 0}`;
330
+ return `${instanced.instancesCount}/${visible}/${instanced.matricesTexture?.revision ?? 0}`;
279
331
  }
280
332
  /**
281
333
  * One corner of a box.
@@ -289,6 +341,8 @@ function cornerOf(box, corner, target) {
289
341
  }
290
342
  /** The shadow map's width and height, in texels: about 64 MB of depth. */
291
343
  export const SHADOW_MAP_SIZE = 4096;
344
+ /** The moving casters' shadow map's width and height, in texels. */
345
+ export const MOVING_SHADOW_MAP_SIZE = 2048;
292
346
  /** The shadow lookup's spread, in texels. */
293
347
  export const SHADOW_RADIUS = 2;
294
348
  /**
@@ -307,6 +361,11 @@ const REFIT_ZOOM_IN = Math.SQRT2;
307
361
  const FIT_MARGIN = 1.25;
308
362
  /** `groundCorner`'s index for the screen center. */
309
363
  const CENTER = -1;
364
+ /**
365
+ * The `userData` flag on a caster routed to the moving map, and on the moving sun's shadow camera.
366
+ * Kept on the objects rather than in a module-level set, so a hot reload of this module keeps them.
367
+ */
368
+ const MOVING_CASTER = 'efpMovingShadow';
310
369
  let _lastSignature = '';
311
370
  /** The casters found by {@link readCasters}. */
312
371
  const _casters = [];
@@ -73,22 +73,38 @@ const VERTEX_ANCHOR = /* glsl */ `#include <shadowmap_vertex>`;
73
73
  const VERTEX_APPLY = /* glsl */ `
74
74
  #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
75
75
  vDirectionalShadowCoord[ 0 ] = ${VIEW_UNIFORM} * vec4( mvPosition.xyz + normalize( transformedNormal ) * directionalLightShadows[ 0 ].shadowNormalBias, 1.0 );
76
+ // The moving casters' sun shares the fit, so only its texel-sized normal bias differs.
77
+ #if NUM_DIR_LIGHT_SHADOWS > 1
78
+ vDirectionalShadowCoord[ 1 ] = ${VIEW_UNIFORM} * vec4( mvPosition.xyz + normalize( transformedNormal ) * directionalLightShadows[ 1 ].shadowNormalBias, 1.0 );
79
+ #endif
76
80
  #endif
77
81
  `;
78
82
  const LOOKUP = /* glsl */ `
79
83
  #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 && defined( SHADOWMAP_TYPE_PCF )
84
+ // Four taps half a radius apart, each a hardware 2x2 compare: a fixed 4x4 footprint.
85
+ float sunShadowTaps( sampler2DShadow map, vec3 coord, vec2 offset ) {
86
+ return 0.25 * (
87
+ texture( map, vec3( coord.xy + vec2( -offset.x, -offset.y ), coord.z ) ) +
88
+ texture( map, vec3( coord.xy + vec2( offset.x, -offset.y ), coord.z ) ) +
89
+ texture( map, vec3( coord.xy + vec2( -offset.x, offset.y ), coord.z ) ) +
90
+ texture( map, vec3( coord.xy + vec2( offset.x, offset.y ), coord.z ) )
91
+ );
92
+ }
80
93
  float sunShadowLit() {
81
94
  vec4 coord = vDirectionalShadowCoord[ 0 ];
82
95
  coord.z += directionalLightShadows[ 0 ].shadowBias;
83
96
  if ( coord.x < 0.0 || coord.x > 1.0 || coord.y < 0.0 || coord.y > 1.0 || coord.z > 1.0 ) return 1.0;
84
- // Four taps half a radius apart, each a hardware 2x2 compare: a fixed 4x4 footprint.
85
97
  vec2 offset = directionalLightShadows[ 0 ].shadowRadius * 0.5 / directionalLightShadows[ 0 ].shadowMapSize;
86
- return 0.25 * (
87
- texture( directionalShadowMap[ 0 ], vec3( coord.xy + vec2( -offset.x, -offset.y ), coord.z ) ) +
88
- texture( directionalShadowMap[ 0 ], vec3( coord.xy + vec2( offset.x, -offset.y ), coord.z ) ) +
89
- texture( directionalShadowMap[ 0 ], vec3( coord.xy + vec2( -offset.x, offset.y ), coord.z ) ) +
90
- texture( directionalShadowMap[ 0 ], vec3( coord.xy + vec2( offset.x, offset.y ), coord.z ) )
91
- );
98
+ float lit = sunShadowTaps( directionalShadowMap[ 0 ], coord.xyz, offset );
99
+ // The moving casters' sun, which three sorts after the still one: both cast, and the sort keeps
100
+ // the order they were mounted in.
101
+ #if NUM_DIR_LIGHT_SHADOWS > 1
102
+ vec4 movingCoord = vDirectionalShadowCoord[ 1 ];
103
+ movingCoord.z += directionalLightShadows[ 1 ].shadowBias;
104
+ vec2 movingOffset = directionalLightShadows[ 1 ].shadowRadius * 0.5 / directionalLightShadows[ 1 ].shadowMapSize;
105
+ lit = min( lit, sunShadowTaps( directionalShadowMap[ 1 ], movingCoord.xyz, movingOffset ) );
106
+ #endif
107
+ return lit;
92
108
  }
93
109
  #else
94
110
  float sunShadowLit() { return 1.0; }
@@ -1,5 +1,5 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { useThree } from '@react-three/fiber';
2
+ import { useFrame, useThree } from '@react-three/fiber';
3
3
  import { Fragment, useEffect, useState } from 'react';
4
4
  import { MeshDepthMaterial } from 'three';
5
5
  import { InstancedMesh } from '../../core/instanced/InstancedMesh';
@@ -7,8 +7,10 @@ import { sameSequence } from '../../utils/arrays';
7
7
  import { createLogger } from '../../utils/logging';
8
8
  import { defKey, useContainer } from '../containers';
9
9
  import { useOccluder } from '../lighting/occluder';
10
+ import { routeShadow } from '../lighting/sun-shadow-map';
10
11
  import { ModelMaterial } from '../materials/ModelMaterial';
11
12
  import { loadModel } from './gltf-cache';
13
+ import { poseAnimation } from './model-asset';
12
14
  import { MODEL_KINDS, ModelContainer, modelKindOf, OPACITY_UNIFORM, } from './model-container';
13
15
  import { useDefaultModelOpacity } from './model-opacity';
14
16
  import { ModelInstance } from './ModelInstance';
@@ -146,7 +148,7 @@ function ModelPartMesh(props) {
146
148
  // instead — but the hit resolution is not: `InstancedMeshImpl.raycast` walks the live slots,
147
149
  // skipping deleted and hidden ones, and raycasts the real merged geometry, so a hit names the
148
150
  // model's actual triangles and the slot that drew them.
149
- const container = useContainer(() => new ModelContainer(asset.extents, defs.length, kind), defs, onKindMismatch);
151
+ const container = useContainer(() => new ModelContainer(asset.extents, defs.length, kind, part.motion), defs, onKindMismatch);
150
152
  const occluder = useOccluder();
151
153
  // The geometry belongs to the module-level cache and may be drawing in another layer, so it is
152
154
  // mounted as a `primitive` with `dispose={null}` — R3F must not free it on unmount. Sharing it is
@@ -170,9 +172,44 @@ function ModelPartMesh(props) {
170
172
  // instancing patch binds the first mesh's textures into it. Each mesh needs its own.
171
173
  if (mesh && !mesh.customDepthMaterial)
172
174
  mesh.customDepthMaterial = new MeshDepthMaterial();
175
+ if (mesh)
176
+ routeShadow(mesh, part.motion !== undefined);
173
177
  }, matrixAutoUpdate: false, matrix: container.meshMatrix,
174
178
  // Models cast the sun's shadow and receive it.
175
- castShadow: true, receiveShadow: true, sortObjects: true, renderOrder: renderOrder, children: [_jsx("primitive", { object: part.geometry, attach: "geometry", dispose: null }), _jsx(ModelMaterial, { source: part.material, opacityUniform: OPACITY_UNIFORM, translucent: kind === 'translucent' })] }), defs.slice(0, mounted).map((def) => (_jsx(ModelInstance, { def: def, container: container }, defKey(def))))] }));
179
+ castShadow: true, receiveShadow: true, sortObjects: true, renderOrder: renderOrder, children: [_jsx("primitive", { object: part.geometry, attach: "geometry", dispose: null }), _jsx(ModelMaterial, { source: part.material, opacityUniform: OPACITY_UNIFORM, translucent: kind === 'translucent' })] }), defs.slice(0, mounted).map((def) => (_jsx(ModelInstance, { def: def, container: container }, defKey(def)))), asset.animation && part.motion && (_jsx(PartAnimation, { animation: asset.animation, container: container }))] }));
180
+ }
181
+ /**
182
+ * Plays an animated part: each frame, poses the asset at the page's time and moves every instance
183
+ * with the part's node.
184
+ *
185
+ * The frame loop runs on demand, so this asks for the next frame itself, and only while the mesh is
186
+ * visible. A hidden layer therefore stops the loop instead of keeping the map at full frame rate.
187
+ * @param props - The animation and the part's container.
188
+ * @returns `null`; the instances live in the container's mesh.
189
+ */
190
+ function PartAnimation(props) {
191
+ const { animation, container } = props;
192
+ useFrame((state) => {
193
+ if (!isShown(container.mesh))
194
+ return;
195
+ // Not `state.clock`: under an external host's frame loop R3F sets it to milliseconds.
196
+ poseAnimation(animation, performance.now() / 1000);
197
+ container.follow();
198
+ state.invalidate();
199
+ });
200
+ return null;
201
+ }
202
+ /**
203
+ * Whether an object and every ancestor draw.
204
+ * @param object - The object to test.
205
+ * @returns `true` when nothing above it is hidden.
206
+ */
207
+ function isShown(object) {
208
+ for (let current = object; current; current = current.parent) {
209
+ if (!current.visible)
210
+ return false;
211
+ }
212
+ return true;
176
213
  }
177
214
  /**
178
215
  * Loads one model, reporting a failure rather than rejecting — one missing model should not cost a
@@ -36,7 +36,7 @@ export function loadModel(url, renderer) {
36
36
  */
37
37
  async function parse(url, renderer) {
38
38
  const gltf = await loaderFor(renderer).loadAsync(url);
39
- return bakeGltf(gltf.scene, url);
39
+ return bakeGltf(gltf.scene, url, gltf.animations);
40
40
  }
41
41
  /**
42
42
  * The loader for one renderer. Meshopt is wired in because its decoder ships inside three's addons
@@ -1,4 +1,4 @@
1
- import { Box3, type BufferGeometry, type Group, type Material } from 'three';
1
+ import { type AnimationClip, AnimationMixer, Box3, type BufferGeometry, type Group, type Material, Matrix4, type Object3D } from 'three';
2
2
  /** One drawable piece of a loaded model: everything in it that shares a source material. */
3
3
  export interface ModelPart {
4
4
  /**
@@ -11,6 +11,23 @@ export interface ModelPart {
11
11
  readonly geometry: BufferGeometry;
12
12
  /** The material the GLB authored for those meshes. Shared; clone before mutating. */
13
13
  readonly material: Material;
14
+ /** How the part moves when the GLB animates it. Absent for a part that never moves. */
15
+ readonly motion?: PartMotion;
16
+ }
17
+ /**
18
+ * The node an animated part follows. Its geometry is baked in the rest pose, so what an instance
19
+ * adds is the node's displacement from that pose: `node.matrixWorld · restInverse`.
20
+ */
21
+ export interface PartMotion {
22
+ /** The part's nearest animated ancestor-or-self, inside {@link ModelAnimation.mixer}'s root. */
23
+ readonly node: Object3D;
24
+ /** The inverse of `node.matrixWorld` in the rest pose the geometry was baked in. */
25
+ readonly restInverse: Matrix4;
26
+ }
27
+ /** The clips a GLB carries, all playing on a loop. Shared by every layer drawing the asset. */
28
+ export interface ModelAnimation {
29
+ /** Drives the loaded scene; every clip has a playing action. */
30
+ readonly mixer: AnimationMixer;
14
31
  }
15
32
  /** A parsed GLB, ready to be instanced. */
16
33
  export interface ModelAsset {
@@ -20,10 +37,21 @@ export interface ModelAsset {
20
37
  readonly parts: readonly ModelPart[];
21
38
  /**
22
39
  * The union of every baked part's bounds, in the model's own y-up space. `ModelContainer` maps
23
- * them into the plan's once, which is the only place the two frames meet.
40
+ * them into the plan's once, which is the only place the two frames meet. Rest pose for an
41
+ * animated model, so its fitted scale does not change while it moves.
24
42
  */
25
43
  readonly extents: Box3;
44
+ /** Present when the GLB carries clips that move some of its parts. */
45
+ readonly animation?: ModelAnimation;
26
46
  }
47
+ /**
48
+ * Poses an animated asset at a point in time. Takes the absolute time rather than a step, because
49
+ * every animated part of every layer drawing the asset calls it each frame, and stepping would play
50
+ * the clips once per caller.
51
+ * @param animation - The asset's animation.
52
+ * @param seconds - The time to pose at.
53
+ */
54
+ export declare function poseAnimation(animation: ModelAnimation, seconds: number): void;
27
55
  /**
28
56
  * Flattens a loaded glTF scene and merges it down to one geometry per source material.
29
57
  *
@@ -46,9 +74,15 @@ export interface ModelAsset {
46
74
  * Merging is what replaces legacy's `BatchedMesh`: we never address a sub-mesh individually — the
47
75
  * addressable unit is the def — so one geometry per material is strictly better, and it costs no
48
76
  * `WEBGL_multi_draw` path.
77
+ *
78
+ * Animation survives the flattening only where it moves whole nodes. A mesh under an animated node
79
+ * is bucketed by that node too, and the part records it as its {@link PartMotion}, so the instance
80
+ * can add the node's displacement each frame. Skinned meshes and morph targets are drawn in their
81
+ * rest pose, with a warning.
49
82
  * @param scene - The glTF scene to bake.
50
83
  * @param url - Where it came from; carried on the asset, and names the model in diagnostics.
84
+ * @param clips - The GLB's animations.
51
85
  * @returns The parsed asset.
52
86
  */
53
- export declare function bakeGltf(scene: Group, url: string): ModelAsset;
87
+ export declare function bakeGltf(scene: Group, url: string, clips?: AnimationClip[]): ModelAsset;
54
88
  //# sourceMappingURL=model-asset.d.ts.map
@@ -1,7 +1,18 @@
1
- import { Box3, BufferAttribute, InstancedMesh, Matrix4, Mesh, } from 'three';
1
+ import { AnimationMixer, Box3, BufferAttribute, InstancedMesh, Matrix4, Mesh, PropertyBinding, SkinnedMesh, } from 'three';
2
2
  import { mergeGeometries } from 'three/examples/jsm/utils/BufferGeometryUtils.js';
3
3
  import { createLogger } from '../../utils/logging';
4
4
  const logger = createLogger('model');
5
+ /**
6
+ * Poses an animated asset at a point in time. Takes the absolute time rather than a step, because
7
+ * every animated part of every layer drawing the asset calls it each frame, and stepping would play
8
+ * the clips once per caller.
9
+ * @param animation - The asset's animation.
10
+ * @param seconds - The time to pose at.
11
+ */
12
+ export function poseAnimation(animation, seconds) {
13
+ animation.mixer.setTime(seconds);
14
+ animation.mixer.getRoot().updateMatrixWorld(true);
15
+ }
5
16
  /**
6
17
  * Flattens a loaded glTF scene and merges it down to one geometry per source material.
7
18
  *
@@ -24,13 +35,21 @@ const logger = createLogger('model');
24
35
  * Merging is what replaces legacy's `BatchedMesh`: we never address a sub-mesh individually — the
25
36
  * addressable unit is the def — so one geometry per material is strictly better, and it costs no
26
37
  * `WEBGL_multi_draw` path.
38
+ *
39
+ * Animation survives the flattening only where it moves whole nodes. A mesh under an animated node
40
+ * is bucketed by that node too, and the part records it as its {@link PartMotion}, so the instance
41
+ * can add the node's displacement each frame. Skinned meshes and morph targets are drawn in their
42
+ * rest pose, with a warning.
27
43
  * @param scene - The glTF scene to bake.
28
44
  * @param url - Where it came from; carried on the asset, and names the model in diagnostics.
45
+ * @param clips - The GLB's animations.
29
46
  * @returns The parsed asset.
30
47
  */
31
- export function bakeGltf(scene, url) {
48
+ export function bakeGltf(scene, url, clips = []) {
32
49
  const buckets = new Map();
33
50
  const extents = new Box3();
51
+ const animated = animatedNodes(scene, clips, url);
52
+ const motions = new Map();
34
53
  scene.updateMatrixWorld(true);
35
54
  scene.traverse((node) => {
36
55
  // `instanceof` on a generic class instantiates its parameters as `any`, so the narrowed node is
@@ -44,6 +63,15 @@ export function bakeGltf(scene, url) {
44
63
  const material = Array.isArray(mesh.material) ? mesh.material[0] : mesh.material;
45
64
  if (!material)
46
65
  return;
66
+ if (mesh instanceof SkinnedMesh) {
67
+ logger.warn('model %s: skinned mesh "%s" is drawn in its rest pose', url, mesh.name);
68
+ }
69
+ const follows = nearestAnimated(mesh, animated);
70
+ let motion = follows ? motions.get(follows) : undefined;
71
+ if (follows && !motion) {
72
+ motion = { node: follows, restInverse: follows.matrixWorld.clone().invert() };
73
+ motions.set(follows, motion);
74
+ }
47
75
  const source = toFloatGeometry(mesh.geometry);
48
76
  // Per-instance attributes three parked on the shared geometry; each baked copy sheds them.
49
77
  const dropped = mesh instanceof InstancedMesh
@@ -58,8 +86,8 @@ export function bakeGltf(scene, url) {
58
86
  if (baked.boundingBox)
59
87
  extents.union(baked.boundingBox);
60
88
  const signature = mergeSignature(baked);
61
- const id = `${material.uuid}|${signature}`;
62
- const bucket = buckets.get(id) ?? { material, signature, geometries: [] };
89
+ const id = `${material.uuid}|${signature}${motion ? `|${motion.node.uuid}` : ''}`;
90
+ const bucket = buckets.get(id) ?? { material, signature, motion, geometries: [] };
63
91
  bucket.geometries.push(baked);
64
92
  buckets.set(id, bucket);
65
93
  };
@@ -76,7 +104,7 @@ export function bakeGltf(scene, url) {
76
104
  }
77
105
  });
78
106
  const parts = [];
79
- for (const [id, { material, signature, geometries }] of buckets) {
107
+ for (const [id, { material, signature, motion, geometries }] of buckets) {
80
108
  const merged = geometries.length === 1 ? geometries[0] : mergeGeometries(geometries);
81
109
  // `mergeGeometries` still returns null when its inputs disagree about something the signature
82
110
  // does not cover — an attribute's item size or array type, a morph target. Reported rather than
@@ -86,9 +114,52 @@ export function bakeGltf(scene, url) {
86
114
  logger.warn('model %s: dropped a part, %d geometries would not merge — material "%s" (%s), %s', url, geometries.length, material.name, material.uuid, signature);
87
115
  continue;
88
116
  }
89
- parts.push({ id, geometry: merged, material });
117
+ parts.push(motion ? { id, geometry: merged, material, motion } : { id, geometry: merged, material });
118
+ }
119
+ if (motions.size === 0)
120
+ return { url, parts, extents };
121
+ const mixer = new AnimationMixer(scene);
122
+ for (const clip of clips)
123
+ mixer.clipAction(clip).play();
124
+ return { url, parts, extents, animation: { mixer } };
125
+ }
126
+ /**
127
+ * The nodes the clips move by position, rotation or scale. A morph-target track moves no node and
128
+ * is reported instead.
129
+ * @param scene - The scene the clips bind to.
130
+ * @param clips - The GLB's animations.
131
+ * @param url - Names the model in diagnostics.
132
+ * @returns The animated nodes.
133
+ */
134
+ function animatedNodes(scene, clips, url) {
135
+ const nodes = new Set();
136
+ for (const clip of clips) {
137
+ for (const track of clip.tracks) {
138
+ const { nodeName, propertyName } = PropertyBinding.parseTrackName(track.name);
139
+ if (propertyName === 'morphTargetInfluences') {
140
+ logger.warn('model %s: morph animation "%s" is not played', url, clip.name);
141
+ continue;
142
+ }
143
+ const node = PropertyBinding.findNode(scene, nodeName);
144
+ if (node)
145
+ nodes.add(node);
146
+ }
147
+ }
148
+ return nodes;
149
+ }
150
+ /**
151
+ * The nearest of a node and its ancestors that an animation moves. Everything below it is static, so
152
+ * its displacement is the whole of the mesh's.
153
+ * @param node - The mesh node.
154
+ * @param animated - The nodes the clips move.
155
+ * @returns The node to follow, or `null` when nothing above the mesh moves.
156
+ */
157
+ function nearestAnimated(node, animated) {
158
+ for (let current = node; current; current = current.parent) {
159
+ if (animated.has(current))
160
+ return current;
90
161
  }
91
- return { url, parts, extents };
162
+ return null;
92
163
  }
93
164
  /**
94
165
  * A stable description of what `mergeGeometries` insists its inputs agree about: whether they are
@@ -3,6 +3,7 @@ import { type Box3, Matrix4 } from 'three';
3
3
  import { type InstancedMeshImpl, type InstancedMeshImplParams } from '../../core/instanced/InstancedMesh';
4
4
  import { type ModelDef } from '../../types/defs';
5
5
  import { SlotContainer } from '../containers';
6
+ import { type PartMotion } from './model-asset';
6
7
  /**
7
8
  * The per-instance uniform a model mesh reads its opacity from. The container owns the name: it
8
9
  * declares the schema on bind and writes each slot's value, and hands the name to `ModelMaterial`,
@@ -48,6 +49,8 @@ export declare class ModelContainer extends SlotContainer<null, InstancedMeshImp
48
49
  * requires and {@link place}'s plan-space answers land where they say. See {@link PLAN_FROM_GLTF}.
49
50
  */
50
51
  readonly meshMatrix: Matrix4;
52
+ /** The node the part follows when the GLB animates it; absent for a static part. */
53
+ readonly motion: PartMotion | undefined;
51
54
  /** The model's bounds in plan units; every instance is fitted against them. */
52
55
  private readonly extents;
53
56
  /**
@@ -55,8 +58,9 @@ export declare class ModelContainer extends SlotContainer<null, InstancedMeshImp
55
58
  * @param extents - The model's own bounds, y-up, as `bakeGltf` left them.
56
59
  * @param count - How many defs the layer holds for this part, used as the mesh's initial capacity.
57
60
  * @param kind - Which of the layer's batches this is; its material is built for that one alone.
61
+ * @param motion - The animated node the part follows, if any.
58
62
  */
59
- constructor(extents: Box3, count: number, kind?: ModelKind);
63
+ constructor(extents: Box3, count: number, kind?: ModelKind, motion?: PartMotion);
60
64
  /**
61
65
  * Paint order is not implemented for models, so this does nothing.
62
66
  *
@@ -74,7 +78,8 @@ export declare class ModelContainer extends SlotContainer<null, InstancedMeshImp
74
78
  */
75
79
  setPaintOrder(): void;
76
80
  /**
77
- * Writes a def's placement into its slot: the model's extents fitted into `bounds`.
81
+ * Writes a def's placement into its slot: the model's extents fitted into `bounds`, and for an
82
+ * animated part, moved by its node's current displacement from the rest pose.
78
83
  *
79
84
  * The mesh carries {@link PLAN_FROM_GLTF}, so its instances are placed in the model's own space,
80
85
  * while {@link fitToBounds} answers in the plan's. Conjugating moves the placement across — undo
@@ -84,6 +89,13 @@ export declare class ModelContainer extends SlotContainer<null, InstancedMeshImp
84
89
  * @param def - The def supplying the bounds.
85
90
  */
86
91
  place(slot: number, def: ModelDef): void;
92
+ /** Re-places every claimed slot, for an animated part after its node moved. */
93
+ follow(): void;
94
+ /**
95
+ * How far the followed node has moved from the pose the geometry was baked in, in glTF space.
96
+ * @returns The shared scratch matrix: the identity for a static part.
97
+ */
98
+ private displacement;
87
99
  /**
88
100
  * Writes a def's opacity into its slot — **clamped to opaque unless this batch blends**.
89
101
  *
@@ -45,6 +45,8 @@ export class ModelContainer extends SlotContainer {
45
45
  * requires and {@link place}'s plan-space answers land where they say. See {@link PLAN_FROM_GLTF}.
46
46
  */
47
47
  meshMatrix = PLAN_FROM_GLTF;
48
+ /** The node the part follows when the GLB animates it; absent for a static part. */
49
+ motion;
48
50
  /** The model's bounds in plan units; every instance is fitted against them. */
49
51
  extents;
50
52
  /**
@@ -52,9 +54,11 @@ export class ModelContainer extends SlotContainer {
52
54
  * @param extents - The model's own bounds, y-up, as `bakeGltf` left them.
53
55
  * @param count - How many defs the layer holds for this part, used as the mesh's initial capacity.
54
56
  * @param kind - Which of the layer's batches this is; its material is built for that one alone.
57
+ * @param motion - The animated node the part follows, if any.
55
58
  */
56
- constructor(extents, count, kind = 'opaque') {
59
+ constructor(extents, count, kind = 'opaque', motion) {
57
60
  super({ schema: MODEL_SCHEMA });
61
+ this.motion = motion;
58
62
  // Mapped once, here, so that everything below reads plan units — `fitToBounds` included.
59
63
  this.extents = extents.clone().applyMatrix4(PLAN_FROM_GLTF);
60
64
  this.kind = kind;
@@ -79,7 +83,8 @@ export class ModelContainer extends SlotContainer {
79
83
  // Nothing: the depth buffer orders models, and a layer's parts are separate meshes regardless.
80
84
  }
81
85
  /**
82
- * Writes a def's placement into its slot: the model's extents fitted into `bounds`.
86
+ * Writes a def's placement into its slot: the model's extents fitted into `bounds`, and for an
87
+ * animated part, moved by its node's current displacement from the rest pose.
83
88
  *
84
89
  * The mesh carries {@link PLAN_FROM_GLTF}, so its instances are placed in the model's own space,
85
90
  * while {@link fitToBounds} answers in the plan's. Conjugating moves the placement across — undo
@@ -93,7 +98,22 @@ export class ModelContainer extends SlotContainer {
93
98
  // Read right to left: into the plan, placed there, and back out again.
94
99
  _placement
95
100
  .multiplyMatrices(GLTF_FROM_PLAN, fitToBounds(this.extents, def.bounds))
96
- .multiply(PLAN_FROM_GLTF));
101
+ .multiply(PLAN_FROM_GLTF)
102
+ .multiply(this.displacement()));
103
+ }
104
+ /** Re-places every claimed slot, for an animated part after its node moved. */
105
+ follow() {
106
+ for (const [slot, def] of this.claims())
107
+ this.place(slot, def);
108
+ }
109
+ /**
110
+ * How far the followed node has moved from the pose the geometry was baked in, in glTF space.
111
+ * @returns The shared scratch matrix: the identity for a static part.
112
+ */
113
+ displacement() {
114
+ if (!this.motion)
115
+ return _displacement.identity();
116
+ return _displacement.multiplyMatrices(this.motion.node.matrixWorld, this.motion.restInverse);
97
117
  }
98
118
  /**
99
119
  * Writes a def's opacity into its slot — **clamped to opaque unless this batch blends**.
@@ -207,3 +227,4 @@ const _quaternion = new Quaternion();
207
227
  const _recenter = new Matrix4();
208
228
  const _matrix = new Matrix4();
209
229
  const _placement = new Matrix4();
230
+ const _displacement = new Matrix4();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@expofp/renderer",
3
- "version": "3.49.2",
3
+ "version": "3.50.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/expofp/efp-app.git",
@@ -42,7 +42,7 @@
42
42
  "troika-three-text": "^0.52.5",
43
43
  "tslib": "^2.3.0",
44
44
  "webgl-memory": "^1.1.3",
45
- "@expofp/geometry": "3.49.2"
45
+ "@expofp/geometry": "3.50.0"
46
46
  },
47
47
  "devDependencies": {
48
48
  "@react-three/test-renderer": "^9.1.0",