@threenative/core 0.3.4 → 0.3.5
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/capabilities.json +1505 -79
- package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
- package/dist/{canvas-layer-DDmC_VVF.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
- package/dist/{game-CljaDv4D.d.ts → game-Bj8G1wmD.d.ts} +102 -11
- package/dist/hot.d.ts +4 -4
- package/dist/index.d.ts +712 -118
- package/dist/index.js +12423 -4955
- package/dist/{gpu-readback-CqJEfWNQ.d.ts → model-lod-BDAUYgsS.d.ts} +80 -5
- package/dist/playtest.d.ts +6 -10
- package/dist/playtest.js +47 -24
- package/dist/react-css.d.ts +62 -0
- package/dist/react-css.js +591 -0
- package/dist/react.d.ts +2 -2
- package/dist/{renderer-CfsS2hxi.d.ts → renderer-9yEo9hPa.d.ts} +489 -22
- package/dist/terrain-jobs-worker.d.ts +2 -0
- package/dist/terrain-jobs-worker.js +130 -0
- package/dist/ui-layer.js +59 -8
- package/dist/world.d.ts +766 -73
- package/dist/world.js +9307 -3543
- package/gpl/recipes/export_world.py +18 -1
- package/mcp/blender-server.mjs +7 -4
- package/mcp/blender.mjs +3 -4
- package/mcp/engine-server.mjs +2 -2
- package/mcp/servers.mjs +4 -4
- package/package.json +15 -9
- package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
- package/patches/three@0.185.1.patch +6594 -700
- package/scripts/apply-three-patch.mjs +62 -4
- package/src/animation-blend.ts +264 -0
- package/src/animation-composition.ts +362 -0
- package/src/animation-layers.ts +260 -0
- package/src/animation-root-motion.ts +283 -0
- package/src/animation.ts +896 -0
- package/src/assets.ts +1303 -0
- package/src/atmosphere/index.ts +335 -0
- package/src/atmosphere/luts.ts +298 -0
- package/src/atmosphere/params.ts +323 -0
- package/src/audio.ts +912 -0
- package/src/billboard.ts +124 -0
- package/src/bone-lengths.ts +157 -0
- package/src/camera-shake.ts +116 -0
- package/src/canvas-layer.ts +47 -0
- package/src/clip-audit.ts +401 -0
- package/src/clustered-batch.ts +492 -0
- package/src/clustered-mesh.ts +638 -0
- package/src/compute-driven.ts +176 -0
- package/src/compute-timing.ts +318 -0
- package/src/config.ts +593 -0
- package/src/debug.ts +82 -0
- package/src/engine-render-hook.ts +25 -0
- package/src/entities.ts +79 -0
- package/src/entity-snapshot.ts +53 -0
- package/src/flight.ts +683 -0
- package/src/fluid-field.ts +748 -0
- package/src/fluid-particles.ts +1253 -0
- package/src/frame-budget.ts +1368 -0
- package/src/game.ts +2390 -0
- package/src/geometry-capture.ts +1098 -0
- package/src/gpu-class.ts +160 -0
- package/src/gpu-frame-observation.ts +424 -0
- package/src/gpu-readback.ts +143 -0
- package/src/gpu-scene-bvh.ts +464 -0
- package/src/grounding.ts +100 -0
- package/src/hot.ts +161 -0
- package/src/import-meta.d.ts +13 -0
- package/src/index.ts +1536 -0
- package/src/input.ts +690 -0
- package/src/instanced-batch-lod.ts +283 -0
- package/src/instanced-batch.ts +274 -0
- package/src/interpolation.ts +129 -0
- package/src/launch-diagnostics.ts +161 -0
- package/src/loop.ts +564 -0
- package/src/matrix-world.ts +245 -0
- package/src/merge-parts.ts +812 -0
- package/src/model-lod.ts +1315 -0
- package/src/net-protocol.ts +333 -0
- package/src/net-session.ts +477 -0
- package/src/net.ts +80 -0
- package/src/ocean/fft.ts +72 -0
- package/src/ocean/spectral.ts +728 -0
- package/src/particle-significance.ts +102 -0
- package/src/particles.ts +648 -0
- package/src/path-follow.ts +175 -0
- package/src/picking.ts +250 -0
- package/src/pipeline-census.ts +1566 -0
- package/src/platform.ts +210 -0
- package/src/playtest.ts +839 -0
- package/src/pointer-events.ts +411 -0
- package/src/pose-measure.ts +435 -0
- package/src/profiling/FrameCounters.ts +231 -0
- package/src/profiling/Spans.ts +548 -0
- package/src/profiling/opacity-convention.ts +21 -0
- package/src/profiling/render-list-validate.ts +175 -0
- package/src/profiling/render-trap-audit.ts +84 -0
- package/src/profiling/scene-warning.ts +190 -0
- package/src/profiling/span-probes.ts +191 -0
- package/src/profiling/unlit-foliage-warning.ts +149 -0
- package/src/projection-apply.ts +1529 -0
- package/src/projection-marker.ts +142 -0
- package/src/projection-plan.ts +1258 -0
- package/src/projection-skinned.ts +419 -0
- package/src/projection-stability.ts +409 -0
- package/src/projection-uniform.ts +328 -0
- package/src/random.ts +41 -0
- package/src/react-css.ts +604 -0
- package/src/react-glyphs.ts +114 -0
- package/src/react-host.ts +576 -0
- package/src/react-layout.ts +265 -0
- package/src/react.ts +60 -0
- package/src/render/alpha-antialiasing.ts +159 -0
- package/src/render/batched-velocity.ts +126 -0
- package/src/render/chain.ts +1021 -0
- package/src/render/daylight.ts +189 -0
- package/src/render/depth-pyramid.ts +596 -0
- package/src/render/foliage-alpha.ts +166 -0
- package/src/render/material-key.ts +60 -0
- package/src/render/mesh-pool.ts +144 -0
- package/src/render/probe-volume.ts +1668 -0
- package/src/render/resolution-subrect.ts +253 -0
- package/src/render/velocity.ts +442 -0
- package/src/render/virtual-shadow-pages.ts +827 -0
- package/src/render/virtual-shadow-partial.ts +174 -0
- package/src/render/virtual-shadow.ts +3330 -0
- package/src/render/world-impostor-surface.ts +722 -0
- package/src/render/world-impostor.ts +558 -0
- package/src/render-camera-cull.ts +441 -0
- package/src/render-pass-budget.ts +501 -0
- package/src/renderProjection.ts +758 -0
- package/src/renderer-config.ts +127 -0
- package/src/renderer.ts +1847 -0
- package/src/replay-protocol.ts +85 -0
- package/src/replay.ts +205 -0
- package/src/resolution-scaler.ts +819 -0
- package/src/rig-preparation.ts +271 -0
- package/src/ripple-field.ts +432 -0
- package/src/scale.ts +109 -0
- package/src/scene.ts +239 -0
- package/src/schedule.ts +155 -0
- package/src/skeletal-mesh.ts +61 -0
- package/src/skeleton.ts +100 -0
- package/src/snow-field.ts +744 -0
- package/src/softbody-topology.ts +269 -0
- package/src/softbody.ts +516 -0
- package/src/sprite-animator.ts +222 -0
- package/src/startup-readiness.ts +386 -0
- package/src/state.ts +66 -0
- package/src/static-transform.ts +274 -0
- package/src/storage-buffer.ts +253 -0
- package/src/streaming.ts +308 -0
- package/src/target-fps.ts +92 -0
- package/src/terrain-jobs-worker.ts +17 -0
- package/src/terrain-jobs.ts +353 -0
- package/src/textures.ts +39 -0
- package/src/tracers.ts +237 -0
- package/src/ui-bridge.ts +368 -0
- package/src/ui-hit-regions.ts +380 -0
- package/src/ui-layer.ts +83 -0
- package/src/ui-state.ts +220 -0
- package/src/version.ts +2 -0
- package/src/viewport.ts +253 -0
- package/src/warmup.ts +1357 -0
- package/src/water-surface.ts +384 -0
- package/src/wave-field.ts +524 -0
- package/src/world-capabilities.ts +131 -0
- package/src/world-cell-proxy.ts +392 -0
- package/src/world-cells.ts +10564 -0
- package/src/world-gpu-scene.ts +3354 -0
- package/src/world-heightmap.ts +82 -0
- package/src/world-package.ts +469 -0
- package/src/world-passes.ts +582 -0
- package/src/world-region.ts +17 -0
- package/src/world-terrain-splat.ts +564 -0
- package/src/world-tiles.ts +3826 -0
- package/src/world-topology.ts +370 -0
- package/src/world-validate.ts +48 -0
- package/src/world.ts +805 -0
package/src/model-lod.ts
ADDED
|
@@ -0,0 +1,1315 @@
|
|
|
1
|
+
import {
|
|
2
|
+
Box3,
|
|
3
|
+
BufferAttribute,
|
|
4
|
+
BufferGeometry,
|
|
5
|
+
type Camera,
|
|
6
|
+
Group,
|
|
7
|
+
Matrix4,
|
|
8
|
+
type Mesh,
|
|
9
|
+
Object3D,
|
|
10
|
+
Sphere,
|
|
11
|
+
Vector3,
|
|
12
|
+
} from "three";
|
|
13
|
+
import { pixelsPerUnit } from "./clustered-mesh.js";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Engine-owned detail selection for automatic discrete LOD (`TN_discrete_lod`).
|
|
17
|
+
*
|
|
18
|
+
* The asset pipeline bakes a chain of index-only levels into the `.glb`; this module decides which
|
|
19
|
+
* one a camera may see, from the level's measured geometric error projected into pixels. It is the
|
|
20
|
+
* one selection authority for a discrete chain: nothing here is appearance, and nothing here
|
|
21
|
+
* touches a material — it swaps between geometries the pipeline already wrote.
|
|
22
|
+
*
|
|
23
|
+
* Projection is done from the camera's own matrices, so perspective and orthographic cameras, zoom,
|
|
24
|
+
* the actual drawing-buffer height and a non-uniformly scaled parent all read correctly. The depth
|
|
25
|
+
* used is a conservative nearest view-space depth of the object's bounding sphere, not the distance
|
|
26
|
+
* to its origin, and a camera at or inside the near plane selects the finest level.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
/** A camera shape this selection needs: the projection terms `three` exposes structurally. */
|
|
30
|
+
interface ILodCameraLike extends Camera {
|
|
31
|
+
readonly isOrthographicCamera?: boolean;
|
|
32
|
+
readonly top?: number;
|
|
33
|
+
readonly bottom?: number;
|
|
34
|
+
readonly zoom?: number;
|
|
35
|
+
readonly near?: number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface ILodView {
|
|
39
|
+
readonly camera: Camera;
|
|
40
|
+
/** Drawing-buffer height in actual raster pixels; a CSS height is the wrong number. */
|
|
41
|
+
readonly viewportHeight: number;
|
|
42
|
+
/**
|
|
43
|
+
* Conservative nearest view-space depth of the object's bounding sphere, in world units. A caller
|
|
44
|
+
* that has not measured the bounds passes the distance to the origin, which is never closer and
|
|
45
|
+
* therefore never over-refines.
|
|
46
|
+
*/
|
|
47
|
+
readonly depth: number;
|
|
48
|
+
/**
|
|
49
|
+
* True when the camera is at or inside the object's near plane, where a projected error has no
|
|
50
|
+
* meaning. The finest level is selected instead of dividing by ~zero.
|
|
51
|
+
*/
|
|
52
|
+
readonly degenerate: boolean;
|
|
53
|
+
/**
|
|
54
|
+
* A view that must not drop below the finest level regardless of budget. Recorded as data so a
|
|
55
|
+
* pass-local caller can prove it honoured the rule.
|
|
56
|
+
*/
|
|
57
|
+
readonly finest?: boolean;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Pixels a one-world-unit error at `depth` covers, for this camera and viewport.
|
|
62
|
+
*
|
|
63
|
+
* Perspective divides the projected scale by the depth; orthographic has no depth term and uses the
|
|
64
|
+
* frustum height instead. A non-positive depth or an unprojectable camera throws rather than
|
|
65
|
+
* returning a plausible-looking wrong scale.
|
|
66
|
+
*/
|
|
67
|
+
export function lodPixelScale(camera: Camera, viewportHeight: number, depth: number): number {
|
|
68
|
+
const like: ILodCameraLike = camera;
|
|
69
|
+
if (!(viewportHeight > 0))
|
|
70
|
+
throw new Error(`AutoLOD needs a positive viewport height, got ${String(viewportHeight)}.`);
|
|
71
|
+
const zoom = like.zoom ?? 1;
|
|
72
|
+
if (like.isOrthographicCamera === true) {
|
|
73
|
+
const height = (like.top ?? 1) - (like.bottom ?? -1);
|
|
74
|
+
if (!(height > 0))
|
|
75
|
+
throw new Error("AutoLOD needs an orthographic frustum with a positive height.");
|
|
76
|
+
return (viewportHeight * zoom) / height;
|
|
77
|
+
}
|
|
78
|
+
if (!(depth > 0)) return Number.POSITIVE_INFINITY;
|
|
79
|
+
return (pixelsPerUnit(camera, viewportHeight) * zoom) / depth;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The projected geometric error of `worldError` at `depth`, in pixels. */
|
|
83
|
+
export function projectedLodError(
|
|
84
|
+
worldError: number,
|
|
85
|
+
camera: Camera,
|
|
86
|
+
viewportHeight: number,
|
|
87
|
+
depth: number,
|
|
88
|
+
): number {
|
|
89
|
+
if (worldError <= 0) return 0;
|
|
90
|
+
return worldError * lodPixelScale(camera, viewportHeight, depth);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The adaptive LOD bias both selection paths share: one multiplier on the camera distance, `>= 1`.
|
|
95
|
+
*
|
|
96
|
+
* `WorldCells`' control loop owns it (see its `adaptiveLod` option) and rewrites it once it has a
|
|
97
|
+
* fresh main-pass GPU reading; `setLodBias` is the only writer. The CPU selection here reads it
|
|
98
|
+
* through {@link biasedLodDistance}, and the GPU scene mirrors it as a uniform, so a placement at
|
|
99
|
+
* one distance crosses the same switch wherever the level is decided. `1` is exactly as authored.
|
|
100
|
+
*/
|
|
101
|
+
// Unsplit package entries must share the control loop's bias, just like the chain registry.
|
|
102
|
+
const LOD_BIAS_KEY = Symbol.for("threenative.lodBias");
|
|
103
|
+
const lodBiasHost = globalThis as Record<symbol, unknown>;
|
|
104
|
+
const lodBiasState = (lodBiasHost[LOD_BIAS_KEY] as { value: number } | undefined) ?? { value: 1 };
|
|
105
|
+
lodBiasHost[LOD_BIAS_KEY] = lodBiasState;
|
|
106
|
+
|
|
107
|
+
/** The multiplier every LOD selection path scales camera distance by. */
|
|
108
|
+
export function lodBias(): number {
|
|
109
|
+
return lodBiasState.value;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Sets the adaptive LOD bias, clamped to `>= 1`. A bias below 1 would refine past what the chain
|
|
114
|
+
* authored, so it is refused rather than applied; a non-finite value is no reading and resets to 1.
|
|
115
|
+
*/
|
|
116
|
+
export function setLodBias(bias: number): void {
|
|
117
|
+
lodBiasState.value = Number.isFinite(bias) && bias >= 1 ? bias : 1;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* The camera distance an LOD switch is compared against: the measured distance times
|
|
122
|
+
* {@link lodBias}. Scaling up crosses every authored switch earlier and never later, so a bias can
|
|
123
|
+
* only coarsen selection, never refine it below the level the chain would show unaided.
|
|
124
|
+
*/
|
|
125
|
+
export function biasedLodDistance(distance: number): number {
|
|
126
|
+
return distance * lodBiasState.value;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const nearest = new Vector3();
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* The conservative nearest view-space depth of a world-space bounding sphere.
|
|
133
|
+
*
|
|
134
|
+
* The distance along the view axis to the sphere's centre minus its radius is the closest the
|
|
135
|
+
* surface can be, which is what a screen-space error must divide by: an error near the camera must
|
|
136
|
+
* not be projected as if it sat at the centre. A camera inside the sphere reports `degenerate`.
|
|
137
|
+
*/
|
|
138
|
+
export function conservativeViewDepth(
|
|
139
|
+
camera: Camera,
|
|
140
|
+
center: Vector3,
|
|
141
|
+
radius: number,
|
|
142
|
+
nearPlane: number,
|
|
143
|
+
): { readonly depth: number; readonly degenerate: boolean } {
|
|
144
|
+
nearest.copy(center).applyMatrix4(camera.matrixWorldInverse);
|
|
145
|
+
const depth = -nearest.z - Math.max(0, radius);
|
|
146
|
+
return { depth, degenerate: depth <= nearPlane };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** The world-space bounding sphere of a cached local sphere under a node's world matrix. */
|
|
150
|
+
export function worldSphere(
|
|
151
|
+
local: Sphere,
|
|
152
|
+
object: Object3D,
|
|
153
|
+
out: Sphere = new Sphere().copy(local), // the engine's Sphere binds no clone
|
|
154
|
+
matrix: Matrix4 = object.matrixWorld,
|
|
155
|
+
): Sphere {
|
|
156
|
+
out.center.copy(local.center).applyMatrix4(matrix);
|
|
157
|
+
const scale = matrix.getMaxScaleOnAxis();
|
|
158
|
+
out.radius = local.radius * scale;
|
|
159
|
+
return out;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* The coarsest level whose projected error fits the budget in every supplied view, then stabilized
|
|
164
|
+
* against the current level.
|
|
165
|
+
*
|
|
166
|
+
* Refines immediately: a selected level over budget is replaced by the finest one that fits. Coarsens
|
|
167
|
+
* only when the candidate is comfortably inside `(1 - hysteresis) * budget`, which stops a camera
|
|
168
|
+
* breathing across a boundary from flipping levels. `levels[0]` is LOD0 and must carry error 0.
|
|
169
|
+
*/
|
|
170
|
+
export function selectLodLevel(
|
|
171
|
+
absoluteErrors: readonly number[],
|
|
172
|
+
current: number,
|
|
173
|
+
budgetPixels: number,
|
|
174
|
+
hysteresis: number,
|
|
175
|
+
views: readonly ILodView[],
|
|
176
|
+
): number {
|
|
177
|
+
if (absoluteErrors.length === 0) return 0;
|
|
178
|
+
const last = absoluteErrors.length - 1;
|
|
179
|
+
if (!(budgetPixels > 0) || views.length === 0) return 0;
|
|
180
|
+
const clampedCurrent = Math.min(Math.max(Math.trunc(current), 0), last);
|
|
181
|
+
|
|
182
|
+
let target = 0;
|
|
183
|
+
outer: for (let index = last; index >= 1; index -= 1) {
|
|
184
|
+
const error = absoluteErrors[index] as number;
|
|
185
|
+
for (const view of views) {
|
|
186
|
+
if (view.degenerate || view.finest === true) continue outer;
|
|
187
|
+
if (projectedLodError(error, view.camera, view.viewportHeight, view.depth) > budgetPixels) {
|
|
188
|
+
continue outer;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
target = index;
|
|
192
|
+
break;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if (target <= clampedCurrent) return target;
|
|
196
|
+
|
|
197
|
+
// Coarsening: reject it unless the candidate is under the hysteresis-adjusted budget in every view.
|
|
198
|
+
const threshold = (1 - hysteresis) * budgetPixels;
|
|
199
|
+
for (const view of views) {
|
|
200
|
+
if (view.degenerate || view.finest === true) return clampedCurrent;
|
|
201
|
+
const error = absoluteErrors[target] as number;
|
|
202
|
+
if (projectedLodError(error, view.camera, view.viewportHeight, view.depth) >= threshold)
|
|
203
|
+
return clampedCurrent;
|
|
204
|
+
}
|
|
205
|
+
return target;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** The glTF extension the asset pipeline writes the discrete chain into. */
|
|
209
|
+
export const TN_DISCRETE_LOD = "TN_discrete_lod";
|
|
210
|
+
|
|
211
|
+
/** Bumped with the written layout; a reader refuses a version it does not understand. */
|
|
212
|
+
export const DISCRETE_LOD_SCHEMA_VERSION = 1;
|
|
213
|
+
|
|
214
|
+
/** Default screen-space error budget, in pixels, when no resolved policy reaches the loader. */
|
|
215
|
+
export const DISCRETE_LOD_DEFAULT_ERROR_PIXELS = 1;
|
|
216
|
+
/** Default coarsen hysteresis when no resolved policy reaches the loader. */
|
|
217
|
+
export const DISCRETE_LOD_DEFAULT_HYSTERESIS = 0.15;
|
|
218
|
+
|
|
219
|
+
interface IDiscreteLodDef {
|
|
220
|
+
readonly absoluteErrors?: unknown;
|
|
221
|
+
readonly counts?: unknown;
|
|
222
|
+
readonly errors?: unknown;
|
|
223
|
+
readonly indices?: unknown;
|
|
224
|
+
readonly lod0Triangles?: unknown;
|
|
225
|
+
readonly schemaVersion?: unknown;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
interface IParserLike {
|
|
229
|
+
readonly associations: Map<object, { meshes?: number; nodes?: number; primitives?: number }>;
|
|
230
|
+
getDependency(type: string, index: number): Promise<unknown>;
|
|
231
|
+
readonly json: {
|
|
232
|
+
animations?: { channels?: { target?: { node?: number } }[] }[];
|
|
233
|
+
extensions?: Record<string, unknown>;
|
|
234
|
+
meshes?: { name?: string; primitives?: { extensions?: Record<string, unknown> }[] }[];
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
interface IPendingLevels {
|
|
239
|
+
readonly absoluteErrors: number[];
|
|
240
|
+
readonly indices: Uint32Array[];
|
|
241
|
+
readonly lod0Triangles: number;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function numberArray(value: unknown, label: string): number[] {
|
|
245
|
+
if (!Array.isArray(value) || value.some((entry) => typeof entry !== "number"))
|
|
246
|
+
throw new Error(`${label} must be an array of numbers.`);
|
|
247
|
+
return value as number[];
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Reads and validates one primitive's chain. Fails closed: an unreadable payload is a defect in the
|
|
252
|
+
* file, and the caller keeps LOD0 and reports it rather than drawing a mangled mesh.
|
|
253
|
+
*/
|
|
254
|
+
async function readPendingLevels(
|
|
255
|
+
parser: IParserLike,
|
|
256
|
+
def: IDiscreteLodDef,
|
|
257
|
+
): Promise<IPendingLevels> {
|
|
258
|
+
if (def.schemaVersion !== DISCRETE_LOD_SCHEMA_VERSION)
|
|
259
|
+
throw new Error(
|
|
260
|
+
`schema version ${String(def.schemaVersion)} is not ${String(DISCRETE_LOD_SCHEMA_VERSION)}.`,
|
|
261
|
+
);
|
|
262
|
+
const indices = numberArray(def.indices, "indices");
|
|
263
|
+
const counts = numberArray(def.counts, "counts");
|
|
264
|
+
const errors = numberArray(def.errors, "errors");
|
|
265
|
+
const absoluteErrors = numberArray(def.absoluteErrors, "absoluteErrors");
|
|
266
|
+
if (
|
|
267
|
+
indices.length !== counts.length ||
|
|
268
|
+
counts.length !== errors.length ||
|
|
269
|
+
counts.length !== absoluteErrors.length
|
|
270
|
+
)
|
|
271
|
+
throw new Error("the level arrays are not parallel.");
|
|
272
|
+
if (typeof def.lod0Triangles !== "number" || !(def.lod0Triangles > 0))
|
|
273
|
+
throw new Error("lod0Triangles must be a positive number.");
|
|
274
|
+
const resolved: Uint32Array[] = [];
|
|
275
|
+
for (const index of indices) {
|
|
276
|
+
const accessor = (await parser.getDependency("accessor", index)) as {
|
|
277
|
+
array: ArrayLike<number>;
|
|
278
|
+
};
|
|
279
|
+
const array = accessor.array;
|
|
280
|
+
resolved.push(array instanceof Uint32Array ? array : Uint32Array.from(array));
|
|
281
|
+
}
|
|
282
|
+
let previous = def.lod0Triangles;
|
|
283
|
+
let previousError = -1;
|
|
284
|
+
for (let level = 0; level < resolved.length; level += 1) {
|
|
285
|
+
const triangles = Math.floor((resolved[level] as Uint32Array).length / 3);
|
|
286
|
+
const error = errors[level] as number;
|
|
287
|
+
if (triangles <= 0 || triangles >= previous)
|
|
288
|
+
throw new Error(`level ${String(level)} is not a reduction.`);
|
|
289
|
+
if (!Number.isFinite(error) || error < previousError)
|
|
290
|
+
throw new Error(`level ${String(level)} has non-monotonic error.`);
|
|
291
|
+
previous = triangles;
|
|
292
|
+
previousError = error;
|
|
293
|
+
}
|
|
294
|
+
return { absoluteErrors, indices: resolved, lod0Triangles: def.lod0Triangles };
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* One baked chain: LOD0 is the mesh's own geometry, then one derived geometry per level sharing the
|
|
299
|
+
* same vertex attributes and differing only in index.
|
|
300
|
+
*
|
|
301
|
+
* A chain belongs to the geometry, not to the mesh, because `Object3D.clone()` — which is how a game
|
|
302
|
+
* reuses an imported model, and what `SkeletonUtils.clone` does for a rig — copies the mesh but
|
|
303
|
+
* *shares* its geometry. Keying selection to mesh identity would silently drop every clone to LOD0
|
|
304
|
+
* forever; recovering the chain from the geometry the clone carries is what makes a clone behave
|
|
305
|
+
* like the source.
|
|
306
|
+
*/
|
|
307
|
+
export interface ILodChain {
|
|
308
|
+
readonly levels: BufferGeometry[];
|
|
309
|
+
readonly errors: readonly number[];
|
|
310
|
+
readonly base: BufferGeometry;
|
|
311
|
+
/** Local-space bounds of the base, shared by every mesh over the chain; the mesh matrix is not. */
|
|
312
|
+
readonly sphere: Sphere;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** Triangles one level of a chain submits. */
|
|
316
|
+
function drawTriangles(geometry: BufferGeometry): number {
|
|
317
|
+
const drawn = geometry.index?.count ?? geometry.getAttribute("position")?.count ?? 0;
|
|
318
|
+
return Math.floor(drawn / 3);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* One mesh's selection state. Every clone shares the source's chain, so this — and only this — holds
|
|
323
|
+
* the level a particular copy currently shows: two copies at different distances must not fight.
|
|
324
|
+
*/
|
|
325
|
+
class ModelLod {
|
|
326
|
+
readonly #mesh: Mesh;
|
|
327
|
+
readonly #chain: ILodChain;
|
|
328
|
+
readonly #policy: IAppliedLod;
|
|
329
|
+
readonly #rung: JoinedRung | undefined;
|
|
330
|
+
/** Only the authority drives selection and activation; every other member merely reports hidden. */
|
|
331
|
+
readonly #authority: boolean;
|
|
332
|
+
#current = 0;
|
|
333
|
+
/** The join container, resolved once from the rung and the instance graph. */
|
|
334
|
+
#container: Object3D | null = null;
|
|
335
|
+
#containerResolved = false;
|
|
336
|
+
|
|
337
|
+
constructor(
|
|
338
|
+
mesh: Mesh,
|
|
339
|
+
chain: ILodChain,
|
|
340
|
+
policy: IAppliedLod,
|
|
341
|
+
rung?: JoinedRung,
|
|
342
|
+
authority = false,
|
|
343
|
+
) {
|
|
344
|
+
this.#mesh = mesh;
|
|
345
|
+
this.#chain = chain;
|
|
346
|
+
this.#policy = policy;
|
|
347
|
+
this.#rung = rung;
|
|
348
|
+
this.#authority = authority;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
get index(): number {
|
|
352
|
+
return this.#current;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** The full-detail geometry the chain was built against. */
|
|
356
|
+
get base(): BufferGeometry {
|
|
357
|
+
return this.#chain.base;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
get triangles(): number {
|
|
361
|
+
// With a joined rung active, the authored primitives draw nothing and the proxy draws the
|
|
362
|
+
// collapse: the authority reports the rung's triangles, every hidden sibling reports zero.
|
|
363
|
+
const rung = this.#rung;
|
|
364
|
+
if (rung?.isHidden(this.#mesh)) return this.#authority ? rung.triangles : 0;
|
|
365
|
+
return drawTriangles(this.#chain.levels[this.#current] as BufferGeometry);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
update(camera: Camera, viewportHeight: number): void {
|
|
369
|
+
const rung = this.#rung;
|
|
370
|
+
if (rung !== undefined && this.#authority) {
|
|
371
|
+
this.#updateJoined(rung, camera, viewportHeight);
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
const world = worldSphere(this.#chain.sphere, this.#mesh, undefined, this.#mesh.matrixWorld);
|
|
375
|
+
const { depth, degenerate } = conservativeViewDepth(
|
|
376
|
+
camera,
|
|
377
|
+
world.center,
|
|
378
|
+
world.radius,
|
|
379
|
+
(camera as ILodCameraLike).near ?? 0,
|
|
380
|
+
);
|
|
381
|
+
const view: ILodView = {
|
|
382
|
+
camera,
|
|
383
|
+
degenerate,
|
|
384
|
+
depth: biasedLodDistance(depth),
|
|
385
|
+
viewportHeight,
|
|
386
|
+
};
|
|
387
|
+
const index = selectLodLevel(
|
|
388
|
+
this.#chain.errors,
|
|
389
|
+
this.#current,
|
|
390
|
+
this.#policy.maxPixelError /
|
|
391
|
+
Math.max(this.#mesh.matrixWorld.getMaxScaleOnAxis(), Number.EPSILON),
|
|
392
|
+
this.#policy.hysteresis,
|
|
393
|
+
[view],
|
|
394
|
+
);
|
|
395
|
+
if (index === this.#current) return;
|
|
396
|
+
this.#current = index;
|
|
397
|
+
this.#mesh.geometry = this.#chain.levels[index] as BufferGeometry;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* The join selection. The rung replaces every member, so its bounds set the depth and the
|
|
402
|
+
* instance's container supplies the world transform the rung geometry was baked against.
|
|
403
|
+
*/
|
|
404
|
+
#updateJoined(rung: JoinedRung, camera: Camera, viewportHeight: number): void {
|
|
405
|
+
if (!this.#containerResolved) {
|
|
406
|
+
this.#container = rung.findContainer(this.#mesh);
|
|
407
|
+
this.#containerResolved = true;
|
|
408
|
+
}
|
|
409
|
+
const container = this.#container;
|
|
410
|
+
if (container === null) return;
|
|
411
|
+
const world = worldSphere(rung.sphere, container, undefined, container.matrixWorld);
|
|
412
|
+
const { depth, degenerate } = conservativeViewDepth(
|
|
413
|
+
camera,
|
|
414
|
+
world.center,
|
|
415
|
+
world.radius,
|
|
416
|
+
(camera as ILodCameraLike).near ?? 0,
|
|
417
|
+
);
|
|
418
|
+
const errors = [...this.#chain.errors, rung.error];
|
|
419
|
+
const joinedIndex = this.#chain.errors.length;
|
|
420
|
+
const view: ILodView = {
|
|
421
|
+
camera,
|
|
422
|
+
degenerate,
|
|
423
|
+
depth: biasedLodDistance(depth),
|
|
424
|
+
viewportHeight,
|
|
425
|
+
};
|
|
426
|
+
const index = selectLodLevel(
|
|
427
|
+
errors,
|
|
428
|
+
this.#current,
|
|
429
|
+
this.#policy.maxPixelError /
|
|
430
|
+
Math.max(container.matrixWorld.getMaxScaleOnAxis(), Number.EPSILON),
|
|
431
|
+
this.#policy.hysteresis,
|
|
432
|
+
[view],
|
|
433
|
+
);
|
|
434
|
+
if (index === joinedIndex) {
|
|
435
|
+
if (rung.activate(container)) {
|
|
436
|
+
this.#current = index;
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
// The rung was refused at runtime (a member moved since load, or the graph no longer carries
|
|
440
|
+
// every member): show the authored geometry rather than a proxy over stale transforms.
|
|
441
|
+
this.#current = 0;
|
|
442
|
+
this.#mesh.geometry = this.#chain.levels[0] as BufferGeometry;
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
445
|
+
rung.deactivate(container);
|
|
446
|
+
if (index !== this.#current) {
|
|
447
|
+
this.#current = index;
|
|
448
|
+
this.#mesh.geometry = this.#chain.levels[index] as BufferGeometry;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** Reverses an active joined rung when the mesh is removed from the graph. */
|
|
453
|
+
release(): void {
|
|
454
|
+
if (this.#rung !== undefined && this.#authority && this.#container !== null)
|
|
455
|
+
this.#rung.deactivate(this.#container);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/** Resolved runtime policy the loader stamps onto a controller, from the manifest. */
|
|
460
|
+
export interface IModelLodPolicy {
|
|
461
|
+
readonly hysteresis: number;
|
|
462
|
+
readonly maxPixelError: number;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
interface IAppliedLod {
|
|
466
|
+
readonly hysteresis: number;
|
|
467
|
+
readonly maxPixelError: number;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* The joined far rung as the artifact records it (`TN_discrete_lod.joined`, PRD-377 §4.4).
|
|
472
|
+
*
|
|
473
|
+
* `error` is the absolute local-space error of the merged, reduced far geometry: the coarsest step
|
|
474
|
+
* the one selection authority may pick, after every discrete level. `mesh` names the detached far
|
|
475
|
+
* mesh, `sources` are the authored `"mesh#primitive"` primitives it collapsed, and `draws` is the
|
|
476
|
+
* one-per-material count it draws as.
|
|
477
|
+
*/
|
|
478
|
+
interface IJoinedRungDef {
|
|
479
|
+
readonly draws: number;
|
|
480
|
+
readonly error: number;
|
|
481
|
+
readonly mesh: string;
|
|
482
|
+
readonly primitives: number;
|
|
483
|
+
readonly sources: readonly string[];
|
|
484
|
+
readonly triangles: number;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/**
|
|
488
|
+
* Proxy objects this module inserts to represent a joined rung. They carry the joined geometry but
|
|
489
|
+
* no authored node identity, so picking must not answer with them: `isLodJoinProxy` is how the
|
|
490
|
+
* framework picker keeps returning the authored primitives whether or not the camera joined them.
|
|
491
|
+
*/
|
|
492
|
+
// The root and /world entry points bundle this module separately, just like CHAINS_KEY below.
|
|
493
|
+
// Visibility handoffs must reach the rung selected by the other entry in the same realm.
|
|
494
|
+
const JOIN_STATE_KEY = Symbol.for("threenative.discreteLodJoinState");
|
|
495
|
+
const joinHost = globalThis as Record<symbol, unknown>;
|
|
496
|
+
const joinState = (joinHost[JOIN_STATE_KEY] ?? {
|
|
497
|
+
proxies: new WeakSet<object>(),
|
|
498
|
+
owners: new WeakMap<Mesh, Object3D>(),
|
|
499
|
+
}) as { proxies: WeakSet<object>; owners: WeakMap<Mesh, Object3D> };
|
|
500
|
+
joinHost[JOIN_STATE_KEY] = joinState;
|
|
501
|
+
const joinedProxies = joinState.proxies;
|
|
502
|
+
const joinedOwners = joinState.owners;
|
|
503
|
+
|
|
504
|
+
/** Internal layer ownership handoff: a joined rung represents the same source render passes. */
|
|
505
|
+
export function setModelLodLayers(mesh: Mesh, mask: number): void {
|
|
506
|
+
mesh.layers.mask = mask;
|
|
507
|
+
joinedOwners.get(mesh)?.traverse((node) => {
|
|
508
|
+
if ((node as Partial<Mesh>).isMesh === true) node.layers.mask = mask;
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/** True when `object` was inserted by the runtime as a joined-rung proxy, not authored in the file. */
|
|
513
|
+
export function isLodJoinProxy(object: object): boolean {
|
|
514
|
+
return joinedProxies.has(object);
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/** A primitive a joined rung can never represent: the bake refuses these, and the runtime re-checks. */
|
|
518
|
+
function isDeforming(mesh: Mesh): boolean {
|
|
519
|
+
return (
|
|
520
|
+
(mesh as Mesh & { isSkinnedMesh?: boolean }).isSkinnedMesh === true ||
|
|
521
|
+
Object.keys(mesh.geometry.morphAttributes).length > 0
|
|
522
|
+
);
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/**
|
|
526
|
+
* True when the mesh, or any ancestor strictly below `container`, is animation-targeted.
|
|
527
|
+
*
|
|
528
|
+
* The container itself is allowed to move: a rung baked in container space rides rigidly with it, so
|
|
529
|
+
* animating the model root does not invalidate the join. Only a member that moves independently —
|
|
530
|
+
* directly, or through an ancestor between it and the container — does.
|
|
531
|
+
*/
|
|
532
|
+
function isAnimatedInContainer(
|
|
533
|
+
mesh: Mesh,
|
|
534
|
+
container: Object3D,
|
|
535
|
+
animated: WeakSet<object>,
|
|
536
|
+
): boolean {
|
|
537
|
+
let current: Object3D | null = mesh;
|
|
538
|
+
while (current !== null && current !== container) {
|
|
539
|
+
if (animated.has(current)) return true;
|
|
540
|
+
current = current.parent;
|
|
541
|
+
}
|
|
542
|
+
return false;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/** The composed local transform of `node` relative to `container`, without touching world matrices. */
|
|
546
|
+
function relativeLocalMatrix(node: Object3D, container: Object3D): Matrix4 {
|
|
547
|
+
const matrix = new Matrix4();
|
|
548
|
+
let current: Object3D | null = node;
|
|
549
|
+
while (current !== null && current !== container) {
|
|
550
|
+
current.updateMatrix();
|
|
551
|
+
matrix.premultiply(current.matrix);
|
|
552
|
+
current = current.parent;
|
|
553
|
+
}
|
|
554
|
+
return matrix;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/** True when `node` is `ancestor` or sits below it. */
|
|
558
|
+
function isWithin(node: Object3D, ancestor: Object3D): boolean {
|
|
559
|
+
let current: Object3D | null = node;
|
|
560
|
+
while (current !== null) {
|
|
561
|
+
if (current === ancestor) return true;
|
|
562
|
+
current = current.parent;
|
|
563
|
+
}
|
|
564
|
+
return false;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/** The nearest common ancestor of every member, or `null` when they share no graph. */
|
|
568
|
+
function lowestCommonAncestor(members: readonly Object3D[]): Object3D | null {
|
|
569
|
+
if (members.length === 0) return null;
|
|
570
|
+
let ancestor: Object3D | null = (members[0] as Object3D).parent;
|
|
571
|
+
while (ancestor !== null) {
|
|
572
|
+
if (members.every((member) => isWithin(member, ancestor as Object3D))) return ancestor;
|
|
573
|
+
ancestor = ancestor.parent;
|
|
574
|
+
}
|
|
575
|
+
return null;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/** Narrows the artifact's joined-rung record, failing closed on a malformed one. */
|
|
579
|
+
function isJoinedRungDef(value: unknown): value is IJoinedRungDef {
|
|
580
|
+
if (typeof value !== "object" || value === null) return false;
|
|
581
|
+
const def = value as Partial<IJoinedRungDef>;
|
|
582
|
+
return (
|
|
583
|
+
typeof def.draws === "number" &&
|
|
584
|
+
Number.isFinite(def.draws) &&
|
|
585
|
+
typeof def.error === "number" &&
|
|
586
|
+
Number.isFinite(def.error) &&
|
|
587
|
+
typeof def.mesh === "string" &&
|
|
588
|
+
typeof def.primitives === "number" &&
|
|
589
|
+
typeof def.triangles === "number" &&
|
|
590
|
+
Array.isArray(def.sources) &&
|
|
591
|
+
def.sources.every((source) => typeof source === "string")
|
|
592
|
+
);
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
interface IJoinActivation {
|
|
596
|
+
readonly proxy: Object3D;
|
|
597
|
+
readonly restored: readonly { readonly mesh: Mesh; readonly visible: boolean }[];
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
/**
|
|
601
|
+
* One mesh's joined far rung: many authored primitives collapsed to one object, one draw per
|
|
602
|
+
* material — whether those primitives were within one mesh or across sibling meshes under a shared
|
|
603
|
+
* container.
|
|
604
|
+
*
|
|
605
|
+
* Selecting it is a draw-topology change, not a geometry pointer swap. The authored primitives stay
|
|
606
|
+
* in the graph — same identities, transforms, render order and picking — and are hidden while one
|
|
607
|
+
* proxy object is added under their shared container as a unit. Reverting removes the proxy and
|
|
608
|
+
* restores each primitive's authored visibility exactly. Per-container state lives here, so two
|
|
609
|
+
* instances of the same model at different distances never fight and a `clone()` gets its own.
|
|
610
|
+
*/
|
|
611
|
+
class JoinedRung {
|
|
612
|
+
readonly name: string;
|
|
613
|
+
readonly draws: number;
|
|
614
|
+
readonly primitives: number;
|
|
615
|
+
readonly triangles: number;
|
|
616
|
+
readonly error: number;
|
|
617
|
+
readonly sphere: Sphere;
|
|
618
|
+
readonly #prototype: Object3D;
|
|
619
|
+
readonly #geometries: Set<BufferGeometry>;
|
|
620
|
+
readonly #memberCount: number;
|
|
621
|
+
readonly #activations = new WeakMap<Object3D, IJoinActivation>();
|
|
622
|
+
/** The authored local transform of every source member, for the runtime-moved-sibling guard. */
|
|
623
|
+
readonly #baselines = new WeakMap<object, Matrix4>();
|
|
624
|
+
/** Members currently hidden by an activation, so a sibling knows it submits no draw this frame. */
|
|
625
|
+
readonly #hidden = new WeakSet<object>();
|
|
626
|
+
|
|
627
|
+
constructor(options: {
|
|
628
|
+
readonly def: IJoinedRungDef;
|
|
629
|
+
readonly geometries: ReadonlySet<BufferGeometry>;
|
|
630
|
+
readonly memberCount: number;
|
|
631
|
+
readonly prototype: Object3D;
|
|
632
|
+
readonly sphere: Sphere;
|
|
633
|
+
}) {
|
|
634
|
+
this.name = options.def.mesh;
|
|
635
|
+
this.draws = options.def.draws;
|
|
636
|
+
this.primitives = options.def.primitives;
|
|
637
|
+
this.triangles = options.def.triangles;
|
|
638
|
+
this.error = options.def.error;
|
|
639
|
+
this.#prototype = options.prototype;
|
|
640
|
+
this.#geometries = new Set(options.geometries);
|
|
641
|
+
this.#memberCount = options.memberCount;
|
|
642
|
+
this.sphere = options.sphere;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
/** True when a mesh is one of the members hidden by an active activation of this rung. */
|
|
646
|
+
isHidden(mesh: Mesh): boolean {
|
|
647
|
+
return this.#hidden.has(mesh);
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/**
|
|
651
|
+
* The nearest ancestor whose subtree contains every member of this rung — the container the rung
|
|
652
|
+
* was baked against. Geometry identity, not node identity, so a clone resolves its own container.
|
|
653
|
+
*/
|
|
654
|
+
findContainer(mesh: Mesh): Object3D | null {
|
|
655
|
+
let ancestor: Object3D | null = mesh.parent;
|
|
656
|
+
while (ancestor !== null) {
|
|
657
|
+
let found = 0;
|
|
658
|
+
ancestor.traverse((node) => {
|
|
659
|
+
const candidate = node as Partial<Mesh>;
|
|
660
|
+
if (
|
|
661
|
+
candidate.isMesh === true &&
|
|
662
|
+
candidate.geometry !== undefined &&
|
|
663
|
+
this.#geometries.has(candidate.geometry)
|
|
664
|
+
)
|
|
665
|
+
found += 1;
|
|
666
|
+
});
|
|
667
|
+
if (found >= this.#memberCount) return ancestor;
|
|
668
|
+
ancestor = ancestor.parent;
|
|
669
|
+
}
|
|
670
|
+
return null;
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/** Snapshots each source member's authored local transform at load, before any game script runs. */
|
|
674
|
+
captureBaselines(container: Object3D, members: readonly Mesh[]): void {
|
|
675
|
+
for (const member of members)
|
|
676
|
+
this.#baselines.set(member, relativeLocalMatrix(member, container));
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
activate(container: Object3D): boolean {
|
|
680
|
+
const members: Mesh[] = [];
|
|
681
|
+
container.traverse((node) => {
|
|
682
|
+
const mesh = node as Mesh;
|
|
683
|
+
if (mesh.isMesh === true && this.#geometries.has(mesh.geometry)) members.push(mesh);
|
|
684
|
+
});
|
|
685
|
+
if (members.length < this.#memberCount) return false;
|
|
686
|
+
const first = members[0];
|
|
687
|
+
if (first === undefined) return false;
|
|
688
|
+
// A joined draw cannot represent different per-member render-pass ownership.
|
|
689
|
+
if (
|
|
690
|
+
members.some(
|
|
691
|
+
(member) =>
|
|
692
|
+
member.layers.mask !== first.layers.mask ||
|
|
693
|
+
member.castShadow !== first.castShadow ||
|
|
694
|
+
member.receiveShadow !== first.receiveShadow,
|
|
695
|
+
)
|
|
696
|
+
) {
|
|
697
|
+
this.deactivate(container);
|
|
698
|
+
return false;
|
|
699
|
+
}
|
|
700
|
+
// The honest risk of joining siblings: their relative transforms are baked into the rung, so a
|
|
701
|
+
// node a script moves independently must be refused. A source member with a baseline that no
|
|
702
|
+
// longer matches its authored local transform is exactly that. (A clone is baselined on its
|
|
703
|
+
// first activation, so movement before that first selection is the one case this cannot see.)
|
|
704
|
+
for (const member of members) {
|
|
705
|
+
const current = relativeLocalMatrix(member, container);
|
|
706
|
+
const baseline = this.#baselines.get(member);
|
|
707
|
+
if (baseline === undefined) this.#baselines.set(member, current);
|
|
708
|
+
else if (!baseline.equals(current)) {
|
|
709
|
+
console.error(
|
|
710
|
+
`TN_DISCRETE_LOD_JOIN_INVALID: '${this.name}' cannot be shown as one unit; a source node moved after load.`,
|
|
711
|
+
);
|
|
712
|
+
if (this.#activations.has(container)) this.deactivate(container);
|
|
713
|
+
return false;
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
if (this.#activations.has(container)) return true;
|
|
717
|
+
const proxy = this.#prototype.clone(true);
|
|
718
|
+
proxy.name = `${this.name}__instance`;
|
|
719
|
+
proxy.visible = true;
|
|
720
|
+
proxy.traverse((node) => {
|
|
721
|
+
joinedProxies.add(node);
|
|
722
|
+
// A stock `Raycaster` ignores `visible`; a no-op raycast keeps the authored primitives the
|
|
723
|
+
// only picking surface even for a game that runs `intersectObjects` on the scene directly.
|
|
724
|
+
if ((node as Partial<Mesh>).isMesh === true) {
|
|
725
|
+
node.raycast = () => undefined;
|
|
726
|
+
node.layers.mask = first.layers.mask;
|
|
727
|
+
node.castShadow = first.castShadow;
|
|
728
|
+
node.receiveShadow = first.receiveShadow;
|
|
729
|
+
}
|
|
730
|
+
});
|
|
731
|
+
const restored: { mesh: Mesh; visible: boolean }[] = [];
|
|
732
|
+
for (const member of members) restored.push({ mesh: member, visible: member.visible });
|
|
733
|
+
for (const { mesh } of restored) {
|
|
734
|
+
mesh.visible = false;
|
|
735
|
+
this.#hidden.add(mesh);
|
|
736
|
+
joinedOwners.set(mesh, proxy);
|
|
737
|
+
}
|
|
738
|
+
container.add(proxy);
|
|
739
|
+
this.#activations.set(container, { proxy, restored });
|
|
740
|
+
// The LOD path's diagnostic: the selection fact and the draw collapse it bought, once per join.
|
|
741
|
+
console.info(
|
|
742
|
+
`TN_DISCRETE_LOD_JOINED ${this.name}: ${String(this.primitives)} primitive(s) collapsed to ${String(this.draws)} draw(s)`,
|
|
743
|
+
);
|
|
744
|
+
return true;
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
deactivate(container: Object3D): boolean {
|
|
748
|
+
const activation = this.#activations.get(container);
|
|
749
|
+
if (activation === undefined) return false;
|
|
750
|
+
for (const { mesh, visible } of activation.restored) {
|
|
751
|
+
mesh.visible = visible;
|
|
752
|
+
this.#hidden.delete(mesh);
|
|
753
|
+
joinedOwners.delete(mesh);
|
|
754
|
+
}
|
|
755
|
+
activation.proxy.removeFromParent();
|
|
756
|
+
this.#activations.delete(container);
|
|
757
|
+
return true;
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
/** A chain and its policy, registered against every level geometry so a clone can find it. */
|
|
762
|
+
interface IRegisteredChain {
|
|
763
|
+
readonly chain: ILodChain;
|
|
764
|
+
readonly policy: IAppliedLod;
|
|
765
|
+
/** Present on every member of a joined rung, so a clone resolves to the same rung. */
|
|
766
|
+
readonly joined?: JoinedRung;
|
|
767
|
+
/** True on the one member that drives selection and activation for the rung. */
|
|
768
|
+
readonly authority?: boolean;
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
/**
|
|
772
|
+
* Every chain currently registered, keyed weakly by each of its level geometries.
|
|
773
|
+
*
|
|
774
|
+
* Keyed by geometry, never by mesh, so a `clone()` — a new mesh over the shared geometry — resolves
|
|
775
|
+
* to the source's chain instead of vanishing. Weak on the key, so a chain whose last live geometry
|
|
776
|
+
* is dropped leaves with it: the value holds its own level geometries, and an ephemeron keeps that
|
|
777
|
+
* self-reference from pinning them.
|
|
778
|
+
*
|
|
779
|
+
* One map per realm, not per module copy: the package builds each entry without code splitting,
|
|
780
|
+
* so `@threenative/core` (whose asset loader registers) and `@threenative/core/world` (whose
|
|
781
|
+
* `WorldCells` reads) each carry this module. A module-local map left WorldCells finding no chain.
|
|
782
|
+
*/
|
|
783
|
+
const CHAINS_KEY = Symbol.for("threenative.discreteLodChains");
|
|
784
|
+
const chainsHost = globalThis as Record<symbol, unknown>;
|
|
785
|
+
const carriedChains = chainsHost[CHAINS_KEY] as
|
|
786
|
+
| WeakMap<BufferGeometry, IRegisteredChain>
|
|
787
|
+
| undefined;
|
|
788
|
+
const chains: WeakMap<BufferGeometry, IRegisteredChain> = carriedChains ?? new WeakMap();
|
|
789
|
+
chainsHost[CHAINS_KEY] = chains;
|
|
790
|
+
|
|
791
|
+
/**
|
|
792
|
+
* Geometry preparation commonly clones and bakes a model transform before instancing. Keep the
|
|
793
|
+
* existing index-only ladder over those copied attributes; never simplify the shape a second time.
|
|
794
|
+
* Hooks belong only to chain geometries, never to Three's prototype. Error scales conservatively
|
|
795
|
+
* by the matrix's largest axis, including non-uniform transforms.
|
|
796
|
+
*/
|
|
797
|
+
const cloneHooks = new WeakSet<BufferGeometry>();
|
|
798
|
+
function preserveChainClones(registered: IRegisteredChain): void {
|
|
799
|
+
for (const source of registered.chain.levels) {
|
|
800
|
+
if (cloneHooks.has(source)) continue;
|
|
801
|
+
cloneHooks.add(source);
|
|
802
|
+
const clone = source.clone.bind(source);
|
|
803
|
+
source.clone = (): BufferGeometry => {
|
|
804
|
+
const copy = clone();
|
|
805
|
+
const current = chains.get(source) ?? registered;
|
|
806
|
+
const chain = current.chain;
|
|
807
|
+
const sourceIndex = chain.levels.indexOf(source);
|
|
808
|
+
const levels = chain.levels.map((level, index) => {
|
|
809
|
+
const geometry = index === sourceIndex ? copy : new BufferGeometry();
|
|
810
|
+
if (geometry !== copy) {
|
|
811
|
+
for (const [name, attribute] of Object.entries(copy.attributes))
|
|
812
|
+
geometry.setAttribute(name, attribute);
|
|
813
|
+
geometry.setIndex(level.index?.clone() ?? null);
|
|
814
|
+
geometry.boundingSphere = copy.boundingSphere;
|
|
815
|
+
geometry.boundingBox = copy.boundingBox;
|
|
816
|
+
}
|
|
817
|
+
return geometry;
|
|
818
|
+
});
|
|
819
|
+
const copied: IRegisteredChain = {
|
|
820
|
+
chain: {
|
|
821
|
+
base: levels[0] as BufferGeometry,
|
|
822
|
+
errors: [...chain.errors],
|
|
823
|
+
levels,
|
|
824
|
+
sphere: chain.sphere.clone(),
|
|
825
|
+
},
|
|
826
|
+
policy: current.policy,
|
|
827
|
+
};
|
|
828
|
+
for (const geometry of levels) chains.set(geometry, copied);
|
|
829
|
+
preserveChainClones(copied);
|
|
830
|
+
const apply = copy.applyMatrix4.bind(copy);
|
|
831
|
+
copy.applyMatrix4 = (matrix: Matrix4): BufferGeometry => {
|
|
832
|
+
apply(matrix);
|
|
833
|
+
const errors = copied.chain.errors as number[];
|
|
834
|
+
const scale = matrix.getMaxScaleOnAxis();
|
|
835
|
+
for (let index = 1; index < errors.length; index += 1)
|
|
836
|
+
errors[index] = (errors[index] as number) * scale;
|
|
837
|
+
copied.chain.sphere.applyMatrix4(matrix);
|
|
838
|
+
return copy;
|
|
839
|
+
};
|
|
840
|
+
return copy;
|
|
841
|
+
};
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
/** Internal frame-tracker contract also used by InstancedBatch's partitioned draws. */
|
|
846
|
+
export interface IModelLodController {
|
|
847
|
+
readonly base: BufferGeometry;
|
|
848
|
+
readonly triangles: number;
|
|
849
|
+
update(camera: Camera, viewportHeight: number): void;
|
|
850
|
+
release(): void;
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
const controllers = new WeakMap<Mesh, IModelLodController>();
|
|
854
|
+
|
|
855
|
+
/** Register selection with the existing frame tracker rather than a second scene walk. */
|
|
856
|
+
export function registerModelLodController(mesh: Mesh, controller: IModelLodController): void {
|
|
857
|
+
controllers.get(mesh)?.release();
|
|
858
|
+
controllers.set(mesh, controller);
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
/** True when `object` is a mesh whose geometry carries a registered chain (a clone, or the source). */
|
|
862
|
+
function isChained(object: object): boolean {
|
|
863
|
+
const mesh = object as Partial<Mesh>;
|
|
864
|
+
const geometry = mesh.geometry;
|
|
865
|
+
return mesh.isMesh === true && geometry !== undefined && chains.has(geometry);
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
/**
|
|
869
|
+
* The mesh's selection state, or `undefined` when its geometry carries no chain.
|
|
870
|
+
*
|
|
871
|
+
* A clone the loader never saw is adopted here, on its first frame, from the geometry it shares with
|
|
872
|
+
* the source; every later frame finds the entry already made. The entry lives in a `WeakMap`, so a
|
|
873
|
+
* dropped clone is not retained, and adopts at most once, so a clone cannot double-register.
|
|
874
|
+
*/
|
|
875
|
+
function controllerFor(mesh: Mesh): IModelLodController | undefined {
|
|
876
|
+
const existing = controllers.get(mesh);
|
|
877
|
+
if (existing !== undefined) return existing;
|
|
878
|
+
// A plain instanced draw cannot use the one-object selector. Its batch owns partitioning.
|
|
879
|
+
if ((mesh as Mesh & { isInstancedMesh?: boolean }).isInstancedMesh === true) return undefined;
|
|
880
|
+
const registered = chains.get(mesh.geometry);
|
|
881
|
+
if (registered === undefined) return undefined;
|
|
882
|
+
const controller = new ModelLod(
|
|
883
|
+
mesh,
|
|
884
|
+
registered.chain,
|
|
885
|
+
registered.policy,
|
|
886
|
+
registered.joined,
|
|
887
|
+
registered.authority === true,
|
|
888
|
+
);
|
|
889
|
+
controllers.set(mesh, controller);
|
|
890
|
+
return controller;
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
/**
|
|
894
|
+
* `GLTFLoader` plugin that reads `TN_discrete_lod` and, once the base geometry is final, builds the
|
|
895
|
+
* derived index-only geometries and registers one controller per primitive.
|
|
896
|
+
*
|
|
897
|
+
* Reading and building are separate on purpose: `widenQuantizedPositions` runs after the loader
|
|
898
|
+
* returns and replaces the base position attribute, so derived geometries must be built *after* it
|
|
899
|
+
* to share the widened attributes rather than pin the quantized ones.
|
|
900
|
+
*/
|
|
901
|
+
export class DiscreteLodPlugin {
|
|
902
|
+
readonly name = TN_DISCRETE_LOD;
|
|
903
|
+
readonly #failClosed: boolean;
|
|
904
|
+
#parser: IParserLike | undefined;
|
|
905
|
+
readonly #pending = new Map<Mesh, IPendingLevels>();
|
|
906
|
+
readonly #rungs: { readonly def: IJoinedRungDef; readonly prototype: Object3D }[] = [];
|
|
907
|
+
/** A temporary holder for far-mesh prototypes, so widening reaches their joined geometry. */
|
|
908
|
+
#holder: Group | undefined;
|
|
909
|
+
|
|
910
|
+
/**
|
|
911
|
+
* `failClosed` rejects the load with the same named error the log line carries, for a loader that
|
|
912
|
+
* has no other way to tell a game its chain was dropped (the Wasm engine's, PRD-617).
|
|
913
|
+
*/
|
|
914
|
+
constructor(options: { readonly failClosed?: boolean } = {}) {
|
|
915
|
+
this.#failClosed = options.failClosed === true;
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
setParser(parser: IParserLike): void {
|
|
919
|
+
this.#parser = parser;
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
#invalid(message: string): void {
|
|
923
|
+
if (this.#failClosed) throw new Error(message);
|
|
924
|
+
console.error(message);
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
async afterRoot(result: { scene?: Object3D }): Promise<void> {
|
|
928
|
+
const parser = this.#parser;
|
|
929
|
+
if (parser === undefined) return;
|
|
930
|
+
for (const [object, association] of parser.associations) {
|
|
931
|
+
const mesh = object as Mesh;
|
|
932
|
+
if (mesh.isMesh !== true) continue;
|
|
933
|
+
const { meshes, primitives } = association;
|
|
934
|
+
if (meshes === undefined || primitives === undefined) continue;
|
|
935
|
+
const def = parser.json.meshes?.[meshes]?.primitives?.[primitives]?.extensions?.[
|
|
936
|
+
TN_DISCRETE_LOD
|
|
937
|
+
] as IDiscreteLodDef | undefined;
|
|
938
|
+
if (def === undefined) continue;
|
|
939
|
+
try {
|
|
940
|
+
this.#pending.set(mesh, await readPendingLevels(parser, def));
|
|
941
|
+
} catch (error) {
|
|
942
|
+
// LOD0 is intact and is what a game must still get; the file is the defect, not the game.
|
|
943
|
+
this.#invalid(
|
|
944
|
+
`TN_DISCRETE_LOD_INVALID: '${mesh.name || "unnamed"}' keeps full detail: ${error instanceof Error ? error.message : String(error)}`,
|
|
945
|
+
);
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
const metadata = parser.json.extensions?.[TN_DISCRETE_LOD] as { joined?: unknown } | undefined;
|
|
949
|
+
const joined = metadata?.joined;
|
|
950
|
+
if (!Array.isArray(joined) || joined.length === 0) return;
|
|
951
|
+
for (const value of joined) {
|
|
952
|
+
if (!isJoinedRungDef(value)) {
|
|
953
|
+
this.#invalid(
|
|
954
|
+
"TN_DISCRETE_LOD_JOIN_INVALID: a joined rung record is malformed; its primitives keep full detail.",
|
|
955
|
+
);
|
|
956
|
+
continue;
|
|
957
|
+
}
|
|
958
|
+
const farIndex = (parser.json.meshes ?? []).findIndex((mesh) => mesh.name === value.mesh);
|
|
959
|
+
if (farIndex < 0) {
|
|
960
|
+
this.#invalid(
|
|
961
|
+
`TN_DISCRETE_LOD_JOIN_INVALID: '${value.mesh}' is not one of the file's meshes; its primitives keep full detail.`,
|
|
962
|
+
);
|
|
963
|
+
continue;
|
|
964
|
+
}
|
|
965
|
+
try {
|
|
966
|
+
const prototype = (await parser.getDependency("mesh", farIndex)) as unknown;
|
|
967
|
+
if (!(prototype instanceof Object3D))
|
|
968
|
+
throw new Error("the far mesh dependency is not an Object3D.");
|
|
969
|
+
// Held under the loaded root until `attach` removes the holder, so `widenQuantizedPositions`
|
|
970
|
+
// reaches the joined geometry exactly as it reaches the authored primitives.
|
|
971
|
+
if (result.scene !== undefined) {
|
|
972
|
+
if (this.#holder === undefined) {
|
|
973
|
+
this.#holder = new Group();
|
|
974
|
+
this.#holder.name = "TN_LOD_JOIN_HOLDER";
|
|
975
|
+
result.scene.add(this.#holder);
|
|
976
|
+
}
|
|
977
|
+
this.#holder.add(prototype);
|
|
978
|
+
}
|
|
979
|
+
this.#rungs.push({ def: value, prototype });
|
|
980
|
+
} catch (error) {
|
|
981
|
+
console.error(
|
|
982
|
+
`TN_DISCRETE_LOD_JOIN_INVALID: '${value.mesh}' could not be read: ${error instanceof Error ? error.message : String(error)}`,
|
|
983
|
+
);
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
if (this.#rungs.length === 0 && this.#holder !== undefined) {
|
|
987
|
+
this.#holder.removeFromParent();
|
|
988
|
+
this.#holder = undefined;
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
/** Builds the derived geometries against the mesh's final (widened) attributes and registers. */
|
|
993
|
+
attach(_root: Object3D, policy: IModelLodPolicy | undefined): number {
|
|
994
|
+
const applied: IAppliedLod = {
|
|
995
|
+
hysteresis: policy?.hysteresis ?? DISCRETE_LOD_DEFAULT_HYSTERESIS,
|
|
996
|
+
maxPixelError: policy?.maxPixelError ?? DISCRETE_LOD_DEFAULT_ERROR_PIXELS,
|
|
997
|
+
};
|
|
998
|
+
// Detach the prototypes before anything else: they are loaded far meshes, never scene content.
|
|
999
|
+
for (const { prototype } of this.#rungs) prototype.removeFromParent();
|
|
1000
|
+
if (this.#holder !== undefined) {
|
|
1001
|
+
this.#holder.removeFromParent();
|
|
1002
|
+
this.#holder = undefined;
|
|
1003
|
+
}
|
|
1004
|
+
let appliedCount = 0;
|
|
1005
|
+
for (const [mesh, pending] of this.#pending) {
|
|
1006
|
+
const base = mesh.geometry;
|
|
1007
|
+
const baseTriangles = base.index?.count ?? base.getAttribute("position")?.count ?? 0;
|
|
1008
|
+
if (Math.floor(baseTriangles / 3) !== pending.lod0Triangles) {
|
|
1009
|
+
// The file's LOD0 no longer matches the payload that was baked against it; keep full detail.
|
|
1010
|
+
this.#invalid(
|
|
1011
|
+
`TN_DISCRETE_LOD_INVALID: '${mesh.name || "unnamed"}' keeps full detail: LOD0 triangles do not match the baked chain.`,
|
|
1012
|
+
);
|
|
1013
|
+
continue;
|
|
1014
|
+
}
|
|
1015
|
+
const levels: BufferGeometry[] = [base];
|
|
1016
|
+
// Same vertex positions, so the same bounds; computed here and shared, not cloned, so a chain
|
|
1017
|
+
// holds one bounds object and a game that pads the base's bounds after load — a
|
|
1018
|
+
// vertex-displacement material's, say — reaches every level instead of leaving a coarser one
|
|
1019
|
+
// culled against the bounds that were true at bake time.
|
|
1020
|
+
base.computeBoundingSphere();
|
|
1021
|
+
base.computeBoundingBox();
|
|
1022
|
+
for (const indices of pending.indices) {
|
|
1023
|
+
const geometry = new BufferGeometry();
|
|
1024
|
+
for (const [name, attribute] of Object.entries(base.attributes)) {
|
|
1025
|
+
geometry.setAttribute(name, attribute);
|
|
1026
|
+
}
|
|
1027
|
+
geometry.setIndex(new BufferAttribute(indices, 1));
|
|
1028
|
+
if (base.boundingSphere !== null && base.boundingSphere !== undefined)
|
|
1029
|
+
geometry.boundingSphere = base.boundingSphere;
|
|
1030
|
+
if (base.boundingBox !== null && base.boundingBox !== undefined)
|
|
1031
|
+
geometry.boundingBox = base.boundingBox;
|
|
1032
|
+
levels.push(geometry);
|
|
1033
|
+
}
|
|
1034
|
+
const sphere = new Sphere();
|
|
1035
|
+
if (base.boundingSphere !== null && base.boundingSphere !== undefined)
|
|
1036
|
+
sphere.copy(base.boundingSphere);
|
|
1037
|
+
const registered: IRegisteredChain = {
|
|
1038
|
+
chain: { base, errors: [0, ...pending.absoluteErrors], levels, sphere },
|
|
1039
|
+
policy: applied,
|
|
1040
|
+
};
|
|
1041
|
+
// Every level, not just the base: a clone made after a selection already swapped the source to
|
|
1042
|
+
// a coarser level carries that derived geometry, and must still resolve to this chain.
|
|
1043
|
+
for (const geometry of levels) chains.set(geometry, registered);
|
|
1044
|
+
preserveChainClones(registered);
|
|
1045
|
+
controllers.set(mesh, new ModelLod(mesh, registered.chain, applied));
|
|
1046
|
+
appliedCount += 1;
|
|
1047
|
+
}
|
|
1048
|
+
this.#registerJoinedRungs(applied);
|
|
1049
|
+
return appliedCount;
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
/**
|
|
1053
|
+
* Resolves each loaded joined rung to its authored primitives and registers it on every member's
|
|
1054
|
+
* chain, marking one as the authority. A clone shares those geometries, so it adopts the same rung
|
|
1055
|
+
* with its own authority; the rung's per-container state keeps two instances independent.
|
|
1056
|
+
*
|
|
1057
|
+
* Refusal is the honest default: a rung whose sources are not all present, share no container, or
|
|
1058
|
+
* are skinned, morphed or animated is dropped rather than half-joined. The bake already made that
|
|
1059
|
+
* call; the runtime re-checks because the loaded graph, not the bake, is what it hides.
|
|
1060
|
+
*/
|
|
1061
|
+
#registerJoinedRungs(applied: IAppliedLod): void {
|
|
1062
|
+
const parser = this.#parser;
|
|
1063
|
+
if (parser === undefined || this.#rungs.length === 0) return;
|
|
1064
|
+
const byKey = new Map<string, Mesh>();
|
|
1065
|
+
const animated = new WeakSet<object>();
|
|
1066
|
+
const targeted = new Set<number>();
|
|
1067
|
+
for (const animation of parser.json.animations ?? []) {
|
|
1068
|
+
for (const channel of animation.channels ?? []) {
|
|
1069
|
+
if (typeof channel.target?.node === "number") targeted.add(channel.target.node);
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
1072
|
+
for (const [object, association] of parser.associations) {
|
|
1073
|
+
if (targeted.size > 0 && association.nodes !== undefined && targeted.has(association.nodes))
|
|
1074
|
+
animated.add(object);
|
|
1075
|
+
const mesh = object as Mesh;
|
|
1076
|
+
if (mesh.isMesh !== true) continue;
|
|
1077
|
+
const { meshes, primitives } = association;
|
|
1078
|
+
if (meshes === undefined || primitives === undefined) continue;
|
|
1079
|
+
const name = parser.json.meshes?.[meshes]?.name ?? "";
|
|
1080
|
+
byKey.set(`${name}#${String(primitives)}`, mesh);
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
for (const { def, prototype } of this.#rungs) {
|
|
1084
|
+
const members: Mesh[] = [];
|
|
1085
|
+
let missing = false;
|
|
1086
|
+
for (const source of def.sources) {
|
|
1087
|
+
const mesh = byKey.get(source);
|
|
1088
|
+
if (mesh === undefined) {
|
|
1089
|
+
missing = true;
|
|
1090
|
+
break;
|
|
1091
|
+
}
|
|
1092
|
+
members.push(mesh);
|
|
1093
|
+
}
|
|
1094
|
+
const container = lowestCommonAncestor(members);
|
|
1095
|
+
const refused =
|
|
1096
|
+
missing ||
|
|
1097
|
+
members.length < 2 ||
|
|
1098
|
+
container === null ||
|
|
1099
|
+
members.some(
|
|
1100
|
+
(member) => isDeforming(member) || isAnimatedInContainer(member, container, animated),
|
|
1101
|
+
);
|
|
1102
|
+
if (refused) {
|
|
1103
|
+
console.error(
|
|
1104
|
+
`TN_DISCRETE_LOD_JOIN_INVALID: '${def.mesh}' cannot be shown as one unit at runtime; its primitives keep full detail.`,
|
|
1105
|
+
);
|
|
1106
|
+
continue;
|
|
1107
|
+
}
|
|
1108
|
+
// Every member needs a chain so the frame tracker manages it, even one the discrete pass
|
|
1109
|
+
// skipped: a join-only cook (maxLevels 1) writes no per-primitive chain at all.
|
|
1110
|
+
const geometries = new Set<BufferGeometry>();
|
|
1111
|
+
for (const member of members) {
|
|
1112
|
+
let registered = chains.get(member.geometry);
|
|
1113
|
+
if (registered === undefined) {
|
|
1114
|
+
member.geometry.computeBoundingSphere();
|
|
1115
|
+
const sphere = new Sphere();
|
|
1116
|
+
if (
|
|
1117
|
+
member.geometry.boundingSphere !== null &&
|
|
1118
|
+
member.geometry.boundingSphere !== undefined
|
|
1119
|
+
)
|
|
1120
|
+
sphere.copy(member.geometry.boundingSphere);
|
|
1121
|
+
registered = {
|
|
1122
|
+
chain: { base: member.geometry, errors: [0], levels: [member.geometry], sphere },
|
|
1123
|
+
policy: applied,
|
|
1124
|
+
};
|
|
1125
|
+
chains.set(member.geometry, registered);
|
|
1126
|
+
}
|
|
1127
|
+
for (const geometry of registered.chain.levels) geometries.add(geometry);
|
|
1128
|
+
}
|
|
1129
|
+
const box = new Box3().setFromObject(prototype);
|
|
1130
|
+
const sphere = new Sphere();
|
|
1131
|
+
box.getBoundingSphere(sphere);
|
|
1132
|
+
const rung = new JoinedRung({
|
|
1133
|
+
def,
|
|
1134
|
+
geometries,
|
|
1135
|
+
memberCount: members.length,
|
|
1136
|
+
prototype,
|
|
1137
|
+
sphere,
|
|
1138
|
+
});
|
|
1139
|
+
rung.captureBaselines(container, members);
|
|
1140
|
+
const authority = members[0] as Mesh;
|
|
1141
|
+
for (const member of members) {
|
|
1142
|
+
const registered = chains.get(member.geometry);
|
|
1143
|
+
if (registered === undefined) continue;
|
|
1144
|
+
const withJoined: IRegisteredChain = {
|
|
1145
|
+
authority: member === authority,
|
|
1146
|
+
chain: registered.chain,
|
|
1147
|
+
joined: rung,
|
|
1148
|
+
policy: registered.policy,
|
|
1149
|
+
};
|
|
1150
|
+
// Every level, not just the base: a clone made after a selection already swapped a member to
|
|
1151
|
+
// a coarser level carries that derived geometry, and must still resolve to this rung.
|
|
1152
|
+
for (const geometry of registered.chain.levels) chains.set(geometry, withJoined);
|
|
1153
|
+
// Members that were already managed (a discrete chain) were built before the rung was known;
|
|
1154
|
+
// rebuild them with the rung and the authority mark.
|
|
1155
|
+
controllers.set(
|
|
1156
|
+
member,
|
|
1157
|
+
new ModelLod(member, registered.chain, applied, rung, member === authority),
|
|
1158
|
+
);
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
/** The LOD0 geometry of a mesh under a discrete chain, or the mesh's own geometry otherwise. */
|
|
1165
|
+
export function baseGeometryOf(mesh: Mesh): BufferGeometry {
|
|
1166
|
+
const controller = controllers.get(mesh);
|
|
1167
|
+
if (controller !== undefined) return controller.base;
|
|
1168
|
+
return chains.get(mesh.geometry)?.chain.base ?? mesh.geometry;
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
/**
|
|
1172
|
+
* The chain registered against `geometry`, or `undefined` when the geometry carries none.
|
|
1173
|
+
*
|
|
1174
|
+
* For a caller that draws one geometry many times. A `ModelLod` swaps one mesh's geometry, so an
|
|
1175
|
+
* instanced batch — which cannot swap a geometry per instance — derives levels of its own from these
|
|
1176
|
+
* numbers and crosses between them by distance instead. Selection stays here: this reads the chain
|
|
1177
|
+
* out and hands it over, and the caller does the arithmetic {@link projectedLodError} documents, with
|
|
1178
|
+
* a screen-space error budget of its own — a batch's placements are all at different distances, so
|
|
1179
|
+
* the budget the loader registered the chain with, which is calibrated for the one mesh it drives,
|
|
1180
|
+
* is not the one that applies. Any level of a chain answers, since a clone may be carrying a derived
|
|
1181
|
+
* geometry.
|
|
1182
|
+
*/
|
|
1183
|
+
export function lodChainOf(geometry: BufferGeometry): ILodChain | undefined {
|
|
1184
|
+
return chains.get(geometry)?.chain;
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
// --- Per-frame update, mirroring `updateClusteredMeshes` ----------------------------------------
|
|
1188
|
+
|
|
1189
|
+
/** The event surface this module subscribes to. Structural, so traverse-only stand-ins keep working. */
|
|
1190
|
+
interface IGraphNode {
|
|
1191
|
+
addEventListener(type: string, listener: (event: never) => void): void;
|
|
1192
|
+
removeEventListener(type: string, listener: (event: never) => void): void;
|
|
1193
|
+
traverse(callback: (object: object) => void): void;
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
interface IChildGraphEvent {
|
|
1197
|
+
readonly child?: unknown;
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
interface ITrackedRoot {
|
|
1201
|
+
readonly items: Set<Mesh>;
|
|
1202
|
+
readonly hooked: WeakSet<object>;
|
|
1203
|
+
readonly onAdded: (event: IChildGraphEvent) => void;
|
|
1204
|
+
readonly onRemoved: (event: IChildGraphEvent) => void;
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
const trackedRoots = new WeakMap<object, ITrackedRoot>();
|
|
1208
|
+
|
|
1209
|
+
function isGraphNode(root: object): root is IGraphNode {
|
|
1210
|
+
const candidate = root as Partial<IGraphNode>;
|
|
1211
|
+
return (
|
|
1212
|
+
typeof candidate.traverse === "function" &&
|
|
1213
|
+
typeof candidate.addEventListener === "function" &&
|
|
1214
|
+
typeof candidate.removeEventListener === "function"
|
|
1215
|
+
);
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
function hookSubtree(tracking: ITrackedRoot, subtree: object): void {
|
|
1219
|
+
(subtree as IGraphNode).traverse((node) => {
|
|
1220
|
+
if (controllers.has(node as Mesh) || isChained(node)) tracking.items.add(node as Mesh);
|
|
1221
|
+
if (tracking.hooked.has(node)) return;
|
|
1222
|
+
tracking.hooked.add(node);
|
|
1223
|
+
const link = node as Partial<IGraphNode>;
|
|
1224
|
+
if (typeof link.addEventListener !== "function") return;
|
|
1225
|
+
link.addEventListener("childadded", tracking.onAdded);
|
|
1226
|
+
(link as IGraphNode).addEventListener("childremoved", tracking.onRemoved);
|
|
1227
|
+
});
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
function unhookSubtree(tracking: ITrackedRoot, subtree: object): void {
|
|
1231
|
+
// Releasing a controller can remove a joined sibling. Snapshot before releasing so Three's
|
|
1232
|
+
// traversal never indexes a children array that the release just shortened.
|
|
1233
|
+
const nodes: object[] = [];
|
|
1234
|
+
(subtree as IGraphNode).traverse((node) => nodes.push(node));
|
|
1235
|
+
for (const node of nodes) {
|
|
1236
|
+
tracking.items.delete(node as Mesh);
|
|
1237
|
+
// A removed mesh must not leave a joined proxy behind in a container that stays in the scene.
|
|
1238
|
+
controllers.get(node as Mesh)?.release();
|
|
1239
|
+
if (!tracking.hooked.has(node)) continue;
|
|
1240
|
+
tracking.hooked.delete(node);
|
|
1241
|
+
const link = node as Partial<IGraphNode>;
|
|
1242
|
+
if (typeof link.removeEventListener !== "function") continue;
|
|
1243
|
+
link.removeEventListener("childadded", tracking.onAdded);
|
|
1244
|
+
(link as IGraphNode).removeEventListener("childremoved", tracking.onRemoved);
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
function trackRoot(root: IGraphNode): ITrackedRoot {
|
|
1249
|
+
const existing = trackedRoots.get(root);
|
|
1250
|
+
if (existing !== undefined) return existing;
|
|
1251
|
+
const tracking: ITrackedRoot = {
|
|
1252
|
+
hooked: new WeakSet(),
|
|
1253
|
+
items: new Set(),
|
|
1254
|
+
onAdded: (event) => {
|
|
1255
|
+
const child: unknown = event.child;
|
|
1256
|
+
if (typeof child === "object" && child !== null && isGraphNode(child))
|
|
1257
|
+
hookSubtree(tracking, child);
|
|
1258
|
+
},
|
|
1259
|
+
onRemoved: (event) => {
|
|
1260
|
+
const child: unknown = event.child;
|
|
1261
|
+
if (
|
|
1262
|
+
typeof child === "object" &&
|
|
1263
|
+
child !== null &&
|
|
1264
|
+
typeof (child as Partial<IGraphNode>).traverse === "function"
|
|
1265
|
+
)
|
|
1266
|
+
unhookSubtree(tracking, child);
|
|
1267
|
+
},
|
|
1268
|
+
};
|
|
1269
|
+
trackedRoots.set(root, tracking);
|
|
1270
|
+
hookSubtree(tracking, root);
|
|
1271
|
+
return tracking;
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
/**
|
|
1275
|
+
* Takes every discrete-LOD mesh under `root` through this frame's selection.
|
|
1276
|
+
*
|
|
1277
|
+
* The engine calls this itself, once a frame, after matrices are synced and before the render.
|
|
1278
|
+
* Multi-view callers that need the finest level across passes use {@link selectLodLevel} directly;
|
|
1279
|
+
* this entry point selects for the one camera it is handed — which is the main view, and is at
|
|
1280
|
+
* least as fine as a shadow pass of lower resolution needs.
|
|
1281
|
+
*
|
|
1282
|
+
* @returns triangles the managed meshes will submit this frame.
|
|
1283
|
+
*/
|
|
1284
|
+
export function updateModelLods(
|
|
1285
|
+
root: { traverse(callback: (object: object) => void): void },
|
|
1286
|
+
camera: Camera,
|
|
1287
|
+
viewportHeight: number,
|
|
1288
|
+
): number {
|
|
1289
|
+
camera.updateMatrixWorld();
|
|
1290
|
+
if (!isGraphNode(root)) {
|
|
1291
|
+
const entries: IModelLodController[] = [];
|
|
1292
|
+
root.traverse((object) => {
|
|
1293
|
+
const entry = controllerFor(object as Mesh);
|
|
1294
|
+
if (entry !== undefined) entries.push(entry);
|
|
1295
|
+
});
|
|
1296
|
+
for (const entry of entries) entry.update(camera, viewportHeight);
|
|
1297
|
+
// Summed after every selection, so a joined rung activated by the authority is reflected in
|
|
1298
|
+
// its hidden siblings' counts whatever order the traversal visited them in.
|
|
1299
|
+
let triangles = 0;
|
|
1300
|
+
for (const entry of entries) triangles += entry.triangles;
|
|
1301
|
+
return triangles;
|
|
1302
|
+
}
|
|
1303
|
+
const tracking = trackRoot(root);
|
|
1304
|
+
for (const mesh of tracking.items) {
|
|
1305
|
+
const entry = controllerFor(mesh);
|
|
1306
|
+
if (entry === undefined) {
|
|
1307
|
+
tracking.items.delete(mesh);
|
|
1308
|
+
continue;
|
|
1309
|
+
}
|
|
1310
|
+
entry.update(camera, viewportHeight);
|
|
1311
|
+
}
|
|
1312
|
+
let triangles = 0;
|
|
1313
|
+
for (const mesh of tracking.items) triangles += controllers.get(mesh)?.triangles ?? 0;
|
|
1314
|
+
return triangles;
|
|
1315
|
+
}
|