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.

10.5 KB
Raw Blame
//! Headless WebGPU harness: a JavaScriptCore realm with the minimal runtime three.js needs
//! (console, timers / requestAnimationFrame, performance, navigator, Canvas 2D, WebGPU), a page
//! script, frames paced like the app, and a PNG of the window canvas.
//!
//!   webgpu-shot --runtime <runtime.js> --script <page.js> [--size 1200x800@2] [--timeout 60]
//!               [--fps 60] [--format bgra8unorm|rgba8unorm] [--out <png>]
//!
//! The page renders into `globalThis.__pocketGpuCanvas` (an `Offscreen` target stands in for the
//! window), calls `__native.sys.shot(path)` (written at the end of the current frame) and
//! `__native.sys.exit(code)`. `--out` shoots the last frame at exit if the page never asked.
//! Prints `[webgpu-shot] frames=… cpu.mean=…ms …` (CPU time of each frame: JS + native, without
//! waiting for the GPU) on exit. Sign with the JIT entitlement (see test/webgpu-compare.mjs).
use std::cell::{Cell, RefCell};
use std::time::{Duration, Instant};

use jsc::{Ctx, Value};
use threert_webgpu as webgpu;

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,
    width: u32,
    height: u32,
    dpr: f64,
    timeout: f64,
    fps: f64,
    format: wgpu::TextureFormat,
    out: Option<String>,
}

fn opts() -> Opts {
    let a: Vec<String> = std::env::args().collect();
    let get = |k: &str| a.iter().position(|x| x == k).and_then(|i| a.get(i + 1)).cloned();
    let size = get("--size").unwrap_or_else(|| "1200x800@2".into());
    let (wh, dpr) = size.split_once('@').unwrap_or((&size, "1"));
    let (w, h) = wh.split_once('x').unwrap_or(("1200", "800"));
    Opts {
        runtime: get("--runtime").expect("--runtime <runtime.js>"),
        script: get("--script").expect("--script <page.js>"),
        width: w.parse().unwrap_or(1200),
        height: h.parse().unwrap_or(800),
        dpr: dpr.parse().unwrap_or(1.0),
        timeout: get("--timeout").and_then(|s| s.parse().ok()).unwrap_or(60.0),
        fps: get("--fps").and_then(|s| s.parse().ok()).unwrap_or(60.0),
        format: match get("--format").as_deref() {
            Some("rgba8unorm") => wgpu::TextureFormat::Rgba8Unorm,
            _ => wgpu::TextureFormat::Bgra8Unorm,
        },
        out: get("--out"),
    }
}

fn install_sys(c: Ctx, sys: Value) {
    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(|| "shot.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("storageGet", c.function(|c, _, _| Ok(c.null())));
    def("storageSet", c.function(|c, _, _| Ok(c.undefined())));
    def("resource", c.function(|c, _, _| 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 write_shot(off: &webgpu::Offscreen, path: &str, opaque: bool, w: u32, h: u32) {
    match off.read_rgba(opaque) {
        Ok(px) => {
            let png = canvas2d::encode_png(w, h, &px);
            if let Some(dir) = std::path::Path::new(path).parent() {
                let _ = std::fs::create_dir_all(dir);
            }
            match std::fs::write(path, png) {
                Ok(()) => eprintln!("[webgpu-shot] wrote {path}"),
                Err(e) => eprintln!("[webgpu-shot] {path}: {e}"),
            }
        }
        Err(e) => eprintln!("[webgpu-shot] readback failed: {e}"),
    }
}

fn pct(v: &mut [f64], p: f64) -> f64 {
    if v.is_empty() {
        return 0.0;
    }
    v.sort_by(|a, b| a.partial_cmp(b).unwrap());
    v[((v.len() - 1) as f64 * p).round() as usize]
}

#[cfg(target_os = "macos")]
unsafe extern "C" {
    fn pthread_set_qos_class_self_np(qos: u32, relative_priority: i32) -> i32;
}
#[cfg(target_os = "macos")]
const QOS_CLASS_USER_INTERACTIVE: u32 = 0x21;

fn main() {
    // The app's main thread (AppKit) runs at user-interactive QoS; without it an idle-between-frames
    // thread lands on efficiency cores and per-frame timings swing by 2x.
    #[cfg(target_os = "macos")]
    unsafe {
        pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0);
    }
    let o = opts();
    let (pw, ph) = ((o.width as f64 * o.dpr).round() as u32, (o.height as f64 * o.dpr).round() as u32);
    if let Err(e) = webgpu::init(&webgpu::GpuOptions::default()) {
        eprintln!("[webgpu-shot] {e}");
        std::process::exit(2);
    }
    let runtime = std::fs::read_to_string(&o.runtime).expect("read runtime");
    let script = std::fs::read_to_string(&o.script).expect("read script");

    let cx = jsc::Context::new("webgpu-shot");
    let c = cx.ctx();
    rt::begin_page(c);
    let native = c.object();
    c.global().set(c, "__native", native);
    let sys = c.object();
    native.set(c, "sys", sys);
    install_sys(c, sys);
    canvas2d::install(c, native);
    webgpu::install(c, native);
    c.global().set(c, "__boot", c.json(&format!(r#"{{"url":"http://localhost/","width":{},"height":{},"dpr":{}}}"#, o.width, o.height, o.dpr)));

    let off = webgpu::Offscreen::new(pw, ph, o.format);
    let (lw, lh) = (o.width as f64, o.height as f64);
    let mut last_opaque = true;
    // Every entry into JS is a window frame for the WebGPU binding: the target is set, and the
    // frame ends (flush, blit, release) when the call returns.
    let mut turn = |f: &mut dyn FnMut()| -> webgpu::WindowFrame {
        webgpu::set_window_target(off.texture(), lw, lh);
        f();
        let fr = webgpu::end_window_frame();
        if fr.drew {
            last_opaque = fr.opaque;
        }
        if let Some(path) = SHOT.with(|s| s.borrow_mut().take()) {
            write_shot(&off, &path, last_opaque, pw, ph);
        }
        fr
    };

    turn(&mut || {
        if let Err(e) = c.eval(&runtime, &o.runtime) {
            eprintln!("[js] runtime: {e}");
        }
        if let Err(e) = c.eval(&script, &o.script) {
            eprintln!("[js] script: {e}");
        }
    });

    let start = Instant::now();
    let frame_ms = 1000.0 / o.fps.max(1.0);
    let mut next_frame = rt::page_now();
    let mut cpu: Vec<f64> = Vec::new();
    let mut stats: Vec<webgpu::Stats> = Vec::new();
    let code = loop {
        if let Some(code) = EXIT.with(|e| e.get()) {
            break code;
        }
        if start.elapsed().as_secs_f64() > o.timeout {
            eprintln!("[webgpu-shot] timeout after {}s", o.timeout);
            break 3;
        }
        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));
            turn(&mut || call_rt(c, "timers", now));
        }
        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);
            webgpu::take_stats();
            let t0 = Instant::now();
            turn(&mut || call_rt(c, "frame", now));
            cpu.push(t0.elapsed().as_secs_f64() * 1000.0);
            stats.push(webgpu::take_stats());
            // keep at most one frame in flight, like a vsync-paced swapchain
            webgpu::wait_idle();
            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 = (wake - rt::page_now()).clamp(0.0, 2.0);
        if sleep > 0.05 {
            std::thread::sleep(Duration::from_secs_f64(sleep / 1000.0));
        }
    };
    if let Some(out) = &o.out {
        write_shot(&off, out, last_opaque, pw, ph);
    }
    // per-frame CPU (skip warm-up frames: pipeline compilation, first uploads)
    let skip = (cpu.len() / 4).min(30);
    let mut steady: Vec<f64> = cpu.iter().skip(skip).copied().collect();
    let n = steady.len().max(1) as f64;
    let mean = steady.iter().sum::<f64>() / n;
    let st = &stats[skip.min(stats.len())..];
    let avg = |f: fn(&webgpu::Stats) -> f64| st.iter().map(f).sum::<f64>() / st.len().max(1) as f64;
    eprintln!(
        "[webgpu-shot] frames={} steady={} cpu.mean={:.3}ms cpu.p50={:.3}ms cpu.p95={:.3}ms native.finish={:.3}ms native.submit={:.3}ms native.write={:.3}ms draws={:.0} passes={:.1} writes={:.0} calls={:.0}",
        cpu.len(),
        steady.len(),
        mean,
        pct(&mut steady.clone(), 0.5),
        pct(&mut steady, 0.95),
        avg(|s| s.finish_ns as f64 / 1e6),
        avg(|s| s.submit_ns as f64 / 1e6),
        avg(|s| s.write_ns as f64 / 1e6),
        avg(|s| s.draws as f64),
        avg(|s| s.passes as f64),
        avg(|s| s.writes as f64),
        avg(|s| s.calls as f64),
    );
    rt::reset_page();
    drop(cx);
    std::process::exit(code);
}