@threenative/core 0.3.4 → 0.3.6
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-Jz4Fdoeb.d.ts} +114 -11
- package/dist/hot.d.ts +4 -4
- package/dist/index.d.ts +712 -118
- package/dist/index.js +12437 -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 +57 -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 +2408 -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 +574 -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 +850 -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
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import type { IRendererLike } from "./renderer.js";
|
|
2
|
+
|
|
3
|
+
export interface IGPUReadbackOptions {
|
|
4
|
+
/** The GPU storage attribute to copy — a TSL storage node's `.value`. */
|
|
5
|
+
readonly attribute: unknown;
|
|
6
|
+
/**
|
|
7
|
+
* Frames between readback requests. `1` asks every frame; larger values throttle.
|
|
8
|
+
*
|
|
9
|
+
* A copy off the GPU costs a queue submission and a mapped buffer, so a game reading a field it
|
|
10
|
+
* only consults for physics asks for it every few frames and pays the staleness instead.
|
|
11
|
+
*/
|
|
12
|
+
readonly everyFrames: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** A landed copy of GPU memory, with the age of the frame that produced it. */
|
|
16
|
+
export interface IGPUReadbackSample {
|
|
17
|
+
readonly data: Float32Array;
|
|
18
|
+
/**
|
|
19
|
+
* Frames between the frame whose GPU state these bytes hold and the frame reading them.
|
|
20
|
+
*
|
|
21
|
+
* This is the number a caller must not be allowed to ignore. A buoyancy solver that treats a
|
|
22
|
+
* 4-frame-old surface as this frame's surface floats a hull through the water it is drawn on,
|
|
23
|
+
* and nothing in the frame says so.
|
|
24
|
+
*/
|
|
25
|
+
readonly staleFrames: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* A throttled, fire-and-forget copy of a GPU buffer into CPU memory.
|
|
30
|
+
*
|
|
31
|
+
* Every sample it hands back carries its own age. That is the whole point: the copy is
|
|
32
|
+
* asynchronous, so the bytes are always some frames behind the GPU, and a class that hid that
|
|
33
|
+
* would let a caller mistake stale data for live data with no way to find out.
|
|
34
|
+
*
|
|
35
|
+
* `request()` never awaits and never blocks the frame. One copy is in flight at a time; requests
|
|
36
|
+
* made while one is pending are dropped rather than queued, because a backlog of copies of a field
|
|
37
|
+
* that has already moved on is latency with no information in it.
|
|
38
|
+
*/
|
|
39
|
+
export class GPUReadback {
|
|
40
|
+
readonly everyFrames: number;
|
|
41
|
+
#attribute: unknown;
|
|
42
|
+
/** Frames observed through `request()`. The clock every other number here is measured against. */
|
|
43
|
+
#frame = 0;
|
|
44
|
+
/** The frame whose GPU state the landed bytes hold, or `-1` when nothing has landed. */
|
|
45
|
+
#sampleFrame = -1;
|
|
46
|
+
/** The frame the in-flight request was issued on, or `-1` when none is in flight. */
|
|
47
|
+
#requestedFrame = -1;
|
|
48
|
+
#pending = false;
|
|
49
|
+
#data: Float32Array | undefined;
|
|
50
|
+
#requests = 0;
|
|
51
|
+
#lands = 0;
|
|
52
|
+
#failures = 0;
|
|
53
|
+
#released = false;
|
|
54
|
+
|
|
55
|
+
constructor(options: IGPUReadbackOptions) {
|
|
56
|
+
if (options.attribute === undefined || options.attribute === null)
|
|
57
|
+
throw new Error("GPUReadback.attribute is required.");
|
|
58
|
+
if (!Number.isInteger(options.everyFrames) || options.everyFrames <= 0)
|
|
59
|
+
throw new Error("GPUReadback.everyFrames must be a positive integer.");
|
|
60
|
+
this.#attribute = options.attribute;
|
|
61
|
+
this.everyFrames = options.everyFrames;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
get released(): boolean {
|
|
65
|
+
return this.#released;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** True while a copy is in flight. A game that wants to pace its own work can read it. */
|
|
69
|
+
get pending(): boolean {
|
|
70
|
+
return this.#pending;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The newest landed bytes, or `undefined` before the first copy lands. */
|
|
74
|
+
get data(): Float32Array | undefined {
|
|
75
|
+
return this.#data;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* How many frames old the landed bytes are.
|
|
80
|
+
*
|
|
81
|
+
* Before anything has landed this is the number of frames since construction, which grows
|
|
82
|
+
* without bound on purpose: "no data yet" and "data from frame zero" must not read the same.
|
|
83
|
+
*/
|
|
84
|
+
get staleFrames(): number {
|
|
85
|
+
if (this.#sampleFrame < 0) return this.#frame;
|
|
86
|
+
return this.#frame - this.#sampleFrame;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The newest bytes with their age attached, or `undefined` before the first copy lands. */
|
|
90
|
+
get sample(): IGPUReadbackSample | undefined {
|
|
91
|
+
if (this.#data === undefined) return undefined;
|
|
92
|
+
return { data: this.#data, staleFrames: this.staleFrames };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Requests, landings and failures, for a report that has to say why a sample is old. */
|
|
96
|
+
get stats(): { readonly requests: number; readonly lands: number; readonly failures: number } {
|
|
97
|
+
return { requests: this.#requests, lands: this.#lands, failures: this.#failures };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Advances the frame clock and starts a copy when the throttle allows one.
|
|
102
|
+
*
|
|
103
|
+
* Safe to call every frame. It returns before the GPU has answered — awaiting it is the one
|
|
104
|
+
* thing that would turn this class into the stall it exists to avoid.
|
|
105
|
+
*/
|
|
106
|
+
request(renderer: IRendererLike): void {
|
|
107
|
+
if (this.#released) throw new Error("GPUReadback cannot request after release.");
|
|
108
|
+
this.#frame += 1;
|
|
109
|
+
if (this.#pending) return;
|
|
110
|
+
if (this.#requestedFrame >= 0 && this.#frame - this.#requestedFrame < this.everyFrames) return;
|
|
111
|
+
const issuedFrame = this.#frame;
|
|
112
|
+
this.#requestedFrame = issuedFrame;
|
|
113
|
+
this.#pending = true;
|
|
114
|
+
this.#requests += 1;
|
|
115
|
+
renderer
|
|
116
|
+
.readback(this.#attribute)
|
|
117
|
+
.then((bytes) => this.#land(bytes, issuedFrame))
|
|
118
|
+
.catch(() => this.#fail());
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
#land(bytes: ArrayBuffer, issuedFrame: number): void {
|
|
122
|
+
this.#pending = false;
|
|
123
|
+
if (this.#released) return;
|
|
124
|
+
this.#data = new Float32Array(bytes);
|
|
125
|
+
this.#sampleFrame = issuedFrame;
|
|
126
|
+
this.#lands += 1;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
#fail(): void {
|
|
130
|
+
this.#pending = false;
|
|
131
|
+
if (this.#released) return;
|
|
132
|
+
this.#failures += 1;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Drops the attribute reference and the landed bytes. Further requests throw. */
|
|
136
|
+
dispose(): void {
|
|
137
|
+
if (this.#released) return;
|
|
138
|
+
this.#released = true;
|
|
139
|
+
this.#pending = false;
|
|
140
|
+
this.#attribute = undefined;
|
|
141
|
+
this.#data = undefined;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
import {
|
|
2
|
+
BufferAttribute,
|
|
3
|
+
BufferGeometry,
|
|
4
|
+
Group,
|
|
5
|
+
InstancedMesh,
|
|
6
|
+
Matrix3,
|
|
7
|
+
Matrix4,
|
|
8
|
+
Mesh,
|
|
9
|
+
type Object3D,
|
|
10
|
+
Vector3,
|
|
11
|
+
} from "three";
|
|
12
|
+
import { MeshBVH, SAH } from "three-mesh-bvh";
|
|
13
|
+
import * as upstreamWebGPU from "three-mesh-bvh/webgpu";
|
|
14
|
+
import { storage } from "three/tsl";
|
|
15
|
+
import { StorageBufferAttribute, type StorageBufferNode, type StructTypeNode } from "three/webgpu";
|
|
16
|
+
import type { IComputeDriven } from "./compute-driven.js";
|
|
17
|
+
import type { IRendererLike } from "./renderer.js";
|
|
18
|
+
|
|
19
|
+
/** Selects the meshes that become part of a GPU trace set. */
|
|
20
|
+
export interface IGPUSceneBVHOptions {
|
|
21
|
+
readonly include?: (object: Mesh) => boolean;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* A material range expressed in packed index elements, after the BVH leaf reorder.
|
|
26
|
+
*
|
|
27
|
+
* `start` and `count` address the uploaded index buffer, not the source geometry, so a single
|
|
28
|
+
* source material can appear as more than one range once the SAH sort interleaves its triangles.
|
|
29
|
+
*/
|
|
30
|
+
export interface IGPUSceneBVHMaterialGroup {
|
|
31
|
+
readonly count: number;
|
|
32
|
+
readonly materialIndex: number;
|
|
33
|
+
readonly start: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface IUpstreamWebGPU {
|
|
37
|
+
readonly bvhNodeStruct: StructTypeNode;
|
|
38
|
+
readonly rayStruct: StructTypeNode;
|
|
39
|
+
readonly bvhIntersectFirstHit: GPUSceneBVHTraceFunction;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface INodeBackings {
|
|
43
|
+
indices: StorageBufferNode<"uvec3"> | null;
|
|
44
|
+
nodes: StorageBufferNode<"struct"> | null;
|
|
45
|
+
normals: StorageBufferNode<"vec3"> | null;
|
|
46
|
+
positions: StorageBufferNode<"vec3"> | null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
interface IPackedScene {
|
|
50
|
+
readonly geometry: BufferGeometry;
|
|
51
|
+
readonly indices: Uint32Array;
|
|
52
|
+
readonly materialGroups: readonly IGPUSceneBVHMaterialGroup[];
|
|
53
|
+
readonly nodes: Uint32Array;
|
|
54
|
+
readonly normals: Float32Array;
|
|
55
|
+
readonly objectCount: number;
|
|
56
|
+
readonly positions: Float32Array;
|
|
57
|
+
readonly triangleCount: number;
|
|
58
|
+
readonly vertexCount: number;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
interface IBuildState {
|
|
62
|
+
indices: number[];
|
|
63
|
+
normals: number[];
|
|
64
|
+
objectCount: number;
|
|
65
|
+
positions: number[];
|
|
66
|
+
triangleCount: number;
|
|
67
|
+
triangleMaterials: number[];
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
interface IRange {
|
|
71
|
+
readonly count: number;
|
|
72
|
+
readonly materialIndex: number;
|
|
73
|
+
readonly start: number;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// three-mesh-bvh/webgpu ships no type declarations for bvhIntersectFirstHit, rayStruct or
|
|
77
|
+
// bvhNodeStruct. Shaping the module object once, here, is what keeps the cast out of every
|
|
78
|
+
// call site.
|
|
79
|
+
// quality-allow: upstream three-mesh-bvh/webgpu exports are untyped; shaped once behind IUpstreamWebGPU
|
|
80
|
+
const upstream = upstreamWebGPU as unknown as IUpstreamWebGPU;
|
|
81
|
+
const EMPTY_NODE_WORDS = 8;
|
|
82
|
+
const NODE_WORDS = 8;
|
|
83
|
+
const now = (): number => globalThis.performance?.now() ?? Date.now();
|
|
84
|
+
|
|
85
|
+
/** The upstream TSL ray query, exposed without renaming or wrapping it. */
|
|
86
|
+
export type GPUSceneBVHTraceFunction = (...args: readonly unknown[]) => unknown;
|
|
87
|
+
export const bvhIntersectFirstHit = upstream.bvhIntersectFirstHit;
|
|
88
|
+
export const rayStruct = upstream.rayStruct;
|
|
89
|
+
|
|
90
|
+
function storageAttribute<T extends ArrayBufferView>(
|
|
91
|
+
array: T,
|
|
92
|
+
itemSize: number,
|
|
93
|
+
): StorageBufferAttribute {
|
|
94
|
+
return new StorageBufferAttribute(array as never, itemSize);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function readStorage<T extends "vec3" | "uvec3">(
|
|
98
|
+
array: Float32Array | Uint32Array,
|
|
99
|
+
type: T,
|
|
100
|
+
itemSize: number,
|
|
101
|
+
): StorageBufferNode<T> {
|
|
102
|
+
return storage(storageAttribute(array, itemSize), type, array.length / itemSize).toReadOnly();
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function readNodeStorage(array: Uint32Array): StorageBufferNode<"struct"> {
|
|
106
|
+
return storage(
|
|
107
|
+
storageAttribute(array, NODE_WORDS),
|
|
108
|
+
upstream.bvhNodeStruct as never,
|
|
109
|
+
array.length / NODE_WORDS,
|
|
110
|
+
).toReadOnly() as StorageBufferNode<"struct">;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function disposeStorage(
|
|
114
|
+
node: StorageBufferNode<"struct"> | StorageBufferNode<"vec3"> | StorageBufferNode<"uvec3"> | null,
|
|
115
|
+
): void {
|
|
116
|
+
node?.value.dispose();
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function replaceStorage<
|
|
120
|
+
T extends StorageBufferNode<"struct"> | StorageBufferNode<"vec3"> | StorageBufferNode<"uvec3">,
|
|
121
|
+
>(current: T, next: T): void {
|
|
122
|
+
current.value.dispose();
|
|
123
|
+
current.value = next.value;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function emptyNodes(): Uint32Array {
|
|
127
|
+
const words = new Uint32Array(EMPTY_NODE_WORDS);
|
|
128
|
+
const bounds = new Float32Array(words.buffer);
|
|
129
|
+
bounds[0] = 0;
|
|
130
|
+
bounds[1] = 0;
|
|
131
|
+
bounds[2] = 0;
|
|
132
|
+
bounds[3] = 0;
|
|
133
|
+
bounds[4] = 0;
|
|
134
|
+
bounds[5] = 0;
|
|
135
|
+
words[6] = 0;
|
|
136
|
+
words[7] = 0xffff0000;
|
|
137
|
+
return words;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function rangesFor(geometry: BufferGeometry, indexCount: number): readonly IRange[] {
|
|
141
|
+
const drawStart = Math.min(indexCount, Math.max(0, Math.floor(geometry.drawRange.start)));
|
|
142
|
+
const drawCount = Number.isFinite(geometry.drawRange.count)
|
|
143
|
+
? Math.max(0, Math.floor(geometry.drawRange.count))
|
|
144
|
+
: indexCount - drawStart;
|
|
145
|
+
const drawEnd = Math.min(indexCount, drawStart + drawCount);
|
|
146
|
+
const groups = geometry.groups;
|
|
147
|
+
if (groups.length === 0) {
|
|
148
|
+
return [
|
|
149
|
+
{
|
|
150
|
+
count: Math.max(0, drawEnd - drawStart) - ((drawEnd - drawStart) % 3),
|
|
151
|
+
materialIndex: 0,
|
|
152
|
+
start: drawStart,
|
|
153
|
+
},
|
|
154
|
+
];
|
|
155
|
+
}
|
|
156
|
+
return groups.flatMap((group) => {
|
|
157
|
+
const start = Math.max(drawStart, Math.floor(group.start));
|
|
158
|
+
const requestedCount = Number.isFinite(group.count)
|
|
159
|
+
? Math.max(0, Math.floor(group.count))
|
|
160
|
+
: indexCount - start;
|
|
161
|
+
const count = Math.min(drawEnd, start + requestedCount) - start;
|
|
162
|
+
const alignedCount = count - (count % 3);
|
|
163
|
+
return alignedCount > 0
|
|
164
|
+
? [{ count: alignedCount, materialIndex: group.materialIndex ?? 0, start }]
|
|
165
|
+
: [];
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function matrixFor(mesh: Mesh, instance: number, target: Matrix4): Matrix4 {
|
|
170
|
+
if (mesh instanceof InstancedMesh) {
|
|
171
|
+
mesh.getMatrixAt(instance, target);
|
|
172
|
+
return target.premultiply(mesh.matrixWorld);
|
|
173
|
+
}
|
|
174
|
+
return target.copy(mesh.matrixWorld);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function appendVertices(
|
|
178
|
+
mesh: Mesh,
|
|
179
|
+
position: ReturnType<BufferGeometry["getAttribute"]>,
|
|
180
|
+
normal: ReturnType<BufferGeometry["getAttribute"]>,
|
|
181
|
+
matrix: Matrix4,
|
|
182
|
+
normalMatrix: Matrix3,
|
|
183
|
+
state: IBuildState,
|
|
184
|
+
): void {
|
|
185
|
+
const localPosition = new Vector3();
|
|
186
|
+
const worldPosition = new Vector3();
|
|
187
|
+
const localNormal = new Vector3();
|
|
188
|
+
const worldNormal = new Vector3();
|
|
189
|
+
for (let vertex = 0; vertex < position.count; vertex += 1) {
|
|
190
|
+
mesh.getVertexPosition(vertex, localPosition);
|
|
191
|
+
worldPosition.copy(localPosition).applyMatrix4(matrix);
|
|
192
|
+
state.positions.push(worldPosition.x, worldPosition.y, worldPosition.z);
|
|
193
|
+
if (normal === undefined) localNormal.set(0, 1, 0);
|
|
194
|
+
else localNormal.set(normal.getX(vertex), normal.getY(vertex), normal.getZ(vertex));
|
|
195
|
+
worldNormal.copy(localNormal).applyNormalMatrix(normalMatrix).normalize();
|
|
196
|
+
state.normals.push(worldNormal.x, worldNormal.y, worldNormal.z);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function padVec3(array: Float32Array): Float32Array {
|
|
201
|
+
const padded = new Float32Array((array.length / 3) * 4);
|
|
202
|
+
for (let source = 0, target = 0; source < array.length; source += 3, target += 4) {
|
|
203
|
+
padded[target] = array[source] ?? 0;
|
|
204
|
+
padded[target + 1] = array[source + 1] ?? 0;
|
|
205
|
+
padded[target + 2] = array[source + 2] ?? 0;
|
|
206
|
+
}
|
|
207
|
+
return padded;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function appendTriangles(
|
|
211
|
+
index: ReturnType<BufferGeometry["getIndex"]>,
|
|
212
|
+
ranges: readonly IRange[],
|
|
213
|
+
vertexOffset: number,
|
|
214
|
+
state: IBuildState,
|
|
215
|
+
): void {
|
|
216
|
+
for (const range of ranges) {
|
|
217
|
+
for (let element = range.start; element < range.start + range.count; element += 1) {
|
|
218
|
+
const sourceIndex = index === null ? element : index.getX(element);
|
|
219
|
+
state.indices.push(vertexOffset + sourceIndex);
|
|
220
|
+
}
|
|
221
|
+
const triangles = range.count / 3;
|
|
222
|
+
for (let triangle = 0; triangle < triangles; triangle += 1) {
|
|
223
|
+
state.triangleMaterials.push(range.materialIndex);
|
|
224
|
+
}
|
|
225
|
+
state.triangleCount += triangles;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function appendMesh(mesh: Mesh, state: IBuildState): void {
|
|
230
|
+
const position = mesh.geometry.getAttribute("position");
|
|
231
|
+
if (position === undefined || position.count === 0) return;
|
|
232
|
+
const index = mesh.geometry.getIndex();
|
|
233
|
+
const ranges = rangesFor(mesh.geometry, index?.count ?? position.count);
|
|
234
|
+
if (ranges.length === 0) return;
|
|
235
|
+
state.objectCount += 1;
|
|
236
|
+
const instances = mesh instanceof InstancedMesh ? Math.max(0, mesh.count) : 1;
|
|
237
|
+
const matrix = new Matrix4();
|
|
238
|
+
const normalMatrix = new Matrix3();
|
|
239
|
+
const normal = mesh.geometry.getAttribute("normal");
|
|
240
|
+
for (let instance = 0; instance < instances; instance += 1) {
|
|
241
|
+
const vertexOffset = state.positions.length / 3;
|
|
242
|
+
matrixFor(mesh, instance, matrix);
|
|
243
|
+
normalMatrix.getNormalMatrix(matrix);
|
|
244
|
+
appendVertices(mesh, position, normal, matrix, normalMatrix, state);
|
|
245
|
+
appendTriangles(index, ranges, vertexOffset, state);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Run-length encode a per-triangle material assignment into packed index element ranges. */
|
|
250
|
+
function materialGroupsFor(materials: Uint32Array): IGPUSceneBVHMaterialGroup[] {
|
|
251
|
+
const groups: IGPUSceneBVHMaterialGroup[] = [];
|
|
252
|
+
let runStart = 0;
|
|
253
|
+
for (let triangle = 1; triangle <= materials.length; triangle += 1) {
|
|
254
|
+
if (triangle < materials.length && materials[triangle] === materials[runStart]) continue;
|
|
255
|
+
groups.push({
|
|
256
|
+
count: (triangle - runStart) * 3,
|
|
257
|
+
materialIndex: materials[runStart] ?? 0,
|
|
258
|
+
start: runStart * 3,
|
|
259
|
+
});
|
|
260
|
+
runStart = triangle;
|
|
261
|
+
}
|
|
262
|
+
return groups;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Materialise the packed index buffer in BVH leaf order and permute the material assignment with
|
|
267
|
+
* it, so a leaf's triangle offset and the material ranges address the same layout.
|
|
268
|
+
*/
|
|
269
|
+
function permuteToLeafOrder(
|
|
270
|
+
bvh: MeshBVH,
|
|
271
|
+
sourceIndices: Uint32Array,
|
|
272
|
+
sourceMaterials: readonly number[],
|
|
273
|
+
): { indices: Uint32Array; materialGroups: IGPUSceneBVHMaterialGroup[] } {
|
|
274
|
+
const triangleCount = sourceIndices.length / 3;
|
|
275
|
+
const indices = new Uint32Array(sourceIndices.length);
|
|
276
|
+
const materials = new Uint32Array(triangleCount);
|
|
277
|
+
for (let slot = 0; slot < triangleCount; slot += 1) {
|
|
278
|
+
const triangle = bvh.resolveTriangleIndex(slot);
|
|
279
|
+
indices[slot * 3] = sourceIndices[triangle * 3] ?? 0;
|
|
280
|
+
indices[slot * 3 + 1] = sourceIndices[triangle * 3 + 1] ?? 0;
|
|
281
|
+
indices[slot * 3 + 2] = sourceIndices[triangle * 3 + 2] ?? 0;
|
|
282
|
+
materials[slot] = sourceMaterials[triangle] ?? 0;
|
|
283
|
+
}
|
|
284
|
+
return { indices, materialGroups: materialGroupsFor(materials) };
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function packScene(scene: Object3D, include: (object: Mesh) => boolean): IPackedScene {
|
|
288
|
+
scene.updateMatrixWorld(true);
|
|
289
|
+
const state: IBuildState = {
|
|
290
|
+
indices: [],
|
|
291
|
+
normals: [],
|
|
292
|
+
objectCount: 0,
|
|
293
|
+
positions: [],
|
|
294
|
+
triangleCount: 0,
|
|
295
|
+
triangleMaterials: [],
|
|
296
|
+
};
|
|
297
|
+
scene.traverse((candidate) => {
|
|
298
|
+
if (!(candidate instanceof Mesh) || candidate.visible === false || !include(candidate)) return;
|
|
299
|
+
appendMesh(candidate, state);
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
const tightPositions = new Float32Array(
|
|
303
|
+
state.positions.length === 0 ? [0, 0, 0] : state.positions,
|
|
304
|
+
);
|
|
305
|
+
const tightNormals = new Float32Array(state.normals.length === 0 ? [0, 1, 0] : state.normals);
|
|
306
|
+
const positions = padVec3(tightPositions);
|
|
307
|
+
const normals = padVec3(tightNormals);
|
|
308
|
+
const sourceIndices = new Uint32Array(state.indices.length === 0 ? [0, 0, 0] : state.indices);
|
|
309
|
+
const geometry = new BufferGeometry();
|
|
310
|
+
geometry.setAttribute("position", new BufferAttribute(tightPositions, 3));
|
|
311
|
+
geometry.setIndex(new BufferAttribute(sourceIndices, 1));
|
|
312
|
+
|
|
313
|
+
let nodes = emptyNodes();
|
|
314
|
+
let indices: Uint32Array = sourceIndices;
|
|
315
|
+
let materialGroups: readonly IGPUSceneBVHMaterialGroup[] = [];
|
|
316
|
+
if (state.indices.length > 0) {
|
|
317
|
+
// Indirect keeps `geometry.index` in source order, so the material assignment collected above
|
|
318
|
+
// still lines up with it; the leaf order is then applied to both at once below.
|
|
319
|
+
const bvh = new MeshBVH(geometry, {
|
|
320
|
+
indirect: true,
|
|
321
|
+
strategy: SAH,
|
|
322
|
+
targetLeafSize: 10,
|
|
323
|
+
verbose: false,
|
|
324
|
+
});
|
|
325
|
+
const serialized = MeshBVH.serialize(bvh, { cloneBuffers: false });
|
|
326
|
+
const root = serialized.roots[0];
|
|
327
|
+
if (root === undefined) throw new Error("GPUSceneBVH could not serialize its root node.");
|
|
328
|
+
nodes = new Uint32Array(root);
|
|
329
|
+
const permuted = permuteToLeafOrder(bvh, sourceIndices, state.triangleMaterials);
|
|
330
|
+
indices = permuted.indices;
|
|
331
|
+
materialGroups = permuted.materialGroups;
|
|
332
|
+
}
|
|
333
|
+
return {
|
|
334
|
+
geometry,
|
|
335
|
+
indices,
|
|
336
|
+
materialGroups,
|
|
337
|
+
nodes,
|
|
338
|
+
normals,
|
|
339
|
+
objectCount: state.objectCount,
|
|
340
|
+
positions,
|
|
341
|
+
triangleCount: state.triangleCount,
|
|
342
|
+
vertexCount: tightPositions.length / 3,
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* Snapshot selected scene meshes into world-space storage buffers for an upstream TSL BVH query.
|
|
348
|
+
*
|
|
349
|
+
* This class owns packing, residency, and release. It deliberately does not own the ray query or
|
|
350
|
+
* a rendered effect: a game imports the exact upstream `bvhIntersectFirstHit` and `rayStruct`
|
|
351
|
+
* exports through the core entry point and uses these four named nodes in its own `src/render/`
|
|
352
|
+
* kernel. The snapshot is static until `rebuild()`.
|
|
353
|
+
*/
|
|
354
|
+
export class GPUSceneBVH extends Group implements IComputeDriven {
|
|
355
|
+
#backings: INodeBackings = {
|
|
356
|
+
indices: readStorage(new Uint32Array([0, 0, 0]), "uvec3", 3),
|
|
357
|
+
nodes: readNodeStorage(emptyNodes()),
|
|
358
|
+
normals: readStorage(new Float32Array([0, 1, 0, 0]), "vec3", 4),
|
|
359
|
+
positions: readStorage(new Float32Array([0, 0, 0, 0]), "vec3", 4),
|
|
360
|
+
};
|
|
361
|
+
readonly indices: StorageBufferNode<"uvec3">;
|
|
362
|
+
readonly nodes: StorageBufferNode<"struct">;
|
|
363
|
+
readonly normals: StorageBufferNode<"vec3">;
|
|
364
|
+
readonly positions: StorageBufferNode<"vec3">;
|
|
365
|
+
readonly warmupNodes: readonly unknown[] = [];
|
|
366
|
+
#buildMs = 0;
|
|
367
|
+
#include: (object: Mesh) => boolean;
|
|
368
|
+
#materialGroups: readonly IGPUSceneBVHMaterialGroup[] = [];
|
|
369
|
+
#objectCount = 0;
|
|
370
|
+
#packedGeometry: BufferGeometry | undefined;
|
|
371
|
+
#positions = 0;
|
|
372
|
+
#released = false;
|
|
373
|
+
#scene: Object3D;
|
|
374
|
+
#triangleCount = 0;
|
|
375
|
+
|
|
376
|
+
constructor(scene: Object3D, options: IGPUSceneBVHOptions = {}) {
|
|
377
|
+
super();
|
|
378
|
+
if (scene?.isObject3D !== true) throw new Error("GPUSceneBVH.scene must be an Object3D.");
|
|
379
|
+
if (options.include !== undefined && typeof options.include !== "function") {
|
|
380
|
+
throw new Error("GPUSceneBVH.include must be a function when provided.");
|
|
381
|
+
}
|
|
382
|
+
this.#scene = scene;
|
|
383
|
+
this.#include = options.include ?? (() => true);
|
|
384
|
+
this.nodes = this.#backings.nodes as StorageBufferNode<"struct">;
|
|
385
|
+
this.positions = this.#backings.positions as StorageBufferNode<"vec3">;
|
|
386
|
+
this.indices = this.#backings.indices as StorageBufferNode<"uvec3">;
|
|
387
|
+
this.normals = this.#backings.normals as StorageBufferNode<"vec3">;
|
|
388
|
+
this.addEventListener("removed", this.#onRemoved);
|
|
389
|
+
this.rebuild();
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
get buildMs(): number {
|
|
393
|
+
return this.#buildMs;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
get materialGroups(): readonly IGPUSceneBVHMaterialGroup[] {
|
|
397
|
+
return this.#materialGroups;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
get objectCount(): number {
|
|
401
|
+
return this.#objectCount;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
get released(): boolean {
|
|
405
|
+
return this.#released;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
get triangleCount(): number {
|
|
409
|
+
return this.#triangleCount;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
get vertexCount(): number {
|
|
413
|
+
return this.#positions;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
attachRenderer(_renderer: IRendererLike): void {
|
|
417
|
+
if (this.#released) throw new Error("GPUSceneBVH cannot be attached after release.");
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
process(_renderer: IRendererLike): void {
|
|
421
|
+
// The snapshot is static by default. A game changes it only by calling rebuild().
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/** Repack the selected scene objects and replace the GPU buffers behind the stable node handles. */
|
|
425
|
+
rebuild(): void {
|
|
426
|
+
if (this.#released) throw new Error("GPUSceneBVH cannot rebuild after release.");
|
|
427
|
+
const started = now();
|
|
428
|
+
const packed = packScene(this.#scene, this.#include);
|
|
429
|
+
const nextNodes = readNodeStorage(packed.nodes);
|
|
430
|
+
const nextPositions = readStorage(packed.positions, "vec3", 4);
|
|
431
|
+
const nextIndices = readStorage(packed.indices, "uvec3", 3);
|
|
432
|
+
const nextNormals = readStorage(packed.normals, "vec3", 4);
|
|
433
|
+
replaceStorage(this.#backings.nodes as StorageBufferNode<"struct">, nextNodes);
|
|
434
|
+
replaceStorage(this.#backings.positions as StorageBufferNode<"vec3">, nextPositions);
|
|
435
|
+
replaceStorage(this.#backings.indices as StorageBufferNode<"uvec3">, nextIndices);
|
|
436
|
+
replaceStorage(this.#backings.normals as StorageBufferNode<"vec3">, nextNormals);
|
|
437
|
+
this.#packedGeometry?.dispose();
|
|
438
|
+
this.#packedGeometry = packed.geometry;
|
|
439
|
+
this.#materialGroups = packed.materialGroups;
|
|
440
|
+
this.#objectCount = packed.objectCount;
|
|
441
|
+
this.#positions = packed.vertexCount;
|
|
442
|
+
this.#triangleCount = packed.triangleCount;
|
|
443
|
+
this.#buildMs = now() - started;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/** Dispose every storage attribute owned by this snapshot. Safe to call more than once. */
|
|
447
|
+
detach(): void {
|
|
448
|
+
if (this.#released) return;
|
|
449
|
+
this.removeEventListener("removed", this.#onRemoved);
|
|
450
|
+
disposeStorage(this.#backings.nodes);
|
|
451
|
+
disposeStorage(this.#backings.positions);
|
|
452
|
+
disposeStorage(this.#backings.indices);
|
|
453
|
+
disposeStorage(this.#backings.normals);
|
|
454
|
+
this.#backings.nodes = null;
|
|
455
|
+
this.#backings.positions = null;
|
|
456
|
+
this.#backings.indices = null;
|
|
457
|
+
this.#backings.normals = null;
|
|
458
|
+
this.#packedGeometry?.dispose();
|
|
459
|
+
this.#packedGeometry = undefined;
|
|
460
|
+
this.#released = true;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
#onRemoved = (): void => this.detach();
|
|
464
|
+
}
|