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.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
#164: an <R3F> object scaled to 0 draws nothing, as three draws it.
shinyobjectz2a5bb19904f1
diff --git a/sdk/r3f/src/input/decompose.ts b/sdk/r3f/src/input/decompose.tsnew file mode 100644index 00000000..2735833f--- /dev/null+++ b/sdk/r3f/src/input/decompose.ts@@ -0,0 +1,59 @@+// A matrix as position, rotation and scale, as three's Matrix4.decompose gives them, and also for a matrix with no+// volume (an axis scaled to 0: scale={0}, a pop-in's first frames, an instance hidden by scaling it away). three gives+// such a matrix the scale 1 and no rotation (its decompose, getWorldScale and extractBasis stop at a determinant of 0)+// but draws the object by the matrix itself: as nothing, or flattened. Read through three's decompose, a scale of 0+// came out as 1 and raea drew the object at full size (#164). Here it is the axes' own lengths, turned as the axes it+// keeps are.+import * as THREE from "three";++const axes = [new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3()];+const turn = new THREE.Matrix4();+const across = new THREE.Vector3();++/** `m`'s position, rotation and scale into p, q and s: three's own decompose where its determinant isn't 0 (the same+ * numbers, bit for bit), else each axis's length as its scale (0 for an axis it flattens) and the rotation of the axes+ * it keeps, completed to a turn. Its determinant() is three's determinantAffine() on an object's matrix, the test+ * three's decompose makes. */+export function decompose(m: THREE.Matrix4, p: THREE.Vector3, q: THREE.Quaternion, s: THREE.Vector3): void {+ if (m.determinant() !== 0) {+ m.decompose(p, q, s);+ return;+ }+ p.setFromMatrixPosition(m);+ // the columns as they are (three's extractBasis gives such a matrix the unit axes too)+ axes.forEach((a, i) => a.setFromMatrixColumn(m, i));+ // each axis made square to the ones kept before it; one with no length, or none of its own, is scaled to 0+ const kept: number[] = [];+ axes.forEach((a, i) => {+ const length = a.length();+ for (const k of kept) a.addScaledVector(axes[k], -a.dot(axes[k]));+ const own = a.length() > 1e-9 * length && length > 0;+ s.setComponent(i, own ? length : 0);+ if (own) {+ a.normalize();+ kept.push(i);+ }+ });+ if (!kept.length) {+ q.identity();+ return;+ }+ if (kept.length === 1) {+ // a line: any axis square to it as the next (the world axis least along it, made square)+ const i = kept[0], a = axes[i], j = (i + 1) % 3;+ const along = [Math.abs(a.x), Math.abs(a.y), Math.abs(a.z)];+ across.set(0, 0, 0).setComponent(along.indexOf(Math.min(...along)), 1);+ axes[j].copy(across).addScaledVector(a, -across.dot(a)).normalize();+ kept.push(j);+ }+ if (kept.length === 2) {+ // a plane: the axis it flattens is the other two's cross product, in turn (x = y × z, y = z × x, z = x × y)+ const l = 3 - kept[0] - kept[1];+ axes[l].crossVectors(axes[(l + 1) % 3], axes[(l + 2) % 3]);+ } else if (across.crossVectors(axes[0], axes[1]).dot(axes[2]) < 0) {+ // all three kept (a determinant under the smallest number, every axis scaled tiny): a mirror on x, as three's+ axes[0].negate();+ s.x = -s.x;+ }+ q.setFromRotationMatrix(turn.makeBasis(axes[0], axes[1], axes[2]));+}diff --git a/sdk/r3f/src/input/scene.ts b/sdk/r3f/src/input/scene.tsindex 1031384b..342488bc 100644--- a/sdk/r3f/src/input/scene.ts+++ b/sdk/r3f/src/input/scene.ts@@ -9,6 +9,7 @@ import "./passes";import { passesOf } from "./targets";import { flipsY } from "./texture";import { arraysOf, posed, posedArrays, rewound, type Arrays } from "./geometry";+import { decompose } from "./decompose";import { isTroikaText, textParts } from "./text";import { clipArrays, clipOf, type Clip } from "./clip";import { cameraOf, fogOf, lightsOf, skyOf, toneOf } from "./lights";@@ -23,10 +24,11 @@ import { nodeInstancedParts } from "./tsl-instances";type V3 = [number, number, number];type Q = [number, number, number, number];-/** an object's own transform, from its matrix (so matrixAutoUpdate={false} objects come out as three draws them) */+/** an object's own transform, from its matrix (so matrixAutoUpdate={false} objects come out as three draws them); a+ * scale of 0 stays 0 (decompose.ts, #164) */function place(o: THREE.Object3D): Props {const p = new THREE.Vector3(), q = new THREE.Quaternion(), s = new THREE.Vector3();- o.matrix.decompose(p, q, s);+ decompose(o.matrix, p, q, s);const out: Props = { position: p.toArray() as V3, quaternion: q.toArray() as Q };out.scale = s.x === s.y && s.y === s.z && s.x > 0 ? s.x : (s.toArray() as V3);return out;@@ -151,7 +153,7 @@ function instancedParts(m: THREE.InstancedMesh, name: string, w: Walk, at: Propsconst copies = new Array(n);for (let i = 0; i < n; i++) {m.getMatrixAt(i, one);- one.decompose(p, q, s);+ decompose(one, p, q, s);const hide = i >= shown || !Number.isFinite(p.x + p.y + p.z + q.x + q.y + q.z + q.w + s.x + s.y + s.z);const size = (v: number) => (hide ? 1e-5 : Math.max(Math.abs(v), 1e-5));e.setFromQuaternion(hide ? q.identity() : q, "XYZ");@@ -171,7 +173,7 @@ function copyParts(m: THREE.InstancedMesh, name: string, w: Walk, at: Props): Paconst kids: Part[] = [];for (let i = 0; i < Math.min(m.count, m.instanceMatrix.count); i++) {m.getMatrixAt(i, one);- one.decompose(p, q, s);+ decompose(one, p, q, s);for (const part of meshParts(m, `${name}.${i}`, w, { position: p.toArray() as V3, quaternion: q.toArray() as Q, scale: s.toArray() as V3 })) {if (m.instanceColor) {m.getColorAt(i, c);@@ -202,7 +204,7 @@ function batchedParts(b: THREE.BatchedMesh, name: string, w: Walk): Part[] {const arrays = arraysOf(b.geometry, { start: range.start, count: range.count, flipV: flipped(material), colors: false });if (!arrays) return;b.getMatrixAt(i, one);- one.decompose(p, q, s);+ decompose(one, p, q, s);let own = surface;if (colours) {b.getColorAt(i, c);@@ -355,7 +357,9 @@ function spriteParts(s: THREE.Sprite, name: string, w: Walk): Part[] {const mat = s.material;if (!mat.visible) return [];const pos = s.getWorldPosition(new THREE.Vector3());- const scale = s.getWorldScale(new THREE.Vector3());+ // three's sprite shader sizes it by its world matrix's axes: none, in a group scaled to 0 (#164)+ const scale = new THREE.Vector3();+ decompose(s.matrixWorld, new THREE.Vector3(), new THREE.Quaternion(), scale);const q = w.camera.getWorldQuaternion(new THREE.Quaternion()).multiply(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 0, 1), mat.rotation));const [cx, cy] = [s.center.x, s.center.y];const positions = [-cx, -cy, 0, 1 - cx, -cy, 0, 1 - cx, 1 - cy, 0, -cx, 1 - cy, 0];diff --git a/sdk/r3f/test/scale.test.tsx b/sdk/r3f/test/scale.test.tsxnew file mode 100644index 00000000..319bb8c8--- /dev/null+++ b/sdk/r3f/test/scale.test.tsx@@ -0,0 +1,117 @@+// An object scaled to 0 (#164): three draws it by its matrix, as nothing (or flat), where three's own Matrix4.decompose+// gives a matrix with no volume the scale 1 and no rotation. sdk/r3f reads transforms through decompose.ts, so a scale+// of 0 stays 0, and a flattened object keeps its turn.+import { describe, expect, test } from "bun:test";+import { useFrame } from "@react-three/fiber";+import { useRef } from "react";+import * as THREE from "three";+import { decompose } from "../src/input/decompose";+import { convert } from "../src/input/scene";+import { end, stepTo } from "../src/input/session";+import type { Part } from "../src/parts";+import type { ReactNode } from "react";++const flat = (parts: Part[]): Part[] => parts.flatMap((p) => [p, ...flat(p.children ?? [])]);+let n = 0;+function partsOf(scene: (i: number) => ReactNode, frame = 0) {+ const key = `scale${n++}`;+ const s = stepTo(key, frame, 24, 640, 360, {}, scene);+ const st = s.state as unknown as { scene: THREE.Scene; camera: THREE.Camera; gl: THREE.WebGLRenderer };+ const parts = flat(convert(st.scene, st.camera, st.gl, 360).parts);+ end(key);+ return parts;+}+const named = (parts: Part[], name: string) => parts.find((p) => String(p.props.name).split(":")[1]?.replace(/\/$/, "") === name)!;+/** a part's transform composed again, as raea's engine composes it (core/scene props.rs local) */+const matrixOf = (p: Part) => {+ const s = p.props.scale as number | number[];+ return new THREE.Matrix4().compose(new THREE.Vector3(...(p.props.position as number[])), new THREE.Quaternion(...(p.props.quaternion as number[])), typeof s === "number" ? new THREE.Vector3(s, s, s) : new THREE.Vector3(...s));+};+const same = (a: THREE.Matrix4, b: THREE.Matrix4) => a.elements.every((x, i) => Math.abs(x - b.elements[i]) < 1e-9);+const box = <><boxGeometry /><meshBasicMaterial /></>;++describe("decompose", () => {+ test("a matrix with volume: three's decompose, the same numbers", () => {+ const m = new THREE.Matrix4().compose(new THREE.Vector3(1, 2, 3), new THREE.Quaternion().setFromEuler(new THREE.Euler(0.3, -1.1, 2)), new THREE.Vector3(-2, 0.5, 1e-4));+ const [p, q, s, p3, q3, s3] = [new THREE.Vector3(), new THREE.Quaternion(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Quaternion(), new THREE.Vector3()];+ decompose(m, p, q, s);+ m.decompose(p3, q3, s3);+ expect([...p.toArray(), ...q.toArray(), ...s.toArray()]).toEqual([...p3.toArray(), ...q3.toArray(), ...s3.toArray()]);+ });++ test("a matrix with no volume composes back to itself: its scale 0, its turn kept", () => {+ const turn = new THREE.Quaternion().setFromEuler(new THREE.Euler(0.7, 0.2, -1.3));+ const scales = [[0, 0, 0], [1, 0, 2], [0, 3, 0], [0, 0, 0.5], [-1, 0, 1], [2, 2, 0], [1e-110, 1e-110, -1e-110]];+ for (const sc of scales) {+ const m = new THREE.Matrix4().compose(new THREE.Vector3(4, -5, 6), turn, new THREE.Vector3(...sc));+ const [p, q, s] = [new THREE.Vector3(), new THREE.Quaternion(), new THREE.Vector3()];+ decompose(m, p, q, s);+ expect(p.toArray()).toEqual([4, -5, 6]);+ expect(Math.abs(q.length() - 1)).toBeLessThan(1e-12);+ // each axis's length (to rounding), an axis scaled to 0 exactly 0+ expect([sc, s.toArray().map((x, i) => Math.abs(Math.abs(x) - Math.abs(sc[i])) <= 1e-12 * Math.abs(sc[i]))]).toEqual([sc, [true, true, true]]);+ const back = new THREE.Matrix4().compose(p, q, s);+ // the tiny scale's elements are about 1e-110: compared relative to it+ expect(back.elements.every((x, i) => Math.abs(x - m.elements[i]) <= 1e-9 * Math.max(1e-200, ...sc.map(Math.abs)))).toBe(true);+ }+ // three's own gives each of these the scale 1, which drew a scale of 0 at full size+ const zero = new THREE.Vector3();+ new THREE.Matrix4().makeScale(0, 0, 0).decompose(new THREE.Vector3(), new THREE.Quaternion(), zero);+ expect(zero.toArray()).toEqual([1, 1, 1]);+ });+});++function PopIn() {+ const ref = useRef<THREE.Mesh>(null!);+ useFrame(() => ref.current.scale.setScalar(0));+ return <mesh ref={ref} name="frame">{box}</mesh>;+}++describe("an object scaled to 0 (#164)", () => {+ test("is sent scaled to 0: a group's scale={0}, a mesh's [0, 0, 0], scale.set, a pop-in before it starts, useFrame", () => {+ const set = new THREE.Mesh(new THREE.BoxGeometry(), new THREE.MeshBasicMaterial());+ set.scale.set(0, 0, 0);+ const parts = partsOf((i) => (+ <>+ <group name="group" scale={0}><mesh>{box}</mesh></group>+ <mesh name="mesh" position={[1, 0, 0]} scale={[0, 0, 0]}>{box}</mesh>+ <primitive name="set" object={set} />+ <mesh name="pop" scale={Math.min(1, Math.max(0, (i - 10) / 10))}>{box}</mesh>+ <PopIn />+ <mesh name="half" scale={0.5}>{box}</mesh>+ </>+ ));+ for (const name of ["group", "mesh", "set", "pop", "frame"]) {+ const s = named(parts, name).props.scale;+ expect([name, s]).toEqual([name, [0, 0, 0]]);+ }+ expect(named(parts, "mesh").props.position).toEqual([1, 0, 0]);+ expect(named(parts, "half").props.scale).toBe(0.5);+ });++ test("a flattened object keeps its turn: scale [1, 0, 2] turned 45 degrees is the same matrix in raea", () => {+ const parts = partsOf(() => <mesh name="flat" position={[0, 1, 0]} rotation={[0, Math.PI / 4, 0]} scale={[1, 0, 2]}>{box}</mesh>);+ const p = named(parts, "flat");+ expect(p.props.scale).toEqual([1, 0, 2]);+ const three = new THREE.Matrix4().compose(new THREE.Vector3(0, 1, 0), new THREE.Quaternion().setFromEuler(new THREE.Euler(0, Math.PI / 4, 0)), new THREE.Vector3(1, 0, 2));+ expect(same(matrixOf(p), three)).toBe(true);+ });++ test("an instance scaled to 0 is shrunk to nothing, a sprite in a group scaled to 0 too", () => {+ const im = new THREE.InstancedMesh(new THREE.BoxGeometry(), new THREE.MeshStandardMaterial(), 2);+ const m = new THREE.Matrix4();+ im.setMatrixAt(0, m.makeTranslation(1, 0, 0));+ im.setMatrixAt(1, m.makeScale(0, 0, 0).setPosition(2, 0, 0));+ const parts = partsOf(() => (+ <>+ <primitive object={im} />+ <group scale={0}><sprite name="sprite"><spriteMaterial /></sprite></group>+ </>+ ));+ const at = parts.find((p) => p.type === "Instances")!.props.at as { position: number[]; scale: number[] }[];+ expect(at[0].scale).toEqual([1, 1, 1]);+ expect(at[1].scale).toEqual([1e-5, 1e-5, 1e-5]);+ expect(at[1].position).toEqual([2, 0, 0]);+ expect(named(parts, "sprite").props.scale).toEqual([0, 0, 1]);+ });+});diff --git a/sdk/r3f/test/scale/check.sh b/sdk/r3f/test/scale/check.shnew file mode 100755index 00000000..359daadf--- /dev/null+++ b/sdk/r3f/test/scale/check.sh@@ -0,0 +1,20 @@+#!/bin/bash+# An <R3F> object scaled to 0 draws nothing, as in three (zero.tsx, #164): no green pixel in either still (unlit, and+# lit with shadows), and the red control box drawn. Before the fix the three green boxes drew at full size. Exits 1 on+# a failure.+# sdk/r3f/test/scale/check.sh (RAEA_BIN: the raea to run, default target/release/raea)+cd "$(dirname "$0")/../../../.." || exit 2+BIN=${RAEA_BIN:-$PWD/target/release/raea}+export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0 RAEA_AUDIO_MUTE=1+OUT=$(mktemp -d "${TMPDIR:-/tmp}/raea-r3f-scale.XXXXXX")+trap 'rm -rf "$OUT"' EXIT+for c in zero zero-lit; do+ "$BIN" render sdk/r3f/test/scale/zero.tsx --composition $c --frame 0 -o "$OUT/$c.png" > "$OUT/$c.log" 2>&1 || { echo "FAIL: $c: the render failed"; tail -3 "$OUT/$c.log"; exit 1; }+ # pixels of a colour: its channel 0.2 over each other (a lit face, tone mapped, is a paler green but still green)+ count() { magick "$OUT/$c.png" -alpha off -fx "$1" -format "%[fx:round(mean*w*h)]" info:; }+ green=$(count "g > r + 0.2 && g > b + 0.2")+ red=$(count "r > g + 0.2 && r > b + 0.2")+ [ "$red" -gt 0 ] || { echo "FAIL: $c: the control box isn't drawn (no red pixel)"; exit 1; }+ [ "$green" -eq 0 ] || { echo "FAIL: $c: $green green pixels: an object scaled to 0 is drawn"; exit 1; }+ echo "PASS: $c: an <R3F> object scaled to 0 draws nothing ($red red pixels of the control, 0 green)"+donediff --git a/sdk/r3f/test/scale/zero.tsx b/sdk/r3f/test/scale/zero.tsxnew file mode 100644index 00000000..08b756ee--- /dev/null+++ b/sdk/r3f/test/scale/zero.tsx@@ -0,0 +1,50 @@+// #164: inside <R3F>, an object scaled to 0 draws nothing, as three draws it. Green is scaled to 0 three ways (a group's+// scale={0}, a mesh's [0, 0, 0], and a pop-in from 0 before it starts); the red box is the control, drawn at half size,+// so a frame with no green says the zero scales drew nothing, not that nothing was drawn. Before the fix every green+// box drew at full size (three's Matrix4.decompose gives a matrix with no volume the scale 1).+import { AbsoluteFill, Composition, interpolate, registerRoot, useCurrentFrame } from "raea";+import { R3F } from "raea/r3f";++// lit: a standard material under a light casting shadows onto a floor, as a character is drawn+function Scene({ lit }: { lit: boolean }) {+ const pop = interpolate(useCurrentFrame(), [10, 20], [0, 1], { extrapolateLeft: "clamp", extrapolateRight: "clamp" });+ const green = lit ? <meshStandardMaterial color="#00ff00" /> : <meshBasicMaterial color="#00ff00" />;+ return (+ <AbsoluteFill style={{ background: "#0000ff" }}>+ <R3F flat={!lit} shadows={lit} camera={{ position: [0, 0, 5], fov: 50 }}>+ {lit && <directionalLight position={[2, 4, 5]} intensity={3} castShadow />}+ {lit && <ambientLight intensity={0.5} />}+ {lit && (+ <mesh position={[0, 0, -1.5]} receiveShadow>+ <planeGeometry args={[20, 20]} />+ <meshStandardMaterial color="#0000ff" />+ </mesh>+ )}+ <mesh position={[-1.4, -1.4, 0]} scale={0.5} castShadow>+ <boxGeometry />+ {lit ? <meshStandardMaterial color="#ff0000" /> : <meshBasicMaterial color="#ff0000" />}+ </mesh>+ <group scale={0}>+ <mesh>+ <boxGeometry args={[2, 2, 2]} />+ {green}+ </mesh>+ </group>+ <mesh position={[1.4, 1.4, 0]} scale={[0, 0, 0]}>+ <boxGeometry />+ {green}+ </mesh>+ <mesh position={[-1.4, 1.4, 0]} scale={pop}>+ <boxGeometry />+ {green}+ </mesh>+ </R3F>+ </AbsoluteFill>+ );+}+registerRoot(() => (+ <>+ <Composition id="zero" component={() => <Scene lit={false} />} width={160} height={160} fps={30} durationInFrames={1} />+ <Composition id="zero-lit" component={() => <Scene lit />} width={160} height={160} fps={30} durationInFrames={1} />+ </>+));