roamwright 0.56.0 → 0.57.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,333 @@
1
+ import * as THREE from 'three';
2
+
3
+ const _ahead = new THREE.Vector3();
4
+ const _triPos = [0, 0, 0, 0.001, 0, 0, 0, 0.001, 0];
5
+ const _triNorm = [0, 0, 1, 0, 0, 1, 0, 0, 1];
6
+ const DUMMY_COLORS = [0x808080, 0x806040, 0x406080, 0x608040];
7
+
8
+ /**
9
+ * Measures where main-thread script time goes across rendering passes (`the view`, `the shadow maps`,
10
+ * `the mirror`, `full-screen passes`) over `timedFrames` frames of the live animation loop.
11
+ *
12
+ * @param {object} options
13
+ * @param {THREE.WebGLRenderer} options.renderer Active renderer.
14
+ * @param {THREE.Scene} options.scene Main world scene.
15
+ * @param {THREE.Camera} options.camera Active view camera.
16
+ * @param {() => number} options.getFrame Returns current frame counter.
17
+ * @param {(ms: number) => Promise<void>} options.wait Async sleep helper.
18
+ * @param {() => number} [options.clock] Monotonic clock in milliseconds.
19
+ * @param {number} [options.timedFrames=60] Number of rendered frames to accumulate.
20
+ * @returns {Promise<string>}
21
+ */
22
+ export async function measureScriptShares({ renderer, scene, camera, getFrame, wait, clock = () => performance.now(), timedFrames = 60 }) {
23
+ const drawScene = renderer.render,
24
+ drawShadows = renderer.shadowMap.render,
25
+ spent = {},
26
+ from = getFrame();
27
+ let inShadows = 0;
28
+ renderer.shadowMap.render = function (...args) {
29
+ const began = clock();
30
+ drawShadows.apply(this, args);
31
+ inShadows += clock() - began;
32
+ };
33
+ renderer.render = function (drawn, lens) {
34
+ const target = renderer.getRenderTarget(),
35
+ kind =
36
+ lens === camera
37
+ ? drawn === scene
38
+ ? 'the view'
39
+ : 'over the view'
40
+ : lens.isOrthographicCamera
41
+ ? 'full-screen passes'
42
+ : 'the mirror',
43
+ began = clock(),
44
+ shadowsBefore = inShadows;
45
+ drawScene.call(this, drawn, lens);
46
+ spent[kind] = (spent[kind] || 0) + clock() - began - (inShadows - shadowsBefore);
47
+ if (!target && kind === 'the view') spent.direct = true;
48
+ };
49
+ while (getFrame() - from < timedFrames) await wait(50);
50
+ renderer.render = drawScene;
51
+ renderer.shadowMap.render = drawShadows;
52
+ const frames = getFrame() - from,
53
+ each = ms => +(ms / frames).toFixed(2);
54
+ return `the view ${each(spent['the view'] || 0)} ms, the shadow maps ${each(inShadows)} ms, the mirror ${each(spent['the mirror'] || 0)} ms, the full-screen passes ${each(spent['full-screen passes'] || 0)} ms`;
55
+ }
56
+
57
+ /**
58
+ * Adds `count` sub-pixel dummy triangles 60 m ahead of the camera cycling across four materials so
59
+ * each draws with a material switch and negligible fragment cost. Returns a cleanup callback.
60
+ *
61
+ * @param {object} options
62
+ * @param {THREE.Scene} options.scene Scene receiving the temporary meshes.
63
+ * @param {THREE.Camera} options.camera Active camera.
64
+ * @param {number} options.count Number of draw calls to add.
65
+ * @returns {() => void}
66
+ */
67
+ export function addDummyDrawCalls({ scene, camera, count }) {
68
+ const group = new THREE.Group(),
69
+ triangle = new THREE.BufferGeometry(),
70
+ materials = DUMMY_COLORS.map(color => new THREE.MeshStandardMaterial({ color }));
71
+ camera.getWorldDirection(_ahead).multiplyScalar(60).add(camera.position);
72
+ triangle.setAttribute('position', new THREE.Float32BufferAttribute(_triPos, 3));
73
+ triangle.setAttribute('normal', new THREE.Float32BufferAttribute(_triNorm, 3));
74
+ for (let i = 0; i < count; i++) {
75
+ const mesh = new THREE.Mesh(triangle, materials[i % materials.length]);
76
+ mesh.position.copy(_ahead);
77
+ mesh.frustumCulled = false;
78
+ group.add(mesh);
79
+ }
80
+ scene.add(group);
81
+ return () => {
82
+ scene.remove(group);
83
+ triangle.dispose();
84
+ for (const material of materials) material.dispose();
85
+ };
86
+ }
87
+
88
+ /**
89
+ * Measures displayed FPS with `count` extra draw calls added, letting their shader compile first.
90
+ *
91
+ * @param {{ shown: () => Promise<number> }} sampler Frame sampler from `createFrameSampler`.
92
+ * @param {object} options
93
+ * @param {THREE.Scene} options.scene
94
+ * @param {THREE.Camera} options.camera
95
+ * @param {number} options.count
96
+ * @param {(ms: number) => Promise<void>} options.wait
97
+ * @param {number} [options.rebuiltMs=2000]
98
+ * @returns {Promise<number>}
99
+ */
100
+ export async function measureWithMoreCalls(sampler, { scene, camera, count, wait, rebuiltMs = 2000 }) {
101
+ const away = addDummyDrawCalls({ scene, camera, count });
102
+ await wait(rebuiltMs);
103
+ const frames = await sampler.shown();
104
+ away();
105
+ return frames;
106
+ }
107
+
108
+ /**
109
+ * Measures ground draw-order sensitivity by turns: resetting ground `renderOrder` to `0`, and
110
+ * switching Three.js opaque sorting to strict near-to-far order.
111
+ *
112
+ * @param {{ byTurns: (change: () => void, back: () => void, settleMs?: number) => Promise<string> }} sampler
113
+ * @param {object} options
114
+ * @param {THREE.WebGLRenderer} options.renderer
115
+ * @param {THREE.Object3D[]} options.ground
116
+ * @returns {Promise<string[]>}
117
+ */
118
+ export async function measureGroundOrder(sampler, { renderer, ground }) {
119
+ const nearFirst = (a, b) => a.groupOrder - b.groupOrder || a.renderOrder - b.renderOrder || a.z - b.z || a.id - b.id;
120
+ const order = ground.map(piece => piece.renderOrder);
121
+ return [
122
+ `drawn in the first place of the frame's order, as a desk draws it ${await sampler.byTurns(
123
+ () => ground.forEach(piece => (piece.renderOrder = 0)),
124
+ () => ground.forEach((piece, at) => (piece.renderOrder = order[at])),
125
+ )}`,
126
+ `with all that hides drawn from the near to the far ${await sampler.byTurns(
127
+ () => renderer.setOpaqueSort(nearFirst),
128
+ () => renderer.setOpaqueSort(null),
129
+ )}`,
130
+ ];
131
+ }
132
+
133
+ /**
134
+ * Measures terrain shader cost by turns against cloned materials (carrying all defines so comparisons
135
+ * against `a copy of itself` isolate shader cost from Three.js opaque program order).
136
+ *
137
+ * @param {{ byTurns: (change: () => void, back: () => void, settleMs?: number) => Promise<string> }} sampler
138
+ * @param {object} options
139
+ * @param {THREE.WebGLRenderer} options.renderer
140
+ * @param {THREE.Mesh[]} options.ground Ground meshes.
141
+ * @param {THREE.Material[]} options.worn Original materials of `ground`.
142
+ * @param {boolean} [options.lightAlone=false] When true, breaks down lighting sub-stages instead of draw order and defines.
143
+ * @param {(ms: number) => Promise<void>} options.wait
144
+ * @param {number} [options.rebuiltMs=2000]
145
+ * @param {Array<[string, string, string]>} [options.defineCuts=[]] Optional `[defineName, cacheKey, label]` tuples stripped when present.
146
+ * @returns {Promise<string>}
147
+ */
148
+ export async function measureGroundParts(sampler, { renderer, ground, worn, lightAlone = false, wait, rebuiltMs = 2000, defineCuts = [] }) {
149
+ const groundCut = (key, cut = text => text, without = []) => {
150
+ const made = new Map();
151
+ return ground.map(piece => {
152
+ const own = piece.material;
153
+ if (!made.has(own)) {
154
+ const cutOne = own.clone();
155
+ cutOne.defines = { ...own.defines };
156
+ for (const define of without) delete cutOne.defines[define];
157
+ cutOne.onBeforeCompile = shader => {
158
+ own.onBeforeCompile(shader);
159
+ shader.fragmentShader = cut(shader.fragmentShader);
160
+ };
161
+ cutOne.customProgramCacheKey = () => `${own.customProgramCacheKey()}:${key}`;
162
+ made.set(own, cutOne);
163
+ }
164
+ return made.get(own);
165
+ });
166
+ };
167
+ const wear = materials => () => ground.forEach((piece, at) => (piece.material = materials[at]));
168
+ const has = define => worn.some(material => define in (material.defines || {}));
169
+ const SKY_READS = [['#include <lights_fragment_maps>', '']];
170
+ const parts = [
171
+ ['a copy of itself (the check: the same)', groundCut('same')],
172
+ [
173
+ 'without its light',
174
+ groundCut('unlit', text =>
175
+ text.replace(
176
+ '#include <roughnessmap_fragment>',
177
+ 'gl_FragColor = vec4(diffuseColor.rgb, 1.0); return;\n#include <roughnessmap_fragment>',
178
+ ),
179
+ ),
180
+ ],
181
+ [
182
+ "without the sky's reads in its light",
183
+ groundCut('skyless', text => SKY_READS.reduce((cut, [from, to]) => cut.replaceAll(from, to), text)),
184
+ ],
185
+ ];
186
+ if (lightAlone) {
187
+ const lights = text => text.replace('#include <lights_fragment_begin>', THREE.ShaderChunk.lights_fragment_begin);
188
+ parts.length = 2; // the copy and the ground without its light
189
+ parts.push(
190
+ ["without the sun's shadows", groundCut('shadowless', text => lights(text).replaceAll('sunShadow()', '1.0'))],
191
+ ['without the haze and fog', groundCut('fogless', text => text.replaceAll('#include <fog_fragment>', ''))],
192
+ ['without its relief', groundCut('flat-relief', text => text.replace(/normal = terrainReliefNormal\([^;]*;/, ''))],
193
+ ["without the clouds' shadows", groundCut('cloudless', text => text.replace('diffuseColor.rgb *= cloudShade(vWP.xz);', ''))],
194
+ );
195
+ } else {
196
+ for (const [define, key, label] of defineCuts) {
197
+ if (has(define)) parts.push([label, groundCut(key, undefined, [define])]);
198
+ }
199
+ }
200
+ for (const [, materials] of parts) {
201
+ wear(materials)(); // compile variants before starting turn-about trials
202
+ await wait(rebuiltMs);
203
+ }
204
+ wear(worn)();
205
+ const told = lightAlone ? [] : await measureGroundOrder(sampler, { renderer, ground });
206
+ for (const [what, materials] of parts) told.push(`${what} ${await sampler.byTurns(wear(materials), wear(worn))}`);
207
+ return `the ground ${told.join('; ')}`;
208
+ }
209
+
210
+ /**
211
+ * Measures the cost of anisotropic texture filtering across currently visible materials by turns.
212
+ *
213
+ * @param {{ byTurns: (change: () => void, back: () => void, settleMs?: number) => Promise<string> }} sampler
214
+ * @param {object} options
215
+ * @param {THREE.WebGLRenderer} options.renderer
216
+ * @param {THREE.Scene} options.scene
217
+ * @returns {Promise<string>}
218
+ */
219
+ export async function measureAnisotropicReads(sampler, { renderer, scene }) {
220
+ const anisotropic = renderer.extensions.get('EXT_texture_filter_anisotropic'),
221
+ filtered = new Set();
222
+ scene.traverseVisible(object => {
223
+ for (const material of [].concat(object.material || [])) {
224
+ const uniforms = renderer.properties.get(material).uniforms || {};
225
+ for (const name in uniforms) {
226
+ const texture = uniforms[name]?.value;
227
+ if (texture?.isTexture && texture.anisotropy > 1 && renderer.properties.get(texture).__webglTexture) filtered.add(texture);
228
+ }
229
+ }
230
+ });
231
+ const readAlong = most => {
232
+ const gl = renderer.getContext();
233
+ for (const texture of filtered) {
234
+ renderer.state.bindTexture(gl.TEXTURE_2D, renderer.properties.get(texture).__webglTexture);
235
+ gl.texParameterf(gl.TEXTURE_2D, anisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(most, texture.anisotropy));
236
+ }
237
+ };
238
+ const along = [];
239
+ if (anisotropic && filtered.size) {
240
+ along.push(
241
+ `at 1 ${await sampler.byTurns(
242
+ () => readAlong(1),
243
+ () => readAlong(Infinity),
244
+ )}`,
245
+ );
246
+ }
247
+ return `${filtered.size} textures read along their long axis: ${along.join('; ') || 'none'}`;
248
+ }
249
+
250
+ /**
251
+ * Measures the upper-bound cost of evaluating every point and spot light at every lit pixel by turns.
252
+ *
253
+ * @param {{ byTurns: (change: () => void, back: () => void, settleMs?: number) => Promise<string> }} sampler
254
+ * @param {object} options
255
+ * @param {THREE.Scene} options.scene
256
+ * @returns {Promise<string>}
257
+ */
258
+ export async function measureDimmedLights(sampler, { scene }) {
259
+ let reaching = false;
260
+ const dimmed = [];
261
+ scene.traverse(light => {
262
+ if (!light.isPointLight && !light.isSpotLight) return;
263
+ dimmed.push(light);
264
+ let { intensity, distance, angle } = light;
265
+ Object.defineProperties(light, {
266
+ intensity: { configurable: true, get: () => (reaching ? Math.max(intensity, 1e-4) : intensity), set: to => (intensity = to) },
267
+ distance: { configurable: true, get: () => (reaching ? 0 : distance), set: to => (distance = to) },
268
+ });
269
+ if (light.isSpotLight) {
270
+ Object.defineProperty(light, 'angle', { configurable: true, get: () => (reaching ? Math.PI / 2 : angle), set: to => (angle = to) });
271
+ }
272
+ });
273
+ return `${dimmed.length} dimmed lights worked out at every pixel ${await sampler.byTurns(
274
+ () => (reaching = true),
275
+ () => (reaching = false),
276
+ )}`;
277
+ }
278
+
279
+ /**
280
+ * Measures planar mirror reflection cost: disabled, drawn with an empty layer mask, and quarter-sized.
281
+ *
282
+ * @param {{ shown: () => Promise<number>, shownWithout: (off: () => void, back: () => void) => Promise<number> }} sampler
283
+ * @param {object} options
284
+ * @param {{ mirror?: boolean }} options.quality
285
+ * @param {{ off: boolean, cam: THREE.Camera, rt: THREE.WebGLRenderTarget | null }} options.mirror
286
+ * @returns {Promise<string>}
287
+ */
288
+ export async function measureMirror(sampler, { quality, mirror }) {
289
+ if (!quality.mirror || !mirror?.rt) return 'this preset has no mirror';
290
+ const off = await sampler.shownWithout(
291
+ () => (mirror.off = true),
292
+ () => (mirror.off = false),
293
+ );
294
+ const seen = mirror.cam.layers.mask;
295
+ mirror.cam.layers.set(31);
296
+ const empty = await sampler.shown();
297
+ mirror.cam.layers.mask = seen;
298
+ const wide = mirror.rt.width,
299
+ high = mirror.rt.height;
300
+ mirror.rt.setSize(Math.round(wide / 4), Math.round(high / 4));
301
+ const small = await sampler.shown();
302
+ mirror.rt.setSize(wide, high);
303
+ return `without the mirror ${off}, with its pass empty ${empty}, with its picture a quarter the size ${small}`;
304
+ }
305
+
306
+ /**
307
+ * Measures full-screen post-processing cost: without TAA smoothing and drawing straight to the screen.
308
+ *
309
+ * @param {{ shown: () => Promise<number> }} sampler
310
+ * @param {object} options
311
+ * @param {{ on: boolean, samples: number, taa: boolean }} options.post
312
+ * @param {(on: boolean, samples: number, taa: boolean) => void} options.setPost
313
+ * @param {() => void} options.resize
314
+ * @param {number} options.frames Baseline FPS with current post settings.
315
+ * @param {(ms: number) => Promise<void>} options.wait
316
+ * @param {number} [options.rebuiltMs=2000]
317
+ * @returns {Promise<string>}
318
+ */
319
+ export async function measurePostPasses(sampler, { post, setPost, resize, frames, wait, rebuiltMs = 2000 }) {
320
+ if (!post.on) return 'this preset draws straight to the screen';
321
+ const { samples, taa } = post,
322
+ drawnAs = async (on, smoothed) => {
323
+ setPost(on, samples, smoothed);
324
+ resize();
325
+ await wait(rebuiltMs);
326
+ return sampler.shown();
327
+ };
328
+ const unsmoothed = taa ? await drawnAs(true, false) : frames,
329
+ straight = await drawnAs(false, false);
330
+ setPost(true, samples, taa);
331
+ resize();
332
+ return `without the smoothing over frames ${unsmoothed}, drawn straight to the screen ${straight}`;
333
+ }