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.

5.4 KB
Raw Blame
//! Main-thread runtime services shared by every host module.
//!
//! The JavaScript context, the GL context and the UI tree live on the main (AppKit) thread.
//! Worker threads (network, decoding, host services) never touch them; they `post`
//! closures that the main thread runs between frames, and the app is woken to do so.
//!
//! A "page" is one JS global context (one navigation). Everything a host module keeps for a page
//! — protected callbacks, timers, sockets — must be dropped in `reset_page` before the context is
//! released, so modules register a reset hook when they install themselves.

use std::any::Any;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
use std::time::Instant;

use jsc::Ctx;

type Task = Box<dyn FnOnce() + Send>;

static QUEUE: Mutex<Vec<Task>> = Mutex::new(Vec::new());
static WAKER: OnceLock<Box<dyn Fn() + Send + Sync>> = OnceLock::new();
static START: OnceLock<Instant> = OnceLock::new();

/// Install the function that wakes the main event loop (called from any thread).
pub fn set_waker(f: impl Fn() + Send + Sync + 'static) {
    let _ = WAKER.set(Box::new(f));
}

/// Run `task` on the main thread soon. Callable from any thread.
pub fn post(task: impl FnOnce() + Send + 'static) {
    QUEUE.lock().unwrap().push(Box::new(task));
    if let Some(w) = WAKER.get() {
        w();
    }
}

/// Main thread: run everything posted so far. Returns how many tasks ran.
pub fn drain() -> usize {
    let tasks = std::mem::take(&mut *QUEUE.lock().unwrap());
    let n = tasks.len();
    for t in tasks {
        t();
    }
    n
}

/// Milliseconds since process start (monotonic).
pub fn now_ms() -> f64 {
    START.get_or_init(Instant::now).elapsed().as_secs_f64() * 1000.0
}

/// Requests a page makes of the app; handled after the current JS call returns.
#[derive(Debug, Clone)]
pub enum AppRequest {
    /// Load a new URL (location.href = …, location.reload()).
    Navigate(String),
    /// A message for the host shell bridge.
    Shell(String, Vec<String>),
    /// window.close() and similar.
    CloseWindow,
    /// The page wants a frame (rAF registered, UI dirty, …).
    Redraw,
}

type Continuation = Box<dyn FnOnce(Ctx, Box<dyn Any + Send>)>;

thread_local! {
    static CTX: Cell<Option<Ctx>> = const { Cell::new(None) };
    static GEN: Cell<u64> = const { Cell::new(0) };
    static PAGE_START: Cell<f64> = const { Cell::new(0.0) };
    static NEXT_ID: Cell<u64> = const { Cell::new(1) };
    static PENDING: RefCell<HashMap<u64, (u64, Continuation)>> = RefCell::new(HashMap::new());
    static RESETS: RefCell<Vec<fn()>> = const { RefCell::new(Vec::new()) };
    static REQUESTS: RefCell<Vec<AppRequest>> = const { RefCell::new(Vec::new()) };
}

/// Main thread: a new page's context is live.
pub fn begin_page(c: Ctx) {
    GEN.with(|g| g.set(g.get() + 1));
    CTX.with(|x| x.set(Some(c)));
    PAGE_START.with(|p| p.set(now_ms()));
}

/// Main thread: drop every per-page resource (before the context is released).
pub fn reset_page() {
    CTX.with(|x| x.set(None));
    GEN.with(|g| g.set(g.get() + 1));
    let pending = PENDING.with(|p| std::mem::take(&mut *p.borrow_mut()));
    drop(pending);
    let hooks = RESETS.with(|r| r.borrow().clone());
    for h in hooks {
        h();
    }
}

/// Register a hook run by `reset_page` (idempotent per function pointer).
pub fn on_reset(f: fn()) {
    RESETS.with(|r| {
        let mut r = r.borrow_mut();
        if !r.iter().any(|g| std::ptr::fn_addr_eq(*g, f)) {
            r.push(f);
        }
    });
}

/// The live page context, if any.
pub fn ctx() -> Option<Ctx> {
    CTX.with(|x| x.get())
}

/// The current page generation (changes on every navigation / teardown).
pub fn page_gen() -> u64 {
    GEN.with(|g| g.get())
}

/// `performance.now()` for the current page.
pub fn page_now() -> f64 {
    now_ms() - PAGE_START.with(|p| p.get())
}

/// Run `work` on a worker thread, then `then` on the main thread with the page context — unless
/// the page went away meanwhile, in which case the result is dropped.
pub fn spawn<R: Send + 'static>(work: impl FnOnce() -> R + Send + 'static, then: impl FnOnce(Ctx, R) + 'static) {
    let id = NEXT_ID.with(|n| {
        let v = n.get();
        n.set(v + 1);
        v
    });
    let generation = page_gen();
    let cont: Continuation = Box::new(move |c, any| {
        if let Ok(r) = any.downcast::<R>() {
            then(c, *r)
        }
    });
    PENDING.with(|p| p.borrow_mut().insert(id, (generation, cont)));
    std::thread::Builder::new()
        .name("rt-worker".into())
        .spawn(move || {
            let r = work();
            post(move || complete(id, Box::new(r)));
        })
        .expect("spawn worker");
}

fn complete(id: u64, r: Box<dyn Any + Send>) {
    let Some((generation, cont)) = PENDING.with(|p| p.borrow_mut().remove(&id)) else { return };
    if generation != page_gen() {
        return;
    }
    if let Some(c) = ctx() {
        cont(c, r);
    }
}

/// Queue a request for the app (processed after the current JS call returns).
pub fn request(r: AppRequest) {
    REQUESTS.with(|q| q.borrow_mut().push(r));
    if let Some(w) = WAKER.get() {
        w();
    }
}

/// Main thread: take queued app requests.
pub fn take_requests() -> Vec<AppRequest> {
    REQUESTS.with(|q| std::mem::take(&mut *q.borrow_mut()))
}

/// Log an uncaught JS error the same way everywhere.
pub fn report(what: &str, err: &str) {
    eprintln!("[js] {what}: {err}");
}