@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.
@@ -0,0 +1,319 @@
1
+ import * as THREE from "three";
2
+ import { BundleGroup } from "three/webgpu";
3
+ //#region src/three/webgpu-instance-buffers.ts
4
+ /**
5
+ * Three r184–r186 adapter (the client's three peer range); it patches the WebGPU backend's
6
+ * `updateBinding`, so re-check that and `NodeUniformBuffer` before widening the range. Instance
7
+ * matrices that fit a UBO are uploaded unconditionally by NodeUniformBuffer, even though
8
+ * InstancedBufferAttribute already supplies change versions.
9
+ * Keep the existing shader/binding layout, and skip only a known, unchanged matrix UBO upload.
10
+ * Other uniforms (camera, materials, time), initial uploads and normal needsUpdate writes pass through.
11
+ */
12
+ var WebGpuInstanceBuffers = class {
13
+ attributes = /* @__PURE__ */ new WeakMap();
14
+ uploaded = /* @__PURE__ */ new WeakMap();
15
+ restore;
16
+ constructor(renderer) {
17
+ const backend = renderer.backend;
18
+ const update = backend.updateBinding;
19
+ backend.updateBinding = (binding) => {
20
+ const attribute = binding.isNodeUniformBuffer ? this.attributes.get(binding.buffer) : void 0;
21
+ if (!attribute) {
22
+ update.call(backend, binding);
23
+ return;
24
+ }
25
+ const previous = this.uploaded.get(binding);
26
+ if (previous?.attribute === attribute && previous.version === attribute.version) return;
27
+ update.call(backend, binding);
28
+ this.uploaded.set(binding, {
29
+ attribute,
30
+ version: attribute.version
31
+ });
32
+ };
33
+ this.restore = () => {
34
+ backend.updateBinding = update;
35
+ };
36
+ }
37
+ track(attribute) {
38
+ const previous = this.attributes.get(attribute.array);
39
+ this.attributes.set(attribute.array, previous === void 0 || previous === attribute ? attribute : false);
40
+ }
41
+ dispose() {
42
+ this.restore();
43
+ }
44
+ };
45
+ //#endregion
46
+ //#region src/three/webgpu-scene-optimizer.ts
47
+ const STABLE_CAMERA_FRAMES = 8;
48
+ /** A tile-sized command cache. The owner checks its draw state before every render. */
49
+ var RenderGroup = class extends BundleGroup {
50
+ eligible = true;
51
+ samples = [];
52
+ cursor = 0;
53
+ changed = false;
54
+ stats = {
55
+ drawCalls: 0,
56
+ triangles: 0
57
+ };
58
+ recordedVersion = -1;
59
+ recordingFrame = -1;
60
+ write(value) {
61
+ if (this.samples[this.cursor] !== value) this.changed = true;
62
+ this.samples[this.cursor++] = value;
63
+ }
64
+ writeArray(values) {
65
+ for (let i = 0; i < values.length; i++) this.write(values[i]);
66
+ }
67
+ };
68
+ /**
69
+ * Uses Three render bundles and a pinned, version-aware instance upload adapter.
70
+ * Bundles are restricted to opaque, unskinned content with ordinary object callbacks. Re-recording
71
+ * on camera changes deliberately keeps Three's frustum culling, sorting and LOD decisions intact.
72
+ */
73
+ var WebGpuSceneOptimizer = class {
74
+ renderer;
75
+ instances;
76
+ renderHook;
77
+ groups = /* @__PURE__ */ new WeakSet();
78
+ active = [];
79
+ frame = 0;
80
+ stableCameraFrames = 0;
81
+ cameraState = [];
82
+ frameSize = new THREE.Vector2();
83
+ matrixSamples = /* @__PURE__ */ new WeakMap();
84
+ restoreRefresh;
85
+ materialSamples = /* @__PURE__ */ new Map();
86
+ videoMaterials = /* @__PURE__ */ new WeakSet();
87
+ materialStates = /* @__PURE__ */ new WeakMap();
88
+ constructor(renderer) {
89
+ this.renderer = renderer;
90
+ this.instances = new WebGpuInstanceBuffers(renderer);
91
+ const nodes = renderer._nodes;
92
+ const refresh = nodes.needsRefresh;
93
+ nodes.needsRefresh = (object) => {
94
+ const group = object.bundle;
95
+ if (group !== null && this.groups.has(group) && group.eligible && group.version === group.recordedVersion && !renderer.getMRT()?.has("velocity")) {
96
+ const monitor = object.getMonitor();
97
+ if (!monitor.hasNode && !monitor.hasAnimation && monitor.renderObjects.has(object)) return false;
98
+ }
99
+ return refresh.call(nodes, object);
100
+ };
101
+ this.restoreRefresh = () => {
102
+ nodes.needsRefresh = refresh;
103
+ };
104
+ this.renderHook = (...args) => {
105
+ let parent = args[0].parent;
106
+ while (parent !== null && !this.groups.has(parent)) parent = parent.parent;
107
+ const group = parent;
108
+ const before = renderer.info.render;
109
+ const draws = before.drawCalls;
110
+ const triangles = before.triangles;
111
+ renderer.renderObject(...args);
112
+ if (group?.isBundleGroup) {
113
+ if (group.recordingFrame !== this.frame) {
114
+ group.recordingFrame = this.frame;
115
+ group.stats = {
116
+ drawCalls: 0,
117
+ triangles: 0
118
+ };
119
+ }
120
+ group.stats.drawCalls += before.drawCalls - draws;
121
+ group.stats.triangles += before.triangles - triangles;
122
+ }
123
+ };
124
+ renderer.setRenderObjectFunction(this.renderHook);
125
+ }
126
+ createGroup() {
127
+ const group = new RenderGroup();
128
+ this.groups.add(group);
129
+ return group;
130
+ }
131
+ /** Update matrices once; Renderer suppresses Three's duplicate scene traversal for this frame. */
132
+ prepare(scene, camera) {
133
+ this.frame++;
134
+ this.active = [];
135
+ this.materialSamples.clear();
136
+ if (scene.matrixWorldAutoUpdate) scene.updateMatrixWorld();
137
+ if (camera.parent === null && camera.matrixWorldAutoUpdate) camera.updateMatrixWorld();
138
+ const cameraState = [
139
+ camera,
140
+ camera.layers.mask,
141
+ ...camera.matrixWorld.elements,
142
+ ...camera.projectionMatrix.elements
143
+ ];
144
+ const sameCamera = cameraState.length === this.cameraState.length && cameraState.every((value, i) => value === this.cameraState[i]);
145
+ this.stableCameraFrames = this.frame <= 2 ? STABLE_CAMERA_FRAMES : sameCamera ? Math.min(STABLE_CAMERA_FRAMES, this.stableCameraFrames + 1) : 0;
146
+ const cacheView = this.stableCameraFrames >= STABLE_CAMERA_FRAMES;
147
+ this.cameraState = cameraState;
148
+ this.renderer.getDrawingBufferSize(this.frameSize);
149
+ const view = [
150
+ camera,
151
+ camera.layers.mask,
152
+ scene.overrideMaterial,
153
+ scene.fog,
154
+ scene.environment,
155
+ scene.environmentIntensity,
156
+ this.renderer.toneMapping,
157
+ this.renderer.toneMappingExposure,
158
+ this.renderer.outputColorSpace,
159
+ this.frameSize.x,
160
+ this.frameSize.y,
161
+ this.renderer.getPixelRatio()
162
+ ];
163
+ view.push(...camera.matrixWorld.elements, ...camera.projectionMatrix.elements);
164
+ if (scene.fog instanceof THREE.Fog) view.push(scene.fog.near, scene.fog.far, scene.fog.color.r, scene.fog.color.g, scene.fog.color.b);
165
+ if (scene.fog instanceof THREE.FogExp2) view.push(scene.fog.density, scene.fog.color.r, scene.fog.color.g, scene.fog.color.b);
166
+ view.push(scene.environment?.version, scene.environmentRotation.x, scene.environmentRotation.y, scene.environmentRotation.z);
167
+ const lights = [];
168
+ const visit = (object, group) => {
169
+ if (group !== void 0 && cacheView) {
170
+ group.write(object);
171
+ group.write(object.visible);
172
+ group.write(object.layers.mask);
173
+ }
174
+ if (!object.visible) return;
175
+ if (object instanceof THREE.Light) {
176
+ lights.push(object, ...object.matrixWorld.elements);
177
+ for (const value of Object.values(object)) this.sampleValue(lights, value);
178
+ }
179
+ if (object instanceof THREE.DirectionalLight || object instanceof THREE.SpotLight) {
180
+ lights.push(...object.target.matrixWorld.elements);
181
+ this.sampleValue(lights, object.target.position);
182
+ }
183
+ if (object instanceof THREE.LOD && object.autoUpdate) object.update(camera);
184
+ if (object instanceof THREE.InstancedMesh) this.instances.track(object.instanceMatrix);
185
+ if (this.groups.has(object)) {
186
+ const own = object;
187
+ if (group !== void 0) this.disable(group);
188
+ group = own;
189
+ own.cursor = 0;
190
+ own.changed = false;
191
+ own.writeArray(view);
192
+ own.eligible = cacheView && !this.renderer.shadowMap.enabled && scene.overrideMaterial === null && scene.onBeforeRender === THREE.Object3D.prototype.onBeforeRender && this.renderer.getRenderObjectFunction() === this.renderHook && this.renderer.xr?.isPresenting !== true;
193
+ this.active.push(own);
194
+ }
195
+ if (group !== void 0 && cacheView) {
196
+ group.write(object.renderOrder);
197
+ group.write(object.frustumCulled);
198
+ group.write(object.matrixWorld);
199
+ group.write(this.sampleMatrix(object.matrixWorld));
200
+ if (object.onBeforeRender !== THREE.Object3D.prototype.onBeforeRender || object.onAfterRender !== THREE.Object3D.prototype.onAfterRender || object instanceof THREE.SkinnedMesh || object instanceof THREE.Sprite || object instanceof THREE.Light || "isClippingGroup" in object) this.disable(group);
201
+ if (object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points) {
202
+ const geometry = object.geometry;
203
+ group.write(geometry);
204
+ group.write(geometry.index);
205
+ group.write(geometry.index?.version);
206
+ group.write(geometry.drawRange.start);
207
+ group.write(geometry.drawRange.count);
208
+ for (const name in geometry.attributes) {
209
+ const attribute = geometry.attributes[name];
210
+ if (attribute === void 0) continue;
211
+ group.write(name);
212
+ group.write(attribute);
213
+ group.write("version" in attribute ? attribute.version : attribute.data.version);
214
+ }
215
+ for (const draw of geometry.groups) {
216
+ group.write(draw.start);
217
+ group.write(draw.count);
218
+ group.write(draw.materialIndex);
219
+ }
220
+ if (object instanceof THREE.Mesh && object.morphTargetInfluences !== void 0) this.disable(group);
221
+ if (object instanceof THREE.InstancedMesh) {
222
+ group.write(object.count);
223
+ group.write(object.instanceMatrix);
224
+ group.write(object.instanceMatrix.version);
225
+ group.write(object.instanceColor);
226
+ group.write(object.instanceColor?.version);
227
+ }
228
+ const materials = Array.isArray(object.material) ? object.material : [object.material];
229
+ for (const material of materials) {
230
+ if (!material.depthTest || !material.depthWrite || material.transparent || (material.clippingPlanes?.length ?? 0) > 0 || material.transmission > 0 || material instanceof THREE.ShaderMaterial) this.disable(group);
231
+ group.write(material);
232
+ group.write(this.sampleMaterial(material));
233
+ if (this.videoMaterials.has(material)) this.disable(group);
234
+ }
235
+ }
236
+ }
237
+ for (const child of object.children) visit(child, group);
238
+ };
239
+ visit(scene);
240
+ for (const group of this.active) {
241
+ group.writeArray(lights);
242
+ this.setEnabled(group, group.eligible);
243
+ if (group.changed || group.cursor !== group.samples.length) group.needsUpdate = true;
244
+ group.samples.length = group.cursor;
245
+ }
246
+ }
247
+ /** Three counts command recording, not cached execution; retain the actual recorded workload. */
248
+ finish() {
249
+ for (const group of this.active) {
250
+ if (!group.isBundleGroup) continue;
251
+ if (group.recordedVersion === group.version && group.recordingFrame !== this.frame) {
252
+ this.renderer.info.render.drawCalls += group.stats.drawCalls;
253
+ this.renderer.info.render.triangles += group.stats.triangles;
254
+ } else if (group.recordingFrame !== this.frame) group.stats = {
255
+ drawCalls: 0,
256
+ triangles: 0
257
+ };
258
+ group.recordedVersion = group.version;
259
+ }
260
+ }
261
+ sampleMatrix(matrix) {
262
+ let sample = this.matrixSamples.get(matrix);
263
+ if (sample === void 0) {
264
+ sample = {
265
+ elements: new Float64Array(matrix.elements),
266
+ revision: 0
267
+ };
268
+ this.matrixSamples.set(matrix, sample);
269
+ } else for (let i = 0; i < 16; i++) if (sample.elements[i] !== matrix.elements[i]) {
270
+ sample.elements.set(matrix.elements);
271
+ sample.revision++;
272
+ break;
273
+ }
274
+ return sample.revision;
275
+ }
276
+ setEnabled(group, enabled) {
277
+ if (group.isBundleGroup !== enabled) {
278
+ Object.assign(group, { isBundleGroup: enabled });
279
+ group.needsUpdate = true;
280
+ }
281
+ }
282
+ disable(group) {
283
+ group.eligible = false;
284
+ }
285
+ sampleMaterial(material) {
286
+ const cached = this.materialSamples.get(material);
287
+ if (cached !== void 0) return cached;
288
+ const sample = [];
289
+ this.videoMaterials.delete(material);
290
+ for (const value of Object.values(material)) {
291
+ if (value instanceof THREE.VideoTexture) this.videoMaterials.add(material);
292
+ this.sampleValue(sample, value);
293
+ }
294
+ const previous = this.materialStates.get(material);
295
+ let revision = previous?.revision ?? 0;
296
+ if (previous === void 0 || sample.length !== previous.sample.length || sample.some((value, i) => value !== previous.sample[i])) revision++;
297
+ this.materialStates.set(material, {
298
+ sample,
299
+ revision
300
+ });
301
+ this.materialSamples.set(material, revision);
302
+ return revision;
303
+ }
304
+ sampleValue(sample, value) {
305
+ if (value instanceof THREE.Color) sample.push(value.r, value.g, value.b);
306
+ else if (value instanceof THREE.Vector2) sample.push(value.x, value.y);
307
+ else if (value instanceof THREE.Vector3) sample.push(value.x, value.y, value.z);
308
+ else if (value instanceof THREE.Texture) sample.push(value, value.version, ...value.matrix.elements, value.offset.x, value.offset.y, value.repeat.x, value.repeat.y, value.rotation);
309
+ else sample.push(value);
310
+ }
311
+ dispose() {
312
+ this.restoreRefresh();
313
+ this.instances.dispose();
314
+ this.active = [];
315
+ this.materialSamples.clear();
316
+ }
317
+ };
318
+ //#endregion
319
+ export { WebGpuSceneOptimizer };
package/package.json ADDED
@@ -0,0 +1,85 @@
1
+ {
2
+ "name": "@bendyline/molen-client",
3
+ "version": "0.0.1",
4
+ "private": false,
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "type": "module",
9
+ "engines": {
10
+ "node": ">=22.13.0"
11
+ },
12
+ "description": "Molen rendering client: three.js wrapper, snapshot sync, interpolation",
13
+ "license": "MIT",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/bendyline/molen.git",
17
+ "directory": "packages/client"
18
+ },
19
+ "homepage": "https://github.com/bendyline/molen/tree/main/packages/client",
20
+ "bugs": {
21
+ "url": "https://github.com/bendyline/molen/issues"
22
+ },
23
+ "keywords": [
24
+ "molen",
25
+ "3d",
26
+ "threejs",
27
+ "webgpu",
28
+ "rendering"
29
+ ],
30
+ "exports": {
31
+ ".": {
32
+ "types": "./dist/index.d.mts",
33
+ "default": "./dist/index.mjs"
34
+ },
35
+ "./camera-track": {
36
+ "types": "./dist/camera-track.d.mts",
37
+ "default": "./dist/camera-track.mjs"
38
+ },
39
+ "./vite": {
40
+ "types": "./dist/vite.d.mts",
41
+ "default": "./dist/vite.mjs"
42
+ },
43
+ "./vehicles": {
44
+ "types": "./dist/vehicles.d.mts",
45
+ "default": "./dist/vehicles.mjs"
46
+ },
47
+ "./aircraft": {
48
+ "types": "./dist/aircraft.d.mts",
49
+ "default": "./dist/aircraft.mjs"
50
+ }
51
+ },
52
+ "files": [
53
+ "dist",
54
+ "NOTICE.md"
55
+ ],
56
+ "dependencies": {
57
+ "zod": "^4.6.5",
58
+ "@bendyline/molen-materials": "0.0.1",
59
+ "@bendyline/molen-schema": "0.0.1"
60
+ },
61
+ "peerDependencies": {
62
+ "@types/three": ">=0.184.0 <0.187.0",
63
+ "three": ">=0.184.0 <0.187.0"
64
+ },
65
+ "peerDependenciesMeta": {
66
+ "@types/three": {
67
+ "optional": true
68
+ }
69
+ },
70
+ "devDependencies": {
71
+ "@biomejs/biome": "^2.5.0",
72
+ "@types/node": "^24",
73
+ "@types/three": "0.184.0",
74
+ "three": "0.184.0",
75
+ "tsdown": "^0.22.2",
76
+ "typescript": "^6.0.3",
77
+ "vitest": "^4.1.8"
78
+ },
79
+ "scripts": {
80
+ "build": "tsdown",
81
+ "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.vite.json",
82
+ "lint": "biome check src",
83
+ "test:unit": "vitest run --passWithNoTests"
84
+ }
85
+ }