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.

6.3 KB
Raw Blame
// ThreeRT native runtime (web-platform globals for JavaScriptCore guests):
// events, timers, console, web utilities, window surface, Canvas 2D, and networking.
//
// Dependencies point one way: runtime/js never imports webgpu/js or renderer/.
// WebGPU builds boot through webgpu/js/index.ts, which calls installRuntime() then installWebGPU().
import * as events from "./core/events.ts";
import * as timers from "./core/timers.ts";
import { console } from "./core/console.ts";
import * as web from "./core/web.ts";
import * as win from "./core/window.ts";
import { installCanvas2D } from "./canvas2d.ts";
import { installNet } from "./net.ts";

let installed = false;

export function installRuntime() {
  if (installed) return;
  installed = true;

  const g = globalThis as any;
  g.window = g; g.self = g; g.top = g; g.parent = g; g.frames = g;
  g.console = console;

  // events
  for (const k of ["Event", "CustomEvent", "UIEvent", "FocusEvent", "MouseEvent", "PointerEvent", "WheelEvent", "KeyboardEvent",
    "InputEvent", "CompositionEvent", "SubmitEvent", "ErrorEvent", "MessageEvent", "CloseEvent", "ProgressEvent", "EventTarget"] as const) {
    g[k] = (events as any)[k];
  }
  g.DOMException = events.DOMExceptionImpl;

  // window is an EventTarget whose methods live on the global object
  const windowTarget = new events.EventTarget();
  g.addEventListener = windowTarget.addEventListener.bind(windowTarget);
  g.removeEventListener = windowTarget.removeEventListener.bind(windowTarget);
  g.dispatchEvent = (e: events.Event) => windowTarget.dispatchEvent(e);
  events.defineHandlers(g, [...events.HANDLER_TYPES, "beforeunload", "unload", "pagehide", "pageshow", "message", "online", "offline", "popstate", "hashchange", "storage", "unhandledrejection"]);
  for (const type of [...events.HANDLER_TYPES, "beforeunload", "unload", "pagehide", "message"]) {
    const desc = Object.getOwnPropertyDescriptor(g, "on" + type)!;
    Object.defineProperty(g, "on" + type, {
      configurable: true, enumerable: true,
      get: () => desc.get!.call(windowTarget),
      set: (v) => desc.set!.call(windowTarget, v),
    });
  }
  events.defineHandlers(events.EventTarget.prototype, []);

  // timers
  Object.assign(g, {
    setTimeout: timers.setTimeout, setInterval: timers.setInterval, clearTimeout: timers.clearTimeout, clearInterval: timers.clearInterval,
    requestAnimationFrame: timers.requestAnimationFrame, cancelAnimationFrame: timers.cancelAnimationFrame,
    queueMicrotask: timers.queueMicrotask,
    requestIdleCallback: (cb: any) => timers.setTimeout(() => cb({ didTimeout: false, timeRemaining: () => 8 }), 1),
    cancelIdleCallback: timers.clearTimeout,
  });

  // performance
  const marks = new Map<string, number>();
  g.performance = {
    now: () => __native.sys.now(),
    timeOrigin: Date.now() - __native.sys.now(),
    mark: (n: string) => { marks.set(n, __native.sys.now()); },
    measure: () => {},
    getEntriesByName: () => [], getEntriesByType: () => [], clearMarks: () => marks.clear(), clearMeasures: () => {},
    memory: undefined,
    toJSON() { return {}; },
  };

  // web utilities
  Object.assign(g, {
    URL: web.URL, URLSearchParams: web.URLSearchParams, TextEncoder: web.TextEncoder, TextDecoder: web.TextDecoder,
    atob: web.atob, btoa: web.btoa, crypto: web.crypto, AbortController: web.AbortController, AbortSignal: web.AbortSignal,
    structuredClone: web.structuredClone,
  });

  // window surface
  Object.defineProperties(g, {
    innerWidth: { get: () => win.viewport.width, configurable: true },
    innerHeight: { get: () => win.viewport.height, configurable: true },
    outerWidth: { get: () => win.viewport.width, configurable: true },
    outerHeight: { get: () => win.viewport.height, configurable: true },
    devicePixelRatio: { get: () => win.viewport.dpr, configurable: true },
    scrollX: { value: 0, configurable: true }, scrollY: { value: 0, configurable: true },
    pageXOffset: { value: 0, configurable: true }, pageYOffset: { value: 0, configurable: true },
    screenX: { value: 0, configurable: true }, screenY: { value: 0, configurable: true },
    isSecureContext: { value: true, configurable: true },
    origin: { get: () => win.location.origin, configurable: true },
    closed: { value: false, configurable: true },
    name: { value: "", writable: true, configurable: true },
  });
  Object.assign(g, {
    location: win.location, history: win.history, navigator: win.navigator, screen: win.screen,
    localStorage: win.localStorage, sessionStorage: win.sessionStorage, Storage: win.Storage,
    matchMedia: win.matchMedia, alert: win.alert, confirm: win.confirm, prompt: win.prompt, open: win.open,
    close: () => __native.sys.closeWindow(), focus: () => {}, blur: () => {}, scrollTo: () => {}, scroll: () => {}, scrollBy: () => {},
    print: () => {}, stop: () => {}, postMessage: () => {},
  });

  // optional native subsystems (only mounted when the host installs them on __native)
  if (__native.c2d) installCanvas2D();
  if (__native.net) installNet();

  // Minimal document surface for libraries (three.js, UI helpers) without a browser DOM.
  const documentTarget = new events.EventTarget() as events.EventTarget & { _hidden?: boolean };
  let focused = true;
  windowTarget.addEventListener("focus", () => { focused = true; });
  windowTarget.addEventListener("blur", () => { focused = false; });
  g.document = Object.assign(documentTarget, {
    get hidden() { return !!documentTarget._hidden; },
    get visibilityState() { return documentTarget._hidden ? "hidden" : "visible"; },
    hasFocus: () => focused,
    get title() { return __boot.title ?? ""; },
    set title(_v: string) { /* the shell owns the window title */ },
    documentElement: { lang: __boot.lang ?? "en-US", style: {} },
    createElement(tag: string) {
      if (String(tag).toLowerCase() === "canvas") return new g.OffscreenCanvas(300, 150);
      throw new DOMException(`no DOM in this runtime: <${tag}>`, "NotSupportedError");
    },
  });

  g.__rt = {
    boot() {},
    timers(now: number) { timers.runTimers(now); },
    frame(now: number) { timers.runFrame(now); },
    windowEvent(name: string, ...data: number[]) {
      win.windowEvent(windowTarget, documentTarget, name, data);
    },
    unload() {
      try { windowTarget.dispatchEvent(new events.Event("pagehide")); windowTarget.dispatchEvent(new events.Event("unload")); } catch { /* */ }
    },
  };
}