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.

42.0 KB
Raw Blame
//! Native real-time viewer window: the live renderer (1-N spp HW-RT path tracing per frame + temporal accumulation +
//! denoise + UE post) presented straight to a vsync'd swapchain at 60 fps. No encoding, no network.
//!
//!   threert-render play <game bundle.js> [--assets <dir>] [--room id] [--width 1280 --height 720 --fps 60]
//!                       [--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. 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
//! Esc. With `pointer: "look"` a click captures the pointer (its motion is the game's look), Esc lets go of it, and
//! Esc again quits. The window is the app of the host channel: `--launch '{"room":"K7Q4MZ"}'` is the `launch`
//! message, `--sensitivity 1.5` scales the look, `--hud-log` prints the HUD the game describes (the window draws
//! none; a selectable table's rows are chosen on stdin with a `hud.choose` host message, which it prints), the game's `net.*` messages are the binary's sockets and HTTP (src/net.rs), and its `audio.*` messages are
//! played (src/audio, the `audio` feature: the ears are the camera of each frame). Its `files.*` and `store.*` are
//! answered from `--pick <dir|file>[,...]` (the player's picks, in order) and `--store <dir>` (the game's storage,
//! `<assets>/.threert/store` by default; `user:` assets resolve there): src/userfiles.rs.
//!
//! 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)

use crate::gpu;
use crate::host::{launch_message_with_caps, HostServices, InputTracker};
use crate::live::{next_spp, parse_cmd, parse_scale, save_bgra, Camera, Cmd, LiveCore};
use crate::script::GameSession;
use anyhow::Result;
use glam::Vec3;
use std::io::{BufRead, Write};
use std::path::{Path, PathBuf};
use std::sync::{mpsc, Arc};
use std::time::{Duration, Instant};
use winit::application::ApplicationHandler;
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};
use winit::window::{CursorGrabMode, Window, WindowId};

pub struct ViewArgs {
    /// `--quality`, `--reconstruction`, `--frame-generation`, `--latency` (live/rendering.rs).
    pub rendering: crate::live::RenderingRequest,
    /// Game bundle to run in-process.
    pub bundle: PathBuf,
    /// Asset root the scene's model / texture paths resolve against.
    pub assets: PathBuf,
    pub room: String,
    pub presets: PathBuf,
    pub width: u32,
    pub height: u32,
    pub fps: u32,
    pub bounces: u32,
    /// Render scale; None = dynamic resolution (default).
    pub scale: Option<f32>,
    /// `--launch`: the `params` of the host channel's `launch` message.
    pub launch: Option<serde_json::Value>,
    /// `--hud-log`: the HUD the game describes, printed when it changes.
    pub hud_log: bool,
    /// `--sensitivity`: scales the pointer's motion into the game's look (1: `host::LOOK_RADIANS` a count).
    pub sensitivity: f32,
    /// `--store <dir>`: the game's store (`store.*`, `user:` assets; docs/RUNTIME.md "Files"); `<assets>/.threert/store`
    /// by default.
    pub store: PathBuf,
    /// `--pick a,b`: what the player picks, in order, for the game's `files.pick` requests (none: `"unsupported"`).
    pub pick: Vec<PathBuf>,
}

/// Editor-style orbit camera around a target point.
#[derive(Clone, Copy)]
struct Orbit {
    target: Vec3,
    yaw: f32,
    pitch: f32,
    dist: f32,
}

impl Orbit {
    fn from_camera(c: &Camera) -> Orbit {
        let dist = c.pos.length().clamp(1.0, 50.0);
        let target = c.pos + c.fwd * dist;
        let off = c.pos - target;
        Orbit { target, yaw: off.x.atan2(off.z), pitch: (off.y / dist).clamp(-1.0, 1.0).asin(), dist }
    }
    fn camera(&self, tan: f32) -> Camera {
        let cp = self.pitch.cos();
        let pos = self.target + Vec3::new(self.yaw.sin() * cp, self.pitch.sin(), self.yaw.cos() * cp) * self.dist;
        Camera::look_at(pos, self.target, tan)
    }
}

struct State {
    window: Arc<Window>,
    surface: wgpu::Surface<'static>,
    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,
    cursor: PhysicalPosition<f64>,
    press: Option<(MouseButton, PhysicalPosition<f64>, bool)>,
    mods: ModifiersState,
    keys: std::collections::HashSet<String>,
    spp: u32,
    spp_cap: u32,
    /// User-selected bounce limit; the frame governor may lower bounces below it to hold the frame rate.
    max_bounces: u32,
    status: String,
    frames: u32,
    stats_t: Instant,
    fps: f32,
    last: Instant,
    snapshot: Option<PathBuf>,
    game: GameSession,
    /// The game reads input (`pointer`): the keys and the pointer between two frames. None: the window's own
    /// controls, as for every game before input.
    input: Option<InputTracker>,
    /// `pointer: "look"`: a click captures the pointer.
    look: bool,
    /// The game's sound (the `audio.*` messages; the ears are the camera of the frame).
    #[cfg(feature = "audio")]
    audio: crate::audio::Audio,
}

impl State {
    /// Captures the pointer for the game's look (hidden, held in the window), or lets go of it.
    fn capture(&mut self, on: bool) {
        let Some(i) = self.input.as_mut() else { return };
        if on == i.captured {
            return;
        }
        if on {
            // (Locked where the system has it, macOS among them; held inside the window elsewhere.)
            if self.window.set_cursor_grab(CursorGrabMode::Locked).or_else(|_| self.window.set_cursor_grab(CursorGrabMode::Confined)).is_err() {
                return eprintln!("view: the pointer cannot be captured here");
            }
            self.window.set_cursor_visible(false);
        } else {
            let _ = self.window.set_cursor_grab(CursorGrabMode::None);
            self.window.set_cursor_visible(true);
        }
        i.captured = on;
    }
}

/// A key by its place on the keyboard, as game code names it (packages/gameplay/src/input.ts).
fn key_name(code: KeyCode) -> Option<String> {
    use KeyCode::*;
    let fixed = match code {
        Space => "Space",
        ShiftLeft | ShiftRight => "Shift",
        ControlLeft | ControlRight => "Ctrl",
        AltLeft | AltRight => "Alt",
        SuperLeft | SuperRight => "Meta",
        Tab => "Tab",
        Enter | NumpadEnter => "Enter",
        Escape => "Escape",
        Backspace => "Backspace",
        ArrowLeft => "Left",
        ArrowRight => "Right",
        ArrowUp => "Up",
        ArrowDown => "Down",
        Minus | Equal | BracketLeft | BracketRight | Semicolon | Quote | Comma | Period | Slash | Backslash | Backquote => return Some(format!("{code:?}")),
        _ => {
            // KeyW -> "W", Digit1 -> "1", F5 -> "F5".
            let name = format!("{code:?}");
            return match name.strip_prefix("Key").or_else(|| name.strip_prefix("Digit")) {
                Some(k) if k.len() == 1 => Some(k.to_string()),
                _ => (name.len() <= 3 && name.starts_with('F') && name[1..].parse::<u8>().is_ok()).then_some(name),
            };
        }
    };
    Some(fixed.to_string())
}

struct App {
    args: ViewArgs,
    /// What the window offers the game beyond the picture (the binary's sockets and HTTP).
    services: Box<dyn HostServices>,
    cmds: mpsc::Receiver<Cmd>,
    state: Option<State>,
    error: Option<anyhow::Error>,
}

fn emit(v: serde_json::Value) {
    let mut out = std::io::stdout().lock();
    let _ = writeln!(out, "{v}");
    let _ = out.flush();
}

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)))?,
        );
        let g = gpu::Gpu::new()?;
        let surface = g.instance.create_surface(window.clone())?;
        let caps = surface.get_capabilities(&g.adapter);
        // The renderer outputs sRGB-encoded bytes already: present through a non-sRGB format.
        let format = caps.formats.iter().copied().find(|f| !f.is_srgb()).unwrap_or(caps.formats[0]);
        let size = window.inner_size();
        let config = wgpu::SurfaceConfiguration {
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            format,
            width: size.width.max(1),
            height: size.height.max(1),
            present_mode: wgpu::PresentMode::Fifo,
            desired_maximum_frame_latency: 2,
            alpha_mode: caps.alpha_modes[0],
            view_formats: vec![],
            color_space: Default::default(),
        };
        surface.configure(&g.device, &config);
        // 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.
        if let Err(e) = game.host_messages(&mut core, &[launch_message_with_caps(a.launch.as_ref(), &self.services.caps())]) {
            eprintln!("game: launch: {e:#}");
        }
        let pointer = game.host.pointer().map(String::from);
        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.bounces = a.bounces;
        core.set_scale(a.scale.unwrap_or(0.0));
        core.set_rendering(a.rendering.clone());
        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 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: Default::default() }),
            primitive: Default::default(),
            depth_stencil: None,
            multisample: Default::default(),
            multiview_mask: None,
            cache: None,
        });
        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);
        emit(serde_json::json!({ "type": "ready", "adapter": core.g.adapter_info.name, "hwrt": core.g.hwrt }));
        self.state = Some(State {
            window,
            surface,
            config,
            core,
            blit,
            blit_layout: layout,
            blit_size,
            blit_bg,
            shown: false,
            home,
            orbit: home,
            tan: cam.tan_half_fov,
            cursor: PhysicalPosition::new(0.0, 0.0),
            press: None,
            mods: ModifiersState::empty(),
            keys: Default::default(),
            spp: 1,
            spp_cap: 16,
            max_bounces: a.bounces,
            status: String::new(),
            frames: 0,
            stats_t: Instant::now(),
            fps: 0.0,
            last: Instant::now(),
            snapshot: None,
            game,
            input: pointer.is_some().then(InputTracker::new),
            look: pointer.as_deref() == Some("look"),
            #[cfg(feature = "audio")]
            audio: {
                let mut au = crate::audio::Audio::new();
                au.open(&a.assets);
                au
            },
        });
        Ok(())
    }
}

impl ApplicationHandler for App {
    fn resumed(&mut self, el: &ActiveEventLoop) {
        if self.state.is_none() {
            if let Err(e) = self.init(el) {
                self.error = Some(e);
                el.exit();
            }
        }
    }

    fn window_event(&mut self, el: &ActiveEventLoop, _id: WindowId, event: WindowEvent) {
        let fps = self.args.fps;
        let Some(s) = self.state.as_mut() else { return };
        match event {
            WindowEvent::CloseRequested => el.exit(),
            WindowEvent::ModifiersChanged(m) => s.mods = m.state(),
            WindowEvent::Focused(false) => {
                // (The keys' ups go to whoever has the keyboard now.)
                s.capture(false);
                if let Some(i) = s.input.as_mut() {
                    i.release_all();
                }
            }
            WindowEvent::CursorMoved { position, .. } => {
                let (dx, dy) = ((position.x - s.cursor.x) as f32, (position.y - s.cursor.y) as f32);
                s.cursor = position;
                if let Some(i) = s.input.as_mut() {
                    let size = s.window.inner_size();
                    i.pointer((position.x / size.width.max(1) as f64) as f32, (position.y / size.height.max(1) as f64) as f32);
                    // (The game's pointer: nothing orbits. A click is still a click: below.)
                    if let Some((_, start, moved)) = &mut s.press {
                        *moved |= (position.x - start.x).hypot(position.y - start.y) > 4.0 * s.window.scale_factor();
                    }
                    return;
                }
                let scale = s.window.scale_factor() as f32;
                if let Some((button, start, moved)) = &mut s.press {
                    if (position.x - start.x).hypot(position.y - start.y) > 4.0 * scale as f64 {
                        *moved = true;
                    }
                    if *moved {
                        let (dx, dy) = (dx / scale, dy / scale);
                        if *button == MouseButton::Right || s.mods.shift_key() {
                            let right = Vec3::new(s.orbit.yaw.cos(), 0.0, -s.orbit.yaw.sin());
                            let k = s.orbit.dist * 0.0015;
                            s.orbit.target += -right * dx * k + Vec3::Y * dy * k;
                        } else {
                            s.orbit.yaw -= dx * 0.005;
                            s.orbit.pitch = (s.orbit.pitch + dy * 0.004).clamp(-1.45, 1.45);
                        }
                    }
                }
            }
            WindowEvent::MouseInput { state, button, .. } if s.look => {
                // The pointer is the game's look: the first click captures it, and from then on the buttons are
                // the game's input (no `click` event: there is no place the pointer points at).
                let n = match button {
                    MouseButton::Left => 0,
                    MouseButton::Middle => 1,
                    MouseButton::Right => 2,
                    _ => return,
                };
                let captured = s.input.as_ref().is_some_and(|i| i.captured);
                if !captured && state == ElementState::Pressed {
                    s.capture(true);
                } else if let Some(i) = s.input.as_mut() {
                    // (An up always: of a button that went down while captured.)
                    if captured || state == ElementState::Released {
                        i.button(n, state == ElementState::Pressed);
                    }
                }
            }
            WindowEvent::MouseInput { state, button, .. } => match state {
                ElementState::Pressed => {
                    s.press = Some((button, s.cursor, false));
                    if let (Some(i), Some(n)) = (s.input.as_mut(), button_number(button)) {
                        i.button(n, true);
                    }
                }
                ElementState::Released => {
                    if let (Some(i), Some(n)) = (s.input.as_mut(), button_number(button)) {
                        i.button(n, false);
                    }
                    if let Some((MouseButton::Left, _, false)) = s.press.take() {
                        let size = s.window.inner_size();
                        let (u, v) = ((s.cursor.x / size.width as f64) as f32, (s.cursor.y / size.height as f64) as f32);
                        let mut meta = s.core.meta();
                        meta["type"] = "click".into();
                        meta["u"] = u.into();
                        meta["v"] = v.into();
                        emit(meta);
                        let cam = s.core.scene_camera();
                        if let Err(e) = s.game.click(&mut s.core, u, v) {
                            eprintln!("game: click failed: {e:#}");
                        }
                        follow_game_camera(s, cam);
                    }
                }
            },
            WindowEvent::MouseWheel { delta, .. } => {
                let dy = match delta {
                    MouseScrollDelta::LineDelta(_, y) => y * 40.0,
                    MouseScrollDelta::PixelDelta(p) => p.y as f32,
                };
                if let Some(i) = s.input.as_mut() {
                    return i.wheel(dy / 40.0);
                }
                s.orbit.dist = (s.orbit.dist * (-dy * 0.002).exp()).clamp(0.3, 100.0);
            }
            WindowEvent::KeyboardInput { event, .. } => {
                // The game's input: the key by its place on the keyboard, down or up.
                if let (Some(i), PhysicalKey::Code(code)) = (s.input.as_mut(), event.physical_key) {
                    if let Some(name) = key_name(code) {
                        i.key(&format!("{code:?}"), &name, event.state == ElementState::Pressed);
                    }
                }
                let name = match &event.logical_key {
                    Key::Character(c) => c.to_uppercase(),
                    Key::Named(NamedKey::Escape) => "Escape".into(),
                    Key::Named(NamedKey::Space) => "Space".into(),
                    _ => return,
                };
                if event.state == ElementState::Pressed {
                    let handler = s.game.host.handler_for_key(&name);
                    if let (Some(h), false) = (&handler, event.repeat) {
                        let cam = s.core.scene_camera();
                        if let Err(e) = s.game.event(&mut s.core, h, serde_json::json!({})) {
                            eprintln!("game: {h} failed: {e:#}");
                        }
                        follow_game_camera(s, cam);
                    } else if s.input.is_some() {
                        // The keys are the game's. Esc lets go of a captured pointer, and quits without one.
                        if name == "Escape" && !event.repeat {
                            if s.input.as_ref().is_some_and(|i| i.captured) {
                                s.capture(false);
                            } else {
                                el.exit();
                            }
                        }
                    } else if !event.repeat {
                        match name.as_str() {
                            "Escape" => el.exit(),
                            "R" => s.orbit = s.home,
                            "P" => s.snapshot = Some(PathBuf::from(format!("view-{}.png", s.core.frame))),
                            // Reconstruction (live/rendering.rs): M between ThreeRT's own and the best this device
                            // has (`auto`: MetalFX's joint denoiser on a Mac, DLSS on an RTX GPU), N through every method.
                            "M" | "N" => {
                                let next: crate::live::Reconstruction = if name == "N" {
                                    crate::live::next_method(&s.core.reconstruction()).into()
                                } else if s.core.reconstruction() == crate::live::Method::Builtin {
                                    crate::live::Reconstruction::Auto
                                } else {
                                    crate::live::Method::Builtin.into()
                                };
                                eprintln!("view: reconstruction {}", next.name());
                                s.core.set_reconstruction(next);
                            }
                            "0" => s.spp_cap = 16,
                            "1" | "2" | "4" | "8" => s.spp_cap = name.parse().unwrap(),
                            // F1..F6 style view modes on the number row with Alt held
                            "V" => s.core.view_mode = (s.core.view_mode + 1) % 6,
                            _ => {}
                        }
                        emit(serde_json::json!({ "type": "key", "key": name }));
                    }
                    s.keys.insert(name);
                } else {
                    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:#}");
                }
                if s.keys.contains("__quit") {
                    el.exit();
                }
            }
            _ => {}
        }
    }

    fn device_event(&mut self, _el: &ActiveEventLoop, _id: DeviceId, event: DeviceEvent) {
        // A captured pointer does not move: its motion comes from the device, and is the game's look.
        if let (DeviceEvent::MouseMotion { delta }, Some(s)) = (event, self.state.as_mut()) {
            if let Some(i) = s.input.as_mut().filter(|i| i.captured) {
                i.motion(delta.0 as f32, delta.1 as f32, self.args.sensitivity);
            }
        }
    }

    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.
        // 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));
        }
    }
}

fn button_number(b: MouseButton) -> Option<u8> {
    match b {
        MouseButton::Left => Some(0),
        MouseButton::Middle => Some(1),
        MouseButton::Right => Some(2),
        _ => None,
    }
}

/// 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<()> {
    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);
    }
    let dt = s.last.elapsed().as_secs_f32().min(0.1);
    s.last = Instant::now();
    while let Ok(c) = cmds.try_recv() {
        match c {
            Cmd::Camera(c) => s.orbit = Orbit::from_camera(&c),
            Cmd::Status(t) => s.status = t,
            Cmd::Snapshot(p, _, _) => s.snapshot = Some(p),
            Cmd::Sync(..) | Cmd::Lockstep(_) => {}
            Cmd::Step { cam, snapshot, .. } => {
                if let Some(c) = cam {
                    s.orbit = Orbit::from_camera(&c);
                }
                if let Some(p) = snapshot {
                    s.snapshot = Some(p);
                }
            }
            Cmd::Reset => s.core.reset_history(),
            Cmd::Time(t) => s.core.set_time(t),
            Cmd::Mode(m) => s.core.view_mode = m,
            Cmd::Bounces(b) => {
                s.max_bounces = b;
                s.core.bounces = b;
            }
            Cmd::SppCap(n) => s.spp_cap = n,
            Cmd::Rendering(r) => s.core.set_rendering(r),
            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)?;
                follow_game_camera(s, cam);
            }
            Cmd::Click(u, v) => {
                let cam = s.core.scene_camera();
                s.game.click(&mut s.core, u, v)?;
                follow_game_camera(s, cam);
            }
            Cmd::Host(messages) => {
                let cam = s.core.scene_camera();
                s.game.host_messages(&mut s.core, &messages)?;
                follow_game_camera(s, cam);
            }
            Cmd::Quit => {
                s.keys.insert("__quit".into());
            }
        }
    }
    // WASD / QE fly: move the orbit target in the view plane (the keys of a game that reads input are its own).
    if s.input.is_none() {
        let speed = s.orbit.dist * 0.8 * dt;
        let fwd = Vec3::new(-s.orbit.yaw.sin(), 0.0, -s.orbit.yaw.cos());
        let right = Vec3::new(s.orbit.yaw.cos(), 0.0, -s.orbit.yaw.sin());
        for (k, dir) in [("W", fwd), ("S", -fwd), ("D", right), ("A", -right), ("E", Vec3::Y), ("Q", -Vec3::Y)] {
            if s.keys.contains(k) {
                s.orbit.target += dir * speed;
            }
        }
    }
    let cam = s.core.scene_camera();
    s.core.advance_time(dt);
    // The host channel, app to game, before the frame script: the frame's input (for a game that reads it), then
    // what the services have (a batch of each socket's messages, answers to requests). One entry for all of it.
    let mut messages: Vec<serde_json::Value> = s.input.as_mut().map(|i| i.message()).into_iter().collect();
    messages.extend(services.poll());
    if let Err(e) = s.game.host_messages(&mut s.core, &messages) {
        eprintln!("game: host messages: {e:#}");
    }
    if let Err(e) = s.game.frame(&mut s.core, dt) {
        eprintln!("game: frame script: {e:#}");
    }
    // Game to app: what the game posted in this frame's entries (events among them).
    let posts = s.game.take_posts();
    for p in &posts {
        #[cfg(feature = "audio")]
        if s.audio.post(p) {
            continue;
        }
        services.post(p);
        if args.hud_log && p["t"] == "hud" {
            eprintln!("hud: {}", p["hud"]);
            // (The window draws no HUD: a menu's row is chosen on stdin, as an app that draws it sends the click.)
            for (item, title, rows) in crate::host::hud_selectables(&p["hud"]) {
                eprintln!("hud: selectable table {item} \"{title}\", {rows} rows: choose one with {}", serde_json::json!({ "cmd": "host", "messages": [crate::host::hud_choose_message(&item, 0)] }));
            }
        }
    }
    if !posts.is_empty() {
        // (A file the game stores is its length here, not tens of megabytes of base64.)
        emit(serde_json::json!({ "type": "host", "messages": posts.iter().map(crate::userfiles::without_payload).collect::<Vec<_>>() }));
    }
    // A game that reads input has the camera to itself (the view follows it with every commit); any other game is
    // looked at through the window's orbit camera, which follows the game's when a handler moves it.
    if s.input.is_none() {
        follow_game_camera(s, cam);
        s.core.set_camera(s.orbit.camera(s.tan));
    }
    #[cfg(feature = "audio")]
    {
        let c = s.core.cam;
        s.audio.listener(c.pos, c.fwd, c.right);
        for (level, text) in s.audio.take_log() {
            eprintln!("audio: {level}: {text}");
        }
    }

    // (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| {
        let buf = s.core.g.device.create_buffer(&wgpu::BufferDescriptor { label: None, size: (s.core.w * s.core.h * 4) as u64, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
        (p, buf)
    });
    s.core.render(s.spp, |e, out| {
        {
            let mut rp = e.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("blit"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &view, depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store } })],
                depth_stencil_attachment: None,
                timestamp_writes: None,
                occlusion_query_set: None,
                multiview_mask: None,
            });
            rp.set_pipeline(blit);
            rp.set_bind_group(0, bg, &[]);
            rp.draw(0..3, 0..1);
        }
        if let Some((_, buf)) = &snap {
            e.copy_buffer_to_buffer(out, 0, buf, 0, buf.size());
        }
    });
    s.window.pre_present_notify();
    s.core.g.queue.present(tex);
    if let Some((path, buf)) = snap {
        buf.slice(..).map_async(wgpu::MapMode::Read, |_| {});
        s.core.g.device.poll(wgpu::PollType::wait_indefinitely())?;
        let px = buf.slice(..).get_mapped_range()?.to_vec();
        save_bgra(&path, &px, s.core.w, s.core.h);
        emit(serde_json::json!({ "type": "snapshot", "path": path }));
    }
    // Frame governor (UE dynamic resolution first): render scale toward the budget; full resolution before extra
    // samples per frame; at the lowest scale and 1 spp still over budget, trade bounces (and give them back later).
    s.core.govern_resolution(fps);
    s.spp = if s.core.render_scale < 1.0 { 1 } else { next_spp(s.spp, s.core.gpu_ms, fps).min(s.spp_cap) };
    if s.core.frame % 30 == 1 {
        let budget = 1000.0 / fps as f32;
        let lowest = !s.core.dynamic_res || s.core.render_scale <= s.core.min_scale;
        if s.spp == 1 && lowest && s.core.gpu_ms > budget * 0.92 && s.core.bounces > 2 {
            s.core.bounces -= 1;
        } else if s.core.gpu_ms < budget * 0.55 && s.core.bounces < s.max_bounces {
            s.core.bounces += 1;
        }
    }
    s.frames += 1;
    if s.stats_t.elapsed() >= Duration::from_millis(500) {
        s.fps = s.frames as f32 / s.stats_t.elapsed().as_secs_f32();
        s.frames = 0;
        s.stats_t = Instant::now();
        let conv = if s.core.history_len >= 4096.0 { "converged".to_string() } else { format!("history {:.0}", s.core.history_len) };
        let g = &s.game;
        let status = [s.status.as_str(), g.status.as_str()].iter().filter(|t| !t.is_empty()).map(|t| format!("{t} · ")).collect::<String>() + &format!("frame script {:.2} ms", g.frame_ms);
        s.window.set_title(&format!(
            "ThreeRT live · {:.0} fps · {} spp/frame · GPU {:.1} ms · {} @ {:.0}% · {conv}{}",
            s.fps,
            s.spp,
            s.core.gpu_ms,
            reconstruction_label(&s.core.reconstruction_status()),
            s.core.render_scale * 100.0,
            if status.is_empty() { String::new() } else { format!(" · {status}") }
        ));
        let mut st = s.core.meta();
        st["type"] = "stats".into();
        st["fps"] = s.fps.into();
        st["spp"] = s.spp.into();
        emit(st);
    }
    Ok(())
}

/// A handler moved the game camera (e.g. a viewpoint switch): the viewer's orbit follows it.
fn follow_game_camera(s: &mut State, before: Camera) {
    let c = s.core.scene_camera();
    if c != before {
        s.home = Orbit::from_camera(&c);
        s.orbit = s.home;
        s.tan = c.tan_half_fov;
    }
}

/// Re-present the last rendered image (no path tracing) on refreshes between content frames.
fn reshow(s: &mut State) -> Result<()> {
    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());
    {
        let mut rp = e.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("reshow"),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &view, depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store } })],
            depth_stencil_attachment: None,
            timestamp_writes: None,
            occlusion_query_set: None,
            multiview_mask: None,
        });
        rp.set_pipeline(&s.blit);
        rp.set_bind_group(0, &s.blit_bg, &[]);
        rp.draw(0..3, 0..1);
    }
    s.core.g.queue.submit([e.finish()]);
    s.window.pre_present_notify();
    s.core.g.queue.present(tex);
    Ok(())
}

const BLIT: &str = r#"
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));
    return vec4<f32>(p * 2.0 - 1.0, 0.0, 1.0);
}

fn texel(x: i32, y: i32) -> vec4<f32> {
    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 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);
    let b = mix(texel(i.x, i.y + 1), texel(i.x + 1, i.y + 1), f.x);
    return mix(a, b, f.y);
}
"#;

/// Opens the window. `services`: what the app answers the game's posts with (`host::NoServices`: nothing).
pub fn run(args: ViewArgs, services: Box<dyn HostServices>) -> Result<()> {
    crate::script::set_asset_root(&args.assets);
    let (tx, rx) = mpsc::channel::<Cmd>();
    std::thread::spawn(move || {
        for line in std::io::stdin().lock().lines() {
            let Ok(line) = line else { break };
            let cmd = serde_json::from_str::<serde_json::Value>(&line).ok().and_then(|v| match v["cmd"].as_str() {
                Some("status") => Some(Cmd::Status(v["text"].as_str().unwrap_or_default().to_string())),
                _ => parse_cmd(&line),
            });
            if let Some(c) = cmd {
                if tx.send(c).is_err() {
                    break;
                }
            }
        }
    });
    let el = EventLoop::new()?;
    let mut app = App { args, services, cmds: rx, state: None, error: None };
    el.run_app(&mut app)?;
    if let Some(e) = app.error {
        return Err(e);
    }
    Ok(())
}

pub fn parse_args(args: &[String], presets: &Path) -> Result<ViewArgs> {
    let flag = |name: &str| args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned();
    let num = |name: &str, d: u32| flag(name).and_then(|v| v.parse().ok()).unwrap_or(d);
    Ok(ViewArgs {
        rendering: crate::live::RenderingRequest::from_flags(&flag)?,
        bundle: PathBuf::from(args.get(2).filter(|a| !a.starts_with("--")).ok_or_else(|| anyhow::anyhow!("game bundle required"))?),
        assets: PathBuf::from(flag("--assets").unwrap_or_else(|| ".".into())),
        room: flag("--room").unwrap_or_else(|| "local".into()),
        presets: presets.to_path_buf(),
        width: num("--width", 1280),
        height: num("--height", 720),
        fps: num("--fps", 60),
        bounces: num("--bounces", 4),
        scale: parse_scale(flag("--scale").as_deref(), None)?,
        launch: crate::live::parse_launch(flag("--launch").as_deref())?,
        hud_log: args.iter().any(|a| a == "--hud-log"),
        sensitivity: flag("--sensitivity").map(|v| v.parse::<f32>()).transpose()?.filter(|v| v.is_finite()).unwrap_or(1.0),
        store: flag("--store").map(PathBuf::from).unwrap_or_else(|| PathBuf::from(flag("--assets").unwrap_or_else(|| ".".into())).join(".threert/store")),
        pick: flag("--pick").map(|p| p.split(',').filter(|p| !p.is_empty()).map(PathBuf::from).collect()).unwrap_or_default(),
    })
}

/// The title's reconstruction: the method that ran, and the one asked for when it did not.
fn reconstruction_label(r: &crate::live::ReconstructionStatus) -> String {
    let active = r.active.as_deref().unwrap_or("builtin");
    match r.skipped.first() {
        Some((m, why, _)) if r.fallback.is_some() => format!("{active} ({m} {})", why.name()),
        _ => active.to_string(),
    }
}