Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

Live edits: what is not the scene's no longer rebuilds it (lens, exposure, fog, background, preset) (#124)

Yujia7b36fe6990a6
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index c05a15d..3682c0e 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2533,6 +2533,22 @@ kernel's shape decided: a shadow ray's origin on the side it leaves from is ever
every kernel it cost Bistro's trace 4 %, so only kernels with glass have it; and the energy table's vec4 indexed
by a variable cost the glass scene 1.5 %, a select chain nothing.
+**What is not the scene's no longer rebuilds it (2026-11-16, after it).** One flag, `Changes::structural`, sends an
+edit to a rebuild of the whole GPU scene, and it was set for things no part of the scene is built from: the scene
+camera's field of view, its depth of field, its exposure's mode, near and far (read by nothing), a camera that is
+not the scene's, fog appearing or turning volumetric, a background appearing, the preset and its overrides, and an
+offline render's size and clock. Bistro: a change of lens rebuilt for 884 and 724 ms; now the frame is as any other
+(15 to 17 ms). Each is applied where it lives: the lens by the view (as a camera's move), depth of field and
+exposure by the post passes and the kernel's clamp, fog and a background by the kernel's variant with them, the
+preset by the few parameters taken from it. A GPU test (`live::inplace_tests`) takes twelve such edits in place on
+one view and holds each to a view built from the edited world: no rebuild, the kernel's parameters the same
+whole, the same state after them, the same picture.
+Found by it: the emitter cull's view cone is made from the lens and was made again only when the camera moved or
+turned, so a lens changed in place kept the old one (it follows the lens now); and after an edit to the light (fog
+gone), the radiance cache and the frames' histories keep the old light for hundreds of frames (5 of 255 steps off
+after 264), here as after a rebuild; the test compares with the histories cleared. Still a rebuild: another sky, and the output's size (a view cannot be resized). The first of the
+scene model's steps: the proxy table next.
+
## 2. Temporal fixes
Targets (2026-11-08): bench-temporal, bench-ghosting and their UE MRQ references move to Bistro night (§ 0 step 7); the
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index 23e96db..5004798 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -46,7 +46,7 @@ runtime, and drives the engine directly, the way a UE game drives its actors:
| Engine API | `packages/scene/src/engine.ts` (`Engine`), `renderer/src/script.rs` (`__engine` natives) | Handles (u32) for geometries (typed arrays), textures (asset path, encoded image or RGBA8 pixels), material-function code, materials, objects (group / mesh / model / light / camera) and their transform, visibility, power, light / camera parameters; the environment and render settings. Descriptors are JSON-shaped (`renderer/src/desc.rs`). |
| Scene binding | `packages/scene/src/engine.ts` `SceneBinding` | Keeps the engine in step with a DSL scene. Objects report their own changes (core.ts change tracking: transforms, visibility, power, shadow flag, mesh geometry / material, add / remove), so a sync visits only what changed. Lights, cameras and materials are compared against what was last sent. |
| World | `renderer/src/world.rs` | The engine's objects, resources, environment and settings, and what changed since the last commit: parameter changes (power, light / material parameters, environment, camera) or structural ones. Asset paths must stay inside the asset root (game code is untrusted on nodes). |
-| Live commit | `renderer/src/live/edits.rs` `LiveCore::commit`, `tables.rs` | Parameter changes rewrite GPU table entries in place (materials, lights, object power, emitter CDF, wetness / rain / fog, camera), and so does hiding or showing a volume, a light without a card or a particle system that is not light-sampled by its own `visible`. Anything structural rebuilds the GPU scene from the world, in memory; history survives, validated per pixel. |
+| Live commit | `renderer/src/live/edits.rs` `LiveCore::commit`, `tables.rs` | Parameter changes rewrite GPU table entries in place (materials, lights, object power, emitter CDF, wetness / rain / fog, camera), and so does hiding or showing a volume, a light without a card or a particle system that is not light-sampled by its own `visible`. What is not the scene's is in place too: the scene camera's lens, depth of field and exposure, which camera is the scene's, fog or a background appearing or going (another variant of the kernel), the render preset. Anything structural rebuilds the GPU scene from the world, in memory; history survives, validated per pixel. |
| Scene runtime | `renderer/src/script.rs` `ScriptHost` | QuickJS (rquickjs) with no I/O (no fs, network or timers; what needs the outside is asked of the app, "The host channel"). Loads a bundle (one script) or ES modules (`game.js` + `threert-runtime.js`, the cloud layout). Memory capped at 1 GiB. Time budgets: setup 120 s, event 1 s, frame 50 ms; the interrupt handler aborts overruns. Every entry ends by running the promise jobs it left, inside its budget ("Promises", below). The time the engine spends inside a voxel call (`voxelExplode`, `voxelEdit`, `voxelFrame`) is the engine's, not the script's: the deadline moves by it as measured, up to 250 ms an entry; past that it counts against the script, and a voxel call made after the deadline throws "interrupted" at once. A prelude adds `TextEncoder`, `structuredClone`, `atob` and `console`. |
| Node host | `packages/gameplay/src/node-host.ts` | `globalThis.__threert`: `setup(room, seed)`, `event(type, payload, ts)` (local authority: execute + commit), `commit(writes, seq)` / `setState(state, seq)` (room authority), `state()`, `frame(dt, now)`, `hostMessages(list, ts)` (the app's messages), `sync()` (the engine follows the scene once more: after an entry's promise jobs), and the editor's `outline()`, `inspect(name)`, `edit(name, path, value)`. |
| World handlers | `packages/gameplay/src/world.ts` | `on[type](world, ev)`: an event handled on this node, changing the scene at once. `WorldContext`: `scene`, `camera`, read-only `state`, `object(id)`, `time`, `now`, `random()`, `emit(type, payload)`. |
diff --git a/renderer/src/desc.rs b/renderer/src/desc.rs
index c6805f1..00f4818 100644
--- a/renderer/src/desc.rs
+++ b/renderer/src/desc.rs
@@ -68,7 +68,7 @@ fn ninety() -> f32 {
90.0
}
-#[derive(Deserialize, Debug, Clone)]
+#[derive(Deserialize, Debug, Clone, PartialEq)]
#[serde(tag = "mode", rename_all = "camelCase")]
pub enum Exposure {
Manual { ev100: f32 },
@@ -76,7 +76,26 @@ pub enum Exposure {
Auto { compensation: f32, min_ev100: f32, max_ev100: f32 },
}
-#[derive(Deserialize, Debug, Clone)]
+impl Exposure {
+ /// The EV100 a scene is taken to be shown at before a frame says: the manual value, or auto exposure's brightest.
+ /// The kernel's firefly clamp is relative to it (`NativePreset::firefly_clamp`).
+ pub fn ev_guess(&self) -> f32 {
+ match self {
+ Exposure::Manual { ev100 } => *ev100,
+ Exposure::Auto { max_ev100, .. } => *max_ev100,
+ }
+ }
+
+ /// The exposure a view starts at: manual, 2^-EV100; auto, a first guess (the histogram takes over from frame 1).
+ pub fn start(&self) -> f32 {
+ match self {
+ Exposure::Manual { ev100 } => 2f32.powf(-ev100),
+ Exposure::Auto { compensation, max_ev100, .. } => 2f32.powf(*compensation) / 2f32.powf(*max_ev100),
+ }
+ }
+}
+
+#[derive(Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Dof {
pub focus_distance: f32,
@@ -159,7 +178,7 @@ pub struct Volumetric {
pub distance: f32,
}
-#[derive(Deserialize, Debug, Clone)]
+#[derive(Deserialize, Debug, Clone, PartialEq)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum Sky {
/// `dynamic`: the sun moves while the scene runs (time of day). The live view then bakes the sky at
@@ -194,7 +213,7 @@ pub enum Sky {
Gradient { zenith: Vec3, horizon: Vec3, ground: Vec3, intensity: f32, horizon_exponent: Option<f32>, glow: Option<SkyGlow>, clouds: Option<SkyClouds>, sky_light_intensity: f32 },
}
-#[derive(Deserialize, Debug, Clone)]
+#[derive(Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SkyGlow {
pub color: Vec3,
@@ -208,7 +227,7 @@ pub struct SkyGlow {
pub power: Option<f32>,
}
-#[derive(Deserialize, Debug, Clone)]
+#[derive(Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SkyClouds {
/// 0..1 sky fraction.
@@ -449,6 +468,14 @@ fn one() -> f32 {
1.0
}
+impl NativePreset {
+ /// The kernel's firefly clamp on indirect paths (`Params::misc[0]`): relative to the exposure, so that it is the
+ /// same in every scene.
+ pub fn firefly_clamp(&self, exposure: &Exposure) -> f32 {
+ self.clamp_indirect * 2f32.powf(exposure.ev_guess())
+ }
+}
+
pub fn merge_json(a: &mut serde_json::Value, b: &serde_json::Value) {
match (a, b) {
(serde_json::Value::Object(a), serde_json::Value::Object(b)) => {
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index 78b630b..816b1ed 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -1559,7 +1559,18 @@ pub fn huge(groups: [usize; GROUPS], instanced: bool) -> bool {
/// Features a scene needs; `THREERT_FEATURES` (bit mask) restricts them for profiling.
pub fn features(scene: &Scene, groups: [usize; GROUPS]) -> u32 {
- features_of(&scene.materials, scene.fog.as_ref(), !scene.textures.is_empty(), !scene.shaders.is_empty(), groups, instance_features(scene)) | if scene.aerial[0] > 0.0 { F_AERIAL } else { 0 }
+ let environment = environment_features(scene.fog.as_ref(), scene.background.is_some(), scene.aerial);
+ features_of(&scene.materials, environment, !scene.textures.is_empty(), !scene.shaders.is_empty(), groups, instance_features(scene))
+}
+
+/// Kernel features of the environment, which edits change: fog (F_FOG, with lit scattering F_VOLUME), a background
+/// (F_BACKGROUND), the sky's aerial perspective (F_AERIAL; `aerial`: `Params::aerial`).
+pub fn environment_features(fog: Option<&crate::desc::Fog>, background: bool, aerial: [f32; 4]) -> u32 {
+ let mut f = if background { F_BACKGROUND } else { 0 } | if aerial[0] > 0.0 { F_AERIAL } else { 0 };
+ if let Some(fog) = fog.filter(|fog| fog.density > 0.0) {
+ f |= F_FOG | if fog.volumetric.as_ref().is_some_and(|v| v.scattering > 0.0) { F_VOLUME } else { 0 };
+ }
+ f
}
/// Kernel features of the scene's structure, which parameter edits do not change: F_INST and F_MASKED for the
@@ -1569,29 +1580,22 @@ pub fn instance_features(scene: &Scene) -> u32 {
// (F_GRID also for a volume function that calls `vgrid` on a node without a grid: it reads zeros.)
let grid = !scene.grids.is_empty() || (!scene.media.is_empty() && scene.volume_fns.iter().any(|(_, code, helpers)| code.contains("vgrid(") || helpers.contains("vgrid(")));
let media = if scene.media.is_empty() { 0 } else { F_MEDIA } | if scene.media.iter().any(|m| m.a[2] != 0) { F_HMEDIA } else { 0 } | if grid { F_GRID } else { 0 };
- let particles = if scene.particles.iter().any(|p| !p.translucent) || !scene.gpu_particles.is_empty() { F_PEMIT } else { 0 } | if scene.procs.is_empty() { 0 } else { F_PROC } | if scene.tinted { F_TINT } else { 0 } | if scene.background.is_some() { F_BACKGROUND } else { 0 } | if scene.gpu_vcolors.is_empty() { 0 } else { F_VCOLOR } | if scene.lights.iter().filter(|l| l.pos[3] != 0.0 && l.ext[3] >= 0.5).count() > RIS_EXACT { F_LISTS } else { 0 };
+ let particles = if scene.particles.iter().any(|p| !p.translucent) || !scene.gpu_particles.is_empty() { F_PEMIT } else { 0 } | if scene.procs.is_empty() { 0 } else { F_PROC } | if scene.tinted { F_TINT } else { 0 } | if scene.gpu_vcolors.is_empty() { 0 } else { F_VCOLOR } | if scene.lights.iter().filter(|l| l.pos[3] != 0.0 && l.ext[3] >= 0.5).count() > RIS_EXACT { F_LISTS } else { 0 };
if scene.gpu_instances.is_empty() {
return media | particles;
}
media | particles | F_INST | if scene.meshes.iter().any(|m| m.opaque < m.count) { F_MASKED } else { 0 } | if scene.units.is_some() { F_UNITS } else { 0 }
}
-/// `features` from the parts parameter edits change (materials, fog), and the instanced meshes' (`instance_features`).
-pub fn features_of(ms: &[crate::scene::GpuMaterial], fog: Option<&crate::desc::Fog>, textures: bool, functions: bool, groups: [usize; GROUPS], instances: u32) -> u32 {
+/// `features` from the parts parameter edits change (the materials; `environment`: `environment_features`), and the
+/// scene's structure (`instances`: `instance_features`).
+pub fn features_of(ms: &[crate::scene::GpuMaterial], environment: u32, textures: bool, functions: bool, groups: [usize; GROUPS], instances: u32) -> u32 {
// `instances` carries the structural features (instance_features): instancing is its F_INST bit.
let instanced = instances & F_INST != 0;
- let mut f = instances;
+ let mut f = instances | environment;
if groups[1] + groups[3] + groups[5] + groups[7] > 0 {
f |= F_MASKED;
}
- if let Some(fog) = fog {
- if fog.density > 0.0 {
- f |= F_FOG;
- if fog.volumetric.as_ref().is_some_and(|v| v.scattering > 0.0) {
- f |= F_VOLUME;
- }
- }
- }
if textures {
f |= F_TEX;
}
@@ -3745,9 +3749,9 @@ mod tests {
fn structural_features_are_not_instancing() {
const M: usize = 1 << 23;
let groups = [M + 5, 3, 0, 0, 0, 0, 0, 0];
- assert_eq!(features_of(&[], None, false, false, groups, F_PEMIT) & F_HUGE, 0);
- assert_eq!(features_of(&[], None, false, false, groups, F_MEDIA) & F_HUGE, 0);
- assert_ne!(features_of(&[], None, false, false, groups, F_INST) & F_HUGE, 0);
+ assert_eq!(features_of(&[], 0, false, false, groups, F_PEMIT) & F_HUGE, 0);
+ assert_eq!(features_of(&[], 0, false, false, groups, F_MEDIA) & F_HUGE, 0);
+ assert_ne!(features_of(&[], 0, false, false, groups, F_INST) & F_HUGE, 0);
}
#[test]
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index 80a9322..d4f8aa3 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -699,11 +699,6 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
}
None => (0.0, 1.0),
};
- // Firefly clamp on indirect paths, expressed relative to the exposure so it is scene independent.
- let ev_guess = match &cam.exposure {
- desc::Exposure::Manual { ev100 } => *ev100,
- desc::Exposure::Auto { max_ev100, .. } => *max_ev100,
- };
let params = gpu::Params {
cam_pos: [cam.position.x, cam.position.y, cam.position.z, cam.tan_half_fov],
cam_fwd: [cam.forward.x, cam.forward.y, cam.forward.z, aspect],
@@ -712,7 +707,7 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
size: [sc.width, sc.height, 0, rng_seed()],
counts: [sc.lights.len() as u32, if total > 0.0 { emitter_tris.len() as u32 } else { 0 }, preset.native.max_bounces, preset.native.russian_roulette_depth],
env: [if has_env { 1.0 } else { 0.0 }, env.width as f32, env.height as f32, -1.0],
- misc: [preset.native.clamp_indirect * 2f32.powf(ev_guess), total, preset.native.energy_compensation, 0.0],
+ misc: [preset.native.firefly_clamp(&cam.exposure), total, preset.native.energy_compensation, 0.0],
sky_color: [sky_color.x, sky_color.y, sky_color.z, 0.0],
counts2: [n_dir, env_nee as u32, 0, first_shadowed],
time: [sc.time, sc.wetness, sc.rain, sc.media.len() as f32],
diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs
index 917345c..626c6ee 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -360,8 +360,7 @@ impl LiveCore {
if self.sc.tables.add_materials(world, &changes.new_materials) {
self.upload_materials();
// (A clear coat, an unlit material: the kernel variant with it, compiled once.)
- let (e, (tex, func, groups)) = (&self.sc.tables, self.sc.fixed_features);
- self.sc.up.kernel.features = gpu::features_of(&e.materials, e.fog.as_ref(), tex, func, groups, self.sc.instance_features) | if e.aerial[0] > 0.0 { gpu::F_AERIAL } else { 0 };
+ self.sc.up.kernel.features = self.sc.tables.features(self.sc.fixed_features, self.sc.instance_features);
} else {
self.fallback = Some("a new material that cannot be added in place (it emits, is glass or a cutout)".into());
self.fallbacks += 1;
@@ -575,9 +574,8 @@ impl LiveCore {
[b.fog, b.fog_color, b.vol, b.vol2] = crate::fog_params(e.fog.as_ref());
}
if d.materials || d.environment {
- // e.g. fog appearing needs the fog kernel variant (compiled once, then cached)
- let (tex, func, groups) = self.sc.fixed_features;
- self.sc.up.kernel.features = gpu::features_of(&e.materials, e.fog.as_ref(), tex, func, groups, self.sc.instance_features) | if e.aerial[0] > 0.0 { gpu::F_AERIAL } else { 0 };
+ // (Fog or a background appearing, a clear coat: the kernel's variant with it, compiled once, then cached.)
+ self.sc.up.kernel.features = e.features(self.sc.fixed_features, self.sc.instance_features);
}
if let Some(c) = e.camera.take() {
self.sc.scene_camera = Camera { pos: c.position, fwd: c.forward, up: c.up, right: c.right, tan_half_fov: c.tan_half_fov };
@@ -595,9 +593,16 @@ impl LiveCore {
self.sky_cover = self.sc.tables.cloud_cover;
self.move_sun(world);
}
- if changes.exposure {
+ if changes.settings {
+ self.apply_settings(world)?;
+ self.lit_changed = self.frame.max(1);
+ }
+ if changes.exposure || changes.settings {
self.apply_exposure(world);
}
+ if changes.dof {
+ self.sc.dof = world.scene_camera().and_then(|c| c.dof.clone());
+ }
Ok(false)
}
@@ -656,18 +661,26 @@ impl LiveCore {
self.lit_changed = self.frame.max(1);
}
- /// The camera's manual exposure changed value (an exposure that follows the time of day), in place: the post pass's
- /// exposure and the kernel's firefly clamp, which is relative to it.
+ /// The scene camera's exposure (its mode, its values) as a build takes it: what the frame is shown at, the auto
+ /// exposure's settings, and the kernel's firefly clamp, which is relative to it.
pub(super) fn apply_exposure(&mut self, world: &World) {
- let Some(cid) = world.settings.camera else { return };
- let Some(crate::world::Kind::Camera(c)) = world.objects.get(&cid).map(|o| &o.kind) else { return };
- let crate::desc::Exposure::Manual { ev100 } = c.exposure else { return };
- let e = 2f32.powf(-ev100);
- if self.sc.exposure > 0.0 {
- self.sc.base.misc[0] *= self.sc.exposure / e;
- }
- self.sc.exposure = e;
- self.sc.exposure_settings.ae2 = [e, 0.0, 0.0, 0.0];
+ let Some(c) = world.scene_camera() else { return };
+ self.sc.base.misc[0] = self.sc.preset.native.firefly_clamp(&c.exposure);
+ self.sc.exposure = c.exposure.start();
+ self.sc.exposure_settings = ExposureSettings::new(&c.exposure, &self.sc.preset.post);
+ }
+
+ /// The preset, its overrides or the scene's name changed: the kernel parameters a build takes from the preset
+ /// (bounces, Russian roulette, energy compensation) and the post passes'. (What the preset says of the exposure:
+ /// `apply_exposure`, after it.)
+ pub(super) fn apply_settings(&mut self, world: &World) -> Result<()> {
+ let preset = scene::preset_of(world, &self.presets, None)?;
+ let b = &mut self.sc.base;
+ (b.counts[2], b.counts[3], b.misc[2]) = (preset.native.max_bounces, preset.native.russian_roulette_depth, preset.native.energy_compensation);
+ self.apply_post(&preset.post);
+ self.sc.preset = preset;
+ self.scene_name = world.settings.name.clone();
+ Ok(())
}
/// Moves movable instances: their kernel records (the old transform kept as the previous frame's, for motion
diff --git a/renderer/src/live/frame.rs b/renderer/src/live/frame.rs
index 9a6f98f..822a2b2 100644
--- a/renderer/src/live/frame.rs
+++ b/renderer/src/live/frame.rs
@@ -214,8 +214,9 @@ impl LiveCore {
}
/// Light LOD: the emitter CDF weighted by distance to the camera (`emitter_lod`) and the emitter cull with its view
- /// cone (`EmitterCull`), rebuilt when the camera is 15 m from where it was last built or has turned LIGHT_LOD_TURN
- /// from that direction (the kernel's emitter pdfs read the same reference from the parameters).
+ /// cone (`EmitterCull`), rebuilt when the camera is 15 m from where it was last built, has turned LIGHT_LOD_TURN
+ /// from that direction, or sees another cone (its lens, the view's shape): the kernel's emitter pdfs read the same
+ /// reference from the parameters.
pub(super) fn update_light_lod(&mut self) {
let d0 = LIGHT_LOD_D0;
let (w, h) = (self.w, self.h);
@@ -227,7 +228,10 @@ impl LiveCore {
let r = glam::Vec3::new(b.light_lod[0], b.light_lod[1], b.light_lod[2]);
let dir = glam::Vec3::new(b.lod_view[0], b.lod_view[1], b.lod_view[2]);
let turned = b.emit_power[2] > 0.0 && dir.dot(self.cam.fwd) < LIGHT_LOD_TURN.to_radians().cos();
- if b.light_lod[3] > 0.0 && r.distance(self.cam.pos) < 15.0 && !turned {
+ // The frustum's half-diagonal: tan = tan(fov / 2) x sqrt(1 + aspect^2).
+ let half = (self.cam.tan_half_fov * (1.0 + (w as f32 / h as f32).powi(2)).sqrt()).atan() + EMITTER_CULL_MARGIN.to_radians();
+ let cone = half.min(std::f32::consts::PI).cos();
+ if b.light_lod[3] > 0.0 && r.distance(self.cam.pos) < 15.0 && !turned && b.lod_view[3] == cone {
return;
}
b.light_lod = [self.cam.pos.x, self.cam.pos.y, self.cam.pos.z, d0];
@@ -235,9 +239,7 @@ impl LiveCore {
let cull = if self.sc.up.kernel.approx & gpu::A_FAR_EMITTERS != 0 { EMITTER_CULL } else { 0.0 };
b.emit_power[1] = cull;
b.emit_power[2] = cull * EMITTER_CULL_VIEW;
- // The frustum's half-diagonal: tan = tan(fov / 2) x sqrt(1 + aspect^2).
- let half = (self.cam.tan_half_fov * (1.0 + (w as f32 / h as f32).powi(2)).sqrt()).atan() + EMITTER_CULL_MARGIN.to_radians();
- b.lod_view = [self.cam.fwd.x, self.cam.fwd.y, self.cam.fwd.z, half.min(std::f32::consts::PI).cos()];
+ b.lod_view = [self.cam.fwd.x, self.cam.fwd.y, self.cam.fwd.z, cone];
// Power edits held back for the emitter worker land first (its job in flight was built for the old reference:
// dropped), so the CDF built here has the powers the objects hold and the reference the kernel reads.
self.land_powers_now();
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
new file mode 100644
index 0000000..4ca04f8
--- /dev/null
+++ b/renderer/src/live/inplace_tests.rs
@@ -0,0 +1,164 @@
+//! An edit the live view takes in place leaves it as a build of the edited world does: no rebuild, the same
+//! parameters and kernel variant, the same picture. (GPU tests: skipped without a GPU.)
+
+use super::*;
+use crate::world::{Geometry, Kind, Settings};
+use glam::Vec3;
+
+/// A wall, a panel before it and an emissive quad that lights both, under a dim sky; camera 4.
+fn world() -> World {
+ let mut w = World::default();
+ let mat = |color: f32, emissive: f32| serde_json::from_value(serde_json::json!({ "name": "m", "color": [color, color * 0.5, color], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [1, 1, 1], "emissiveIntensity": emissive, "doubleSided": true })).unwrap();
+ w.set_material(1, mat(0.8, 0.0));
+ w.set_material(5, mat(0.0, 40.0));
+ let quad = |s: f32| Geometry { positions: vec![-s, -s, 0.0, s, -s, 0.0, s, s, 0.0, -s, s, 0.0], normals: [0.0, 0.0, 1.0].repeat(4), uvs: vec![0.0; 8], indices: vec![0, 1, 2, 0, 2, 3], groups: vec![], colors: vec![] };
+ w.set_geometry(2, quad(1.0)).unwrap();
+ w.set_geometry(3, quad(0.25)).unwrap();
+ let mesh = |geometry, material| Kind::Mesh { geometry, material, own_blas: false, materials: vec![] };
+ w.set_object(10, "wall".into(), None, mesh(2, 1), true, false).unwrap();
+ w.set_object(11, "panel".into(), None, mesh(3, 1), true, false).unwrap();
+ w.set_transform(11, Vec3::new(-0.4, 0.0, 0.5), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ w.set_object(12, "lamp".into(), None, mesh(3, 5), true, false).unwrap();
+ w.set_transform(12, Vec3::new(0.6, 0.3, 1.5), glam::Quat::from_rotation_y(2.6), Vec3::ONE).unwrap();
+ w.set_object(4, "camera".into(), None, Kind::Camera(camera(50.0, None, manual(0.0))), true, false).unwrap();
+ w.set_transform(4, Vec3::new(0.0, 0.0, 5.0), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ w.set_settings(Settings { camera: Some(4), ..Default::default() });
+ w
+}
+
+fn manual(ev: f32) -> serde_json::Value {
+ serde_json::json!({ "mode": "manual", "ev100": ev })
+}
+
+fn camera(fov: f32, dof: Option<f32>, exposure: serde_json::Value) -> crate::desc::Camera {
+ let mut c = serde_json::json!({ "fov": fov, "near": 0.1, "far": 100, "exposure": exposure });
+ if let Some(focus) = dof {
+ c["dof"] = serde_json::json!({ "focusDistance": focus, "fStop": 1.4, "sensorWidth": 36 });
+ }
+ serde_json::from_value(c).unwrap()
+}
+
+/// A view's state: the kernel's parameters whole (as words; not the camera's four vectors, which the frame writes from
+/// the view), and what the passes after it take. (After a frame: the frame writes the light LOD's reference.)
+fn state(c: &LiveCore) -> (Vec<u32>, String) {
+ let s = &c.sc;
+ let rest = format!(
+ "features {:#x} | exposure {} {:?} {:?} {:?} {:?} | lens {} {:?} view {:?} {:?} {} | post {} {:?} {} {:?} {:?} | {}",
+ s.up.kernel.features, s.exposure, s.exposure_settings.ae, s.exposure_settings.ae2, s.exposure_settings.speed, s.exposure_settings.lx,
+ s.tan_half_fov, s.dof, s.scene_camera.pos, s.scene_camera.fwd, s.scene_camera.tan_half_fov,
+ c.post_key, c.bloom, c.vignette, c.post, c.blur, c.scene_name
+ );
+ let camera = (std::mem::offset_of!(gpu::Params, cam_up) + 16) / 4;
+ assert_eq!((std::mem::offset_of!(gpu::Params, cam_pos), camera), (0, 16), "the camera's vectors are the parameters' first");
+ (bytemuck::cast_slice::<_, u32>(bytemuck::bytes_of(&s.base))[camera..].to_vec(), rest)
+}
+
+/// Holds a view that took an edit in place to one built from the edited world.
+fn same_state(what: &str, live: &LiveCore, fresh: &LiveCore) {
+ let ((a, ra), (b, rb)) = (state(live), state(fresh));
+ let words: Vec<usize> = (0..a.len()).filter(|&k| a[k] != b[k]).map(|k| k + 16).collect();
+ assert!(words.is_empty(), "{what}: the kernel's parameters differ from a build's at words {words:?}");
+ assert_eq!(ra, rb, "{what}: the view's state against a build's");
+}
+
+/// The output (BGRA8) after `frames` frames in lockstep.
+fn picture(core: &mut LiveCore, frames: u32) -> Vec<u8> {
+ core.fixed_dt = Some(1.0 / 60.0);
+ for _ in 0..frames {
+ core.render(1, |_, _| {});
+ }
+ let (d, out) = (&core.g.device, &core.targets.out);
+ let to = d.create_buffer(&wgpu::BufferDescriptor { label: None, size: out.size(), usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
+ let mut e = d.create_command_encoder(&Default::default());
+ e.copy_buffer_to_buffer(out, 0, &to, 0, out.size());
+ core.g.queue.submit([e.finish()]);
+ to.slice(..).map_async(wgpu::MapMode::Read, |_| {});
+ d.poll(wgpu::PollType::wait_indefinitely()).unwrap();
+ let bytes = to.slice(..).get_mapped_range().unwrap().to_vec();
+ bytes
+}
+
+/// The view without its histories (the radiance cache emptied, the frames' histories reset), as a new view is.
+fn forget(core: &mut LiveCore) {
+ if let Some(c) = &core.cache {
+ let mut e = core.g.device.create_command_encoder(&Default::default());
+ c.bufs.clear(&mut e);
+ core.g.queue.submit([e.finish()]);
+ }
+ core.reset = true;
+}
+
+/// Mean absolute difference of two pictures, in 8-bit steps.
+fn apart(a: &[u8], b: &[u8]) -> f64 {
+ assert_eq!(a.len(), b.len());
+ a.iter().zip(b).map(|(x, y)| x.abs_diff(*y) as f64).sum::<f64>() / a.len() as f64
+}
+
+/// Each edit, on one view that takes them one after another, against a view built from the world as it is then.
+#[test]
+fn edits_in_place_leave_what_a_build_does() {
+ let presets = crate::default_presets_dir();
+ let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new("."), &presets, 96, 54));
+ let mut w = world();
+ let mut live = match open(&w) {
+ Ok(c) => c,
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ w.take_changes();
+ let mut before = picture(&mut live, 24);
+ let fog = |density: f32, volumetric: bool| -> crate::desc::Fog {
+ let mut f = serde_json::json!({ "density": density, "heightFalloff": 0.05, "height": 0.0, "color": [0.4, 0.5, 0.7], "intensity": 1.0 });
+ if volumetric {
+ f["volumetric"] = serde_json::json!({ "scattering": 0.9 });
+ }
+ serde_json::from_value(f).unwrap()
+ };
+ type Edit = (&'static str, bool, Box<dyn Fn(&mut World)>);
+ let edits: Vec<Edit> = vec![
+ ("a longer lens", true, Box::new(|w| w.set_camera_desc(4, camera(25.0, None, manual(0.0))).unwrap())),
+ ("a depth of field", false, Box::new(|w| w.set_camera_desc(4, camera(25.0, Some(4.5), manual(0.0))).unwrap())),
+ ("a manual exposure", true, Box::new(|w| w.set_camera_desc(4, camera(25.0, Some(4.5), manual(1.5))).unwrap())),
+ ("auto exposure", false, Box::new(|w| w.set_camera_desc(4, camera(25.0, Some(4.5), serde_json::json!({ "mode": "auto", "compensation": 0.5, "minEv100": -3, "maxEv100": 4 }))).unwrap())),
+ ("manual again, no depth of field", false, Box::new(|w| w.set_camera_desc(4, camera(25.0, None, manual(0.0))).unwrap())),
+ ("fog", true, Box::new(move |w| w.set_environment(crate::desc::Environment { fog: Some(fog(0.25, false)), ..w.environment.clone() }))),
+ ("volumetric fog", false, Box::new(move |w| w.set_environment(crate::desc::Environment { fog: Some(fog(0.25, true)), ..w.environment.clone() }))),
+ ("no fog", true, Box::new(|w| w.set_environment(crate::desc::Environment { fog: None, ..w.environment.clone() }))),
+ ("a background", true, Box::new(|w| w.set_environment(crate::desc::Environment { background: Some([0.2, 0.6, 0.1]), ..w.environment.clone() }))),
+ ("no background", true, Box::new(|w| w.set_environment(crate::desc::Environment { background: None, ..w.environment.clone() }))),
+ ("the preset's overrides", false, Box::new(|w| w.set_settings(Settings { overrides: Some(serde_json::json!({ "native": { "maxBounces": 1, "energyCompensation": 0.0, "clampIndirect": 3.0 }, "post": { "vignette": 0.9 } })), name: "renamed".into(), ..w.settings.clone() }))),
+ ("another preset", false, Box::new(|w| w.set_settings(Settings { preset: "preview".into(), overrides: None, ..w.settings.clone() }))),
+ ];
+ for (what, seen, edit) in &edits {
+ edit(&mut w);
+ assert!(!live.commit(&mut w).unwrap(), "{what}: in place");
+ let mut fresh = open(&w).unwrap();
+ // (With no history, as the new view has none: the radiance cache and the frames' histories hold the light as
+ // it was for a while, here as after a rebuild; fog gone was still 5 steps off after 264 frames.)
+ let now = picture(&mut live, 2);
+ forget(&mut live);
+ let (a, b) = (picture(&mut live, 24), picture(&mut fresh, 24));
+ assert!(apart(&a, &b) < 2.0, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b));
+ same_state(what, &live, &fresh);
+ if *seen {
+ assert!(apart(&now, &before) > 1.0, "{what}: the picture did not change at once ({:.2} steps)", apart(&now, &before));
+ }
+ before = a;
+ }
+ // Another camera becomes the scene's: its place, its lens and its exposure.
+ w.set_object(6, "second".into(), None, Kind::Camera(camera(70.0, None, manual(-1.0))), true, false).unwrap();
+ w.set_transform(6, Vec3::new(1.0, 0.5, 4.0), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ live.commit(&mut w).unwrap();
+ w.set_settings(Settings { camera: Some(6), ..w.settings.clone() });
+ assert!(!live.commit(&mut w).unwrap(), "another camera: in place");
+ let mut fresh = open(&w).unwrap();
+ (picture(&mut live, 1), picture(&mut fresh, 1));
+ same_state("another camera", &live, &fresh);
+ assert!(live.cam == fresh.cam, "the view is at the scene's camera");
+ // A view moved away from the scene's camera stays there through a depth of field or an exposure; a lens takes it back.
+ let away = Camera { pos: live.cam.pos + Vec3::new(0.5, 0.0, 0.0), ..live.cam };
+ live.cam = away;
+ w.set_camera_desc(6, camera(70.0, Some(3.0), manual(2.0))).unwrap();
+ assert!(!live.commit(&mut w).unwrap() && live.cam == away && live.sc.dof.is_some(), "a depth of field and an exposure: the view stays");
+ w.set_camera_desc(6, camera(40.0, Some(3.0), manual(2.0))).unwrap();
+ assert!(!live.commit(&mut w).unwrap() && live.cam == live.sc.scene_camera && live.cam != away, "a lens: the view takes the scene's camera");
+}
diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rs
index 2339041..becee5d 100644
--- a/renderer/src/live/load.rs
+++ b/renderer/src/live/load.rs
@@ -25,7 +25,7 @@ pub(super) struct LoadedScene {
/// The scene has instanced meshes or procedural geometry (the raster experiment draws only flattened triangles:
/// primary visibility is traced).
pub(super) instanced: bool,
- /// Kernel features of the instanced meshes (gpu::instance_features), which edits cannot change.
+ /// Kernel features of the scene's structure (gpu::instance_features), which edits cannot change.
pub(super) instance_features: u32,
pub(super) name: String,
pub(super) triangles: usize,
@@ -35,6 +35,8 @@ pub(super) struct LoadedScene {
pub(super) bgs: Vec<wgpu::BindGroup>,
pub(super) exposure: f32,
pub(super) exposure_settings: ExposureSettings,
+ /// The render preset the kernel's parameters and the post passes' settings were taken from.
+ pub(super) preset: crate::desc::Preset,
pub(super) tan_half_fov: f32,
pub(super) scene_camera: Camera,
/// The camera's depth of field (UE: off unless it sets a focus distance).
@@ -245,12 +247,10 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
base.cam_fwd[3] = w as f32 / h as f32;
let bgs = targets.bind_groups(&g.device, passes, &up.accum);
let exposure_settings = ExposureSettings::new(&sc.camera.exposure, &sc.preset.post);
- // Manual: 2^-EV100. Auto: a first guess (the GPU histogram takes the exposure over from frame 1; the kernel's
- // firefly clamp, `Params::misc[0]`, keeps `prepare`'s guess).
- let exposure = match &sc.camera.exposure {
- crate::desc::Exposure::Manual { ev100 } => 2f32.powf(-ev100),
- crate::desc::Exposure::Auto { compensation, max_ev100, .. } => 2f32.powf(*compensation) / 2f32.powf(*max_ev100),
- };
+ // (Auto: a first guess; the GPU histogram takes the exposure over from frame 1, and the kernel's firefly clamp,
+ // `Params::misc[0]`, keeps `prepare`'s guess.)
+ let exposure = sc.camera.exposure.start();
+ let preset = sc.preset.clone();
let c = &sc.camera;
let scene_camera = Camera { pos: c.position, fwd: c.forward, up: c.up, right: c.right, tan_half_fov: c.tan_half_fov };
let (tris, tri_nodes, tri_instances) = (std::mem::take(&mut sc.tris), std::mem::take(&mut sc.tri_nodes), std::mem::take(&mut sc.tri_instances));
@@ -303,5 +303,5 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
inst_at_load: instances.len(),
added: Default::default(),
};
- Ok((LoadedScene { timings, triangles, tris, tri_nodes, tri_instances, pool_tris, meshes, instances, gpu_instances, procs, proc_of, proc_first, instanced, instance_features, name: sc.name.clone(), up, base, bgs, exposure, exposure_settings, tan_half_fov: c.tan_half_fov, scene_camera, dof: c.dof.clone(), tables, fixed_features, dynamic, edit, sky: None, emit, sky_inputs, mat_runs, tri_order }, sc.preset.post))
+ Ok((LoadedScene { timings, triangles, tris, tri_nodes, tri_instances, pool_tris, meshes, instances, gpu_instances, procs, proc_of, proc_first, instanced, instance_features, name: sc.name.clone(), up, base, bgs, exposure, exposure_settings, preset, tan_half_fov: c.tan_half_fov, scene_camera, dof: c.dof.clone(), tables, fixed_features, dynamic, edit, sky: None, emit, sky_inputs, mat_runs, tri_order }, sc.preset.post))
}
diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rs
index f0d40f5..11abe63 100644
--- a/renderer/src/live/mod.rs
+++ b/renderer/src/live/mod.rs
@@ -1058,6 +1058,9 @@ mod timer_tests {
}
}
+#[cfg(test)]
+mod inplace_tests;
+
#[cfg(test)]
mod instanced_tests {
use super::*;
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index df696ee..e02e2c2 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -944,8 +944,8 @@ pub const MAX_MEDIA: usize = 32;
/// (pathtrace.wgsl `medium_span`).
pub const MEDIUM_HIDDEN: u32 = 2;
-pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&serde_json::Value>) -> Result<Scene> {
- let t0 = web_time::Instant::now();
+/// A world's render preset: the preset its settings name, the settings' overrides over it, then `overrides`.
+pub fn preset_of(w: &World, presets_dir: &Path, overrides: Option<&serde_json::Value>) -> Result<desc::Preset> {
let st = &w.settings;
let mut preset_json: serde_json::Value = serde_json::from_slice(&crate::files::preset(presets_dir, &st.preset).with_context(|| format!("preset {}", st.preset))?)?;
if let Some(o) = &st.overrides {
@@ -954,7 +954,13 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
if let Some(o) = overrides {
desc::merge_json(&mut preset_json, o);
}
- let preset: desc::Preset = serde_json::from_value(preset_json)?;
+ Ok(serde_json::from_value(preset_json)?)
+}
+
+pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&serde_json::Value>) -> Result<Scene> {
+ let t0 = web_time::Instant::now();
+ let st = &w.settings;
+ let preset = preset_of(w, presets_dir, overrides)?;
let order = w.ordered();
let mut worlds: HashMap<u32, Mat4> = HashMap::new();
for id in &order {
diff --git a/renderer/src/tables.rs b/renderer/src/tables.rs
index abf62aa..989247e 100644
--- a/renderer/src/tables.rs
+++ b/renderer/src/tables.rs
@@ -110,6 +110,14 @@ impl Tables {
}
/// Applies parameter changes; Err / Ok(None) means the scene must be rebuilt instead.
+ /// The kernel features the scene needs as these tables are: what the materials and the environment ask for (edits
+ /// change them), with the scene's structural ones (`fixed`: textures, material functions, the traversal groups;
+ /// `structure`: `gpu::instance_features`).
+ pub fn features(&self, (textures, functions, groups): (bool, bool, [usize; crate::GROUPS]), structure: u32) -> u32 {
+ let environment = crate::gpu::environment_features(self.fog.as_ref(), self.background.is_some(), self.aerial);
+ crate::gpu::features_of(&self.materials, environment, textures, functions, groups, structure)
+ }
+
pub fn apply(&mut self, w: &World, c: &Changes, now: f32) -> Result<Option<Dirty>> {
if c.structural || !c.poses.is_empty() || !c.moved.is_empty() {
return Ok(None);
diff --git a/renderer/src/world.rs b/renderer/src/world.rs
index ad2a588..e7180ce 100644
--- a/renderer/src/world.rs
+++ b/renderer/src/world.rs
@@ -290,8 +290,13 @@ pub struct Changes {
pub camera: bool,
/// The atmosphere's sun moved (time of day): the live view rewrites its light and re-bakes the sky in place.
pub sun: bool,
- /// Only the camera's manual exposure value changed: applied in place.
+ /// The scene camera's exposure changed (its mode or its values): applied in place (live/edits.rs `apply_exposure`).
pub exposure: bool,
+ /// The scene camera's depth of field changed: the post pass's, in place. (Not `camera`: the view stays where it is.)
+ pub dof: bool,
+ /// The preset, its overrides or the scene's name changed: what a build takes from them is taken again in place
+ /// (live/edits.rs `apply_settings`).
+ pub settings: bool,
/// Models whose animation pose changed.
pub poses: HashSet<u32>,
/// Movable objects that moved: everything under them is re-transformed in place.
@@ -325,7 +330,7 @@ pub struct Changes {
impl Changes {
pub fn any(&self) -> bool {
- self.structural || !self.shown.is_empty() || !self.new_materials.is_empty() || !self.materials.is_empty() || !self.lights.is_empty() || !self.powers.is_empty() || !self.customs.is_empty() || self.environment || self.camera || self.sun || self.exposure || !self.poses.is_empty() || !self.moved.is_empty() || !self.instanced.is_empty() || self.edits()
+ self.structural || !self.shown.is_empty() || !self.new_materials.is_empty() || !self.materials.is_empty() || !self.lights.is_empty() || !self.powers.is_empty() || !self.customs.is_empty() || self.environment || self.camera || self.sun || self.exposure || self.dof || self.settings || !self.poses.is_empty() || !self.moved.is_empty() || !self.instanced.is_empty() || self.edits()
}
/// Geometry edits are pending (`geometries`, `added`, `removed`).
pub fn edits(&self) -> bool {
@@ -890,21 +895,22 @@ impl World {
}
pub fn set_camera_desc(&mut self, id: u32, c: desc::Camera) -> Result<()> {
+ let active = self.settings.camera == Some(id);
let o = self.objects.get_mut(&id).ok_or_else(|| anyhow!("unknown object {id}"))?;
- // Only the manual exposure's value changed (an exposure that follows the time of day): in place. Anything else
- // (exposure mode, DOF, the lens) shapes the kernel parameters: rebuild (rare).
- let ev_only = match (&o.kind, &c.exposure) {
- (Kind::Camera(old), desc::Exposure::Manual { .. }) => {
- matches!(old.exposure, desc::Exposure::Manual { .. }) && old.fov == c.fov && old.near == c.near && old.far == c.far && format!("{:?}", old.dof) == format!("{:?}", c.dof)
+ // In place, when it is the scene's camera: a field of view is the view's (as a camera's move: the view takes
+ // it), a depth of field and an exposure are the post passes' (and the kernel's clamp). Nothing is built from a
+ // camera that is not the scene's, nor from near and far; a camera made of another kind of object is a new object.
+ let (fov, dof, exposure) = match &o.kind {
+ Kind::Camera(old) => (old.fov != c.fov, old.dof != c.dof, old.exposure != c.exposure),
+ _ => {
+ self.changes.structural = true;
+ (false, false, false)
}
- _ => false,
};
o.kind = Kind::Camera(c);
- if ev_only {
- self.changes.exposure = true;
- } else {
- self.changes.structural = true;
- }
+ self.changes.camera |= active && fov;
+ self.changes.dof |= active && dof;
+ self.changes.exposure |= active && exposure;
Ok(())
}
@@ -965,10 +971,9 @@ impl World {
}
pub fn set_environment(&mut self, e: desc::Environment) {
- let sky_same = format!("{:?}", self.environment.sky) == format!("{:?}", e.sky);
- let fog_shape = |f: &Option<desc::Fog>| f.as_ref().map(|f| (f.volumetric.is_some(), f.density > 0.0));
- // (A background appearing or going is a kernel feature, F_BACKGROUND: a rebuild; a new colour is not.)
- if !sky_same || fog_shape(&self.environment.fog) != fog_shape(&e.fog) || self.environment.background.is_some() != e.background.is_some() {
+ // Fog appearing, turning volumetric or going, and a background appearing or going, are kernel features: another
+ // variant of the kernel, not another scene. A new sky is baked with the scene (a rebuild).
+ if self.environment.sky != e.sky {
self.changes.structural = true;
} else {
self.changes.environment = true;
@@ -978,11 +983,15 @@ impl World {
pub fn set_settings(&mut self, s: Settings) {
let old = &self.settings;
- if old.preset != s.preset || old.overrides != s.overrides || old.width != s.width || old.height != s.height || old.time != s.time || old.name != s.name {
- self.changes.structural = true;
+ // (The size and the clock are an offline render's: a live view has its host's size and its own clock.)
+ if old.preset != s.preset || old.overrides != s.overrides || old.name != s.name {
+ self.changes.settings = true;
}
if old.camera != s.camera {
+ // Another camera: its place and lens, its depth of field and its exposure.
self.changes.camera = true;
+ self.changes.dof = true;
+ self.changes.exposure = true;
}
self.settings = s;
}
@@ -993,6 +1002,14 @@ impl World {
// ------------------------------------------------------------------------------------------ queries
+ /// The scene's camera (`Settings::camera`), when it names one.
+ pub fn scene_camera(&self) -> Option<&desc::Camera> {
+ match self.settings.camera.and_then(|id| self.objects.get(&id)).map(|o| &o.kind) {
+ Some(Kind::Camera(c)) => Some(c),
+ _ => None,
+ }
+ }
+
/// Object `id`'s world matrix: its transform and its parents'. One that is not finite (a NaN or infinite position,
/// rotation or scale anywhere up the chain, as a script may set) places the object at a point, scale 1e-6 at its
/// translation where that is finite, as `scene::instance_world` places a hidden instance: what it draws is not
@@ -1507,24 +1524,67 @@ mod tests {
assert!(w.instanced.is_empty());
}
- /// three.js's background (F_BACKGROUND, a kernel feature): appearing or going rebuilds (the kernel is patched or
- /// not); a new colour is a parameter edit.
+ /// three.js's background (F_BACKGROUND) and the fog's shape (F_FOG, F_VOLUME) are kernel features: appearing or
+ /// going is a parameter edit, as a new colour is (the live view takes the kernel's other variant). A new sky rebuilds.
#[test]
- fn background_presence_is_structural() {
+ fn a_background_and_fog_come_and_go_in_place() {
let mut w = World::default();
w.take_changes();
let base = w.environment.clone();
let env = |b: Option<[f32; 3]>| desc::Environment { background: b, ..base.clone() };
- let e = env(Some([1.0, 0.0, 0.0]));
- w.set_environment(e);
- assert!(w.take_changes().structural, "a background appears");
- let e = env(Some([0.0, 1.0, 0.0]));
- w.set_environment(e);
+ for (b, what) in [(Some([1.0, 0.0, 0.0]), "a background appears"), (Some([0.0, 1.0, 0.0]), "a new colour"), (None, "the background goes")] {
+ w.set_environment(env(b));
+ let c = w.take_changes();
+ assert!(!c.structural && c.environment, "{what}");
+ }
+ let fog: desc::Fog = serde_json::from_value(serde_json::json!({ "density": 0.02, "heightFalloff": 0.2, "height": 0.0, "color": [1, 1, 1] })).unwrap();
+ w.set_environment(desc::Environment { fog: Some(fog), ..base.clone() });
+ let c = w.take_changes();
+ assert!(!c.structural && c.environment, "fog appears");
+ let sky: desc::Sky = serde_json::from_value(serde_json::json!({ "type": "color", "color": [0, 0, 1], "intensity": 1, "skyLightIntensity": 1 })).unwrap();
+ w.set_environment(desc::Environment { sky, ..base.clone() });
+ assert!(w.take_changes().structural, "another sky");
+ }
+
+ /// The scene camera's lens and exposure, and the preset: in place. Another camera's lens: nothing to do.
+ #[test]
+ fn a_lens_an_exposure_and_a_preset_change_in_place() {
+ let mut w = World::default();
+ let cam = |fov: f32, exposure: serde_json::Value| -> desc::Camera { serde_json::from_value(serde_json::json!({ "fov": fov, "near": 0.1, "far": 100, "exposure": exposure })).unwrap() };
+ let manual = |ev: f32| serde_json::json!({ "mode": "manual", "ev100": ev });
+ w.set_object(1, "camera".into(), None, Kind::Camera(cam(50.0, manual(0.0))), true, false).unwrap();
+ w.set_object(2, "other".into(), None, Kind::Camera(cam(50.0, manual(0.0))), true, false).unwrap();
+ w.set_settings(Settings { camera: Some(1), ..Default::default() });
+ w.take_changes();
+ w.set_camera_desc(1, cam(30.0, manual(0.0))).unwrap();
+ let c = w.take_changes();
+ assert!(!c.structural && c.camera && !c.exposure && !c.dof, "a lens: the view takes it");
+ let mut with_dof = cam(30.0, manual(0.0));
+ with_dof.dof = Some(serde_json::from_value(serde_json::json!({ "focusDistance": 3, "fStop": 2, "sensorWidth": 36 })).unwrap());
+ w.set_camera_desc(1, with_dof).unwrap();
+ let c = w.take_changes();
+ assert!(!c.structural && !c.camera && c.dof, "a depth of field: the view stays");
+ w.set_camera_desc(1, cam(30.0, manual(0.0))).unwrap();
+ w.take_changes();
+ w.set_camera_desc(1, cam(30.0, manual(2.0))).unwrap();
+ let c = w.take_changes();
+ assert!(!c.structural && !c.camera && c.exposure, "an exposure value");
+ w.set_camera_desc(1, cam(30.0, serde_json::json!({ "mode": "auto", "compensation": 0, "minEv100": -2, "maxEv100": 12 }))).unwrap();
+ let c = w.take_changes();
+ assert!(!c.structural && !c.camera && c.exposure, "an exposure mode");
+ w.set_camera_desc(2, cam(20.0, manual(5.0))).unwrap();
+ assert!(!w.take_changes().any(), "a camera that is not the scene's");
+ w.set_settings(Settings { camera: Some(2), ..w.settings.clone() });
+ let c = w.take_changes();
+ assert!(!c.structural && c.camera && c.exposure && c.dof, "the scene's camera is another");
+ w.set_settings(Settings { preset: "preview".into(), ..w.settings.clone() });
+ let c = w.take_changes();
+ assert!(!c.structural && c.settings, "another preset");
+ w.set_settings(Settings { overrides: Some(serde_json::json!({ "native": { "maxBounces": 2 } })), ..w.settings.clone() });
let c = w.take_changes();
- assert!(!c.structural && c.environment, "a new colour");
- let e = env(None);
- w.set_environment(e);
- assert!(w.take_changes().structural, "the background goes");
+ assert!(!c.structural && c.settings, "the preset's overrides");
+ w.set_settings(Settings { width: 640, height: 360, time: 3.0, ..w.settings.clone() });
+ assert!(!w.take_changes().any(), "an offline render's size and clock");
}
#[test]