@bendyline/molen-client 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/NOTICE.md +11 -0
- package/README.md +95 -0
- package/dist/aircraft.d.mts +23 -0
- package/dist/aircraft.mjs +99 -0
- package/dist/camera-track.d.mts +20 -0
- package/dist/camera-track.mjs +102 -0
- package/dist/index.d.mts +1000 -0
- package/dist/index.mjs +4579 -0
- package/dist/math-ev_jEkRe.mjs +42 -0
- package/dist/model-signals-DVlLyP-w.d.mts +17 -0
- package/dist/model-signals-Gw1COJfo.mjs +53 -0
- package/dist/renderer-B3pd4N-J.d.mts +446 -0
- package/dist/vehicle-interior-0o-8QV_-.d.mts +31 -0
- package/dist/vehicle-interior-DZT0HmWC.mjs +12 -0
- package/dist/vehicles.d.mts +17 -0
- package/dist/vehicles.mjs +174 -0
- package/dist/vite.d.mts +24 -0
- package/dist/vite.mjs +57 -0
- package/dist/webgpu-driver-DXsRuz8j.mjs +75 -0
- package/dist/webgpu-frame-timer-Xnuq1Hld.mjs +97 -0
- package/dist/webgpu-scene-optimizer-D6e9ZJQM.mjs +319 -0
- package/package.json +85 -0
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { t as createVehicleInteriorVisual } from "./vehicle-interior-DZT0HmWC.mjs";
|
|
2
|
+
import * as THREE from "three";
|
|
3
|
+
import { mergeGeometries } from "three/addons/utils/BufferGeometryUtils.js";
|
|
4
|
+
//#region src/vehicle-camera.ts
|
|
5
|
+
/** Seat-space cockpit and collision-shortened chase views for any vehicle host. */
|
|
6
|
+
function vehicleCameraPose(transform, spec, options) {
|
|
7
|
+
const rotation = new THREE.Quaternion().fromArray(transform.rot);
|
|
8
|
+
const yaw = options.lookYaw ?? 0, pitch = options.lookPitch ?? 0;
|
|
9
|
+
const direction = new THREE.Vector3(-Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), Math.cos(yaw) * Math.cos(pitch)).applyQuaternion(rotation);
|
|
10
|
+
const origin = new THREE.Vector3().fromArray(transform.pos);
|
|
11
|
+
let position = new THREE.Vector3().fromArray(spec.driverEye).applyQuaternion(rotation).add(origin);
|
|
12
|
+
let target = position.clone().add(direction);
|
|
13
|
+
if (options.view === "chase") {
|
|
14
|
+
target = origin.clone().add(new THREE.Vector3(0, 1.1, 0));
|
|
15
|
+
position = target.clone().addScaledVector(direction, -spec.length - 3).add(new THREE.Vector3(0, 2.8, 0));
|
|
16
|
+
const distance = target.distanceTo(position), hit = options.obstructionDistance?.(target.toArray(), position.toArray());
|
|
17
|
+
if (hit !== void 0 && hit < distance) {
|
|
18
|
+
const offset = position.clone().sub(target).normalize();
|
|
19
|
+
position.copy(target).addScaledVector(offset, Math.max(.2, hit - .25));
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
const forward = target.clone().sub(position).normalize();
|
|
23
|
+
return {
|
|
24
|
+
position: position.toArray(),
|
|
25
|
+
lookAt: target.toArray(),
|
|
26
|
+
yaw: Math.atan2(forward.z, forward.x),
|
|
27
|
+
pitch: Math.asin(forward.y)
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
//#endregion
|
|
31
|
+
//#region src/vehicles.ts
|
|
32
|
+
/** Bind a loaded entity GLB to generic wheel/steering animation using external node names. */
|
|
33
|
+
function createVehicleVisual(model, vehicle) {
|
|
34
|
+
const interior = vehicle.visual.interior === void 0 ? void 0 : createVehicleInteriorVisual(model, vehicle.visual.interior);
|
|
35
|
+
const nodes = /* @__PURE__ */ new Map();
|
|
36
|
+
const frontWheels = new Set(vehicle.visual.frontWheelNodes);
|
|
37
|
+
const wheels = [];
|
|
38
|
+
let steeringWheel;
|
|
39
|
+
const color = new THREE.Color(vehicle.color);
|
|
40
|
+
model.traverse((object) => {
|
|
41
|
+
object.userData.vehicleGeometry = true;
|
|
42
|
+
const named = nodes.get(object.name) ?? [];
|
|
43
|
+
named.push(object);
|
|
44
|
+
nodes.set(object.name, named);
|
|
45
|
+
if (object instanceof THREE.Mesh) {
|
|
46
|
+
object.castShadow = true;
|
|
47
|
+
object.receiveShadow = true;
|
|
48
|
+
object.material = (Array.isArray(object.material) ? object.material : [object.material]).map((source) => {
|
|
49
|
+
const material = source.clone();
|
|
50
|
+
if (source.name === vehicle.visual.paintMaterial && "color" in material) material.color.copy(color);
|
|
51
|
+
return material;
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
for (const name of vehicle.visual.wheelNodes) for (const node of nodes.get(name) ?? []) wheels.push({
|
|
56
|
+
node,
|
|
57
|
+
front: frontWheels.has(name),
|
|
58
|
+
baseY: node.rotation.y
|
|
59
|
+
});
|
|
60
|
+
if (vehicle.visual.steeringWheelNode !== void 0) steeringWheel = nodes.get(vehicle.visual.steeringWheelNode)?.[0];
|
|
61
|
+
return {
|
|
62
|
+
object: model,
|
|
63
|
+
interior,
|
|
64
|
+
update(steer, angle, signals) {
|
|
65
|
+
for (const wheel of wheels) {
|
|
66
|
+
wheel.node.rotation.y = wheel.baseY + (wheel.front ? -steer : 0);
|
|
67
|
+
const spinner = wheel.node.children[0] ?? wheel.node;
|
|
68
|
+
spinner.rotation.x = angle;
|
|
69
|
+
}
|
|
70
|
+
if (interior === void 0 && steeringWheel !== void 0) steeringWheel.rotation.z = steer * 2.5;
|
|
71
|
+
interior?.update({
|
|
72
|
+
steering: steer,
|
|
73
|
+
wheelAngle: angle,
|
|
74
|
+
...signals
|
|
75
|
+
});
|
|
76
|
+
},
|
|
77
|
+
dispose() {
|
|
78
|
+
const geometries = /* @__PURE__ */ new Set();
|
|
79
|
+
const materials = /* @__PURE__ */ new Set();
|
|
80
|
+
model.traverse((object) => {
|
|
81
|
+
if (!(object instanceof THREE.Mesh)) return;
|
|
82
|
+
geometries.add(object.geometry);
|
|
83
|
+
for (const material of Array.isArray(object.material) ? object.material : [object.material]) materials.add(material);
|
|
84
|
+
});
|
|
85
|
+
for (const geometry of geometries) geometry.dispose();
|
|
86
|
+
for (const material of materials) material.dispose();
|
|
87
|
+
model.removeFromParent();
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
const parkedMaterial = new THREE.MeshStandardMaterial({
|
|
92
|
+
vertexColors: true,
|
|
93
|
+
roughness: .55,
|
|
94
|
+
metalness: .12
|
|
95
|
+
});
|
|
96
|
+
const parkedTemplates = /* @__PURE__ */ new Map();
|
|
97
|
+
function coloredBox(x, y, z, width, height, length, color) {
|
|
98
|
+
const geometry = new THREE.BoxGeometry(width, height, length).translate(x, y, z).toNonIndexed();
|
|
99
|
+
geometry.deleteAttribute("uv");
|
|
100
|
+
const tint = new THREE.Color(color);
|
|
101
|
+
const colors = new Float32Array(geometry.getAttribute("position").count * 3);
|
|
102
|
+
for (let i = 0; i < colors.length; i += 3) {
|
|
103
|
+
colors[i] = tint.r;
|
|
104
|
+
colors[i + 1] = tint.g;
|
|
105
|
+
colors[i + 2] = tint.b;
|
|
106
|
+
}
|
|
107
|
+
geometry.setAttribute("color", new THREE.BufferAttribute(colors, 3));
|
|
108
|
+
return geometry;
|
|
109
|
+
}
|
|
110
|
+
/** Generic dimension-driven proxy used only for large dormant parking batches. */
|
|
111
|
+
function parkedTemplate(spec, color) {
|
|
112
|
+
const key = `${spec.width}:${spec.length}:${spec.height}:${spec.wheelbase}:${color}`;
|
|
113
|
+
const cached = parkedTemplates.get(key);
|
|
114
|
+
if (cached !== void 0) return cached;
|
|
115
|
+
const parts = [coloredBox(0, spec.height * .34, 0, spec.width, spec.height * .48, spec.length, color), coloredBox(0, spec.height * .72, -spec.length * .06, spec.width * .82, spec.height * .42, spec.length * .52, "#526b78")];
|
|
116
|
+
for (const x of [-spec.wheelTrack / 2, spec.wheelTrack / 2]) for (const z of [-spec.wheelbase / 2, spec.wheelbase / 2]) {
|
|
117
|
+
const wheel = new THREE.CylinderGeometry(spec.wheelRadius, spec.wheelRadius, spec.width * .1, 8);
|
|
118
|
+
wheel.rotateZ(Math.PI / 2);
|
|
119
|
+
wheel.translate(x, spec.wheelRadius, z);
|
|
120
|
+
const wheelGeometry = wheel.toNonIndexed();
|
|
121
|
+
wheelGeometry.deleteAttribute("uv");
|
|
122
|
+
const charcoal = new THREE.Color("#20242a");
|
|
123
|
+
const colors = new Float32Array(wheelGeometry.getAttribute("position").count * 3);
|
|
124
|
+
for (let i = 0; i < colors.length; i += 3) {
|
|
125
|
+
colors[i] = charcoal.r;
|
|
126
|
+
colors[i + 1] = charcoal.g;
|
|
127
|
+
colors[i + 2] = charcoal.b;
|
|
128
|
+
}
|
|
129
|
+
wheelGeometry.setAttribute("color", new THREE.BufferAttribute(colors, 3));
|
|
130
|
+
parts.push(wheelGeometry);
|
|
131
|
+
wheel.dispose();
|
|
132
|
+
}
|
|
133
|
+
const geometry = mergeGeometries(parts);
|
|
134
|
+
for (const part of parts) part.dispose();
|
|
135
|
+
geometry.computeBoundingBox();
|
|
136
|
+
geometry.computeBoundingSphere();
|
|
137
|
+
parkedTemplates.set(key, geometry);
|
|
138
|
+
return geometry;
|
|
139
|
+
}
|
|
140
|
+
/** Shared proxy geometry and instance batches for dormant terrain-owned entities. */
|
|
141
|
+
function createParkedVehicleBatch(placements, origin = [0, 0]) {
|
|
142
|
+
const group = new THREE.Group();
|
|
143
|
+
group.name = "surface:parked-cars";
|
|
144
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
145
|
+
for (const placement of placements) {
|
|
146
|
+
const key = `${placement.kind}:${placement.color}`;
|
|
147
|
+
const list = buckets.get(key) ?? [];
|
|
148
|
+
list.push(placement);
|
|
149
|
+
buckets.set(key, list);
|
|
150
|
+
}
|
|
151
|
+
const matrix = new THREE.Matrix4();
|
|
152
|
+
const rotation = new THREE.Quaternion();
|
|
153
|
+
const position = new THREE.Vector3();
|
|
154
|
+
const scale = new THREE.Vector3(1, 1, 1);
|
|
155
|
+
for (const list of buckets.values()) {
|
|
156
|
+
const first = list[0];
|
|
157
|
+
const mesh = new THREE.InstancedMesh(parkedTemplate(first.spec, first.color), parkedMaterial, list.length);
|
|
158
|
+
mesh.name = `vehicle:${first.kind}`;
|
|
159
|
+
mesh.userData.vehicleIds = list.map((placement) => placement.id);
|
|
160
|
+
mesh.userData.terrainOwnedInstances = true;
|
|
161
|
+
mesh.castShadow = true;
|
|
162
|
+
mesh.receiveShadow = true;
|
|
163
|
+
list.forEach((placement, index) => {
|
|
164
|
+
position.set(placement.position[0] - origin[0], placement.position[1], placement.position[2] - origin[1]);
|
|
165
|
+
rotation.setFromEuler(new THREE.Euler(placement.pitch ?? 0, placement.yaw, placement.roll ?? 0, "YXZ"));
|
|
166
|
+
mesh.setMatrixAt(index, matrix.compose(position, rotation, scale));
|
|
167
|
+
});
|
|
168
|
+
mesh.computeBoundingSphere();
|
|
169
|
+
group.add(mesh);
|
|
170
|
+
}
|
|
171
|
+
return group;
|
|
172
|
+
}
|
|
173
|
+
//#endregion
|
|
174
|
+
export { createParkedVehicleBatch, createVehicleInteriorVisual, createVehicleVisual, vehicleCameraPose };
|
package/dist/vite.d.mts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
//#region src/vite.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Erase the types from a TypeScript scene script, preserving every line and column. `filename`
|
|
4
|
+
* is only used in error messages.
|
|
5
|
+
*/
|
|
6
|
+
declare function stripScriptTypes(source: string, filename: string): string;
|
|
7
|
+
/** The subset of Vite's plugin shape this uses; structural, so no dependency on vite. */
|
|
8
|
+
interface MolenScriptsPlugin {
|
|
9
|
+
name: string;
|
|
10
|
+
enforce: "pre";
|
|
11
|
+
load(id: string): Promise<string | undefined>;
|
|
12
|
+
}
|
|
13
|
+
interface MolenScriptsOptions {
|
|
14
|
+
/** Restrict stripping to matching paths (default: any `.ts` imported with `?raw`). */
|
|
15
|
+
include?: RegExp;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Vite plugin: serve `*.ts?raw` imports as type-stripped JavaScript, so a browser host can glob
|
|
19
|
+
* its scene scripts (`import.meta.glob('../scripts/*.ts', { query: '?raw' })`) and hand the
|
|
20
|
+
* strings to `inlineScriptSources` exactly as it did with `.js`.
|
|
21
|
+
*/
|
|
22
|
+
declare function molenScripts(options?: MolenScriptsOptions): MolenScriptsPlugin;
|
|
23
|
+
//#endregion
|
|
24
|
+
export { MolenScriptsOptions, MolenScriptsPlugin, molenScripts, stripScriptTypes };
|
package/dist/vite.mjs
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import * as nodeModule from "node:module";
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
//#region src/vite.ts
|
|
4
|
+
/**
|
|
5
|
+
* Node reports `stripTypeScriptTypes` as experimental on first use. The warning is about Node's
|
|
6
|
+
* API, not about anything the user did, and it would print on every scene load — so it is
|
|
7
|
+
* silenced narrowly (this exact warning, only around the call) rather than globally.
|
|
8
|
+
*/
|
|
9
|
+
function withoutExperimentalWarning(fn) {
|
|
10
|
+
const original = process.emitWarning;
|
|
11
|
+
process.emitWarning = ((warning, ...rest) => {
|
|
12
|
+
const name = warning instanceof Error ? warning.name : rest[0];
|
|
13
|
+
const text = warning instanceof Error ? warning.message : warning;
|
|
14
|
+
if (name === "ExperimentalWarning" && text.includes("stripTypeScriptTypes")) return;
|
|
15
|
+
original.call(process, warning, ...rest);
|
|
16
|
+
});
|
|
17
|
+
try {
|
|
18
|
+
return fn();
|
|
19
|
+
} finally {
|
|
20
|
+
process.emitWarning = original;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Erase the types from a TypeScript scene script, preserving every line and column. `filename`
|
|
25
|
+
* is only used in error messages.
|
|
26
|
+
*/
|
|
27
|
+
function stripScriptTypes(source, filename) {
|
|
28
|
+
const strip = nodeModule.stripTypeScriptTypes;
|
|
29
|
+
if (strip === void 0) throw new Error(`cannot load TypeScript scene script "${filename}": this Node (${process.version}) has no module.stripTypeScriptTypes — upgrade to Node 22.13+, or author the script as .js`);
|
|
30
|
+
try {
|
|
31
|
+
return withoutExperimentalWarning(() => strip(source, { mode: "strip" }));
|
|
32
|
+
} catch (error) {
|
|
33
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
34
|
+
throw new Error(`cannot erase types from "${filename}": ${message} (scene scripts must use erasable syntax only — no enums, namespaces, or parameter properties)`);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Vite plugin: serve `*.ts?raw` imports as type-stripped JavaScript, so a browser host can glob
|
|
39
|
+
* its scene scripts (`import.meta.glob('../scripts/*.ts', { query: '?raw' })`) and hand the
|
|
40
|
+
* strings to `inlineScriptSources` exactly as it did with `.js`.
|
|
41
|
+
*/
|
|
42
|
+
function molenScripts(options) {
|
|
43
|
+
return {
|
|
44
|
+
name: "molen:scene-scripts",
|
|
45
|
+
enforce: "pre",
|
|
46
|
+
async load(id) {
|
|
47
|
+
const [file, query] = id.split("?");
|
|
48
|
+
if (file === void 0 || query === void 0) return void 0;
|
|
49
|
+
if (!query.split("&").includes("raw") || !file.endsWith(".ts")) return void 0;
|
|
50
|
+
if (options?.include !== void 0 && !options.include.test(file)) return void 0;
|
|
51
|
+
const source = await readFile(file, "utf8");
|
|
52
|
+
return `export default ${JSON.stringify(stripScriptTypes(source, file))};`;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
//#endregion
|
|
57
|
+
export { molenScripts, stripScriptTypes };
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { n as installWebGpuTimestampGuard } from "./webgpu-frame-timer-Xnuq1Hld.mjs";
|
|
2
|
+
import { CanvasTarget, WebGPUBackend, WebGPURenderer } from "three/webgpu";
|
|
3
|
+
//#region src/three/webgpu-depth-bias.ts
|
|
4
|
+
const guardedBackends = /* @__PURE__ */ new WeakSet();
|
|
5
|
+
/**
|
|
6
|
+
* Three r184 reverses WebGPU depth comparisons but copies polygon offsets unchanged into the
|
|
7
|
+
* pipeline descriptor. Negative offsets then push water/decals behind the surface they cover.
|
|
8
|
+
* The descriptor is built synchronously, even for compileAsync; restore the authored material
|
|
9
|
+
* immediately so cache keys, shared materials and later draws retain their original values.
|
|
10
|
+
*/
|
|
11
|
+
function installWebGpuDepthBiasGuard(renderer) {
|
|
12
|
+
if (!renderer.reversedDepthBuffer) return;
|
|
13
|
+
const backend = renderer.backend;
|
|
14
|
+
if (guardedBackends.has(backend)) return;
|
|
15
|
+
guardedBackends.add(backend);
|
|
16
|
+
const createPipeline = backend.createRenderPipeline;
|
|
17
|
+
backend.createRenderPipeline = (object, promises) => {
|
|
18
|
+
const material = object.material;
|
|
19
|
+
if (!material.polygonOffset) {
|
|
20
|
+
createPipeline.call(backend, object, promises);
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
const factor = material.polygonOffsetFactor;
|
|
24
|
+
const units = material.polygonOffsetUnits;
|
|
25
|
+
material.polygonOffsetFactor = -factor;
|
|
26
|
+
material.polygonOffsetUnits = -units;
|
|
27
|
+
try {
|
|
28
|
+
createPipeline.call(backend, object, promises);
|
|
29
|
+
} finally {
|
|
30
|
+
material.polygonOffsetFactor = factor;
|
|
31
|
+
material.polygonOffsetUnits = units;
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
//#endregion
|
|
36
|
+
//#region src/three/webgpu-driver.ts
|
|
37
|
+
/** Loaded only by the asynchronous backend factory, never by a legacy WebGL-only viewer. */
|
|
38
|
+
async function createWebGpuDriver(options) {
|
|
39
|
+
const canvas = typeof document !== "undefined" ? document.createElement("canvas") : new OffscreenCanvas(1, 1);
|
|
40
|
+
canvas.width = 1;
|
|
41
|
+
canvas.height = 1;
|
|
42
|
+
const renderer = new WebGPURenderer({
|
|
43
|
+
canvas,
|
|
44
|
+
alpha: false,
|
|
45
|
+
antialias: options.antialias ?? false,
|
|
46
|
+
reversedDepthBuffer: options.reverseDepthBuffer ?? false,
|
|
47
|
+
logarithmicDepthBuffer: options.logarithmicDepthBuffer ?? false,
|
|
48
|
+
trackTimestamp: false,
|
|
49
|
+
...options.powerPreference === "high-performance" || options.powerPreference === "low-power" ? { powerPreference: options.powerPreference } : {}
|
|
50
|
+
});
|
|
51
|
+
const initialBackend = renderer.backend;
|
|
52
|
+
try {
|
|
53
|
+
await renderer.init();
|
|
54
|
+
if (!(renderer.backend instanceof WebGPUBackend)) throw new Error("Three.js could not initialize a WebGPU adapter/device");
|
|
55
|
+
installWebGpuTimestampGuard(renderer);
|
|
56
|
+
installWebGpuDepthBiasGuard(renderer);
|
|
57
|
+
renderer.getContext();
|
|
58
|
+
if (options.canvas !== void 0) {
|
|
59
|
+
const previousTarget = renderer.getCanvasTarget();
|
|
60
|
+
renderer.setCanvasTarget(new CanvasTarget(options.canvas));
|
|
61
|
+
previousTarget.dispose();
|
|
62
|
+
renderer.getContext();
|
|
63
|
+
}
|
|
64
|
+
renderer.info.autoReset = false;
|
|
65
|
+
return renderer;
|
|
66
|
+
} catch (error) {
|
|
67
|
+
const initialized = renderer.hasInitialized();
|
|
68
|
+
if (initialized) renderer.dispose();
|
|
69
|
+
if (!initialized || renderer.backend !== initialBackend) initialBackend.dispose();
|
|
70
|
+
renderer.getCanvasTarget().dispose();
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
//#endregion
|
|
75
|
+
export { createWebGpuDriver };
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
//#region src/three/webgpu-frame-timer.ts
|
|
2
|
+
const guardedBackends = /* @__PURE__ */ new WeakSet();
|
|
3
|
+
const timingOwners = /* @__PURE__ */ new WeakSet();
|
|
4
|
+
/**
|
|
5
|
+
* Three r184 caches its canvas pass descriptor and leaves timestampWrites on it when timing
|
|
6
|
+
* is disabled. Clear that stale state before an untracked pass, including after a target swap.
|
|
7
|
+
* This guard lasts for the driver lifetime so disposing a timer cannot restore stale writes.
|
|
8
|
+
*/
|
|
9
|
+
function installWebGpuTimestampGuard(renderer) {
|
|
10
|
+
const backend = renderer.backend;
|
|
11
|
+
if (guardedBackends.has(backend)) return;
|
|
12
|
+
guardedBackends.add(backend);
|
|
13
|
+
const initialize = backend.initTimestampQuery;
|
|
14
|
+
backend.initTimestampQuery = (type, uid, descriptor) => {
|
|
15
|
+
if (!backend.trackTimestamp) {
|
|
16
|
+
delete descriptor.timestampWrites;
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
initialize.call(backend, type, uid, descriptor);
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
/** One asynchronous readback at a time; never wait for the GPU on the render loop. */
|
|
23
|
+
function createWebGpuFrameTimer(renderer, options = {}) {
|
|
24
|
+
const interval = options.sampleEveryFrames ?? 4;
|
|
25
|
+
if (!Number.isSafeInteger(interval) || interval < 1) throw new RangeError("sampleEveryFrames must be a positive integer");
|
|
26
|
+
if (options.maxPendingQueries !== void 0 && (!Number.isSafeInteger(options.maxPendingQueries) || options.maxPendingQueries < 1)) throw new RangeError("maxPendingQueries must be a positive integer");
|
|
27
|
+
if (!renderer.hasFeature("timestamp-query")) return;
|
|
28
|
+
const backend = renderer.backend;
|
|
29
|
+
if (timingOwners.has(renderer) || backend.trackTimestamp) return;
|
|
30
|
+
installWebGpuTimestampGuard(renderer);
|
|
31
|
+
timingOwners.add(renderer);
|
|
32
|
+
let disposed = false;
|
|
33
|
+
let active = false;
|
|
34
|
+
let pending = false;
|
|
35
|
+
let untilSample = 0;
|
|
36
|
+
let latest;
|
|
37
|
+
function disableTracking() {
|
|
38
|
+
backend.trackTimestamp = false;
|
|
39
|
+
const descriptor = backend.get(renderer.getCanvasTarget()).descriptor;
|
|
40
|
+
if (descriptor !== void 0) delete descriptor.timestampWrites;
|
|
41
|
+
}
|
|
42
|
+
function finishReadback() {
|
|
43
|
+
pending = false;
|
|
44
|
+
if (disposed) timingOwners.delete(renderer);
|
|
45
|
+
}
|
|
46
|
+
return {
|
|
47
|
+
begin() {
|
|
48
|
+
if (disposed || pending || active) return false;
|
|
49
|
+
if (untilSample > 0) {
|
|
50
|
+
untilSample--;
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
backend.trackTimestamp = true;
|
|
54
|
+
active = true;
|
|
55
|
+
untilSample = interval - 1;
|
|
56
|
+
return true;
|
|
57
|
+
},
|
|
58
|
+
end() {
|
|
59
|
+
if (!active) return;
|
|
60
|
+
active = false;
|
|
61
|
+
pending = true;
|
|
62
|
+
let result;
|
|
63
|
+
try {
|
|
64
|
+
result = renderer.resolveTimestampsAsync("render");
|
|
65
|
+
} catch {
|
|
66
|
+
pending = false;
|
|
67
|
+
latest = void 0;
|
|
68
|
+
return;
|
|
69
|
+
} finally {
|
|
70
|
+
disableTracking();
|
|
71
|
+
}
|
|
72
|
+
result.then((milliseconds) => {
|
|
73
|
+
finishReadback();
|
|
74
|
+
if (disposed) return;
|
|
75
|
+
latest = milliseconds !== void 0 && Number.isFinite(milliseconds) && milliseconds >= 0 ? milliseconds : void 0;
|
|
76
|
+
}, () => {
|
|
77
|
+
finishReadback();
|
|
78
|
+
latest = void 0;
|
|
79
|
+
});
|
|
80
|
+
},
|
|
81
|
+
poll() {
|
|
82
|
+
const value = latest;
|
|
83
|
+
latest = void 0;
|
|
84
|
+
return value;
|
|
85
|
+
},
|
|
86
|
+
dispose() {
|
|
87
|
+
if (disposed) return;
|
|
88
|
+
disposed = true;
|
|
89
|
+
active = false;
|
|
90
|
+
latest = void 0;
|
|
91
|
+
disableTracking();
|
|
92
|
+
if (!pending) timingOwners.delete(renderer);
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
//#endregion
|
|
97
|
+
export { installWebGpuTimestampGuard as n, createWebGpuFrameTimer as t };
|