Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

feat(poc): motion blur, a real cursor and an analytic Gaussian shadow, behind an A/B switch

Etienne Lescotdb128741ddd7
diff --git a/poc/composite.wgsl b/poc/composite.wgsl
index e0e6639f4..72b11af1d 100644
--- a/poc/composite.wgsl
+++ b/poc/composite.wgsl
@@ -22,8 +22,17 @@ struct U {
webcam : vec4f,
// shadowIntensity | bgBlurPx | shadowOffsetY | shadowSpread
fx : vec4f,
- // webcamRadius | motionBlurPx | webcamCoverScale | optimised(0/1)
+ // webcamRadius | unused | webcamCoverScale | optimised(0/1)
b : vec4f,
+ // Directional motion blur, in pixels: screenBlur.xy | webcamBlur.xy. A vector,
+ // not a scalar — the recording smears along the camera's real travel, which
+ // during a pan or a layout move is not horizontal.
+ mb : vec4f,
+ // The cursor, drawn synthetically from the recorded trace: x | y | size |
+ // opacity. Position is in stage pixels, already carried through the zoom.
+ cursor : vec4f,
+ // cursorBlur.xy | clickScale | unused. clickScale pulses on a real click.
+ cursorFx : vec4f,
};
@group(0) @binding(0) var<uniform> u : U;
@@ -69,9 +78,9 @@ fn quad(vi : u32, rect : vec4f) -> VsOut {
return quad(i, u.screen);
}
-/** The shadow's quad: the rect, grown by the spread — its exact reach. */
+/** The shadow's quad: the rect grown by 3σ, the Gaussian's reach. */
@vertex fn vsScreenShadow(@builtin(vertex_index) i : u32) -> VsOut {
- let s = u.fx.w + 1.0;
+ let s = u.fx.w * 3.0 + 1.0;
return quad(i, vec4f(u.screen.xy - vec2f(s), u.screen.zw + vec2f(s * 2.0)) + vec4f(0.0, u.fx.z, 0.0, 0.0));
}
@@ -80,10 +89,18 @@ fn quad(vi : u32, rect : vec4f) -> VsOut {
}
@vertex fn vsWebcamShadow(@builtin(vertex_index) i : u32) -> VsOut {
- let s = u.fx.w + 1.0;
+ let s = u.fx.w * 3.0 + 1.0;
return quad(i, vec4f(u.webcam.xy - vec2f(s), u.webcam.zw + vec2f(s * 2.0)) + vec4f(0.0, u.fx.z, 0.0, 0.0));
}
+/** The cursor's quad: its box, grown for the shadow, the click bounce and the smear. */
+@vertex fn vsCursor(@builtin(vertex_index) i : u32) -> VsOut {
+ let size = u.cursor.z;
+ let pad = 6.0 + length(u.cursorFx.xy);
+ let rect = vec4f(u.cursor.xy - vec2f(pad), vec2f(size * 1.5 + pad * 2.0));
+ return quad(i, rect);
+}
+
// ---- geometry ---------------------------------------------------------------
/** Signed distance to a rounded box. Negative inside. */
@@ -150,43 +167,70 @@ fn blurredGradient(uv : vec2f) -> vec3f {
// ---- effect 2: the drop shadow ----------------------------------------------
//
-// The shape is known analytically — a rounded rect — so the shadow needs no blur
-// pass: the coverage of that box, sampled at a few offsets, IS the shadow. No
-// silhouette texture, no ping-pong, no 18 passes.
+// A REAL Gaussian, computed analytically — not sampled.
+//
+// The wrong way (what this replaced): sample the rounded-box SDF at a ring of
+// offsets and average. Few taps band into visible rings, many taps are slow, and
+// neither is a Gaussian — it is a box blur of a hard mask. It looked like stacked
+// translucent rectangles because that is exactly what it was.
//
-// The quad already bounds it to the rect + spread, so the "outside" case never
-// reaches a fragment. What is left is the inside: every tap lands within `spread`
-// of the pixel, so within the box SHRUNK by spread they all hit, and the answer
-// is `intensity` with no taps at all. That is the box's Minkowski difference with
-// the tap disc — the same number by arithmetic, not an approximation. Only the
-// band around the edge pays the twelve samples.
+// The right way (Evan Wallace, "Fast Rounded Rectangle Shadows"): the convolution
+// of a 2D Gaussian with a box is separable and each axis is an integral of the
+// Gaussian — which is the error function, erf. So a plain box shadow is a closed
+// form, no samples at all: `(erf(right) - erf(left)) * (erf(top) - erf(bottom))`.
+// Rounded corners break separability only near the corner, so the x extent is
+// integrated against the Gaussian in y over a handful of steps — the exact
+// profile, smoothly weighted, no banding. O(1) per pixel and beautiful.
+
+const SQRT_2PI = 2.5066282746310002;
+const INV_SQRT_2 = 0.7071067811865476;
+
+fn gauss1(x : f32, sigma : f32) -> f32 {
+ return exp(-(x * x) / (2.0 * sigma * sigma)) / (SQRT_2PI * sigma);
+}
+
+/** erf, componentwise (Abramowitz & Stegun 7.1.27). Max error ~5e-4. */
+fn erf2(x : vec2f) -> vec2f {
+ let s = sign(x);
+ let a = abs(x);
+ var r = 1.0 + (0.278393 + (0.230389 + 0.078108 * (a * a)) * a) * a;
+ r = r * r;
+ return s - s / (r * r);
+}
+
+/** Fraction of a Gaussian-blurred box covering x, at height y, with rounded corners. */
+fn shadowRowX(x : f32, y : f32, sigma : f32, corner : f32, half : vec2f) -> f32 {
+ // How far the rounded corner pulls the edge in at this height.
+ let d = min(half.y - corner - abs(y), 0.0);
+ let curved = half.x - corner + sqrt(max(0.0, corner * corner - d * d));
+ let integral = 0.5 + 0.5 * erf2((x + vec2f(-curved, curved)) * (INV_SQRT_2 / sigma));
+ return integral.y - integral.x;
+}
fn shadowAt(px : vec2f, rect : vec4f, radius : f32, intensity : f32) -> f32 {
if (intensity <= 0.0) {
return 0.0;
}
- let centre = rect.xy + rect.zw * 0.5 + vec2f(0.0, u.fx.z);
+ let sigma = max(u.fx.w, 0.5);
let half = rect.zw * 0.5;
- let spread = u.fx.w;
- let p = px - centre;
-
- if (u.b.w > 0.5) {
- if (sdRoundBox(p, max(half - vec2f(spread), vec2f(0.0)), max(radius - spread, 0.0)) < -0.5) {
- return intensity;
- }
- }
+ let corner = min(radius, min(half.x, half.y));
+ // Offset the shadow down by u.fx.z, like a light from above.
+ let p = px - (rect.xy + half + vec2f(0.0, u.fx.z));
- var acc = 0.0;
- let taps = 12;
- let golden = 2.39996;
- for (var i = 0; i < taps; i = i + 1) {
- let fi = f32(i);
- let r = sqrt((fi + 0.5) / f32(taps)) * spread;
- let a = fi * golden;
- let o = vec2f(cos(a), sin(a)) * r;
- acc = acc + cover(sdRoundBox(p + o, half, radius));
+ // Integrate the x-profile against the Gaussian in y, over ±3σ clamped to the
+ // box — four steps is plenty because each is analytic in x.
+ let low = p.y - half.y;
+ let high = p.y + half.y;
+ let start = clamp(-3.0 * sigma, low, high);
+ let end = clamp(3.0 * sigma, low, high);
+ let step = (end - start) / 4.0;
+ var y = start + step * 0.5;
+ var value = 0.0;
+ for (var i = 0; i < 4; i = i + 1) {
+ value = value + shadowRowX(p.x, p.y - y, sigma, corner, half) * gauss1(y, sigma) * step;
+ y = y + step;
}
- return (acc / f32(taps)) * intensity;
+ return clamp(value, 0.0, 1.0) * intensity;
}
@fragment fn fsScreenShadow(in : VsOut) -> @location(0) vec4f {
@@ -200,19 +244,23 @@ fn shadowAt(px : vec2f, rect : vec4f, radius : f32, intensity : f32) -> f32 {
// ---- effect 3: the masks + the sources --------------------------------------
/**
- * Directional motion blur while the camera moves. Skipped at rest: a branch is
- * free next to seven texture fetches, and it is uniform across the frame.
+ * The recording, smeared along the camera's travel while it moves.
+ *
+ * The blur is a VECTOR now (u.mb.xy): a pan or a layout move sends the camera
+ * diagonally, and a horizontal-only smear would be wrong for exactly the motion a
+ * screen demo has most of. Skipped at rest — a branch is free next to seven
+ * fetches, and it is uniform across the frame.
*/
-fn sampleScreen(px : vec2f, blurPx : f32) -> vec3f {
+fn sampleScreen(px : vec2f, blur : vec2f) -> vec3f {
let uv0 = (px - u.screen.xy) / max(u.screen.zw, vec2f(1.0));
- if (blurPx < 0.5) {
+ if (length(blur) < 0.5) {
return textureSampleBaseClampToEdge(screenTex, samp, clamp(uv0, vec2f(0.0), vec2f(1.0))).rgb;
}
var acc = vec3f(0.0);
let taps = 7;
for (var i = 0; i < taps; i = i + 1) {
let t = (f32(i) / f32(taps - 1)) - 0.5;
- let uv = ((px + vec2f(blurPx * t, 0.0)) - u.screen.xy) / max(u.screen.zw, vec2f(1.0));
+ let uv = ((px + blur * t) - u.screen.xy) / max(u.screen.zw, vec2f(1.0));
acc = acc + textureSampleBaseClampToEdge(screenTex, samp, clamp(uv, vec2f(0.0), vec2f(1.0))).rgb;
}
return acc / f32(taps);
@@ -224,7 +272,76 @@ fn sampleScreen(px : vec2f, blurPx : f32) -> vec3f {
if (c <= 0.0) {
discard;
}
- return vec4f(sampleScreen(px, u.b.y), c);
+ return vec4f(sampleScreen(px, u.mb.xy), c);
+}
+
+// ---- the cursor -------------------------------------------------------------
+//
+// Drawn from the recorded trace, per frame — never baked into the video. A
+// polygon SDF, so it is a shape the shader computes, not a sprite it samples; the
+// real app swaps theme PNGs in here, which is a texture read in the same quad,
+// not a different pipeline. The hard parts a POC has to prove are all here: it
+// follows the zoom (its position rides the screen rect), it bounces on a real
+// click (clickScale), it casts a shadow, and it smears when it moves fast.
+
+/** Signed distance to the classic arrow pointer, tip at local (0,0). Neg inside. */
+fn sdCursor(p : vec2f) -> f32 {
+ var v = array<vec2f, 7>(
+ vec2f(0.00, 0.00), vec2f(0.00, 1.00), vec2f(0.24, 0.76),
+ vec2f(0.40, 1.14), vec2f(0.56, 1.07), vec2f(0.39, 0.69), vec2f(0.70, 0.69),
+ );
+ var d = dot(p - v[0], p - v[0]);
+ var s = 1.0;
+ for (var i = 0; i < 7; i = i + 1) {
+ let j = (i + 6) % 7;
+ let e = v[j] - v[i];
+ let w = p - v[i];
+ let b = w - e * clamp(dot(w, e) / dot(e, e), 0.0, 1.0);
+ d = min(d, dot(b, b));
+ // Winding test. The three conditions are kept as scalars, not packed into a
+ // vec3<bool>: the `>` inside that constructor is parsed as a template close.
+ let c0 = p.y >= v[i].y;
+ let c1 = p.y < v[j].y;
+ let c2 = e.x * w.y > e.y * w.x;
+ if ((c0 && c1 && c2) || (!c0 && !c1 && !c2)) { s = -s; }
+ }
+ return s * sqrt(d);
+}
+
+/** Signed distance to the arrow at a stage pixel, in px, with the click bounce. */
+fn cursorSD(px : vec2f) -> f32 {
+ // Scale about the tip (local origin) so a click bounce pulls toward the
+ // hotspot, not the centre. 1.2 fits the 0..1.14 arrow inside the quad.
+ let s = u.cursor.z / 1.2;
+ let local = (px - u.cursor.xy) / max(s, 1.0) / u.cursorFx.z;
+ return sdCursor(local) * s * u.cursorFx.z;
+}
+
+@fragment fn fsCursor(in : VsOut) -> @location(0) vec4f {
+ let px = in.uv * u.a.xy;
+ let blur = u.cursorFx.xy;
+ let outline = max(u.cursor.z * 0.05, 1.5); // the arrow's own black rim, in px
+
+ // Fill (white interior) and outline (interior + rim) coverage, both smeared
+ // along the travel when the cursor moves fast. No drop shadow — the contrast on
+ // a light page is the rim, which is part of the pointer, not a cast shadow.
+ var fill = 0.0;
+ var edge = 0.0;
+ let moving = length(blur) >= 0.5;
+ let taps = select(1, 5, moving);
+ for (var i = 0; i < taps; i = i + 1) {
+ let t = select(0.0, (f32(i) / f32(taps - 1)) - 0.5, moving);
+ let d = cursorSD(px + blur * t);
+ fill = fill + cover(d);
+ edge = edge + cover(d - outline);
+ }
+ fill = fill / f32(taps);
+ edge = edge / f32(taps);
+
+ // White inside, fading to a black rim; `edge` carries the opacity so the rim is
+ // solid. The click bounce is already baked into cursorSD.
+ let rgb = vec3f(fill / max(edge, 1e-4));
+ return vec4f(rgb, edge * u.cursor.w);
}
/**
@@ -232,6 +349,13 @@ fn sampleScreen(px : vec2f, blurPx : f32) -> vec3f {
* circle when docked and rounded rect when grown. The SDF interpolates the SHAPE
* for free — a tessellated 2D mask would rebuild geometry every frame for this.
*/
+fn sampleWebcam(px : vec2f, centre : vec2f) -> vec3f {
+ var uv = (px - centre) / max(u.webcam.zw, vec2f(1.0));
+ // Cover-fit: a 4:3 source in a square hole would squash without this.
+ uv = uv * vec2f(u.b.z, 1.0) + vec2f(0.5);
+ return textureSampleBaseClampToEdge(webcamTex, samp, clamp(uv, vec2f(0.0), vec2f(1.0))).rgb;
+}
+
@fragment fn fsWebcam(in : VsOut) -> @location(0) vec4f {
let px = in.uv * u.a.xy;
let centre = u.webcam.xy + u.webcam.zw * 0.5;
@@ -239,10 +363,16 @@ fn sampleScreen(px : vec2f, blurPx : f32) -> vec3f {
if (c <= 0.0) {
discard;
}
- // Cover-fit: a 4:3 source in a square hole would squash without this. Sample
- // the middle and let the mask crop, which is what the eye expects.
- var uv = (px - centre) / max(u.webcam.zw, vec2f(1.0));
- uv = uv * vec2f(u.b.z, 1.0) + vec2f(0.5);
- let cam = textureSampleBaseClampToEdge(webcamTex, samp, clamp(uv, vec2f(0.0), vec2f(1.0)));
- return vec4f(cam.rgb, c);
+ // Smear along its travel during a layout move, exactly like the recording.
+ let blur = u.mb.zw;
+ if (length(blur) < 0.5) {
+ return vec4f(sampleWebcam(px, centre), c);
+ }
+ var acc = vec3f(0.0);
+ let taps = 5;
+ for (var i = 0; i < taps; i = i + 1) {
+ let t = (f32(i) / f32(taps - 1)) - 0.5;
+ acc = acc + sampleWebcam(px + blur * t, centre);
+ }
+ return vec4f(acc / f32(taps), c);
}
diff --git a/poc/index.html b/poc/index.html
index cac94faee..3a4343afa 100644
--- a/poc/index.html
+++ b/poc/index.html
@@ -50,9 +50,21 @@
<input id="optimise" type="checkbox" checked style="width: auto" />
</div>
<button id="run">Lancer</button>
+ </div>
+
+ <div class="row" style="border-top: 1px solid #2a2a34; padding-top: 16px;">
+ <div>
+ <label for="compareMode">comparer</label>
+ <select id="compareMode" style="width: auto; min-width: 210px; background: #22222c; color: #e8e8ee; border: 1px solid #33333f; border-radius: 6px; padding: 6px 8px; font-size: 13px;">
+ <option value="perf">Perf : optimisé vs naïf</option>
+ <option value="effects">Effets : activés vs coupés</option>
+ <option value="instruments">Mesure : instrumenté vs propre</option>
+ </select>
+ </div>
<button id="compare" style="background: #22222c; border: 1px solid #33333f">
- Comparer A/B
+ Comparer A/B (8 exports)
</button>
+ <span id="compareNote" style="font-size: 12px; color: #8b8b9a; align-self: center;"></span>
</div>
<div class="stats">
diff --git a/poc/main.js b/poc/main.js
index 404715473..1d65ce149 100644
--- a/poc/main.js
+++ b/poc/main.js
@@ -41,6 +41,7 @@ function regionStrength(t, start, end, ramp) {
}
const lerp = (a, b, t) => a + (b - a) * t;
+const clampAbs = (x, m) => Math.max(-m, Math.min(m, x));
const lerpRect = (a, b, t) => ({
x: lerp(a.x, b.x, t),
y: lerp(a.y, b.y, t),
@@ -129,12 +130,26 @@ function evaluate(sc, t, prev) {
// Circle when docked (radius = half the bubble), rounded rect when grown.
const webcamRadius = lerp(Math.min(base.webcam.w, base.webcam.h) / 2, 26, move);
- // --- velocity: what the motion blur is for ---
+ // --- motion blur: a VECTOR, along the camera's real travel ---
+ // The recording smears along how its centre moved since last frame, plus a
+ // term for the zoom scaling the content outward. A pan is diagonal; a
+ // horizontal-only smear would be wrong for most of what a screen demo does.
const cx = screen.x + screen.w / 2;
const cy = screen.y + screen.h / 2;
- let velocity = 0;
+ const wcx = webcam.x + webcam.w / 2;
+ const wcy = webcam.y + webcam.h / 2;
+ let screenBlur = { x: 0, y: 0 };
+ let webcamBlur = { x: 0, y: 0 };
if (prev) {
- velocity = Math.hypot(cx - prev.cx, cy - prev.cy) + Math.abs(screen.w - prev.w) * 0.5;
+ const k = 0.9;
+ screenBlur = {
+ x: clampAbs((cx - prev.cx) * k, 22),
+ y: clampAbs((cy - prev.cy) * k, 22),
+ };
+ webcamBlur = {
+ x: clampAbs((wcx - prev.wcx) * k, 18),
+ y: clampAbs((wcy - prev.wcy) * k, 18),
+ };
}
return {
@@ -142,8 +157,57 @@ function evaluate(sc, t, prev) {
webcam,
webcamRadius,
zoomScale,
- motionBlurPx: Math.min(velocity * 0.35, 24),
- memo: { cx, cy, w: screen.w },
+ screenBlur,
+ webcamBlur,
+ memo: { cx, cy, wcx, wcy },
+ };
+}
+
+// ---- the cursor: from the recorded trace, drawn synthetically ---------------
+//
+// The real product records positions + clicks and draws the cursor each frame
+// from that data — never baked into the video. This loads a REAL trace (the one
+// shipped with the screen recording) so the POC exercises the actual shape of the
+// data: normalised positions at irregular timestamps, and click/mouseup events.
+
+async function loadCursor(url) {
+ const doc = await (await fetch(url)).json();
+ // Dedup by timestamp (the trace repeats samples) and sort.
+ const byTime = new Map();
+ for (const s of doc.samples) byTime.set(s.timeMs, s);
+ const samples = [...byTime.values()].sort((a, b) => a.timeMs - b.timeMs);
+ const clicks = doc.samples.filter((s) => s.interactionType === "click").map((s) => s.timeMs);
+ return { samples, clicks };
+}
+
+/** Position (normalised to the recording) and click bounce at time t. */
+function cursorAt(trace, timeMs) {
+ const s = trace.samples;
+ if (s.length === 0) return null;
+ // Linear scan is fine at ~290 samples; a binary search is the same code later.
+ let i = 0;
+ while (i < s.length - 1 && s[i + 1].timeMs <= timeMs) i++;
+ const a = s[i];
+ const b = s[Math.min(i + 1, s.length - 1)];
+ const span = b.timeMs - a.timeMs;
+ const f = span > 0 ? Math.max(0, Math.min(1, (timeMs - a.timeMs) / span)) : 0;
+
+ // Click bounce: the pointer dips to 0.82 and springs back over ~140 ms after a
+ // real click — the same cue the app gives, driven by the recorded event.
+ let clickScale = 1;
+ for (const c of trace.clicks) {
+ const dt = timeMs - c;
+ if (dt >= 0 && dt < 140) {
+ const p = dt / 140;
+ clickScale = 1 - 0.18 * Math.sin(p * Math.PI);
+ }
+ }
+
+ return {
+ cx: lerp(a.cx, b.cx, f),
+ cy: lerp(a.cy, b.cy, f),
+ visible: a.visible !== false,
+ clickScale,
};
}
@@ -174,10 +238,12 @@ async function run(override = {}) {
document.querySelector("#run").disabled = true;
log("opening sources…");
- const [screen, webcam] = await Promise.all([
+ const [screen, webcam, cursor] = await Promise.all([
openVideo("media/screen.mp4"),
openVideo("media/webcam.mp4"),
+ loadCursor("media/cursor.json"),
]);
+ log(`cursor: ${cursor.samples.length} samples, ${cursor.clicks.length} clicks`);
const seconds = Number(document.querySelector("#seconds").value);
const screenDuration = await screen.track.computeDuration();
const duration = Math.min(seconds, screenDuration);
@@ -271,6 +337,7 @@ async function run(override = {}) {
screen: makePass("vsScreen", "fsScreen", OVER),
webcamShadow: makePass("vsWebcamShadow", "fsWebcamShadow", OVER),
webcam: makePass("vsWebcam", "fsWebcam", OVER),
+ cursor: makePass("vsCursor", "fsCursor", OVER),
};
// The bake runs before any video exists, so it gets a layout of its own: the
@@ -300,7 +367,7 @@ async function run(override = {}) {
// packing has to reproduce the holes exactly — get one offset wrong and the
// shader reads a radius where a rect belongs, draws nothing, and reports no
// error at all.
- const uniforms = new Float32Array(20);
+ const uniforms = new Float32Array(32);
const uniformBuffer = device.createBuffer({
size: uniforms.byteLength,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
@@ -314,14 +381,18 @@ async function run(override = {}) {
await output.start();
const sc = scene(OUT, Number(document.querySelector("#padding").value));
- const shadowIntensity = Number(document.querySelector("#shadow").value);
- const bgBlur = Number(document.querySelector("#blur").value);
+ // effectsOn === false forces the effects OFF (not just absent) so the "effects
+ // on vs off" comparison isolates their cost against the same everything-else.
+ const effectsOn = override.effectsOn ?? true;
+ const shadowIntensity = effectsOn ? Number(document.querySelector("#shadow").value) : 0;
+ const bgBlur = effectsOn ? Number(document.querySelector("#blur").value) : 0;
const camAspect = webcam.track.displayWidth / webcam.track.displayHeight;
let memo = null;
+ let curMemo = null;
// Bake the background. Once, here — not 210 times inside the loop.
uniforms.set([OUT.width, OUT.height, 0, 0], 0);
- uniforms.set([shadowIntensity, bgBlur, 18, 42], 12);
+ uniforms.set([shadowIntensity, bgBlur, 16, 22], 12);
device.queue.writeBuffer(uniformBuffer, 0, uniforms);
{
const enc = device.createCommandEncoder();
@@ -419,12 +490,32 @@ async function run(override = {}) {
m = mark();
const f = evaluate(sc, t, memo);
memo = f.memo;
+
+ // The cursor: interpolate the recorded trace, then place it in the SCREEN's
+ // coordinate space, so it rides the zoom for free — its position is carried
+ // through the same rect the recording is.
+ const cur = cursorAt(cursor, t * 1000);
+ const curX = f.screen.x + (cur?.cx ?? 0) * f.screen.w;
+ const curY = f.screen.y + (cur?.cy ?? 0) * f.screen.h;
+ const curSize = OUT.height * 0.05;
+ let curBlurX = 0;
+ let curBlurY = 0;
+ if (cur && curMemo) {
+ curBlurX = clampAbs((curX - curMemo.x) * 0.8, 30);
+ curBlurY = clampAbs((curY - curMemo.y) * 0.8, 30);
+ }
+ curMemo = cur ? { x: curX, y: curY } : null;
+ const curVisible = !!cur && cur.visible;
+
// Field n at float 4n — the struct is all-vec4 so this stays true.
uniforms.set([OUT.width, OUT.height, t, 28], 0); // stage | time | radius
uniforms.set([f.screen.x, f.screen.y, f.screen.w, f.screen.h], 4);
uniforms.set([f.webcam.x, f.webcam.y, f.webcam.w, f.webcam.h], 8);
- uniforms.set([shadowIntensity, bgBlur, 18, 42], 12); // intensity | bgBlur | offsetY | spread
- uniforms.set([f.webcamRadius, f.motionBlurPx, camAspect, optimised ? 1 : 0], 16);
+ uniforms.set([shadowIntensity, bgBlur, 16, 22], 12); // intensity | bgBlur | shadowOffsetY | sigma
+ uniforms.set([f.webcamRadius, 0, camAspect, optimised ? 1 : 0], 16); // radius | - | coverScale | opt
+ uniforms.set([f.screenBlur.x, f.screenBlur.y, f.webcamBlur.x, f.webcamBlur.y], 20); // mb
+ uniforms.set([curX, curY, curSize, curVisible ? 1 : 0], 24); // cursor
+ uniforms.set([curBlurX, curBlurY, cur?.clickScale ?? 1, 0], 28); // cursorFx
device.queue.writeBuffer(uniformBuffer, 0, uniforms);
const bind = device.createBindGroup({
layout: bindGroupLayout,
@@ -489,6 +580,12 @@ async function run(override = {}) {
pass.setPipeline(passes.webcam);
pass.draw(6);
}
+ // The cursor, on top of everything — drawn each frame from the trace, culled
+ // when the recorded position is off-stage.
+ if (curVisible && curX > -curSize && curY > -curSize && curX < OUT.width && curY < OUT.height) {
+ pass.setPipeline(passes.cursor);
+ pass.draw(6);
+ }
pass.end();
if (useQueries) {
encoder.resolveQuerySet(querySet, 0, 2, resolveBuffer, 0);
@@ -670,49 +767,86 @@ async function run(override = {}) {
* arms differ by that uniform and nothing else — no reload, no recompile, no
* second session.
*/
+// Every A/B this POC can run, each naming EXACTLY the two things it compares and
+// what one run() override turns one arm into the other. Each holds everything
+// else fixed, so the difference is the named lever and nothing else.
+const COMPARISONS = {
+ perf: {
+ title: "Perf : optimisé vs naïf",
+ a: { label: "optimisé", over: { optimised: true, instrumented: false } },
+ b: { label: "naïf", over: { optimised: false, instrumented: false } },
+ note: "fond cuit + culling, vs fond recalculé + tout dessiné. Même image.",
+ },
+ effects: {
+ title: "Effets : activés vs coupés",
+ a: { label: "effets ON", over: { effectsOn: true, optimised: true, instrumented: false } },
+ b: { label: "effets OFF", over: { effectsOn: false, optimised: true, instrumented: false } },
+ note: "ombre + flou de fond présents, vs à zéro. Le prix des effets eux-mêmes.",
+ },
+ instruments: {
+ title: "Mesure : instrumenté vs propre",
+ a: { label: "instrumenté", over: { instrumented: true, optimised: true } },
+ b: { label: "propre", over: { instrumented: false, optimised: true } },
+ note: "fence + lecture des timestamps par image, vs rien. Le coût de la mesure.",
+ },
+};
+
+/**
+ * Interleaved A/B/A/B, because an effect can only be told apart from drift.
+ *
+ * Two identical runs measured 34.8 and 28.3 fps on this machine — 23% apart,
+ * which is the size of the effects under test. Sequential arms therefore prove
+ * nothing: they alternate so drift shows up as a run disagreeing with its OWN
+ * repeat instead of masquerading as the change. Same rule, and same reason, as
+ * the app's export bench. The shader variants all live in one module, chosen by a
+ * uniform, so an arm differs from its pair by that uniform and nothing else.
+ */
async function compare(rounds = 3) {
+ const spec = COMPARISONS[document.querySelector("#compareMode").value] ?? COMPARISONS.perf;
const median = (xs) => {
const s = [...xs].sort((a, b) => a - b);
return s.length % 2 ? s[(s.length - 1) / 2] : (s[s.length / 2 - 1] + s[s.length / 2]) / 2;
};
const spread = (xs) => (Math.max(...xs) - Math.min(...xs)) / median(xs);
- const arms = { OPTIMISED: [], NAIVE: [] };
+ const arms = [
+ { ...spec.a, runs: [] },
+ { ...spec.b, runs: [] },
+ ];
// Round 0 is thrown away. Both arms climb monotonically across the first
- // rounds — 15.0 → 28.4 → 33.3 and 27.9 → 37.2 → 42.0 — which is the browser
- // and the GPU waking up, not the arms differing. Keeping it put a 64% spread
- // on a 23% effect and voided the comparison by itself.
+ // rounds — 15.0 → 28.4 → 33.3 — which is the browser and the GPU waking up,
+ // not the arms differing. Keeping it put a 64% spread on a 23% effect and
+ // voided the comparison by itself.
for (let r = 0; r <= rounds; r++) {
- for (const [name, optimised] of [
- ["OPTIMISED", true],
- ["NAIVE", false],
- ]) {
- // Clean on both sides: the instruments cost 17%, and they are not what
- // is being compared here.
- const res = await run({ optimised, instrumented: false });
- if (r > 0) arms[name].push(res.cruiseFps);
+ for (const arm of arms) {
+ const res = await run(arm.over);
+ if (r > 0) arm.runs.push(res.cruiseFps);
}
}
document.querySelector("#log").textContent = "";
- log("=== baked background + shadow early-out, vs neither (interleaved A/B) ===\n");
- for (const [name, xs] of Object.entries(arms)) {
+ log(`=== ${spec.title} — A/B interleavé, ${rounds} tours + 1 chauffe ===`);
+ log(`${spec.note}\n`);
+ for (const arm of arms) {
log(
- `${name.padEnd(13)} cruise ${median(xs).toFixed(1).padStart(5)} fps spread ${(spread(xs) * 100).toFixed(0)}% runs: ${xs.map((x) => x.toFixed(1)).join(" / ")}`,
+ `${arm.label.padEnd(13)} croisière ${median(arm.runs).toFixed(1).padStart(5)} fps spread ${(spread(arm.runs) * 100).toFixed(0)}% ${arm.runs.map((x) => x.toFixed(1)).join(" / ")}`,
);
}
- const gain = median(arms.OPTIMISED) - median(arms.NAIVE);
- const gainPct = (gain / median(arms.NAIVE)) * 100;
- const worst = Math.max(spread(arms.OPTIMISED), spread(arms.NAIVE)) * 100;
- log(`\ngain: ${gain > 0 ? "+" : ""}${gain.toFixed(1)} fps (${gainPct.toFixed(0)}%)`);
+ const [A, B] = arms;
+ const gain = median(A.runs) - median(B.runs);
+ const gainPct = (gain / median(B.runs)) * 100;
+ const worst = Math.max(spread(A.runs), spread(B.runs)) * 100;
+ log(
+ `\n${A.label} vs ${B.label}: ${gain > 0 ? "+" : ""}${gain.toFixed(1)} fps (${gainPct.toFixed(0)}%)`,
+ );
if (worst >= Math.abs(gainPct)) {
log(
- `\n!! VOID: same-arm spread reaches ${worst.toFixed(0)}%, as large as the effect.\n This run says nothing. Repeat on a steadier machine.`,
+ `\n!! VOID : spread intra-bras ${worst.toFixed(0)}%, aussi grand que l'effet.\n Ce run ne dit rien — refaire sur une machine calme.`,
);
} else {
- log(`\nsame-arm spread ${worst.toFixed(0)}% — smaller than the effect, so the effect is real.`);
+ log(`\nspread intra-bras ${worst.toFixed(0)}% < l'effet — le résultat tient.`);
}
- setStat("fps", median(arms.OPTIMISED).toFixed(1));
+ setStat("fps", median(A.runs).toFixed(1));
}
document.querySelector("#run").addEventListener("click", () => {
@@ -725,10 +859,18 @@ document.querySelector("#run").addEventListener("click", () => {
});
document.querySelector("#compare").addEventListener("click", () => {
- document.querySelector("#log").textContent = "comparing, please wait…\n";
+ document.querySelector("#log").textContent = "comparaison en cours, patientez…\n";
compare().catch((error) => {
log(`\nFAILED: ${error.message}`);
console.error(error);
document.querySelector("#run").disabled = false;
});
});
+
+// Show the selected comparison's plain-language note next to the dropdown.
+const modeSelect = document.querySelector("#compareMode");
+const updateNote = () => {
+ document.querySelector("#compareNote").textContent = COMPARISONS[modeSelect.value]?.note ?? "";
+};
+modeSelect.addEventListener("change", updateNote);
+updateNote();