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.

#131: what an R3F scene throws is the composition's error, and three's PMREMGenerator no longer takes the scene with it. The scene renders under raea's own error boundary (sdk/r3f session.ts Caught): a throw while rendering, in an effect or a ref is thrown out of the <R3F> drawing it, the root ended, so the render is refused naming it as a throw outside R3F is ("REFUSED the composition threw at frame 0: Error: mesh threw", exit 1). R3F's own root only reported it (reportError, else a stack without its message), drew nothing and the render ended with 0 errors. PMREMGenerator (pmrem.ts): fromEquirectangular of a panorama raea loads is that panorama, lighting the scene as scene.environment; fromScene (RoomEnvironment) and fromCubemap are left out with a warning naming them, the scene drawn without them (it threw in _sceneToCubeUV inside the stand-in renderer). Checked: both of the issue's repros (the box now draws, the throw now refuses), sdk/r3f test/errors.test.tsx 4/4, the r3f suite 54/55 (the one failure is coverage.test's Skybox/Lightmap raea-web parity cases, unrelated and failing before). docs/r3f.feature R3F15

shinyobjectzbb7dc3b79f61
diff --git a/docs/r3f.feature b/docs/r3f.feature
index 37ae036f..90ebd903 100644
--- a/docs/r3f.feature
+++ b/docs/r3f.feature
@@ -247,3 +247,15 @@ Feature: React Three Fiber both ways: an R3F scene drawn by raea, a raea composi
facing that light or sideways, as the hemisphere light is), and its constant band is scaled as three's
irradiance is (0.886, where 0.282 made it a third as bright)
And in-approx: SSIM 0.9848 (Phong's F0 is held at Bevy's highest, 0.16, so its orange highlight glints less)
+
+ Scenario: R3F15. What an R3F scene throws is the composition's error (#131)
+ Given an <R3F> whose scene throws: rendering a component, in an effect, in a ref
+ Then the frame throws it out of the <R3F> drawing it (src/input/session.ts: the scene under raea's own error
+ boundary), so the render is refused naming it, exactly as a throw outside R3F is: "REFUSED the composition threw
+ at frame 0: Error: ...", exit 1
+ And never as R3F's own root reported it (reportError, else a stack without its message), the scene drawing nothing
+ and the render ending with 0 errors
+ And three's PMREMGenerator makes no GPU cube map in raea (src/input/pmrem.ts): fromEquirectangular of a panorama
+ raea loads is that panorama, lighting the scene as scene.environment does; fromScene (RoomEnvironment) and
+ fromCubemap are left out with a warning naming them, the scene drawn without them
+ And test/errors.test.tsx holds it
diff --git a/sdk/r3f/src/input/R3F.tsx b/sdk/r3f/src/input/R3F.tsx
index eff6ddd5..166994b9 100644
--- a/sdk/r3f/src/input/R3F.tsx
+++ b/sdk/r3f/src/input/R3F.tsx
@@ -13,9 +13,11 @@ import { Held, useWake } from "./hold";
import { stepTo, type Config } from "./session";
import { convert } from "./scene";
import { standInImages } from "./texture";
+import { standInPMREM } from "./pmrem";
import { elementsOf } from "../parts";
standInImages();
+standInPMREM();
export interface R3FProps extends Config {
children?: ReactNode;
diff --git a/sdk/r3f/src/input/lights.ts b/sdk/r3f/src/input/lights.ts
index 5d8f5cc8..542f7e3d 100644
--- a/sdk/r3f/src/input/lights.ts
+++ b/sdk/r3f/src/input/lights.ts
@@ -5,6 +5,7 @@ import * as THREE from "three";
import { toRaea, stopsOf } from "../units";
import type { Part, Props } from "./material";
import { srcOf } from "./texture";
+import { LEFT_OUT } from "./pmrem";
const hex = (c: THREE.Color) => "#" + c.getHexString();
const at = (o: THREE.Object3D) => o.getWorldPosition(new THREE.Vector3()).toArray() as [number, number, number];
@@ -164,7 +165,10 @@ export function skyOf(scene: THREE.Scene, gl?: THREE.WebGLRenderer, webgpu = fal
}
const env = srcOf(scene.environment);
const sky = bg instanceof THREE.Texture ? srcOf(bg) : undefined;
- if (scene.environment && !(env && PANORAMA.test(env))) warnOnce("scene.environment", "isn't a panorama file raea can load (.hdr, .exr, .png, .jpg): left out");
+ // three's PMREMGenerator making one from a scene or a cube map (pmrem.ts): said as that, not as a missing file
+ const by = scene.environment?.userData?.[LEFT_OUT];
+ if (scene.environment && typeof by === "string" && !env) warnOnce("scene.environment", `made by three's ${by}, which renders on the GPU and raea doesn't make yet: the scene is drawn without it (use a panorama: <Environment preset> or PMREMGenerator.fromEquirectangular of an .hdr)`);
+ else if (scene.environment && !(env && PANORAMA.test(env))) warnOnce("scene.environment", "isn't a panorama file raea can load (.hdr, .exr, .png, .jpg): left out");
if (bg instanceof THREE.Texture && !(sky && PANORAMA.test(sky))) warnOnce("scene.background", "texture isn't a panorama file raea can load: left out");
const rotation = scene.environmentRotation?.y ?? 0;
if (env && PANORAMA.test(env)) {
diff --git a/sdk/r3f/src/input/pmrem.ts b/sdk/r3f/src/input/pmrem.ts
new file mode 100644
index 00000000..7653027a
--- /dev/null
+++ b/sdk/r3f/src/input/pmrem.ts
@@ -0,0 +1,36 @@
+// three's PMREMGenerator filters an environment on the GPU: it renders a scene (RoomEnvironment, three's own recipe for
+// soft studio light) or a panorama into a cube map with the renderer, which in raea is a stand-in that never draws
+// (session.ts). raea filters an environment itself, from a panorama (lights.ts skyOf, raea's <Environment>), so the
+// generator hands back what raea can read: fromEquirectangular of a panorama raea loads is that panorama, lighting the
+// scene as scene.environment; fromScene and fromCubemap are left out, the scene drawn without them and a warning saying
+// so (skyOf). fromScene threw inside the stand-in renderer and took the whole <R3F> scene with it (#131).
+import * as THREE from "three";
+import { srcOf } from "./texture";
+
+/** what a stand-in environment was made by, when raea can't light by it: skyOf names it in its warning */
+export const LEFT_OUT = "raeaLeftOut";
+
+function standIn(src: string | undefined, by: string): THREE.WebGLRenderTarget {
+ const t = new THREE.WebGLRenderTarget(1, 1);
+ t.texture.mapping = THREE.CubeUVReflectionMapping;
+ if (src) t.texture.userData.src = src;
+ else t.texture.userData[LEFT_OUT] = by;
+ return t;
+}
+
+let done = false;
+
+/** PMREMGenerator's makers as stand-ins, once */
+export function standInPMREM() {
+ if (done) return;
+ done = true;
+ const pm = THREE.PMREMGenerator.prototype as unknown as Record<string, unknown>;
+ pm.fromScene = () => standIn(undefined, "PMREMGenerator.fromScene");
+ pm.fromSceneAsync = async () => standIn(undefined, "PMREMGenerator.fromScene");
+ pm.fromEquirectangular = (texture: THREE.Texture) => standIn(srcOf(texture), "PMREMGenerator.fromEquirectangular");
+ pm.fromEquirectangularAsync = async (texture: THREE.Texture) => standIn(srcOf(texture), "PMREMGenerator.fromEquirectangular");
+ pm.fromCubemap = () => standIn(undefined, "PMREMGenerator.fromCubemap");
+ pm.fromCubemapAsync = async () => standIn(undefined, "PMREMGenerator.fromCubemap");
+ pm.compileCubemapShader = () => {};
+ pm.compileEquirectangularShader = () => {};
+}
diff --git a/sdk/r3f/src/input/session.ts b/sdk/r3f/src/input/session.ts
index 84a8e5c1..49c9d5bd 100644
--- a/sdk/r3f/src/input/session.ts
+++ b/sdk/r3f/src/input/session.ts
@@ -5,7 +5,7 @@
// a frame's scene is the same whichever frame came before it: a render equals its play (raea's first rule).
import * as THREE from "three";
import { advance, createRoot, extend, flushSync, type ReconcilerRoot, type RenderProps, type RootState } from "@react-three/fiber";
-import type { ReactNode } from "react";
+import { Component, createElement, type ReactNode } from "react";
import { renderInto } from "./targets";
extend(THREE as unknown as Parameters<typeof extend>[0]);
@@ -92,6 +92,21 @@ const seedOf = (key: string) => [...key].reduce((h, c) => Math.imul(h ^ c.charCo
const sessions = new Map<string, Session>();
+/** The scene under an error boundary of raea's: what it throws (rendering, in an effect, in a ref) is handed to `on`,
+ * and it draws nothing after. A promise thrown (a load suspending) isn't an error and passes by it, as before. */
+class Caught extends Component<{ on: (error: unknown) => void; children?: ReactNode }, { failed: boolean }> {
+ state = { failed: false };
+ static getDerivedStateFromError() {
+ return { failed: true };
+ }
+ componentDidCatch(error: unknown) {
+ this.props.on(error);
+ }
+ render() {
+ return this.state.failed ? null : this.props.children;
+ }
+}
+
export type Config = Omit<RenderProps<HTMLCanvasElement>, "gl" | "frameloop" | "size" | "events" | "dpr">;
function start(key: string, width: number, height: number, config: Config, json: string): Session {
@@ -115,8 +130,16 @@ export function stepTo(key: string, frame: number, fps: number, width: number, h
const live = s;
const render = (i: number) => {
let store: ReturnType<typeof live.root.render> | undefined;
- seeded(live, () => flushSync(() => { store = live.root.render(scene(i)); }));
+ let failed: { error: unknown } | undefined;
+ seeded(live, () => flushSync(() => { store = live.root.render(createElement(Caught, { on: (error: unknown) => void (failed ??= { error }) }, scene(i))); }));
if (store) live.state = store.getState();
+ // thrown out of the <R3F> that's drawing it, so the composition throws as it would outside R3F: the render is
+ // refused, naming the error. R3F's own root only reports it (reportError, else console.error: a stack without its
+ // message) and draws nothing, and the render ended with 0 errors (#131). The root starts again next time
+ if (failed) {
+ end(key);
+ throw failed.error;
+ }
};
// the same frame drawn again (a live replay): its children may have changed, its clock hasn't. When parts of it
// mounted only now (a model, a font: what suspended while the frames were stepped, loaded since), their useFrame
diff --git a/sdk/r3f/test/errors.test.tsx b/sdk/r3f/test/errors.test.tsx
new file mode 100644
index 00000000..a4fdcfd1
--- /dev/null
+++ b/sdk/r3f/test/errors.test.tsx
@@ -0,0 +1,87 @@
+// What an R3F scene throws is the composition's error, and three's PMREMGenerator doesn't take the scene with it
+// (#131: any error inside <R3F> was swallowed, the scene drew nothing and the render ended with 0 errors).
+import { describe, expect, test } from "bun:test";
+import { useThree } from "@react-three/fiber";
+import { useEffect, useMemo, type ReactNode } from "react";
+import * as THREE from "three";
+import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js";
+import { convert } from "../src/input/scene";
+import { end, stepTo } from "../src/input/session";
+import { standInPMREM } from "../src/input/pmrem";
+import type { Part } from "../src/parts";
+
+standInPMREM();
+
+const flat = (parts: Part[]): Part[] => parts.flatMap((p) => [p, ...flat(p.children ?? [])]);
+let n = 0;
+function partsOf(scene: (i: number) => ReactNode, key = `e${n++}`) {
+ const s = stepTo(key, 0, 30, 400, 400, {}, scene);
+ const st = s.state as unknown as { scene: THREE.Scene; camera: THREE.Camera; gl: THREE.WebGLRenderer };
+ return flat(convert(st.scene, st.camera, st.gl, 400).parts);
+}
+const Box = () => (
+ <mesh>
+ <boxGeometry />
+ <meshBasicMaterial color="red" />
+ </mesh>
+);
+
+describe("an error inside the scene", () => {
+ test("thrown while rendering, it's thrown out of the frame with its message, and the next frame starts again", () => {
+ const Boom = (): null => {
+ throw new Error("mesh threw");
+ };
+ expect(() => partsOf(() => (<><Box /><Boom /></>), "boom")).toThrow("mesh threw");
+ // the same key without the throw draws: the failed root was ended, not kept
+ expect(partsOf(() => <Box />, "boom").some((p) => p.type === "Mesh")).toBe(true);
+ end("boom");
+ });
+
+ test("thrown in an effect, it's thrown out too", () => {
+ const Late = () => {
+ useEffect(() => {
+ throw new Error("effect threw");
+ }, []);
+ return null;
+ };
+ expect(() => partsOf(() => (<><Box /><Late /></>))).toThrow("effect threw");
+ });
+});
+
+describe("three's PMREMGenerator", () => {
+ test("fromScene (RoomEnvironment) leaves the environment out with a warning and the scene draws", () => {
+ const warned: string[] = [];
+ const warn = console.warn;
+ console.warn = (m: string) => void warned.push(String(m));
+ try {
+ const Studio = () => {
+ const { gl, scene } = useThree();
+ useMemo(() => {
+ const pm = new THREE.PMREMGenerator(gl);
+ scene.environment = pm.fromScene(new RoomEnvironment(), 0.04).texture;
+ }, [gl, scene]);
+ return null;
+ };
+ const parts = partsOf(() => (<><Studio /><Box /></>));
+ expect(parts.some((p) => p.type === "Mesh")).toBe(true);
+ expect(parts.some((p) => p.type === "Environment")).toBe(false);
+ } finally {
+ console.warn = warn;
+ }
+ expect(warned.some((w) => w.includes("PMREMGenerator.fromScene"))).toBe(true);
+ });
+
+ test("fromEquirectangular of a panorama lights the scene by that panorama", () => {
+ const Sky = () => {
+ const { gl, scene } = useThree();
+ useMemo(() => {
+ const hdr = new THREE.Texture();
+ hdr.userData.src = "media/studio.hdr";
+ scene.environment = new THREE.PMREMGenerator(gl).fromEquirectangular(hdr).texture;
+ }, [gl, scene]);
+ return null;
+ };
+ const env = partsOf(() => (<><Sky /><Box /></>)).find((p) => p.type === "Environment");
+ expect(env?.props.src).toBe("media/studio.hdr");
+ });
+});