roamwright 0.56.0 → 0.58.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,406 @@
1
+ import * as THREE from 'three';
2
+ import {
3
+ DEFAULT_LOW_GROUPS,
4
+ DEFAULT_PROBE_LEGS,
5
+ createFrameSampler,
6
+ parseLowTrials,
7
+ parseStandAt,
8
+ summarizeRouteLeg,
9
+ } from '../runtime/perf-probe.js';
10
+ import {
11
+ measureAnisotropicReads,
12
+ measureDimmedLights,
13
+ measureGroundParts,
14
+ measureMirror,
15
+ measurePostPasses,
16
+ measureScriptShares,
17
+ measureWithMoreCalls,
18
+ } from './perf-probe-passes.js';
19
+
20
+ const SETTLE_MS = 12000,
21
+ LOOP_MS = 3000,
22
+ REBUILT_MS = 2000,
23
+ TURNS = 4,
24
+ FIT_SECONDS = 8,
25
+ RECOMPILED_MS = 35000,
26
+ LEG_MS = 12000;
27
+
28
+ /**
29
+ * Flies a four-leg route around the current camera position without holding quality or frame pacing,
30
+ * recording inter-frame intervals and reporting hitch counts (>25 ms, >50 ms, >100 ms) per leg.
31
+ *
32
+ * @param {object} options
33
+ * @param {THREE.Camera} options.camera Active view camera.
34
+ * @param {(flying: boolean) => void} options.setFly Enables flight mode.
35
+ * @param {(x: number, z: number, yaw: number) => void} options.placePlayer Places the player horizontally.
36
+ * @param {{ y: number, pitch: number }} options.player Mutable player pose.
37
+ * @param {(x: number, z: number) => number} options.ground Ground height sampler in metres.
38
+ * @param {Array<[string, number, number, number, number]>} [options.legs=DEFAULT_PROBE_LEGS] Route leg definitions.
39
+ * @param {number} [options.legMs=12000] Duration of each leg in milliseconds.
40
+ * @param {(ms: number) => Promise<void>} [options.wait] Async sleep helper.
41
+ * @param {() => Promise<number>} [options.nextFrame] Resolves on the next animation frame with timestamp in ms.
42
+ * @returns {Promise<string[]>}
43
+ */
44
+ export async function flyProbeRoute({
45
+ camera,
46
+ setFly,
47
+ placePlayer,
48
+ player,
49
+ ground,
50
+ legs = DEFAULT_PROBE_LEGS,
51
+ legMs = LEG_MS,
52
+ wait = ms => new Promise(resolve => setTimeout(resolve, ms)),
53
+ nextFrame = () => new Promise(requestAnimationFrame),
54
+ }) {
55
+ const x = camera.position.x,
56
+ z = camera.position.z,
57
+ told = [];
58
+ setFly(true);
59
+ for (const [name, up, speed, direction, pitch] of legs) {
60
+ const half = (speed * legMs) / 2,
61
+ move = along => {
62
+ const at = x + direction * along;
63
+ placePlayer(at, z, (-direction * Math.PI) / 2);
64
+ player.y = ground(at, z) + up;
65
+ player.pitch = pitch;
66
+ };
67
+ move(-half);
68
+ await wait(1500); // let the leg's starting view settle before counting gaps
69
+ const gaps = [],
70
+ start = await nextFrame();
71
+ let time = start,
72
+ last = start;
73
+ while (time - start < legMs) {
74
+ move(-half + (time - start) * speed);
75
+ time = await nextFrame();
76
+ gaps.push(time - last);
77
+ last = time;
78
+ }
79
+ told.push(summarizeRouteLeg(name, gaps, time - start));
80
+ }
81
+ return told;
82
+ }
83
+
84
+ /**
85
+ * Self-measuring page probe for environments where external DevTools or Playwright scripts cannot
86
+ * drive the browser (such as mobile simulators). Reads query parameters (`?probe[=mode]`, `at`, `then`, `set`),
87
+ * isolates GPU, pass, shader, texture, light, mirror, and draw-call costs in displayed frames per second,
88
+ * and writes every finding to `noteLog`.
89
+ *
90
+ * @param {object} options
91
+ * @param {{ get: (name: string) => string | null }} options.query Opening URL query parameters (`URLSearchParams`).
92
+ * @param {{ mode: string, quality: string, frame: number }} options.state Live engine state.
93
+ * @param {THREE.Scene} options.scene Active world scene.
94
+ * @param {THREE.Camera} options.camera Active view camera.
95
+ * @param {THREE.WebGLRenderer} options.renderer Active renderer.
96
+ * @param {object} options.post Post-processing state (`on`, `samples`, `taa`, `scale`, `bloom`, `aoScene`).
97
+ * @param {(on: boolean, samples: number, taa: boolean) => void} options.setPost Rebuilds the post-processing pipeline.
98
+ * @param {object} options.mirror Planar reflection state (`off`, `cam`, `rt`).
99
+ * @param {Record<string, unknown>} options.quality Active preset figures (`mirror`, `worldLeast`).
100
+ * @param {Record<string, Record<string, unknown>>} options.presets Preset definitions (`low`, `medium`, `high`).
101
+ * @param {(name: string) => void} options.applyQuality Applies a named quality preset.
102
+ * @param {(size: number) => void} [options.setFarShadow] Updates far shadow map resolution when `farShadow` is probed.
103
+ * @param {() => number | null} options.cardTime Returns last GPU frame time from quality fit (ms) or `null`.
104
+ * @param {(held: boolean) => void} options.holdQuality Locks or releases automatic quality fitting.
105
+ * @param {(held: boolean) => void} options.holdPace Locks or releases adaptive frame pacing.
106
+ * @param {(w: number, h?: number, pr?: number) => void} options.holdSize Locks or releases viewport size.
107
+ * @param {() => void} options.resize Applies viewport / post-processing sizing.
108
+ * @param {() => number} options.viewportWidth Current viewport width in CSS pixels.
109
+ * @param {() => number} options.viewportHeight Current viewport height in CSS pixels.
110
+ * @param {(kind: string, text: string) => void} options.noteLog Diagnostic log writer.
111
+ * @param {() => HTMLElement | null} [options.hudElement] Returns the HUD root element toggled during the full probe.
112
+ * @param {() => { player: { y: number, pitch: number }, space: { ground: (x: number, z: number) => number }, setFly: (on: boolean) => void, placePlayer: (x: number, z: number, yaw: number) => void }} options.getWorld Returns live player/space placement helpers.
113
+ * @param {(frames?: number) => Promise<{ ms: number, cpu: number, update: number, draw: number, calls: number, tris: number, px: string }>} options.bench Back-to-back GPU-fenced frame benchmark.
114
+ * @param {Array<[string, string, string]>} [options.groundDefineCuts=[]] Optional `[defineName, cacheKey, label]` tuples for ground shader breakdown.
115
+ * @param {string[][]} [options.lowGroups=DEFAULT_LOW_GROUPS] Preset key groups swapped during `?probe=lows`.
116
+ * @param {Array<[string, number, number, number, number]>} [options.routeLegs=DEFAULT_PROBE_LEGS] Legs for `?probe=route`.
117
+ * @param {(ms: number) => Promise<void>} [options.wait] Async sleep helper in milliseconds.
118
+ * @param {() => number} [options.clock] Monotonic clock in milliseconds.
119
+ * @param {() => Promise<number>} [options.nextFrame] Animation-frame awaiter.
120
+ * @param {number} [options.settleMs=12000] Initial world settle wait in milliseconds.
121
+ * @param {number} [options.loopMs=3000] Counting window per FPS sample in milliseconds.
122
+ * @param {number} [options.rebuiltMs=2000] Settle wait after rebuilding a shader/pipeline in milliseconds.
123
+ * @param {number} [options.recompiledMs=35000] Settle wait after recompiling all lit shaders in milliseconds.
124
+ * @param {number} [options.turns=4] Turn-about pair count.
125
+ * @param {number} [options.fitSeconds=8] Seconds to sample `cardTime` alongside displayed FPS at the end of the full probe.
126
+ * @returns {Promise<void>}
127
+ */
128
+ export async function runSelfProbe({
129
+ query,
130
+ state,
131
+ scene,
132
+ camera,
133
+ renderer,
134
+ post,
135
+ setPost,
136
+ mirror,
137
+ quality,
138
+ presets,
139
+ applyQuality,
140
+ setFarShadow,
141
+ cardTime,
142
+ holdQuality,
143
+ holdPace,
144
+ holdSize,
145
+ resize,
146
+ viewportWidth,
147
+ viewportHeight,
148
+ noteLog,
149
+ hudElement = () => null,
150
+ getWorld,
151
+ bench,
152
+ groundDefineCuts = [],
153
+ lowGroups = DEFAULT_LOW_GROUPS,
154
+ routeLegs = DEFAULT_PROBE_LEGS,
155
+ wait = ms => new Promise(resolve => setTimeout(resolve, ms)),
156
+ clock = () => performance.now(),
157
+ nextFrame = () => new Promise(requestAnimationFrame),
158
+ settleMs = SETTLE_MS,
159
+ loopMs = LOOP_MS,
160
+ rebuiltMs = REBUILT_MS,
161
+ recompiledMs = RECOMPILED_MS,
162
+ turns = TURNS,
163
+ fitSeconds = FIT_SECONDS,
164
+ }) {
165
+ const sampler = createFrameSampler({ getFrame: () => state.frame, wait, clock, loopMs, turns });
166
+ const { shown, shownWithout, byTurns } = sampler;
167
+
168
+ while (state.mode !== 'play') await wait(250);
169
+
170
+ if (query.get('probe') === 'route') {
171
+ await wait(settleMs);
172
+ const world = getWorld();
173
+ const legs = await flyProbeRoute({
174
+ camera,
175
+ setFly: world.setFly,
176
+ placePlayer: world.placePlayer,
177
+ player: world.player,
178
+ ground: (x, z) => world.space.ground(x, z),
179
+ legs: routeLegs,
180
+ wait,
181
+ nextFrame,
182
+ });
183
+ for (const leg of legs) noteLog('note', `probe at ${state.quality}, flown ${leg}`);
184
+ return;
185
+ }
186
+
187
+ holdQuality(true);
188
+ holdPace(true);
189
+
190
+ const stand = parseStandAt(query.get('at'));
191
+ if (stand) {
192
+ const world = getWorld();
193
+ world.setFly(true);
194
+ world.placePlayer(stand.x, stand.z, stand.yaw);
195
+ world.player.y = world.space.ground(stand.x, stand.z) + stand.up;
196
+ world.player.pitch = stand.pitch;
197
+ }
198
+
199
+ await wait(settleMs);
200
+ const mode = query.get('probe');
201
+
202
+ if (mode === 'ground' || mode === 'light') {
203
+ const pieces = scene.getObjectsByProperty('name', 'ground'),
204
+ told = await measureGroundParts(sampler, {
205
+ renderer,
206
+ ground: pieces,
207
+ worn: pieces.map(piece => piece.material),
208
+ lightAlone: mode === 'light',
209
+ wait,
210
+ rebuiltMs,
211
+ defineCuts: groundDefineCuts,
212
+ });
213
+ for (const part of told.split('; ')) noteLog('note', `probe at ${state.quality}: ${part}`);
214
+ } else if (mode === 'passes' && post.on) {
215
+ const { samples, taa } = post,
216
+ smoothed = on => () => {
217
+ setPost(true, samples, on);
218
+ resize();
219
+ };
220
+ noteLog(
221
+ 'note',
222
+ `probe at ${state.quality}: without the smoothing over frames ${await byTurns(smoothed(false), smoothed(taa), rebuiltMs)}`,
223
+ );
224
+ noteLog(
225
+ 'note',
226
+ `probe at ${state.quality}: without the bloom ${await byTurns(
227
+ () => (post.bloom.enabled = false),
228
+ () => (post.bloom.enabled = true),
229
+ )}`,
230
+ );
231
+ } else if (mode === 'count') {
232
+ const counts = async () => [await shown(), await shown(), await shown()].join(' ');
233
+ noteLog(
234
+ 'note',
235
+ `probe at ${state.quality}, ${post.on ? 'through the passes' : 'drawn straight to the screen'}: ${await counts()} frames shown`,
236
+ );
237
+ const next = query.get('then');
238
+ if (next) {
239
+ applyQuality(next);
240
+ await wait(settleMs);
241
+ noteLog(
242
+ 'note',
243
+ `probe, then at ${state.quality} within the visit, ${post.on ? 'through the passes' : 'drawn straight to the screen'}: ${await counts()} frames shown`,
244
+ );
245
+ }
246
+ }
247
+
248
+ if (mode === 'lows') {
249
+ const counts = async () => [await shown(), await shown(), await shown()].join(' '),
250
+ own = presets[state.quality],
251
+ told = [`as it is ${await counts()}`],
252
+ trials = parseLowTrials(query.get('set'), presets, lowGroups);
253
+ for (const [keys, values] of trials) {
254
+ const kept = keys.map(key => own[key]);
255
+ keys.forEach((key, at) => (own[key] = values[at]));
256
+ applyQuality(state.quality);
257
+ if (keys[0] === 'farShadow' && setFarShadow) {
258
+ setFarShadow(values[0]);
259
+ await wait(recompiledMs);
260
+ }
261
+ await wait(settleMs);
262
+ told.push(`with ${keys.map((key, at) => `${key} ${values[at]}`).join(', ')} ${await counts()}`);
263
+ keys.forEach((key, at) => (own[key] = kept[at]));
264
+ }
265
+ applyQuality(state.quality);
266
+ await wait(settleMs);
267
+ told.push(`as it is again ${await counts()}`);
268
+ for (const part of told) noteLog('note', `probe at ${state.quality}: ${part}`);
269
+ }
270
+
271
+ if (mode) {
272
+ holdQuality(false);
273
+ holdPace(false);
274
+ return;
275
+ }
276
+
277
+ await bench(6);
278
+ const whole = await bench(20),
279
+ frames = await shown(),
280
+ shadows = renderer.shadowMap,
281
+ drawn = scene.children.filter(child => child.visible && !child.isLight),
282
+ show = on => {
283
+ for (const child of drawn) child.visible = on;
284
+ };
285
+ const shares = await measureScriptShares({ renderer, scene, camera, getFrame: () => state.frame, wait, clock });
286
+ const meshes = { instanced: [], single: [] };
287
+ scene.traverseVisible(mesh => {
288
+ if (mesh.isMesh) meshes[mesh.isInstancedMesh || mesh.isBatchedMesh ? 'instanced' : 'single'].push(mesh);
289
+ });
290
+ const ground = scene.getObjectsByProperty('name', 'ground'),
291
+ showGround = on => {
292
+ for (const piece of ground) piece.visible = on;
293
+ },
294
+ showKind = (kind, on) => {
295
+ for (const mesh of meshes[kind]) mesh.visible = on;
296
+ },
297
+ hud = hudElement();
298
+ const without = {
299
+ shadowRedraw: await shownWithout(
300
+ () => (shadows.autoUpdate = false),
301
+ () => (shadows.autoUpdate = true),
302
+ ),
303
+ bloom: post.on
304
+ ? await shownWithout(
305
+ () => (post.bloom.enabled = false),
306
+ () => (post.bloom.enabled = true),
307
+ )
308
+ : frames,
309
+ hud: hud
310
+ ? await shownWithout(
311
+ () => (hud.hidden = true),
312
+ () => (hud.hidden = false),
313
+ )
314
+ : frames,
315
+ instanced: await shownWithout(
316
+ () => showKind('instanced', false),
317
+ () => showKind('instanced', true),
318
+ ),
319
+ single: await shownWithout(
320
+ () => showKind('single', false),
321
+ () => showKind('single', true),
322
+ ),
323
+ scene: await shownWithout(
324
+ () => show(false),
325
+ () => show(true),
326
+ ),
327
+ ground: await shownWithout(
328
+ () => showGround(false),
329
+ () => showGround(true),
330
+ ),
331
+ };
332
+ const calls = [
333
+ await measureWithMoreCalls(sampler, { scene, camera, count: 100, wait, rebuiltMs }),
334
+ await measureWithMoreCalls(sampler, { scene, camera, count: 200, wait, rebuiltMs }),
335
+ ];
336
+ holdSize(viewportWidth(), viewportHeight(), renderer.domElement.width / viewportWidth() / 2);
337
+ const halfSize = await shown();
338
+ holdSize(0);
339
+ const flat = new THREE.MeshBasicMaterial({ color: 0x6b6a4a }),
340
+ worn = ground.map(piece => piece.material);
341
+ const groundFlat = await byTurns(
342
+ () => ground.forEach(piece => (piece.material = flat)),
343
+ () => ground.forEach((piece, at) => (piece.material = worn[at])),
344
+ );
345
+ flat.dispose();
346
+ const groundLight = await measureGroundParts(sampler, {
347
+ renderer,
348
+ ground,
349
+ worn,
350
+ wait,
351
+ rebuiltMs,
352
+ defineCuts: groundDefineCuts,
353
+ });
354
+ const reads = await measureAnisotropicReads(sampler, { renderer, scene });
355
+ const worlds = [],
356
+ ownScale = post.scale;
357
+ if (post.on) {
358
+ for (const share of new Set([quality.worldLeast ?? ownScale, 1])) {
359
+ if (share === ownScale) continue;
360
+ const drawnAs = to => () => {
361
+ post.scale = to;
362
+ resize();
363
+ };
364
+ worlds.push(`at ${share} of each side ${await byTurns(drawnAs(share), drawnAs(ownScale))}`);
365
+ }
366
+ }
367
+ const lights = await measureDimmedLights(sampler, { scene });
368
+ const occlusion = post.on
369
+ ? `the occlusion pass left empty ${await byTurns(
370
+ () => (post.aoScene.visible = false),
371
+ () => (post.aoScene.visible = true),
372
+ )}`
373
+ : 'no occlusion pass under this preset';
374
+ const grounds = `the ground in one flat colour ${groundFlat}; ${groundLight}`,
375
+ upscaled = `the world, drawn at ${ownScale} of each side: ${worlds.join('; ') || 'at no other size under this preset'}`;
376
+ const mirrored = await measureMirror(sampler, { quality, mirror });
377
+ const passes = await measurePostPasses(sampler, { post, setPost, resize, frames, wait, rebuiltMs });
378
+ holdQuality(false);
379
+ holdPace(false);
380
+ const told = [
381
+ `${frames} frames shown a second; handed over back to back a frame is ${whole.ms} ms (script ${whole.cpu}: update ${whole.update}, ` +
382
+ `draw ${whole.draw}), ${whole.calls} calls, ${whole.tris} triangles`,
383
+ `frames shown without the shadows' redraw ${without.shadowRedraw}, the bloom ${without.bloom}, the HUD ${without.hud}, the instanced ` +
384
+ `meshes ${without.instanced}, the single meshes ${without.single}, the ground ${without.ground}, anything in the scene ${without.scene}; ` +
385
+ `with a hundred draw calls more ${calls[0]}, with two hundred ${calls[1]}`,
386
+ `at half the picture's size ${halfSize}`,
387
+ grounds,
388
+ `${lights}; ${occlusion}`,
389
+ reads,
390
+ upscaled,
391
+ `${mirrored}; ${passes}`,
392
+ `the script's time in a frame's passes: ${shares}`,
393
+ ];
394
+ for (const [at, part] of told.entries()) noteLog('note', `probe ${at + 1} at ${state.quality}, ${whole.px}: ${part}`);
395
+
396
+ const timed = [];
397
+ for (let second = 0; second < fitSeconds; second++) {
398
+ const from = state.frame;
399
+ await wait(1000);
400
+ timed.push(`${cardTime()?.toFixed(1) ?? '?'} ms at ${state.frame - from}`);
401
+ }
402
+ noteLog(
403
+ 'note',
404
+ `probe, the fit's timing of the card's frame in each of ${fitSeconds} seconds, with the frames shown in it: ${timed.join(', ')}`,
405
+ );
406
+ }
@@ -285,3 +285,33 @@ export const seaBody = (water = {}) => {
285
285
  export const seaOpacity = (water = {}) => `/* glsl */
286
286
  opacity = mix(0.06, 0.95, 1.0 - dot(exp(-${glslVec3({ ...SEA_WATER, ...water }.absorption)} * opticalPath), vec3(0.2, 0.5, 0.3)));
287
287
  opacity = mix(opacity, 1.0, smoothstep(6.0, 7.8, waterline));`;
288
+
289
+ const glslStretch = ([along, across]) =>
290
+ along === across ? `vec2(${glslFloat(along)})` : `vec2(${glslFloat(along)}, ${glslFloat(across)})`;
291
+ const glslAcross = across => (across < 0 ? `-pileRow.z * ${glslFloat(-across)}` : `pileRow.z * ${glslFloat(across)}`);
292
+
293
+ /**
294
+ * Generates the GLSL snippet for water ripples around rows of pier/jetty piles (`uPileRows`), returning an empty string
295
+ * when no pile rows are configured so materials without piles compile no loop.
296
+ * @param {object|null} options Pile-row shader options (`PileRowsOptions`).
297
+ * @returns {string}
298
+ */
299
+ export function pileRowsGlsl(options) {
300
+ if (!options) return '';
301
+ const { rows, along, halfWidth, firstPile, pitch, pairs, gap, pileRange, spots = [], reach = 160, strength = 0.19 } = options;
302
+ const spotLines = spots.map(
303
+ spot =>
304
+ ` pileRipples += ripple(q - vec2(${glslFloat(spot.along)}, ${glslAcross(spot.across)}), ${glslStretch(spot.stretch)}, ${glslFloat(spot.range)}, ${glslFloat(spot.phase)});\n`,
305
+ );
306
+ return ` if (uHasDepth > 0.5 && dist < ${glslFloat(reach)}) {
307
+ vec2 pileRipples = vec2(0.0);
308
+ for (int i = 0; i < ${rows}; i++) {
309
+ vec4 pileRow = uPileRows[i]; vec2 d = vec2(cos(pileRow.w - 10.0), sin(pileRow.w - 10.0)), r = vW.xz - pileRow.xy, q = vec2(dot(r, d), d.x * r.y - d.y * r.x);
310
+ if (pileRow.w < 0.5 || abs(q.y) > ${glslFloat(halfWidth)} || q.x < ${glslFloat(along[0])} || q.x > ${glslFloat(along[1])}) continue;
311
+ float pile = clamp(floor((q.x - ${glslFloat(firstPile)}) / ${glslFloat(pitch)} + 0.5), 0.0, ${glslFloat(pairs - 1)});
312
+ pileRipples += ripple(q - vec2(${glslFloat(firstPile)} + ${glslFloat(pitch)} * pile, sign(q.y) * ${glslFloat(gap)}), vec2(1.0), ${glslFloat(pileRange)}, pile);
313
+ ${spotLines.join('')} }
314
+ g += pileRipples * ${glslFloat(strength)} * OW(8.0);
315
+ }
316
+ `;
317
+ }
@@ -4,10 +4,10 @@
4
4
  */
5
5
 
6
6
  import * as THREE from 'three';
7
- import { FOAM_GLSL, SEA_WAVES, seaBody, seaOpacity } from './sea-shaders.js';
7
+ import { FOAM_GLSL, SEA_WAVES, pileRowsGlsl, seaBody, seaOpacity } from './sea-shaders.js';
8
8
  import { RAIN_GLSL, RAIN_PARS } from './rain-rings.js';
9
9
  import { STREAM_FLOW_GLSL } from './stream-flow.js';
10
- import { glslFloat, glslVec3 } from './glsl-literal.js';
10
+ import { glslVec3 } from './glsl-literal.js';
11
11
  import { DEEP, FAR } from '../geometry/stream.js';
12
12
 
13
13
  /** Default linear RGB colours and Beer-Lambert absorption for open water and streams. */
@@ -53,33 +53,6 @@ export const REFLECTION_SMEAR = 2 * 0.75 * REFLECTION_SMEAR_MOST;
53
53
  * @property {number} [strength] - How much the ripples bend the surface's normal (0.19).
54
54
  */
55
55
 
56
- const glslStretch = ([along, across]) =>
57
- along === across ? `vec2(${glslFloat(along)})` : `vec2(${glslFloat(along)}, ${glslFloat(across)})`;
58
- const glslAcross = across => (across < 0 ? `-pileRow.z * ${glslFloat(-across)}` : `pileRow.z * ${glslFloat(across)}`);
59
-
60
- // The ripples of the rows of piles, written from the options so that a material with none compiles no loop. A row's uniform is
61
- // (anchor x, anchor z, side, heading + 10); a w under 0.5 turns the row off. Rows start as a Vector4's defaults (0, 0, 0, 1):
62
- // on, at the origin, so a world places every row it asks for.
63
- function pileRowsGlsl(options) {
64
- if (!options) return '';
65
- const { rows, along, halfWidth, firstPile, pitch, pairs, gap, pileRange, spots = [], reach = 160, strength = 0.19 } = options;
66
- const spotLines = spots.map(
67
- spot =>
68
- ` pileRipples += ripple(q - vec2(${glslFloat(spot.along)}, ${glslAcross(spot.across)}), ${glslStretch(spot.stretch)}, ${glslFloat(spot.range)}, ${glslFloat(spot.phase)});\n`,
69
- );
70
- return ` if (uHasDepth > 0.5 && dist < ${glslFloat(reach)}) {
71
- vec2 pileRipples = vec2(0.0);
72
- for (int i = 0; i < ${rows}; i++) {
73
- vec4 pileRow = uPileRows[i]; vec2 d = vec2(cos(pileRow.w - 10.0), sin(pileRow.w - 10.0)), r = vW.xz - pileRow.xy, q = vec2(dot(r, d), d.x * r.y - d.y * r.x);
74
- if (pileRow.w < 0.5 || abs(q.y) > ${glslFloat(halfWidth)} || q.x < ${glslFloat(along[0])} || q.x > ${glslFloat(along[1])}) continue;
75
- float pile = clamp(floor((q.x - ${glslFloat(firstPile)}) / ${glslFloat(pitch)} + 0.5), 0.0, ${glslFloat(pairs - 1)});
76
- pileRipples += ripple(q - vec2(${glslFloat(firstPile)} + ${glslFloat(pitch)} * pile, sign(q.y) * ${glslFloat(gap)}), vec2(1.0), ${glslFloat(pileRange)}, pile);
77
- ${spotLines.join('')} }
78
- g += pileRipples * ${glslFloat(strength)} * OW(8.0);
79
- }
80
- `;
81
- }
82
-
83
56
  /**
84
57
  * Place row `index` of a water material's rows of piles (see {@link PileRowsOptions}): its seaward anchor (`x`, `z`, metres),
85
58
  * the `side` (+1 or -1) its extra ripple spots lie to, and its `heading` (radians) towards the shore.
@@ -381,7 +354,7 @@ ${pileRowsGlsl(pileRows)} #ifdef SEA
381
354
  });
382
355
  if (pileRows) waterMat.uniforms.uPileRows = { value: Array.from({ length: pileRows.rows }, () => new THREE.Vector4()) };
383
356
  Object.assign(waterMat.uniforms, wakeUniforms, cloudUniforms);
384
- const streamMat = waterMat.clone();
357
+ const streamMat = cloneWaterMaterial(waterMat);
385
358
  Object.assign(streamMat.uniforms, wakeUniforms, cloudUniforms);
386
359
  streamMat.uniforms.uHasDepth.value = 0;
387
360
  streamMat.uniforms.uRefl = { value: null };
@@ -392,6 +365,33 @@ ${pileRowsGlsl(pileRows)} #ifdef SEA
392
365
  return { waterMat, streamMat, waterMaterials };
393
366
  }
394
367
 
368
+ const isRenderTargetUniform = v => Boolean(v?.isRenderTargetTexture || (Array.isArray(v) && v.some(x => x?.isRenderTargetTexture)));
369
+
370
+ // Clone a water ShaderMaterial without feeding render-target textures (such as `uRefl`) into Three's
371
+ // `UniformsUtils.clone`, which warns and nulls them; skipped uniforms are shared by reference.
372
+ function cloneWaterMaterial(source, shareAll = false) {
373
+ const saved = source.uniforms,
374
+ shared = [];
375
+ if (shareAll) source.uniforms = {};
376
+ else {
377
+ const filtered = {};
378
+ for (const [key, entry] of Object.entries(saved)) {
379
+ if (isRenderTargetUniform(entry?.value)) shared.push([key, entry]);
380
+ else filtered[key] = entry;
381
+ }
382
+ if (shared.length) source.uniforms = filtered;
383
+ }
384
+ let variant;
385
+ try {
386
+ variant = source.clone();
387
+ } finally {
388
+ source.uniforms = saved;
389
+ }
390
+ if (shareAll) variant.uniforms = { ...saved };
391
+ else for (const [key, entry] of shared) variant.uniforms[key] = entry;
392
+ return variant;
393
+ }
394
+
395
395
  function trackWaterVariant(source, variant) {
396
396
  const list = source._waterMaterials;
397
397
  if (list) {
@@ -402,9 +402,8 @@ function trackWaterVariant(source, variant) {
402
402
 
403
403
  // Preserve the live lighting, clock and wake uniforms when specializing a water material.
404
404
  function waterVariant(material) {
405
- const variant = material.clone();
405
+ const variant = cloneWaterMaterial(material, true);
406
406
  Object.assign(variant.defaultAttributeValues, material.defaultAttributeValues);
407
- Object.assign(variant.uniforms, material.uniforms);
408
407
  trackWaterVariant(material, variant);
409
408
  return variant;
410
409
  }
@@ -467,7 +466,7 @@ const SHARED = [
467
466
  /** Clone open-water and stream materials for another land while sharing global lighting, wind and wake uniforms. */
468
467
  export function landWater(waterMat, depth, rect, level, sea = null) {
469
468
  const make = (hasDepth, own) => {
470
- const variant = waterMat.clone();
469
+ const variant = cloneWaterMaterial(waterMat);
471
470
  for (const uniformName of SHARED) {
472
471
  if (waterMat.uniforms[uniformName]) variant.uniforms[uniformName] = waterMat.uniforms[uniformName];
473
472
  }
@@ -1,10 +1,23 @@
1
1
  const SOFTWARE = /swiftshader|llvmpipe|software|basic render/i;
2
2
  const INTEGRATED = /intel|mali|adreno|powervr/i;
3
3
 
4
- // A first guess at the preset a device can hold, from what the browser tells of it, before any frame is timed: 'low' where it
5
- // draws in software or has little memory, 'medium' for a device held in the hand, 'high' for a desk with the cores, the memory
6
- // and more than an integrated chip. `device` is its description (`readDevice`); or `handheld`, `memoryGB` and `cores` are given
7
- // apart, as functions.
4
+ /**
5
+ * First guess at the quality preset a device can hold, from what the browser reports before any frame is timed:
6
+ * `'low'` where it draws in software or has little memory, `'medium'` for a handheld device with enough memory,
7
+ * and `'high'` for a desktop with sufficient cores, memory, and a discrete GPU.
8
+ *
9
+ * @param {object} options
10
+ * @param {{ getContext: () => WebGLRenderingContext }} options.renderer Active WebGL renderer.
11
+ * @param {import('./device.js').Device | null} [options.device=null] Device description from `readDevice` or `describeDevice`.
12
+ * @param {() => boolean} [options.handheld] Override for whether the device is handheld (defaults to `device.handheld`).
13
+ * @param {() => number | undefined} [options.memoryGB] Override for device memory in GB (defaults to `device.memoryGB`).
14
+ * @param {() => number | undefined} [options.cores] Override for logical core count (defaults to `device.cores`).
15
+ * @param {number} [options.smallMemory=2] Memory at or below this (GB) always selects `'low'`.
16
+ * @param {number} [options.phoneMemory=4] Handheld memory at or below this (GB) selects `'low'`.
17
+ * @param {number} [options.desktopMemory=8] Desktop memory below this (GB) selects `'medium'`.
18
+ * @param {number} [options.desktopCores=8] Desktop cores below this selects `'medium'`.
19
+ * @returns {{ deviceQuality: () => 'low' | 'medium' | 'high', drawnInSoftware: () => boolean }}
20
+ */
8
21
  export function createDeviceQuality({
9
22
  renderer,
10
23
  device = null,
@@ -36,3 +49,61 @@ export function createDeviceQuality({
36
49
  }
37
50
  return { deviceQuality, drawnInSoftware };
38
51
  }
52
+
53
+ /**
54
+ * Ground render order for a device: on a performance-aimed device (a phone), the ground is drawn after
55
+ * opaque buildings, trees, and figures so depth testing rejects covered ground pixels instead of shading them.
56
+ * Quality-aimed devices (desktops and tablets) keep render order `0`.
57
+ *
58
+ * @param {import('./device.js').Device | null | undefined} device Device description from `readDevice` or `describeDevice`.
59
+ * @param {number} [performanceOrder=5] Render order used on performance-aimed devices.
60
+ * @returns {number}
61
+ */
62
+ export function groundRenderOrder(device, performanceOrder = 5) {
63
+ return device?.aim === 'performance' ? performanceOrder : 0;
64
+ }
65
+
66
+ /**
67
+ * Builds the active preset table for a device without mutating the base presets. On a performance-aimed
68
+ * device, matching entries from `performanceOverrides` are merged into the cloned preset objects; on a
69
+ * quality-aimed device, the base presets are kept as-is.
70
+ *
71
+ * @template {Record<string, Record<string, unknown>>} T
72
+ * @param {T} basePresets Base preset definitions (for example `{ low, medium, high }`).
73
+ * @param {import('./device.js').Device | null | undefined} device Device description from `readDevice` or `describeDevice`.
74
+ * @param {Partial<Record<keyof T, Record<string, unknown>>>} [performanceOverrides={}] Per-preset overrides applied when `device.aim === 'performance'`.
75
+ * @returns {T}
76
+ */
77
+ export function resolveDevicePresets(basePresets, device, performanceOverrides = {}) {
78
+ const perf = device?.aim === 'performance';
79
+ const resolved = {};
80
+ for (const name of Object.keys(basePresets)) {
81
+ const override = perf ? performanceOverrides[name] : null;
82
+ resolved[name] = override ? { ...basePresets[name], ...override } : { ...basePresets[name] };
83
+ }
84
+ return /** @type {T} */ (resolved);
85
+ }
86
+
87
+ /**
88
+ * Chooses the post-processing pipeline settings for an active quality preset and display density.
89
+ * A preset without post-processing draws directly to the canvas only if the canvas itself was created
90
+ * with antialiasing (`canvasSmooth`); otherwise it stays on the post-processing path with multisampled
91
+ * scene targets (capped to 2x on high-density displays where four device pixels already cover each CSS pixel).
92
+ *
93
+ * @param {object} options
94
+ * @param {{ post?: boolean, samples?: number, taa?: boolean }} options.preset Active quality preset figures.
95
+ * @param {boolean} [options.canvasSmooth=false] Whether the WebGL canvas was created with `antialias: true`.
96
+ * @param {number} [options.pixelRatio=1] Current display pixel ratio (`devicePixelRatio`).
97
+ * @param {number} [options.highDensityThreshold=1.75] Pixel ratio at or above which >2 MSAA samples drop to 2.
98
+ * @returns {{ enabled: boolean, samples: number, taa: boolean }}
99
+ */
100
+ export function choosePostPipeline({ preset, canvasSmooth = false, pixelRatio = 1, highDensityThreshold = 1.75 }) {
101
+ const direct = !preset.post && canvasSmooth;
102
+ const rawSamples = preset.post ? (preset.samples ?? 0) : 4;
103
+ const samples = rawSamples > 2 && (pixelRatio || 1) >= highDensityThreshold ? 2 : rawSamples;
104
+ return {
105
+ enabled: !direct,
106
+ samples,
107
+ taa: Boolean(preset.post && preset.taa),
108
+ };
109
+ }