roamwright 0.58.0 → 0.60.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,410 @@
1
+ /**
2
+ * Pipeline warm-up: hands the card, one draw at a time and only while the page waits, every program a scene's first frame
3
+ * draws into its target (and any full-screen post-processing passes into theirs), so the card builds its pipelines behind
4
+ * the loading bar instead of in that frame's wait.
5
+ *
6
+ * On Metal (through ANGLE) and D3D12 a program is linked when `renderer.compile()` says so, but the card's driver builds the
7
+ * pipeline of a program on the first draw that binds it to a framebuffer's formats and a vertex layout: about 40 ms a
8
+ * pipeline on an M5 Pro, a hundred of them on a world's first frame, and that frame waits for each. Drawing them all at
9
+ * once does not shorten the wait: every synchronous call the page makes afterwards (a program's first uniform lookup, an
10
+ * upload that needs its buffer back) then waits for the whole queue. So this pass draws one representative object per
11
+ * (target format, program, vertex layout) — or one full-screen quad pass per (target format, program) — into a one-pixel
12
+ * scissor of its real target, puts a fence after it, and draws the next only once the card has passed the fence. The page's
13
+ * own calls then wait for one pipeline at most, and the pipelines build while the page waits on workers or on the links of
14
+ * programs still compiling. Nothing shows: one pixel of a target the first real frame draws over, and the pass is stopped
15
+ * (`stop`) before that frame is drawn.
16
+ *
17
+ * @module
18
+ */
19
+
20
+ import * as THREE from 'three';
21
+ import { RENDER_LAYERS } from './context.js';
22
+ import { describeRenderTargetFormat } from './target-format.js';
23
+ import { createNextTask } from '../runtime/next-task.js';
24
+
25
+ const FENCE_GIVE_UP_MS = 4000; // a fence not passed by then is not waited for (a page in the background, a lost context)
26
+ const FENCE_POLL_MS = 2; // milliseconds between non-blocking fence checks while a pipeline builds
27
+
28
+ // Whether the card can be handed the object at all: a mesh, points, a line or a sprite with a material to show, positions
29
+ // to draw and a range and a count that draw them.
30
+ function drawable(object) {
31
+ if (!(object.isMesh || object.isPoints || object.isLine || object.isSprite)) return false;
32
+ const material = object.material;
33
+ if (!material || material.visible === false) return false;
34
+ const geometry = object.geometry;
35
+ if (!geometry?.attributes?.position?.count || geometry.drawRange.count === 0) return false;
36
+ return !object.isInstancedMesh || object.count > 0;
37
+ }
38
+
39
+ // The programs a material draws with (Three keeps one per output colour space), or null while any of them is still linking:
40
+ // a draw that reached a linking program would wait for its link.
41
+ function linkedPrograms(renderer, material) {
42
+ const list = [];
43
+ const materials = Array.isArray(material) ? material : [material];
44
+ for (let i = 0; i < materials.length; i++) {
45
+ const one = materials[i];
46
+ if (one.visible === false) continue;
47
+ const variants = renderer.properties.get(one).programs;
48
+ if (!variants) return null;
49
+ for (const program of variants.values()) {
50
+ if (!program.isReady()) return null;
51
+ list.push(program);
52
+ }
53
+ }
54
+ return list.length ? list : null;
55
+ }
56
+
57
+ // What the card's pipeline depends on in a geometry and its object: each attribute's name, size, store and normalisation,
58
+ // an index buffer, and the object's kind (instanced, skinned, batched), which change the vertex stage or its bindings.
59
+ function vertexLayout(geometry, object) {
60
+ const attributes = geometry.attributes;
61
+ let key = '';
62
+ for (const name in attributes) {
63
+ const attribute = attributes[name];
64
+ const store = attribute.array ?? attribute.data?.array;
65
+ key += (key ? ',' : '') + name + attribute.itemSize + (attribute.normalized ? 'n' : '') + (store?.constructor?.name ?? attribute.type);
66
+ }
67
+ if (geometry.index) key += '|index';
68
+ if (object.isInstancedMesh) key += '|instanced';
69
+ if (object.isSkinnedMesh) key += '|skinned';
70
+ if (object.isBatchedMesh) key += '|batched';
71
+ return key;
72
+ }
73
+
74
+ function targetFormatKey(into) {
75
+ return into ? describeRenderTargetFormat(into).key : 'screen';
76
+ }
77
+
78
+ function programIds(programs) {
79
+ let ids = '';
80
+ for (let i = 0; i < programs.length; i++) ids += (i ? ',' : '') + programs[i].id;
81
+ return ids;
82
+ }
83
+
84
+ /**
85
+ * Create the pipeline warm-up of one scene.
86
+ *
87
+ * @param {object} options
88
+ * @param {THREE.WebGLRenderer} options.renderer The renderer the scene is drawn with.
89
+ * @param {THREE.Scene} options.scene The scene whose first frame is prepared.
90
+ * @param {THREE.Camera} options.camera The camera the first frame is drawn with.
91
+ * @param {() => THREE.WebGLRenderTarget | null} options.target Read at each enqueue and draw: the target the scene's frame
92
+ * is drawn into (`null`: the screen). The pipelines are built for its attachment formats, so they must be the frame's own.
93
+ * @param {(program: object) => void} [options.useProgram] Looks a program's uniforms up before its first draw (a
94
+ * synchronous round trip, made while the card is idle); without it Three does it inside the draw.
95
+ * @param {() => void} [options.place] Places the scene's world matrices before objects are picked by the view, for a scene
96
+ * that keeps its own matrices rather than Three's automatic ones.
97
+ * @param {number} [options.layer=RENDER_LAYERS.warmDraw] The layer lent, for the length of one draw, to the object drawn
98
+ * and to the lights the view sees.
99
+ * @returns {{
100
+ * enqueue: (options?: object) => number,
101
+ * enqueuePasses: (entries: Array<[THREE.Material, THREE.WebGLRenderTarget | null]>) => number,
102
+ * stop: () => void,
103
+ * dispose: () => void,
104
+ * readonly busy: boolean,
105
+ * }}
106
+ * `enqueue({ view = camera, cull = true })` queues one representative of every linked (target format, program, vertex
107
+ * layout) the scene shows (only those the view's frustum reaches, when `cull`) and hands them over from now on; it says
108
+ * how many it queued.
109
+ * `enqueuePasses(entries)` queues one full-screen quad draw per linked (target format, program) from `[material, target]`
110
+ * pairs (for post-processing passes such as `postMaterials()`).
111
+ * `stop()` drops what is queued: nothing more is drawn once the draw in flight has been passed by the card.
112
+ * `dispose()` stops the pass and releases its internal full-screen quad geometry.
113
+ * `busy` says whether a draw is queued or in flight.
114
+ */
115
+ export function createPipelineWarmup({ renderer, scene, camera, target, useProgram, place, layer = RENDER_LAYERS.warmDraw }) {
116
+ const nextTask = createNextTask(); // checks a fence on the next task without a nested setTimeout floor
117
+ const warmMask = 1 << layer;
118
+ let gl = null; // the context, taken at the first draw: until then the renderer may still be a stand-in
119
+ const drawn = new Set(); // the (target format, programs, layout) combinations already queued or handed over
120
+ const queue = [];
121
+ const lights = []; // the lights the view saw when `enqueue` last ran
122
+ const lightMasks = [];
123
+ const frustum = new THREE.Frustum();
124
+ const viewProjection = new THREE.Matrix4();
125
+ const savedViewport = new THREE.Vector4();
126
+ const savedScissor = new THREE.Vector4();
127
+ let quad = null; // lazy full-screen quad for `enqueuePasses`
128
+ let quadScene = null;
129
+ let quadCamera = null;
130
+ let fence = null; // the fence after the last burst of draws, until the card passes it
131
+ let running = false;
132
+ let stopped = false;
133
+ let burstSize = 1; // draws handed over per fence; kept at 1 unless the caller expects a longer main-thread wait
134
+
135
+ // Resolves once the card passed the last draw's fence, asked without blocking: at once when there is none.
136
+ function cardPassed() {
137
+ const waiting = fence;
138
+ fence = null;
139
+ if (!waiting) return Promise.resolve();
140
+ return new Promise(resolve => {
141
+ const since = performance.now();
142
+ const ask = () => {
143
+ const passed = gl.clientWaitSync(waiting, 0, 0) !== gl.TIMEOUT_EXPIRED;
144
+ if (!passed && performance.now() - since < FENCE_GIVE_UP_MS) {
145
+ setTimeout(ask, FENCE_POLL_MS);
146
+ return;
147
+ }
148
+ gl.deleteSync(waiting);
149
+ resolve();
150
+ };
151
+ nextTask(ask);
152
+ });
153
+ }
154
+
155
+ // The lights are collected by `enqueue`; a light shown or hidden since changes the programs Three picks, so the view's
156
+ // lights are collected again when one of them no longer shows.
157
+ function lightsStillShow(view) {
158
+ for (let i = 0; i < lights.length; i++) {
159
+ for (let object = lights[i]; object; object = object.parent) {
160
+ if (object.visible === false) {
161
+ collectLights(view);
162
+ return;
163
+ }
164
+ }
165
+ }
166
+ }
167
+
168
+ function collectLights(view) {
169
+ lights.length = 0;
170
+ scene.traverseVisible(object => {
171
+ if (object.isLight && object.layers.test(view.layers)) lights.push(object);
172
+ });
173
+ }
174
+
175
+ // Runs one 1x1-scissored draw into `into` (null: screen) and restores all renderer state.
176
+ function drawIntoPixel(into, draw) {
177
+ gl ??= renderer.getContext();
178
+ const previous = renderer.getRenderTarget();
179
+ const face = renderer.getActiveCubeFace();
180
+ const mip = renderer.getActiveMipmapLevel();
181
+ const autoClear = renderer.autoClear;
182
+ const shadowAuto = renderer.shadowMap.autoUpdate;
183
+ const shadowNeeds = renderer.shadowMap.needsUpdate;
184
+ let scissorTest;
185
+ try {
186
+ // nothing cleared and no shadow map drawn: the first real frame does both, whole
187
+ renderer.autoClear = false;
188
+ renderer.shadowMap.autoUpdate = false;
189
+ renderer.shadowMap.needsUpdate = false;
190
+ if (into) {
191
+ savedViewport.copy(into.viewport);
192
+ savedScissor.copy(into.scissor);
193
+ scissorTest = into.scissorTest;
194
+ into.viewport.set(0, 0, 1, 1);
195
+ into.scissor.set(0, 0, 1, 1);
196
+ into.scissorTest = true;
197
+ renderer.setRenderTarget(into);
198
+ } else {
199
+ renderer.setRenderTarget(null);
200
+ renderer.getViewport(savedViewport);
201
+ renderer.getScissor(savedScissor);
202
+ scissorTest = renderer.getScissorTest();
203
+ renderer.setViewport(0, 0, 1, 1);
204
+ renderer.setScissor(0, 0, 1, 1);
205
+ renderer.setScissorTest(true);
206
+ }
207
+ draw();
208
+ } finally {
209
+ renderer.autoClear = autoClear;
210
+ renderer.shadowMap.autoUpdate = shadowAuto;
211
+ renderer.shadowMap.needsUpdate = shadowNeeds;
212
+ if (into) {
213
+ into.viewport.copy(savedViewport);
214
+ into.scissor.copy(savedScissor);
215
+ into.scissorTest = scissorTest;
216
+ } else {
217
+ renderer.setViewport(savedViewport);
218
+ renderer.setScissor(savedScissor);
219
+ renderer.setScissorTest(scissorTest);
220
+ }
221
+ renderer.setRenderTarget(previous, face, mip);
222
+ }
223
+ }
224
+
225
+ // Hands the card one scene object into a pixel of the target, with the view and the scene's lights lent to the warm
226
+ // layer for the length of the draw, and everything put back after it.
227
+ function handOverObject(item) {
228
+ const { object, view } = item;
229
+ if (!drawable(object)) return false;
230
+ const into = target();
231
+ lightsStillShow(view);
232
+ const viewMask = view.layers.mask;
233
+ const objectMask = object.layers.mask;
234
+ const culled = object.frustumCulled;
235
+ for (let i = 0; i < lights.length; i++) {
236
+ lightMasks[i] = lights[i].layers.mask;
237
+ lights[i].layers.mask |= warmMask;
238
+ }
239
+ view.layers.mask = warmMask;
240
+ object.layers.mask |= warmMask;
241
+ object.frustumCulled = false; // drawn wherever it stands: the card builds the pipeline before it clips anything
242
+ try {
243
+ drawIntoPixel(into, () => renderer.render(scene, view));
244
+ } finally {
245
+ view.layers.mask = viewMask;
246
+ object.layers.mask = objectMask;
247
+ object.frustumCulled = culled;
248
+ for (let i = 0; i < lights.length; i++) lights[i].layers.mask = lightMasks[i];
249
+ }
250
+ return true;
251
+ }
252
+
253
+ // Hands the card one full-screen pass material into its own target.
254
+ function handOverPass(item) {
255
+ const { material, into } = item;
256
+ if (!material || material.visible === false) return false;
257
+ if (!quad) {
258
+ quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), null);
259
+ quad.frustumCulled = false;
260
+ quadScene = new THREE.Scene();
261
+ quadScene.add(quad);
262
+ quadCamera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
263
+ }
264
+ quad.material = material;
265
+ try {
266
+ drawIntoPixel(into, () => renderer.render(quadScene, quadCamera));
267
+ } finally {
268
+ quad.material = null;
269
+ }
270
+ return true;
271
+ }
272
+
273
+ // Hands over up to `burstSize` queued draws per fence. Uniform lookups (`useProgram`) run for the whole burst before
274
+ // any draw is submitted so a synchronous lookup never stalls behind an earlier draw in the same burst.
275
+ const burst = [];
276
+ function handNext() {
277
+ if (stopped || !queue.length) {
278
+ running = false;
279
+ return;
280
+ }
281
+ burst.length = 0;
282
+ while (burst.length < burstSize && queue.length) {
283
+ const item = queue.shift();
284
+ const ready = item.kind === 'pass' ? item.material && item.material.visible !== false : drawable(item.object);
285
+ if (ready) burst.push(item);
286
+ }
287
+ if (!burst.length) {
288
+ running = false;
289
+ return;
290
+ }
291
+ if (useProgram) {
292
+ for (let i = 0; i < burst.length; i++) {
293
+ const programs = burst[i].programs;
294
+ for (let j = 0; j < programs.length; j++) useProgram(programs[j]);
295
+ }
296
+ }
297
+ let issued = false;
298
+ for (let i = 0; i < burst.length; i++) {
299
+ const item = burst[i];
300
+ if (item.kind === 'pass' ? handOverPass(item) : handOverObject(item)) issued = true;
301
+ }
302
+ burst.length = 0;
303
+ if (!issued) {
304
+ running = false;
305
+ return;
306
+ }
307
+ gl ??= renderer.getContext();
308
+ fence = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0);
309
+ gl.flush();
310
+ cardPassed().then(handNext);
311
+ }
312
+
313
+ function startPump() {
314
+ if (!queue.length) return;
315
+ stopped = false;
316
+ if (!running) {
317
+ running = true;
318
+ handNext();
319
+ }
320
+ }
321
+
322
+ /**
323
+ * Queue one representative of every linked (target format, program, vertex layout) the scene shows and hand them over.
324
+ *
325
+ * @param {object} [options]
326
+ * @param {THREE.Camera} [options.view=camera] The view whose lights and layers the first frame is drawn with.
327
+ * @param {boolean} [options.cull=true] Queue only what the view's frustum reaches; without it, everything the scene shows.
328
+ * @param {number} [options.batch=1] Maximum draws submitted before waiting on a fence; higher values keep the card busy
329
+ * across a long main-thread task, with all uniform lookups in a burst run before any draw is submitted.
330
+ * @returns {number} How many combinations were queued.
331
+ */
332
+ function enqueue({ view = camera, cull = true, batch = 1 } = {}) {
333
+ burstSize = Math.max(1, batch | 0);
334
+ place?.();
335
+ const formats = targetFormatKey(target());
336
+ if (cull) {
337
+ view.updateMatrixWorld();
338
+ viewProjection.multiplyMatrices(view.projectionMatrix, view.matrixWorldInverse);
339
+ frustum.setFromProjectionMatrix(viewProjection);
340
+ }
341
+ collectLights(view);
342
+ let count = 0;
343
+ scene.traverseVisible(object => {
344
+ if (!drawable(object) || !object.layers.test(view.layers)) return;
345
+ if (cull && object.frustumCulled && !frustum.intersectsObject(object)) return;
346
+ const programs = linkedPrograms(renderer, object.material);
347
+ if (!programs) return;
348
+ const key = formats + '|' + programIds(programs) + '|' + vertexLayout(object.geometry, object);
349
+ if (drawn.has(key)) return; // queued already, or handed over
350
+ drawn.add(key);
351
+ queue.push({ kind: 'object', object, view, programs, key });
352
+ count++;
353
+ });
354
+ startPump();
355
+ return count;
356
+ }
357
+
358
+ /**
359
+ * Queue one full-screen quad draw per linked (target format, program) from `[material, target]` entries (such as
360
+ * `postMaterials()`).
361
+ *
362
+ * @param {Array<[THREE.Material, THREE.WebGLRenderTarget | null]>} entries Pass materials paired with their targets.
363
+ * @param {object} [options]
364
+ * @param {number} [options.batch=1] Maximum draws submitted per fence.
365
+ * @returns {number} How many pass pipelines were queued.
366
+ */
367
+ function enqueuePasses(entries, { batch = 1 } = {}) {
368
+ burstSize = Math.max(1, batch | 0);
369
+ let count = 0;
370
+ for (let i = 0; i < entries.length; i++) {
371
+ const [material, into = null] = entries[i];
372
+ if (!material || material.visible === false) continue;
373
+ const programs = linkedPrograms(renderer, material);
374
+ if (!programs) continue;
375
+ const key = targetFormatKey(into) + '|pass|' + programIds(programs);
376
+ if (drawn.has(key)) continue;
377
+ drawn.add(key);
378
+ queue.push({ kind: 'pass', material, into, programs, key });
379
+ count++;
380
+ }
381
+ startPump();
382
+ return count;
383
+ }
384
+
385
+ /** Drop what is queued: nothing more is drawn once the draw in flight has been passed by the card. What was dropped can be queued again. */
386
+ function stop() {
387
+ stopped = true;
388
+ for (let i = 0; i < queue.length; i++) drawn.delete(queue[i].key);
389
+ queue.length = 0;
390
+ }
391
+
392
+ /** Stop the pass and release internal scratch geometry. */
393
+ function dispose() {
394
+ stop();
395
+ if (quad) {
396
+ quad.geometry.dispose();
397
+ quad = quadScene = quadCamera = null;
398
+ }
399
+ }
400
+
401
+ return {
402
+ enqueue,
403
+ enqueuePasses,
404
+ stop,
405
+ dispose,
406
+ get busy() {
407
+ return running;
408
+ },
409
+ };
410
+ }
@@ -153,7 +153,7 @@ export function createWaterMaterials({
153
153
  }
154
154
  void accumulateReflTap(vec2 baseUv, float offsetY, float weight, inout vec3 sumColor, inout float sumWeight) {
155
155
  vec3 tap = texture2D(uRefl, clamp(baseUv + vec2(0.0, offsetY), 0.003, 0.997)).rgb;
156
- if (tap.r >= 0.0 && tap.g >= 0.0 && tap.b >= 0.0) {
156
+ if (tap.r >= 0.0 && tap.g >= 0.0 && tap.b >= 0.0 && tap.r < 200.0 && tap.g < 200.0 && tap.b < 200.0) {
157
157
  sumColor += min(tap, vec3(24.0)) * weight;
158
158
  sumWeight += weight;
159
159
  }
@@ -1,16 +1,11 @@
1
1
  /** Per-renderer WebGL2 fence and timer queries for measuring frame cost. */
2
+ import { createNextTask } from './next-task.js';
3
+
2
4
  export function createGpuTiming(renderer) {
3
5
  const NANOSECONDS_IN_MS = 1e6;
4
6
  const GIVE_UP_MS = 400; // a fence not passed by then is not waited for (a page in the background, a lost context)
7
+ const nextTask = createNextTask();
5
8
 
6
- // Runs a function as the next task, without the four milliseconds a nested setTimeout waits.
7
- const channel = new MessageChannel(),
8
- waiting = [];
9
- channel.port1.onmessage = () => waiting.shift()();
10
- function nextTask(run) {
11
- waiting.push(run);
12
- channel.port2.postMessage(0);
13
- }
14
9
  // Fall back to a synchronous pixel read when a visible context repeatedly times out.
15
10
  let blocks = false;
16
11
  const _pixel = new Uint8Array(4);
@@ -0,0 +1,23 @@
1
+ /**
2
+ * A queue that runs each function given to it as the next task, in the order given.
3
+ *
4
+ * A nested `setTimeout` waits four milliseconds before it runs, however small a wait it asks for. A message through a
5
+ * `MessageChannel` does not, so a page that asks the card something again and again (`runtime/gpu-timing.js`: has a fence
6
+ * been passed) or hands it work a little at a time (`rendering/warm-pipelines.js`) runs between the page's own tasks
7
+ * without holding them up.
8
+ *
9
+ * @returns {(run: () => void) => void} Queues `run` as the next task.
10
+ */
11
+ export function createNextTask() {
12
+ let channel = null; // made at the first task: a port with a listener keeps a Node process alive, and a world's offline
13
+ // tests load this module without ever queueing one
14
+ const waiting = [];
15
+ return run => {
16
+ waiting.push(run);
17
+ if (!channel) {
18
+ channel = new MessageChannel();
19
+ channel.port1.onmessage = () => waiting.shift()();
20
+ }
21
+ channel.port2.postMessage(0);
22
+ };
23
+ }