roamwright 0.0.0-stage → 0.1.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/CONTRIBUTING.md +12 -0
- package/LICENSE +21 -0
- package/README.md +62 -2
- package/examples/index.html +19 -0
- package/examples/island.js +62 -0
- package/geometry/builder.js +543 -0
- package/geometry/instances.js +76 -0
- package/geometry/placement.js +65 -0
- package/geometry/primitives.js +172 -0
- package/index.js +8 -0
- package/licenses/baking-lab.txt +21 -0
- package/licenses/fidelityfx-fsr.txt +19 -0
- package/licenses/three.txt +21 -0
- package/math/curve.js +93 -0
- package/math/noise.js +80 -0
- package/math/random.js +27 -0
- package/math/scalar.js +12 -0
- package/motion/player.js +248 -0
- package/motion/spaces.js +206 -0
- package/package.json +50 -4
- package/rendering/context.js +20 -0
- package/rendering/dof.js +59 -0
- package/rendering/eye-adapt.js +119 -0
- package/rendering/piece-batch.js +411 -0
- package/rendering/post-shaders.js +236 -0
- package/rendering/post.js +519 -0
- package/rendering/still-casters.js +32 -0
- package/rendering/taa.js +171 -0
- package/rendering/textures.js +63 -0
- package/rendering/world-matrices.js +75 -0
- package/runtime/first-use.js +60 -0
- package/runtime/gpu-timing.js +75 -0
- package/runtime/hand-over.js +102 -0
- package/runtime/pool.js +153 -0
- package/runtime/quality-fit.js +190 -0
- package/runtime/quality-store.js +58 -0
- package/runtime/seen.js +36 -0
- package/runtime/worker.js +53 -0
package/rendering/taa.js
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import * as THREE from 'three';
|
|
2
|
+
|
|
3
|
+
// ════════════════════════════════════════════════════════════════════════
|
|
4
|
+
// Temporal anti-aliasing: the lens is moved by a fraction of a pixel each frame (eight points of the Halton 2, 3 sequence),
|
|
5
|
+
// so that over a few frames every pixel sees its whole span, and the final pass keeps a running picture of what it saw:
|
|
6
|
+
// last frame's picture, carried to where each pixel's point now stands (by the scene's depth and the lens's own motion),
|
|
7
|
+
// takes a sixteenth of this frame. What last frame's picture holds that this frame's pixel and the eight round it do not (a person who
|
|
8
|
+
// walked on, smoke that drifted, a place first uncovered) is clipped back to the spread of that neighbourhood, so nothing
|
|
9
|
+
// leaves a trail. Grass blades, leaf edges, roof tiles, railings and glints that crawled and flickered as the lens moved
|
|
10
|
+
// settle. Only the scene is drawn with the lens moved: the names drawn after it, the sky's mask and anything worked out
|
|
11
|
+
// from the lens between frames see it where it stands. The running picture is light before tone mapping, exposed and
|
|
12
|
+
// squashed into 0 to 1 by its brightest channel (SQUASH), so a blinding lamp weighs no more than white and cannot
|
|
13
|
+
// flicker through the clip; the present pass (post-shaders.js) undoes that and tone-maps it.
|
|
14
|
+
// ════════════════════════════════════════════════════════════════════════
|
|
15
|
+
const JITTER_POINTS = 8, // the Halton points the lens steps through, then again
|
|
16
|
+
KEEP = 0.06, // the share of this frame in the running picture while the picture stands still,
|
|
17
|
+
KEEP_MOVING = 0.2, // and at most, while it slides under the lens (KEEP_SLIDE pixels a frame or more): less blur in motion
|
|
18
|
+
KEEP_SLIDE = 8,
|
|
19
|
+
// how many deviations of the neighbourhood the running picture may stray from its mean: in a still picture wide, or each
|
|
20
|
+
// step of the lens clips it anew and every edge flickers; in a sliding one narrow, or what passed leaves a trail
|
|
21
|
+
CLIP_STILL = 2.0,
|
|
22
|
+
CLIP = 1.0,
|
|
23
|
+
JUMP = 40, // metres the lens moves in one frame that start the picture afresh (a jump to a place; a scene's cut says so itself)
|
|
24
|
+
STALE = 1000; // milliseconds between two frames that start it afresh (a page that was hidden, a long pause)
|
|
25
|
+
|
|
26
|
+
const halton = (i, base) => {
|
|
27
|
+
let f = 1,
|
|
28
|
+
r = 0;
|
|
29
|
+
for (; i > 0; i = Math.floor(i / base)) {
|
|
30
|
+
f /= base;
|
|
31
|
+
r += f * (i % base);
|
|
32
|
+
}
|
|
33
|
+
return r;
|
|
34
|
+
};
|
|
35
|
+
// The lens's offsets, in pixels from the pixel's centre.
|
|
36
|
+
const JITTER = Array.from({ length: JITTER_POINTS }, (_, i) => [halton(i + 1, 2) - 0.5, halton(i + 1, 3) - 0.5]);
|
|
37
|
+
|
|
38
|
+
export function createTemporalAA(camera) {
|
|
39
|
+
// The uniforms the final pass reads: last frame's picture, the matrix that carries a point of this frame's picture to where it
|
|
40
|
+
// stood in the last (both without the offset), this frame's offset in clip space, and whether to start afresh.
|
|
41
|
+
const taaUniforms = {
|
|
42
|
+
tHistory: { value: null },
|
|
43
|
+
uReproj: { value: new THREE.Matrix4() },
|
|
44
|
+
uJit: { value: new THREE.Vector2() },
|
|
45
|
+
uFresh: { value: 1 },
|
|
46
|
+
};
|
|
47
|
+
const taa = { history: [], flip: 0, fresh: true, last: 0, index: 0, saved: [0, 0] };
|
|
48
|
+
const viewProj = new THREE.Matrix4(),
|
|
49
|
+
lastViewProj = new THREE.Matrix4(),
|
|
50
|
+
lastLens = new THREE.Vector3();
|
|
51
|
+
|
|
52
|
+
// The two running pictures (read one, write the other), in half floats. Not the scene target's packed floats: with 5 or 6 bits of
|
|
53
|
+
// mantissa a step of that store is 1.5 to 3 percent of the light, a sixteenth of a difference under about eight steps rounds back to
|
|
54
|
+
// what was there, and the running picture stuck a step or two off the frame: in a moving view the sky behind birds kept faint lines
|
|
55
|
+
// along its bands. A half float's step is a thousandth. A card draws into half floats only with alpha (RGB16F cannot be drawn
|
|
56
|
+
// into), so each is 8 bytes a pixel.
|
|
57
|
+
function makeHistory() {
|
|
58
|
+
taa.history = [0, 1].map(
|
|
59
|
+
() => new THREE.WebGLRenderTarget(2, 2, { type: THREE.HalfFloatType, format: THREE.RGBAFormat, depthBuffer: false }),
|
|
60
|
+
);
|
|
61
|
+
taa.fresh = true;
|
|
62
|
+
}
|
|
63
|
+
function disposeHistory() {
|
|
64
|
+
for (const t of taa.history) t.dispose();
|
|
65
|
+
taa.history = [];
|
|
66
|
+
}
|
|
67
|
+
function sizeHistory(w, h) {
|
|
68
|
+
for (const t of taa.history) t.setSize(w, h);
|
|
69
|
+
taa.fresh = true;
|
|
70
|
+
}
|
|
71
|
+
// The running picture starts afresh on the next frame: a cut, a crossing, a new size.
|
|
72
|
+
function dropHistory() {
|
|
73
|
+
taa.fresh = true;
|
|
74
|
+
}
|
|
75
|
+
// The target this frame's running picture is written into; the last frame's is handed to the final pass.
|
|
76
|
+
function historyInto() {
|
|
77
|
+
taaUniforms.tHistory.value = taa.history[taa.flip].texture;
|
|
78
|
+
taa.flip = 1 - taa.flip;
|
|
79
|
+
return taa.history[taa.flip];
|
|
80
|
+
}
|
|
81
|
+
const historyNow = () => taa.history[taa.flip];
|
|
82
|
+
|
|
83
|
+
// Moves the lens by this frame's offset for a picture w x h pixels, after noting how the lens moved since the last frame.
|
|
84
|
+
function jitterLens(w, h) {
|
|
85
|
+
const now = performance.now(),
|
|
86
|
+
p = camera.projectionMatrix,
|
|
87
|
+
e = p.elements;
|
|
88
|
+
if (now - taa.last > STALE || camera.position.distanceToSquared(lastLens) > JUMP * JUMP) taa.fresh = true;
|
|
89
|
+
taa.last = now;
|
|
90
|
+
lastLens.copy(camera.position);
|
|
91
|
+
viewProj.multiplyMatrices(p, camera.matrixWorldInverse);
|
|
92
|
+
taaUniforms.uReproj.value.copy(viewProj).invert().premultiply(lastViewProj);
|
|
93
|
+
lastViewProj.copy(viewProj);
|
|
94
|
+
taaUniforms.uFresh.value = taa.fresh ? 1 : 0;
|
|
95
|
+
taa.fresh = false;
|
|
96
|
+
const point = JITTER[taa.index++ % JITTER_POINTS], // read by index: no iterator made in a frame
|
|
97
|
+
dx = (2 * point[0]) / w,
|
|
98
|
+
dy = (2 * point[1]) / h;
|
|
99
|
+
taaUniforms.uJit.value.set(dx, dy);
|
|
100
|
+
taa.saved[0] = e[8];
|
|
101
|
+
taa.saved[1] = e[9];
|
|
102
|
+
e[8] -= dx; // a point's clip x gains -dx times its view depth, which is dx once divided by w = -depth
|
|
103
|
+
e[9] -= dy;
|
|
104
|
+
camera.projectionMatrixInverse.copy(p).invert();
|
|
105
|
+
}
|
|
106
|
+
// Puts the lens back where it stands, for everything drawn after the scene.
|
|
107
|
+
function steadyLens() {
|
|
108
|
+
const e = camera.projectionMatrix.elements;
|
|
109
|
+
e[8] = taa.saved[0];
|
|
110
|
+
e[9] = taa.saved[1];
|
|
111
|
+
camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert();
|
|
112
|
+
}
|
|
113
|
+
// The running pictures while they exist, for the reckoning of memory.
|
|
114
|
+
const taaTargets = () => taa.history;
|
|
115
|
+
|
|
116
|
+
return {
|
|
117
|
+
disposeHistory,
|
|
118
|
+
dropHistory,
|
|
119
|
+
historyInto,
|
|
120
|
+
historyNow,
|
|
121
|
+
jitterLens,
|
|
122
|
+
makeHistory,
|
|
123
|
+
sizeHistory,
|
|
124
|
+
steadyLens,
|
|
125
|
+
taaTargets,
|
|
126
|
+
taaUniforms,
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Exposed light squashed into 0 to 1 and back: the running picture's form.
|
|
131
|
+
const SQUASH = `/* glsl */ vec3 squash(vec3 c){ return c / (1.0 + max(c.r, max(c.g, c.b))); }
|
|
132
|
+
vec3 unsquash(vec3 c){ return c / max(1.0 - max(c.r, max(c.g, c.b)), 1e-3); }`;
|
|
133
|
+
// The final pass's part (post-shaders.js, under TAA): steady(cur, mean, spread) returns the running picture at this pixel (squashed)
|
|
134
|
+
// from this frame's exposed light cur and its neighbourhood's mean and spread (standard deviation) in YCoCg. It needs the final
|
|
135
|
+
// pass's tDepth and uPx.
|
|
136
|
+
const TAA_FS = `/* glsl */ uniform sampler2D tHistory; uniform mat4 uReproj; uniform vec2 uJit; uniform float uFresh; ${SQUASH}
|
|
137
|
+
vec3 toYCoCg(vec3 c){ return vec3(0.25 * c.r + 0.5 * c.g + 0.25 * c.b, 0.5 * c.r - 0.5 * c.b, -0.25 * c.r + 0.5 * c.g - 0.25 * c.b); }
|
|
138
|
+
vec3 fromYCoCg(vec3 y){ return vec3(y.x + y.y - y.z, y.x + y.z, y.x - y.y - y.z); }
|
|
139
|
+
// where this pixel's point stood in the last frame's picture: carried by the nearest of five depths round it, so an edge moves
|
|
140
|
+
// with what stands in front of it
|
|
141
|
+
vec2 lastUv(vec2 uv){
|
|
142
|
+
float d = texture2D(tDepth, uv).x; vec2 at = uv;
|
|
143
|
+
for (int k = 0; k < 4; k++) {
|
|
144
|
+
vec2 o = uv + vec2(k < 2 ? -1.0 : 1.0, k == 0 || k == 2 ? -1.0 : 1.0) * uPx; float e = texture2D(tDepth, o).x;
|
|
145
|
+
if (e < d) { d = e; at = o; }
|
|
146
|
+
}
|
|
147
|
+
vec2 ndc = at * 2.0 - 1.0 - uJit; // where the point would stand without this frame's offset
|
|
148
|
+
vec4 h = uReproj * vec4(ndc, d * 2.0 - 1.0, 1.0);
|
|
149
|
+
return uv + (h.xy / h.w - ndc) * 0.5; }
|
|
150
|
+
// the last picture at uv, by a Catmull-Rom spline from five filtered lookups: one filtered lookup would soften it a little more each frame
|
|
151
|
+
vec3 lastAt(vec2 uv){
|
|
152
|
+
vec2 p = uv / uPx, t1 = floor(p - 0.5) + 0.5, f = p - t1;
|
|
153
|
+
vec2 w0 = f * (-0.5 + f * (1.0 - 0.5 * f)), w1 = 1.0 + f * f * (-2.5 + 1.5 * f), w2 = f * (0.5 + f * (2.0 - 1.5 * f)), w3 = f * f * (-0.5 + 0.5 * f);
|
|
154
|
+
vec2 w12 = w1 + w2, t0 = (t1 - 1.0) * uPx, t3 = (t1 + 2.0) * uPx, t12 = (t1 + w2 / w12) * uPx;
|
|
155
|
+
vec3 s = texture2D(tHistory, vec2(t12.x, t0.y)).rgb * (w12.x * w0.y) + texture2D(tHistory, vec2(t0.x, t12.y)).rgb * (w0.x * w12.y)
|
|
156
|
+
+ texture2D(tHistory, t12).rgb * (w12.x * w12.y) + texture2D(tHistory, vec2(t3.x, t12.y)).rgb * (w3.x * w12.y)
|
|
157
|
+
+ texture2D(tHistory, vec2(t12.x, t3.y)).rgb * (w12.x * w3.y);
|
|
158
|
+
return max(s / (w12.x * w0.y + w0.x * w12.y + w12.x * w12.y + w3.x * w12.y + w12.x * w3.y), 0.0); }
|
|
159
|
+
vec3 steady(vec3 cur, vec3 mean, vec3 spread){
|
|
160
|
+
vec2 uv = lastUv(vUv);
|
|
161
|
+
vec3 now = squash(cur);
|
|
162
|
+
if (uFresh > 0.5 || uv.x < 0.0 || uv.y < 0.0 || uv.x > 1.0 || uv.y > 1.0) return now;
|
|
163
|
+
float slide = length((uv - vUv) / uPx); // pixels the picture slid under the lens since the last frame
|
|
164
|
+
vec3 last = toYCoCg(unsquash(lastAt(uv))), off = last - mean,
|
|
165
|
+
a = abs(off / (spread * mix(${CLIP_STILL.toFixed(2)}, ${CLIP.toFixed(2)}, clamp(slide, 0.0, 1.0)) + 1e-4));
|
|
166
|
+
float m = max(a.x, max(a.y, a.z));
|
|
167
|
+
if (m > 1.0) last = mean + off / m; // clipped to the neighbourhood's box, along the line to its middle
|
|
168
|
+
float keep = mix(${KEEP.toFixed(3)}, ${KEEP_MOVING.toFixed(3)}, clamp(slide / ${KEEP_SLIDE.toFixed(1)}, 0.0, 1.0));
|
|
169
|
+
return mix(squash(max(fromYCoCg(last), 0.0)), now, keep); }`;
|
|
170
|
+
|
|
171
|
+
export { SQUASH, TAA_FS };
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import * as THREE from 'three';
|
|
2
|
+
|
|
3
|
+
// A canvas w x h whose every pixel is worked out here, fn(u, v, out) -> rgba (0..255) at the pixel's middle. A light's texture is
|
|
4
|
+
// made this way, never by a canvas's own gradient: WebKit (an iPhone's engine) dithers a gradient a little in each channel
|
|
5
|
+
// apart, which a night's exposure turns into red and green specks over a lantern's pool or a window's patch of light.
|
|
6
|
+
function pixelCanvas(w, h, fn) {
|
|
7
|
+
const c = document.createElement('canvas');
|
|
8
|
+
c.width = w;
|
|
9
|
+
c.height = h;
|
|
10
|
+
const g = c.getContext('2d'),
|
|
11
|
+
img = g.createImageData(w, h),
|
|
12
|
+
d = img.data,
|
|
13
|
+
out = [0, 0, 0, 255];
|
|
14
|
+
for (let y = 0, k = 0; y < h; y++)
|
|
15
|
+
for (let x = 0; x < w; x++, k += 4) {
|
|
16
|
+
out[3] = 255;
|
|
17
|
+
fn((x + 0.5) / w, (y + 0.5) / h, out);
|
|
18
|
+
d[k] = out[0];
|
|
19
|
+
d[k + 1] = out[1];
|
|
20
|
+
d[k + 2] = out[2];
|
|
21
|
+
d[k + 3] = out[3];
|
|
22
|
+
}
|
|
23
|
+
g.putImageData(img, 0, 0);
|
|
24
|
+
return c;
|
|
25
|
+
}
|
|
26
|
+
// A square texture built by pixelCanvas, with opts.draw(context, size) drawing over it.
|
|
27
|
+
function pixelTexture(size, fn, opts = {}) {
|
|
28
|
+
const c = pixelCanvas(size, size, fn);
|
|
29
|
+
if (opts.draw) opts.draw(c.getContext('2d'), size);
|
|
30
|
+
return canvasTexture(c, opts);
|
|
31
|
+
}
|
|
32
|
+
// The value at t of a falloff given by stops [[t, value], ...] in rising t, straight between them and held beyond the ends, as
|
|
33
|
+
// a canvas gradient's stops are.
|
|
34
|
+
function falloffAt(stops, t) {
|
|
35
|
+
if (t <= stops[0][0]) return stops[0][1];
|
|
36
|
+
for (let i = 1; i < stops.length; i++) {
|
|
37
|
+
const [t1, v1] = stops[i];
|
|
38
|
+
if (t <= t1) {
|
|
39
|
+
const [t0, v0] = stops[i - 1];
|
|
40
|
+
return v0 + ((v1 - v0) * (t - t0)) / (t1 - t0);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return stops[stops.length - 1][1];
|
|
44
|
+
}
|
|
45
|
+
// A texture from a canvas: repeating unless clamped, in sRGB unless it holds data.
|
|
46
|
+
function canvasTexture(c, opts = {}) {
|
|
47
|
+
const t = new THREE.CanvasTexture(c);
|
|
48
|
+
t.wrapS = t.wrapT = opts.clamp ? THREE.ClampToEdgeWrapping : THREE.RepeatWrapping;
|
|
49
|
+
t.colorSpace = opts.data ? THREE.NoColorSpace : THREE.SRGBColorSpace;
|
|
50
|
+
t.anisotropy = opts.aniso || 4;
|
|
51
|
+
return t;
|
|
52
|
+
}
|
|
53
|
+
// A map of numbers that is written once need not stay in memory once it is on the graphics card: its array is let go there.
|
|
54
|
+
// Regenerate the texture after a graphics context loss when using this option.
|
|
55
|
+
function onCardOnly(texture) {
|
|
56
|
+
texture.onUpdate = () => {
|
|
57
|
+
texture.image.data = null;
|
|
58
|
+
texture.onUpdate = null;
|
|
59
|
+
};
|
|
60
|
+
return texture;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export { canvasTexture, falloffAt, onCardOnly, pixelCanvas, pixelTexture };
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import * as THREE from 'three';
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
// ════════════════════════════════════════════════════════════════════════
|
|
5
|
+
// Where everything stands in the world, worked out once a frame and only for what moved
|
|
6
|
+
// ════════════════════════════════════════════════════════════════════════
|
|
7
|
+
// Update world transforms once before rendering multiple passes. Compose a local
|
|
8
|
+
// matrix when its transform changes, then propagate changes through descendants.
|
|
9
|
+
// Reparenting also invalidates the world transform. For manually managed matrices,
|
|
10
|
+
// set matrixWorldNeedsUpdate after editing the matrix directly.
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
const plainWalk = THREE.Object3D.prototype.updateMatrixWorld;
|
|
14
|
+
|
|
15
|
+
// Has the object been moved, turned or scaled since it was last asked? (The first time it has.)
|
|
16
|
+
function moved(o) {
|
|
17
|
+
const p = o.position,
|
|
18
|
+
q = o.quaternion,
|
|
19
|
+
s = o.scale;
|
|
20
|
+
let k = o.placedAt;
|
|
21
|
+
if (k === undefined) k = o.placedAt = new Float64Array(10).fill(NaN);
|
|
22
|
+
if (
|
|
23
|
+
k[0] === p.x &&
|
|
24
|
+
k[1] === p.y &&
|
|
25
|
+
k[2] === p.z &&
|
|
26
|
+
k[3] === q.x &&
|
|
27
|
+
k[4] === q.y &&
|
|
28
|
+
k[5] === q.z &&
|
|
29
|
+
k[6] === q.w &&
|
|
30
|
+
k[7] === s.x &&
|
|
31
|
+
k[8] === s.y &&
|
|
32
|
+
k[9] === s.z
|
|
33
|
+
)
|
|
34
|
+
return false;
|
|
35
|
+
k[0] = p.x;
|
|
36
|
+
k[1] = p.y;
|
|
37
|
+
k[2] = p.z;
|
|
38
|
+
k[3] = q.x;
|
|
39
|
+
k[4] = q.y;
|
|
40
|
+
k[5] = q.z;
|
|
41
|
+
k[6] = q.w;
|
|
42
|
+
k[7] = s.x;
|
|
43
|
+
k[8] = s.y;
|
|
44
|
+
k[9] = s.z;
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
// Three's own walk (Object3D.updateMatrixWorld), but for the test of what moved
|
|
48
|
+
function place(o, force) {
|
|
49
|
+
if (o.updateMatrixWorld !== plainWalk) {
|
|
50
|
+
o.updateMatrixWorld(force); // a kind with work of its own to do (a camera, a skinned mesh): Three's walk from here down
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
if (o.matrixAutoUpdate && moved(o)) o.updateMatrix();
|
|
54
|
+
if (o.placedUnder !== o.parent) {
|
|
55
|
+
o.placedUnder = o.parent;
|
|
56
|
+
force = true;
|
|
57
|
+
}
|
|
58
|
+
if (o.matrixWorldNeedsUpdate || force) {
|
|
59
|
+
if (o.matrixWorldAutoUpdate) {
|
|
60
|
+
if (o.parent === null) o.matrixWorld.copy(o.matrix);
|
|
61
|
+
else o.matrixWorld.multiplyMatrices(o.parent.matrixWorld, o.matrix);
|
|
62
|
+
}
|
|
63
|
+
o.matrixWorldNeedsUpdate = false;
|
|
64
|
+
force = true;
|
|
65
|
+
}
|
|
66
|
+
const children = o.children;
|
|
67
|
+
for (let i = 0; i < children.length; i++) place(children[i], force);
|
|
68
|
+
}
|
|
69
|
+
// Called once a frame, before anything is drawn
|
|
70
|
+
function trackWorldMatrices(scene) {
|
|
71
|
+
scene.matrixWorldAutoUpdate = false;
|
|
72
|
+
return () => place(scene, false);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export { trackWorldMatrices };
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Initialize a compiled Three.js program before other draws reach the driver.
|
|
3
|
+
* Call useAtFrameStart() at the beginning of each frame. When rendering stops,
|
|
4
|
+
* a timeout drains requests that would otherwise never resolve.
|
|
5
|
+
*/
|
|
6
|
+
export function createFirstUse({ renderer, waitMs = 250, now = () => performance.now() }) {
|
|
7
|
+
const waiting = [];
|
|
8
|
+
const asked = [];
|
|
9
|
+
let frameBegan = -Infinity;
|
|
10
|
+
|
|
11
|
+
function useProgram(program) {
|
|
12
|
+
if (!program.program) return;
|
|
13
|
+
const gl = renderer.getContext();
|
|
14
|
+
const previous = renderer.debug.checkShaderErrors;
|
|
15
|
+
try {
|
|
16
|
+
renderer.debug.checkShaderErrors = previous && !gl.getProgramParameter(program.program, gl.LINK_STATUS);
|
|
17
|
+
program.getUniforms();
|
|
18
|
+
} finally {
|
|
19
|
+
renderer.debug.checkShaderErrors = previous;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function settle() {
|
|
23
|
+
for (let i = asked.length - 1; i >= 0; i--) {
|
|
24
|
+
const [programs, resolve] = asked[i];
|
|
25
|
+
if (programs.some(p => waiting.includes(p))) continue;
|
|
26
|
+
asked.splice(i, 1);
|
|
27
|
+
resolve();
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function putToUse(programs) {
|
|
31
|
+
if (!programs.length) return Promise.resolve();
|
|
32
|
+
if (now() - frameBegan > waitMs) {
|
|
33
|
+
programs.forEach(useProgram);
|
|
34
|
+
return Promise.resolve();
|
|
35
|
+
}
|
|
36
|
+
waiting.push(...programs);
|
|
37
|
+
return new Promise(resolve => {
|
|
38
|
+
asked.push([programs, resolve]);
|
|
39
|
+
setTimeout(
|
|
40
|
+
() => {
|
|
41
|
+
for (const p of programs) {
|
|
42
|
+
const at = waiting.indexOf(p);
|
|
43
|
+
if (at < 0) continue;
|
|
44
|
+
waiting.splice(at, 1);
|
|
45
|
+
useProgram(p);
|
|
46
|
+
}
|
|
47
|
+
settle();
|
|
48
|
+
},
|
|
49
|
+
waitMs * (programs.length + 1),
|
|
50
|
+
);
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
function useAtFrameStart() {
|
|
54
|
+
frameBegan = now();
|
|
55
|
+
if (!waiting.length) return;
|
|
56
|
+
useProgram(waiting.shift());
|
|
57
|
+
settle();
|
|
58
|
+
}
|
|
59
|
+
return { putToUse, useAtFrameStart, useProgram };
|
|
60
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/** Per-renderer WebGL2 fence and timer queries for measuring frame cost. */
|
|
2
|
+
export function createGpuTiming(renderer) {
|
|
3
|
+
const NANOSECONDS_IN_MS = 1e6;
|
|
4
|
+
const GIVE_UP_MS = 400; // a fence not passed by then is not waited for (a page in the background, a lost context)
|
|
5
|
+
|
|
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
|
+
// Fall back to a synchronous pixel read when a visible context repeatedly times out.
|
|
15
|
+
let blocks = false;
|
|
16
|
+
const _pixel = new Uint8Array(4);
|
|
17
|
+
const cardBlocks = () => blocks;
|
|
18
|
+
// Resolves once the card has drawn everything handed to it before this call, with when that was seen (performance.now()),
|
|
19
|
+
// whether it was already so the first time it was asked (the card was not behind), and whether the wait was given up.
|
|
20
|
+
function cardDone() {
|
|
21
|
+
const gl = renderer.getContext();
|
|
22
|
+
if (blocks) {
|
|
23
|
+
gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, _pixel);
|
|
24
|
+
return Promise.resolve({ at: performance.now(), prompt: false, gaveUp: false });
|
|
25
|
+
}
|
|
26
|
+
const fence = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0),
|
|
27
|
+
since = performance.now();
|
|
28
|
+
let asked = 0;
|
|
29
|
+
if (!fence) return Promise.resolve({ at: since, prompt: false, gaveUp: true });
|
|
30
|
+
gl.flush();
|
|
31
|
+
return new Promise(resolve => {
|
|
32
|
+
const ask = () => {
|
|
33
|
+
const at = performance.now(),
|
|
34
|
+
waiting = gl.clientWaitSync(fence, 0, 0) === gl.TIMEOUT_EXPIRED;
|
|
35
|
+
if (waiting && at - since < GIVE_UP_MS) {
|
|
36
|
+
asked++;
|
|
37
|
+
nextTask(ask);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
gl.deleteSync(fence);
|
|
41
|
+
if (waiting && !globalThis.document?.hidden) blocks = true; // not passed in all that time on a page that is being shown: fences do not work here
|
|
42
|
+
resolve({ at, prompt: asked === 0, gaveUp: waiting });
|
|
43
|
+
};
|
|
44
|
+
nextTask(ask);
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// How long the card itself works on a frame, measured by the card (a timer query) where the browser offers one: Chrome on
|
|
49
|
+
// a desktop does. timeCard() is called before a frame is handed over and returns the function to call after it, or null
|
|
50
|
+
// when no measurement can begin (no such query here, or the last one has not been answered yet); cardWork() gives the last
|
|
51
|
+
// answer in milliseconds, or null if there has been none.
|
|
52
|
+
let timer; // the extension, once asked for (null where there is none)
|
|
53
|
+
let asked = null, // the query waiting for its answer
|
|
54
|
+
work = null;
|
|
55
|
+
function timeCard() {
|
|
56
|
+
const gl = renderer.getContext();
|
|
57
|
+
if (timer === undefined) timer = gl.getExtension('EXT_disjoint_timer_query_webgl2');
|
|
58
|
+
if (!timer) return null;
|
|
59
|
+
if (asked) {
|
|
60
|
+
if (!gl.getQueryParameter(asked, gl.QUERY_RESULT_AVAILABLE)) return null;
|
|
61
|
+
if (!gl.getParameter(timer.GPU_DISJOINT_EXT)) work = gl.getQueryParameter(asked, gl.QUERY_RESULT) / NANOSECONDS_IN_MS;
|
|
62
|
+
gl.deleteQuery(asked);
|
|
63
|
+
asked = null;
|
|
64
|
+
}
|
|
65
|
+
const query = gl.createQuery();
|
|
66
|
+
if (!query) return null;
|
|
67
|
+
gl.beginQuery(timer.TIME_ELAPSED_EXT, query);
|
|
68
|
+
return () => {
|
|
69
|
+
gl.endQuery(timer.TIME_ELAPSED_EXT);
|
|
70
|
+
asked = query;
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
const cardWork = () => work;
|
|
74
|
+
return { cardBlocks, cardDone, cardWork, timeCard };
|
|
75
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Share an upload budget across temporary zero-range draws and direct buffer
|
|
3
|
+
* writes. Call frameDrawn() after each render. frameShare() returns the current
|
|
4
|
+
* byte budget and painted() resolves after the browser has painted.
|
|
5
|
+
*/
|
|
6
|
+
export function createHandOver({ painted, frameShare }) {
|
|
7
|
+
let handing = Promise.resolve();
|
|
8
|
+
let handed = 0,
|
|
9
|
+
drawn = 0;
|
|
10
|
+
const beforeFirst = [];
|
|
11
|
+
// Overlapping roots may refer to the same geometry before it has drawn.
|
|
12
|
+
const inHand = new WeakSet();
|
|
13
|
+
function frameDrawn() {
|
|
14
|
+
drawn++;
|
|
15
|
+
handed = 0;
|
|
16
|
+
if (beforeFirst.length) {
|
|
17
|
+
restore(beforeFirst);
|
|
18
|
+
beforeFirst.length = 0;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
const countHanded = bytes => {
|
|
22
|
+
handed += bytes;
|
|
23
|
+
};
|
|
24
|
+
const frameFull = () => handed >= frameShare();
|
|
25
|
+
// A browser can paint without rendering a scene while loading.
|
|
26
|
+
async function nextShare() {
|
|
27
|
+
const was = drawn;
|
|
28
|
+
await painted();
|
|
29
|
+
if (drawn === was) handed = 0;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const heldBytes = geometry => Object.values(geometry.attributes).reduce((sum, a) => sum + (a.array?.byteLength ?? 0), 0);
|
|
33
|
+
const letsGo = geometry => Object.values(geometry.attributes).some(a => Object.hasOwn(a, 'onUploadCallback'));
|
|
34
|
+
|
|
35
|
+
function handToCard(roots) {
|
|
36
|
+
const found = new Map();
|
|
37
|
+
for (const root of roots)
|
|
38
|
+
root.traverse(o => {
|
|
39
|
+
if (o.isMesh && !o.isSkinnedMesh && !inHand.has(o.geometry) && heldBytes(o.geometry) && letsGo(o.geometry))
|
|
40
|
+
found.set(o.geometry, [...(found.get(o.geometry) ?? []), o]);
|
|
41
|
+
});
|
|
42
|
+
const turn = handing.then(() => handOver(found));
|
|
43
|
+
handing = turn.catch(() => {});
|
|
44
|
+
return turn;
|
|
45
|
+
}
|
|
46
|
+
async function handOver(found) {
|
|
47
|
+
let batch = [];
|
|
48
|
+
const flush = async () => {
|
|
49
|
+
try {
|
|
50
|
+
await nextShare();
|
|
51
|
+
} finally {
|
|
52
|
+
restore(batch);
|
|
53
|
+
batch = [];
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
for (const [geometry, meshes] of found) {
|
|
57
|
+
if (inHand.has(geometry)) continue;
|
|
58
|
+
inHand.add(geometry);
|
|
59
|
+
const range = { ...geometry.drawRange },
|
|
60
|
+
was = meshes.map(m => ({ visible: m.visible, frustumCulled: m.frustumCulled }));
|
|
61
|
+
geometry.setDrawRange(0, 0);
|
|
62
|
+
for (const m of meshes) {
|
|
63
|
+
m.visible = true;
|
|
64
|
+
m.frustumCulled = false;
|
|
65
|
+
}
|
|
66
|
+
// The first render uploads everything queued before the render loop started.
|
|
67
|
+
if (!drawn) {
|
|
68
|
+
beforeFirst.push([geometry, meshes, range, was]);
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
countHanded(heldBytes(geometry));
|
|
72
|
+
batch.push([geometry, meshes, range, was]);
|
|
73
|
+
if (frameFull()) await flush();
|
|
74
|
+
}
|
|
75
|
+
if (batch.length) await flush();
|
|
76
|
+
}
|
|
77
|
+
function restore(handedOver) {
|
|
78
|
+
for (const [geometry, meshes, range, was] of handedOver) {
|
|
79
|
+
geometry.setDrawRange(range.start, range.count);
|
|
80
|
+
inHand.delete(geometry);
|
|
81
|
+
meshes.forEach((m, i) => Object.assign(m, was[i]));
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function paced(steps) {
|
|
86
|
+
let step;
|
|
87
|
+
while (!(step = steps.next()).done) {
|
|
88
|
+
countHanded(step.value);
|
|
89
|
+
if (frameFull()) await nextShare();
|
|
90
|
+
}
|
|
91
|
+
return step.value;
|
|
92
|
+
}
|
|
93
|
+
function drain(steps) {
|
|
94
|
+
let step;
|
|
95
|
+
do step = steps.next();
|
|
96
|
+
while (!step.done);
|
|
97
|
+
return step.value;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const anyFrameDrawn = () => drawn > 0;
|
|
101
|
+
return { anyFrameDrawn, countHanded, drain, frameDrawn, frameFull, handToCard, heldBytes, paced };
|
|
102
|
+
}
|