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.

6.7 KB
Raw Blame
// record: playable-brick-rush
// A playable ad's shape in raea (docs/playables.feature): a hand shows the move until the first touch, the player drags
// the paddle, three misses or a cleared wall ends it on an EndCard that opens the store. One game, two compositions
// (portrait and landscape) so each network's either orientation gets its own layout. Rendered with `raea render`, no
// one touches it: the paddle follows the ball, and the same file is the video ad.
import { AbsoluteFill, Composition, registerRoot, useCurrentFrame, useGameState, useVideoConfig, type FrameInput } from "raea";
import { Sphere } from "raea/3d";
import { LinearRgba, Srgba } from "raea/color";
import { StandardMaterial } from "raea/pbr";
import { Cuboid, Mesh3d } from "raea/mesh";
import { AmbientLight, DirectionalLight } from "raea/light";
import { Transform } from "raea/transform";
import { Camera3d } from "raea/camera";
import { EndCard } from "raea/playable";

const FPS = 30;
const COLS = 6, ROWS = 4, LIVES = 3;
const W = 6, TOP = 6; // field: x in [-W/2, W/2], y from 0 (paddle) to TOP
const FOV = 0.733; // radians, vertical
const COLORS = ["#ef476f", "#f78c6b", "#06d6a0", "#118ab2"];

interface Game { px: number; bx: number; by: number; vx: number; vy: number; alive: boolean[]; broke: number[]; hit: number; missed: number; lives: number; touched: boolean; over: "" | "won" | "lost" }
const INITIAL: Game = { px: 0, bx: 0, by: 0.6, vx: 0.06, vy: 0.1, alive: Array(COLS * ROWS).fill(true), broke: Array(COLS * ROWS).fill(-99), hit: -99, missed: -99, lives: LIVES, touched: false, over: "" };
const brickPos = (i: number): [number, number] => [(i % COLS - (COLS - 1) / 2) * (W / COLS), TOP - 0.5 - Math.floor(i / COLS) * 0.5];

/** The camera's distance that fits the whole field on a screen of this aspect */
const distance = (aspect: number) => Math.max((TOP + 1.5) / 2, (W + 1) / 2 / aspect) / Math.tan(FOV / 2);

/** A pointer's x on screen, in field units at the paddle's depth */
function fieldX(input: FrameInput, width: number, height: number): number | undefined {
  if (!input.pointer) return undefined;
  const d = distance(width / height);
  const halfH = Math.tan(FOV / 2) * d;
  return ((input.pointer.x / width) * 2 - 1) * halfH * (width / height);
}

const stepFor = (width: number, height: number) => (s: Game, input: FrameInput, frame: number): Game => {
  if (s.over) return s;
  const touched = s.touched || !!input.pointer?.down || !!input.touches?.length;
  const want = touched ? fieldX(input, width, height) ?? s.px : s.bx; // before the first touch, the paddle plays itself
  const px = Math.max(-W / 2 + 0.7, Math.min(W / 2 - 0.7, s.px + Math.max(-0.35, Math.min(0.35, want - s.px))));
  let { bx, by, vx, vy, hit, missed, lives } = s;
  bx += vx; by += vy;
  if (bx < -W / 2 + 0.12 || bx > W / 2 - 0.12) vx = -vx;
  if (by > TOP) vy = -Math.abs(vy);
  if (by < 0.15 && by > -0.2 && vy < 0 && Math.abs(bx - px) < 0.8) { vy = Math.abs(vy); vx += (bx - px) * 0.05; hit = frame; }
  if (by < -1.2) { lives -= 1; missed = frame; bx = px; by = 0.6; vx = 0.06; vy = 0.1; }
  const alive = s.alive.slice(), broke = s.broke.slice();
  for (let i = 0; i < alive.length; i++) {
    if (!alive[i]) continue;
    const [x, y] = brickPos(i);
    if (Math.abs(bx - x) < W / COLS / 2 && Math.abs(by - y) < 0.22) { alive[i] = false; broke[i] = frame; vy = -vy; break; }
  }
  const over = !alive.some(Boolean) ? "won" : lives <= 0 ? "lost" : "";
  return { px, bx, by, vx, vy, alive, broke, hit, missed, lives, touched, over };
};

const steps = new Map<string, ReturnType<typeof stepFor>>();
const stepOf = (w: number, h: number) => steps.get(`${w}x${h}`) ?? steps.set(`${w}x${h}`, stepFor(w, h)).get(`${w}x${h}`)!;

function BrickRush() {
  const { width, height } = useVideoConfig();
  const g = useGameState(INITIAL, stepOf(width, height));
  const now = useCurrentFrame();
  const last = g.broke.reduce((m, b) => Math.max(m, b), -99);
  const kick = Math.max(0, 1 - (now - last) / 8);
  const shake = kick * kick * 0.08 * Math.sin(now * 2.7);
  const squash = Math.max(0, 1 - (now - g.hit) / 6);
  const flash = Math.max(0, 1 - (now - g.missed) / 12);
  const d = distance(width / height);
  const s = width / 1080; // page sizes scale with the composition
  return (
    <AbsoluteFill style={{ background: `rgb(${16 + 90 * flash}, 20, 34)` }}>
      <Camera3d transform={Transform.fromXyz(shake, TOP / 2 + shake, d).lookingAt([0, TOP / 2, 0])} projection={{ Perspective: { fov: FOV } }} />
      <AmbientLight brightness={180} />
      <DirectionalLight transform={Transform.fromXyz(2, 8, 6).lookingAt([0, 0, 0])} illuminance={9600} shadow_maps_enabled />
      <Mesh3d transform={Transform.fromXyz(g.px, 0, 0).withScale([1 + 0.25 * squash, 1 - 0.35 * squash, 1])} name="paddle">
        <Cuboid half_size={[0.7, 0.1, 0.2]} />
        <StandardMaterial base_color="#f0ebd8" perceptual_roughness={0.4} />
      </Mesh3d>
      <Mesh3d transform={Transform.fromXyz(g.bx, g.by, 0)} name="ball">
        <Sphere radius={0.14} />
        <StandardMaterial base_color="#ffd166" emissive={LinearRgba.from(Srgba.hex("#ffd166")).mul(0.6)} />
      </Mesh3d>
      {g.alive.map((on, i) => {
        const [x, y] = brickPos(i);
        const t = (now - g.broke[i]) / 10;
        if (!on && t > 1) return null;
        const pop = on ? 1 : 1 + 0.6 * t;
        return (
          <Mesh3d key={i} transform={Transform.fromXyz(x, y, on ? 0 : t * 0.8).withScale([pop, on ? 1 : 1 - t, on ? 1 : 1 - t])} name={`brick-${i}`}>
            <Cuboid half_size={[(W / COLS - 0.08) / 2, 0.2, 0.2]} />
            <StandardMaterial base_color={on ? COLORS[Math.floor(i / COLS)] : "#ffffff"} perceptual_roughness={0.5} />
          </Mesh3d>
        );
      })}
      <div style={{ position: "absolute", left: 40 * s, top: 36 * s, fontFamily: "Inter, system-ui, sans-serif", fontWeight: 800, fontSize: 56 * s, color: "#f0ebd8" }}>
        {"♥".repeat(Math.max(0, g.lives))}
      </div>
      {!g.touched ? (
        <div style={{ position: "absolute", left: 0, right: 0, bottom: height * 0.12, textAlign: "center", fontFamily: "Inter, system-ui, sans-serif", fontWeight: 900, fontSize: 64 * s, color: "#ffffff", opacity: 0.6 + 0.4 * Math.sin(now / 5) ** 2 }}>
          {`👆 Drag to play`}
        </div>
      ) : null}
      <EndCard show={!!g.over} title={g.over === "won" ? "Wall cleared!" : "So close!"} subtitle={g.over === "won" ? "300 more levels inside" : "Can you clear the wall?"} cta={g.over === "won" ? "Keep playing" : "Try again"} />
    </AbsoluteFill>
  );
}

registerRoot(() => (
  <>
    <Composition id="brick-rush-portrait" component={BrickRush} width={1080} height={1920} fps={FPS} durationInFrames={FPS * 45} />
    <Composition id="brick-rush-landscape" component={BrickRush} width={1920} height={1080} fps={FPS} durationInFrames={FPS * 45} />
  </>
));