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.

24.9 KB
Raw Blame
//! ThreeRT Live 3D Wallpaper Host for Omarchy / Hyprland (`wlr-layer-shell` + `threert-webgpu`).
//!
//! Renders standard `three/webgpu` + TSL scenes directly into a Wayland `Layer::Background`
//! swapchain in a single native process (zero browser/Chromium/DOM overhead), with:
//! - Automatic `omarchy-shell background setSuspended` handoff & clean restore on exit
//! - Event-driven Hyprland occlusion pause (0 FPS, 0% CPU/GPU when covered or DPMS off)
//! - AC/battery adaptive FPS and render-scale profiles
//! - Live Omarchy `colors.toml` theme palette injection (`globalThis.__wallpaper.theme`)
//! - Built-in headless mode & JSON telemetry for apples-to-apples benchmarking
use std::cell::{Cell, RefCell};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

use jsc::{Ctx, Value};
use smithay_client_toolkit::shell::wlr_layer::Layer;
use threert_webgpu as webgpu;

mod hypr;
mod omarchy;
mod wayland;

use hypr::OcclusionState;
use omarchy::{OmarchySuspendGuard, ThemeWatcher};
use wayland::WaylandWallpaper;

static SIG_STOP: AtomicBool = AtomicBool::new(false);

extern "C" fn handle_signal(_sig: libc::c_int) {
    SIG_STOP.store(true, Ordering::SeqCst);
}

thread_local! {
    static WAKE_AT: Cell<f64> = const { Cell::new(f64::INFINITY) };
    static WANT_FRAME: Cell<bool> = const { Cell::new(false) };
    static EXIT: Cell<Option<i32>> = const { Cell::new(None) };
    static SHOT: RefCell<Option<String>> = const { RefCell::new(None) };
    static RNG: Cell<u64> = const { Cell::new(0x9e37_79b9_7f4a_7c15) };
}

struct Opts {
    runtime: String,
    script: String,
    fps: f64,
    battery_fps: f64,
    render_scale: f64,
    battery_scale: f64,
    headless: Option<(u32, u32, f64)>,
    shot: Option<String>,
    shot_frame: u32,
    duration: Option<f64>,
    fixed_time: Option<f64>,
    omarchy: bool,
    occlusion_pause: bool,
    force_paused: bool,
    stats_json: Option<String>,
    output: Option<String>,
    layer: Layer,
    colors_path: Option<String>,
    assets_dir: Option<String>,
    scale_override: Option<f64>,
}

fn parse_opts() -> Opts {
    let args: Vec<String> = std::env::args().collect();
    let get = |k: &str| args.iter().position(|x| x == k).and_then(|i| args.get(i + 1)).cloned();
    let has = |k: &str| args.iter().any(|x| x == k);

    let headless = get("--headless").map(|s| {
        let (wh, dpr) = s.split_once('@').unwrap_or((&s, "1"));
        let (w, h) = wh.split_once('x').unwrap_or(("1440", "900"));
        (w.parse().unwrap_or(1440), h.parse().unwrap_or(900), dpr.parse().unwrap_or(1.0))
    });
    let layer = match get("--layer").as_deref() {
        Some("top") => Layer::Top,
        Some("bottom") => Layer::Bottom,
        _ => Layer::Background,
    };
    Opts {
        runtime: get("--runtime").unwrap_or_else(|| "out/webgpu/runtime.js".into()),
        script: get("--script").unwrap_or_else(|| "out/webgpu/wallpaper-demo.js".into()),
        fps: get("--fps").and_then(|s| s.parse().ok()).unwrap_or(60.0),
        battery_fps: get("--battery-fps").and_then(|s| s.parse().ok()).unwrap_or(24.0),
        render_scale: get("--render-scale").and_then(|s| s.parse().ok()).unwrap_or(1.0),
        battery_scale: get("--battery-scale").and_then(|s| s.parse().ok()).unwrap_or(0.75),
        headless,
        shot: get("--shot"),
        shot_frame: get("--shot-frame").and_then(|s| s.parse().ok()).unwrap_or(4),
        duration: get("--duration").and_then(|s| s.parse().ok()),
        fixed_time: get("--fixed-time").and_then(|s| s.parse().ok()),
        omarchy: has("--omarchy"),
        occlusion_pause: !has("--no-occlusion-pause"),
        force_paused: has("--force-paused"),
        stats_json: get("--stats-json"),
        output: get("--output"),
        layer,
        colors_path: get("--colors"),
        assets_dir: get("--assets"),
        scale_override: get("--scale").and_then(|s| s.parse().ok()),
    }
}

fn install_sys(c: Ctx, sys: Value, assets_dir: std::path::PathBuf) {
    let def = |name: &str, f: Value| sys.set(c, name, f);
    def("now", c.function(|c, _, _| Ok(c.num(rt::page_now()))));
    def("wakeAt", c.function(|c, _, a| {
        let t = a.first().map(|v| v.to_num(c)).unwrap_or(f64::INFINITY);
        WAKE_AT.with(|w| w.set(if t.is_nan() { f64::INFINITY } else { t }));
        Ok(c.undefined())
    }));
    def("requestFrame", c.function(|c, _, _| {
        WANT_FRAME.with(|w| w.set(true));
        Ok(c.undefined())
    }));
    def("log", c.function(|c, _, a| {
        let level = a.first().map(|v| v.to_string(c)).unwrap_or_default();
        let msg = a.get(1).map(|v| v.to_string(c)).unwrap_or_default();
        eprintln!("[{level}] {msg}");
        Ok(c.undefined())
    }));
    def("exit", c.function(|c, _, a| {
        EXIT.with(|e| e.set(Some(a.first().map(|v| v.to_i32(c)).unwrap_or(0))));
        Ok(c.undefined())
    }));
    def("shot", c.function(|c, _, a| {
        let path = a.first().map(|v| v.to_string(c)).unwrap_or_else(|| "wallpaper.png".into());
        SHOT.with(|s| *s.borrow_mut() = Some(path));
        Ok(c.undefined())
    }));
    def("randomBytes", c.function(|c, _, a| {
        let v = a.first().copied().unwrap_or(c.undefined());
        if let Some(b) = v.bytes(c) {
            RNG.with(|r| {
                let mut x = r.get();
                for byte in b.iter_mut() {
                    x ^= x << 13;
                    x ^= x >> 7;
                    x ^= x << 17;
                    *byte = x as u8;
                }
                r.set(x);
            });
        }
        Ok(v)
    }));
    def("locale", c.function(|c, _, _| Ok(c.str("en-US"))));
    def("storageGet", c.function(|c, _, _| Ok(c.null())));
    def("storageSet", c.function(|c, _, _| Ok(c.undefined())));
    def("resource", c.function(move |c, _, a| {
        let rel = a.first().map(|v| v.to_string(c)).unwrap_or_default();
        let rel = rel.trim_start_matches("./");
        if rel.is_empty() || rel.contains("..") || rel.starts_with('/') {
            return Ok(c.null());
        }
        let path = assets_dir.join(rel);
        match std::fs::read(&path) {
            Ok(bytes) => Ok(c.array_buffer(bytes)),
            Err(e) => {
                eprintln!("[threert-wallpaper] resource miss {}: {e}", path.display());
                Ok(c.null())
            }
        }
    }));
    for name in ["navigate", "shell", "closeWindow"] {
        def(name, c.function(|c, _, _| Ok(c.undefined())));
    }
}

fn call_rt(c: Ctx, name: &str, now: f64) {
    let rtv = c.global().get(c, "__rt");
    if !rtv.is_object(c) {
        return;
    }
    let f = rtv.get(c, name);
    if f.is_function(c) {
        if let Err(e) = c.call(f, Some(rtv), &[c.num(now)]) {
            eprintln!("[js] __rt.{name}: {e}");
        }
    }
}

fn install_wallpaper_bridge(c: Ctx, theme_json: &str, fixed_time: Option<f64>, fps: f64, battery: bool, render_scale: f64) {
    let ft = match fixed_time {
        Some(t) => format!("{t}"),
        None => "null".into(),
    };
    let script = format!(
        r#"globalThis.__wallpaper = {{
            theme: {theme_json},
            fixedTime: {ft},
            fps: {fps},
            battery: {battery},
            renderScale: {render_scale},
            _listeners: [],
            onThemeChange(fn) {{ if (typeof fn === "function") this._listeners.push(fn); }},
            _emitTheme(next) {{
                this.theme = next;
                for (const fn of this._listeners) {{
                    try {{ fn(next); }} catch (e) {{ console.error("theme listener:", e); }}
                }}
            }}
        }};"#
    );
    let _ = c.eval(&script, "<wallpaper-bridge>");
}

fn push_theme_to_js(c: Ctx, theme_json: &str) {
    let script = format!("globalThis.__wallpaper && globalThis.__wallpaper._emitTheme({theme_json});");
    let _ = c.eval(&script, "<wallpaper-theme>");
}

fn write_shot_tex(tex: &wgpu::Texture, path: &str, opaque: bool) -> bool {
    let size = tex.size();
    match webgpu::image::read_rgba(webgpu::device(), webgpu::queue(), tex, opaque, !opaque) {
        Ok((w, h, px)) => {
            let png = canvas2d::encode_png(w, h, &px);
            if let Some(dir) = std::path::Path::new(path).parent() {
                if !dir.as_os_str().is_empty() {
                    let _ = std::fs::create_dir_all(dir);
                }
            }
            match std::fs::write(path, png) {
                Ok(()) => {
                    eprintln!("[threert-wallpaper] wrote {path} ({w}x{h}, tex={}x{})", size.width, size.height);
                    true
                }
                Err(e) => {
                    eprintln!("[threert-wallpaper] write {path}: {e}");
                    false
                }
            }
        }
        Err(e) => {
            eprintln!("[threert-wallpaper] readback failed: {e}");
            false
        }
    }
}

fn percentile(sorted: &[f64], p: f64) -> f64 {
    if sorted.is_empty() {
        return 0.0;
    }
    let idx = ((sorted.len() - 1) as f64 * p).round() as usize;
    sorted[idx.min(sorted.len() - 1)]
}

fn main() {
    let proc_start = Instant::now();
    let o = parse_opts();

    unsafe {
        libc::signal(libc::SIGINT, handle_signal as *const () as libc::sighandler_t);
        libc::signal(libc::SIGTERM, handle_signal as *const () as libc::sighandler_t);
    }

    // Wallpaper-optimized GPU initialization: prefer LowPower (iGPU) & compact MemoryUsage.
    let gpu = match webgpu::init(&webgpu::GpuOptions {
        power_preference: wgpu::PowerPreference::LowPower,
        memory_hints: wgpu::MemoryHints::MemoryUsage,
        ..Default::default()
    }) {
        Ok(g) => g,
        Err(e) => {
            eprintln!("[threert-wallpaper] GPU unavailable: {e}");
            std::process::exit(2);
        }
    };
    let adapter_info = gpu.adapter.get_info();
    eprintln!(
        "[threert-wallpaper] GPU: {} ({:?}, {:?})",
        adapter_info.name, adapter_info.device_type, adapter_info.backend
    );

    let runtime_js = std::fs::read_to_string(&o.runtime).unwrap_or_else(|e| panic!("read {}: {e}", o.runtime));
    let script_js = std::fs::read_to_string(&o.script).unwrap_or_else(|e| panic!("read {}: {e}", o.script));

    let mut theme_watcher = ThemeWatcher::new(o.colors_path.as_ref().map(Into::into));
    let mut battery = omarchy::on_battery();
    let mut last_battery_check = Instant::now();
    let mut omarchy_guard = OmarchySuspendGuard::new(o.omarchy && o.headless.is_none());

    let output_scale = o.scale_override.unwrap_or_else(|| {
        if o.headless.is_some() {
            1.0
        } else {
            hypr::monitor_scale(o.output.as_deref())
        }
    });
    let current_render_scale = |bat: bool| if bat { o.battery_scale } else { o.render_scale };
    let current_fps = |bat: bool| (if bat { o.battery_fps } else { o.fps }).max(1.0);

    // Initialize either Wayland wlr-layer-shell surface or offscreen headless target.
    let mut wl: Option<WaylandWallpaper> = None;
    let mut offscreen: Option<webgpu::Offscreen> = None;
    let (boot_w, boot_h, boot_dpr) = if let Some((w, h, dpr)) = o.headless {
        let eff = (dpr * current_render_scale(battery)).clamp(0.25, 4.0);
        let pw = ((w as f64 * eff).floor() as u32).max(1);
        let ph = ((h as f64 * eff).floor() as u32).max(1);
        offscreen = Some(webgpu::Offscreen::new(pw, ph, wgpu::TextureFormat::Bgra8Unorm));
        (w, h, eff)
    } else {
        let w = WaylandWallpaper::new(
            &gpu.instance,
            &gpu.adapter,
            &gpu.device,
            o.layer,
            o.output.as_deref(),
            output_scale,
            current_render_scale(battery),
        )
        .unwrap_or_else(|e| {
            eprintln!("[threert-wallpaper] Wayland layer-shell failed: {e}");
            std::process::exit(2);
        });
        let (lw, lh) = w.logical_size();
        let eff = w.scale;
        eprintln!(
            "[threert-wallpaper] Wayland layer-shell ready: logical={}x{} physical={}x{} scale={:.2}",
            lw, lh, w.phys_w, w.phys_h, eff
        );
        wl = Some(w);
        (lw, lh, eff)
    };

    // Setup event-driven Hyprland occlusion watcher (live mode only).
    let occlusion = OcclusionState::new(o.force_paused);
    if o.headless.is_none() && o.occlusion_pause && !o.force_paused {
        if hypr::spawn_watcher(Arc::clone(&occlusion), o.output.clone()) {
            eprintln!("[threert-wallpaper] Hyprland occlusion auto-pause active (initial occluded={})", occlusion.is_occluded());
        }
    }

    // Boot JavaScriptCore realm + ThreeRT runtime + WebGPU.
    let cx = jsc::Context::new("threert-wallpaper");
    let c = cx.ctx();
    rt::begin_page(c);
    let native = c.object();
    c.global().set(c, "__native", native);
    let assets_dir = o.assets_dir.as_ref().map(std::path::PathBuf::from).unwrap_or_else(|| {
        std::path::Path::new(&o.script)
            .parent()
            .map(|p| p.join("assets"))
            .unwrap_or_else(|| std::path::PathBuf::from("assets"))
    });
    let sys = c.object();
    native.set(c, "sys", sys);
    install_sys(c, sys, assets_dir);
    canvas2d::install(c, native);
    webgpu::install(c, native);
    c.global().set(
        c,
        "__boot",
        c.json(&format!(
            r#"{{"url":"http://localhost/","width":{},"height":{},"dpr":{},"lang":"en-US","title":"ThreeRT Wallpaper"}}"#,
            boot_w, boot_h, boot_dpr
        )),
    );
    install_wallpaper_bridge(
        c,
        theme_watcher.current_json(),
        o.fixed_time,
        current_fps(battery),
        battery,
        current_render_scale(battery),
    );

    // Evaluate runtime & scene script.
    let mut eval_failed = false;
    if let Some(off) = &offscreen {
        webgpu::set_window_target(off.texture(), boot_w as f64, boot_h as f64);
    }
    if let Err(e) = c.eval(&runtime_js, &o.runtime) {
        eprintln!("[js] runtime: {e}");
        eval_failed = true;
    }
    if !eval_failed {
        if let Err(e) = c.eval(&script_js, &o.script) {
            eprintln!("[js] script: {e}");
            eval_failed = true;
        }
    }
    let _ = webgpu::end_window_frame();
    if eval_failed {
        omarchy_guard.restore_now();
        rt::reset_page();
        drop(cx);
        std::process::exit(1);
    }

    let loop_start = Instant::now();
    let mut ttff_ms: Option<f64> = None;
    let mut frames: u64 = 0;
    let mut direct_frames: u64 = 0;
    let mut blitted_frames: u64 = 0;
    let mut paused_ms: f64 = 0.0;
    let mut frame_cpu_ms: Vec<f64> = Vec::with_capacity(4096);
    let mut shot_written = false;
    let mut next_frame = rt::page_now();

    let exit_code = loop {
        if SIG_STOP.load(Ordering::SeqCst) {
            break 0;
        }
        if let Some(code) = EXIT.with(|e| e.get()) {
            break code;
        }
        if let Some(dur) = o.duration {
            if loop_start.elapsed().as_secs_f64() >= dur {
                break 0;
            }
        }
        if let Some(w) = wl.as_mut() {
            w.poll_events();
            if w.state.closed {
                break 0;
            }
        }

        // Occlusion / force-pause sleep: completely halt JS + GPU until uncovered!
        // Always render at least 1 frame first so TTFF & initial wallpaper frame are ready.
        if (o.force_paused || (o.occlusion_pause && occlusion.is_occluded())) && frames >= 1 {
            let p0 = Instant::now();
            let remain = o
                .duration
                .map(|d| Duration::from_secs_f64((d - loop_start.elapsed().as_secs_f64()).max(0.0)))
                .unwrap_or(Duration::from_millis(500));
            let wait = remain.min(Duration::from_millis(500));
            if !wait.is_zero() {
                occlusion.wait_while_occluded(wait);
            }
            paused_ms += p0.elapsed().as_secs_f64() * 1000.0;
            next_frame = rt::page_now();
            continue;
        }

        // Periodic AC/battery & Omarchy theme checks (only while awake, low frequency).
        if last_battery_check.elapsed() >= Duration::from_secs(5) {
            last_battery_check = Instant::now();
            let new_bat = omarchy::on_battery();
            if new_bat != battery {
                battery = new_bat;
                if let Some(w) = wl.as_mut() {
                    w.reconfigure(&gpu.device, output_scale * current_render_scale(battery));
                }
            }
        }
        if let Some(new_theme) = theme_watcher.poll_changed() {
            push_theme_to_js(c, &new_theme);
        }

        rt::drain();
        let now = rt::page_now();
        if WAKE_AT.with(|w| w.get()) <= now + 0.5 {
            WAKE_AT.with(|w| w.set(f64::INFINITY));
            if let Some(off) = &offscreen {
                webgpu::set_window_target(off.texture(), boot_w as f64, boot_h as f64);
            }
            call_rt(c, "timers", now);
            let _ = webgpu::end_window_frame();
        }

        let target_fps = current_fps(battery);
        let frame_ms = 1000.0 / target_fps;

        if WANT_FRAME.with(|w| w.get()) && now >= next_frame {
            WANT_FRAME.with(|w| w.set(false));
            next_frame = (next_frame + frame_ms).max(now);

            if let Some(off) = &offscreen {
                let f0 = Instant::now();
                webgpu::set_window_target(off.texture(), boot_w as f64, boot_h as f64);
                call_rt(c, "frame", now);
                let fr = webgpu::end_window_frame();
                frame_cpu_ms.push(f0.elapsed().as_secs_f64() * 1000.0);
                if fr.drew {
                    frames += 1;
                    if fr.blitted {
                        blitted_frames += 1;
                    } else {
                        direct_frames += 1;
                    }
                    if ttff_ms.is_none() {
                        ttff_ms = Some(proc_start.elapsed().as_secs_f64() * 1000.0);
                        eprintln!("[threert-wallpaper] TTFF={:.1}ms", ttff_ms.unwrap());
                    }
                    if let Some(path) = SHOT.with(|s| s.borrow_mut().take()) {
                        shot_written = write_shot_tex(off.texture(), &path, fr.opaque);
                    } else if let Some(path) = &o.shot {
                        if !shot_written && frames >= o.shot_frame as u64 {
                            shot_written = write_shot_tex(off.texture(), path, fr.opaque);
                            if o.duration.is_none() {
                                break 0;
                            }
                        }
                    }
                }
                webgpu::wait_idle();
            } else if let Some(w) = wl.as_mut() {
                if w.state.resized {
                    w.reconfigure(&gpu.device, output_scale * current_render_scale(battery));
                }
                match w.surface.get_current_texture() {
                    Ok(surface_tex) => {
                        let f0 = Instant::now();
                        let (lw, lh) = w.logical_size();
                        webgpu::set_window_target(&surface_tex.texture, lw as f64, lh as f64);
                        call_rt(c, "frame", now);
                        let fr = webgpu::end_window_frame();
                        if fr.drew {
                            if let Some(path) = &o.shot {
                                if !shot_written && frames + 1 >= o.shot_frame as u64 {
                                    shot_written = write_shot_tex(&surface_tex.texture, path, fr.opaque);
                                }
                            }
                            surface_tex.present();
                            frame_cpu_ms.push(f0.elapsed().as_secs_f64() * 1000.0);
                            frames += 1;
                            if fr.blitted {
                                blitted_frames += 1;
                            } else {
                                direct_frames += 1;
                            }
                            if ttff_ms.is_none() {
                                ttff_ms = Some(proc_start.elapsed().as_secs_f64() * 1000.0);
                                eprintln!("[threert-wallpaper] TTFF={:.1}ms (direct={})", ttff_ms.unwrap(), !fr.blitted);
                                omarchy_guard.suspend_now();
                            }
                        } else {
                            // Never discard an acquired Vulkan swapchain texture on Wayland (wgpu-hal can wedge
                            // subsequent acquires with Timeout). Submit a minimal clear and present cleanly.
                            let view = surface_tex.texture.create_view(&Default::default());
                            let mut enc = gpu.device.create_command_encoder(&Default::default());
                            {
                                let _pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
                                    label: Some("wallpaper-idle-clear"),
                                    color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                                        view: &view,
                                        resolve_target: None,
                                        ops: wgpu::Operations {
                                            load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.008, g: 0.015, b: 0.03, a: 1.0 }),
                                            store: wgpu::StoreOp::Store,
                                        },
                                    })],
                                    ..Default::default()
                                });
                            }
                            gpu.queue.submit([enc.finish()]);
                            surface_tex.present();
                        }
                    }
                    Err(e @ (wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated)) => {
                        eprintln!("[threert-wallpaper] surface {e:?}, reconfiguring...");
                        WANT_FRAME.with(|wf| wf.set(true));
                        w.state.resized = true;
                        w.reconfigure(&gpu.device, output_scale * current_render_scale(battery));
                    }
                    Err(wgpu::SurfaceError::Timeout) => {
                        WANT_FRAME.with(|wf| wf.set(true));
                        std::thread::sleep(Duration::from_millis(8));
                    }
                    Err(wgpu::SurfaceError::OutOfMemory) => {
                        eprintln!("[threert-wallpaper] surface OOM");
                        break 1;
                    }
                    Err(wgpu::SurfaceError::Other) => {
                        eprintln!("[threert-wallpaper] surface Other error");
                        WANT_FRAME.with(|wf| wf.set(true));
                    }
                }
            }

            continue;
        }

        webgpu::poll();
        let wake = WAKE_AT
            .with(|w| w.get())
            .min(if WANT_FRAME.with(|w| w.get()) { next_frame } else { f64::INFINITY });
        let sleep_ms = (wake - rt::page_now()).clamp(0.0, 50.0);
        if sleep_ms > 0.25 {
            std::thread::sleep(Duration::from_secs_f64(sleep_ms / 1000.0));
        }
    };

    occlusion.request_stop();
    omarchy_guard.restore_now();

    let elapsed_ms = loop_start.elapsed().as_secs_f64() * 1000.0;
    let active_ms = (elapsed_ms - paused_ms).max(1.0);
    let achieved_fps = frames as f64 / (active_ms / 1000.0);
    frame_cpu_ms.sort_by(|a, b| a.total_cmp(b));
    let (pw, ph) = if let Some(w) = &wl {
        (w.phys_w, w.phys_h)
    } else if let Some(off) = &offscreen {
        let s = off.texture().size();
        (s.width, s.height)
    } else {
        (0, 0)
    };

    let wg = webgpu::take_stats();
    let stats = serde_json::json!({
        "gpu": adapter_info.name,
        "backend": format!("{:?}", adapter_info.backend),
        "logical": [boot_w, boot_h],
        "physical": [pw, ph],
        "scale": boot_dpr,
        "target_fps": current_fps(battery),
        "frames": frames,
        "direct_frames": direct_frames,
        "blitted_frames": blitted_frames,
        "ttff_ms": ttff_ms,
        "elapsed_ms": elapsed_ms,
        "paused_ms": paused_ms,
        "active_ms": active_ms,
        "achieved_fps": achieved_fps,
        "frame_cpu_p50_ms": percentile(&frame_cpu_ms, 0.50),
        "frame_cpu_p95_ms": percentile(&frame_cpu_ms, 0.95),
        "frame_cpu_p99_ms": percentile(&frame_cpu_ms, 0.99),
        "webgpu_draws": wg.draws,
        "webgpu_submits": wg.submits,
        "webgpu_finish_ms": wg.finish_ns as f64 / 1e6,
        "webgpu_submit_ms": wg.submit_ns as f64 / 1e6,
        "webgpu_write_ms": wg.write_ns as f64 / 1e6,
    });
    eprintln!("[threert-wallpaper] stats: {stats}");
    if let Some(path) = &o.stats_json {
        if let Some(dir) = std::path::Path::new(path).parent() {
            if !dir.as_os_str().is_empty() {
                let _ = std::fs::create_dir_all(dir);
            }
        }
        let _ = std::fs::write(path, serde_json::to_string_pretty(&stats).unwrap_or_default());
    }

    rt::reset_page();
    drop(wl);
    drop(offscreen);
    drop(cx);
    std::process::exit(exit_code);
}