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.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
Live view: a view can change size, the window follows its own (#132)
Yujia2d6b808fc56d
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex bd2a77a..bcebb5e 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -2574,6 +2574,23 @@ buffers and histories owned by the view, and the environment an object of its owside the environment hangs on is not (here the scene's, as the scene DSL has it). Still against that: theper-pixel accumulation buffer is made with the scene's data. Resize moves it to the view.+**The view at another size (2026-11-16, scene step A3).** A view's size was fixed when it opened: the window could+not be resized, and the per-pixel samples were made with the scene's data. The view owns every buffer that follows+its size now (`live/targets.rs`: the samples, the passes' own and their bind groups, the output, the kernel's+four), and `LiveCore::resize` makes those again and nothing else: the scene's data, its acceleration structures+and the radiance cache stay, the frames' histories start again. Bistro, to 1920 × 1080 or 2560 × 1440: 0.5 ms on+the CPU, and the next frame waits for the GPU about half a frame longer, once (a rebuild there is 0.7–0.9 s). The+window (`play`) is resizable and follows its size and its display's density (`view.rs` `fit`), and takes each+answer of the surface as wgpu documents it (`acquire`): before, a window the system resized (moved to a display+of another scale) reported `surface: Outdated` on every frame from then on (#101). A covered or minimised window+has no present to pace its loop: it configured its surface and printed an error on every turn and took a core+(96 %); it says so once now and waits for the next frame's time (3–4 %), the game's frame running as ever. The+headless runner takes `{"cmd":"resize"}`. A test holds a resized view to one built at that size+(state, picture; the scene's buffers and the cache the same handles) and fails with each of four steps of+`resize` left out; on Bistro a view resized and back is the view only reset (dE 0.18, SSIM 0.9995 at the same+frames). Left: the browser host's view is still fixed; the merged layout keeps the cache in one buffer with the+size's buffers, so a resize there empties it; a drag makes every buffer again at each step.+## 2. Temporal fixesTargets (2026-11-08): bench-temporal, bench-ghosting and their UE MRQ references move to Bistro night (§ 0 step 7); thediff --git a/docs/RUNTIME.md b/docs/RUNTIME.mdindex fb2b35c..a0021b0 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`, `live/state.rs` | Parameter changes rewrite GPU table entries in place (materials, lights, object power, emitter CDF), 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 data is held beside it and derived whole from the world, by the same function at load and on an edit (`live/state.rs`): the view's state (`ViewState`: the scene camera's lens, depth of field and exposure, which camera is the scene's, the render preset) and the environment (`Environment`: wetness, rain, fog or a background, appearing or going with another variant of the kernel; its sky, baked and put in place by `apply_sky`). 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`, `live/state.rs` | Parameter changes rewrite GPU table entries in place (materials, lights, object power, emitter CDF), 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 data is held beside it and derived whole from the world, by the same function at load and on an edit (`live/state.rs`): the view's state (`ViewState`: the scene camera's lens, depth of field and exposure, which camera is the scene's, the render preset) and the environment (`Environment`: wetness, rain, fog or a background, appearing or going with another variant of the kernel; its sky, baked and put in place by `apply_sky`). Anything structural rebuilds the GPU scene from the world, in memory; history survives, validated per pixel. The view's size is the view's: `LiveCore::resize` makes the buffers that follow it again (`live/targets.rs`) and leaves the scene's data and the radiance cache; the window (`play`) follows its size and its display's density, the headless runner takes `{"cmd":"resize"}`. || 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/gpu.rs b/renderer/src/gpu.rsindex ca29157..e9d41cc 100644--- a/renderer/src/gpu.rs+++ b/renderer/src/gpu.rs@@ -352,10 +352,11 @@ pub struct Uploaded {/// The uniform tables (`Gpu::uniform_tables`): the uniform buffers the kernel reads four tables from (merged.rs/// `UNIFORM_TABLES`' order; `Gpu::sync_tables` copies their sections there each frame).pub uniform: Option<[wgpu::Buffer; 4]>,+ /// The trace's samples, a `Pixel` a pixel: the view's buffer (a live view's targets', an offline render's own:+ /// `accum_buffer`). A handle of it here, for the scene's bind group, where the kernel's layout has it;+ /// `Gpu::set_accum` gives it another (a view of another size).pub accum: wgpu::Buffer,pub params: wgpu::Buffer,- pub width: u32,- pub height: u32,/// Kernel specialisation for this scene (`Gpu::pipeline`).pub kernel: Kernel,/// Triangle vertices / shading attributes (posed models rewrite their ranges).@@ -448,8 +449,6 @@ pub struct Translucent {pub params: wgpu::Buffer,pub points: wgpu::Buffer,pub count: wgpu::Buffer,- /// Live below full resolution: (colour, transmittance) per traced pixel (translucent.wgsl `tlow`).- pub low: wgpu::Buffer,}impl Uploaded {@@ -1219,6 +1218,8 @@ pub const CACHE_SIZE: u64 = 1 << 18;/// and the invocations of a dispatch row (DEFERRED_ROW).pub const DEFERRED_BYTES: u64 = 96;pub const DEFERRED_ROW: u32 = 16384;+/// The bytes of a traced pixel's samples (records.wgsl `Pixel`), in a view's buffer of them (`Gpu::accum_buffer`).+pub const SAMPLE_BYTES: u64 = 80;/// A buffer, or a range of one: in the merged layout (merged.rs) several of the engine's buffers are ranges of the one/// buffer a binding holds.@@ -1291,13 +1292,28 @@ pub struct KernelBufs {}impl KernelBufs {+ /// Each in a buffer of its own: the live passes' four of these bytes, made (and `deferred` of one record: its view+ /// makes it for what it traces), with this radiance cache and loop guard's count.+ fn separate(d: &wgpu::Device, cache: CacheBuffers, guard: Option<Buf>, refl: u64, motion: u64, direct: u64, lists: u64) -> KernelBufs {+ let sb = |label: &str, size: u64| Buf::whole(d.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false }));+ KernelBufs { cache, refl: sb("refl", refl), motion: sb("motion", motion), direct: sb("direct", direct), lists: sb("light lists", lists), deferred: Some(deferred_buffer(d, 1)), guard, merged: None }+ }++ /// These for a view of another size: the four that follow the size made again, the radiance cache and the loop+ /// guard's count kept. The merged layout's are one buffer: all of it made again, the cache (as long) empty.+ pub fn resized(&self, d: &wgpu::Device, refl: u64, motion: u64, direct: u64, lists: u64) -> KernelBufs {+ match self.merged {+ Some(_) => KernelBufs::new(d, true, true, self.cache.val.size / 32, refl, motion, direct, lists),+ None => KernelBufs::separate(d, self.cache.clone(), self.guard.clone(), refl, motion, direct, lists),+ }+ }+/// For a cache of `entries` and the live passes' four of these bytes./// `guard`: the layout as written has the guard's count (`Gpu::guard_room`).pub fn new(d: &wgpu::Device, merged: bool, guard: bool, entries: u64, refl: u64, motion: u64, direct: u64, lists: u64) -> KernelBufs {if !merged {- let sb = |label: &str, size: u64| Buf::whole(d.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false }));- let guard = guard.then(|| sb("loop guard", crate::merged::GUARD_WORDS as u64 * 4));- return KernelBufs { cache: CacheBuffers::new(d, entries), refl: sb("refl", refl), motion: sb("motion", motion), direct: sb("direct", direct), lists: sb("light lists", lists), deferred: Some(deferred_buffer(d, 1)), guard, merged: None };+ let guard = guard.then(|| Buf::whole(d.create_buffer(&wgpu::BufferDescriptor { label: Some("loop guard"), size: crate::merged::GUARD_WORDS as u64 * 4, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false })));+ return KernelBufs::separate(d, CacheBuffers::new(d, entries), guard, refl, motion, direct, lists);}// (The cache's keys and sums are as long as the kernel's struct says, whatever `entries`: `live_sizes`. A// section's range is the bytes asked for: a pass that binds it sees an array of that length.)@@ -1922,17 +1938,41 @@ impl Gpu {}/// The translucency pass's bind group (group 2) drawing into `target` (live: the composed image; offline: sums);- pub fn translucent_bind_group(&self, t: &Translucent, target: &wgpu::Buffer) -> wgpu::BindGroup {+ /// `low`: (colour, transmittance) per traced pixel, where a live view draws below full resolution+ /// (`translucent_low`; translucent.wgsl `tlow`).+ pub fn translucent_bind_group(&self, t: &Translucent, target: &wgpu::Buffer, low: &wgpu::Buffer) -> wgpu::BindGroup {fn e(b: u32, buf: &wgpu::Buffer) -> wgpu::BindGroupEntry<'_> {wgpu::BindGroupEntry { binding: b, resource: buf.as_entire_binding() }}self.device.create_bind_group(&wgpu::BindGroupDescriptor {label: Some("translucent"),layout: self.tl_layout.as_ref().unwrap(),- entries: &[wgpu::BindGroupEntry { binding: 0, resource: t.tlas.as_binding() }, e(1, &t.params), e(2, target), e(3, &t.points), e(4, &t.count), e(5, &t.low)],+ entries: &[wgpu::BindGroupEntry { binding: 0, resource: t.tlas.as_binding() }, e(1, &t.params), e(2, target), e(3, &t.points), e(4, &t.count), e(5, low)],})}+ /// A view's buffer of the trace's samples (`Uploaded::accum`): a `Pixel` a pixel, the largest buffer a view holds+ /// (`view_fits`).+ pub fn accum_buffer(&self, w: u32, h: u32) -> wgpu::Buffer {+ self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("accum"), size: w as u64 * h as u64 * SAMPLE_BYTES, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false })+ }++ /// Whether this device holds a view of `w` x `h` (its samples in one buffer).+ pub fn view_fits(&self, w: u32, h: u32) -> bool {+ self.buffer_fits(w as u64 * h as u64 * SAMPLE_BYTES)+ }++ /// A view's buffer for translucent particles drawn below full resolution (`translucent_bind_group`'s `low`).+ pub fn translucent_low(&self, w: u32, h: u32) -> wgpu::Buffer {+ self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("translucent low"), size: (w as u64 * h as u64).max(1) * 16, usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: false })+ }++ /// Another buffer for the trace's samples (a view of another size): the scene bound again with it.+ pub fn set_accum(&self, up: &mut Uploaded, accum: &wgpu::Buffer) {+ up.accum = accum.clone();+ self.rebind_scene(up);+ }+/// The radiance cache's per-frame resolve (pathtrace.wgsl `cache_resolve`; kernel bind groups).pub fn cache_resolve_pipeline(&self) -> wgpu::ComputePipeline {let module = &self.module;@@ -1991,7 +2031,7 @@ impl Gpu {/// Uploads a prepared scene (geometry, materials, textures, environment, acceleration structures) and returns the/// bind group used by both the offline and the live kernels. `accum` holds one 80-byte Pixel per output pixel.#[allow(clippy::too_many_arguments)]- pub fn upload(&self, scene: &Scene, w: u32, h: u32, tri_verts: &[[f32; 4]], groups: [usize; GROUPS], nodes: &[u8], emitters: &[[f32; 4]], light_tree: &[[f32; 4]], env: &EnvMap, env_cdf: &[f32], energy: &[[f32; 4]], timings: &mut Vec<(String, f64)>) -> Result<Uploaded> {+ pub fn upload(&self, scene: &Scene, accum: &wgpu::Buffer, tri_verts: &[[f32; 4]], groups: [usize; GROUPS], nodes: &[u8], emitters: &[[f32; 4]], light_tree: &[[f32; 4]], env: &EnvMap, env_cdf: &[f32], energy: &[[f32; 4]], timings: &mut Vec<(String, f64)>) -> Result<Uploaded> {let d = &self.device;let t0 = Instant::now();// (The vertices too: the kernel's tree over no triangle is a leaf of triangle 0, which these zeros make a@@ -2089,8 +2129,7 @@ impl Gpu {GridsGpu { atlas, pipeline, grids, step: std::cell::Cell::new(0) }});let grid_view = grids.as_ref().map_or_else(|| self.no_grid_view.clone(), |g| g.atlas.create_view(&Default::default()));- let accum_size = (w as u64) * (h as u64) * 80;- let b_accum = d.create_buffer(&wgpu::BufferDescriptor { label: Some("accum"), size: accum_size, usage: st | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });+ let b_accum = accum.clone();let b_params = d.create_buffer(&wgpu::BufferDescriptor { label: Some("params"), size: std::mem::size_of::<Params>() as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });let (tex_view, tex_info) = self.texture_pages(scene, timings);@@ -2337,8 +2376,7 @@ impl Gpu {let params = d.create_buffer(&wgpu::BufferDescriptor { label: Some("translucent params"), size: 48, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });let points = d.create_buffer(&wgpu::BufferDescriptor { label: Some("volume points"), size: VOLUME_TRAIN_CAP as u64 * 16, usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: false });let count = d.create_buffer(&wgpu::BufferDescriptor { label: Some("volume point count"), size: 16, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });- let low = d.create_buffer(&wgpu::BufferDescriptor { label: Some("translucent low"), size: (w as u64 * h as u64).max(1) * 16, usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: false });- let t = Translucent { blas, tlas, size, verts, first: scene.trans_first, params, points, count, low };+ let t = Translucent { blas, tlas, size, verts, first: scene.trans_first, params, points, count };// Built once now (collapsed quads): bind groups may use the TLAS before the first particle pass.let mut enc = d.create_command_encoder(&Default::default());t.build(&mut enc);@@ -2431,7 +2469,7 @@ impl Gpu {timings.push(("upload_ms".into(), t0.elapsed().as_secs_f64() * 1000.0));// (The scene's own pipelines, made above: particles, grid programs.)self.save_pipeline_cache();- Ok(Uploaded { bg, bg_parts, heap, uniform, accum: b_accum, params: b_params, width: w, height: h, kernel, verts: b_verts, attrs: b_attrs, prev_verts: b_prev, dynamic_first, accel, units: scene.units.clone(), particles, gpu_particles, grids, translucent, vcolors: !scene.gpu_vcolors.is_empty(), media_nodes: scene.media_nodes.clone(), media_hidden: std::cell::RefCell::new(scene.media.iter().map(|m| m.a[1] == crate::scene::MEDIUM_HIDDEN).collect()), room, words, cdf_words: env_cdf.len(), region_words, env_tex })+ Ok(Uploaded { bg, bg_parts, heap, uniform, accum: b_accum, params: b_params, kernel, verts: b_verts, attrs: b_attrs, prev_verts: b_prev, dynamic_first, accel, units: scene.units.clone(), particles, gpu_particles, grids, translucent, vcolors: !scene.gpu_vcolors.is_empty(), media_nodes: scene.media_nodes.clone(), media_hidden: std::cell::RefCell::new(scene.media.iter().map(|m| m.a[1] == crate::scene::MEDIUM_HIDDEN).collect()), room, words, cdf_words: env_cdf.len(), region_words, env_tex })}/// Bytes Metal allocates for an AABB BLAS over `count` boxes in `boxes` (its own size query through wgpu-hal; None@@ -3218,14 +3256,14 @@ impl Gpu {#[cfg(not(target_arch = "wasm32"))]/// Offline translucency: the pass (translucent.wgsl) `spp` times at random points in each pixel, each with a fresh/// lighting estimate per hit; the mean (colour, transmittance) per pixel. Empty without translucent particles.- fn render_translucent(&self, up: &Uploaded, base: Params, spp: u32) -> Result<Vec<[f32; 4]>> {+ fn render_translucent(&self, up: &Uploaded, base: Params, spp: u32, (w, h): (u32, u32)) -> Result<Vec<[f32; 4]>> {let Some(t) = &up.translucent else { return Ok(vec![]) };let d = &self.device;- let (w, h) = (up.width, up.height);let pipeline = self.translucent_pipelines(&up.kernel, false).draw;let size = w as u64 * h as u64 * 16;let sums = d.create_buffer(&wgpu::BufferDescriptor { label: Some("translucent sums"), size, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false });- let tbg = self.translucent_bind_group(t, &sums);+ // (Drawn at full resolution: the reduced image's buffer is bound and not read.)+ let tbg = self.translucent_bind_group(t, &sums, &self.translucent_low(1, 1));let tp = TranslucentParams { size: [w, h, t.first, 0], view: [w, h, 0, 0], misc: [0.0; 4] };self.queue.write_buffer(&t.params, 0, bytemuck::bytes_of(&tp));let n = spp.max(1);@@ -3269,7 +3307,7 @@ impl Gpu {pub fn render(&self, scene: &Scene, tri_verts: &[[f32; 4]], groups: [usize; GROUPS], nodes: &[u8], emitters: &[[f32; 4]], light_tree: &[[f32; 4]], env: &EnvMap, env_cdf: &[f32], energy: &[[f32; 4]], base: Params, spp: u32, timings: &mut Vec<(String, f64)>) -> Result<Frame> {let d = &self.device;let (w, h) = (scene.width, scene.height);- let up = self.upload(scene, w, h, tri_verts, groups, nodes, emitters, light_tree, env, env_cdf, energy, timings)?;+ let up = self.upload(scene, &self.accum_buffer(w, h), tri_verts, groups, nodes, emitters, light_tree, env, env_cdf, energy, timings)?;let pipeline = self.pipeline(&up.kernel, false);// Particles: placed once, at the scene time and camera.if up.particles.is_some() {@@ -3349,7 +3387,7 @@ impl Gpu {}}let t_tl = Instant::now();- let overlay = self.render_translucent(&up, base, spp)?;+ let overlay = self.render_translucent(&up, base, spp, (w, h))?;if up.translucent.is_some() {timings.push(("translucent_ms".into(), t_tl.elapsed().as_secs_f64() * 1000.0));}diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rsindex 6be8b3d..f0ec612 100644--- a/renderer/src/live/edits.rs+++ b/renderer/src/live/edits.rs@@ -614,8 +614,7 @@ impl LiveCore {self.view = view;self.view.write(&mut self.sc.base);if ch.settings {- let preset = self.view.preset.clone();- self.apply_post(&preset.post);+ self.apply_post();self.scene_name = world.settings.name.clone();self.lit_changed = self.frame.max(1);}diff --git a/renderer/src/live/frame.rs b/renderer/src/live/frame.rsindex f255b50..5d8410f 100644--- a/renderer/src/live/frame.rs+++ b/renderer/src/live/frame.rs@@ -257,6 +257,9 @@ impl LiveCore {let (w, h) = (self.w, self.h);let (iw, ih) = self.internal_size();self.ensure_deferred(iw as u64 * ih as u64);+ if self.sc.up.translucent.is_some() {+ self.targets.translucent_low(&self.g);+ }let now = Instant::now();// Lockstep (benchmarks) renders at a fixed frame time, whatever the wall clock says.self.frame_dt = self.fixed_dt.unwrap_or_else(|| now.duration_since(self.last_frame).as_secs_f32());@@ -545,7 +548,7 @@ impl LiveCore {let low = (iw, ih) != (w, h);let tp = gpu::TranslucentParams { size: [w, h, t.first, 1], view: [iw, ih, gpu::VOLUME_TRAIN_CAP, low as u32], misc: [VOLUME_TRAIN_SHARE, translucent_hidden(self.frame) as u32 as f32, 0.0, 0.0] };g.queue.write_buffer(&t.params, 0, bytemuck::bytes_of(&tp));- (pipes, g.translucent_bind_group(t, target), &t.count)+ (pipes, g.translucent_bind_group(t, target, self.targets.translucent_low.as_ref().expect("made at the frame's start")), &t.count)});// The pass (train = false) or the volume training (train = true).let tl_dispatch = |pass: &mut wgpu::ComputePass, train: bool| {@@ -587,7 +590,7 @@ impl LiveCore {let mut pass = e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some(name), timestamp_writes: Some(wgpu::ComputePassTimestampWrites { query_set: &p.queries, beginning_of_pass_write_index: Some(q), end_of_pass_write_index: Some(q + 1) }) });if (self.view_mode != 0 || !layout::VIEW_MODE_PASSES.contains(name)) && (tiles_on || *name != layout::LIGHT_TILES_PASS) {pass.set_pipeline(pipe);- pass.set_bind_group(0, &self.sc.bgs[k], &[]);+ pass.set_bind_group(0, &self.targets.bgs[k], &[]);let (gw, gh) = grid.size((w, h), (iw, ih), self.prev_isz);pass.dispatch_workgroups(gw.div_ceil(8), gh.div_ceil(8), 1);}@@ -611,7 +614,7 @@ impl LiveCore {continue;}pass.set_pipeline(pipe);- pass.set_bind_group(0, &self.sc.bgs[k], &[]);+ pass.set_bind_group(0, &self.targets.bgs[k], &[]);let (gw, gh) = grid.size((w, h), (iw, ih), self.prev_isz);pass.dispatch_workgroups(gw.div_ceil(8), gh.div_ceil(8), 1);if *name == "upscale" {diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rsindex 51d5165..7f226e8 100644--- a/renderer/src/live/inplace_tests.rs+++ b/renderer/src/live/inplace_tests.rs@@ -1,5 +1,5 @@//! 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.)+//! parameters and kernel variant, the same picture. So does another size. (GPU tests: skipped without a GPU.)use super::*;use crate::world::{Geometry, Kind, Settings};@@ -50,8 +50,8 @@ fn camera(fov: f32, dof: Option<f32>, exposure: serde_json::Value) -> crate::desserde_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 else these edits reach: the lights' table and the sun, the sky's map, what the passes after+/// A view's state: the kernel's parameters whole (as words; not the camera's four vectors and the size, which the frame+/// writes from the view), and what else these edits reach: the lights' table and the sun, the sky's map, what the passes after/// the kernel take. (After a frame: the frame writes the light LOD's reference.)fn state(c: &LiveCore) -> (Vec<u32>, String) {let (s, v, sky) = (&c.sc, &c.view, &c.env.sky);@@ -63,15 +63,17 @@ fn state(c: &LiveCore) -> (Vec<u32>, String) {v.exposure, v.exposure_settings, v.camera, v.dof,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)+ assert_eq!((std::mem::offset_of!(gpu::Params, cam_pos), std::mem::offset_of!(gpu::Params, size) + 16), (0, FRAME_WORDS * 4), "the camera's vectors and the size are the parameters' first");+ (bytemuck::cast_slice::<_, u32>(bytemuck::bytes_of(&s.base))[FRAME_WORDS..].to_vec(), rest)}+/// The parameters' words the frame writes from the view: the camera's four vectors, the size.+const FRAME_WORDS: usize = 20;+/// 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();+ let words: Vec<usize> = (0..a.len()).filter(|&k| a[k] != b[k]).map(|k| k + FRAME_WORDS).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");}@@ -189,4 +191,65 @@ fn edits_in_place_leave_what_a_build_does() {assert!(!live.commit(&mut w).unwrap() && live.cam == away && live.view.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.view.camera && live.cam != away, "a lens: the view takes the scene's camera");+ // A commit that rebuilds (another mesh) and brings another preset with it.+ w.set_object(13, "more".into(), None, Kind::Mesh { geometry: 3, material: 1, own_blas: false, materials: vec![] }, true, false).unwrap();+ w.set_settings(Settings { preset: "cinematic".into(), overrides: Some(serde_json::json!({ "post": { "vignette": 0.3 } })), ..w.settings.clone() });+ assert!(live.commit(&mut w).unwrap(), "another mesh: a rebuild");+ let mut fresh = open(&w).unwrap();+ (picture(&mut live, 1), picture(&mut fresh, 1));+ same_state("a rebuild with another preset", &live, &fresh);+}++/// A view at another size, against a view built at that size: the same state and picture, with the scene's data and+/// the radiance cache it had; an edit and a rebuild after it as in a view of that size; a size the device does not+/// hold refused.+#[test]+fn a_resized_view_is_a_view_built_at_that_size() {+ let presets = crate::default_presets_dir();+ let open = |w: &World, (x, y): (u32, u32)| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new("."), &presets, x, y));+ let mut w = world();+ let mut live = match open(&w, (96, 54)) {+ Ok(c) => c,+ Err(e) => return eprintln!("skipped: {e}"),+ };+ w.take_changes();+ picture(&mut live, 8);+ let (verts, cache, out) = (live.sc.up.verts.clone(), live.targets.kernel.cache.val.buffer.clone(), live.targets.out.clone());+ live.resize(96, 54).unwrap();+ assert!(live.targets.out == out && !live.reset, "the same size: the view as it was");+ let against = |what: &str, live: &mut LiveCore, w: &World| {+ let size = (live.w, live.h);+ let mut fresh = open(w, size).unwrap();+ forget(live);+ let (a, b) = (picture(live, 24), picture(&mut fresh, 24));+ assert_eq!(a.len(), (size.0 * size.1 * 4) as usize, "{what}: the output's size");+ // (0.02 to 0.13 steps as measured; 9 with the scene bound to the old size's samples.)+ assert!(apart(&a, &b) < 0.5, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b));+ same_state(what, live, &fresh);+ };+ // (Smaller than a tile of 8 too.)+ for size in [(160, 90), (54, 96), (97, 55), (5, 3), (1, 1), (96, 54)] {+ live.resize(size.0, size.1).unwrap();+ assert!(live.reset && (live.w, live.h) == size, "{size:?}: the histories start again");+ assert!(live.sc.up.verts == verts, "{size:?}: the scene's data is as it was");+ assert!(live.g.merged || live.targets.kernel.cache.val.buffer == cache, "{size:?}: the radiance cache is as it was");+ against(&format!("{size:?}"), &mut live, &w);+ }+ // An edit in place, then a rebuild, in a view that was resized.+ live.resize(128, 72).unwrap();+ w.set_camera_desc(4, camera(25.0, Some(4.5), manual(1.0))).unwrap();+ assert!(!live.commit(&mut w).unwrap(), "a lens after another size: in place");+ against("a lens after another size", &mut live, &w);+ live.rebuild(&w).unwrap();+ against("a rebuild after another size", &mut live, &w);+ // More pixels than a buffer holds.+ assert!(live.resize(1 << 20, 1 << 20).is_err() && (live.w, live.h) == (128, 72), "a size the device does not hold is refused");+ against("a size refused", &mut live, &w);+ // A display of another density: dynamic resolution starts again from its points' resolution, a fixed scale stays.+ live.set_scale(0.0);+ live.set_display_scale(2.0);+ assert!(live.dynamic_res && live.render_scale == 0.5, "dynamic resolution on a display of two pixels a point");+ live.set_scale(0.75);+ live.set_display_scale(1.0);+ assert!(!live.dynamic_res && live.render_scale == 0.75, "a fixed scale through another density");}diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rsindex 8a5ccd8..da7f88c 100644--- a/renderer/src/live/load.rs+++ b/renderer/src/live/load.rs@@ -31,8 +31,6 @@ pub(super) struct LoadedScene {pub(super) triangles: usize,pub(super) up: gpu::Uploaded,pub(super) base: gpu::Params,- /// The live passes' bind groups, a pass each (`Targets::bind_groups`).- pub(super) bgs: Vec<wgpu::BindGroup>,/// GPU table copies that parameter edits rewrite in place (`commit`).pub(super) tables: tables::Tables,/// CPU copy of the dynamic triangles (posed models: the tail of the GPU triangle order from `dynamic_first`):@@ -199,7 +197,7 @@ impl EmitterWorker {}}-pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Path, w: u32, h: u32, targets: &Targets, passes: &Passes) -> Result<(LoadedScene, ViewState, Environment)> {+pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Path, w: u32, h: u32, targets: &Targets) -> Result<(LoadedScene, ViewState, Environment)> {let t0 = Instant::now();let mut sc = scene::build(world, assets, presets, None)?;sc.width = w;@@ -218,7 +216,7 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Plet (mat_runs, tri_order) = (std::mem::take(&mut prep.mat_runs), std::mem::take(&mut prep.tri_order));let fixed_features = (!sc.textures.is_empty(), !sc.shaders.is_empty(), prep.groups);// (The light tree is the tables' by now: its nodes from there.)- let up = g.upload(&sc, w, h, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, crate::ltree::nodes_of(tables.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, &mut timings)?;+ let up = g.upload(&sc, &targets.accum, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, crate::ltree::nodes_of(tables.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, &mut timings)?;let _ = g.pipeline(&up.kernel, true); // compile the scene's kernel variant now, not in the first frameif !g.merged {let _ = g.kernel_pass(&up.kernel, "finish");@@ -235,7 +233,6 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P}base.ltile[3] = super::LIST_CANDIDATES;base.cam_fwd[3] = w as f32 / h as f32;- let bgs = targets.bind_groups(&g.device, passes, &up.accum);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));let instanced = !sc.gpu_instances.is_empty() || !sc.procs.is_empty();let instance_features = gpu::instance_features(&sc);@@ -286,5 +283,5 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Pinst_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, tables, fixed_features, dynamic, edit, emit, mat_runs, tri_order }, view, env))+ 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, tables, fixed_features, dynamic, edit, emit, mat_runs, tri_order }, view, env))}diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rsindex ce7db12..a5f2157 100644--- a/renderer/src/live/mod.rs+++ b/renderer/src/live/mod.rs@@ -22,6 +22,7 @@//! | {"cmd":"camera",...,"frames":n,"sync":id | "snapshot":p} | {"cmd":"frames","n":n,"sync":id | "snapshot":p}//! (a step: camera, frames, and the sync answer / snapshot at its last frame, in one command)//! | {"cmd":"scale","scale":s (0 = auto)} | {"cmd":"quit"}+//! | {"cmd":"resize","width":w,"height":h} (the view at another size; stderr "live: resized to wxh in t ms")//!//! The files: this one holds `LiveCore` itself (its settings, camera, resolution governor and readbacks) and what the//! others share; `targets` the live passes' pipelines, screen-size buffers and bind group; `load` a scene loaded and@@ -147,6 +148,13 @@ struct LiveParams {/// uniform ones (`Params::ltile.w`; half past the camera hit). 2 read as 4, 8 and 16 on the lamp-rooms shots.pub(super) const LIST_CANDIDATES: u32 = 2;+/// The kernel's group-1 bind groups over a view's targets: the trace's, and the translucency pass's where the device+/// has one (`gpu::Gpu::tl_vis_layout`: without `finish`'s records).+fn kernel_bind_groups(g: &gpu::Gpu, raster: Option<&Raster>, targets: &Targets) -> (wgpu::BindGroup, Option<wgpu::BindGroup>) {+ let vis = raster.map_or(&g.no_vis_view, |r| &r.vis);+ (gpu::vis_bind_group(&g.device, &g.vis_layout, vis, &targets.kernel, true), g.tl_vis_layout.as_ref().map(|l| gpu::vis_bind_group(&g.device, l, vis, &targets.kernel, false)))+}+#[derive(Clone, Copy, PartialEq, Debug)]pub struct Camera {pub pos: Vec3,@@ -207,6 +215,8 @@ pub enum Cmd {Status(String),/// Render scale (0 = dynamic resolution).Scale(f32),+ /// The view at another size, pixels (`LiveCore::resize`; the window host: its window's).+ Resize(u32, u32),Quit,}@@ -489,10 +499,9 @@ impl LiveCore {// The scene's post preset replaces this LUT below (apply_post).let cache_on = !std::env::var("THREERT_CACHE").is_ok_and(|v| v == "0");// (Without the cache the kernel binds one of one entry.)- let targets = Targets::new(&g, w, h, &vec![0u16; (LUT * LUT * LUT * 4) as usize], if cache_on { gpu::CACHE_SIZE } else { 1 });- let (sc, view, env) = load_scene(&g, world, assets, presets, w, h, &targets, &passes)?;+ let targets = Targets::new(&g, &passes, w, h, &vec![0u16; (LUT * LUT * LUT * 4) as usize], if cache_on { gpu::CACHE_SIZE } else { 1 });+ let (sc, view, env) = load_scene(&g, world, assets, presets, w, h, &targets)?;let cam = view.camera;- let pp = view.preset.post.clone();let (triangles, scene_name) = (sc.triangles, sc.name.clone());let profile = (g.timestamps && std::env::var("THREERT_PROFILE").is_ok()).then(|| {// trace, the post passes, cache resolve, then the particle pass, the BLAS rebuild, the translucency pass and@@ -516,16 +525,14 @@ impl LiveCore {let timer = (g.timestamps && profile.is_none()).then(|| FrameTimer::new(&g.device));let raster = std::env::var("THREERT_RASTER").is_ok_and(|v| v == "1").then(|| Raster::new(&g, w, h));let cache = cache_on.then(|| RadianceCache { bufs: targets.kernel.cache.clone(), resolve: g.cache_resolve_pipeline() });- let vis = raster.as_ref().map_or(&g.no_vis_view, |r| &r.vis);- let kernel_bg = gpu::vis_bind_group(&g.device, &g.vis_layout, vis, &targets.kernel, true);- let tl_kernel_bg = g.tl_vis_layout.as_ref().map(|l| gpu::vis_bind_group(&g.device, l, vis, &targets.kernel, false));+ let (kernel_bg, tl_kernel_bg) = kernel_bind_groups(&g, raster.as_ref(), &targets);// (Read whenever a kernel of this session may have the guard: under software traversal a scene's first unit// brings it, `gpu::loop_guard_of`.)let guard_read = (gpu::loop_guard_of(!g.hwrt).is_some() && targets.kernel.guard.is_some()).then(|| (g.device.create_buffer(&wgpu::BufferDescriptor { label: Some("loop guard read"), size: 4, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }), Arc::new(AtomicU32::new(0))));let mut core = LiveCore { particle_spawns: Default::default(), grid_sources: Default::default(), g, passes, targets, sc, view, env, presets: presets.to_path_buf(), assets: assets.to_path_buf(), w, h, seq: 0, aspect: w as f32 / h as f32, cam, prev_cam: cam, frame: 0, history_len: 0.0, reset: true, bloom: ([0.0; 6], [0.0; 6]), vignette: 0.0, post: [0.0; 4], blur: (0.0, 0.0), inflight: Default::default(), gpu_ms: 0.0, gpu_frame: 0, gpu_trace_ms: 0.0, edit_ms: 0.0, instanced_ms: 0.0, edit_split: EditSplit::default(), rebuild_ms: 0.0, fallback: None, fallbacks: 0, bounces: 4, rays: true, view_mode: std::env::var("THREERT_VIEW_MODE").ok().and_then(|v| v.parse().ok()).unwrap_or(0), fixed_dt: None, motion_blur_off: false, triangles, scene_name, time: 0.0, frame_dt: 1.0 / 60.0, last_frame: Instant::now(), post_key: String::new(), render_scale: 1.0, dynamic_res: false, min_scale: MIN_SCALE, display_scale: 1.0, over_budget: (0, 0), born: Instant::now(), governed: Instant::now(), profile, timer, raster, cache, kernel_bg, tl_kernel_bg, prev_span: None, reposed: false, emitters_moved: false, pose_span: None, pose_reposed: false, inst_moving: vec![], inst_moved: false, prev_isz: (0, 0), light_tiles: None, lit_changed: 0, spark_lights: false, shown_spp: 1, cpu_skin_ms: 0.0, cpu_upload_ms: 0.0, gpu_blas_ms: 0.0, cpu_wait_ms: 0.0, guard_trips: guard_read.as_ref().map(|_| 0), guard_read };core.spark_lights = core.sc.tables.emitter_tris.iter().any(|e| e.nominal);- core.apply_post(&pp);+ core.apply_post();Ok(core)}@@ -570,8 +577,7 @@ impl LiveCore {}pub fn rebuild(&mut self, world: &World) -> Result<()> {- let (s, view, env) = load_scene(&self.g, world, &self.assets, &self.presets, self.w, self.h, &self.targets, &self.passes)?;- self.apply_post(&view.preset.post);+ let (s, view, env) = load_scene(&self.g, world, &self.assets, &self.presets, self.w, self.h, &self.targets)?;self.triangles = s.triangles;self.scene_name = s.name.clone();// The scene's camera changed (a new lens rebuilds, and a move in the same commit comes with it): the view takes it.@@ -580,6 +586,7 @@ impl LiveCore {self.cam = view.camera;}(self.view, self.env) = (view, env);+ self.apply_post();// What the grid programs had simulated goes with the grids that are still the same.self.g.carry_grids(&self.sc.up, &s.up);self.sc = s;@@ -592,19 +599,23 @@ impl LiveCore {Ok(())}- /// Rebuilds the tonemap LUT and bloom / vignette / fringe / grain settings when the scene's post preset changed.- fn apply_post(&mut self, pp: &crate::desc::PostPreset) {+ /// The post passes' settings from the view's preset (`self.view`: assigned before this): the tone-map table,+ /// written when the preset's post settings are others, and bloom / vignette / fringe / grain / motion blur, of+ /// which the bloom's stages and the blur's reach follow the view's size.+ fn apply_post(&mut self) {+ let preset = self.view.preset.clone();+ let pp = &preset.post;let key = format!("{pp:?}");- if key == self.post_key {- return;+ if key != self.post_key {+ let lut = tonemap_lut(pp);+ self.g.queue.write_texture(+ wgpu::TexelCopyTextureInfo { texture: &self.targets.lut_tex, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },+ bytemuck::cast_slice(&lut),+ wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(LUT * 8), rows_per_image: Some(LUT) },+ wgpu::Extent3d { width: LUT, height: LUT, depth_or_array_layers: LUT },+ );+ self.post_key = key;}- let lut = tonemap_lut(pp);- self.g.queue.write_texture(- wgpu::TexelCopyTextureInfo { texture: &self.targets.lut_tex, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },- bytemuck::cast_slice(&lut),- wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(LUT * 8), rows_per_image: Some(LUT) },- wgpu::Extent3d { width: LUT, height: LUT, depth_or_array_layers: LUT },- );self.bloom = bloom_stages(pp, self.w, self.h);self.vignette = pp.vignette;// THREERT_NO_GRAIN=1: no film grain (a fresh random pattern every frame; comparisons between frames see it as error).@@ -620,7 +631,6 @@ impl LiveCore {};self.post = [pp.chromatic_aberration, grain, pp.bloom.threshold, mb.max / 100.0 * self.w as f32];self.blur = (if mb.max > 0.0 { mb.amount.max(0.0) } else { 0.0 }, mb.target_fps);- self.post_key = key;}/// Switches to a different world: camera from it, history cleared.@@ -638,14 +648,15 @@ impl LiveCore {Ok(())}- /// The view is a display's physical pixels, `k` a point: dynamic resolution, from the points' resolution (the rays- /// a view in points starts with) down to `MIN_SCALE` of it. A fixed scale is set after it (`set_scale`).+ /// The view is a display's physical pixels, `k` a point: dynamic resolution runs from the points' resolution (the+ /// rays a view in points starts with) down to `MIN_SCALE` of it, and starts there again; a fixed scale stays.pub fn set_display_scale(&mut self, k: f32) {let k = k.max(1.0);self.display_scale = k;self.min_scale = (MIN_SCALE / k).max(SCALE_FLOOR);- self.render_scale = 1.0 / k;- self.dynamic_res = true;+ if self.dynamic_res {+ self.render_scale = 1.0 / k;+ }}/// The scene's lighting is changing: something moved or was edited in the last 45 frames, or the scene has spark@@ -694,16 +705,44 @@ impl LiveCore {return;}self.targets.kernel.deferred = Some(gpu::deferred_buffer(&self.g.device, (pixels + pixels / 4).min(self.w as u64 * self.h as u64)));- let vis = self.raster.as_ref().map_or(&self.g.no_vis_view, |r| &r.vis);- self.kernel_bg = gpu::vis_bind_group(&self.g.device, &self.g.vis_layout, vis, &self.targets.kernel, true);+ (self.kernel_bg, self.tl_kernel_bg) = kernel_bind_groups(&self.g, self.raster.as_ref(), &self.targets);+ }++ /// The view at another size (its host's window, in pixels): the targets that follow the size are made again+ /// (`Targets::resize`) and bound, the scene with the new samples' buffer; the frames' histories start again. The+ /// scene's data, the radiance cache (the world's), the view's camera, state and render scale stay. A size this+ /// device does not hold is refused, the view as it was.+ pub fn resize(&mut self, w: u32, h: u32) -> Result<()> {+ let (w, h) = (w.max(1), h.max(1));+ if (w, h) == (self.w, self.h) {+ return Ok(());+ }+ if !self.g.view_fits(w, h) {+ anyhow::bail!("a view of {w} x {h}: more samples than this device holds in one buffer");+ }+ (self.w, self.h, self.aspect) = (w, h, w as f32 / h as f32);+ self.targets.resize(&self.g, &self.passes, w, h);+ if self.raster.is_some() {+ self.raster = Some(Raster::new(&self.g, w, h));+ }+ if let Some(c) = &mut self.cache {+ c.bufs = self.targets.kernel.cache.clone();+ }+ (self.kernel_bg, self.tl_kernel_bg) = kernel_bind_groups(&self.g, self.raster.as_ref(), &self.targets);+ self.g.set_accum(&mut self.sc.up, &self.targets.accum);+ self.apply_post();+ // As a new view: no history, no frame before this one.+ (self.reset, self.prev_isz) = (true, (0, 0));+ Ok(())}/// Renders one frame with `spp` samples per pixel; returns the command buffers to submit after the samples./// Path-trace dispatches are submitted inside (each needs its own uniform contents).- /// Traced resolution at the current render scale.+ /// Traced resolution at the current render scale: 8 pixels a side at least, or the view's where it has fewer.pub fn internal_size(&self) -> (u32, u32) {let s = self.render_scale.clamp(SCALE_FLOOR, 1.0);- (((self.w as f32 * s).round() as u32).clamp(8, self.w), ((self.h as f32 * s).round() as u32).clamp(8, self.h))+ let side = |n: u32| ((n as f32 * s).round() as u32).clamp(n.min(8), n);+ (side(self.w), side(self.h))}/// Dynamic resolution (UE r.DynamicRes): twice a second, move the render scale toward the frame budget (traced@@ -804,7 +843,7 @@ impl LiveCore {let composed = read(&fb.buffer, fb.offset, tn * 16)?;let spec_pp = t.buf("spec_pp");let spec = read(&spec_pp.buffer, spec_pp.offset + n * 8, tn * 8)?; // spec_pp slot 1: (rgb, history) as two pairs of f16- let samples = read(&self.sc.up.accum, 0, tn * 80)?; // the kernel's samples (live.wgsl `Pixel`): emit at 48+ let samples = read(&self.targets.accum, 0, tn * gpu::SAMPLE_BYTES)?; // the kernel's samples (live.wgsl `Pixel`): emit at 48let (composed, spec, samples): (&[[f32; 4]], &[[u32; 2]], &[[f32; 20]]) = (bytemuck::cast_slice(&composed), bytemuck::cast_slice(&spec), bytemuck::cast_slice(&samples));let (mut dif, mut spe, mut emi) = (Vec::with_capacity(w * h * 3), Vec::with_capacity(w * h * 3), Vec::with_capacity(w * h * 3));let finite = |v: f32| if v.is_finite() { v } else { 0.0 };diff --git a/renderer/src/live/session.rs b/renderer/src/live/session.rsindex 23bac3d..8787456 100644--- a/renderer/src/live/session.rs+++ b/renderer/src/live/session.rs@@ -5,13 +5,12 @@ use super::*;/// Headless runner: renders at a fixed frame rate and saves snapshots on request (tools/bench-live.ts).pub fn run(presets: &Path, opts: LiveOpts) -> Result<()> {- let (w, h) = (opts.width, opts.height);let (cmd_tx, cmd_rx) = mpsc::channel::<Cmd>();spawn_stdin_reader(cmd_tx);if let Some(store) = &opts.store {crate::files::set_user_root(Some(store));}- let (mut game, mut core) = crate::script::GameSession::start(&opts.bundle, &opts.room, &opts.assets, gpu::Gpu::new()?, presets, w, h)?;+ let (mut game, mut core) = crate::script::GameSession::start(&opts.bundle, &opts.room, &opts.assets, gpu::Gpu::new()?, presets, opts.width, opts.height)?;// The host channel: this runner is the app. How the game was opened, once after setup; what the game posts goes// out on stdout (`emit_posts`), and whoever drives the runner answers with `{"cmd":"host"}`.if let Err(e) = game.host_messages(&mut core, &[crate::host::launch_message_with_caps(opts.launch.as_ref(), &opts.caps.iter().map(String::as_str).collect::<Vec<_>>())]) {@@ -21,13 +20,13 @@ pub fn run(presets: &Path, opts: LiveOpts) -> Result<()> {// Frame-script cost (script + commit), reported every 2 s.let (mut fs_sum, mut fs_max, mut fs_n) = (0.0f32, 0.0f32, 0u32);core.bounces = opts.bounces;+ core.set_scale(opts.scale.unwrap_or(0.0));core.set_display_scale(opts.display_scale);- if let Some(s) = opts.scale {- core.set_scale(s);- }eprintln!("live: load {}", serde_json::Value::Object(core.load_timings().iter().map(|(k, v)| (k.clone(), (*v).into())).collect()));- eprintln!("live: {}x{} @{} fps on {} ({})", w, h, opts.fps, core.g.adapter_info.name, if core.g.hwrt { "HW RT" } else { "BVH" });- let staging = core.g.device.create_buffer(&wgpu::BufferDescriptor { label: Some("snapshot"), size: (w * h * 4) as u64, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });+ eprintln!("live: {}x{} @{} fps on {} ({})", core.w, core.h, opts.fps, core.g.adapter_info.name, if core.g.hwrt { "HW RT" } else { "BVH" });+ // A snapshot's pixels, at the view's size.+ let staging_for = |core: &LiveCore| core.g.device.create_buffer(&wgpu::BufferDescriptor { label: Some("snapshot"), size: core.targets.out.size(), usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });+ let mut staging = staging_for(&core);let frame_dt = Duration::from_secs_f64(1.0 / opts.fps as f64);let mut next = Instant::now();let mut snapshots: Vec<(PathBuf, u32, u32)> = vec![]; // path, min history, first eligible frame@@ -81,6 +80,16 @@ pub fn run(presets: &Path, opts: LiveOpts) -> Result<()> {Cmd::Mode(m) => core.view_mode = m,Cmd::Bounces(b) => core.bounces = b,Cmd::Scale(s) => core.set_scale(s),+ Cmd::Resize(w, h) => {+ let t = Instant::now();+ match core.resize(w, h) {+ Ok(()) => {+ staging = staging_for(&core);+ eprintln!("live: resized to {}x{} in {:.1} ms", core.w, core.h, t.elapsed().as_secs_f64() * 1e3);+ }+ Err(e) => eprintln!("live: resize: {e:#}"),+ }+ }Cmd::Event(kind, payload) => {if let Err(e) = game.event(&mut core, &kind, payload) {eprintln!("live: event {kind} failed: {e:#}");@@ -123,7 +132,7 @@ pub fn run(presets: &Path, opts: LiveOpts) -> Result<()> {let pending = !snapshots.is_empty();core.render(spp, |e, out| {if pending {- e.copy_buffer_to_buffer(out, 0, &staging, 0, (w * h * 4) as u64);+ e.copy_buffer_to_buffer(out, 0, &staging, 0, staging.size());}});game.click_shown();@@ -157,7 +166,7 @@ pub fn run(presets: &Path, opts: LiveOpts) -> Result<()> {}let _ = std::fs::write(path, bytemuck::cast_slice(hdr.as_deref().unwrap_or(&[])));} else {- save_bgra(path, &px, w, h);+ save_bgra(path, &px, core.w, core.h);}eprintln!("live: snapshot {} at history {hist} ({spp} spp/frame, GPU {:.2} ms, scale {:.2})", path.display(), core.gpu_ms, core.render_scale);false@@ -277,6 +286,7 @@ pub fn parse_cmd(line: &str) -> Option<Cmd> {"bounces" => Cmd::Bounces(v["bounces"].as_u64()?.clamp(1, 16) as u32),"spp" => Cmd::SppCap(v["max"].as_u64()?.clamp(1, 16) as u32),"scale" => Cmd::Scale(v["scale"].as_f64()? as f32),+ "resize" => Cmd::Resize(v["width"].as_u64()? as u32, v["height"].as_u64()? as u32),"sync" => Cmd::Sync(v["id"].as_str().map(str::to_string).unwrap_or_else(|| v["id"].to_string()), v["frames"].as_u64().unwrap_or(1) as u32),"quit" => Cmd::Quit,_ => return None,diff --git a/renderer/src/live/targets.rs b/renderer/src/live/targets.rsindex 1f184d4..5aa6d45 100644--- a/renderer/src/live/targets.rs+++ b/renderer/src/live/targets.rs@@ -104,9 +104,13 @@ impl Passes {}}-/// Screen-size targets shared across scene reloads.+/// The view's targets: every buffer that follows its size (the trace's samples, what the kernel leaves the passes,+/// the passes' own, the output), the radiance cache, the passes' parameters and tone-map table, and the bind groups+/// over them. A scene reload leaves them; another size makes the ones that follow it again (`resize`).pub struct Targets {pub(super) params: wgpu::Buffer,+ /// The trace's samples, a `Pixel` a pixel (`gpu::Uploaded::accum` is a handle of it, for the scene's bind group).+ pub(super) accum: wgpu::Buffer,/// The passes' own buffers (`layout::RESOURCES`' `Own`), by binding: what each holds and when is live.wgsl's/// table ("The live passes' buffers").pub(super) bufs: Vec<(u32, Buf)>,@@ -116,20 +120,27 @@ pub struct Targets {/// a trace: the specular-lobe rays (`refl`), motion vectors per traced pixel (pathtrace.wgsl `motion_out`) and the/// deterministic direct light per traced pixel (`direct_out`).pub kernel: gpu::KernelBufs,+ /// Translucent particles per traced pixel (`gpu::Gpu::translucent_low`): made for the first scene that draws them.+ pub(super) translucent_low: Option<wgpu::Buffer>,pub(super) lut_tex: wgpu::Texture,pub(super) lut_view: wgpu::TextureView,pub(super) sampler: wgpu::Sampler,+ /// The bind group of each pass, in `Passes::pipes`' order.+ pub(super) bgs: Vec<wgpu::BindGroup>,+ size: (u32, u32),+}++/// What a view of `w` x `h` holds of each of the kernel's four buffers that follow its size, bytes (`gpu::KernelBufs`:+/// the specular rays, the motion vectors, the direct light, the light tiles' lists).+fn kernel_bytes(w: u32, h: u32) -> [u64; 4] {+ let n = (w * h) as u64;+ [n * 32, n * 16, n * 16, layout::light_lists(w, h) as u64 * 16]}impl Targets {/// For a view of `w` x `h` and a radiance cache of `cache` entries.- pub(super) fn new(g: &gpu::Gpu, w: u32, h: u32, lut: &[u16], cache: u64) -> Targets {+ pub(super) fn new(g: &gpu::Gpu, passes: &Passes, w: u32, h: u32, lut: &[u16], cache: u64) -> Targets {let d = &g.device;- let n = (w * h) as u64;- let sb = |label: &str, bytes: u64| d.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size: bytes, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false });- let quarter = (w.div_ceil(4) * h.div_ceil(4)) as u64;- let texels = |j: u32| bloom_dim(w, h, j).0 as u64 * bloom_dim(w, h, j).1 as u64;- let bloom_texels = (0..5).map(texels).sum::<u64>() + (0..6).map(|k| texels(bloom_stage_level(k))).sum::<u64>();let lut_tex = d.create_texture(&wgpu::TextureDescriptor {label: Some("tonemap lut"),size: wgpu::Extent3d { width: LUT, height: LUT, depth_or_array_layers: LUT },@@ -146,7 +157,47 @@ impl Targets {wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(LUT * 8), rows_per_image: Some(LUT) },wgpu::Extent3d { width: LUT, height: LUT, depth_or_array_layers: LUT },);- // The passes' own buffers, in binding order.+ let (bufs, out) = Self::own(d, w, h);+ let [refl, motion, direct, lists] = kernel_bytes(w, h);+ let mut t = Targets {+ params: d.create_buffer(&wgpu::BufferDescriptor { label: Some("live params"), size: std::mem::size_of::<LiveParams>() as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }),+ accum: g.accum_buffer(w, h),+ bufs,+ out,+ kernel: gpu::KernelBufs::new(d, g.merged, g.guard_room(), cache, refl, motion, direct, lists),+ translucent_low: None,+ lut_view: lut_tex.create_view(&Default::default()),+ lut_tex,+ sampler: d.create_sampler(&wgpu::SamplerDescriptor { mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, ..Default::default() }),+ bgs: vec![],+ size: (w, h),+ };+ t.bgs = t.bind_groups(d, passes);+ t+ }++ /// For another size: what follows it is made again (the samples, the passes' own buffers and the output, the+ /// kernel's four, the translucent particles'), with the bind groups over them. The radiance cache, which is the+ /// world's, the passes' parameters and the tone-map table stay. (The merged layout keeps the cache in one buffer+ /// with the rest: it starts empty.)+ pub(super) fn resize(&mut self, g: &gpu::Gpu, passes: &Passes, w: u32, h: u32) {+ let d = &g.device;+ (self.bufs, self.out) = Self::own(d, w, h);+ self.accum = g.accum_buffer(w, h);+ let [refl, motion, direct, lists] = kernel_bytes(w, h);+ self.kernel = self.kernel.resized(d, refl, motion, direct, lists);+ self.translucent_low = None;+ self.size = (w, h);+ self.bgs = self.bind_groups(d, passes);+ }++ /// The passes' own buffers for a view of `w` x `h`, in binding order, and the output among them.+ fn own(d: &wgpu::Device, w: u32, h: u32) -> (Vec<(u32, Buf)>, wgpu::Buffer) {+ let n = (w * h) as u64;+ let sb = |label: &str, bytes: u64| d.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size: bytes, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false });+ let quarter = (w.div_ceil(4) * h.div_ceil(4)) as u64;+ let texels = |j: u32| bloom_dim(w, h, j).0 as u64 * bloom_dim(w, h, j).1 as u64;+ let bloom_texels = (0..5).map(texels).sum::<u64>() + (0..6).map(|k| texels(bloom_stage_level(k))).sum::<u64>();let bufs: Vec<(u32, Buf)> = layout::BINDINGS.iter().filter_map(|b| {@@ -162,15 +213,13 @@ impl Targets {}).collect();let out = bufs.iter().find(|b| b.0 == layout::binding("out_px").binding).expect("out_px").1.buffer.clone();- Targets {- params: d.create_buffer(&wgpu::BufferDescriptor { label: Some("live params"), size: std::mem::size_of::<LiveParams>() as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }),- bufs,- out,- kernel: gpu::KernelBufs::new(d, g.merged, g.guard_room(), cache, n * 32, n * 16, n * 16, layout::light_lists(w, h) as u64 * 16),- lut_view: lut_tex.create_view(&Default::default()),- lut_tex,- sampler: d.create_sampler(&wgpu::SamplerDescriptor { mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, ..Default::default() }),- }+ (bufs, out)+ }++ /// The buffer translucent particles are drawn into below full resolution, made on first use.+ pub(super) fn translucent_low(&mut self, g: &gpu::Gpu) -> &wgpu::Buffer {+ let (w, h) = self.size;+ self.translucent_low.get_or_insert_with(|| g.translucent_low(w, h))}/// The buffer live.wgsl binds as `name` (the passes' own, or the kernel's).@@ -189,12 +238,12 @@ impl Targets {}}- /// The bind group of each pass, in `Passes::pipes`' order (`sample`: the trace's samples).- pub(super) fn bind_groups(&self, d: &wgpu::Device, passes: &Passes, sample: &wgpu::Buffer) -> Vec<wgpu::BindGroup> {+ /// The bind group of each pass, in `Passes::pipes`' order.+ fn bind_groups(&self, d: &wgpu::Device, passes: &Passes) -> Vec<wgpu::BindGroup> {let entry = |b: &'_ layout::Binding| -> wgpu::BindGroupEntry<'_> {let resource = match layout::resource(b) {layout::Res::Params => self.params.as_entire_binding(),- layout::Res::Samples => sample.as_entire_binding(),+ layout::Res::Samples => self.accum.as_entire_binding(),layout::Res::Lut => wgpu::BindingResource::TextureView(&self.lut_view),layout::Res::LutSampler => wgpu::BindingResource::Sampler(&self.sampler),_ => self.buf_at(b).binding(),diff --git a/renderer/src/view.rs b/renderer/src/view.rsindex bf68357..12d5be9 100644--- a/renderer/src/view.rs+++ b/renderer/src/view.rs@@ -5,7 +5,8 @@//! [--launch '{..}'] [--store <dir>] [--pick <dir|file>[,...]]//!//! The game runs in this process (script.rs): its code builds the scene, key bindings and clicks run its handlers, its-//! frame script animates. `view` is the same window.+//! frame script animates. `view` is the same window. The view is the window's pixels: resizing the window, or moving+//! it to a display of another density, resizes the view (`fit`).//!//! A game that reads input (`pointer` in its definition; docs/RUNTIME.md "Input") has the keys, the pointer and the//! camera to itself: the window sends it an `input` message every frame and keeps none of the controls below but@@ -20,6 +21,7 @@//! Controls: left-drag orbit · right/shift-drag pan · wheel zoom · WASD/QE fly · R reset camera · 1/2/4/8 cap spp,//! 0 adaptive · P snapshot · Esc quit. Scripted over stdio://! stdin JSON lines: {"cmd":"event","type":t,"payload":{..}} | {"cmd":"camera",...} | {"cmd":"snapshot","path":p} | {"cmd":"quit"}+//! | {"cmd":"resize","width":w,"height":h} (the window's size, pixels)//! | {"cmd":"host","messages":[{"t":..}, ..]}//! stdout JSON lines: {"type":"ready"} | {"type":"click","u":..,"v":..,"cam":{..},"seq":n} | {"type":"key","key":"L"}//! | {"type":"host","messages":[..]} (what the game posted)@@ -35,7 +37,7 @@ use std::path::{Path, PathBuf};use std::sync::{mpsc, Arc};use std::time::{Duration, Instant};use winit::application::ApplicationHandler;-use winit::dpi::{LogicalSize, PhysicalPosition};+use winit::dpi::{LogicalSize, PhysicalPosition, PhysicalSize};use winit::event::{DeviceEvent, DeviceId, ElementState, MouseButton, MouseScrollDelta, WindowEvent};use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};use winit::keyboard::{Key, KeyCode, ModifiersState, NamedKey, PhysicalKey};@@ -96,7 +98,12 @@ struct State {config: wgpu::SurfaceConfiguration,core: LiveCore,blit: wgpu::RenderPipeline,+ blit_layout: wgpu::BindGroupLayout,+ /// The view's and the surface's sizes for the blit (`BLIT`'s `size`).+ blit_size: wgpu::Buffer,blit_bg: wgpu::BindGroup,+ /// The last frame had a surface to draw on (`acquire`): its present paces the loop.+ shown: bool,home: Orbit,orbit: Orbit,tan: f32,@@ -195,7 +202,7 @@ impl App {fn init(&mut self, el: &ActiveEventLoop) -> Result<()> {let a = &self.args;let window = Arc::new(- el.create_window(Window::default_attributes().with_title("ThreeRT live").with_inner_size(LogicalSize::new(a.width, a.height)).with_resizable(false))?,+ el.create_window(Window::default_attributes().with_title("ThreeRT live").with_inner_size(LogicalSize::new(a.width, a.height)))?,);let g = gpu::Gpu::new()?;let surface = g.instance.create_surface(window.clone())?;@@ -215,8 +222,8 @@ impl App {color_space: Default::default(),};surface.configure(&g.device, &config);- // The view is the window's physical pixels (`--width` / `--height` are its size in points): the temporal upscaler- // resolves to the display, and nothing is stretched after it.+ // The view is the window's physical pixels (`--width` / `--height` are its first size in points): the temporal+ // upscaler resolves to the display, and nothing is stretched after it.let (vw, vh) = (config.width, config.height);let (mut game, mut core) = GameSession::start(&a.bundle, &a.room, &a.assets, g, &a.presets, vw, vh)?;// The host channel: how the game was opened, once after setup.@@ -227,35 +234,28 @@ impl App {if let Some(p) = &pointer {eprintln!("view: the game reads input (pointer: {p}){}", if p == "look" { ": click to capture the pointer, Esc lets go" } else { "" });}- core.set_display_scale(window.scale_factor() as f32);core.bounces = a.bounces;- if let Some(s) = a.scale {- core.set_scale(s);- }+ core.set_scale(a.scale.unwrap_or(0.0));+ core.set_display_scale(window.scale_factor() as f32);let d = &core.g.device;let module = d.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("blit"), source: wgpu::ShaderSource::Wgsl(BLIT.into()) });- let layout = d.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {- label: None,- entries: &[wgpu::BindGroupLayoutEntry {- binding: 0,- visibility: wgpu::ShaderStages::FRAGMENT,- ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only: true }, has_dynamic_offset: false, min_binding_size: None },- count: None,- }],- });+ let buffer = |binding, ty| wgpu::BindGroupLayoutEntry { binding, visibility: wgpu::ShaderStages::FRAGMENT, ty: wgpu::BindingType::Buffer { ty, has_dynamic_offset: false, min_binding_size: None }, count: None };+ let layout = d.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: None, entries: &[buffer(0, wgpu::BufferBindingType::Storage { read_only: true }), buffer(1, wgpu::BufferBindingType::Uniform)] });let pl = d.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&layout)], immediate_size: 0 });let blit = d.create_render_pipeline(&wgpu::RenderPipelineDescriptor {label: Some("blit"),layout: Some(&pl),vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() },- fragment: Some(wgpu::FragmentState { module: &module, entry_point: Some("fs"), targets: &[Some(format.into())], compilation_options: wgpu::PipelineCompilationOptions { constants: &[("W", vw as f64), ("H", vh as f64), ("SW", config.width as f64), ("SH", config.height as f64)], ..Default::default() } }),+ fragment: Some(wgpu::FragmentState { module: &module, entry_point: Some("fs"), targets: &[Some(format.into())], compilation_options: Default::default() }),primitive: Default::default(),depth_stencil: None,multisample: Default::default(),multiview_mask: None,cache: None,});- let blit_bg = d.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: core.targets.out.as_entire_binding() }] });+ let blit_size = d.create_buffer(&wgpu::BufferDescriptor { label: Some("blit size"), size: 16, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });+ core.g.queue.write_buffer(&blit_size, 0, bytemuck::cast_slice(&[vw as f32, vh as f32, config.width as f32, config.height as f32]));+ let blit_bg = blit_bind_group(d, &layout, &core.targets.out, &blit_size);let cam = core.scene_camera();let home = Orbit::from_camera(&cam);eprintln!("view: {}x{} ({}x{} points) on {} ({}), {:?}", vw, vh, a.width, a.height, core.g.adapter_info.name, if core.g.hwrt { "HW RT" } else { "BVH" }, format);@@ -266,7 +266,10 @@ impl App {config,core,blit,+ blit_layout: layout,+ blit_size,blit_bg,+ shown: false,home,orbit: home,tan: cam.tan_half_fov,@@ -454,6 +457,8 @@ impl ApplicationHandler for App {s.keys.remove(&name);}}+ // A display of another density (the window's pixels follow: `fit`).+ WindowEvent::ScaleFactorChanged { scale_factor, .. } => s.core.set_display_scale(scale_factor as f32),WindowEvent::RedrawRequested => {if let Err(e) = frame(s, &self.cmds, self.services.as_mut(), &self.args, fps) {eprintln!("view: {e:#}");@@ -476,10 +481,16 @@ impl ApplicationHandler for App {}fn about_to_wait(&mut self, el: &ActiveEventLoop) {+ let Some(s) = &self.state else { return };// Present on every vsync (Fifo blocks); `frame` decides whether to render a new image or re-show the last.- if let Some(s) = &self.state {+ // With nothing to draw on (the window covered or minimised) no present blocks: the loop waits for the next+ // content frame's time, at which the game's frame runs as ever.+ let due = s.last + Duration::from_secs_f64(1.0 / self.args.fps as f64);+ if s.shown || Instant::now() >= due {s.window.request_redraw();el.set_control_flow(ControlFlow::Poll);+ } else {+ el.set_control_flow(ControlFlow::WaitUntil(due));}}}@@ -493,9 +504,68 @@ fn button_number(b: MouseButton) -> Option<u8> {}}+/// The surface and the view at the window's size, once the window's pixels are no longer the surface's (it was+/// resized, or moved to a display of another density): whether the view changed. Nothing to fit while the window has+/// no pixels (minimised). A size the device does not hold as a view: the view stays, stretched to the window.+fn fit(s: &mut State) -> bool {+ let size = s.window.inner_size();+ if size.width == 0 || size.height == 0 || (size.width, size.height) == (s.config.width, s.config.height) {+ return false;+ }+ (s.config.width, s.config.height) = (size.width, size.height);+ s.surface.configure(&s.core.g.device, &s.config);+ let before = (s.core.w, s.core.h);+ if let Err(e) = s.core.resize(size.width, size.height) {+ eprintln!("view: {e:#}");+ }+ s.core.g.queue.write_buffer(&s.blit_size, 0, bytemuck::cast_slice(&[s.core.w as f32, s.core.h as f32, size.width as f32, size.height as f32]));+ s.blit_bg = blit_bind_group(&s.core.g.device, &s.blit_layout, &s.core.targets.out, &s.blit_size);+ (s.core.w, s.core.h) != before+}++/// The surface's texture to draw this frame on, each answer of `get_current_texture` taken as wgpu says. None when+/// there is nothing to draw on for now: the window has no pixels (minimised) or is covered, or its surface was no+/// longer the window's and is configured again (made again, if lost) for the next frame. Said once when a window+/// that was drawn no longer is: a driver that waits for a snapshot of a covered window sees why none comes.+fn acquire(s: &mut State) -> Result<Option<wgpu::SurfaceTexture>> {+ use wgpu::CurrentSurfaceTexture as T;+ let size = s.window.inner_size();+ let (tex, why) = if size.width == 0 || size.height == 0 {+ (None, "no pixels")+ } else {+ match s.surface.get_current_texture() {+ // (Suboptimal: another size, which `fit` configures before the next frame.)+ T::Success(t) | T::Suboptimal(t) => (Some(t), ""),+ T::Timeout => (None, "timeout"),+ T::Occluded => (None, "occluded"),+ T::Outdated => {+ s.surface.configure(&s.core.g.device, &s.config);+ (None, "outdated")+ }+ T::Lost => {+ s.surface = s.core.g.instance.create_surface(s.window.clone())?;+ s.surface.configure(&s.core.g.device, &s.config);+ (None, "lost")+ }+ T::Validation => return Err(anyhow::anyhow!("surface: a validation error")),+ }+ };+ if s.shown && tex.is_none() {+ eprintln!("view: nothing to draw on ({why})");+ }+ s.shown = tex.is_some();+ Ok(tex)+}++fn blit_bind_group(d: &wgpu::Device, layout: &wgpu::BindGroupLayout, out: &wgpu::Buffer, size: &wgpu::Buffer) -> wgpu::BindGroup {+ d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("blit"), layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: out.as_entire_binding() }, wgpu::BindGroupEntry { binding: 1, resource: size.as_entire_binding() }] })+}+fn frame(s: &mut State, cmds: &mpsc::Receiver<Cmd>, services: &mut dyn HostServices, args: &ViewArgs, fps: u32) -> Result<()> {- // Content runs at `fps` regardless of the display's refresh rate (120 Hz panels re-show the last image).- let render_new = s.last.elapsed() >= Duration::from_secs_f64(1.0 / fps as f64) - Duration::from_millis(2);+ let resized = fit(s);+ // Content runs at `fps` regardless of the display's refresh rate (120 Hz panels re-show the last image; a resized+ // view has none).+ let render_new = resized || s.last.elapsed() >= Duration::from_secs_f64(1.0 / fps as f64) - Duration::from_millis(2);if !render_new {return reshow(s);}@@ -524,6 +594,10 @@ fn frame(s: &mut State, cmds: &mpsc::Receiver<Cmd>, services: &mut dyn HostServi}Cmd::SppCap(n) => s.spp_cap = n,Cmd::Scale(v) => s.core.set_scale(v),+ Cmd::Resize(w, h) => {+ // The window's size; the view follows it (`fit`).+ let _ = s.window.request_inner_size(PhysicalSize::new(w, h));+ }Cmd::Event(kind, payload) => {let cam = s.core.scene_camera();s.game.event(&mut s.core, &kind, payload)?;@@ -602,13 +676,8 @@ fn frame(s: &mut State, cmds: &mpsc::Receiver<Cmd>, services: &mut dyn HostServi}}- let tex = match s.surface.get_current_texture() {- wgpu::CurrentSurfaceTexture::Success(t) | wgpu::CurrentSurfaceTexture::Suboptimal(t) => t,- other => {- s.surface.configure(&s.core.g.device, &s.config);- return Err(anyhow::anyhow!("surface: {other:?}"));- }- };+ // (Nothing to draw on: the game's frame ran.)+ let Some(tex) = acquire(s)? else { return Ok(()) };let view = tex.texture.create_view(&Default::default());let (blit, bg) = (&s.blit, &s.blit_bg);let snap = s.snapshot.take().map(|p| {@@ -691,10 +760,7 @@ fn follow_game_camera(s: &mut State, before: Camera) {/// Re-present the last rendered image (no path tracing) on refreshes between content frames.fn reshow(s: &mut State) -> Result<()> {- let tex = match s.surface.get_current_texture() {- wgpu::CurrentSurfaceTexture::Success(t) | wgpu::CurrentSurfaceTexture::Suboptimal(t) => t,- _ => return Ok(()),- };+ let Some(tex) = acquire(s)? else { return Ok(()) };let view = tex.texture.create_view(&Default::default());let mut e = s.core.g.device.create_command_encoder(&Default::default());{@@ -717,11 +783,9 @@ fn reshow(s: &mut State) -> Result<()> {}const BLIT: &str = r#"-override W: f32 = 1280.0;-override H: f32 = 720.0;-override SW: f32 = 1280.0;-override SH: f32 = 720.0;+struct Size { view: vec2<f32>, surface: vec2<f32> }@group(0) @binding(0) var<storage, read> px: array<u32>;+@group(0) @binding(1) var<uniform> size: Size;@vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {let p = vec2<f32>(f32((i << 1u) & 2u), f32(i & 2u));@@ -729,15 +793,13 @@ override SH: f32 = 720.0;}fn texel(x: i32, y: i32) -> vec4<f32> {- let c = px[u32(clamp(y, 0, i32(H) - 1)) * u32(W) + u32(clamp(x, 0, i32(W) - 1))];+ let c = px[u32(clamp(y, 0, i32(size.view.y) - 1)) * u32(size.view.x) + u32(clamp(x, 0, i32(size.view.x) - 1))];return vec4<f32>(f32((c >> 16u) & 255u), f32((c >> 8u) & 255u), f32(c & 255u), 255.0) / 255.0;}@fragment fn fs(@builtin(position) p: vec4<f32>) -> @location(0) vec4<f32> {- // The view's pixels are the window's (1 : 1); bilinear if the window moved to a display of another density.- let dims = vec2<f32>(W, H);- let uv = p.xy / vec2<f32>(SW, SH);- let q = uv * dims - 0.5;+ // The view's pixels are the window's (1 : 1); bilinear for a view that could not take the window's size (`fit`).+ let q = p.xy / size.surface * size.view - 0.5;let f = fract(q);let i = vec2<i32>(floor(q));let a = mix(texel(i.x, i.y), texel(i.x + 1, i.y), f.x);