Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

7.1 KB
Raw Blame
// The browser host a playable export runs a raea game in (docs/playables.feature PA1): the game's registered
// composition (the one nearest the screen's shape, so a portrait and a landscape one can both ship) put on a stage
// scaled uniformly into the screen, a Clock stepped 1/fps at a time off requestAnimationFrame with the person's input
// recorded per frame, and its 3D drawn by three.js under the page. It starts when the network says the ad is
// viewable, pauses while it isn't, and ends on the game's own EndCard or, at the composition's last frame, on one of
// its own.
import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client";
import * as THREE from "three";
import { Clock, getCompositions, type InputTimeline, type RegisteredComposition } from "raea";
import { EndCard } from "../cards";
import { network, onAdEvent, whenReady } from "../network";
import { Input } from "./input";
import { Scene3d } from "./scene";
import { UNDER, backgroundUnder3d } from "@raea/r3f/three/page";
import { Tonemap } from "./tonemap";

declare const __RAEA_PLAYABLE__: { title?: string; cta?: string } | undefined;
const config = typeof __RAEA_PLAYABLE__ === "object" && __RAEA_PLAYABLE__ ? __RAEA_PLAYABLE__ : {};


function pick(comps: RegisteredComposition[]): RegisteredComposition {
  const screen = innerWidth / Math.max(1, innerHeight);
  return comps.reduce((a, b) => (Math.abs(Math.log((b.width / b.height) / screen)) < Math.abs(Math.log((a.width / a.height) / screen)) ? b : a));
}

/** The 3D is drawn under the page, so the page elements holding it are cleared and the innermost solid background
 *  among them becomes the 3D's clear colour, as the native engine shows the page's background behind the 3D. */
function boot() {
  const comps = getCompositions();
  if (!comps.length) throw new Error("raea playable: the game registered no composition (registerRoot)");
  // a still (tools/parity.ts): one composition at one frame, no one playing, as `raea render --frame` draws it
  const still = network === "preview" ? new URLSearchParams(location.hash.slice(1)) : undefined;
  const fixed = still?.has("still") ? comps.find((c) => c.id === still.get("comp")) ?? comps[0] : undefined;
  let comp = fixed ?? pick(comps);

  document.head.insertAdjacentHTML("beforeend", `<style>html,body{margin:0;height:100%;overflow:hidden;background:#000;touch-action:none;user-select:none;-webkit-user-select:none}[${UNDER}]{background:transparent!important}#raea-stage{position:absolute;transform-origin:0 0;overflow:hidden}#raea-stage>canvas,#raea-page{position:absolute;inset:0;width:100%;height:100%}</style>`);
  const stage = document.createElement("div");
  stage.id = "raea-stage";
  const canvas = document.createElement("canvas");
  const page = document.createElement("div");
  page.id = "raea-page";
  stage.append(canvas, page);
  document.body.append(stage);

  // the 3D is tone-mapped by its own pass (antialiased in its target) and left transparent where nothing was drawn
  const renderer = new THREE.WebGLRenderer({ canvas, antialias: false, alpha: true, premultipliedAlpha: true, powerPreference: "high-performance" });
  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  const tonemap = new Tonemap(renderer);
  const scene = new Scene3d();

  const layout = () => {
    if (comps.length > 1 && !fixed) comp = pick(comps);
    const s = Math.min(innerWidth / comp.width, innerHeight / comp.height);
    Object.assign(stage.style, {
      width: `${comp.width}px`,
      height: `${comp.height}px`,
      left: `${(innerWidth - comp.width * s) / 2}px`,
      top: `${(innerHeight - comp.height * s) / 2}px`,
      transform: `scale(${s})`,
    });
    // the canvas is drawn at the screen's pixels, not the composition's
    renderer.setPixelRatio(Math.min(2, devicePixelRatio || 1) * s);
    renderer.setSize(comp.width, comp.height, false);
    tonemap.resize();
    scene.fit(comp.width, comp.height);
  };
  layout();
  addEventListener("resize", layout);

  const input = new Input(stage, () => comp);
  const root = createRoot(page);
  const timeline: InputTimeline = {};
  let frame = 0;
  let timedOut = false;
  let running = false;
  let visible = true;
  let last = 0;
  let acc = 0;
  let over = false;
  let shown = false;
  let firstDrawn = false;
  // the ad events so far, for tools/check.ts to read back
  const events: string[] = ((globalThis as { __raeaAdEvents?: string[] }).__raeaAdEvents = []);
  // the preview page inside raea's review (a sandboxed frame) tells the review each event, which shows them beside it
  const tell = (kind: string) => {
    if (network === "preview" && window.parent !== window) window.parent.postMessage({ raeaPlayable: kind }, "*");
  };
  onAdEvent((e) => {
    events.push(e.kind);
    if (e.kind === "end") over = true;
    tell(e.kind);
  });
  // the player took over from the game's own hand
  input.onFirstTouch(() => tell("touch"));

  const draw = () => {
    const C = comp.component;
    flushSync(() =>
      root.render(
        <Clock frame={frame} fps={comp.fps} width={comp.width} height={comp.height} durationInFrames={comp.durationInFrames} input={timeline} defaultProps={comp.defaultProps}>
          <C {...comp.defaultProps} />
          <EndCard show={timedOut} title={config.title} cta={config.cta} />
        </Clock>,
      ),
    );
    scene.sync(page, frame / comp.fps);
    const clear = backgroundUnder3d(page);
    // the page's own background colour behind the 3D, untouched by the tone curve as natively
    stage.style.background = clear ?? "#000000";
    canvas.style.visibility = scene.any ? "visible" : "hidden";
    if (scene.any) tonemap.render(scene.scene, scene.camera);
    // a preview build says when its first frame was drawn (tools/check.ts reads it: startup on a slow phone)
    if (!firstDrawn && network === "preview") console.info(`raea playable: first frame at ${Math.round(performance.now())} ms`);
    firstDrawn = true;
  };

  const tick = (now: number) => {
    requestAnimationFrame(tick);
    if (!running || !visible) {
      last = now;
      return;
    }
    const step = 1000 / comp.fps;
    acc += Math.min(250, now - last);
    last = now;
    let stepped = false;
    // the game stops stepping once it is over (its EndCard showed, or time ran out): the card stays on the last frame
    while (acc >= step && !over) {
      acc -= step;
      timeline[frame] = input.now();
      if (frame + 1 >= comp.durationInFrames) {
        timedOut = true;
        break;
      }
      frame++;
      stepped = true;
    }
    if (stepped || (timedOut && !shown)) {
      shown = timedOut;
      draw();
    }
  };

  if (fixed) {
    frame = Math.min(Number(still!.get("still")), comp.durationInFrames - 1);
    draw();
    (globalThis as { __raeaStill?: boolean }).__raeaStill = true;
    return;
  }
  draw();
  whenReady(
    () => {
      running = true;
      last = performance.now();
      tell("ready");
    },
    (on) => {
      if (on !== visible) tell(on ? "viewable" : "hidden");
      visible = on;
    },
  );
  requestAnimationFrame(tick);
}

if (document.readyState === "loading") addEventListener("DOMContentLoaded", boot);
else boot();