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.

#165: an <R3F> scene lit by PMREMGenerator.fromScene(new RoomEnvironment(), sigma) is lit by that room, as three lights it. Since #131, fromScene handed back a stand-in that raea left out with a warning, because raea's <Environment> and its engine took panorama files only: the scene was drawn with no environment, so a box three draws 255,195,160 on its front face came out 136,76,58, and anything the room alone lights was near black. <Environment> now takes `room` (three.js's RoomEnvironment, made with no file) and `blur` (fromScene's sigma) in place of `src`. The engine makes the room itself (raea-sys-environment room.rs): RoomEnvironment's room, boxes, light boxes and point light at three r185's sizes and strengths, each direction from fromScene's cube camera traced to what it hits and shaded with three's Lambert, GGX and light falloff, blurred by sigma as fromScene's two half blurs do, then filtered like any panorama; runtime/look names it in env_srcs as room:SIGMA. On the R3F side, fromScene of a RoomEnvironment returns a texture marked with its sigma, which lights.ts turns into <Environment room blur> with the scene's environmentIntensity and rotation, and as the background when the room is that too; fromScene of any other scene, and fromCubemap, are still left out with a warning. The other way round, src/three (room.ts) draws <Environment room> as RoomEnvironment through the renderer's PMREMGenerator, and the source export writes it so. Tests: room.rs checks the room's light at 14 directions against three's own RoomEnvironment object (within 1e-3), the blur and the source name; runtime/look's camera test reads room sources into env_srcs; the envmap conformance test and test/errors.test.tsx hold the props and the conversion, and export.test.tsx the export. test/room/check.sh renders test/room/room.tsx and holds three pixels within 8 levels of three's, which test/room/three.ts works out on the CPU with three 0.185's PMREM and MeshStandardMaterial shading: #131's box face is 255,189,155 (three 255,195,160; 136,76,58 before), and two grey boxes lit by the room alone are 137 and 125 (three 140 and 127; 23 and 19 before). Left open: fromScene's options.position is drawn from the origin, with a warning, and the light meter does not count a room. Filed as R3F15b in docs/r3f.feature.

shinyobjectz9202d88e6902
diff --git a/docs/manual/reference/sdk/3d.md b/docs/manual/reference/sdk/3d.md
index df195378..e5dc973d 100644
--- a/docs/manual/reference/sdk/3d.md
+++ b/docs/manual/reference/sdk/3d.md
@@ -288,6 +288,7 @@ Used in: [ui/widgets/viewport_node](https://github.com/shinyobjectz/raea/blob/ma
Light from all around, out of a panorama: soft light from the sky and reflections of it in every glossy or metal
surface (image-based lighting), and with `background` the panorama as the sky. Put it inside the Canvas3D, once a
frame; its src, intensity, rotation and background may change from frame to frame (a cut from a hall to a street).
+With `room` in place of a panorama it is three.js's RoomEnvironment, soft studio light with no file.
Bevy's EnvironmentMapLight with maps already filtered is <EnvironmentMapLight>.
Its panorama is filtered by Bevy's generator and, with `background`, drawn as the sky (engine/render
environment.rs):
@@ -1522,7 +1523,9 @@ The props of [`Entity`](#entity), tabled there.
| Field | Type | What it is |
| --- | --- | --- |
-| `src` (required) | `string` | an equirectangular panorama in the media folder: a Radiance.hdr (Poly Haven's), an OpenEXR.exr, or an 8-bit.png/.jpg. Change it between frames to cut from one place to another |
+| `src` | `string` | an equirectangular panorama in the media folder: a Radiance.hdr (Poly Haven's), an OpenEXR.exr, or an 8-bit.png/.jpg. Change it between frames to cut from one place to another. Give it or `room`, not both |
+| `room` | `boolean` | three.js's RoomEnvironment in place of a panorama: a white studio room with soft light boxes, made by raea with no file. It is the light a three.js scene gets from PMREMGenerator.fromScene(new RoomEnvironment(), blur), which <R3F> turns into this |
+| `blur` | `number` | with `room`, its blur in radians before it lights (fromScene's sigma: three's examples use 0.04); 0 by default |
| `intensity` | `number` | how strongly it lights the scene (1 by default: a sky about as bright as an AmbientLight of 2.5 overall); animate it, or set 0 to switch it off for a shot |
| `rotation` | `number` | a turn about the vertical axis, in radians, for both the light and the sky: puts the sun where the shot wants it |
| `background` | `boolean` | draw the panorama as the sky behind everything (off by default: light only) |
diff --git a/docs/manual/reference/sdk/light.md b/docs/manual/reference/sdk/light.md
index bad0a920..3104e83d 100644
--- a/docs/manual/reference/sdk/light.md
+++ b/docs/manual/reference/sdk/light.md
@@ -90,6 +90,7 @@ Used in: [ui/render_ui_to_texture](https://github.com/shinyobjectz/raea/blob/mai
Light from all around, out of a panorama: soft light from the sky and reflections of it in every glossy or metal
surface (image-based lighting), and with `background` the panorama as the sky. Put it inside the Canvas3D, once a
frame; its src, intensity, rotation and background may change from frame to frame (a cut from a hall to a street).
+With `room` in place of a panorama it is three.js's RoomEnvironment, soft studio light with no file.
Bevy's EnvironmentMapLight with maps already filtered is <EnvironmentMapLight>.
Its panorama is filtered by Bevy's generator and, with `background`, drawn as the sky (engine/render
environment.rs):
@@ -384,7 +385,9 @@ The props of [`DirectionalLight`](#directionallight), tabled there.
| Field | Type | What it is |
| --- | --- | --- |
-| `src` (required) | `string` | an equirectangular panorama in the media folder: a Radiance.hdr (Poly Haven's), an OpenEXR.exr, or an 8-bit.png/.jpg. Change it between frames to cut from one place to another |
+| `src` | `string` | an equirectangular panorama in the media folder: a Radiance.hdr (Poly Haven's), an OpenEXR.exr, or an 8-bit.png/.jpg. Change it between frames to cut from one place to another. Give it or `room`, not both |
+| `room` | `boolean` | three.js's RoomEnvironment in place of a panorama: a white studio room with soft light boxes, made by raea with no file. It is the light a three.js scene gets from PMREMGenerator.fromScene(new RoomEnvironment(), blur), which <R3F> turns into this |
+| `blur` | `number` | with `room`, its blur in radians before it lights (fromScene's sigma: three's examples use 0.04); 0 by default |
| `intensity` | `number` | how strongly it lights the scene (1 by default: a sky about as bright as an AmbientLight of 2.5 overall); animate it, or set 0 to switch it off for a shot |
| `rotation` | `number` | a turn about the vertical axis, in radians, for both the light and the sky: puts the sun where the shot wants it |
| `background` | `boolean` | draw the panorama as the sky behind everything (off by default: light only) |
diff --git a/docs/r3f.feature b/docs/r3f.feature
index a8254e2c..547e8ed8 100644
--- a/docs/r3f.feature
+++ b/docs/r3f.feature
@@ -261,6 +261,28 @@ Feature: React Three Fiber both ways: an R3F scene drawn by raea, a raea composi
fromCubemap are left out with a warning naming them, the scene drawn without them
And test/errors.test.tsx holds it
+ @done
+ Scenario: R3F15b. three's RoomEnvironment lights an R3F scene (#165)
+ Given an <R3F> scene whose scene.environment is new PMREMGenerator(gl).fromScene(new RoomEnvironment(), sigma)
+ .texture, three's own recipe for soft studio light with no HDR file
+ When raea renders it
+ Then it is lit by the same room, made by raea's engine: <Environment room blur={sigma}>, which src/input/pmrem.ts
+ and lights.ts make of it (its intensity, its turn about +Y, and as the background when the room is that too)
+ And the room is three's (systems/environment room.rs): RoomEnvironment's boxes, light boxes and point light,
+ each direction from fromScene's cube camera traced to what it hits and lit by three's formulas, blurred by
+ sigma as fromScene blurs it, then filtered like any panorama
+ And fromScene of any other scene, and fromCubemap, are still left out with a warning naming them
+ And raea's own <Environment room> is drawn by three as RoomEnvironment through fromScene (src/three/scene.ts),
+ and the source export writes it so (src/export/emit.ts)
+ Status (11-16): done. The front face of #131's box, 136,76,58 before (no environment), is 255,189,155; three
+ draws 255,195,160. Two grey boxes lit by the room alone at half intensity: 137 and 125 against three's 140 and
+ 127 (23 and 19 before). three's pixels come from test/room/three.ts, which runs three 0.185's PMREM (the room
+ in its 256 cube, the GGX filter chain, textureCubeUV) and MeshStandardMaterial's shading on the CPU, so the
+ check needs no browser; test/room/check.sh renders test/room/room.tsx and holds each pixel within 8 levels.
+ The room's light at 14 directions matches three's own RoomEnvironment object to 1e-3 (room.rs tests); Bevy's
+ filter in place of three's PMREM puts the rest within 3 to 6 levels. Not done: fromScene's options.position
+ (a cube camera away from the origin) is drawn from the origin, with a warning
+
Rule: What three.js work online is made of draws in raea (0.1.5)
Goal, 2026-11-15: "ship all of this in 0.1.5". An audit that day rendered 25 probes of what people post online made
diff --git a/runtime/look/src/camera.rs b/runtime/look/src/camera.rs
index bed8dcd2..2e7fba61 100644
--- a/runtime/look/src/camera.rs
+++ b/runtime/look/src/camera.rs
@@ -28,6 +28,15 @@ pub fn env_shown(sent: Option<&V>, cam: &mut BTreeMap<String, V>) {
cam.insert("env_srcs".into(), V::S(serde_json::to_string(&list).unwrap_or_default()));
}
+/// An <Environment>'s source in env_srcs: its panorama's path, or for <Environment room> `room:` and its blur (three's
+/// RoomEnvironment, which raea-sys-environment's room.rs makes, #165).
+pub fn env_src(e: &Item) -> Option<String> {
+ if e.props.get("room") == Some(&Value::Bool(true)) {
+ return Some(format!("room:{}", n(&e.props, "blur", 0.0)));
+ }
+ e.props.get("src").and_then(Value::as_str).map(src_path)
+}
+
/// The camera row (`row`, id "cam": the scene's first camera) and a row for each camera after it (cam1, cam2, ...), each
/// drawn in its `order` over the ones before, cleared or not by its `clear` (<Camera3d order clear_color>, Bevy's
/// Camera: two_passes, split_screen), clearing to the first's colour when it clears.
@@ -157,11 +166,8 @@ fn lit(all: &[Vec<Item>], p: &mut Program, row: &mut BTreeMap<String, V>, id: &s
let envs: Vec<Option<&Item>> = all.iter().map(|its| its.iter().find(|i| i.kind == "environment" && !i.props.contains_key("diffuse_map"))).collect();
if envs.iter().any(Option::is_some) {
let mut srcs: Vec<String> = Vec::new();
- let idx: Vec<f64> = envs.iter().map(|e| match e.and_then(|e| e.props.get("src")).and_then(Value::as_str) {
- Some(s) => {
- let s = src_path(s);
- (srcs.iter().position(|x| *x == s).unwrap_or_else(|| { srcs.push(s); srcs.len() - 1 })) as f64
- }
+ let idx: Vec<f64> = envs.iter().map(|e| match e.and_then(|e| env_src(e)) {
+ Some(s) => (srcs.iter().position(|x| *x == s).unwrap_or_else(|| { srcs.push(s); srcs.len() - 1 })) as f64,
None => -1.0,
}).collect();
row.insert("env_srcs".into(), V::S(serde_json::to_string(&srcs).unwrap_or_default()));
diff --git a/runtime/look/tests/camera.rs b/runtime/look/tests/camera.rs
index ba126a77..649b3358 100644
--- a/runtime/look/tests/camera.rs
+++ b/runtime/look/tests/camera.rs
@@ -48,3 +48,23 @@ fn a_camera_with_a_rotation_keeps_it_exactly_and_one_without_has_none() {
camera(&[vec![cam(json!({ "position": [4, 3, 6], "lookAt": [0, 0.2, 0], "rotation": [0.1, 0.2, 0.3] }))]], &mut Program::default(), &mut plain);
assert!(!plain.contains_key("rot_qw"), "a rotation that isn't a quaternion places nothing");
}
+
+#[test]
+fn an_environment_room_is_a_source_of_its_own_by_its_blur() {
+ // <Environment room blur> (three's RoomEnvironment, #165): no file, the engine makes it; the same room on two
+ // frames is one source, a file beside it another
+ let env = |p: serde_json::Value| Item { kind: "environment", props: Arc::new(p.as_object().unwrap().clone()), shape: None, material: None, at: None, world: Mat4::IDENTITY };
+ let frames = vec![
+ vec![cam(json!({ "position": [0, 0, 5] })), env(json!({ "room": true, "blur": 0.04, "intensity": 1 }))],
+ vec![cam(json!({ "position": [0, 0, 5] })), env(json!({ "room": true, "blur": 0.04, "intensity": 0.5 }))],
+ vec![cam(json!({ "position": [0, 0, 5] })), env(json!({ "src": "sky.hdr" }))],
+ vec![cam(json!({ "position": [0, 0, 5] })), env(json!({ "room": true }))],
+ ];
+ let mut row: BTreeMap<String, V> = [("id".to_string(), V::S("cam".into()))].into();
+ camera(&frames, &mut Program::default(), &mut row);
+ let srcs: Vec<String> = match row.get("env_srcs") {
+ Some(V::S(s)) => serde_json::from_str(s).unwrap(),
+ other => panic!("no env_srcs: {other:?}"),
+ };
+ assert_eq!(srcs, ["room:0.04", "sky.hdr", "room:0"]);
+}
diff --git a/sdk/r3f/src/export/emit.ts b/sdk/r3f/src/export/emit.ts
index ffb44b5a..e33aea0b 100644
--- a/sdk/r3f/src/export/emit.ts
+++ b/sdk/r3f/src/export/emit.ts
@@ -134,7 +134,7 @@ export function emit(rec: Recording, name: string, title: string): string {
const c = rec.camera, s = rec.settings;
const camTrack = { p: same(c.p) ? undefined : c.p, q: same(c.q) ? undefined : c.q, fov: c.fov.length && !same(c.fov) ? c.fov : undefined, height: c.height.length && !same(c.height) ? c.height : undefined };
const exposure = r5(s.exposure * (s.toneMapping === THREE.ACESFilmicToneMapping ? 0.6 : 1));
- const env = rec.environment as { src: string; intensity: number; rotation: number; background: boolean; backgroundIntensity: number } | undefined;
+ const env = rec.environment as Env | undefined;
// raea's frame effects and Tony are drawn by raea-effects.ts, the composer <Raea> uses (three and its examples only)
const kinds = [...new Set(rec.effects.flat().map((e) => e.kind))];
const drawn = kinds.filter((k) => DRAWN_EFFECTS.includes(k));
@@ -164,7 +164,7 @@ const TONY = ${s.tony};
}, 1);
`
: "";
- const loader = env ? (/\.exr$/i.test(env.src) ? ["EXRLoader", "three/examples/jsm/loaders/EXRLoader.js"] : /\.hdr$/i.test(env.src) ? ["HDRLoader", "three/examples/jsm/loaders/HDRLoader.js"] : ["TextureLoader", ""]) : undefined;
+ const loader = env ? (env.room ? ["RoomEnvironment", "three/examples/jsm/environments/RoomEnvironment.js"] : /\.exr$/i.test(env.src) ? ["EXRLoader", "three/examples/jsm/loaders/EXRLoader.js"] : /\.hdr$/i.test(env.src) ? ["HDRLoader", "three/examples/jsm/loaders/HDRLoader.js"] : ["TextureLoader", ""]) : undefined;
const TONE = s.tony ? "AgXToneMapping" : toneName(s.toneMapping);
return `// ${title}: written by raea's source export (raea/r3f, docs/r3f.feature R3F9), ${N} frame${N > 1 ? "s" : ""} at ${rec.fps} fps, ${rec.width}x${rec.height}.
@@ -302,8 +302,12 @@ export default function ${name}() {
`;
}
-function envComponent(loader: string, env: { src: string; intensity: number; rotation: number; background: boolean; backgroundIntensity: number }): string {
+/** raea's <Environment> as the export keeps it (three/scene.ts): a panorama's src, or three's room and its blur */
+type Env = { src: string; room?: boolean; blur?: number; intensity: number; rotation: number; background: boolean; backgroundIntensity: number };
+
+function envComponent(loader: string, env: Env): string {
const k = 1000 * EXPOSURE;
+ if (env.room) return roomComponent(env, k);
return `
/** raea's <Environment>: its panorama lighting the scene${env.background ? " and drawn behind it" : ""} (raea's 1 is 1000 nits at Bevy's exposure) */
function Environment() {
@@ -320,6 +324,30 @@ ${env.background ? ` scene.background = t;\n scene.backgroundIntensity = $
`;
}
+/** raea's <Environment room> as three makes it: RoomEnvironment through PMREMGenerator.fromScene */
+function roomComponent(env: Env, k: number): string {
+ return `
+/** raea's <Environment room>: three's RoomEnvironment lighting the scene${env.background ? " and drawn behind it" : ""} (raea's 1 is 1000 nits at Bevy's exposure) */
+function Environment() {
+ const { gl, scene } = useThree();
+ const t = useMemo(() => {
+ const pmrem = new THREE.PMREMGenerator(gl);
+ const room = new RoomEnvironment();
+ const made = pmrem.fromScene(room, ${env.blur ?? 0}).texture;
+ room.dispose();
+ pmrem.dispose();
+ return made;
+ }, [gl]);
+ useLayoutEffect(() => {
+ scene.environment = t;
+ scene.environmentIntensity = ${r5(env.intensity * k)};
+ scene.environmentRotation.set(0, ${env.rotation}, 0);
+${env.background ? ` scene.background = t;\n scene.backgroundIntensity = ${r5(env.backgroundIntensity * k)};\n scene.backgroundRotation.set(0, ${env.rotation}, 0);\n` : ""} }, [t, scene]);
+ return null;
+}
+`;
+}
+
const MODEL = `
interface ModelState { src: string; time: number; loop: boolean; animation?: string | number; animations?: { clip: string | number; time?: number; weight?: number }[]; hide?: string[]; morphs?: Record<string, number> | number[]; refinish?: Record<string, unknown>[] }
diff --git a/sdk/r3f/src/input/lights.ts b/sdk/r3f/src/input/lights.ts
index cf39b981..1121353a 100644
--- a/sdk/r3f/src/input/lights.ts
+++ b/sdk/r3f/src/input/lights.ts
@@ -5,7 +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";
+import { LEFT_OUT, ROOM } from "./pmrem";
const hex = (c: THREE.Color) => "#" + c.getHexString();
const at = (o: THREE.Object3D) => o.getWorldPosition(new THREE.Vector3()).toArray() as [number, number, number];
@@ -163,15 +163,25 @@ export function skyOf(scene: THREE.Scene, gl?: THREE.WebGLRenderer, webgpu = fal
if (webgpu && !toned) warnOnce("scene.background", "is tone-mapped by three's WebGPURenderer with a curve raea doesn't copy for it: drawn as given");
background = hex(toned ?? bg);
}
- const env = srcOf(scene.environment);
- const sky = bg instanceof THREE.Texture ? srcOf(bg) : undefined;
- // three's PMREMGenerator making one from a scene or a cube map (pmrem.ts): said as that, not as a missing file
+ // three's RoomEnvironment through PMREMGenerator.fromScene (pmrem.ts): raea's <Environment room>, the same room
+ const room = (t: unknown) => (t instanceof THREE.Texture && typeof t.userData?.[ROOM] === "number" ? (t.userData[ROOM] as number) : undefined);
+ const envRoom = room(scene.environment), skyRoom = room(bg);
+ const env = envRoom === undefined ? srcOf(scene.environment) : undefined;
+ const sky = bg instanceof THREE.Texture && skyRoom === undefined ? srcOf(bg) : undefined;
+ // three's PMREMGenerator making one from another 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");
+ 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; PMREMGenerator.fromScene of three's RoomEnvironment is made)`);
+ else if (scene.environment && envRoom === undefined && !(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 && skyRoom === undefined && !(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)) {
+ if (envRoom !== undefined) {
+ const props: Props = { room: true, blur: envRoom, intensity: scene.environmentIntensity, rotation };
+ if (skyRoom === envRoom) Object.assign(props, { background: true, backgroundIntensity: scene.backgroundIntensity });
+ parts.push({ type: "Environment", props });
+ } else if (skyRoom !== undefined) {
+ // the room behind the scene, lighting nothing
+ parts.push({ type: "Environment", props: { room: true, blur: skyRoom, intensity: 0, rotation: scene.backgroundRotation?.y ?? 0, background: true, backgroundIntensity: scene.backgroundIntensity } });
+ } else if (env && PANORAMA.test(env)) {
const props: Props = { src: env, intensity: scene.environmentIntensity, rotation };
if (sky === env) Object.assign(props, { background: true, backgroundIntensity: scene.backgroundIntensity });
parts.push({ type: "Environment", props });
diff --git a/sdk/r3f/src/input/pmrem.ts b/sdk/r3f/src/input/pmrem.ts
index 7653027a..d92db8b1 100644
--- a/sdk/r3f/src/input/pmrem.ts
+++ b/sdk/r3f/src/input/pmrem.ts
@@ -1,14 +1,17 @@
// 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).
+// (session.ts). raea filters an environment itself (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 of three's RoomEnvironment is raea's <Environment room>, the same room made by raea's
+// engine (#165); fromScene of any other scene 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";
+/** a stand-in for three's RoomEnvironment: its blur (fromScene's sigma), which skyOf makes <Environment room blur> */
+export const ROOM = "raeaRoom";
function standIn(src: string | undefined, by: string): THREE.WebGLRenderTarget {
const t = new THREE.WebGLRenderTarget(1, 1);
@@ -18,6 +21,25 @@ function standIn(src: string | undefined, by: string): THREE.WebGLRenderTarget {
return t;
}
+/** three's RoomEnvironment (three/examples/jsm/environments/RoomEnvironment.js), which names its scene so */
+const isRoom = (scene: THREE.Object3D) => (scene as THREE.Scene).isScene === true && scene.name === "RoomEnvironment";
+
+/** fromScene: the room as raea's own, anything else left out. A cube camera placed away from fromScene's default, the
+ * origin (options.position), is drawn from the origin, and said so once. */
+function fromScene(scene: THREE.Object3D, sigma = 0, _near?: number, _far?: number, options?: { position?: THREE.Vector3 }): THREE.WebGLRenderTarget {
+ if (!isRoom(scene)) return standIn(undefined, "PMREMGenerator.fromScene");
+ const t = new THREE.WebGLRenderTarget(1, 1);
+ t.texture.mapping = THREE.CubeUVReflectionMapping;
+ t.texture.userData[ROOM] = Number.isFinite(sigma) && sigma > 0 ? sigma : 0;
+ const p = options?.position;
+ if (p && p.lengthSq() > 0 && !warnedAt) {
+ warnedAt = true;
+ console.warn(`raea/r3f: PMREMGenerator.fromScene(RoomEnvironment) at position [${p.toArray().join(", ")}] is lit as from the origin, fromScene's default (raea makes the room from there)`);
+ }
+ return t;
+}
+let warnedAt = false;
+
let done = false;
/** PMREMGenerator's makers as stand-ins, once */
@@ -25,8 +47,8 @@ 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.fromScene = fromScene;
+ pm.fromSceneAsync = async (...a: Parameters<typeof fromScene>) => fromScene(...a);
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");
diff --git a/sdk/r3f/src/three/room.ts b/sdk/r3f/src/three/room.ts
new file mode 100644
index 00000000..c5daa66c
--- /dev/null
+++ b/sdk/r3f/src/three/room.ts
@@ -0,0 +1,42 @@
+// <Environment room> on the three.js side (#165): three's RoomEnvironment through a renderer's PMREMGenerator, the way
+// a three.js scene gets soft studio light with no file. scene.ts calls room() for the part and again from apply()
+// once the page has its renderer, which the PMREMGenerator needs.
+import * as THREE from "three";
+import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js";
+import { EXPOSURE } from "../units";
+
+type Props = Record<string, unknown>;
+
+/** three's RoomEnvironment filtered by a renderer's PMREMGenerator, made once a renderer and blur */
+const rooms = new WeakMap<THREE.WebGLRenderer, Map<number, THREE.Texture>>();
+function roomOf(renderer: THREE.WebGLRenderer, blur: number): THREE.Texture {
+ let made = rooms.get(renderer);
+ if (!made) rooms.set(renderer, (made = new Map()));
+ let t = made.get(blur);
+ if (!t) {
+ const pm = new THREE.PMREMGenerator(renderer);
+ const room = new RoomEnvironment();
+ t = pm.fromScene(room, blur).texture;
+ room.dispose();
+ pm.dispose();
+ made.set(blur, t);
+ }
+ return t;
+}
+
+/** the scene lit by the room (and with `background` showing it), its keys kept in userData.raeaEnvironment for
+ * apply() and the source export; with no renderer yet the scene has no environment until one comes */
+export function room(scene: THREE.Scene, p: Props, renderer?: THREE.WebGLRenderer) {
+ const blur = (p.blur as number) ?? 0, intensity = (p.intensity as number) ?? 1, rotation = (p.rotation as number) ?? 0;
+ const sky = (p.backgroundIntensity as number) ?? intensity;
+ scene.userData.raeaEnvironment = { room: true, blur, intensity, rotation, background: !!p.background, backgroundIntensity: sky };
+ const t = renderer ? roomOf(renderer, blur) : null;
+ scene.environment = intensity > 0 ? t : null;
+ scene.environmentIntensity = intensity * 1000 * EXPOSURE;
+ scene.environmentRotation.set(0, rotation, 0);
+ if (p.background) {
+ scene.background = t;
+ scene.backgroundIntensity = sky * 1000 * EXPOSURE;
+ scene.backgroundRotation.set(0, rotation, 0);
+ }
+}
diff --git a/sdk/r3f/src/three/scene.ts b/sdk/r3f/src/three/scene.ts
index 5dec7115..f546888b 100644
--- a/sdk/r3f/src/three/scene.ts
+++ b/sdk/r3f/src/three/scene.ts
@@ -12,6 +12,7 @@ import { GEOMETRY, geometryOfShape, shapesReady } from "./geometry";
import { KINDS, PRIMITIVES } from "./kinds";
import { TONE, fitCamera, makeLight, setCamera, setLight, vec } from "./lights";
import { MATERIAL, paint, texture, vertexColoured } from "./materials";
+import { room } from "./room";
import { shaderMaterial } from "./shader";
import { ModelPart, decal, gizmoLines, imagePlane, instanced, place } from "./things";
import { EXPOSURE } from "../units";
@@ -103,6 +104,7 @@ export class Scene3d {
private height = 1;
private seconds = 0;
private cameraEl?: Element;
+ private renderer?: THREE.WebGLRenderer; // apply()'s last, which an <Environment room> is made on
sync(root: Element, seconds = this.seconds) {
this.seconds = seconds;
@@ -301,6 +303,10 @@ export class Scene3d {
case "Canvas3D":
return k;
case "Environment": {
+ if (p.room) {
+ room(this.scene, p, this.renderer);
+ return k;
+ }
const src = p.src as string;
// attached once it has loaded (a cube-UV map made from an empty texture fails to compile), by this page's
// next sync or, if the rows don't change, here
@@ -462,8 +468,11 @@ export class Scene3d {
for (const m of this.flats) placeFlat(m, this.camera, width, height);
}
- /** raea's settings on a renderer: tone mapping, exposure, shadows */
+ /** raea's settings on a renderer: tone mapping, exposure, shadows; an <Environment room> waiting for it made */
apply(renderer: THREE.WebGLRenderer) {
+ const env = this.scene.userData.raeaEnvironment as Props | undefined;
+ if (this.renderer !== renderer && env?.room) room(this.scene, env, renderer);
+ this.renderer = renderer;
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.grade * (this.settings.toneMapping === THREE.ACESFilmicToneMapping ? 0.6 : 1);
diff --git a/sdk/r3f/test/errors.test.tsx b/sdk/r3f/test/errors.test.tsx
index f1a00e95..ac5489de 100644
--- a/sdk/r3f/test/errors.test.tsx
+++ b/sdk/r3f/test/errors.test.tsx
@@ -49,25 +49,71 @@ describe("an error inside the scene", () => {
});
describe("three's PMREMGenerator", () => {
- test("fromScene (RoomEnvironment) leaves the environment out with a warning and the scene draws", () => {
+ const warnings = (fn: () => void) => {
const warned: string[] = [];
const warn = console.warn;
console.warn = (m: string) => void warned.push(String(m));
try {
+ fn();
+ } finally {
+ console.warn = warn;
+ }
+ return warned;
+ };
+
+ test("fromScene of three's RoomEnvironment lights the scene as raea's <Environment room>, with its blur (#165)", () => {
+ let parts: Part[] = [];
+ const warned = warnings(() => {
const Studio = () => {
const { gl, scene } = useThree();
useMemo(() => {
const pm = new THREE.PMREMGenerator(gl);
scene.environment = pm.fromScene(new RoomEnvironment(), 0.04).texture;
+ scene.environmentIntensity = 0.8;
+ scene.environmentRotation.set(0, 0.5, 0);
}, [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;
- }
+ parts = partsOf(() => (<><Studio /><Box /></>));
+ });
+ expect(parts.some((p) => p.type === "Mesh")).toBe(true);
+ const env = parts.filter((p) => p.type === "Environment");
+ expect(env.map((p) => p.props)).toEqual([{ room: true, blur: 0.04, intensity: 0.8, rotation: 0.5 }]);
+ expect(warned.filter((w) => w.includes("environment"))).toEqual([]);
+ });
+
+ test("the room as the background too is drawn behind the scene; as the background alone it lights nothing", () => {
+ const Room = ({ light }: { light: boolean }) => {
+ const { gl, scene } = useThree();
+ useMemo(() => {
+ const t = new THREE.PMREMGenerator(gl).fromScene(new RoomEnvironment()).texture;
+ if (light) scene.environment = t;
+ scene.background = t;
+ }, [gl, scene, light]);
+ return null;
+ };
+ const both = partsOf(() => (<><Room light /><Box /></>)).find((p) => p.type === "Environment");
+ expect(both?.props).toMatchObject({ room: true, blur: 0, intensity: 1, background: true, backgroundIntensity: 1 });
+ const behind = partsOf(() => (<><Room light={false} /><Box /></>)).find((p) => p.type === "Environment");
+ expect(behind?.props).toMatchObject({ room: true, intensity: 0, background: true });
+ });
+
+ test("fromScene of any other scene leaves the environment out with a warning and the scene draws", () => {
+ let parts: Part[] = [];
+ const warned = warnings(() => {
+ const Own = () => {
+ const { gl, scene } = useThree();
+ useMemo(() => {
+ const own = new THREE.Scene();
+ own.add(new THREE.Mesh(new THREE.BoxGeometry(), new THREE.MeshBasicMaterial({ color: "white" })));
+ scene.environment = new THREE.PMREMGenerator(gl).fromScene(own).texture;
+ }, [gl, scene]);
+ return null;
+ };
+ parts = partsOf(() => (<><Own /><Box /></>));
+ });
+ expect(parts.some((p) => p.type === "Mesh")).toBe(true);
+ expect(parts.some((p) => p.type === "Environment")).toBe(false);
expect(warned.some((w) => w.includes("PMREMGenerator.fromScene"))).toBe(true);
});
diff --git a/sdk/r3f/test/export.test.tsx b/sdk/r3f/test/export.test.tsx
index 52f3fc58..9586dca5 100644
--- a/sdk/r3f/test/export.test.tsx
+++ b/sdk/r3f/test/export.test.tsx
@@ -1,6 +1,10 @@
// raea → R3F source (docs/r3f.feature R3F9): what the source export writes. tools/parity.sh draws what it writes in
// Chrome against raea's render (src-* cases); this checks what's in the file.
import { describe, expect, test } from "bun:test";
+import { AbsoluteFill } from "raea";
+import { Cuboid } from "raea/3d";
+import { Environment } from "raea/light";
+import { Mesh, MeshStandardMaterial, PerspectiveCamera } from "@raea/render/three";
import { toR3FSource } from "../src/export";
import { OUTPUTS, SIZE } from "./parity/fixtures";
@@ -31,6 +35,24 @@ describe("the source export", () => {
expect(src).toContain('<fog attach="fog" args={["#0b0e14", 6, 14]} />');
});
+ test("an <Environment room> is three's RoomEnvironment through PMREMGenerator.fromScene, with its blur (#165)", async () => {
+ const Lit = () => (
+ <AbsoluteFill>
+ <PerspectiveCamera position={[0, 0, 5]} lookAt={[0, 0, 0]} fov={32} />
+ <Environment room blur={0.04} background />
+ <Mesh name="box">
+ <Cuboid args={[2, 1.3, 1.3]} />
+ <MeshStandardMaterial color="#d97757" roughness={0.5} />
+ </Mesh>
+ </AbsoluteFill>
+ );
+ const { source: src } = await toR3FSource(Lit as never, { ...SIZE });
+ expect(src).toContain('import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js";');
+ expect(src).toContain("pmrem.fromScene(room, 0.04).texture");
+ expect(src).toContain("scene.background = t;");
+ expect(src).toContain("<Suspense fallback={null}><Environment /></Suspense>");
+ });
+
test("effects and Tony are drawn by raea-effects.ts, the composer <Raea> uses, written beside the module", async () => {
const bloom = await toR3FSource(OUTPUTS.bloom.component as never, { ...SIZE });
expect(bloom.source).toContain('import { Effects, type Effect } from "./raea-effects";');
diff --git a/sdk/r3f/test/room/check.sh b/sdk/r3f/test/room/check.sh
new file mode 100755
index 00000000..0bde6c26
--- /dev/null
+++ b/sdk/r3f/test/room/check.sh
@@ -0,0 +1,34 @@
+#!/bin/bash
+# <R3F> lit by three's RoomEnvironment (#165): room.tsx's scenes rendered by raea, each checked pixel within 8 levels
+# of what three draws there (three.ts works three's pixels out on the CPU: bun sdk/r3f/test/room/three.ts). Before
+# raea made the room, the scene was drawn without it: the repro's box face 136,76,58 against three's 255,195,160, the
+# grey boxes black. Exits 1 on a failure.
+# sdk/r3f/test/room/check.sh (RAEA_BIN: the raea to run, default target/release/raea)
+cd "$(dirname "$0")/../../../.." || exit 2
+BIN=${RAEA_BIN:-$PWD/target/release/raea}
+export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0 RAEA_AUDIO_MUTE=1
+OUT=$(mktemp -d "${TMPDIR:-/tmp}/raea-r3f-room.XXXXXX")
+trap 'rm -rf "$OUT"' EXIT
+T=sdk/r3f/test/room/room.tsx
+fail=0
+# composition, pixel x, y, three's r,g,b (three.ts)
+while read -r comp x y want; do
+ [ -f "$OUT/$comp.png" ] || {
+ "$BIN" render $T --composition "$comp" --frame 0 -o "$OUT/$comp.png" > "$OUT/$comp.log" 2>&1 || { echo "FAIL: $comp: the render failed"; tail -3 "$OUT/$comp.log"; exit 1; }
+ ! grep -q 'PMREMGenerator.fromScene' "$OUT/$comp.log" || { echo "FAIL: $comp: raea left the room out ($(grep -m1 -o 'scene.environment.*' "$OUT/$comp.log"))"; fail=1; }
+ }
+ # the 9 x 9 pixels round it, averaged
+ got=$(magick "$OUT/$comp.png" -crop "9x9+$((x - 4))+$((y - 4))" +repage -scale '1x1!' -format '%[fx:int(255*r+.5)],%[fx:int(255*g+.5)],%[fx:int(255*b+.5)]' info:)
+ if awk -F, -v a="$got" -v b="$want" 'BEGIN { split(a, g, ","); split(b, w, ","); for (i = 1; i <= 3; i++) if (g[i] - w[i] > 8 || w[i] - g[i] > 8) exit 1 }'; then
+ echo "ok $comp $x,$y: raea $got, three $want"
+ else
+ echo "FAIL $comp $x,$y: raea $got, three $want"
+ fail=1
+ fi
+done <<'EOF'
+repro 200 200 255,195,160
+grey 97 200 140,140,140
+grey 303 200 127,127,127
+EOF
+[ $fail = 0 ] && echo "PASS: an <R3F> scene is lit by three's RoomEnvironment as three lights it"
+exit $fail
diff --git a/sdk/r3f/test/room/room.tsx b/sdk/r3f/test/room/room.tsx
new file mode 100644
index 00000000..66b34bf6
--- /dev/null
+++ b/sdk/r3f/test/room/room.tsx
@@ -0,0 +1,53 @@
+// Scenes lit by three's RoomEnvironment through PMREMGenerator.fromScene, three's own recipe for soft studio light
+// (#165), for check.sh to measure against what three draws (three.ts works three's pixels out on the CPU).
+// repro: #131's repro, an orange box under a directional light and the room (the issue measured its front face)
+// grey: two grey boxes (roughness 0.5 and 1) lit by the room alone at half its intensity, so no channel clips
+import { useMemo } from "react";
+import { useThree } from "@react-three/fiber";
+import * as THREE from "three";
+import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js";
+import { AbsoluteFill, Composition, registerRoot } from "raea";
+import { R3F } from "raea/r3f";
+
+function Studio({ intensity = 1 }: { intensity?: number }) {
+ const { gl, scene } = useThree();
+ useMemo(() => {
+ scene.environment = new THREE.PMREMGenerator(gl).fromScene(new RoomEnvironment(), 0.04).texture;
+ scene.environmentIntensity = intensity;
+ }, [gl, scene, intensity]);
+ return null;
+}
+
+const Repro = () => (
+ <AbsoluteFill style={{ background: "#00f" }}>
+ <R3F flat camera={{ position: [0, 0, 5], fov: 32 }}>
+ <Studio />
+ <directionalLight position={[2, 4, 4]} intensity={1.5} />
+ <mesh>
+ <boxGeometry args={[2, 1.3, 1.3]} />
+ <meshStandardMaterial color="#D97757" roughness={0.5} />
+ </mesh>
+ </R3F>
+ </AbsoluteFill>
+);
+
+const Grey = () => (
+ <AbsoluteFill style={{ background: "#00f" }}>
+ <R3F flat camera={{ position: [0, 0, 6], fov: 32 }}>
+ <Studio intensity={0.5} />
+ {([[-0.8, 0.5], [0.8, 1]] as const).map(([x, roughness]) => (
+ <mesh key={x} position={[x, 0, 0]}>
+ <boxGeometry args={[1.2, 1.2, 1.2]} />
+ <meshStandardMaterial color="#808080" roughness={roughness} />
+ </mesh>
+ ))}
+ </R3F>
+ </AbsoluteFill>
+);
+
+registerRoot(() => (
+ <>
+ <Composition id="repro" component={Repro} width={400} height={400} fps={30} durationInFrames={1} />
+ <Composition id="grey" component={Grey} width={400} height={400} fps={30} durationInFrames={1} />
+ </>
+));
diff --git a/sdk/r3f/test/room/three.ts b/sdk/r3f/test/room/three.ts
new file mode 100644
index 00000000..58c4e1e6
--- /dev/null
+++ b/sdk/r3f/test/room/three.ts
@@ -0,0 +1,204 @@
+// What three.js draws for room.tsx's scenes, worked out on the CPU so check.sh has three's pixels without a browser
+// (#165): PMREMGenerator.fromScene(new RoomEnvironment()) and MeshStandardMaterial's shading as three 0.185 does them.
+// bun sdk/r3f/test/room/three.ts prints each checked pixel's colour
+// 1. The room as fromScene renders it into its cube (256 a face, texel centres): three's own RoomEnvironment object
+// (its boxes' matrices, its materials, its point light), each direction traced to the box it hits; a light box is
+// its emissive, a wall or box is lit by the point light (Lambert + BRDF_GGX_Multiscatter, three's attenuation).
+// fromScene's sigma blur (0.04 in the scenes) is left out: it softens only mirror reflections.
+// 2. PMREM's GGX VNDF filter chain (_applyGGXFilter: 11 levels, 256 Hammersley samples each, the incremental
+// roughness times 1.25 t), each level read bilinearly within a face.
+// 3. textureCubeUV's roughnessToMip, getIBLIrradiance and getIBLRadiance, RE_IndirectSpecular_Physical's
+// multiple scattering with the DFG LUT, RE_Direct_Physical for a directional light, no tone mapping (R3F's flat),
+// sRGB out.
+import * as THREE from "three";
+import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js";
+// @ts-expect-error: three's DFG LUT (the one WebGLRenderer binds as dfgLUT) is internal, with no declaration file
+import { getDFGLUT } from "three/src/renderers/shaders/DFGLUTData.js";
+
+type V3 = THREE.Vector3;
+const sat = (x: number) => Math.min(Math.max(x, 0), 1);
+
+// the DFG LUT, sampled as texture2D(dfgLUT, vec2(roughness, dotNV)) with linear filtering
+const LUT = (getDFGLUT() as THREE.DataTexture).image.data as Uint16Array;
+function dfg(r: number, nv: number): [number, number] {
+ const fx = Math.min(Math.max(r * 16 - 0.5, 0), 15), fy = Math.min(Math.max(nv * 16 - 0.5, 0), 15);
+ const x0 = Math.floor(fx), y0 = Math.floor(fy), x1 = Math.min(x0 + 1, 15), y1 = Math.min(y0 + 1, 15);
+ const tx = fx - x0, ty = fy - y0;
+ const at = (x: number, y: number, c: number) => THREE.DataUtils.fromHalfFloat(LUT[(y * 16 + x) * 2 + c]);
+ const o: [number, number] = [0, 0];
+ for (let c = 0; c < 2; c++) o[c] = (at(x0, y0, c) * (1 - tx) + at(x1, y0, c) * tx) * (1 - ty) + (at(x0, y1, c) * (1 - tx) + at(x1, y1, c) * tx) * ty;
+ return o;
+}
+
+/** BRDF_GGX_Multiscatter for a grey f0 (f90 1) */
+function ggx(l: V3, v: V3, n: V3, f0: number, rough: number) {
+ const a2 = rough ** 4;
+ const h = l.clone().add(v).normalize();
+ const nl = sat(n.dot(l)), nv = sat(n.dot(v)), nh = sat(n.dot(h)), vh = sat(v.dot(h));
+ const fr = Math.pow(2, (-5.55473 * vh - 6.98316) * vh);
+ const F = f0 * (1 - fr) + fr;
+ const V = 0.5 / Math.max(nl * Math.sqrt(a2 + (1 - a2) * nv * nv) + nv * Math.sqrt(a2 + (1 - a2) * nl * nl), 1e-6);
+ const D = a2 / (Math.PI * (nh * nh * (a2 - 1) + 1) ** 2);
+ const [dv, dl] = [dfg(rough, nv), dfg(rough, nl)];
+ const [ev, el] = [1 - dv[0] - dv[1], 1 - dl[0] - dl[1]];
+ const favg = f0 + (1 - f0) / 21;
+ const fms = ((f0 * dv[0] + dv[1]) * (f0 * dl[0] + dl[1]) * favg) / (1 - ev * el * favg + 1e-6);
+ return F * V * D + fms * ev * el;
+}
+
+// 1. the room
+type Box = { inv: THREE.Matrix4; m: THREE.Matrix4; back: boolean; emissive?: number };
+const boxes: Box[] = [];
+let light = new THREE.Vector3(), lightK = 0, reach = 0;
+{
+ const room = new RoomEnvironment();
+ room.updateMatrixWorld(true);
+ room.traverse((o) => {
+ if (o instanceof THREE.PointLight) [light, lightK, reach] = [o.getWorldPosition(new THREE.Vector3()), o.intensity, o.distance];
+ if (!(o instanceof THREE.Mesh)) return;
+ const mat = o.material as THREE.MeshStandardMaterial | THREE.MeshLambertMaterial;
+ const add = (m: THREE.Matrix4) =>
+ boxes.push({ m, inv: m.clone().invert(), back: mat.side === THREE.BackSide, emissive: mat instanceof THREE.MeshLambertMaterial ? mat.emissive.r * mat.emissiveIntensity : undefined });
+ if (o instanceof THREE.InstancedMesh) {
+ for (let i = 0; i < o.count; i++) {
+ const at = new THREE.Matrix4();
+ o.getMatrixAt(i, at);
+ add(o.matrixWorld.clone().multiply(at));
+ }
+ } else add(o.matrixWorld.clone());
+ });
+}
+function radiance(d: V3): number {
+ let best = Infinity, hit: Box | undefined, nl = new THREE.Vector3();
+ for (const b of boxes) {
+ const lo = new THREE.Vector3().applyMatrix4(b.inv);
+ const ld = d.clone().applyMatrix3(new THREE.Matrix3().setFromMatrix4(b.inv));
+ let t0 = -Infinity, t1 = Infinity, a0 = -1, a1 = -1;
+ for (let k = 0; k < 3; k++) {
+ const o = lo.getComponent(k), dd = ld.getComponent(k);
+ if (Math.abs(dd) < 1e-12) {
+ if (Math.abs(o) > 0.5) t0 = Infinity;
+ continue;
+ }
+ let ta = (-0.5 - o) / dd, tb = (0.5 - o) / dd;
+ if (ta > tb) [ta, tb] = [tb, ta];
+ if (ta > t0) [t0, a0] = [ta, k];
+ if (tb < t1) [t1, a1] = [tb, k];
+ }
+ if (t0 > t1) continue;
+ const [t, axis] = b.back ? [t1, a1] : [t0, a0];
+ if (t < 0.1 || t >= best || axis < 0) continue;
+ [best, hit] = [t, b];
+ nl = new THREE.Vector3();
+ nl.setComponent(axis, Math.sign(lo.getComponent(axis) + ld.getComponent(axis) * t) * (b.back ? -1 : 1));
+ }
+ if (!hit) return 0;
+ if (hit.emissive !== undefined) return hit.emissive;
+ const p = d.clone().multiplyScalar(best);
+ const n = nl.applyMatrix3(new THREE.Matrix3().getNormalMatrix(hit.m)).normalize();
+ const to = light.clone().sub(p);
+ const dist = to.length();
+ const l = to.divideScalar(dist);
+ const irr = sat(n.dot(l)) * lightK * (1 / Math.max(dist * dist, 0.01)) * sat(1 - (dist / reach) ** 4) ** 2;
+ return irr / Math.PI + irr * ggx(l, d.clone().negate(), n, 0.04, 1);
+}
+
+// 2. PMREM: cube levels of 256, 128, 64, 32, then 16 (seven of them), PMREM's face layout (getUV)
+type Level = { n: number; px: Float32Array };
+function face(d: V3) {
+ const [ax, ay, az] = [Math.abs(d.x), Math.abs(d.y), Math.abs(d.z)];
+ const f = ax > az ? (ax > ay ? (d.x > 0 ? 0 : 3) : d.y > 0 ? 1 : 4) : az > ay ? (d.z > 0 ? 2 : 5) : d.y > 0 ? 1 : 4;
+ const uv = [[d.z / ax, d.y / ax], [-d.x / ay, -d.z / ay], [-d.x / az, d.y / az], [-d.z / ax, d.y / ax], [-d.x / ay, d.z / ay], [d.x / az, d.y / az]][f];
+ return { f, u: 0.5 * (uv[0] + 1), v: 0.5 * (uv[1] + 1) };
+}
+function dir(f: number, u: number, v: number): V3 {
+ const [a, b] = [2 * u - 1, 2 * v - 1];
+ return new THREE.Vector3(...([[1, b, a], [-a, 1, -b], [-a, b, 1], [-1, b, -a], [-a, -1, b], [a, b, -1]][f] as [number, number, number])).normalize();
+}
+function sample(l: Level, d: V3) {
+ const { f, u, v } = face(d), n = l.n, o = f * n * n;
+ const fx = Math.min(Math.max(u * n - 0.5, 0), n - 1), fy = Math.min(Math.max(v * n - 0.5, 0), n - 1);
+ const x0 = Math.floor(fx), y0 = Math.floor(fy), x1 = Math.min(x0 + 1, n - 1), y1 = Math.min(y0 + 1, n - 1);
+ const [tx, ty] = [fx - x0, fy - y0];
+ const p = (x: number, y: number) => l.px[o + y * n + x];
+ return (p(x0, y0) * (1 - tx) + p(x1, y0) * tx) * (1 - ty) + (p(x0, y1) * (1 - tx) + p(x1, y1) * tx) * ty;
+}
+function make(n: number, at: (d: V3) => number): Level {
+ const px = new Float32Array(6 * n * n);
+ for (let f = 0; f < 6; f++) for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) px[f * n * n + y * n + x] = at(dir(f, (x + 0.5) / n, (y + 0.5) / n));
+ return { n, px };
+}
+const radical = (i: number) => {
+ let b = i >>> 0;
+ b = ((b << 16) | (b >>> 16)) >>> 0;
+ b = (((b & 0x55555555) << 1) | ((b & 0xaaaaaaaa) >>> 1)) >>> 0;
+ b = (((b & 0x33333333) << 2) | ((b & 0xcccccccc) >>> 2)) >>> 0;
+ b = (((b & 0x0f0f0f0f) << 4) | ((b & 0xf0f0f0f0) >>> 4)) >>> 0;
+ b = (((b & 0x00ff00ff) << 8) | ((b & 0xff00ff00) >>> 8)) >>> 0;
+ return b * 2.3283064365386963e-10;
+};
+/** _getGGXShader's pass: V = N, 256 VNDF samples of the level before, weighted by N.L */
+function filter(src: Level, n: number, rough: number): Level {
+ const alpha = rough * rough;
+ const hs = Array.from({ length: 256 }, (_, i) => {
+ const r = Math.sqrt(i / 256), phi = 2 * Math.PI * radical(i);
+ const [t1, t2] = [r * Math.cos(phi), r * Math.sin(phi)];
+ return new THREE.Vector3(alpha * t1, alpha * t2, Math.sqrt(Math.max(0, 1 - t1 * t1 - t2 * t2))).normalize();
+ });
+ return make(n, (N) => {
+ const T = new THREE.Vector3().crossVectors(Math.abs(N.z) < 0.999 ? new THREE.Vector3(0, 0, 1) : new THREE.Vector3(1, 0, 0), N).normalize();
+ const B = new THREE.Vector3().crossVectors(N, T);
+ let [acc, w] = [0, 0];
+ for (const h of hs) {
+ const H = T.clone().multiplyScalar(h.x).addScaledVector(B, h.y).addScaledVector(N, h.z).normalize();
+ const L = H.multiplyScalar(2 * N.dot(H)).sub(N).normalize();
+ const nl = Math.max(N.dot(L), 0);
+ if (nl > 0) [acc, w] = [acc + sample(src, L) * nl, w + nl];
+ }
+ return w > 0 ? acc / w : 0;
+ });
+}
+const SIZES = [256, 128, 64, 32, 16, 16, 16, 16, 16, 16, 16];
+const levels: Level[] = [make(256, radiance)];
+for (let i = 1; i < SIZES.length; i++) {
+ const [t, s] = [i / 10, (i - 1) / 10];
+ levels.push(filter(levels[i - 1], SIZES[i], Math.sqrt(t * t - s * s) * t * 1.25));
+}
+
+// 3. the material's lookups and shading
+function mip(r: number) {
+ if (r >= 0.8) return (1 - r) * 5 - 2;
+ if (r >= 0.4) return ((0.8 - r) * 3) / 0.4 - 1;
+ if (r >= 0.305) return (0.4 - r) / 0.095 + 2;
+ if (r >= 0.21) return (0.305 - r) / 0.095 + 3;
+ return -2 * Math.log2(1.16 * r);
+}
+/** textureCubeUV: mip m is level 8 - m */
+function cubeUV(d: V3, rough: number) {
+ const m = Math.min(Math.max(mip(rough), -2), 8), mi = Math.floor(m), mf = m - mi;
+ const c0 = sample(levels[8 - mi], d);
+ return mf === 0 ? c0 : c0 * (1 - mf) + sample(levels[8 - mi - 1], d) * mf;
+}
+const srgb = (c: number) => Math.round(255 * sat(c <= 0.0031308 ? c * 12.92 : 1.055 * c ** (1 / 2.4) - 0.055));
+
+/** a MeshStandardMaterial pixel (metalness 0) lit by the room at `envK` and a directional light */
+export function shade(hex: string, rough: number, n: V3, v: V3, envK: number, sun?: { dir: V3; k: number }): number[] {
+ const c = new THREE.Color(hex);
+ const fab = dfg(rough, sat(n.dot(v)));
+ const single = 0.04 * fab[0] + fab[1], ems = 1 - fab[0] - fab[1], favg = 0.04 + 0.96 / 21;
+ const multi = ((single * favg) / (1 - ems * favg)) * ems;
+ const E = cubeUV(n, 1) * envK;
+ const r = v.clone().negate().reflect(n).lerp(n, rough ** 4).normalize();
+ const rad = cubeUV(r, rough) * envK;
+ const irr = sun ? sat(n.dot(sun.dir)) * sun.k : 0;
+ const spec = sun ? irr * ggx(sun.dir, v, n, 0.04, rough) : 0;
+ return [c.r, c.g, c.b].map((a) => srgb(irr * a / Math.PI + spec + rad * single + multi * E + a * (1 - single - multi) * E));
+}
+
+if (import.meta.main) {
+ const front = new THREE.Vector3(0, 0, 1);
+ // room.tsx "repro": #131's box, camera (0, 0, 5), a directional light from (2, 4, 4) at 1.5, the frame's middle
+ console.log("repro 200,200", shade("#D97757", 0.5, front, front, 1, { dir: new THREE.Vector3(2, 4, 4).normalize(), k: 1.5 }).join(","));
+ // room.tsx "grey": two grey boxes at x -0.8 and 0.8 (front faces at z 0.6), camera (0, 0, 6), the room at 0.5
+ for (const [x, r, px] of [[-0.8, 0.5, 97], [0.8, 1, 303]] as const) console.log(`grey ${px},200`, shade("#808080", r, front, new THREE.Vector3(-x, 0, 5.4).normalize(), 0.5).join(","));
+}
diff --git a/sdk/raea/conformance/envmap.test.tsx b/sdk/raea/conformance/envmap.test.tsx
index 328308fa..484e3abc 100644
--- a/sdk/raea/conformance/envmap.test.tsx
+++ b/sdk/raea/conformance/envmap.test.tsx
@@ -1,7 +1,7 @@
// docs/control.feature FC0a: Bevy's EnvironmentMapLight with its own prefiltered maps (3d/pbr, 3d/animated_material),
-// its rotation, and Bevy's Skybox (3d/rotate_environment_map).
+// its rotation, and Bevy's Skybox (3d/rotate_environment_map); <Environment room>, three.js's RoomEnvironment (#165).
import { describe, expect, test } from "bun:test";
-import { EnvironmentMapLight, Skybox } from "raea/light";
+import { Environment, EnvironmentMapLight, Skybox } from "raea/light";
import { renderFrame } from "../src/test";
const html = (el: React.ReactElement) => renderFrame(el, { frame: 0, width: 320, height: 240, fps: 30, durationInFrames: 30 });
@@ -41,3 +41,18 @@ describe("rotation and Skybox: Bevy's Quat on both, the sky's cubemap and bright
expect(() => html(<EnvironmentMapLight diffuse_map="d.ktx2" specular_map="s.ktx2" rotation={[0, 0, 0] as never} />)).toThrow(/unit Quat/);
});
});
+
+describe("Environment room: three.js's RoomEnvironment, with no file (#165)", () => {
+ test("room and its blur reach the Environment row, with no src", () => {
+ const out = html(<Environment room blur={0.04} intensity={0.5} />);
+ expect(out).toContain('data-3d="Environment"');
+ for (const s of ["&quot;room&quot;:true", "&quot;blur&quot;:0.04", "&quot;intensity&quot;:0.5"]) expect(out).toContain(s);
+ expect(out).not.toContain("&quot;src&quot;");
+ });
+ test("a room with a src, a blur without a room, a negative blur or neither src nor room is refused", () => {
+ expect(() => html(<Environment room src="sky.hdr" />)).toThrow(/src \(a panorama\) or room, not both/);
+ expect(() => html(<Environment src="sky.hdr" blur={0.04} />)).toThrow(/blur is the room's/);
+ expect(() => html(<Environment room blur={-1} />)).toThrow(/blur must be 0 or more/);
+ expect(() => html(<Environment />)).toThrow(/or room for three's RoomEnvironment/);
+ });
+});
diff --git a/sdk/render/src/3d/effects.tsx b/sdk/render/src/3d/effects.tsx
index 4f35558d..564b8e19 100644
--- a/sdk/render/src/3d/effects.tsx
+++ b/sdk/render/src/3d/effects.tsx
@@ -248,8 +248,14 @@ export function Grade(props: GradeProps) {
export interface EnvironmentProps {
/** an equirectangular panorama in the media folder: a Radiance .hdr (Poly Haven's), an OpenEXR .exr, or an 8-bit
- * .png/.jpg. Change it between frames to cut from one place to another */
- src: string;
+ * .png/.jpg. Change it between frames to cut from one place to another. Give it or `room`, not both */
+ src?: string;
+ /** three.js's RoomEnvironment in place of a panorama: a white studio room with soft light boxes, made by raea with
+ * no file. It is the light a three.js scene gets from PMREMGenerator.fromScene(new RoomEnvironment(), blur), which
+ * <R3F> turns into this */
+ room?: boolean;
+ /** with `room`, its blur in radians before it lights (fromScene's sigma: three's examples use 0.04); 0 by default */
+ blur?: number;
/** how strongly it lights the scene (1 by default: a sky about as bright as an AmbientLight of 2.5 overall); animate
* it, or set 0 to switch it off for a shot */
intensity?: number;
@@ -264,13 +270,20 @@ export interface EnvironmentProps {
/** Light from all around, out of a panorama: soft light from the sky and reflections of it in every glossy or metal
* surface (image-based lighting), and with `background` the panorama as the sky. Put it inside the Canvas3D, once a
* frame; its src, intensity, rotation and background may change from frame to frame (a cut from a hall to a street).
+ * With `room` in place of a panorama it is three.js's RoomEnvironment, soft studio light with no file.
* Bevy's EnvironmentMapLight with maps already filtered is <EnvironmentMapLight>.
* Its panorama is filtered by Bevy's generator and, with `background`, drawn as the sky (engine/render
* environment.rs): @bevy bevy_light::probe::GeneratedEnvironmentMapLight. Bevy's Skybox from its own cubemap is <Skybox>. */
export function Environment(props: EnvironmentProps) {
- if (typeof props.src !== "string" || props.src === "") throw new TypeError(`Environment: src must be a panorama's path, staticFile("sky.hdr"), got ${JSON.stringify(props.src)}`);
- if (!/\.(hdr|exr|png|jpe?g)$/i.test(props.src.split("?")[0])) throw new TypeError(`Environment: src must be an equirectangular .hdr, .exr, .png or .jpg, got ${JSON.stringify(props.src)}`);
- for (const k of ["intensity", "backgroundIntensity"] as const) {
+ if (props.room !== undefined && typeof props.room !== "boolean") throw new TypeError(`Environment: room is true or false, got ${JSON.stringify(props.room)}`);
+ if (props.room) {
+ if (props.src !== undefined) throw new TypeError(`Environment: give src (a panorama) or room, not both`);
+ } else {
+ if (typeof props.src !== "string" || props.src === "") throw new TypeError(`Environment: src must be a panorama's path, staticFile("sky.hdr"), or room for three's RoomEnvironment, got ${JSON.stringify(props.src)}`);
+ if (!/\.(hdr|exr|png|jpe?g)$/i.test(props.src.split("?")[0])) throw new TypeError(`Environment: src must be an equirectangular .hdr, .exr, .png or .jpg, got ${JSON.stringify(props.src)}`);
+ if (props.blur !== undefined) throw new TypeError(`Environment: blur is the room's (with room), not a panorama's`);
+ }
+ for (const k of ["intensity", "backgroundIntensity", "blur"] as const) {
const v = props[k];
if (v !== undefined && !(typeof v === "number" && v >= 0 && Number.isFinite(v))) throw new RangeError(`Environment: ${k} must be 0 or more, got ${v}`);
}
diff --git a/systems/environment/src/lib.rs b/systems/environment/src/lib.rs
index 254e8c46..3d3e20b6 100644
--- a/systems/environment/src/lib.rs
+++ b/systems/environment/src/lib.rs
@@ -11,7 +11,8 @@
//! taken off and its targets keep the filtered light. Filtering every frame was 2.2 ms of GPU a frame at 1920x1080 in
//! the Rome film (lightprobe_radiance_map and lightprobe_irradiance_map), for the same light each frame.
//!
-//! Camera columns: env_srcs (a JSON list of panorama paths), env_i (which one this frame, -1 none; keyed), env_k (its
+//! Camera columns: env_srcs (a JSON list of panorama paths, or `room:SIGMA` for three's RoomEnvironment, which room.rs
+//! makes), env_i (which one this frame, -1 none; keyed), env_k (its
//! intensity in cd/m²; keyed), env_rot (a turn about +Y, radians; keyed), sky_k (the sky's brightness, 0 no sky;
//! keyed).
@@ -35,6 +36,8 @@ pub use prefiltered::{sync_prefiltered, Prefiltered};
/// A panorama's sun, for traced lighting (RT6)
mod sun;
pub use sun::{sync_suns, Suns};
+/// three.js's RoomEnvironment made as a panorama (<Environment room>, #165)
+mod room;
/// The camera's panoramas as cubemaps, in env_srcs' order, and each one's bake entity (its filtered light).
#[derive(Component)]
@@ -165,6 +168,16 @@ fn equirect(path: &Path) -> Result<Equirect, String> {
Ok(Equirect { w, h, px })
}
+/// One of env_srcs as a panorama: three's room made here (`room:` and its blur), else the file, found as a media
+/// source is.
+fn source(inserted: &[Tup], src: &str, dir: &Path) -> Result<Equirect, String> {
+ if let Some(sigma) = room::blur_of(src) {
+ return Ok(room::room(sigma));
+ }
+ let path = resolve_src(inserted, src, dir).map_err(|e| format!("Environment: {e}"))?;
+ equirect(&path).map_err(|e| format!("Environment: {e}"))
+}
+
/// A PFM (colour, "PF"): its header, then RGB floats row by row from the bottom; a negative scale is little-endian.
fn pfm(b: &[u8]) -> Option<Equirect> {
let mut fields = Vec::new();
@@ -299,8 +312,7 @@ pub fn environment(world: &mut World, e: Entity, vals: &BTreeMap<String, V>, ins
}
let mut eqs = Vec::new();
for s in &srcs {
- let path = resolve_src(inserted, s, dir).map_err(|e| format!("Environment: {e}"))?;
- eqs.push(equirect(&path).map_err(|e| format!("Environment: {e}"))?);
+ eqs.push(source(inserted, s, dir)?);
}
let widest = eqs.iter().map(|q| q.w).max().unwrap_or(1024) as u32;
let size = (widest / 4).max(64).next_power_of_two().min(2048);
@@ -351,8 +363,7 @@ fn grow(world: &mut World, e: Entity, vals: &BTreeMap<String, V>, inserted: &[Tu
}
let size = world.resource::<Assets<Image>>().get(&first).map_or(512, |i| i.width());
for s in &srcs[have..] {
- let path = resolve_src(inserted, s, dir).map_err(|e| format!("Environment: {e}"))?;
- let q = equirect(&path).map_err(|e| format!("Environment: {e}"))?;
+ let q = source(inserted, s, dir)?;
let (map, _, bake) = panorama(world, &q, size);
let mut m = world.get_mut::<EnvMaps>(e).ok_or("camera: its environment went")?;
m.0.push(map);
diff --git a/systems/environment/src/room.rs b/systems/environment/src/room.rs
new file mode 100644
index 00000000..7fa9ffbc
--- /dev/null
+++ b/systems/environment/src/room.rs
@@ -0,0 +1,316 @@
+//! three.js's RoomEnvironment as a panorama (#165): the soft studio light a three.js scene gets from
+//! `PMREMGenerator.fromScene(new RoomEnvironment(), sigma)` with no HDR file, made by raea with no file either.
+//!
+//! The room is three's own (three/examples/jsm/environments/RoomEnvironment.js, r185, the same since r155's physical
+//! lights): a white box room, six white boxes on its floor, six light boxes on its walls and ceiling and one point light
+//! (900 cd, reaching 28 m), the whole scene 3.5 m down. Each direction from fromScene's cube camera (at the origin) is
+//! traced to the box it hits, and that box is coloured as three draws it into its cube (no tone mapping, linear): a
+//! light box (an emissive-only MeshLambertMaterial) is its emissive intensity; a wall or a box (a white
+//! MeshStandardMaterial, roughness 1, metalness 0) is lit by the point light alone with three's direct lighting
+//! (RE_Direct_Physical: Lambert's diffuse and BRDF_GGX, with its Schlick Fresnel, height-correlated Smith and GGX terms,
+//! and three's distance attenuation), no shadows (nothing in the room casts any). three adds a multiple-scattering
+//! term to BRDF_GGX that is under 1e-4 of a white wall's diffuse at roughness 1: left out. `sigma` blurs it as
+//! fromScene does before filtering (three's two half blurs about +Y, clipped at its 20 taps). The panorama is then
+//! filtered like any other (Bevy's generator in the place of three's PMREM).
+
+use bevy::math::{Quat, Vec3};
+
+use super::Equirect;
+
+/// An <Environment room>'s source in the camera row's env_srcs (runtime/look camera.rs): `room:` and the blur, in
+/// radians.
+pub const PREFIX: &str = "room:";
+
+/// The blur of a room source (`room:0.04`), or None for a panorama file.
+pub fn blur_of(src: &str) -> Option<f32> {
+ let b = src.strip_prefix(PREFIX)?;
+ let b: f32 = if b.is_empty() { 0.0 } else { b.parse().ok()? };
+ (b.is_finite() && b >= 0.0).then_some(b)
+}
+
+/// The panorama's size: three renders the room into a cube of 256 a face, which an equirectangular 1024 wide makes.
+const WIDTH: usize = 1024;
+
+/// How a box is drawn: the room (seen from inside: three's BackSide), a white box, or a light box's emissive.
+#[derive(Clone, Copy, PartialEq)]
+enum Kind {
+ Room,
+ Solid,
+ Light(f32),
+}
+
+/// One of the room's boxes: three's unit BoxGeometry placed by position, a turn about +Y (its only rotation) and scale.
+struct Part {
+ at: Vec3,
+ turn: f32,
+ size: Vec3,
+ kind: Kind,
+}
+
+/// RoomEnvironment's scene is moved this far up (its position.y).
+const DROP: f32 = -3.5;
+/// The point light: its position, intensity (cd) and distance (its decay is 2).
+const LIGHT: [f32; 3] = [0.418, 16.199, 0.300];
+const LIGHT_K: f32 = 900.0;
+const LIGHT_REACH: f32 = 28.0;
+
+/// RoomEnvironment's boxes, as its constructor places them.
+fn parts() -> Vec<Part> {
+ let p = |at: [f32; 3], turn: f32, size: [f32; 3], kind: Kind| Part { at: Vec3::new(at[0], at[1] + DROP, at[2]), turn, size: Vec3::from(size), kind };
+ vec![
+ p([-0.757, 13.219, 0.717], 0.0, [31.713, 28.305, 28.591], Kind::Room),
+ p([-10.906, 2.009, 1.846], -0.195, [2.328, 7.905, 4.651], Kind::Solid),
+ p([-5.607, -0.754, -0.758], 0.994, [1.970, 1.534, 3.955], Kind::Solid),
+ p([6.167, 0.857, 7.803], 0.561, [3.927, 6.285, 3.687], Kind::Solid),
+ p([-2.017, 0.018, 6.124], 0.333, [2.002, 4.566, 2.064], Kind::Solid),
+ p([2.291, -0.756, -2.621], -0.286, [1.546, 1.552, 1.496], Kind::Solid),
+ p([-2.193, -0.369, -5.547], 0.516, [3.875, 3.487, 2.986], Kind::Solid),
+ p([-16.116, 14.37, 8.208], 0.0, [0.1, 2.428, 2.739], Kind::Light(50.0)),
+ p([-16.109, 18.021, -8.207], 0.0, [0.1, 2.425, 2.751], Kind::Light(50.0)),
+ p([14.904, 12.198, -1.832], 0.0, [0.15, 4.265, 6.331], Kind::Light(17.0)),
+ p([-0.462, 8.89, 14.520], 0.0, [4.38, 5.441, 0.088], Kind::Light(43.0)),
+ p([3.235, 11.486, -12.541], 0.0, [2.5, 2.0, 0.1], Kind::Light(20.0)),
+ p([0.0, 20.0, 0.0], 0.0, [1.0, 0.1, 1.0], Kind::Light(100.0)),
+ ]
+}
+
+/// Where a ray from `o` along unit `d` meets a part as three draws it (a BackSide room where the ray leaves it, a
+/// FrontSide box where it enters), past three's cube camera's near plane: the distance and the face's normal, facing
+/// the ray.
+fn hit(part: &Part, o: Vec3, d: Vec3) -> Option<(f32, Vec3)> {
+ let back = Quat::from_rotation_y(-part.turn);
+ let lo = back * (o - part.at) / part.size;
+ let ld = back * d / part.size;
+ let (mut t0, mut t1, mut a0, mut a1) = (f32::NEG_INFINITY, f32::INFINITY, 0usize, 0usize);
+ for k in 0..3 {
+ if ld[k].abs() < 1e-12 {
+ if lo[k].abs() > 0.5 {
+ return None;
+ }
+ continue;
+ }
+ let (mut ta, mut tb) = ((-0.5 - lo[k]) / ld[k], (0.5 - lo[k]) / ld[k]);
+ if ta > tb {
+ std::mem::swap(&mut ta, &mut tb);
+ }
+ if ta > t0 {
+ (t0, a0) = (ta, k);
+ }
+ if tb < t1 {
+ (t1, a1) = (tb, k);
+ }
+ }
+ if t0 > t1 {
+ return None;
+ }
+ let (t, axis) = if part.kind == Kind::Room { (t1, a1) } else { (t0, a0) };
+ if t < 0.1 {
+ return None;
+ }
+ let mut n = Vec3::ZERO;
+ n[axis] = (lo[axis] + ld[axis] * t).signum();
+ if part.kind == Kind::Room {
+ n = -n;
+ }
+ Some((t, Quat::from_rotation_y(part.turn) * n))
+}
+
+/// three's BRDF_GGX for a white dielectric at roughness 1 (f0 0.04, f90 1, alpha 1).
+fn ggx(l: Vec3, v: Vec3, n: Vec3) -> f32 {
+ let sat = |x: f32| x.clamp(0.0, 1.0);
+ let (nl, nv, vh) = (sat(n.dot(l)), sat(n.dot(v)), sat(v.dot((l + v).normalize())));
+ let fresnel = ((-5.55473 * vh - 6.98316) * vh).exp2();
+ let f = 0.04 * (1.0 - fresnel) + fresnel;
+ // at alpha 1 (a2 = 1) V_GGX_SmithCorrelated is 0.5 / (nl + nv) and D_GGX is 1 / pi, whatever the half vector
+ f * 0.5 / (nl + nv).max(1e-6) / std::f32::consts::PI
+}
+
+/// The room's light along a world direction from its cube camera at the origin.
+fn radiance(parts: &[Part], d: Vec3) -> f32 {
+ let mut best: Option<(f32, Vec3, Kind)> = None;
+ for p in parts {
+ if let Some((t, n)) = hit(p, Vec3::ZERO, d) {
+ if best.is_none_or(|b| t < b.0) {
+ best = Some((t, n, p.kind));
+ }
+ }
+ }
+ let Some((t, n, kind)) = best else { return 0.0 };
+ if let Kind::Light(k) = kind {
+ return k;
+ }
+ let at = d * t;
+ let to = Vec3::from(LIGHT) + Vec3::new(0.0, DROP, 0.0) - at;
+ let dist = to.length();
+ let l = to / dist;
+ // getDistanceAttenuation(distance, 28, 2)
+ let fall = 1.0 / (dist * dist).max(0.01) * (1.0 - (dist / LIGHT_REACH).powi(4)).clamp(0.0, 1.0).powi(2);
+ let irradiance = n.dot(l).clamp(0.0, 1.0) * LIGHT_K * fall;
+ irradiance / std::f32::consts::PI + irradiance * ggx(l, -d, n)
+}
+
+/// A pixel's world direction in raea's panoramas (Equirect::sample's: the middle straight ahead, -Z).
+fn direction(x: f32, y: f32, w: usize, h: usize) -> Vec3 {
+ let lon = (x / w as f32 - 0.5) * std::f32::consts::TAU;
+ let polar = y / h as f32 * std::f32::consts::PI;
+ Vec3::new(polar.sin() * lon.sin(), polar.cos(), -polar.sin() * lon.cos())
+}
+
+/// three's RoomEnvironment as a panorama, blurred by `sigma` radians as fromScene blurs it.
+pub fn room(sigma: f32) -> Equirect {
+ let (w, h) = (WIDTH, WIDTH / 2);
+ let parts = parts();
+ let mut px = Vec::with_capacity(w * h);
+ for y in 0..h {
+ for x in 0..w {
+ let v = radiance(&parts, direction(x as f32 + 0.5, y as f32 + 0.5, w, h));
+ px.push([v; 3]);
+ }
+ }
+ let mut eq = Equirect { w, h, px };
+ if sigma > 0.0 {
+ blur(&mut eq, sigma);
+ }
+ eq
+}
+
+/// three's fromScene blur (PMREMGenerator._blur about its default pole, +Y) on the panorama. three blurs its 256 cube
+/// twice: turning each direction about +Y (along its latitude, by angle, not arc) and then along its meridian through
+/// the pole, each with taps a texel (pi / 510 radians) apart out to 3 sigma, Gaussian weights summing to 1, and at
+/// most 20 taps (a larger sigma is clipped to 19 texels a side, which three warns of). On a panorama both are
+/// straight lines: a row, then a column carried over the pole.
+fn blur(eq: &mut Equirect, sigma: f32) {
+ let step = std::f32::consts::PI / (2.0 * 255.0);
+ let sigma_px = sigma / step;
+ let samples = (1 + (3.0 * sigma_px).floor() as usize).min(20);
+ let weight = |i: usize| (-(i as f32 / sigma_px).powi(2) / 2.0).exp();
+ let sum: f32 = weight(0) + (1..samples).map(|i| 2.0 * weight(i)).sum::<f32>();
+ let taps: Vec<f32> = (0..samples).map(|i| weight(i) / sum).collect();
+ let (w, h) = (eq.w, eq.h);
+ let at = |px: &[[f32; 3]], x: f32, y: usize| {
+ let fx = x.rem_euclid(w as f32);
+ let x0 = fx.floor() as usize % w;
+ let t = fx - fx.floor();
+ let (a, b) = (px[y * w + x0][0], px[y * w + (x0 + 1) % w][0]);
+ a * (1.0 - t) + b * t
+ };
+ // along each row: a turn about +Y by i steps is i steps of longitude
+ let dx = step * w as f32 / std::f32::consts::TAU;
+ let src = eq.px.clone();
+ for y in 0..h {
+ for x in 0..w {
+ let mut v = taps[0] * src[y * w + x][0];
+ for (i, k) in taps.iter().enumerate().skip(1) {
+ v += k * (at(&src, x as f32 - i as f32 * dx, y) + at(&src, x as f32 + i as f32 * dx, y));
+ }
+ eq.px[y * w + x] = [v; 3];
+ }
+ }
+ // along each meridian, over the pole onto the opposite one
+ let dy = step * h as f32 / std::f32::consts::PI;
+ let src = eq.px.clone();
+ let meridian = |x: usize, y: f32| {
+ let (mut fy, mut fx) = (y, x as f32);
+ if fy < 0.0 {
+ (fy, fx) = (-fy, fx + w as f32 / 2.0);
+ } else if fy > h as f32 {
+ (fy, fx) = (2.0 * h as f32 - fy, fx + w as f32 / 2.0);
+ }
+ let fy = (fy - 0.5).clamp(0.0, (h - 1) as f32);
+ let y0 = fy.floor() as usize;
+ let t = fy - y0 as f32;
+ at(&src, fx, y0) * (1.0 - t) + at(&src, fx, (y0 + 1).min(h - 1)) * t
+ };
+ for y in 0..h {
+ for x in 0..w {
+ let c = y as f32 + 0.5;
+ let mut v = taps[0] * src[y * w + x][0];
+ for (i, k) in taps.iter().enumerate().skip(1) {
+ v += k * (meridian(x, c - i as f32 * dy) + meridian(x, c + i as f32 * dy));
+ }
+ eq.px[y * w + x] = [v; 3];
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Directions and the light three draws there, from three's own RoomEnvironment object (its matrices and
+ /// materials, traced and lit by three's formulas with the multiple-scattering term in): each box, three of the light
+ /// boxes, walls, the ceiling, the floor and a corner.
+ const THREE: [(&str, [f32; 3], f32); 14] = [
+ ("box1", [-0.977138, -0.133588, 0.165395], 0.3917562),
+ ("box2", [-0.792082, -0.600949, -0.107080], 0.7193024),
+ ("box3", [0.599263, -0.256827, 0.758237], 0.3620106),
+ ("box4", [-0.275255, -0.475180, 0.835727], 0.1959535),
+ ("box5", [0.416670, -0.774050, -0.476688], 0.8218551),
+ ("box6", [-0.308452, -0.544187, -0.780203], 0.2548782),
+ ("light1", [-0.763754, 0.515141, 0.388986], 50.0),
+ ("light4", [-0.029816, 0.347853, 0.937075], 43.0),
+ ("light5", [0.212609, 0.524852, -0.824213], 20.0),
+ ("wall", [0.309426, 0.206284, -0.928279], 0.5509641),
+ ("light1 again", [-0.780399, 0.520266, 0.346844], 50.0),
+ ("ceiling", [0.431934, 0.863868, 0.259161], 0.4399573),
+ ("floor", [0.512148, -0.384111, 0.768221], 0.2772276),
+ ("corner", [-0.577350, -0.577350, -0.577350], 0.5250023),
+ ];
+
+ #[test]
+ fn the_room_is_lit_as_three_draws_it() {
+ let parts = parts();
+ for (name, d, want) in THREE {
+ let got = radiance(&parts, Vec3::from(d).normalize());
+ assert!((got - want).abs() <= want * 1e-3, "{name}: {got}, three draws {want}");
+ }
+ // straight up is the ceiling's light box, straight down the floor under the light
+ assert_eq!(radiance(&parts, Vec3::Y), 100.0);
+ assert!((radiance(&parts, -Vec3::Y) - 0.72742).abs() < 1e-3);
+ }
+
+ #[test]
+ fn a_pixel_is_the_direction_sample_reads() {
+ let eq = room(0.0);
+ assert_eq!((eq.w, eq.h), (1024, 512));
+ let parts = parts();
+ for (name, d, _) in THREE {
+ let d = Vec3::from(d).normalize();
+ let (got, want) = (eq.sample(d)[0], radiance(&parts, d));
+ // the panorama's bilinear sample of a smooth wall is the light there; a box's or light's edge may be a
+ // pixel off, so only the smooth ones
+ if want < 10.0 && !name.starts_with("box") {
+ assert!((got - want).abs() < want * 0.02, "{name}: the panorama gives {got}, the room {want}");
+ }
+ }
+ }
+
+ #[test]
+ fn the_blur_averages_and_softens_an_edge() {
+ // its weights sum to 1: light the same everywhere stays so, over the pole too
+ let mut even = Equirect { w: 64, h: 32, px: vec![[2.0; 3]; 64 * 32] };
+ blur(&mut even, 0.04);
+ assert!(even.px.iter().all(|p| (p[0] - 2.0).abs() < 1e-4));
+ let (sharp, soft, wide) = (room(0.0), room(0.04), room(0.2));
+ // a smooth wall barely changes (the ceiling over the light, curved, by 1.7%)
+ for (name, d, _) in [THREE[9], THREE[11], THREE[12]] {
+ let (a, b) = (sharp.sample(Vec3::from(d))[0], soft.sample(Vec3::from(d))[0]);
+ assert!((a - b).abs() < a * 0.03, "{name}: {a} blurred to {b}");
+ }
+ // the ceiling's light box (1 m across, 16.5 m up: 0.06 radians) is softened by 0.04 at its middle, and a
+ // larger sigma, clipped at 19 texels a side, softens it more
+ let up = |e: &Equirect| e.sample(Vec3::Y)[0];
+ assert_eq!(up(&sharp), 100.0);
+ assert!(up(&soft) < 90.0 && up(&soft) > 30.0, "{}", up(&soft));
+ assert!(up(&wide) < up(&soft), "{} vs {}", up(&wide), up(&soft));
+ }
+
+ #[test]
+ fn a_room_source_is_named_by_its_blur() {
+ assert_eq!(blur_of("room:0.04"), Some(0.04));
+ assert_eq!(blur_of("room:0"), Some(0.0));
+ assert_eq!(blur_of("room:"), Some(0.0));
+ assert_eq!(blur_of("sky.hdr"), None);
+ assert_eq!(blur_of("room:-1"), None);
+ }
+}