Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

R3F25 (part): postprocessing's effects as raea FramePasses, a FramePass's uv over the camera's Viewport, three's tone exposure as a Grade exposure

shinyobjectzf5f7b72912e7
diff --git a/docs/r3f.feature b/docs/r3f.feature
index b0ffa45f..20166829 100644
--- a/docs/r3f.feature
+++ b/docs/r3f.feature
@@ -470,6 +470,17 @@ Feature: React Three Fiber both ways: an R3F scene drawn by raea, a raea composi
ray-traced reflections) or a <FramePass> raea ships for it: Noise, Scanline, Sepia, DotScreen, ColorAverage,
ColorDepth, Grid, Glitch, ShockWave, TiltShift, ASCII, LUT, GodRays, Outline
And none is left out without a warning; in-post2 and in-tslpost: SSIM at least 0.92 against three.js
+ Status (11-15, in progress): postprocessing's Noise, Scanline, Sepia, DotScreen, ColorAverage, ColorDepth, Grid,
+ Glitch, ShockWave, LUT3D and @react-three/postprocessing's ASCII and TiltShift2 are FramePasses with their own
+ shaders in WGSL (sdk/r3f src/input/effects.ts, effects-sampled.ts); TiltShift (one Gaussian for its Kawase blur)
+ and GodRays (the sun's disc against the depth prepass, unblurred) are close and say so. A FramePass's uv now spans
+ the camera's Viewport, not the Engine's w x (h + 1) target (systems/framepass: patterns drifted a row by the
+ frame's foot). three's tone exposure (toneMappingExposure, ACES's 1/0.6) is a Grade `exposure`, Bevy's colour
+ grading on every pixel before the curve (new: grade_exposure), not the camera's, which skipped unlit colours (0.74
+ stops dark under ACES) and made effects before a composer's ToneMapping read lit and unlit pixels in two scales.
+ in-post2 0.9879, in-post3 0.9767; the full parity list unchanged. Left: Outline (selected meshes in a composition
+ pass, once scene.ts is free), Texture, Depth, LUT1D, three/webgpu's PostProcessing (in-tslpost), and the
+ background under a composer's ToneMapping (three maps it, raea shows it as given)
Scenario: R3F26. <R3F> in a box smaller than the page (#130)
Given an <R3F> in a box of its own inside a larger page
diff --git a/runtime/look/src/post.rs b/runtime/look/src/post.rs
index 8308e277..60276acd 100644
--- a/runtime/look/src/post.rs
+++ b/runtime/look/src/post.rs
@@ -190,7 +190,7 @@ fn grade(g: &Map<String, Value>, row: &mut BTreeMap<String, V>) {
if let Some(s) = shares(g) {
row.insert("grade_passes".into(), V::S(s));
}
- for (k, col) in [("temperature", "grade_temperature"), ("tint", "grade_tint"), ("saturation", "grade_saturation")] {
+ for (k, col) in [("temperature", "grade_temperature"), ("tint", "grade_tint"), ("saturation", "grade_saturation"), ("exposure", "grade_exposure")] {
if let Some(x) = num(g, k) {
row.insert(col.into(), V::N(x));
}
diff --git a/sdk/guides/craft/bevy/r3f.md b/sdk/guides/craft/bevy/r3f.md
index 8f2253ba..57eb3639 100644
--- a/sdk/guides/craft/bevy/r3f.md
+++ b/sdk/guides/craft/bevy/r3f.md
@@ -88,8 +88,10 @@ normal, matcap, shadow, points and line materials; ShaderMaterial and RawShaderM
by raea); TSL node materials, unlit and lit (0.1.5); textures, environment maps, fog, the background, shadows; drei's
`<Text>`, `<Sky>`, `<Stars>`, `<Clouds>`, `<ContactShadows>`, `<Environment>`; @react-three/postprocessing's effects
that raea has (bloom, vignette, depth of field and bokeh, chromatic aberration, lens distortion, SSAO,
-anti-aliasing, pixelation, tone mapping, brightness, contrast, hue and saturation). Close, not exact:
-hemisphere lights, light probes, Phong and toon materials.
+anti-aliasing, pixelation, tone mapping, brightness, contrast, hue and saturation), and, as raea frame passes running
+the effect's own shader (0.1.5), noise, scanlines, sepia, dot screen, colour average and depth, grid, glitch, shock
+wave, LUT, ASCII and `<TiltShift2>`. Close, not exact: hemisphere lights, light probes, Phong and toon materials,
+`<TiltShift>` and `<GodRays>`.
What raea can't draw is named once in the render's output (`raea/r3f: ...`), and the frame draws without it:
diff --git a/sdk/r3f/src/input/effects-sampled.ts b/sdk/r3f/src/input/effects-sampled.ts
new file mode 100644
index 00000000..9b604ceb
--- /dev/null
+++ b/sdk/r3f/src/input/effects-sampled.ts
@@ -0,0 +1,294 @@
+// postprocessing's effects that read more than the frame's own pixel, as raea <FramePass>es (docs/r3f.feature R3F25,
+// effects.ts): the frame elsewhere (a glitch's or a shock wave's moved uv, a tilt shift's blur, an ASCII cell), a
+// texture (a glitch's perturbation map, the ASCII characters, a LUT), the depth (god rays). Where three draws a pass of
+// its own first (a Kawase blur, the light source's mask), the FramePass does its work in one go, close to it, and says
+// so once.
+import * as THREE from "three";
+import type { Ctx, Extra, PPEffect, Spec } from "./effects";
+import { flipsY, pngOf, srcOf } from "./texture";
+
+type U = { value: unknown };
+const u = (e: PPEffect, k: string) => (e.uniforms?.get(k) as U | undefined)?.value;
+const num = (v: unknown, d: number) => (typeof v === "number" && Number.isFinite(v) ? v : d);
+
+/** a texture as a FramePass takes it, and whether its rows count from the bottom; undefined when raea can't load it */
+function picture(t: unknown, sampler: Record<string, unknown>): { pic: unknown; flip: number } | undefined {
+ const tex = t as THREE.Texture | null;
+ const src = tex && srcOf(tex);
+ return src ? { pic: { src, sampler }, flip: flipsY(tex) ? 1 : 0 } : undefined;
+}
+
+/** postprocessing's KawaseBlurPass kernels, by KernelSize */
+const KERNELS = [[0, 0], [0, 1, 1], [0, 1, 1, 2], [0, 1, 2, 2, 3], [0, 1, 2, 3, 4, 4, 5], [0, 1, 2, 3, 4, 5, 7, 8, 9, 10]];
+
+/** a Kawase blur's spread as a Gaussian's sigma in pixels: each pass averages four taps (k + 0.5) texels off on both
+ * axes, at the pass's resolution scale */
+function kawaseSigma(kernelSize: number, resolutionScale: number, scale: number): number {
+ const k = KERNELS[Math.max(0, Math.min(KERNELS.length - 1, Math.round(kernelSize)))];
+ const texel = 1 / Math.max(resolutionScale, 1e-3);
+ return Math.sqrt(k.reduce((s, x) => s + ((x + 0.5) * texel * scale) ** 2, 0));
+}
+
+/** a 3D LUT (three's Data3DTexture, n x n x n) as a horizontal strip picture, n slices of blue side by side, red
+ * across each and green down, as postprocessing's 2D LUTs are laid out */
+const strips = new WeakMap<object, string>();
+function stripOf(t: THREE.Data3DTexture): string | undefined {
+ const done = strips.get(t);
+ if (done) return done;
+ const { data, width: n, height, depth } = t.image as { data: ArrayLike<number>; width: number; height: number; depth: number };
+ if (!data || n !== height || n !== depth) return undefined;
+ const ch = Math.round(data.length / (n * n * n));
+ if (ch < 3) return undefined;
+ const float = !(data instanceof Uint8Array || data instanceof Uint8ClampedArray);
+ const rgba = new Uint8Array(n * n * n * 4);
+ for (let b = 0; b < n; b++)
+ for (let g = 0; g < n; g++)
+ for (let r = 0; r < n; r++) {
+ const from = ((b * n + g) * n + r) * ch;
+ const to = (g * n * n + b * n + r) * 4;
+ for (let i = 0; i < 3; i++) rgba[to + i] = float ? Math.round(Math.min(1, Math.max(0, data[from + i])) * 255) : data[from + i];
+ rgba[to + 3] = 255;
+ }
+ const s = pngOf(rgba, n * n, n);
+ strips.set(t, s);
+ return s;
+}
+
+const v3 = new THREE.Vector3();
+const sphere = new THREE.Sphere();
+
+export const SAMPLED: Record<string, Spec> = {
+ // the frame read at a uv a random column or row band flips, nudged by the perturbation map (its update() picks the
+ // band and seeds each frame, by R3F's clock and Math.random, seeded in raea)
+ GlitchEffect: {
+ uv: true,
+ uniforms: ["active", "columns", "random", "seeds", "distortion"],
+ extra: (e) => {
+ const t = picture(u(e, "perturbationMap"), { wrap: "repeat" });
+ return t && { textures: { perturb: t.pic }, uniforms: { flip: t.flip } };
+ },
+ body: `var q = p;
+ if (u_active() > 0.5) {
+ let cols = u_columns();
+ let rnd = u_random();
+ let seeds = u_seeds();
+ let dist = u_distortion();
+ if (q.y < dist.x + cols && q.y > dist.x - cols * rnd) {
+ let sx = clamp(ceil(seeds.x), 0.0, 1.0);
+ q.y = sx * (1.0 - (q.y + dist.y)) + (1.0 - sx) * dist.y;
+ }
+ if (q.x < dist.y + cols && q.x > dist.y - cols * rnd) {
+ let sy = clamp(ceil(seeds.y), 0.0, 1.0);
+ q.x = sy * dist.x + (1.0 - sy) * (1.0 - (q.x + dist.x));
+ }
+ let tq = q * rnd * rnd;
+ let n = textureSampleLevel(tex_perturb, samp_perturb, select(tq, vec2<f32>(tq.x, 1.0 - tq.y), u_flip() > 0.5), 0.0).rg;
+ q += n * seeds * (rnd * 0.2);
+ }
+ o = pp_frame(q);`,
+ },
+ // the frame pushed out in a ring around the epicentre (its update() projects it and grows the ring)
+ ShockWaveEffect: {
+ uv: true,
+ uniforms: ["active", "center", "cameraDistance", "size", "radius", "maxRadius", "waveSize", "amplitude"],
+ body: `var q = p;
+ if (u_active() > 0.5) {
+ let ac = vec2<f32>(u_resolution().x / u_resolution().y, 1.0);
+ let d = q * ac - u_center() * ac;
+ let dist = sqrt(dot(d, d)) * (0.1 * u_cameraDistance() / u_size());
+ if (dist > u_radius() && dist < u_radius() + u_waveSize()) {
+ let angle = (dist - u_radius()) * 6.283185307179586 / u_waveSize();
+ let cs = (1.0 - cos(angle)) * 0.5;
+ let extent = u_maxRadius() + u_waveSize();
+ let decay = max(extent - dist * dist, 0.0) / extent;
+ q -= ((cs * u_amplitude() * d) / dist) * decay;
+ }
+ }
+ o = pp_frame(q);`,
+ },
+ // postprocessing's: the frame blurred outside a band (its Kawase blur passes, here one Gaussian of their spread),
+ // the band's own pixels kept
+ TiltShiftEffect: {
+ uniforms: ["rotation", "maskParams"],
+ extra: (e, ctx) => {
+ const bp = e.blurPass as { kernelSize?: number; scale?: number; resolution?: { scale?: number }; blurMaterial?: { uniforms?: { maskParams?: U } } } | undefined;
+ const mask = bp?.blurMaterial?.uniforms?.maskParams?.value as THREE.Vector4 | undefined;
+ if (!mask) return undefined;
+ ctx.warn("<TiltShift>", "is blurred in one pass, a Gaussian as wide as its Kawase blur: close to three's, not the same");
+ return { uniforms: { blurMask: [mask.x, mask.y, mask.z, mask.w], sigma: kawaseSigma(num(bp?.kernelSize, 2), num(bp?.resolution?.scale, 0.5), num(bp?.scale, 1)) } };
+ },
+ body: `let res = u_resolution();
+ var v2 = (p - 0.5) * 2.0 * vec2<f32>(res.x / res.y, 1.0);
+ let rot = u_rotation();
+ v2 = vec2<f32>(dot(rot, v2), dot(rot, vec2<f32>(v2.y, -v2.x)));
+ let bm = u_blurMask();
+ let sg = (1.0 - (smoothstep(bm.x, bm.y, v2.y) - smoothstep(bm.w, bm.z, v2.y))) * u_sigma();
+ var acc = vec4<f32>(0.0);
+ var wsum = 0.0;
+ for (var i = -3; i <= 3; i++) {
+ for (var j = -3; j <= 3; j++) {
+ let d = vec2<f32>(f32(i), f32(j)) * 0.7;
+ let w = exp(-0.5 * dot(d, d));
+ acc += pp_frame(p + d * sg / res) * w;
+ wsum += w;
+ }
+ }
+ let mp = u_maskParams();
+ o = mix(acc / wsum, c, step(mp.x, v2.y) - step(mp.y, v2.y));`,
+ },
+ // @react-three/postprocessing's <TiltShift2> (Evan Wallace's): the frame blurred along `direction`, more the further
+ // from the line from `start` to `end`
+ TiltShift2Effect: {
+ uniforms: ["blur", "taper", "start", "end", "direction", "samples"],
+ body: `let res = u_resolution();
+ let sp = u_start() * res;
+ let ep = u_end() * res;
+ let fs = u_samples();
+ let hs = fs / 2.0;
+ let maxd = length(res);
+ let fc = vec3<f32>(in.position.x, res.y - in.position.y, 0.5);
+ let off = fract(sin(dot(fc, vec3<f32>(12.9898, 78.233, 151.7182))) * 43758.5453);
+ let nrm = normalize(vec2<f32>(sp.y - ep.y, ep.x - sp.x));
+ let radius = smoothstep(0.0, 1.0, abs(dot(p * res - sp, nrm)) / (u_taper() * maxd)) * u_blur() * (maxd / 16.0);
+ var acc = vec4<f32>(0.0);
+ var total = 0.0;
+ for (var i = 0; i <= 100; i++) {
+ if (f32(i) >= fs) { break; }
+ let pc = (-hs + f32(i) + off - 0.5) / hs;
+ let w = 1.0 - abs(pc);
+ let s = pp_frame(p + normalize(u_direction()) / res * pc * radius);
+ acc += vec4<f32>(s.rgb * s.a, s.a) * w;
+ total += w;
+ }
+ o = acc / total;
+ o = vec4<f32>(o.rgb / (o.a + 0.00001), o.a);`,
+ },
+ // @react-three/postprocessing's <ASCII>: each cell's grey picks a character from the canvas it drew them on
+ ASCIIEffect: {
+ uniforms: ["uCellSize", "uCharactersCount", "uInvert", "uColor"],
+ extra: (e) => {
+ const t = picture(u(e, "uCharacters"), { wrap: "repeat", filter: "nearest" });
+ return t && { textures: { chars: t.pic }, uniforms: { flip: t.flip } };
+ },
+ body: `let cell = u_resolution() / u_uCellSize();
+ let grid = 1.0 / cell;
+ let px = pp_frame(grid * (0.5 + floor(p / grid)));
+ var g = dot(px.rgb, vec3<f32>(0.299, 0.587, 0.114));
+ if (u_uInvert() > 0.5) { g = 1.0 - g; }
+ let ci = floor((u_uCharactersCount() - 1.0) * g);
+ let offs = vec2<f32>(ci - 16.0 * floor(ci / 16.0), -floor(ci / 16.0)) / 16.0;
+ let m = p * (cell / 16.0);
+ let cu = (m - floor(m * 16.0) / 16.0) - vec2<f32>(0.0, 1.0 / 16.0) + offs;
+ let ch = textureSampleLevel(tex_chars, samp_chars, select(cu, vec2<f32>(cu.x, 1.0 - cu.y), u_flip() > 0.5), 0.0);
+ o = vec4<f32>(u_uColor() * ch.r, px.a);`,
+ },
+ // postprocessing's LUT3DEffect (<LUT>): the colour looked up in its table, in sRGB as the effect reads it; a 3D table
+ // as a strip of slices (a 2D one as it's drawn), between two slices
+ LUT3DEffect: {
+ srgb: true,
+ uniforms: [],
+ extra: (e, ctx) => {
+ const t = u(e, "lut") as (THREE.Texture & { isData3DTexture?: boolean }) | null;
+ if (!t?.image) return undefined;
+ const { width, height } = t.image as { width: number; height: number };
+ let lut: Extra["textures"];
+ let horizontal = width > height ? 1 : 0;
+ let size = Math.min(width, height);
+ let [tw, th] = [1 / width, 1 / height];
+ let flip = 0;
+ if (t.isData3DTexture) {
+ const s = stripOf(t as THREE.Data3DTexture);
+ if (!s) return undefined;
+ lut = { lut: { src: s } };
+ [horizontal, size, tw, th] = [1, width, 1 / (width * width), 1 / width];
+ } else {
+ const p = picture(t, {});
+ if (!p) return undefined;
+ lut = { lut: p.pic };
+ flip = p.flip;
+ }
+ if (e.defines?.has("CUSTOM_INPUT_DOMAIN")) ctx.warn("<LUT> input domain", "isn't read: the table spans 0 to 1");
+ return { textures: lut, uniforms: { lut: [size, tw, th, horizontal], flip } };
+ },
+ body: `let l = u_lut();
+ let rgb = clamp(c.rgb, vec3<f32>(0.0), vec3<f32>(1.0)) * ((l.x - 1.0) / l.x) + 0.5 / l.x;
+ let slice = rgb.b * l.x;
+ let s0 = floor(slice);
+ let ci = slice - s0 - 0.5;
+ let s1 = s0 + sign(ci);
+ var uv0 = vec2<f32>(0.0);
+ var uv1 = vec2<f32>(0.0);
+ if (l.w > 0.5) {
+ let xo = clamp(rgb.r * l.z, l.y * 0.5, l.z - l.y * 0.5);
+ uv0 = vec2<f32>(s0 * l.z + xo, rgb.g);
+ uv1 = vec2<f32>(s1 * l.z + xo, rgb.g);
+ } else {
+ let yo = clamp(rgb.g * l.y, l.z * 0.5, l.y - l.z * 0.5);
+ uv0 = vec2<f32>(rgb.r, s0 * l.y + yo);
+ uv1 = vec2<f32>(rgb.r, s1 * l.y + yo);
+ }
+ if (u_flip() > 0.5) {
+ uv0.y = 1.0 - uv0.y;
+ uv1.y = 1.0 - uv1.y;
+ }
+ let a0 = textureSampleLevel(tex_lut, samp_lut, uv0, 0.0);
+ let a1 = textureSampleLevel(tex_lut, samp_lut, uv1, 0.0);
+ o = vec4<f32>(mix(a0, a1, abs(ci)).rgb, c.a);`,
+ },
+ // god rays: light streaked from the sun toward each pixel, decaying, where the sun is seen. three draws the light
+ // source into a mask of its own (the scene's depth in front of it) and blurs the rays; here the mask is the sun's
+ // disc on screen where the depth prepass has nothing nearer, the rays unblurred
+ GodRaysEffect: {
+ uniforms: [],
+ extra: (e, ctx) => {
+ const sun = (e.lightSource ?? e._lightSource) as THREE.Mesh | undefined;
+ const cam = (e.camera as THREE.Camera | undefined) ?? ctx.camera;
+ const m = e.godRaysMaterial as { uniforms?: Record<string, U>; defines?: Record<string, string> } | undefined;
+ if (!sun?.isMesh || !cam || !m?.uniforms) return undefined;
+ sun.updateWorldMatrix(true, false);
+ cam.updateWorldMatrix(true, false);
+ const g = sun.geometry;
+ if (!g.boundingSphere) g.computeBoundingSphere();
+ sphere.copy(g.boundingSphere ?? new THREE.Sphere(new THREE.Vector3(), 1)).applyMatrix4(sun.matrixWorld);
+ const z = -v3.copy(sphere.center).applyMatrix4(cam.matrixWorldInverse).z;
+ if (z <= 0) return undefined;
+ const ndc = v3.copy(sphere.center).project(cam);
+ const persp = cam as THREE.PerspectiveCamera;
+ const fy = persp.isPerspectiveCamera ? 1 / Math.tan(THREE.MathUtils.degToRad(persp.fov) / 2) : 1;
+ const aspect = ctx.size[0] / ctx.size[1];
+ const ry = persp.isPerspectiveCamera ? (sphere.radius / z) * fy * 0.5 : 0.05;
+ const mat = (Array.isArray(sun.material) ? sun.material[0] : sun.material) as THREE.MeshBasicMaterial;
+ const col = mat?.color ?? new THREE.Color(1, 1, 1);
+ const a = mat?.transparent ? num(mat.opacity, 1) : 1;
+ const un = (k: string, d: number) => num(m.uniforms?.[k]?.value, d);
+ ctx.warn("<GodRays>", "masks the light by its disc on screen and the depth, its rays unblurred: close to three's, not the same");
+ return {
+ prepass: true,
+ uniforms: {
+ sun: [(ndc.x + 1) / 2, (ndc.y + 1) / 2, ry / aspect, ry],
+ rays: [un("density", 0.96), un("decay", 0.9), un("weight", 0.4), un("exposure", 0.6)],
+ more: [un("clampMax", 1), Number(m.defines?.SAMPLES_INT ?? 60), z, sphere.radius],
+ color: [col.r * a, col.g * a, col.b * a],
+ },
+ };
+ },
+ body: `let sun = u_sun();
+ let rays = u_rays();
+ let more = u_more();
+ let n = max(more.y, 1.0);
+ var coord = p;
+ let delta = (sun.xy - p) * (1.0 / n) * rays.x;
+ var decay = 1.0;
+ var acc = vec3<f32>(0.0);
+ for (var i = 0; i < 256; i++) {
+ if (f32(i) >= n) { break; }
+ coord += delta;
+ let d = (coord - sun.xy) / sun.zw;
+ if (dot(d, d) <= 1.0 && depth(vec2<f32>(coord.x, 1.0 - coord.y)) >= more.z - more.w * 1.05) {
+ acc += u_color() * decay * rays.z;
+ }
+ decay *= rays.y;
+ }
+ o = vec4<f32>(clamp(acc * rays.w, vec3<f32>(0.0), vec3<f32>(more.x)), c.a);`,
+ },
+};
diff --git a/sdk/r3f/src/input/effects.ts b/sdk/r3f/src/input/effects.ts
new file mode 100644
index 00000000..b833940d
--- /dev/null
+++ b/sdk/r3f/src/input/effects.ts
@@ -0,0 +1,197 @@
+// postprocessing's effects raea has no effect of its own for, as raea <FramePass>es (docs/r3f.feature R3F25): each
+// effect's mainImage or mainUv (its GLSL in pmndrs' postprocessing, or @react-three/postprocessing's own) ported to
+// WGSL, read with its own uniforms as the effect set them (a scanline's count, a grid's scale, a dot screen's angle:
+// what its setSize and setters worked out), then blended over the frame by its blendFunction and opacity, as its
+// EffectPass blends it. A pass runs where the effect does in the composer: on the frame before tone mapping, or after
+// it when it comes after a <ToneMapping>. The effects that read the frame elsewhere, a texture or the depth are in
+// effects-sampled.ts.
+import type * as THREE from "three";
+import { FramePass } from "raea/3d";
+import { COMPONENTS } from "../parts";
+import type { Part } from "./material";
+import { SAMPLED } from "./effects-sampled";
+
+// raea's <FramePass> among the components a part may name (here until parts.tsx's table takes it: lane r3f-tsl has
+// that table open for R3F22's <Compute>)
+COMPONENTS.FramePass ??= FramePass;
+
+/** an effect of pmndrs' postprocessing, as post.ts reads it */
+export interface PPEffect {
+ name: string;
+ blendMode?: { blendFunction?: number; opacity?: { value: number } };
+ uniforms?: Map<string, { value: unknown }>;
+ defines?: Map<string, string>;
+ inputColorSpace?: string | null;
+ [k: string]: unknown;
+}
+
+/** where an effect is drawn: the composer's clock (R3F's, in seconds), the frame's size, whether a <ToneMapping> comes
+ * before it, the composer's camera, and how to name what's drawn differently */
+export interface Ctx {
+ time: number;
+ size: [number, number];
+ after: boolean;
+ camera?: THREE.Camera;
+ warn: (k: string, why: string) => void;
+}
+
+/** what an effect adds to its pass beyond its own uniforms: values worked out here, textures (a picture each, as a
+ * <FramePass>'s `textures` takes it), the depth prepass */
+export interface Extra {
+ uniforms?: Record<string, number | number[]>;
+ textures?: Record<string, unknown>;
+ prepass?: boolean;
+}
+
+/** one effect in WGSL: `c` is the frame's colour, `p` the uv as GL has it (y up), `o` what it outputs; its uniforms
+ * (u_NAME()) are the effect's own, plus `time`, `resolution` and what `extra` works out. `uv`: a mainUv effect,
+ * whose output is the frame read at its moved uv, never blended. `srgb`: an effect that reads sRGB colours
+ * (inputColorSpace), as its EffectPass hands them over and takes them back */
+export interface Spec {
+ uniforms: string[];
+ body: string;
+ extra?: (e: PPEffect, ctx: Ctx) => Extra | undefined;
+ uv?: boolean;
+ srgb?: boolean;
+}
+
+/** three's `rand` (ShaderChunk common), its sRGB transfer, the frame read at a GL uv, and postprocessing's blend
+ * functions, by BlendFunction's number */
+const PRELUDE = /* wgsl */ `
+fn pp_rand(uv: vec2<f32>) -> f32 {
+ let dt = dot(uv, vec2<f32>(12.9898, 78.233));
+ let sn = dt - 3.141592653589793 * floor(dt / 3.141592653589793);
+ return fract(sin(sn) * 43758.5453);
+}
+fn pp_srgb(c: vec3<f32>) -> vec3<f32> {
+ return select(pow(max(c, vec3<f32>(0.0)), vec3<f32>(0.41666)) * 1.055 - 0.055, c * 12.92, c <= vec3<f32>(0.0031308));
+}
+fn pp_linear(c: vec3<f32>) -> vec3<f32> {
+ return select(pow(max(c, vec3<f32>(0.0)) * 0.9478672986 + 0.0521327014, vec3<f32>(2.4)), c * 0.0773993808, c <= vec3<f32>(0.04045));
+}
+fn pp_frame(q: vec2<f32>) -> vec4<f32> {
+ return frame(vec2<f32>(q.x, 1.0 - q.y));
+}
+fn pp_blend(dst: vec4<f32>, src: vec4<f32>, opacity: f32, mode: i32) -> vec4<f32> {
+ let a = dst.rgb;
+ let b = src.rgb;
+ var c = b;
+ switch mode {
+ case 0: { c = a + b; }
+ case 1: { return mix(dst, src, src.a * opacity); }
+ case 2: { c = (a + b) * 0.5; }
+ case 4: { c = mix(step(vec3<f32>(0.0), b) * (1.0 - min(vec3<f32>(1.0), (1.0 - a) / max(b, vec3<f32>(1e-9)))), vec3<f32>(1.0), step(vec3<f32>(1.0), a)); }
+ case 5: { c = step(vec3<f32>(0.0), a) * mix(min(vec3<f32>(1.0), a / max(1.0 - b, vec3<f32>(1e-9))), vec3<f32>(1.0), step(vec3<f32>(1.0), b)); }
+ case 6: { c = min(a, b); }
+ case 7: { c = abs(a - b); }
+ case 8: { c = a / max(b, vec3<f32>(1e-9)); }
+ case 9: { return dst; }
+ case 10: { c = a + b - 2.0 * a * b; }
+ case 11: { let x = min(a, vec3<f32>(1.0)); let y = min(b, vec3<f32>(1.0)); c = mix(2.0 * x * y, 1.0 - 2.0 * (1.0 - x) * (1.0 - y), step(vec3<f32>(0.5), y)); }
+ case 16: { c = max(a, b); }
+ case 17: { c = clamp(b + a - 1.0, vec3<f32>(0.0), vec3<f32>(1.0)); }
+ case 18: { c = min(a + b, vec3<f32>(1.0)); }
+ case 21: { c = a * b; }
+ case 22: { c = max(1.0 - abs(1.0 - a - b), vec3<f32>(0.0)); }
+ case 23: { return mix(dst, src, opacity); }
+ case 24: { c = mix(2.0 * b * a, 1.0 - 2.0 * (1.0 - b) * (1.0 - a), step(vec3<f32>(0.5), a)); }
+ case 26: { c = mix(min(a * a / max(1.0 - b, vec3<f32>(1e-9)), vec3<f32>(1.0)), b, step(vec3<f32>(1.0), b)); }
+ case 28: { c = a + b - min(a * b, vec3<f32>(1.0)); }
+ case 30: { return src; }
+ case 31: { c = max(a - b, vec3<f32>(0.0)); }
+ default: { return mix(dst, src, opacity); }
+ }
+ return mix(dst, vec4<f32>(c, max(dst.a, src.a)), opacity);
+}
+`;
+
+/** the blend functions PRELUDE has (the rest are drawn as NORMAL, named once) */
+const BLENDS = new Set([0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 16, 17, 18, 21, 22, 23, 24, 26, 28, 30, 31]);
+
+/** the effects that read only the frame's own pixel */
+const BODIES: Record<string, Spec> = {
+ NoiseEffect: {
+ uniforms: [],
+ extra: (e) => ({ uniforms: { premultiply: e.defines?.has("PREMULTIPLY") ? 1 : 0 } }),
+ body: "let n = vec3<f32>(pp_rand(p * (1.0 + u_time())));\n o = select(vec4<f32>(n, c.a), vec4<f32>(min(c.rgb * n, vec3<f32>(1.0)), c.a), u_premultiply() > 0.5);",
+ },
+ ScanlineEffect: {
+ uniforms: ["count", "scrollSpeed"],
+ body: "let y = p.y + u_time() * u_scrollSpeed();\n let sl = vec2<f32>(sin(y * u_count()), cos(y * u_count()));\n o = vec4<f32>(sl.x, sl.y, sl.x, c.a);",
+ },
+ SepiaEffect: {
+ uniforms: ["weightsR", "weightsG", "weightsB"],
+ body: "o = vec4<f32>(dot(c.rgb, u_weightsR()), dot(c.rgb, u_weightsG()), dot(c.rgb, u_weightsB()), c.a);",
+ },
+ DotScreenEffect: {
+ uniforms: ["angle", "scale"],
+ body: "let q = p * u_resolution();\n let pt = u_scale() * vec2<f32>(dot(u_angle().yx, vec2<f32>(q.x, -q.y)), dot(u_angle(), q));\n o = vec4<f32>(c.rgb * 10.0 - 5.0 + sin(pt.x) * sin(pt.y) * 4.0, c.a);",
+ },
+ ColorAverageEffect: {
+ uniforms: [],
+ body: "o = vec4<f32>(vec3<f32>(dot(c.rgb, vec3<f32>(0.3333333))), c.a);",
+ },
+ ColorDepthEffect: {
+ uniforms: ["factor"],
+ body: "o = vec4<f32>(floor(c.rgb * u_factor() + 0.5) / u_factor(), c.a);",
+ },
+ GridEffect: {
+ uniforms: ["scale", "lineWidth"],
+ body: "let g = 0.5 - max(abs(fract(p.x * u_scale().x) - 0.5), abs(fract(p.y * u_scale().y) - 0.5));\n o = vec4<f32>(vec3<f32>(smoothstep(0.0, max(u_lineWidth(), 1e-6), g)), c.a);",
+ },
+};
+
+const SPECS: Record<string, Spec> = { ...BODIES, ...SAMPLED };
+
+/** the effects this module draws */
+export const FRAME_EFFECTS = new Set(Object.keys(SPECS));
+
+/** a uniform's value as a FramePass takes it: a number, or a vector's components */
+export function valueOf(v: unknown): number | number[] | undefined {
+ if (typeof v === "number") return v;
+ if (typeof v === "boolean") return v ? 1 : 0;
+ if (Array.isArray(v) && v.length >= 2 && v.length <= 4 && v.every((x) => typeof x === "number")) return v as number[];
+ const o = v as { x?: number; y?: number; z?: number; w?: number; r?: number; g?: number; b?: number } | null;
+ if (!o || typeof o !== "object") return undefined;
+ if (typeof o.r === "number") return [o.r, o.g ?? 0, o.b ?? 0];
+ if (typeof o.x === "number" && typeof o.y === "number") return typeof o.w === "number" ? [o.x, o.y, o.z ?? 0, o.w] : typeof o.z === "number" ? [o.x, o.y, o.z] : [o.x, o.y];
+ return undefined;
+}
+
+/** `e` as a FramePass part, or undefined when it isn't one of these (or lacks what it needs: a texture, its uniforms) */
+export function framePass(e: PPEffect, ctx: Ctx): Part | undefined {
+ // @react-three/postprocessing's <TiltShift2> names its effect TiltShiftEffect too: it's the one with a taper
+ const spec = SPECS[e.name === "TiltShiftEffect" && e.uniforms?.has("taper") ? "TiltShift2Effect" : e.name];
+ if (!spec) return undefined;
+ let mode = typeof e.blendMode?.blendFunction === "number" ? e.blendMode.blendFunction : 23;
+ if (spec.uv) mode = 30;
+ else if (!BLENDS.has(mode)) {
+ ctx.warn(`<${e.name.replace(/Effect$/, "")}> blend ${mode}`, "isn't one raea blends with: drawn as NORMAL");
+ mode = 23;
+ }
+ const uniforms: Record<string, number | number[]> = { time: ctx.time, resolution: ctx.size, opacity: e.blendMode?.opacity?.value ?? 1, blend: mode };
+ for (const k of spec.uniforms) {
+ const v = valueOf(e.uniforms?.get(k)?.value);
+ if (v === undefined) return undefined;
+ uniforms[k] = v;
+ }
+ const extra = spec.extra ? spec.extra(e, ctx) : {};
+ if (!extra) return undefined;
+ Object.assign(uniforms, extra.uniforms);
+ const [into, back] = spec.srgb ? ["pp_srgb(", ")"] : ["", ""];
+ const wgsl = `${PRELUDE}
+fn shade(in: FullscreenVertexOutput) -> vec4<f32> {
+ let f = frame(in.uv);
+ let c = vec4<f32>(${into}f.rgb${back}, f.a);
+ let p = vec2<f32>(in.uv.x, 1.0 - in.uv.y);
+ var o = c;
+ ${spec.body}
+ let b = pp_blend(c, o, u_opacity(), i32(u_blend()));
+ return vec4<f32>(${spec.srgb ? "pp_linear(b.rgb)" : "b.rgb"}, b.a);
+}
+`;
+ const props: Record<string, unknown> = { wgsl, uniforms, at: ctx.after ? "after-tonemap" : "before-tonemap" };
+ if (extra.textures) props.textures = extra.textures;
+ if (extra.prepass) props.prepass = true;
+ return { type: "FramePass", props };
+}
diff --git a/sdk/r3f/src/input/kinds.ts b/sdk/r3f/src/input/kinds.ts
index e0d8bb5c..0a239192 100644
--- a/sdk/r3f/src/input/kinds.ts
+++ b/sdk/r3f/src/input/kinds.ts
@@ -79,7 +79,7 @@ export const EFFECTS: Record<string, { status: InputStatus; raea: string; note?:
ChromaticAberrationEffect: { status: "near", raea: "Grade aberration (the offset's length)" },
HueSaturationEffect: { status: "near", raea: "Grade saturation (1 + saturation)", note: "hue isn't turned" },
BrightnessContrastEffect: { status: "near", raea: "Grade midtones (contrast, brightness as lift)" },
- ToneMappingEffect: { status: "drawn", raea: "ToneMapping (its mode; ACES with three's 1/0.6 as exposure)" },
+ ToneMappingEffect: { status: "drawn", raea: "ToneMapping (its mode; ACES's 1/0.6 as a Grade exposure, every pixel before the curve)" },
DepthOfFieldEffect: { status: "near", raea: "DepthOfField (gaussian, worldFocusDistance as focus, bokehScale as its blur)" },
BokehEffect: { status: "near", raea: "DepthOfField (bokeh)", note: "postprocessing's legacy bokeh, its focus as raea's" },
RealisticBokehEffect: { status: "near", raea: "DepthOfField (bokeh)", note: "postprocessing's legacy bokeh, its focus as raea's" },
@@ -90,5 +90,9 @@ export const EFFECTS: Record<string, { status: InputStatus; raea: string; note?:
N8AOPostPass: { status: "near", raea: "AmbientOcclusion (Bevy's SSAO)" },
PixelationEffect: { status: "near", raea: "Look pixel (granularity / 5 as the cell)" },
LensDistortionEffect: { status: "near", raea: "LensDistortion (distortion.x as k1)" },
- ...Object.fromEntries(["NoiseEffect", "GlitchEffect", "ScanlineEffect", "SepiaEffect", "DotScreenEffect", "ColorAverageEffect", "ColorDepthEffect", "GridEffect", "GodRaysEffect", "ShockWaveEffect", "TiltShiftEffect", "LUT3DEffect", "LUT1DEffect", "LUTEffect", "TextureEffect", "DepthEffect", "OutlineEffect", "ASCIIEffect"].map((k) => [k, { status: "none" as const, raea: "left out, named once", note: "write it as a raea <FramePass> (WESL) outside <R3F>" }])),
+ ...Object.fromEntries(["NoiseEffect", "ScanlineEffect", "SepiaEffect", "DotScreenEffect", "ColorAverageEffect", "ColorDepthEffect", "GridEffect"].map((k) => [k, { status: "drawn" as const, raea: "FramePass: its shader in WGSL, read with its own uniforms, blended as its EffectPass blends it (effects.ts)" }])),
+ ...Object.fromEntries(["GlitchEffect", "ShockWaveEffect", "LUT3DEffect", "LUTEffect", "ASCIIEffect"].map((k) => [k, { status: "drawn" as const, raea: "FramePass: its shader in WGSL, the frame read at its moved uv or its texture (a perturbation map, its characters, its table as a strip of slices) (effects-sampled.ts)" }])),
+ TiltShiftEffect: { status: "near", raea: "FramePass: the frame blurred outside its band", note: "one Gaussian as wide as its Kawase blur passes; <TiltShift2>'s effect (same name) is drawn as it is" },
+ GodRaysEffect: { status: "near", raea: "FramePass: rays streaked from the sun's disc on screen, where the depth prepass has nothing nearer", note: "its light source's own mask and the rays' blur aren't drawn" },
+ ...Object.fromEntries(["LUT1DEffect", "TextureEffect", "DepthEffect", "OutlineEffect"].map((k) => [k, { status: "none" as const, raea: "left out, named once", note: "write it as a raea <FramePass> (WESL) outside <R3F>" }])),
};
diff --git a/sdk/r3f/src/input/lights.ts b/sdk/r3f/src/input/lights.ts
index 542f7e3d..5bfafb6a 100644
--- a/sdk/r3f/src/input/lights.ts
+++ b/sdk/r3f/src/input/lights.ts
@@ -1,7 +1,9 @@
// three.js's lights, cameras, fog and environment as raea's parts, in world space (raea places a light and the camera
// by position and target, not inside a group). Intensities go through units.ts: a three light and the raea light it
// becomes put the same light on screen.
+import { Fragment } from "react";
import * as THREE from "three";
+import { COMPONENTS } from "../parts";
import { toRaea, stopsOf } from "../units";
import type { Part, Props } from "./material";
import { srcOf } from "./texture";
@@ -182,12 +184,21 @@ export function skyOf(scene: THREE.Scene, gl?: THREE.WebGLRenderer, webgpu = fal
return { parts, background };
}
+/** a tone mapping and the stops three scales every pixel by before its curve, as raea's: the stops are a <Grade>'s
+ * exposure (Bevy's colour grading, all pixels), not <ToneMapping exposure>, the camera's, which lights only what lights
+ * shade (under ACES an unlit colour, a sprite, a line, a basic material was 0.74 stops dark); the two in a fragment */
+export function toneParts(mode: string, stops: number): Part {
+ const tone: Part = { type: "ToneMapping", props: { mode } };
+ if (stops === 0) return tone;
+ COMPONENTS.Fragment ??= Fragment as unknown as (typeof COMPONENTS)[string];
+ return { type: "Fragment", props: {}, children: [tone, { type: "Grade", props: { exposure: stops } }] };
+}
+
/** three's renderer settings (R3F sets them from <Canvas flat linear>) as raea's tone mapping */
export function toneOf(gl: THREE.WebGLRenderer): Part {
const modes: Record<number, string> = { [THREE.ACESFilmicToneMapping]: "aces", [THREE.AgXToneMapping]: "agx", [THREE.NeutralToneMapping]: "neutral", [THREE.ReinhardToneMapping]: "reinhard", [THREE.CineonToneMapping]: "aces", [THREE.LinearToneMapping]: "none", [THREE.NoToneMapping]: "none" };
- const props: Props = { mode: modes[gl.toneMapping] ?? "none" };
- // three's ACES scales its input by 1/0.6 where Bevy's ACESFitted doesn't: the same picture is 0.74 stops up in raea
- const stops = stopsOf(gl.toneMappingExposure / (gl.toneMapping === THREE.ACESFilmicToneMapping ? 0.6 : 1));
- if (stops !== 0) props.exposure = stops;
- return { type: "ToneMapping", props };
+ const mode = modes[gl.toneMapping] ?? "none";
+ // three's ACES scales its input by 1/0.6 where Bevy's ACESFitted doesn't; with no curve, three ignores the exposure
+ const stops = mode === "none" ? 0 : stopsOf(gl.toneMappingExposure / (gl.toneMapping === THREE.ACESFilmicToneMapping ? 0.6 : 1));
+ return toneParts(mode, stops);
}
diff --git a/sdk/r3f/src/input/post.ts b/sdk/r3f/src/input/post.ts
index ca67f291..6abc6dd8 100644
--- a/sdk/r3f/src/input/post.ts
+++ b/sdk/r3f/src/input/post.ts
@@ -1,14 +1,17 @@
// @react-three/postprocessing's <EffectComposer> as raea's frame effects (docs/r3f.feature R3F12). Its effects are R3F
// instances under the composer's <group>, objects of pmndrs' postprocessing library, not three's: each is read here and
// becomes the raea effect that does the same thing (Bloom, Grade, ToneMapping, DepthOfField, AntiAliasing,
-// AmbientOcclusion, Look, LensDistortion), which raea's engine draws after the scene as Bevy does. One raea has nothing
-// for (noise, glitch, scanlines, god rays ...) is named once and left out.
+// AmbientOcclusion, Look, LensDistortion), which raea's engine draws after the scene as Bevy does, or a <FramePass>
+// that does what the effect's shader does (noise, scanlines, sepia, dot screen, colour average and depth, grid,
+// glitch, shock wave, tilt shift, ASCII, LUT, god rays: effects.ts, effects-sampled.ts, R3F25). One raea has neither
+// for is named once and left out.
//
// A composer renders the scene into a render target, where three doesn't tone-map: the frame is mapped only by a
// <ToneMapping> effect in it (postprocessing's ToneMappingEffect), so a scene with a composer is drawn untonemapped
// unless it has one.
import type * as THREE from "three";
import type { Part, Props } from "./material";
+import { framePass, type PPEffect } from "./effects";
const warned = new Set<string>();
function warnOnce(k: string, why: string) {
@@ -33,12 +36,20 @@ const TONE: Record<number, string> = { 0: "none", 1: "reinhard", 2: "reinhard",
const num = (v: unknown, d: number) => (typeof v === "number" && Number.isFinite(v) ? v : d);
+/** the R3F root's clock and size where the composer was last found: the effects' time and resolution (an EffectPass's
+ * time is its composer's deltas summed, R3F's clock as raea steps it) */
+let root: { time: number; size: [number, number]; camera?: THREE.Camera } = { time: 0, size: [1, 1] };
+
+type R3FInstance = { children?: { object?: unknown }[]; root?: { getState?: () => { clock?: { elapsedTime?: number }; size?: { width: number; height: number }; camera?: THREE.Camera } } };
+
/** the composers' effects in a scene, in the order they're drawn, and whether a composer was found */
export function composerEffects(scene: THREE.Scene): { found: boolean; effects: unknown[] } {
const effects: unknown[] = [];
let found = false;
scene.traverse((o) => {
- const inst = (o as unknown as { __r3f?: { children?: { object?: unknown }[] } }).__r3f;
+ const inst = (o as unknown as { __r3f?: R3FInstance }).__r3f;
+ const st = inst?.children?.length ? inst.root?.getState?.() : undefined;
+ if (st) root = { time: st.clock?.elapsedTime ?? 0, size: [st.size?.width ?? 1, st.size?.height ?? 1], camera: st.camera };
for (const c of inst?.children ?? []) {
const e = c.object;
if (isEffect(e) || isPass(e)) {
@@ -55,6 +66,9 @@ export function postParts(effects: unknown[]): { parts: Part[]; tone?: Part } {
const parts: Part[] = [];
const grade: Props = {};
let tone: Part | undefined;
+ // effects after a <ToneMapping> run on the tone-mapped frame; before it, on the frame as three has it (the tone's
+ // exposure is the Grade's, put on in the tone mapping pass)
+ let mapped = false;
for (const raw of effects) {
if (isPass(raw) && !isEffect(raw)) {
const n = raw.constructor.name;
@@ -63,8 +77,8 @@ export function postParts(effects: unknown[]): { parts: Part[]; tone?: Part } {
continue;
}
const e = raw as Effect;
- // a blend of SKIP (0) draws nothing; an effect's opacity scales it
- if (e.blendMode?.blendFunction === 0) continue;
+ // a blend of SKIP (BlendFunction 9, DST) draws nothing; an effect's opacity scales it
+ if (e.blendMode?.blendFunction === 9) continue;
const share = num(e.blendMode?.opacity?.value, 1);
switch (e.name) {
case "BloomEffect":
@@ -97,8 +111,11 @@ export function postParts(effects: unknown[]): { parts: Part[]; tone?: Part } {
}
case "ToneMappingEffect": {
const mode = TONE[num(e.mode, 7)] ?? "agx";
- // three's ACES scales its input by 1/0.6 where Bevy's doesn't (lights.ts's toneOf does the same)
- tone = { type: "ToneMapping", props: mode === "aces" ? { mode, exposure: Math.log2(1 / 0.6) } : { mode } };
+ // three's ACES scales its input by 1/0.6 where Bevy's doesn't: as the Grade's exposure, on every pixel just before
+ // the curve (lights.ts's toneParts), so the effects before it see three's values
+ tone = { type: "ToneMapping", props: { mode } };
+ if (mode === "aces") grade.exposure = Math.log2(1 / 0.6);
+ mapped = true;
break;
}
case "DepthOfFieldEffect": {
@@ -133,8 +150,11 @@ export function postParts(effects: unknown[]): { parts: Part[]; tone?: Part } {
parts.push({ type: "LensDistortion", props: { k1: d?.x ?? 0 } });
break;
}
- default:
- warnOnce(`<EffectComposer> effect ${e.name}`, "has no raea counterpart: left out (write it as a raea <FramePass> outside <R3F>)");
+ default: {
+ const pass = framePass(e as PPEffect, { ...root, after: mapped, warn: warnOnce });
+ if (pass) parts.push(pass);
+ else warnOnce(`<EffectComposer> effect ${e.name}`, "has no raea counterpart: left out (write it as a raea <FramePass> outside <R3F>)");
+ }
}
}
if (Object.keys(grade).length) parts.push({ type: "Grade", props: grade });
diff --git a/sdk/r3f/src/three/scene.ts b/sdk/r3f/src/three/scene.ts
index 4e5d0000..5dec7115 100644
--- a/sdk/r3f/src/three/scene.ts
+++ b/sdk/r3f/src/three/scene.ts
@@ -42,6 +42,9 @@ export interface Settings {
* AgX, its nearest, for a renderer drawing without the composer */
tony: boolean;
exposure: number;
+ /** a <Grade>'s exposure (a multiplier): Bevy's colour grading puts it on every pixel before the curve, as three's
+ * toneMappingExposure does */
+ grade: number;
shadows: boolean;
shadowMap: number;
}
@@ -86,7 +89,7 @@ function panorama(src: string, done: () => void): THREE.Texture {
export class Scene3d {
readonly scene = new THREE.Scene();
camera: THREE.Camera = new THREE.PerspectiveCamera(50, 1, 0.1, 1000);
- settings: Settings = { toneMapping: THREE.AgXToneMapping, tony: true, exposure: 1, shadows: true, shadowMap: 2048 };
+ settings: Settings = { toneMapping: THREE.AgXToneMapping, tony: true, exposure: 1, grade: 1, shadows: true, shadowMap: 2048 };
/** the frame effects on the page (Bloom, DepthOfField, Outline ...), each kind's props: the app's composer draws them */
effects: { kind: string; props: Props }[] = [];
/** whether the page drew any 3D at the last sync */
@@ -134,6 +137,8 @@ export class Scene3d {
}
// a paint look is in the surfaces (paint.ts); the frame pass only draws its cells
paintLook(this.scene, this.effects.find((e) => e.kind === "Look")?.props);
+ const ge = this.effects.find((e) => e.kind === "Grade")?.props.exposure;
+ this.settings.grade = 2 ** (typeof ge === "number" ? ge : 0);
this.fit(this.width, this.height);
}
@@ -461,7 +466,7 @@ export class Scene3d {
apply(renderer: THREE.WebGLRenderer) {
renderer.toneMapping = this.settings.toneMapping;
// three's ACES scales its input by 1/0.6 (tonemapping_pars_fragment); Bevy's ACESFitted doesn't
- renderer.toneMappingExposure = this.settings.exposure * (this.settings.toneMapping === THREE.ACESFilmicToneMapping ? 0.6 : 1);
+ renderer.toneMappingExposure = this.settings.exposure * this.settings.grade * (this.settings.toneMapping === THREE.ACESFilmicToneMapping ? 0.6 : 1);
paintTone.mode.value = !this.settings.tony && this.settings.toneMapping === THREE.ACESFilmicToneMapping ? 1 : 0;
paintTone.exposure.value = renderer.toneMappingExposure;
renderer.shadowMap.enabled = this.settings.shadows;
diff --git a/sdk/r3f/test/parity/fixtures.tsx b/sdk/r3f/test/parity/fixtures.tsx
index f99b3bd9..c2a6f912 100644
--- a/sdk/r3f/test/parity/fixtures.tsx
+++ b/sdk/r3f/test/parity/fixtures.tsx
@@ -13,6 +13,7 @@ import inter from "./fonts/Inter-400.json";
export { OUTPUTS } from "./outputs";
import { TSL_INPUTS } from "./tsl";
+import { POST2_INPUTS } from "./post2";
export const SIZE = { width: 640, height: 360, fps: 24 };
@@ -375,6 +376,8 @@ export const INPUTS: Record<string, InputCase> = {
},
// TSL node materials lit by the scene and moved by compute (R3F21, R3F22): test/parity/tsl.tsx
...TSL_INPUTS,
+ // postprocessing's effects raea draws as frame passes (R3F25): test/parity/post2.tsx
+ ...POST2_INPUTS,
};
const WAVE_VERTEX = /* glsl */ `
diff --git a/sdk/r3f/test/parity/post2.tsx b/sdk/r3f/test/parity/post2.tsx
new file mode 100644
index 00000000..4a6cfab8
--- /dev/null
+++ b/sdk/r3f/test/parity/post2.tsx
@@ -0,0 +1,62 @@
+// The parity cases for postprocessing's effects raea draws as <FramePass>es (docs/r3f.feature R3F25, src/input/effects.ts):
+// each a lit scene under a composer of them, drawn by raea and by three.js in Chrome.
+import * as PP from "@react-three/postprocessing";
+import { BlendFunction } from "postprocessing";
+import type { InputCase } from "./fixtures";
+
+const scene = (
+ <>
+ <color attach="background" args={["#1d2330"]} />
+ <ambientLight intensity={0.5} />
+ <directionalLight position={[2, 5, 1]} intensity={2.5} />
+ <mesh position={[0, 0.6, 0]}>
+ <sphereGeometry args={[0.6, 32, 16]} />
+ <meshStandardMaterial color="#e05a2b" roughness={0.4} />
+ </mesh>
+ <mesh position={[1.4, 0.4, -0.6]}>
+ <boxGeometry args={[0.8, 0.8, 0.8]} />
+ <meshStandardMaterial color="#3a8fd8" roughness={0.5} />
+ </mesh>
+ <mesh rotation={[-Math.PI / 2, 0, 0]}>
+ <planeGeometry args={[8, 8]} />
+ <meshStandardMaterial color="#cfd6e0" roughness={0.9} />
+ </mesh>
+ </>
+);
+
+export const POST2_INPUTS: Record<string, InputCase> = {
+ // sepia, scanlines overlaid, a grid at a third, the colours cut to 5 bits, then tone-mapped
+ post2: {
+ canvas: { camera: { position: [3, 2.5, 4], fov: 45 } },
+ frame: 6,
+ scene: () => (
+ <>
+ {scene}
+ <PP.EffectComposer>
+ <PP.Sepia intensity={0.8} />
+ <PP.Scanline density={1.2} opacity={0.25} />
+ <PP.Grid scale={1.5} lineWidth={0.05} blendFunction={BlendFunction.MULTIPLY} />
+ <PP.ColorDepth bits={5} />
+ <PP.ToneMapping mode={6} />
+ </PP.EffectComposer>
+ </>
+ ),
+ },
+ // after the tone mapping (a dot screen's rgb*10-5 goes far below 0, which three's ACES curve turns bright and Bevy's
+ // clamps): a dot screen at half, the colours averaged, screen-blended noise
+ post3: {
+ canvas: { camera: { position: [3, 2.5, 4], fov: 45 } },
+ frame: 6,
+ scene: () => (
+ <>
+ {scene}
+ <PP.EffectComposer>
+ <PP.ToneMapping mode={6} />
+ <PP.DotScreen angle={Math.PI / 4} scale={0.9} opacity={0.5} />
+ <PP.ColorAverage opacity={0.6} />
+ <PP.Noise opacity={0.08} />
+ </PP.EffectComposer>
+ </>
+ ),
+ },
+};
diff --git a/sdk/r3f/test/post.test.ts b/sdk/r3f/test/post.test.ts
index c2d0739c..8f732dae 100644
--- a/sdk/r3f/test/post.test.ts
+++ b/sdk/r3f/test/post.test.ts
@@ -1,7 +1,7 @@
// @react-three/postprocessing's effects as raea's (src/input/post.ts, docs/r3f.feature R3F12): pmndrs postprocessing's
// own classes, read the way they're found under an <EffectComposer>.
import { describe, expect, test } from "bun:test";
-import { BloomEffect, ChromaticAberrationEffect, DepthOfFieldEffect, EffectComposer, EffectPass, HueSaturationEffect, NoiseEffect, RenderPass, SMAAEffect, ToneMappingEffect, ToneMappingMode, VignetteEffect } from "postprocessing";
+import { BlendFunction, BloomEffect, ChromaticAberrationEffect, DepthEffect, DepthOfFieldEffect, EffectComposer, EffectPass, GlitchEffect, HueSaturationEffect, LUT3DEffect, NoiseEffect, RenderPass, ScanlineEffect, SMAAEffect, ToneMappingEffect, ToneMappingMode, VignetteEffect } from "postprocessing";
import * as THREE from "three";
import { postParts } from "../src/input/post";
import { standInRenderer } from "../src/input/session";
@@ -26,10 +26,11 @@ describe("<EffectComposer> → raea's frame effects", () => {
expect(tone!.props).toEqual({ mode: "agx" });
});
- test("ACES carries three's 1/0.6 as exposure", () => {
- const { tone } = postParts([new ToneMappingEffect({ mode: ToneMappingMode.ACES_FILMIC })]);
- expect(tone!.props.mode).toBe("aces");
- expect(tone!.props.exposure as number).toBeCloseTo(Math.log2(1 / 0.6));
+ test("ACES carries three's 1/0.6 as the Grade's exposure, every pixel before the curve, not the camera's", () => {
+ const { tone, parts } = postParts([new ToneMappingEffect({ mode: ToneMappingMode.ACES_FILMIC })]);
+ expect(tone!.props).toEqual({ mode: "aces" });
+ const grade = parts.find((p) => p.type === "Grade")!;
+ expect(grade.props.exposure as number).toBeCloseTo(Math.log2(1 / 0.6));
});
test("one raea has nothing for is named and left out", () => {
@@ -37,13 +38,62 @@ describe("<EffectComposer> → raea's frame effects", () => {
const said: string[] = [];
console.warn = (s: string) => said.push(s);
try {
- expect(postParts([new NoiseEffect()]).parts).toEqual([]);
- expect(said.join("\n")).toContain("NoiseEffect");
+ expect(postParts([new DepthEffect()]).parts).toEqual([]);
+ expect(said.join("\n")).toContain("DepthEffect");
} finally {
console.warn = warn;
}
});
+ test("noise and scanlines are frame passes: their shader, their uniforms, their blend (R3F25)", () => {
+ const scan = new ScanlineEffect({ density: 1.5 });
+ scan.setSize(640, 360);
+ const { parts } = postParts([new NoiseEffect({ premultiply: true }), scan, new NoiseEffect({ blendFunction: BlendFunction.SKIP })]);
+ expect(parts.map((p) => p.type)).toEqual(["FramePass", "FramePass"]);
+ const [noise, lines] = parts.map((p) => p.props as { wgsl: string; uniforms: Record<string, number>; at: string });
+ expect(noise.wgsl).toContain("fn shade(");
+ expect(noise.uniforms.premultiply).toBe(1);
+ expect(noise.uniforms.blend).toBe(BlendFunction.SCREEN);
+ expect(lines.uniforms.count).toBe(540);
+ expect(lines.uniforms.blend).toBe(BlendFunction.OVERLAY);
+ expect(lines.at).toBe("before-tonemap");
+ });
+
+ test("a frame pass before an ACES <ToneMapping> reads the frame as three has it, the exposure put on after it", () => {
+ const { parts } = postParts([new NoiseEffect(), new ToneMappingEffect({ mode: ToneMappingMode.ACES_FILMIC }), new NoiseEffect()]);
+ const [before, after] = parts.filter((p) => p.type === "FramePass").map((p) => p.props as { uniforms: Record<string, number>; at: string; wgsl: string });
+ expect(before.at).toBe("before-tonemap");
+ expect(before.wgsl).not.toContain("u_gain");
+ expect(after.at).toBe("after-tonemap");
+ });
+
+ test("a glitch reads the frame at its moved uv and its perturbation map; a 3D LUT is a strip of slices (R3F25)", () => {
+ const [glitch] = postParts([new GlitchEffect()]).parts;
+ const g = glitch.props as { uniforms: Record<string, unknown>; textures: Record<string, { src: string }>; wgsl: string };
+ // a mainUv effect isn't blended: its output is the frame where its uv lands
+ expect(g.uniforms.blend).toBe(30);
+ expect(g.textures.perturb.src).toStartWith("data:image/png;base64,");
+ expect(g.wgsl).toContain("o = pp_frame(q);");
+ const n = 2;
+ const data = new Float32Array(n * n * n * 4).map((_, i) => (i % 4 === 3 ? 1 : (i % 4) / 3));
+ const lut = new THREE.Data3DTexture(data, n, n, n);
+ const [pass] = postParts([new LUT3DEffect(lut)]).parts;
+ const l = pass.props as { uniforms: Record<string, unknown>; textures: Record<string, { src: string }>; wgsl: string };
+ expect(l.uniforms.lut).toEqual([n, 1 / (n * n), 1 / n, 1]);
+ expect(l.textures.lut.src).toStartWith("data:image/png;base64,");
+ // read in sRGB, as the effect asks, and taken back
+ expect(l.wgsl).toContain("pp_srgb(f.rgb)");
+ expect(l.wgsl).toContain("pp_linear(b.rgb)");
+ });
+
+ test("<TiltShift2>'s effect, also named TiltShiftEffect, is told apart by its taper", () => {
+ const uniforms = new Map<string, { value: unknown }>([["blur", { value: 0.15 }], ["taper", { value: 0.5 }], ["start", { value: [0.5, 0] }], ["end", { value: [0.5, 1] }], ["direction", { value: [1, 1] }], ["samples", { value: 10 }]]);
+ const [pass] = postParts([{ name: "TiltShiftEffect", blendMode: { blendFunction: BlendFunction.NORMAL, opacity: { value: 1 } }, uniforms, defines: new Map() }]).parts;
+ const p = pass.props as { uniforms: Record<string, unknown>; wgsl: string };
+ expect(p.uniforms.start).toEqual([0.5, 0]);
+ expect(p.wgsl).toContain("u_taper()");
+ });
+
test("every effect postprocessing exports is decided in kinds.ts", async () => {
const pp = (await import("postprocessing")) as Record<string, unknown>;
const effects = Object.keys(pp).filter((k) => /Effect$/.test(k) && typeof pp[k] === "function" && k !== "Effect");
diff --git a/sdk/r3f/test/roundtrip.test.tsx b/sdk/r3f/test/roundtrip.test.tsx
index a3c46346..7a4d9ec7 100644
--- a/sdk/r3f/test/roundtrip.test.tsx
+++ b/sdk/r3f/test/roundtrip.test.tsx
@@ -100,9 +100,9 @@ describe("raea → three.js → raea", () => {
// its look: one unit from the eye toward [0, 0.5, 0]
const dir = new THREE.Vector3(...(cam.props.lookAt as [number, number, number])).sub(new THREE.Vector3(4, 3, 6));
expect(dir.normalize().dot(new THREE.Vector3(-4, -2.5, -6).normalize())).toBeGreaterThan(0.99999);
- const tone = ofType(back, "ToneMapping")[0].props;
- expect(tone.mode).toBe("aces");
- expect(near(tone.exposure as number, 0.5)).toBe(true);
+ expect(ofType(back, "ToneMapping")[0].props).toEqual({ mode: "aces" });
+ // three's toneMappingExposure scales every pixel: it comes back as the Grade's exposure (lights.ts toneParts)
+ expect(near(ofType(back, "Grade")[0].props.exposure as number, 0.5)).toBe(true);
expect(ofType(back, "Fog")[0].props).toEqual({ color: "#203040", near: 4, far: 30 });
});
diff --git a/sdk/r3f/tools/parity.sh b/sdk/r3f/tools/parity.sh
index f3caa87e..6ccb7a00 100755
--- a/sdk/r3f/tools/parity.sh
+++ b/sdk/r3f/tools/parity.sh
@@ -15,13 +15,16 @@ CASES=(in-basic:24 in-instanced:12 in-lights:0 in-things:0 in-catch:0 in-lettra:
CASES+=(in-tsl-lit:12)
# a plain three.js program (test/parity/programs.ts) through <Three> (R3F19)
CASES+=(in-vanilla:24)
+# postprocessing's effects as raea <FramePass>es (test/parity/post2.tsx), before and after an ACES tone mapping (R3F25)
+CASES+=(in-post2:6 in-post3:6)
[ -z "${R3F_CASES:-}" ] || read -ra CASES <<<"$R3F_CASES"
mkdir -p "$OUT"
for c in "${CASES[@]}"; do
# a src-* case is its out-* composition, drawn from the R3F source the source export wrote for it
(cd test/parity && raea render native.tsx --composition "$(echo "${c%%:*}" | sed 's/^src-/out-/')" --frame "${c##*:}" -o "$OUT/${c%%:*}-native.png" >/dev/null)
done
-bun tools/shoot.ts "$URL" "$OUT" $([ -z "${R3F_CASES:-}" ] || for c in "${CASES[@]}"; do echo "${c%%:*}"; done)
+# Chrome shoots exactly these cases (shoot.ts's own list is for running it alone)
+bun tools/shoot.ts "$URL" "$OUT" $(for c in "${CASES[@]}"; do echo "${c%%:*}"; done)
fail=0
for c in "${CASES[@]}"; do
id=${c%%:*}
diff --git a/sdk/render/src/3d/effects.tsx b/sdk/render/src/3d/effects.tsx
index 9152efd4..941e9ae3 100644
--- a/sdk/render/src/3d/effects.tsx
+++ b/sdk/render/src/3d/effects.tsx
@@ -212,6 +212,9 @@ export interface GradeProps {
tint?: number;
/** the whole frame's saturation after tone mapping (1 keeps it) */
saturation?: number;
+ /** stops of exposure on every pixel just before tone mapping, unlit colours and emission included (0 keeps it):
+ * <ToneMapping exposure> is the camera's, which brightens only what lights shade */
+ exposure?: number;
/** the grade on the shadows: saturation, contrast, gamma, gain, lift */
shadows?: GradeSection;
/** the grade on the midtones */
diff --git a/systems/framepass/src/lib.rs b/systems/framepass/src/lib.rs
index 3997ce98..3b463bb0 100644
--- a/systems/framepass/src/lib.rs
+++ b/systems/framepass/src/lib.rs
@@ -10,6 +10,11 @@
//! 1e30)
//! normal(uv) with `prepass`: the surface's world-space normal
//! `at`: "before-tonemap" (the HDR frame, after bloom) or "after-tonemap" (the display colours; the default).
+//!
+//! `in.uv` spans the camera's Viewport, not its target: the Engine's target is w x (h + 1), a tag row under the frame,
+//! and Bevy's frame textures are the target's size, so a pass drawn over the whole texture saw uv 0..1 over h + 1 rows
+//! (a pattern by uv drifting a row by the frame's foot, R3F25). The pass draws in the Viewport, and frame(), depth()
+//! and normal() map its uv back onto the texture.
use std::collections::HashMap;
@@ -24,6 +29,7 @@ use bevy::render::{
},
renderer::{RenderContext, RenderDevice, ViewQuery},
texture::{FallbackImage, GpuImage},
+ camera::ExtractedCamera,
view::{ExtractedView, ViewTarget},
Render, RenderApp, RenderStartup, RenderSystems,
};
@@ -99,17 +105,19 @@ impl Inline {
pub struct FramePasses(pub Vec<Pass>);
/// The module a pass's source is compiled as, in WESL: its bindings and accessors, the source, and the entry point
-/// unless it has its own. Bindings: 0 the frame, 1 its sampler, 2 the uniforms (the camera's near plane, then the
-/// slots), 3 + 2i a texture and 4 + 2i its sampler, 11 the texture array and 12 its sampler, 13 the depth and 14 the
-/// normals with a prepass.
+/// unless it has its own. Bindings: 0 the frame, 1 its sampler, 2 the uniforms (the camera's near plane, the
+/// Viewport's place in the texture, then the slots), 3 + 2i a texture and 4 + 2i its sampler, 11 the texture array and
+/// 12 its sampler, 13 the depth and 14 the normals with a prepass.
pub fn module(source: &str, uniforms: &[(String, &'static str)], textures: &[String], array: Option<&str>, prepass: bool) -> String {
let mut m = String::from(
"import bevy_core_pipeline::fullscreen_vertex_shader::FullscreenVertexOutput;\n\n\
@group(0) @binding(0) var raea_frame: texture_2d<f32>;\n\
@group(0) @binding(1) var raea_frame_sampler: sampler;\n\
- struct RaeaPass { near: vec4<f32>, s: array<vec4<f32>, 16> };\n\
+ struct RaeaPass { near: vec4<f32>, view: vec4<f32>, s: array<vec4<f32>, 16> };\n\
@group(0) @binding(2) var<uniform> raea_pass: RaeaPass;\n\
- fn frame(uv: vec2<f32>) -> vec4<f32> { return textureSampleLevel(raea_frame, raea_frame_sampler, uv, 0.0); }\n",
+ // a uv over the camera's Viewport as one over the frame's texture (view: its size, then its corner, over the texture's)\n\
+ fn raea_view_uv(uv: vec2<f32>) -> vec2<f32> { return raea_pass.view.zw + uv * raea_pass.view.xy; }\n\
+ fn frame(uv: vec2<f32>) -> vec4<f32> { return textureSampleLevel(raea_frame, raea_frame_sampler, raea_view_uv(uv), 0.0); }\n",
);
for (i, t) in textures.iter().enumerate() {
m += &format!("@group(0) @binding({}) var tex_{t}: texture_2d<f32>;\n@group(0) @binding({}) var samp_{t}: sampler;\n", 3 + i * 2, 4 + i * 2);
@@ -120,7 +128,7 @@ pub fn module(source: &str, uniforms: &[(String, &'static str)], textures: &[Str
if prepass {
m += "@group(0) @binding(13) var raea_depth: texture_depth_2d;\n\
@group(0) @binding(14) var raea_normal: texture_2d<f32>;\n\
- fn raea_texel(uv: vec2<f32>, size: vec2<u32>) -> vec2<i32> { return clamp(vec2<i32>(uv * vec2<f32>(size)), vec2<i32>(0), vec2<i32>(size) - vec2<i32>(1)); }\n\
+ fn raea_texel(uv: vec2<f32>, size: vec2<u32>) -> vec2<i32> { return clamp(vec2<i32>(raea_view_uv(uv) * vec2<f32>(size)), vec2<i32>(0), vec2<i32>(size) - vec2<i32>(1)); }\n\
// reverse-Z: the depth is near / distance, 0 where nothing was drawn\n\
fn depth(uv: vec2<f32>) -> f32 {\n\
\x20 let d = textureLoad(raea_depth, raea_texel(uv, textureDimensions(raea_depth)), 0);\n\
@@ -228,7 +236,7 @@ struct Pipelines {
samplers: HashMap<(u128, String), Sampler>,
}
-const UNIFORM_BYTES: u64 = (16 * (1 + SLOTS)) as u64;
+const UNIFORM_BYTES: u64 = (16 * (2 + SLOTS)) as u64;
fn init_pipelines(mut commands: Commands, device: Res<RenderDevice>) {
let tex = || texture_2d(TextureSampleType::Float { filterable: true });
@@ -289,23 +297,43 @@ fn queue(views: Query<(&ViewTarget, &FramePasses)>, pipelines: Option<ResMut<Pip
}
}
-type Views<'w, 's> = ViewQuery<'w, 's, (&'static ViewTarget, &'static FramePasses, &'static ExtractedView, Option<&'static ViewPrepassTextures>)>;
+type Views<'w, 's> = ViewQuery<'w, 's, (&'static ViewTarget, &'static FramePasses, &'static ExtractedView, Option<&'static ViewPrepassTextures>, Option<&'static ExtractedCamera>)>;
+
+/// The camera's Viewport in its target (x, y, w, h in px), and its size and corner over the target's (the uniforms'
+/// `view`); none without a Viewport, the pass then spanning the target.
+fn viewport(camera: Option<&ExtractedCamera>) -> Option<([f32; 4], Vec4)> {
+ let c = camera?;
+ let v = c.viewport.as_ref()?;
+ rect(v.physical_position, v.physical_size, c.physical_target_size?)
+}
+
+/// A Viewport at `at`, `size` big, in a `target`-sized texture, as `viewport` gives it.
+fn rect(at: UVec2, size: UVec2, target: UVec2) -> Option<([f32; 4], Vec4)> {
+ let (at, size, t) = (at.as_vec2(), size.as_vec2(), target.as_vec2());
+ if t.x <= 0.0 || t.y <= 0.0 || size.x <= 0.0 || size.y <= 0.0 {
+ return None;
+ }
+ Some(([at.x, at.y, size.x, size.y], Vec4::new(size.x / t.x, size.y / t.y, at.x / t.x, at.y / t.y)))
+}
/// The passes placed before tone mapping (BEFORE) or after it.
fn draw<const BEFORE: bool>(view: Views<'_, '_>, p: Option<Res<Pipelines>>, cache: Res<PipelineCache>, images: Res<RenderAssets<GpuImage>>, fallback: Res<FallbackImage>, mut ctx: RenderContext) {
let Some(p) = p else { return };
let at = if BEFORE { At::BeforeTonemap } else { At::AfterTonemap };
- let (target, passes, extracted, prepass) = view.into_inner();
+ let (target, passes, extracted, prepass, camera) = view.into_inner();
// a perspective camera's near plane, from its infinite reverse-Z projection
let near = extracted.clip_from_view.w_axis.z;
+ let port = viewport(camera);
+ let view_uv = port.map_or(Vec4::new(1.0, 1.0, 0.0, 0.0), |p| p.1);
for pass in passes.0.iter().filter(|x| x.at == at) {
if let Some(w) = &pass.written {
let Some((layout, id)) = p.written.get(&(pass.shader, target.main_texture_format())) else { continue };
let Some(rp) = cache.get_render_pipeline(*id) else { continue };
let post = target.post_process_write();
let sampler = |n: &str| p.samplers.get(&(pass.shader, n.to_string())).cloned();
+ // over the whole texture, as it reads its frame binding by its own uv: it has no frame() to map
if let Some(group) = written::group(ctx.render_device(), &cache.get_bind_group_layout(layout), w, post.source, &images, sampler) {
- blit(&mut ctx, post.destination, rp, &group);
+ blit(&mut ctx, post.destination, rp, &group, None);
}
continue;
}
@@ -318,7 +346,7 @@ fn draw<const BEFORE: bool>(view: Views<'_, '_>, p: Option<Res<Pipelines>>, cach
continue;
}
let mut bytes: Vec<u8> = Vec::with_capacity(UNIFORM_BYTES as usize);
- for v in std::iter::once(Vec4::new(near, 0.0, 0.0, 0.0)).chain(pass.slots.iter().copied()) {
+ for v in [Vec4::new(near, 0.0, 0.0, 0.0), view_uv].into_iter().chain(pass.slots.iter().copied()) {
for f in v.to_array() {
bytes.extend_from_slice(&f.to_ne_bytes());
}
@@ -376,12 +404,13 @@ fn draw<const BEFORE: bool>(view: Views<'_, '_>, p: Option<Res<Pipelines>>, cach
)),
)
};
- blit(&mut ctx, post.destination, rp, &group);
+ blit(&mut ctx, post.destination, rp, &group, port.map(|p| p.0));
}
}
-/// The pass's full-screen triangle drawn into `dest`.
-fn blit(ctx: &mut RenderContext, dest: &TextureView, rp: &RenderPipeline, group: &BindGroup) {
+/// The pass's full-screen triangle drawn into `dest`, in `port` (x, y, w, h) when the camera has a Viewport. What's
+/// outside it (the tag row) no pass after reads: Bevy's upscaling scissors to the Viewport.
+fn blit(ctx: &mut RenderContext, dest: &TextureView, rp: &RenderPipeline, group: &BindGroup, port: Option<[f32; 4]>) {
let mut rpass = ctx.command_encoder().begin_render_pass(&RenderPassDescriptor {
label: Some("raea_frame_pass"),
color_attachments: &[Some(RenderPassColorAttachment { view: dest, depth_slice: None, resolve_target: None, ops: Operations::default() })],
@@ -390,6 +419,9 @@ fn blit(ctx: &mut RenderContext, dest: &TextureView, rp: &RenderPipeline, group:
occlusion_query_set: None,
multiview_mask: None,
});
+ if let Some([x, y, w, h]) = port {
+ rpass.set_viewport(x, y, w, h, 0.0, 1.0);
+ }
rpass.set_pipeline(rp);
rpass.set_bind_group(0, group, &[]);
rpass.draw(0..3, 0..1);
@@ -408,6 +440,21 @@ mod tests {
assert!(!m.contains("fn depth(") && m.contains("return shade(in);"));
let d = module("@fragment fn f(in: FullscreenVertexOutput) -> @location(0) vec4<f32> { return vec4(depth(in.uv)); }", &[], &[], None, true);
assert!(d.contains("fn depth(") && d.contains("fn normal(") && !d.contains("raea_frame_pass("));
+ // the frame, the depth and the normals are read at the Viewport's uv mapped onto their textures
+ assert!(m.contains("textureSampleLevel(raea_frame, raea_frame_sampler, raea_view_uv(uv), 0.0)"));
+ assert!(d.contains("vec2<i32>(raea_view_uv(uv) * vec2<f32>(size))"));
+ }
+
+ #[test]
+ fn a_pass_spans_the_cameras_viewport_not_the_tag_row_under_it() {
+ // the Engine's 640 x 361 target, its camera's 640 x 360 Viewport at the top: uv 1 is the frame's last row
+ let (port, view) = rect(UVec2::ZERO, UVec2::new(640, 360), UVec2::new(640, 361)).unwrap();
+ assert_eq!(port, [0.0, 0.0, 640.0, 360.0]);
+ assert_eq!(view, Vec4::new(1.0, 360.0 / 361.0, 0.0, 0.0));
+ // a Viewport placed in its target: its corner over the target's
+ let (_, v) = rect(UVec2::new(100, 50), UVec2::new(200, 100), UVec2::new(400, 200)).unwrap();
+ assert_eq!(v, Vec4::new(0.5, 0.5, 0.25, 0.25));
+ assert!(rect(UVec2::ZERO, UVec2::ZERO, UVec2::new(640, 361)).is_none());
}
#[test]
diff --git a/systems/post/src/camera/on.rs b/systems/post/src/camera/on.rs
index 30eb1292..c58ca650 100644
--- a/systems/post/src/camera/on.rs
+++ b/systems/post/src/camera/on.rs
@@ -112,6 +112,9 @@ pub fn grading(world: &mut World, e: Entity, vals: &Vals) {
cg.global.temperature = num(vals, "grade_temperature", 0.0);
cg.global.tint = num(vals, "grade_tint", 0.0);
cg.global.post_saturation = num(vals, "grade_saturation", 1.0);
+ // stops on every pixel just before the curve (Bevy's tonemapping applies it), where <ToneMapping exposure>, the
+ // camera's, lights only lit and emissive shading: three's toneMappingExposure (and its ACES's 1/0.6) is this one
+ cg.global.exposure = num(vals, "grade_exposure", 0.0);
for (pre, sec) in [("grade_s_", &mut cg.shadows), ("grade_m_", &mut cg.midtones), ("grade_h_", &mut cg.highlights)] {
let d = ColorGradingSection::default();
*sec = ColorGradingSection {