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.

R3F27: R3F's pointer events and drei's OrbitControls in a live play

shinyobjectzfbcc03fc38f2
diff --git a/bench/render-play/rows.tsv b/bench/render-play/rows.tsv
index 20bfaccd..0fca3eb0 100644
--- a/bench/render-play/rows.tsv
+++ b/bench/render-play/rows.tsv
@@ -8,7 +8,7 @@
# React on the page with 3D in the world, picking and input replay are all here: the games (pong and platformer on
# the page, arena3d's 3D drawn live), bevy-ts' live cases (keys, the pointer, a gamepad, the window and the World's
# components through useQuery), the bridge's Engine reads (engine3d: a cube the World moves, React's marker reading it)
-# and pick3d (on* on 3D parts: hover, press, leave)
+# and pick3d (on* on 3D parts: hover, press, leave); an <R3F>'s own pointer events and <OrbitControls> (r3f live/pointer)
sdk/react/bench/games/pong/edit.tsx keys:ArrowUp,ArrowDown,,ArrowUp 0.25 0.75 1.25 1.75
sdk/react/bench/games/platformer/edit.tsx keys:ArrowRight,ArrowRight+ArrowUp,ArrowRight, 0.25 0.75 1.25 1.75
sdk/react/bench/games/arena3d/edit.tsx keys:ArrowRight,ArrowUp,ArrowLeft+ArrowUp,ArrowDown, 0.25 0.75 1.25 1.75
@@ -21,3 +21,4 @@ sdk/raea/bench/bevy-ts/cases/live-window.tsx script:sdk/raea/bench/bevy-ts/cases
sdk/raea/bench/bevy-ts/cases/text3d-readback.tsx script:sdk/raea/bench/bevy-ts/cases/live-world.json 0.3 0.6
bench/bridge/engine3d.tsx - 0.3 0.9 1.25
sdk/raea/bench/bevy/pick3d/edit.tsx script:bench/render-play/pick3d.json 0.1 0.2 0.3 0.4 0.6 0.9
+sdk/r3f/test/live/pointer.tsx script:sdk/r3f/test/live/pointer.json 0.2 0.4 0.6 0.9
diff --git a/sdk/r3f/src/input/R3F.tsx b/sdk/r3f/src/input/R3F.tsx
index 4e7a79ba..5d5f4d2d 100644
--- a/sdk/r3f/src/input/R3F.tsx
+++ b/sdk/r3f/src/input/R3F.tsx
@@ -6,10 +6,12 @@
// frame, never the wall clock.
import { useContext, useId, type ReactNode } from "react";
import { AbsoluteFill, useCurrentFrame, useVideoConfig } from "raea";
-import { ClockContext, LocalTimeContext } from "@raea/app/clock";
+import { ClockContext, LocalTimeContext, type FrameInput } from "@raea/app/clock";
+import { wireKeys } from "@raea/app/games";
import type * as THREE from "three";
import { FiberOf, useBridge } from "./bridge";
import { Held, useWake } from "./hold";
+import { inCanvas, viewBox } from "./pointer";
import { stepTo, type Config } from "./session";
import { convert } from "./scene";
import { standInImages } from "./texture";
@@ -54,7 +56,16 @@ function Inner({ fiber, children, name, width: boxW, height: boxH, ...config }:
</ClockContext>,
);
};
- const s = stepTo(name ?? id, frame, fps, width, height, config, at);
+ // the input at local frame i, from raea's input timeline (by composition frame): sent to R3F's canvas as the pointer
+ // events of a live play, or of a render given an input log, in the box the page laid out for it (pointer.ts)
+ let box: number[] | null | undefined;
+ const input = clock && ((i: number) => {
+ const e = clock.input[clock.frame - frame + i];
+ if (!e) return undefined;
+ if (box === undefined) box = viewBox();
+ return inCanvas(wireKeys({ ...e, keys: Array.isArray(e.keys) ? [...e.keys] : [] } as FrameInput), [width, height], box);
+ });
+ const s = stepTo(name ?? id, frame, fps, width, height, config, at, input ?? undefined);
const { scene, camera, gl } = s.state as unknown as { scene: THREE.Scene; camera: THREE.Camera; gl: THREE.WebGLRenderer };
// R3F's clock: what a node material's `time` reads (useFrame's own steps, 1/fps a frame)
const r3fClock = (s.state as unknown as { clock: { elapsedTime: number } }).clock;
diff --git a/sdk/r3f/src/input/pointer.ts b/sdk/r3f/src/input/pointer.ts
new file mode 100644
index 00000000..3c103613
--- /dev/null
+++ b/sdk/r3f/src/input/pointer.ts
@@ -0,0 +1,147 @@
+// The pointer in a live play (docs/r3f.feature R3F27): raea's input, frame by frame, as the DOM events a browser would
+// have sent R3F's canvas. R3F's own event manager (its `events`, connected to the stand-in canvas) raycasts each one
+// through the R3F camera and calls onClick, onPointerOver, onPointerMove and the rest on the mesh it hits; drei's
+// <OrbitControls> (three's controls) listen on the same canvas and its document. The events come from the input
+// timeline, a frame's against the frame before, so a render with no pointer sends none, and a root stepped again from
+// frame 0 gets the same events on the same frames: a recorded input log replays to the same frames.
+import type * as THREE from "three";
+import type { FrameInput } from "@raea/app/clock";
+import { hasNative, native } from "@raea/app/native";
+
+type Listener = (e: unknown) => void;
+
+/** a DOM event as R3F and three's controls read it: its type, the pointer, the buttons and the wheel */
+export type DomEvent = Record<string, unknown> & { type: string };
+
+/** a minimal EventTarget: listeners by type, called in the order added (an object's handleEvent as one function) */
+class Target {
+ private on = new Map<string, Set<Listener>>();
+ private fnOf(fn: Listener | { handleEvent: Listener; __raea?: Listener }): Listener {
+ return typeof fn === "function" ? fn : (fn.__raea ??= (e) => fn.handleEvent(e));
+ }
+ addEventListener(type: string, fn: Listener | { handleEvent: Listener } | null) {
+ if (!fn) return;
+ let set = this.on.get(type);
+ if (!set) this.on.set(type, (set = new Set()));
+ set.add(this.fnOf(fn));
+ }
+ removeEventListener(type: string, fn: Listener | { handleEvent: Listener } | null) {
+ if (fn) this.on.get(type)?.delete(this.fnOf(fn));
+ }
+ dispatchEvent(e: { type: string }): boolean {
+ for (const f of [...(this.on.get(e.type) ?? [])]) f(e);
+ return true;
+ }
+}
+
+/** What R3F and three's controls are given as the canvas: an event target the size of the <R3F>, whose document gets
+ * the events that bubble (a control's pointermove and pointerup after its pointerdown) */
+export class EventCanvas extends Target {
+ style: Record<string, string> = {};
+ readonly ownerDocument = Object.assign(new Target(), { body: {}, documentElement: {} });
+ constructor(public width: number, public height: number) {
+ super();
+ }
+ get clientWidth() {
+ return this.width;
+ }
+ get clientHeight() {
+ return this.height;
+ }
+ getBoundingClientRect() {
+ const { width, height } = this;
+ return { left: 0, top: 0, width, height, x: 0, y: 0, right: width, bottom: height };
+ }
+ getRootNode() {
+ return this.ownerDocument;
+ }
+ setPointerCapture() {}
+ releasePointerCapture() {}
+ hasPointerCapture() {
+ return false;
+ }
+ focus() {}
+ getContext() {
+ return null;
+ }
+}
+
+/** the events that bubble from the canvas to its document */
+const BUBBLES = new Set(["pointerdown", "pointermove", "pointerup", "click", "contextmenu", "wheel"]);
+
+/** a DOM button's number, by Bevy's MouseButton name (FrameInput's `buttons`) */
+const BUTTON: Record<string, number> = { Middle: 1, Right: 2, Back: 3, Forward: 4 };
+
+/** the DOM's `buttons` bitmask for what's held */
+function held(i: FrameInput | undefined): number {
+ let b = i?.pointer?.down ? 1 : 0;
+ for (const n of i?.buttons ?? []) b |= n === "Right" ? 2 : n === "Middle" ? 4 : n === "Back" ? 8 : n === "Forward" ? 16 : 0;
+ return b;
+}
+
+/** The DOM events that take R3F's canvas from input `prev` to `now`, in the order a browser sends them: the move, the
+ * presses, the releases (a primary release a click as well, a right press the context menu), the wheel; the pointer
+ * gone, a pointerleave. x and y are frame px, the canvas's own when the <R3F> fills the frame. */
+export function eventsBetween(prev: FrameInput | undefined, now: FrameInput | undefined): DomEvent[] {
+ const p = now?.pointer ?? prev?.pointer;
+ if (!p) return [];
+ const keys = now?.keys ?? [];
+ const base = (type: string, button = 0, buttons = held(now)) => ({
+ type, offsetX: p.x, offsetY: p.y, clientX: p.x, clientY: p.y, pageX: p.x, pageY: p.y, screenX: p.x, screenY: p.y,
+ button, buttons, pointerId: 1, pointerType: "mouse", isPrimary: true, deltaX: 0, deltaY: 0, deltaMode: 0,
+ shiftKey: keys.includes("Shift"), ctrlKey: keys.includes("Control"), altKey: keys.includes("Alt"), metaKey: keys.includes("Meta"),
+ });
+ if (!now?.pointer) return [base("pointerleave", 0, 0)];
+ const out: DomEvent[] = [];
+ const was = prev?.pointer;
+ if (!was || was.x !== p.x || was.y !== p.y) out.push(base("pointermove", -1));
+ // presses before releases: a button pressed and another let go in one frame
+ if (p.down && !was?.down) out.push(base("pointerdown", 0));
+ for (const n of now.buttons ?? []) if (!prev?.buttons?.includes(n) && BUTTON[n] !== undefined) {
+ out.push(base("pointerdown", BUTTON[n]));
+ if (n === "Right") out.push(base("contextmenu", 2));
+ }
+ if (!p.down && was?.down) out.push(base("pointerup", 0), base("click", 0));
+ for (const n of prev?.buttons ?? []) if (!now.buttons?.includes(n) && BUTTON[n] !== undefined) out.push(base("pointerup", BUTTON[n]));
+ if (now.wheel && (now.wheel.x || now.wheel.y)) out.push({ ...base("wheel", 0), deltaX: now.wheel.x, deltaY: now.wheel.y });
+ return out;
+}
+
+/** The box the <R3F>'s camera draws its view in, [x, y, w, h] in frame px, as the page last laid it out: a camera in a
+ * page element picks in its box (sdk/render events3d's page.viewBox). None when it fills the frame, or from a host
+ * that can't say */
+export function viewBox(): number[] | null {
+ if (!hasNative()) return null;
+ try {
+ return (native as (n: string, a: object) => number[] | null)("page.viewBox", {});
+ } catch {
+ return null;
+ }
+}
+
+/** `i` with its pointer in R3F's canvas px (`size`): the frame's, or in a box, the box's, scaled to R3F's size. Off
+ * the box, the pointer is gone, unless it's pressed (a drag goes on outside the canvas, as a browser's does) */
+export function inCanvas(i: FrameInput | undefined, size: [number, number], box: number[] | null): FrameInput | undefined {
+ const p = i?.pointer;
+ if (!p || !box) return i;
+ const [x, y, w, h] = box;
+ const off = p.x < x || p.y < y || p.x >= x + w || p.y >= y + h;
+ if (off && !p.down) return { ...i, pointer: undefined };
+ return { ...i, pointer: { x: ((p.x - x) * size[0]) / w, y: ((p.y - y) * size[1]) / h, down: p.down } };
+}
+
+/** Each event dispatched on `canvas` (and its document, for those that bubble), with the scene's and camera's matrices
+ * as the last frame left them (three's renderer updates them as it draws, before an event raycasts against them) */
+export function dispatchInput(canvas: EventCanvas, drawn: (THREE.Object3D | undefined)[], events: DomEvent[]) {
+ if (!events.length) return;
+ for (const o of drawn) o?.updateMatrixWorld();
+ for (const raw of events) {
+ let stopped = false;
+ const e = Object.assign(raw, {
+ target: canvas, currentTarget: canvas, timeStamp: 0,
+ preventDefault() {}, stopPropagation() { stopped = true; },
+ });
+ canvas.dispatchEvent(e);
+ if (BUBBLES.has(e.type) && !stopped) canvas.ownerDocument.dispatchEvent(e);
+ }
+}
diff --git a/sdk/r3f/src/input/session.ts b/sdk/r3f/src/input/session.ts
index 6349dc10..f51cbe64 100644
--- a/sdk/r3f/src/input/session.ts
+++ b/sdk/r3f/src/input/session.ts
@@ -4,8 +4,10 @@
// step since the last frame. Going backwards (a seek, a scrub) starts the root again from frame 0 and steps forward, so
// a frame's scene is the same whichever frame came before it: a render equals its play (raea's first rule).
import * as THREE from "three";
-import { advance, createRoot, extend, flushSync, type ReconcilerRoot, type RenderProps, type RootState } from "@react-three/fiber";
+import { advance, createRoot, events, extend, flushSync, type ReconcilerRoot, type RenderProps, type RootState } from "@react-three/fiber";
import { Component, createElement, type ReactNode } from "react";
+import type { FrameInput } from "@raea/app/clock";
+import { dispatchInput, EventCanvas, eventsBetween } from "./pointer";
import { standInRenderer } from "./renderer";
import { nextRandom, seedOf } from "./seed";
@@ -13,11 +15,6 @@ export { standInRenderer, warnOnce } from "./renderer";
extend(THREE as unknown as Parameters<typeof extend>[0]);
-function standInCanvas(width: number, height: number): HTMLCanvasElement {
- const noop = () => {};
- return { style: {}, width, height, addEventListener: noop, removeEventListener: noop, getBoundingClientRect: () => ({ left: 0, top: 0, width, height, x: 0, y: 0, right: width, bottom: height }) } as unknown as HTMLCanvasElement;
-}
-
export interface Session {
root: ReconcilerRoot<HTMLCanvasElement>;
state: RootState;
@@ -29,6 +26,10 @@ export interface Session {
subs: number;
/** its Math.random's state: seeded as it starts, so a root started again draws the same numbers */
rand: number;
+ /** the canvas R3F's events and three's controls listen on (pointer.ts) */
+ canvas: EventCanvas;
+ /** the input its events last came from */
+ input?: FrameInput;
}
/** Math.random as `s`'s own generator (mulberry32) while `fn` runs: drei's <Float> phase, <Sparkles>, three's uuids
@@ -63,16 +64,21 @@ class Caught extends Component<{ on: (error: unknown) => void; children?: ReactN
export type Config = Omit<RenderProps<HTMLCanvasElement>, "gl" | "frameloop" | "size" | "events" | "dpr">;
function start(key: string, width: number, height: number, config: Config, json: string): Session {
- const root = createRoot(standInCanvas(width, height));
+ const canvas = new EventCanvas(width, height);
+ const root = createRoot(canvas as unknown as HTMLCanvasElement);
let state: RootState | undefined;
- void root.configure({ ...config, gl: standInRenderer(), frameloop: "never", dpr: 1, size: { width, height, top: 0, left: 0 }, events: undefined, onCreated: (s) => { state = s; config.onCreated?.(s); } });
- const s: Session = { root, state: state as unknown as RootState, frame: -1, config: json, subs: 0, rand: seedOf(key) };
+ // the renderer's canvas the same one: drei's controls take gl.domElement before R3F's events connect to the canvas
+ const gl = Object.assign(standInRenderer(), { domElement: canvas as unknown as HTMLCanvasElement });
+ // R3F's own event manager, connected to the canvas as it mounts: the pointer events of a live play (pointer.ts)
+ void root.configure({ ...config, gl, frameloop: "never", dpr: 1, size: { width, height, top: 0, left: 0 }, events, onCreated: (s) => { state = s; config.onCreated?.(s); } });
+ const s: Session = { root, state: state as unknown as RootState, frame: -1, config: json, subs: 0, rand: seedOf(key), canvas };
sessions.set(key, s);
return s;
}
-/** The root `key` at local frame `frame` (fps a second), each step rendering `scene(i)` first. */
-export function stepTo(key: string, frame: number, fps: number, width: number, height: number, config: Config, scene: (i: number) => ReactNode): Session {
+/** The root `key` at local frame `frame` (fps a second), each step rendering `scene(i)` first. `input(i)`: the input at
+ * local frame i, sent to R3F's canvas as the pointer events since the frame before (pointer.ts) */
+export function stepTo(key: string, frame: number, fps: number, width: number, height: number, config: Config, scene: (i: number) => ReactNode, input?: (i: number) => FrameInput | undefined): Session {
const json = JSON.stringify({ width, height, config }, (_k, v) => (typeof v === "function" ? String(v) : v instanceof THREE.Object3D ? v.uuid : v));
let s = sessions.get(key);
if (s && (frame < s.frame || s.config !== json)) {
@@ -103,13 +109,23 @@ export function stepTo(key: string, frame: number, fps: number, width: number, h
if (subsOf(live) > live.subs && !late.has(key)) {
late.add(key);
end(key);
- return stepTo(key, frame, fps, width, height, config, scene);
+ return stepTo(key, frame, fps, width, height, config, scene, input);
}
}
+ // the pointer's events since the frame before, as a browser sends them between two frames: what their handlers set
+ // is drawn this step. Before the root first renders there's nothing to hit and nothing listening: after it
+ const send = (i: number) => {
+ const now = input?.(i);
+ const evs = eventsBetween(live.input, now);
+ live.input = now;
+ if (evs.length) seeded(live, () => flushSync(() => dispatchInput(live.canvas, [live.state?.scene, live.state?.camera], evs)));
+ };
for (let i = s.frame + 1; i <= frame; i++) {
// what it draws into targets is this step's (R3F23): the last step's passes go
(live.state?.gl as unknown as { __raea?: { step?: () => void } } | undefined)?.__raea?.step?.();
+ if (input && i > 0) send(i);
render(i);
+ if (input && i === 0) send(i);
seeded(live, () => advance(i / fps, true, live.state));
live.frame = i;
live.subs = subsOf(live);
diff --git a/sdk/r3f/test/esm.ts b/sdk/r3f/test/esm.ts
index 65ce9230..472ccaa0 100644
--- a/sdk/r3f/test/esm.ts
+++ b/sdk/r3f/test/esm.ts
@@ -11,5 +11,15 @@ plugin({
contents: readFileSync(a.path.replace(/\.cjs\.js$/, ".esm.js"), "utf8"),
loader: "js",
}));
+ // drei and three-stdlib the same: their CommonJS builds require three's (OrbitControls' instanceof
+ // PerspectiveCamera failed, so the wheel's dolly was off)
+ b.onLoad({ filter: /@react-three\/drei\/index\.cjs\.js$/ }, (a) => ({
+ contents: readFileSync(a.path.replace(/\.cjs\.js$/, ".js"), "utf8"),
+ loader: "js",
+ }));
+ b.onLoad({ filter: /three-stdlib\/.+\.cjs$/ }, (a) => ({
+ contents: readFileSync(a.path.replace(/\.cjs$/, ".js"), "utf8"),
+ loader: "js",
+ }));
},
});
diff --git a/sdk/r3f/test/live/pointer.json b/sdk/r3f/test/live/pointer.json
new file mode 100644
index 00000000..c7e4f300
--- /dev/null
+++ b/sdk/r3f/test/live/pointer.json
@@ -0,0 +1,12 @@
+{
+ "0": ["Pointer:600:40"],
+ "4": ["Pointer:227:180"],
+ "8": ["Pointer:227:180:down"],
+ "10": ["Pointer:227:180"],
+ "14": ["Pointer:600:300"],
+ "16": ["Pointer:600:300:down"],
+ "18": ["Pointer:540:300:down"],
+ "20": ["Pointer:480:300:down"],
+ "22": ["Pointer:420:300:down"],
+ "24": ["Pointer:420:300"]
+}
diff --git a/sdk/r3f/test/live/pointer.tsx b/sdk/r3f/test/live/pointer.tsx
new file mode 100644
index 00000000..67fc4b92
--- /dev/null
+++ b/sdk/r3f/test/live/pointer.tsx
@@ -0,0 +1,32 @@
+// R3F's pointer events and drei's <OrbitControls> in a live play (docs/r3f.feature R3F27): the ball turns yellow under
+// the pointer and green once clicked, and a drag on the empty frame turns the camera. bench/render-play plays it with
+// pointer.json's input and renders the input it logged: the same frames (render = play).
+import { useState } from "react";
+import { Composition, registerRoot } from "raea";
+import { R3F } from "raea/r3f";
+import { OrbitControls } from "@react-three/drei";
+
+function Ball() {
+ const [hot, setHot] = useState(false);
+ const [on, setOn] = useState(false);
+ return (
+ <mesh position={[-1.2, 0, 0]} onPointerOver={() => setHot(true)} onPointerOut={() => setHot(false)} onClick={() => setOn((v) => !v)}>
+ <sphereGeometry args={[0.8, 32, 16]} />
+ <meshBasicMaterial color={on ? (hot ? "#88ff99" : "#22dd44") : hot ? "#ffcc00" : "#4466ff"} />
+ </mesh>
+ );
+}
+
+const Pointer = () => (
+ <R3F flat camera={{ position: [0, 0, 5], fov: 50 }}>
+ <color attach="background" args={["#111"]} />
+ <OrbitControls enableDamping={false} />
+ <Ball />
+ <mesh position={[1.2, 0, 0]}>
+ <boxGeometry args={[1.2, 1.2, 1.2]} />
+ <meshNormalMaterial />
+ </mesh>
+ </R3F>
+);
+
+registerRoot(() => <Composition id="pointer" component={Pointer} width={640} height={360} fps={30} durationInFrames={60} />);
diff --git a/sdk/r3f/test/pointer.test.tsx b/sdk/r3f/test/pointer.test.tsx
new file mode 100644
index 00000000..d5b2e17f
--- /dev/null
+++ b/sdk/r3f/test/pointer.test.tsx
@@ -0,0 +1,120 @@
+// R3F's pointer events and controls in a live play (docs/r3f.feature R3F27, src/input/pointer.ts): raea's input, frame
+// by frame, sent to R3F's canvas as a browser's DOM events, so R3F's handlers fire on the mesh under the pointer and
+// drei's <OrbitControls> turn the camera; no input sends nothing, and the same input stepped again gives the same frames.
+import { describe, expect, test } from "bun:test";
+import { OrbitControls } from "@react-three/drei";
+import type { ReactNode } from "react";
+import * as THREE from "three";
+import type { FrameInput } from "@raea/app/clock";
+import { eventsBetween, inCanvas } from "../src/input/pointer";
+import { end, stepTo } from "../src/input/session";
+
+const at = (x: number, y: number, down = false, more: Partial<FrameInput> = {}): FrameInput => ({ keys: [], pointer: { x, y, down }, ...more });
+const types = (prev: FrameInput | undefined, now: FrameInput | undefined) => eventsBetween(prev, now).map((e) => `${e.type}:${e.button}`);
+
+describe("raea's input as DOM events", () => {
+ test("a move, a press, a release and its click, in a browser's order", () => {
+ expect(types(undefined, at(10, 20))).toEqual(["pointermove:-1"]);
+ expect(types(at(10, 20), at(10, 20))).toEqual([]);
+ expect(types(at(10, 20), at(12, 20, true))).toEqual(["pointermove:-1", "pointerdown:0"]);
+ expect(types(at(12, 20, true), at(12, 20))).toEqual(["pointerup:0", "click:0"]);
+ expect(eventsBetween(at(0, 0), at(30, 40))[0]).toMatchObject({ offsetX: 30, offsetY: 40, clientX: 30, pointerType: "mouse", buttons: 0 });
+ });
+
+ test("the other buttons, the wheel, the modifier keys and the pointer gone", () => {
+ expect(types(at(5, 5), at(5, 5, false, { buttons: ["Right"] }))).toEqual(["pointerdown:2", "contextmenu:2"]);
+ expect(types(at(5, 5, false, { buttons: ["Right"] }), at(5, 5))).toEqual(["pointerup:2"]);
+ const wheel = eventsBetween(at(5, 5), at(5, 5, false, { wheel: { x: 0, y: 120 } }));
+ expect(wheel).toMatchObject([{ type: "wheel", deltaY: 120 }]);
+ expect(eventsBetween(at(5, 5), at(6, 5, true, { keys: ["Shift"] }))[1]).toMatchObject({ type: "pointerdown", shiftKey: true, buttons: 1 });
+ expect(types(at(5, 5), undefined)).toEqual(["pointerleave:0"]);
+ expect(types(undefined, undefined)).toEqual([]);
+ });
+
+ test("in a box, the pointer is the box's, scaled to R3F's size; off it, gone unless pressed", () => {
+ const box = [100, 50, 400, 300];
+ expect(inCanvas(at(300, 200), [400, 300], box)!.pointer).toEqual({ x: 200, y: 150, down: false });
+ expect(inCanvas(at(300, 200), [800, 600], box)!.pointer).toEqual({ x: 400, y: 300, down: false });
+ expect(inCanvas(at(20, 20), [400, 300], box)!.pointer).toBeUndefined();
+ expect(inCanvas(at(20, 20, true), [400, 300], box)!.pointer).toEqual({ x: -80, y: -30, down: true });
+ expect(inCanvas(at(20, 20), [400, 300], null)!.pointer).toEqual({ x: 20, y: 20, down: false });
+ });
+});
+
+let n = 0;
+/** the root stepped to `frame` with input `input(i)` at frame i (400 x 400, R3F's default camera at z 5) */
+function stepped(scene: () => ReactNode, frame: number, input?: (i: number) => FrameInput | undefined, key = `pointer${n++}`) {
+ return stepTo(key, frame, 30, 400, 400, {}, scene, input);
+}
+
+describe("R3F's events on the mesh under the pointer", () => {
+ const said: string[] = [];
+ const Box = () => (
+ <mesh
+ onPointerOver={() => said.push("over")}
+ onPointerOut={() => said.push("out")}
+ onPointerDown={() => said.push("down")}
+ onClick={(e) => said.push(`click ${e.object.type} ${e.point.z.toFixed(2)}`)}
+ onPointerMissed={() => said.push("missed")}
+ >
+ <boxGeometry />
+ <meshBasicMaterial />
+ </mesh>
+ );
+ // over the box from frame 1, pressed at 3, let go at 4, off it at 6, a press and release there at 7 and 8
+ const script = (i: number): FrameInput | undefined =>
+ i < 1 ? undefined : i < 6 ? at(200, 200, i === 3) : at(20, 20, i === 7);
+
+ test("over, down, click with the hit's point, out, and a click on nothing missed", () => {
+ said.length = 0;
+ const key = "pointer-box";
+ stepped(Box, 9, script, key);
+ end(key);
+ expect(said).toEqual(["over", "down", "click Mesh 0.50", "out", "missed"]);
+ });
+
+ test("a render with no input sends nothing, and the same input stepped again says the same", () => {
+ said.length = 0;
+ stepped(Box, 9);
+ expect(said).toEqual([]);
+ const once = (key: string) => {
+ said.length = 0;
+ stepped(Box, 9, script, key);
+ end(key);
+ return [...said];
+ };
+ expect(once("pointer-a")).toEqual(once("pointer-b"));
+ });
+});
+
+describe("drei's <OrbitControls>", () => {
+ const scene = () => (
+ <>
+ <OrbitControls />
+ <mesh><boxGeometry /><meshBasicMaterial /></mesh>
+ </>
+ );
+ // a drag 100 px to the right from frame 2 to 6, then a turn of the wheel at 8
+ const drag = (i: number): FrameInput => at(200 + Math.max(0, Math.min(i, 6) - 2) * 25, 200, i >= 2 && i < 6, i === 8 ? { wheel: { x: 0, y: 100 } } : {});
+ const cameraAt = (input?: (i: number) => FrameInput, frame = 9) => {
+ const key = `orbit${n++}`;
+ const s = stepped(scene, frame, input, key);
+ const c = (s.state.camera as THREE.Camera).position.clone();
+ end(key);
+ return c;
+ };
+
+ test("a drag turns the camera around the target and the wheel moves it back; no input leaves it", () => {
+ const still = cameraAt();
+ expect(still.toArray().map((v) => +v.toFixed(3))).toEqual([0, 0, 5]);
+ const turned = cameraAt(drag, 7);
+ expect(turned.length()).toBeCloseTo(5, 3);
+ expect(turned.x).toBeLessThan(-1);
+ const wheeled = cameraAt(drag, 9);
+ expect(wheeled.length()).toBeGreaterThan(5.2);
+ });
+
+ test("the same drag stepped again ends in the same place", () => {
+ expect(cameraAt(drag).toArray()).toEqual(cameraAt(drag).toArray());
+ });
+});