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: a ShaderMaterial under a composer is scene light, and the composer's own passes aren't drawn. three draws a scene that goes through a composer into the composer's float buffer, where a ShaderMaterial's colour is scene light and its tone mapping and colour space includes do nothing; sdk/r3f sent it as "display", so raea drew it darker and more saturated than three's, out of reach of the composer's tone mapping and encoding. Under a composer it now goes as "linear" with linearToOutputTexel the identity (shader.ts composing): in-shaderbloom, a ShaderMaterial and a faint bloom (test/parity/post2.tsx, tools/parity.sh), goes from 0.9758 to 0.9848, the ball's mean colour from 133,66,33 to 186,135,96 against three's 194,145,110. The passes a composer draws into its own targets, which R3F23 put on raea's GPU, are dropped when raea draws the composer as its own effects: targets.ts passesOf keeps only the passes whose pictures the frame reads, directly or through a kept pass. One bloom was 17 cameras (the scene drawn again into the composer's buffer, and 16 quads for its luminance and mip chain) and is now none, while a target the frame shows is still drawn (test/composer.test.tsx, 3 tests). in-post's frame is the same to the pixel; the full parity list of 42 passes; docs/r3f.feature R3F25 status

shinyobjectz6665a2e5a8b7
diff --git a/docs/r3f.feature b/docs/r3f.feature
index d498ef43..3ffef8b5 100644
--- a/docs/r3f.feature
+++ b/docs/r3f.feature
@@ -610,6 +610,16 @@ Feature: React Three Fiber both ways: an R3F scene drawn by raea, a raea composi
Viewport. in-tslpost 0.9737 (bloom), in-tslpost2 0.9233 (sepia, chromatic aberration). Left: Outline (selected
meshes in a composition pass, once scene.ts is free), Texture, Depth, LUT1D, and the background under a
composer's or a PostProcessing's tone mapping (three maps it, raea shows it as given)
+ Later (11-15): a scene drawn through a composer is drawn into its float buffer by three, where a ShaderMaterial's
+ colour is scene light and its tone mapping and colour space includes do nothing; it went as "display" (the
+ canvas's value), drawn darker and more saturated than three's, the composer's tone mapping and encoding never
+ reaching it. It now goes as "linear" under a composer (shader.ts composing): in-shaderbloom (a ShaderMaterial
+ and a faint bloom, test/parity/post2.tsx) 0.9758 to 0.9848, the ball's mean colour 133,66,33 to 186,135,96
+ against three's 194,145,110. And the composer's own passes into its targets, which R3F23 drew on raea's GPU,
+ aren't drawn under a composer raea draws as its effects (targets.ts passesOf keeps the passes whose pictures
+ the frame reads): one bloom was 17 cameras, the scene drawn again into the composer's buffer and 16 quads for
+ its luminance and mip chain, and is none; a target the frame shows is still drawn (test/composer.test.tsx).
+ in-post's frame is the same to the pixel; the full list of 42 passes
@done
Scenario: R3F26. <R3F> in a box smaller than the page (#130)
diff --git a/sdk/r3f/src/input/scene.ts b/sdk/r3f/src/input/scene.ts
index 36d4d15f..c50773ed 100644
--- a/sdk/r3f/src/input/scene.ts
+++ b/sdk/r3f/src/input/scene.ts
@@ -13,7 +13,7 @@ import { isTroikaText, textParts } from "./text";
import { clipArrays, clipOf, type Clip } from "./clip";
import { cameraOf, fogOf, lightsOf, skyOf, toneOf } from "./lights";
import { materialOf, type Part, type Props } from "./material";
-import { isShader, ownAttributes, shaderPart } from "./shader";
+import { composing, isShader, ownAttributes, shaderPart } from "./shader";
import { drawsPatched } from "./patched";
import { composerEffects, postParts } from "./post";
import { classicOf } from "./tsl";
@@ -429,9 +429,10 @@ export function sceneParts(scene: THREE.Object3D, camera: THREE.Camera, gl: THRE
/** R3F's scene, camera and renderer settings as raea's parts, this frame */
export function convert(scene: THREE.Scene, camera: THREE.Camera, gl: THREE.WebGLRenderer, height: number, time = 0, delta = 0): Converted {
- const { w, drawn } = sceneParts(scene, camera, gl, height, "r3f", time, delta);
- // what the app drew into render targets itself this frame, drawn on the GPU before the screen (passes.ts, R3F23)
- drawn.unshift(...passesOf(gl));
+ // an <EffectComposer>'s effects (post.ts): its frame is tone-mapped only by a ToneMapping effect in it, and three
+ // draws the scene into its buffer, a ShaderMaterial's colour scene light there (shader.ts composing)
+ const composer = composerEffects(scene);
+ const { w, drawn } = composing(composer.found, () => sceneParts(scene, camera, gl, height, "r3f", time, delta));
// a node material runs only under three's WebGPURenderer, so a scene with one is drawn by it (whatever gl stands in)
let webgpu = (gl as { isWebGPURenderer?: boolean }).isWebGPURenderer === true;
if (!webgpu) scene.traverse((o) => {
@@ -441,11 +442,13 @@ export function convert(scene: THREE.Scene, camera: THREE.Camera, gl: THREE.WebG
const sky = skyOf(scene, gl, webgpu);
const cam = cameraOf(camera);
const fog = fogOf(scene.fog as THREE.Fog | THREE.FogExp2 | null);
- // an <EffectComposer>'s effects (post.ts): its frame is tone-mapped only by a ToneMapping effect in it
- const composer = composerEffects(scene);
const post = composer.found ? postParts(composer.effects) : { parts: [] as Part[], tone: undefined };
const tone = composer.found ? post.tone ?? { type: "ToneMapping", props: { mode: "none" } } : toneOf(gl);
+ // what the app drew into render targets itself this frame, drawn on the GPU before the screen (passes.ts, R3F23).
+ // Under a composer raea draws as its own effects, only the passes whose pictures the frame shows: the composer's
+ // own (the scene into its buffer, a bloom's mip chain) are raea's effects now, and would draw the scene again
+ const passes = passesOf(gl, composer.found ? [...sky.parts, ...w.world, ...drawn] : undefined);
// what the app dispatched with gl.compute since the last frame, run before the cameras draw (tsl-compute.ts, R3F22)
const computes = dispatchesOf(gl)?.part(time);
- return { parts: [...(cam ? [cam] : []), tone, ...(fog ? [fog] : []), ...sky.parts, ...post.parts, ...(computes ? [computes] : []), ...w.world, ...drawn], background: sky.background };
+ return { parts: [...(cam ? [cam] : []), tone, ...(fog ? [fog] : []), ...sky.parts, ...post.parts, ...(computes ? [computes] : []), ...w.world, ...passes, ...drawn], background: sky.background };
}
diff --git a/sdk/r3f/src/input/shader.ts b/sdk/r3f/src/input/shader.ts
index f73d8748..cfc7061e 100644
--- a/sdk/r3f/src/input/shader.ts
+++ b/sdk/r3f/src/input/shader.ts
@@ -6,7 +6,8 @@
// What three puts on screen is what raea's engine shows: a ShaderMaterial's colour is the canvas's value unless it
// includes three's tone mapping, so it goes as "display" (the engine takes it back through Bevy's tone mapping); one
// that includes <tonemapping_fragment> on a tone-mapped material goes as "linear", those includes dropped, and Bevy's
-// tone mapping maps it as three's would.
+// tone mapping maps it as three's would. Drawn through a composer, every one goes as "linear": three draws it into the
+// composer's float buffer, its colour scene light, and the composer tone-maps and encodes the frame.
import * as THREE from "three";
import { onGpu } from "./targets";
import { flipsY, srcOf } from "./texture";
@@ -119,6 +120,25 @@ export function decideIfdefs(src: string, defines: Set<string> | Map<string, str
/** three's sRGB encoding, which <colorspace_fragment> calls (three declares it in front of every fragment shader) */
const OUTPUT_TEXEL = "vec4 linearToOutputTexel(vec4 v) { return vec4(mix(pow(v.rgb, vec3(0.41666)) * 1.055 - vec3(0.055), v.rgb * 12.92, vec3(lessThanEqual(v.rgb, vec3(0.0031308)))), v.a); }\n";
+// into a composer's float buffer, three's output colour space is the target's (linear): the colour as it is
+const LINEAR_TEXEL = "vec4 linearToOutputTexel(vec4 v) { return v; }\n";
+
+// whether the scene being converted is drawn through a composer (an <EffectComposer>, three's EffectComposer, a
+// PostProcessing: post.ts composerEffects). three draws it into the composer's float buffer, where it tone-maps and
+// encodes nothing, so a ShaderMaterial's colour there is scene light, which the composer's own tone mapping (or none)
+// and encoding make the frame
+let composed = false;
+
+/** `f` run with the scene drawn through a composer (`on`) or not, as convert walks it */
+export function composing<T>(on: boolean, f: () => T): T {
+ const was = composed;
+ composed = on;
+ try {
+ return f();
+ } finally {
+ composed = was;
+ }
+}
/** a uniform's value as numbers (a texture is listed apart); undefined for one with nothing raea can send */
function valueOf(v: unknown): number | boolean | number[] | undefined {
@@ -160,8 +180,9 @@ export function shaderPart(m: THREE.ShaderMaterial, points = false): Part {
const defines = Object.entries(m.defines ?? {}).filter(([, v]) => v !== false).map(([k, v]) => `#define ${k} ${v === true ? "" : v}`).join("\n");
let vertex = expandIncludes(m.vertexShader);
let fragment = expandIncludes(m.fragmentShader);
- // three's tone mapping, when the shader asks for it, is Bevy's here: the shader's colour is then scene light
- const tones = /#include +<tonemapping_fragment>/.test(m.fragmentShader) && m.toneMapped;
+ // three's tone mapping, when the shader asks for it, is Bevy's here: the shader's colour is then scene light, as it
+ // is in a composer's buffer, where three's tone mapping and colour space includes do nothing
+ const tones = composed || (/#include +<tonemapping_fragment>/.test(m.fragmentShader) && m.toneMapped);
if (tones) fragment = expandIncludes(m.fragmentShader.replace(/^[ \t]*#include +<(tonemapping_fragment|colorspace_fragment)>/gm, ""));
else if (/#include +<tonemapping_fragment>/.test(m.fragmentShader)) fragment = expandIncludes(m.fragmentShader.replace(/^[ \t]*#include +<tonemapping_fragment>/gm, ""));
// three's prefix in front of a ShaderMaterial (not a raw one): no clipping planes (raea cuts the mesh, clip.ts)
@@ -170,7 +191,7 @@ export function shaderPart(m: THREE.ShaderMaterial, points = false): Part {
// naga's GLSL reads a parameter's `in` but not `const in` (three's <common> declares its helpers so)
const params = (src: string) => src.replace(/([(,]\s*)const\s+in\s+/g, "$1in ");
vertex = params(decideIfdefs(front + vertex, on));
- fragment = params(decideIfdefs(front + (raw ? "" : OUTPUT_TEXEL) + fragment, on));
+ fragment = params(decideIfdefs(front + (raw ? "" : composed ? LINEAR_TEXEL : OUTPUT_TEXEL) + fragment, on));
const uniforms: Record<string, number | boolean | number[]> = {};
const textures: Record<string, string | { src: string; colorSpace: "linear" }> = {};
const flipY: string[] = [];
diff --git a/sdk/r3f/src/input/targets.ts b/sdk/r3f/src/input/targets.ts
index fc905270..b51cef15 100644
--- a/sdk/r3f/src/input/targets.ts
+++ b/sdk/r3f/src/input/targets.ts
@@ -278,8 +278,39 @@ export function imageOf(rt: THREE.RenderTarget): string {
return `render:${t.uuid}@${w}x${h}:${w}x${h}${float ? ":float" : ""}`;
}
-/** the parts of what the app drew into targets on raea's GPU this frame (the stand-in renderer's passes), in order */
-export function passesOf(gl: THREE.WebGLRenderer): Part[] {
+/** the parts of what the app drew into targets on raea's GPU this frame (the stand-in renderer's passes), in order.
+ * With `seen` (the frame's parts), only the passes whose pictures it reads, or a pass it keeps reads */
+export function passesOf(gl: THREE.WebGLRenderer, seen?: Part[]): Part[] {
const passes = (gl as unknown as { __raea?: { passes?: Pass[] } }).__raea?.passes;
- return passes ? passes.flatMap((p) => p.parts) : [];
+ if (!passes?.length) return [];
+ if (!seen) return passes.flatMap((p) => p.parts);
+ const want = readsOf(seen);
+ const keep = new Set<Pass>();
+ for (let grew = true; grew; ) {
+ grew = false;
+ for (const p of passes) {
+ if (keep.has(p) || !want.has(p.target.texture.uuid)) continue;
+ keep.add(p);
+ readsOf(p.parts, want);
+ grew = true;
+ }
+ }
+ return passes.filter((p) => keep.has(p)).flatMap((p) => p.parts);
+}
+
+/** the render targets `parts` read, by texture uuid: every image name ("render:UUID@...", imageOf) in their props */
+function readsOf(parts: Part[], out = new Set<string>()): Set<string> {
+ const scan = (v: unknown): void => {
+ if (typeof v === "string") {
+ if (v.includes("render:")) for (const m of v.matchAll(/render:([^@:\s"]+)@/g)) out.add(m[1]);
+ } else if (Array.isArray(v)) {
+ // a geometry's numbers hold no names
+ if (typeof v[0] !== "number") v.forEach(scan);
+ } else if (v && typeof v === "object" && !ArrayBuffer.isView(v)) for (const x of Object.values(v)) scan(x);
+ };
+ for (const p of parts) {
+ scan(p.props);
+ if (p.children) readsOf(p.children, out);
+ }
+ return out;
}
diff --git a/sdk/r3f/test/composer.test.tsx b/sdk/r3f/test/composer.test.tsx
new file mode 100644
index 00000000..261ef7d4
--- /dev/null
+++ b/sdk/r3f/test/composer.test.tsx
@@ -0,0 +1,81 @@
+// A scene drawn through a composer (post.ts composerEffects): three draws it into the composer's float buffer, so a
+// ShaderMaterial's colour is scene light there (shader.ts composing), and the composer's own passes into its targets
+// (the scene into its buffer, a bloom's mip chain) aren't drawn by raea, whose effects stand for them (targets.ts
+// passesOf). A target the frame shows is still drawn.
+import { expect, test } from "bun:test";
+import * as PP from "@react-three/postprocessing";
+import { createPortal, useFrame } from "@react-three/fiber";
+import { useMemo, type ReactNode } from "react";
+import * as THREE from "three";
+import { convert } from "../src/input/scene";
+import { end, stepTo } from "../src/input/session";
+import type { Part } from "../src/parts";
+
+const flat = (parts: Part[]): Part[] => parts.flatMap((p) => [p, ...flat(p.children ?? [])]);
+let n = 0;
+function partsOf(scene: () => ReactNode): Part[] {
+ const key = `composer${n++}`;
+ const s = stepTo(key, 2, 30, 640, 360, {}, scene);
+ const st = s.state as unknown as { scene: THREE.Scene; camera: THREE.Camera; gl: THREE.WebGLRenderer };
+ const out = flat(convert(st.scene, st.camera, st.gl, 360).parts);
+ end(key);
+ return out;
+}
+
+function Ball() {
+ const m = useMemo(() => new THREE.ShaderMaterial({
+ vertexShader: "void main() { gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }",
+ fragmentShader: "void main() { gl_FragColor = linearToOutputTexel(vec4(0.8, 0.4, 0.2, 1.0)); }",
+ }), []);
+ return <mesh material={m}><sphereGeometry /></mesh>;
+}
+
+/** a knot drawn into a target every frame, shown on a plane (or the plane plain) */
+function Fbo({ show = true }: { show?: boolean }) {
+ const target = useMemo(() => new THREE.WebGLRenderTarget(128, 64), []);
+ const scene = useMemo(() => new THREE.Scene(), []);
+ const cam = useMemo(() => {
+ const c = new THREE.PerspectiveCamera(50, 2, 0.1, 100);
+ c.position.set(0, 0, 4);
+ return c;
+ }, []);
+ useFrame(({ gl }) => {
+ gl.setRenderTarget(target);
+ gl.render(scene, cam);
+ gl.setRenderTarget(null);
+ });
+ return (
+ <>
+ {createPortal(<mesh><torusKnotGeometry args={[0.6, 0.2, 32, 8]} /><meshBasicMaterial color="#2266ff" /></mesh>, scene)}
+ <mesh><planeGeometry args={[2, 1]} /><meshBasicMaterial map={show ? target.texture : null} /></mesh>
+ </>
+ );
+}
+
+const bloom = <PP.EffectComposer><PP.Bloom intensity={0.6} luminanceThreshold={0.9} mipmapBlur /></PP.EffectComposer>;
+const shader = (out: Part[]) => out.find((p) => p.type === "ThreeShaderMaterial")!;
+const intoTargets = (out: Part[]) => out.filter((p) => typeof p.props.target === "string");
+
+test("a ShaderMaterial is scene light under a composer, its output colour space the buffer's", () => {
+ const plain = shader(partsOf(() => <Ball />));
+ expect(plain.props.output).toBe("display");
+ expect((plain.props.glsl as { fragment: string }).fragment).toContain("0.41666");
+ const composed = shader(partsOf(() => <><Ball />{bloom}</>));
+ expect(composed.props.output).toBe("linear");
+ expect((composed.props.glsl as { fragment: string }).fragment).toContain("vec4 linearToOutputTexel(vec4 v) { return v; }");
+});
+
+test("a composer's own passes aren't drawn: one camera, the screen's, for the scene and a bloom", () => {
+ const out = partsOf(() => <><Ball />{bloom}</>);
+ expect(intoTargets(out)).toEqual([]);
+ expect(out.filter((p) => p.type === "ThreeShaderMaterial").length).toBe(1);
+ expect(out.some((p) => p.type === "Bloom")).toBe(true);
+});
+
+test("under a composer, a target the frame shows is drawn and one it doesn't isn't; without one, both are", () => {
+ const shown = intoTargets(partsOf(() => <><Fbo />{bloom}</>));
+ expect(shown.length).toBe(1);
+ expect(shown[0].props.target).toMatch(/:128x64$/);
+ expect(intoTargets(partsOf(() => <><Fbo show={false} />{bloom}</>))).toEqual([]);
+ expect(intoTargets(partsOf(() => <Fbo show={false} />)).length).toBe(1);
+});
diff --git a/sdk/r3f/test/parity/post2.tsx b/sdk/r3f/test/parity/post2.tsx
index 4a6cfab8..25b05854 100644
--- a/sdk/r3f/test/parity/post2.tsx
+++ b/sdk/r3f/test/parity/post2.tsx
@@ -2,6 +2,8 @@
// 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 { useMemo } from "react";
+import * as THREE from "three";
import type { InputCase } from "./fixtures";
const scene = (
@@ -24,6 +26,29 @@ const scene = (
</>
);
+// a ShaderMaterial's colour with no tone mapping of its own (output "display"), shaded by a fixed light, beside a lit one
+const BALL_FRAGMENT = /* glsl */ `
+varying vec3 vNormal;
+void main() {
+ float light = 0.3 + 0.7 * max(dot(normalize(vNormal), normalize(vec3(0.4, 0.8, 0.6))), 0.0);
+ gl_FragColor = vec4(vec3(0.85, 0.42, 0.2) * light, 1.0);
+}`;
+const BALL_VERTEX = /* glsl */ `
+varying vec3 vNormal;
+void main() {
+ vNormal = normalize(normalMatrix * normal);
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
+}`;
+
+function ShadedBall() {
+ const m = useMemo(() => new THREE.ShaderMaterial({ vertexShader: BALL_VERTEX, fragmentShader: BALL_FRAGMENT }), []);
+ return (
+ <mesh position={[-0.7, 0.7, 0]} material={m}>
+ <sphereGeometry args={[0.6, 48, 24]} />
+ </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: {
@@ -59,4 +84,29 @@ export const POST2_INPUTS: Record<string, InputCase> = {
</>
),
},
+ // a ShaderMaterial under a composer whose bloom makes raea's camera HDR (its glow faint: only the knot passes the
+ // threshold), with the renderer's ACES: three draws the ShaderMaterial's colour into the composer's buffer
+ shaderbloom: {
+ canvas: { camera: { position: [0, 1.6, 4.2], fov: 45 } },
+ frame: 6,
+ scene: () => (
+ <>
+ <color attach="background" args={["#1d2330"]} />
+ <ambientLight intensity={0.5} />
+ <directionalLight position={[2, 5, 1]} intensity={2.5} />
+ <ShadedBall />
+ <mesh position={[0.8, 0.7, -0.3]}>
+ <torusKnotGeometry args={[0.35, 0.12, 128, 16]} />
+ <meshStandardMaterial color="#202a3a" emissive="#58c8ff" emissiveIntensity={4} />
+ </mesh>
+ <mesh rotation={[-Math.PI / 2, 0, 0]}>
+ <planeGeometry args={[8, 8]} />
+ <meshStandardMaterial color="#cfd6e0" roughness={0.9} />
+ </mesh>
+ <PP.EffectComposer>
+ <PP.Bloom intensity={0.6} luminanceThreshold={0.9} mipmapBlur />
+ </PP.EffectComposer>
+ </>
+ ),
+ },
};
diff --git a/sdk/r3f/tools/parity.sh b/sdk/r3f/tools/parity.sh
index 1b8c7cfc..e2ec89b5 100755
--- a/sdk/r3f/tools/parity.sh
+++ b/sdk/r3f/tools/parity.sh
@@ -20,7 +20,7 @@ CASES+=(in-tsl-fbo: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)
+CASES+=(in-post2:6 in-post3:6 in-shaderbloom:6)
# three/webgpu's PostProcessing: its scene pass and TSL nodes as raea's effects (test/parity/tslpost.tsx, R3F25)
CASES+=(in-tslpost:6 in-tslpost2:6)
# render targets an app draws itself, on raea's GPU: a useFBO, and GPUComputationRenderer's ping-pong (test/parity/targets.tsx, R3F23)