Character games — a picture becomes a toy figure, and every figure gets a gallery
prompts/pkg/llms/character-games.md on every deploy, so it
can't drift from what the platform actually does. Read it from your terminal any
time with npx vibes-diy skills.
A character becomes a figure spec, and the spec becomes a toon action figure. A picture or a few words go to the model once; the answer is a small JSON spec (body proportions, colours, costume pattern, hair, mask, accessories, a pose), and one builder turns any spec into a cel-shaded three.js figure made of simple shapes with an ink outline. The spec is the record: small enough to save, share, edit with sliders and rebuild anywhere.
The moment this is for: someone holds up their superhero drawing, their
cosplay photo, the party's wizard or the class mascot and sees it stand on a
little stage and turn, in its own colours, holding its own gear. Then a whole
cast hangs on a wall, and each one steps forward as a figure. The worked
examples are two live vibes, jchris/hero-figure-lab (the character maker)
and jchris/hero-universe (a shared universe whose cast opens in the 3D
gallery).
The files: lib/figure.js (the spec, sanitizeSpec, buildFigure),
lib/sculpt.js (a picture or words → one callAI read → a spec), App.jsx
(the maker), components/Gallery3D.jsx (the room) and access.js (the
figures database).
The spec and its sanitizer
| field | shape |
|---|---|
body |
nine multipliers, 1.0 an average athletic adult: height, shoulders, chest, waist, hips, arms and legs (thickness), legLength, head |
skin, colors |
#rrggbb: skin, and six costume colours suit, secondary, accent, boots, gloves, belt |
pattern |
where secondary shows on the torso: solid, trunks, yoke, split, stripe (a centre stripe in accent) |
hair, mask |
{ style, color } each |
accessories |
up to 5 { kind, color, size }, most defining first |
pose |
stand, power (hands on hips) |
Every spec passes through sanitizeSpec before the builder sees it: a model answer, an old saved record and a slider edit all come out with every
number clamped to its range, every colour a real hex and every word from its
list, so the builder reads each field as it is. The lab's spec adds
sleeves, gloves, boots, beard, a helmet and a visor, ready and fly
poses and a chest emblem (star, bolt, crest, flame, heart, a letter), each
the same way: a list, a sanitizer line, a few primitives.
The 21 accessory kinds, each a few primitives on one rig point: on the back
cape, wings, jetpack, scarf; on the shoulders shoulder-pads; on the
head horns, bat-ears, antenna, halo, crown, goggles; on the
forearms gauntlets; in a hand shield, hammer, sword, staff, bow,
claws, energy-hands; on the belt belt-pouches; around the figure
aura. ACCESSORY_KINDS lists exactly the kinds the builder has a case for,
because the schema offers the model that list and every kind it picks shows
on the figure: add a case and its name together.
lib/figure.js
js// lib/figure.js — the figure spec, its sanitizer and the builder. Plain module, no React.
import * as THREE from "three";
// [key, min, max]: multipliers where 1.0 is an average athletic adult.
export const BODY_KEYS = [["height", 0.85, 1.2], ["shoulders", 0.7, 1.5], ["chest", 0.7, 1.5], ["waist", 0.6, 1.4], ["hips", 0.7, 1.4],
["arms", 0.6, 1.7], ["legs", 0.6, 1.7], ["legLength", 0.88, 1.12], ["head", 0.8, 1.3]];
// Grow this list with each accessory case below: the model is offered exactly these.
export const ACCESSORY_KINDS = ["cape", "horns", "energy-hands", "aura"];
export const HAIR = ["none", "short", "long"];
export const MASKS = ["none", "domino", "cowl"];
export const PATTERNS = ["solid", "trunks", "yoke", "split", "stripe"];
export const POSES = ["stand", "power"];
export const DEFAULT_SPEC = {
name: "New hero",
reads: [],
body: Object.fromEntries(BODY_KEYS.map(([k]) => [k, 1])),
skin: "#c98e63",
colors: { suit: "#2456d6", secondary: "#d62839", accent: "#ffd23f", boots: "#d62839", gloves: "#d62839", belt: "#ffd23f" },
pattern: "trunks",
hair: { style: "short", color: "#2b1d14" },
mask: { style: "domino", color: "#111827" },
accessories: [{ kind: "cape", color: "#d62839", size: 1 }],
pose: "power",
};
const HEX = /^#[0-9a-f]{6}$/i;
const hexOr = (v, d) => (typeof v === "string" && HEX.test(v.trim()) ? v.trim().toLowerCase() : d);
const pick = (v, list, d) => (list.includes(v) ? v : d);
const clamp = (v, lo, hi, d) => (Number.isFinite(Number(v)) ? Math.min(hi, Math.max(lo, Number(v))) : d);
// Whatever arrives (a model answer, an old saved doc, a slider edit) becomes a spec the builder trusts.
export function sanitizeSpec(raw) {
const r = raw && typeof raw === "object" ? raw : {};
const d = DEFAULT_SPEC;
const rc = r.colors || {};
const suit = hexOr(rc.suit, d.colors.suit);
const secondary = hexOr(rc.secondary, d.colors.secondary);
const accent = hexOr(rc.accent, d.colors.accent);
const seen = new Set();
return {
name: typeof r.name === "string" && r.name.trim() ? r.name.trim().slice(0, 60) : d.name,
reads: (Array.isArray(r.reads) ? r.reads : []).filter((s) => typeof s === "string").slice(0, 6),
body: Object.fromEntries(BODY_KEYS.map(([k, lo, hi]) => [k, Math.round(clamp(r.body?.[k], lo, hi, 1) * 100) / 100])),
skin: hexOr(r.skin, d.skin),
colors: { suit, secondary, accent, boots: hexOr(rc.boots, secondary), gloves: hexOr(rc.gloves, secondary), belt: hexOr(rc.belt, accent) },
pattern: pick(r.pattern, PATTERNS, "solid"),
hair: { style: pick(r.hair?.style, HAIR, "short"), color: hexOr(r.hair?.color, d.hair.color) },
mask: { style: pick(r.mask?.style, MASKS, "none"), color: hexOr(r.mask?.color, suit) },
accessories: (Array.isArray(r.accessories) ? r.accessories : [])
.filter((a) => a && ACCESSORY_KINDS.includes(a.kind) && !seen.has(a.kind) && seen.add(a.kind))
.slice(0, 5)
.map((a) => ({ kind: a.kind, color: hexOr(a.color, accent), size: clamp(a.size, 0.4, 1.6, 1) })),
pose: pick(r.pose, POSES, "stand"),
};
}
// Three bands of light: the cel-shaded look. One texture shared by every part.
let gradientMap = null;
function toonGradient() {
if (gradientMap) return gradientMap;
gradientMap = new THREE.DataTexture(new Uint8Array([70, 150, 220, 255]), 4, 1, THREE.RedFormat);
gradientMap.minFilter = gradientMap.magFilter = THREE.NearestFilter;
gradientMap.needsUpdate = true;
return gradientMap;
}
// A tapered capsule hanging down from its origin: an arm, a leg, a braid.
function limb(r1, r2, len, mat) {
const g = new THREE.Group();
const cyl = new THREE.Mesh(new THREE.CylinderGeometry(r1, r2, len, 16), mat);
const end = new THREE.Mesh(new THREE.SphereGeometry(r2, 16, 10), mat);
cyl.position.y = -len / 2;
end.position.y = -len;
g.add(cyl, end, new THREE.Mesh(new THREE.SphereGeometry(r1, 16, 10), mat));
return g;
}
// The figure faces +z, its left side is +x, its feet stand on y = 0.
export function buildFigure(rawSpec) {
const spec = sanitizeSpec(rawSpec);
const { body: B, colors: C } = spec;
const M = (color, o = {}) => new THREE.MeshToonMaterial({ color, gradientMap: toonGradient(), ...o });
const mesh = (geo, mat) => new THREE.Mesh(geo, mat);
const anims = [];
const H = 1.8 * B.height;
const root = new THREE.Group();
const body = new THREE.Group();
root.add(body);
// Landmarks every part hangs from, and the torso's radius at each height.
const hipY = H * 0.49 * B.legLength;
const shoulderY = H * 0.815;
const waistY = hipY + (shoulderY - hipY) * 0.33;
const chestY = hipY + (shoulderY - hipY) * 0.68;
const sw = H * 0.118 * B.shoulders;
const cr = H * 0.098 * B.chest;
const hr = H * 0.086 * B.hips;
const neckR = H * 0.031 * Math.sqrt(B.shoulders);
const depth = 0.62;
const keys = [
[hipY - H * 0.05, hr * 0.3],
[hipY, hr],
[waistY, H * 0.074 * B.waist],
[chestY, cr],
[shoulderY - H * 0.035, Math.max(cr * 0.96, sw * 0.8)],
[shoulderY, sw * 0.62],
[shoulderY + H * 0.024, neckR * 1.1],
];
const radiusAt = (y) => {
const i = keys.findIndex(([ky]) => ky >= y);
if (i <= 0) return keys[i === 0 ? 0 : keys.length - 1][1];
const [[y0, r0], [y1, r1]] = [keys[i - 1], keys[i]];
const t = (y - y0) / (y1 - y0);
return r0 + (r1 - r0) * t * t * (3 - 2 * t);
};
// Torso: one lathe through the profile, the costume pattern painted into vertex colours.
const [y0, y1] = [keys[0][0], keys[keys.length - 1][0]];
const pts = [new THREE.Vector2(0.0001, y0)];
for (let i = 0; i <= 64; i++) pts.push(new THREE.Vector2(radiusAt(y0 + ((y1 - y0) * i) / 64), y0 + ((y1 - y0) * i) / 64));
pts.push(new THREE.Vector2(0.0001, y1 + 0.002));
const torso = new THREE.LatheGeometry(pts, 48);
torso.scale(1, 1, depth);
const [suitC, secC, accC] = [C.suit, C.secondary, C.accent].map((c) => new THREE.Color(c));
const pos = torso.attributes.position;
const col = new Float32Array(pos.count * 3);
for (let i = 0; i < pos.count; i++) {
const [x, y] = [pos.getX(i), pos.getY(i)];
let c = suitC;
if (spec.pattern === "trunks" && y < hipY + H * 0.012) c = secC;
if (spec.pattern === "yoke" && y > chestY - H * 0.015 + Math.abs(x) * 0.55) c = secC;
if (spec.pattern === "split" && x > 0) c = secC;
if (spec.pattern === "stripe" && Math.abs(x) < cr * 0.17) c = accC;
col.set([c.r, c.g, c.b], i * 3);
}
torso.setAttribute("color", new THREE.BufferAttribute(col, 3));
const beltY = hipY + (waistY - hipY) * 0.35;
const belt = mesh(new THREE.TorusGeometry(radiusAt(beltY) * 1.01, H * 0.011, 8, 48), M(C.belt));
belt.rotation.x = Math.PI / 2;
belt.scale.set(1, depth, 1);
belt.position.y = beltY;
body.add(mesh(torso, M(0xffffff, { vertexColors: true })), belt);
// Head: a skull scaled to an egg, with sphere shells on its surface for hair and masks.
const headR = H * 0.064 * B.head;
const headY = shoulderY + H * 0.03 + headR * 0.95;
const mask = spec.mask.style;
const neck = mesh(new THREE.CylinderGeometry(neckR, neckR * 1.15, headY - shoulderY, 16), M(mask === "cowl" ? spec.mask.color : spec.skin));
neck.position.y = (shoulderY + headY) / 2 - headR * 0.3;
const head = new THREE.Group();
head.position.y = headY;
const skull = new THREE.Group();
skull.scale.set(0.88, 1.05, 0.95);
skull.add(mesh(new THREE.SphereGeometry(headR, 32, 24), M(spec.skin)));
head.add(skull);
body.add(neck, head);
const shell = (rMul, phi0, phiLen, th0, thLen, color) =>
skull.add(mesh(new THREE.SphereGeometry(headR * rMul, 32, 20, phi0, phiLen, th0, thLen), M(color, { side: THREE.DoubleSide })));
for (const s of [1, -1]) {
const eye = mesh(new THREE.SphereGeometry(headR * 0.13, 12, 8), new THREE.MeshBasicMaterial({ color: mask === "none" ? 0x1d1b22 : 0xffffff }));
eye.scale.set(1, 0.7, 0.45);
eye.position.set(s * headR * 0.33, headR * 0.1, headR * 0.93);
skull.add(eye);
}
if (mask === "domino") shell(1.035, Math.PI / 2 - 1.15, 2.3, 1.18, 0.44, spec.mask.color);
if (mask === "cowl") shell(1.03, 0, Math.PI * 2, 0, 1.6, spec.mask.color);
const hair = mask === "cowl" ? "none" : spec.hair.style;
if (hair !== "none") {
shell(1.05, 0, Math.PI * 2, 0, 1.12, spec.hair.color);
shell(1.05, Math.PI / 2 + 1.15, Math.PI * 2 - 2.3, 1.1, hair === "long" ? 1.7 : 0.8, spec.hair.color); // the back, around the face
}
// Arms and legs: jointed groups, so a pose is a handful of rotations.
const ar = H * 0.027 * B.arms;
const lr = H * 0.042 * B.legs;
const hipJointY = hipY - H * 0.03;
const kneeY = H * 0.05 + (hipJointY - H * 0.05) / 2;
const arms = {};
for (const [side, s] of [["L", 1], ["R", -1]]) {
const suitSide = spec.pattern === "split" && s > 0 ? C.secondary : C.suit;
const shoulder = new THREE.Group();
shoulder.position.set(s * sw * 0.98, shoulderY - ar * 0.9, 0);
const elbow = new THREE.Group();
elbow.position.y = -H * 0.165;
const hand = new THREE.Group();
hand.position.y = -H * 0.15 - ar * 0.85;
shoulder.add(mesh(new THREE.SphereGeometry(ar * 1.4, 16, 12), M(suitSide)), limb(ar * 1.18, ar * 0.95, H * 0.165, M(suitSide)), elbow);
elbow.add(limb(ar * 0.95, ar * 0.8, H * 0.15, M(C.gloves)), hand);
hand.add(mesh(new THREE.SphereGeometry(ar * 1.2, 14, 10), M(C.gloves)));
arms[side] = { shoulder, elbow, hand };
const hip = new THREE.Group();
hip.position.set(s * hr * 0.52, hipJointY, 0);
const knee = new THREE.Group();
knee.position.y = kneeY - hipJointY;
const foot = mesh(new THREE.SphereGeometry(1, 16, 10), M(C.boots));
foot.scale.set(lr * 0.62, lr * 0.45, lr * 1.25);
foot.position.set(0, H * 0.05 - kneeY - lr * 0.15, lr * 0.55);
hip.add(limb(lr * 1.05, lr * 0.74, hipJointY - kneeY, M(suitSide)), knee);
knee.add(limb(lr * 0.74, lr * 0.52, kneeY - H * 0.05, M(C.boots)), foot);
body.add(shoulder, hip);
}
// Accessories: a few primitives each, attached to a rig point.
for (const a of spec.accessories) {
if (a.kind === "cape") {
const len = (shoulderY - H * 0.07) * Math.min(1, a.size);
const geo = new THREE.PlaneGeometry(sw * 2.05, len, 8, 16);
geo.translate(0, -len / 2, 0);
const base = geo.attributes.position.array.slice();
const cape = mesh(geo, M(a.color, { side: THREE.DoubleSide }));
cape.position.set(0, shoulderY, -radiusAt(chestY) * depth - H * 0.015);
body.add(cape);
anims.push((t) => {
const p = geo.attributes.position.array;
for (let i = 0; i < p.length; i += 3) {
const v = -base[i + 1] / len; // 0 at the shoulders, 1 at the hem
p[i] = base[i] * (1 + v * 0.28);
p[i + 2] = -v * v * H * 0.12 - Math.sin(t * 2.3 + v * 4.2) * H * 0.012 * v;
}
geo.attributes.position.needsUpdate = true;
geo.computeVertexNormals();
});
}
if (a.kind === "horns") {
for (const s of [1, -1]) {
const horn = mesh(new THREE.ConeGeometry(headR * 0.22, headR * 1.25 * a.size, 10), M(a.color));
horn.position.set(s * headR * 0.72, headR * 1.05, headR * 0.05);
horn.rotation.set(-0.25, 0, -s * 0.55);
head.add(horn);
}
}
if (a.kind === "energy-hands") {
const glow = new THREE.MeshBasicMaterial({ color: a.color, transparent: true, opacity: 0.55, blending: THREE.AdditiveBlending, depthWrite: false });
glow.userData.outlineParameters = { visible: false }; // light carries no ink line
for (const side of ["L", "R"]) {
const ball = mesh(new THREE.SphereGeometry(ar * 2.1 * a.size, 16, 12), glow);
arms[side].hand.add(ball, new THREE.PointLight(a.color, 1.2, H * 0.6));
anims.push((t) => ball.scale.setScalar(0.85 + 0.2 * Math.sin(t * 6 + (side === "L" ? 0 : 1.7))));
}
}
if (a.kind === "aura") {
const c = document.createElement("canvas");
c.width = c.height = 128;
const g = c.getContext("2d");
const grad = g.createRadialGradient(64, 64, 4, 64, 64, 64);
grad.addColorStop(0, a.color + "e6");
grad.addColorStop(1, a.color + "00");
g.fillStyle = grad;
g.fillRect(0, 0, 128, 128);
const sprite = new THREE.Sprite(new THREE.SpriteMaterial({ map: new THREE.CanvasTexture(c), blending: THREE.AdditiveBlending, depthWrite: false }));
sprite.scale.set(H * 1.1 * a.size, H * 1.35 * a.size, 1);
root.add(sprite);
const center = new THREE.Vector3(0, H * 0.52, 0);
const away = new THREE.Vector3();
anims.push((t, dt, camera) => {
sprite.material.opacity = 0.6 + 0.25 * Math.sin(t * 2.5);
// Each frame: behind the figure from wherever the camera stands, so the glow rims it.
root.worldToLocal(away.copy(camera.position)).sub(center).normalize().multiplyScalar(-H * 0.35);
sprite.position.copy(center).add(away);
});
}
}
// Pose: rotations on the joints.
const { L, R } = arms;
L.shoulder.rotation.z = 0.14;
R.shoulder.rotation.z = -0.14;
if (spec.pose === "power") {
L.shoulder.rotation.set(0.1, 0, 0.78);
R.shoulder.rotation.set(0.1, 0, -0.78);
L.elbow.rotation.set(-0.2, 0, -1.65);
R.elbow.rotation.set(-0.2, 0, 1.65);
}
anims.push((t) => (body.scale.y = 1 + 0.006 * Math.sin(t * 1.8))); // a slow breath
return {
group: root,
spec,
H,
update(t, dt, camera) {
for (const f of anims) f(t, dt, camera);
},
dispose() {
root.traverse((o) => {
o.geometry?.dispose();
for (const m of [o.material].flat()) {
m?.map?.dispose();
m?.dispose();
}
});
},
};
}
Every part is a MeshToonMaterial that shares one gradientMap, which is what makes the figure read as a painted toy.
The ink line comes from OutlineEffect wrapping the renderer: draw each frame with outline.render(scene, camera), and give glow materials userData.outlineParameters = { visible: false } so light stays soft.
The lab's full builder adds spiky,
curly, bun and braided hair, and an fx list of glow parts it hides before a
.glb export through GLTFExporter.
Reading a picture or words into a spec
A picture goes to the model as an image_url part beside the text part, with { schema }, and the answer passes through sanitizeSpec. A picture
the person picks is shrunk with shrinkPhoto and read as a data URL, and its
real colours are measured first: k-means over the middle of the frame, where
the character usually stands, seeded farthest-point so a small vivid costume
colour keeps its own cluster.
lib/sculpt.js
js// lib/sculpt.js — a picture or words in, a sanitized figure spec out.
import { callAI } from "call-ai";
import { shrinkPhoto } from "./photos.js";
import { ACCESSORY_KINDS, BODY_KEYS, HAIR, MASKS, PATTERNS, POSES, sanitizeSpec } from "./figure.js";
// A picked file → a small data URL for the model (shrunk, location stripped).
export async function pictureForModel(file) {
const small = (await shrinkPhoto(file, { maxEdge: 1024, type: "image/jpeg" })) ?? file;
return new Promise((resolve, reject) => {
const r = new FileReader();
r.onload = () => resolve(r.result);
r.onerror = () => reject(r.error);
r.readAsDataURL(small);
});
}
const d2 = (a, b) => (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2;
const toHex = (c) => "#" + c.map((v) => Math.round(v).toString(16).padStart(2, "0")).join("");
// k-means over a 90px copy of the middle of the frame: the colours really there, largest share first.
async function measurePalette(dataUrl, k = 8) {
const img = new Image();
img.src = dataUrl;
await img.decode();
const [sx, sy, sw, sh] = [img.width * 0.15, img.height * 0.05, img.width * 0.7, img.height * 0.9];
const c = document.createElement("canvas");
c.width = Math.max(1, Math.round((sw * 90) / Math.max(sw, sh)));
c.height = Math.max(1, Math.round((sh * 90) / Math.max(sw, sh)));
const g = c.getContext("2d", { willReadFrequently: true });
g.drawImage(img, sx, sy, sw, sh, 0, 0, c.width, c.height);
const data = g.getImageData(0, 0, c.width, c.height).data;
const px = [];
for (let i = 0; i < data.length; i += 4) if (data[i + 3] > 128) px.push([data[i], data[i + 1], data[i + 2]]);
if (!px.length) return [];
// Farthest-point seeds, so a small vivid costume colour keeps its own cluster.
const centers = [px[Math.floor(px.length / 2)]];
while (centers.length < k) {
let best = px[0];
let bestD = -1;
for (let i = 0; i < px.length; i += 3) {
const d = Math.min(...centers.map((c0) => d2(px[i], c0)));
if (d > bestD) [best, bestD] = [px[i], d];
}
centers.push(best);
}
let counts = [];
for (let iter = 0; iter < 12; iter++) {
const sums = centers.map(() => [0, 0, 0]);
counts = centers.map(() => 0);
for (const p of px) {
let bi = 0;
for (let j = 1; j < k; j++) if (d2(p, centers[j]) < d2(p, centers[bi])) bi = j;
for (let n = 0; n < 3; n++) sums[bi][n] += p[n];
counts[bi]++;
}
for (let j = 0; j < k; j++) if (counts[j]) centers[j] = sums[j].map((s) => s / counts[j]);
}
return centers
.map((c0, j) => ({ hex: toHex(c0), share: counts[j] / px.length }))
.filter((c0) => c0.share > 0.008)
.sort((a, b) => b.share - a.share);
}
const hex = { type: "string", description: "#rrggbb" };
const oneOf = (list) => ({ type: "string", enum: list });
const SPEC_SCHEMA = {
properties: {
name: { type: "string" },
reads: { type: "array", items: { type: "string" } },
body: { type: "object", properties: Object.fromEntries(BODY_KEYS.map(([k]) => [k, { type: "number" }])) },
skin: hex,
colors: { type: "object", properties: { suit: hex, secondary: hex, accent: hex, boots: hex, gloves: hex, belt: hex } },
pattern: oneOf(PATTERNS),
hair: { type: "object", properties: { style: oneOf(HAIR), color: hex } },
mask: { type: "object", properties: { style: oneOf(MASKS), color: hex } },
accessories: { type: "array", items: { type: "object", properties: { kind: oneOf(ACCESSORY_KINDS), color: hex, size: { type: "number" } } } },
pose: oneOf(POSES),
},
};
function specPrompt({ name, about, palette }) {
const ranges = BODY_KEYS.map(([k, lo, hi]) => `${k} ${lo}–${hi}`).join(", ");
return [
"You turn a character into settings for a stylized 3D action figure built from simple shapes.",
name ? `The character is ${name}. ${about || ""}` : about ? `The character: ${about}` : "Look closely at the character in the picture.",
`Body numbers are multipliers where 1.0 is an average athletic adult: ${ranges}. arms and legs are thickness. Read them from the silhouette and use the whole range for an extreme build.`,
"suit covers most of the body, secondary is the second costume color, accent the trim and glow color.",
palette.length
? `Colors measured from the middle of the picture, largest share first: ${palette.map((p) => `${p.hex} (${Math.round(p.share * 100)}%)`).join(", ")}. They are pixel averages, so shading and background make them darker and duller than the costume reads. Use them to judge hue, then write each costume color as a fan would paint the action figure: the true color at full brightness.`
: "",
"pattern says where secondary shows on the torso: solid, trunks, yoke (upper chest and shoulders), split (left half), stripe (center stripe in accent).",
"accessories: the top 3 things that make this character recognizable, most defining first. A power they throw is energy-hands or an aura in that color. size 0.5–1.5.",
"reads: 3 to 5 short notes naming what you saw and the setting it drove.",
]
.filter(Boolean)
.join("\n\n");
}
// One AI read. `picture` is a data URL from the person's file, or the address of a picture the
// platform hosts (an ImgGen portrait), passed to the model as it is.
// A portrait already on the device draws from a local blob: URL the model can't open, so turn it into a data URL;
// a hosted https URL goes to the model as it is.
export async function hostable(src) {
if (!src.startsWith("blob:")) return src;
const blob = await (await fetch(src)).blob();
return await new Promise((resolve) => {
const r = new FileReader();
r.onload = () => resolve(r.result);
r.readAsDataURL(blob);
});
}
export async function sculpt({ picture, name, about }) {
const palette = picture?.startsWith("data:") ? await measurePalette(picture).catch(() => []) : [];
const text = specPrompt({ name, about, palette });
const prompt = picture ? [{ type: "text", text }, { type: "image_url", image_url: { url: picture } }] : text;
const raw = await callAI(prompt, { schema: SPEC_SCHEMA });
const spec = sanitizeSpec(typeof raw === "string" ? JSON.parse(raw) : raw);
if (name) spec.name = name.slice(0, 60);
return spec;
}
lib/photos.js is the photo picker's shrinkPhoto module as it stands.
The maker
One three.js engine lives for the life of the page inside a
useEffect(..., []); show(spec) swaps the figure. The camera is framed once
from the stage height, which holds the tallest figure. Reading a picture calls
AI from the press, so a guest gets the answer too.
App.jsx
jsximport React, { useEffect, useRef, useState } from "react";
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { OutlineEffect } from "three/addons/effects/OutlineEffect.js";
import { useFireproof } from "use-fireproof";
import { useVibe, useViewer } from "use-vibes";
import { Button, Field, Heading, Row, Stack, Text, Textarea } from "@vibes.diy/ui";
import { DEFAULT_SPEC, buildFigure } from "./lib/figure.js";
import { pictureForModel, sculpt } from "./lib/sculpt.js";
const STAGE_H = 1.8;
function useStage(mountRef) {
const engine = useRef(null);
useEffect(() => {
const mount = mountRef.current;
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
mount.appendChild(renderer.domElement);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(32, 1, 0.05, 60);
const controls = new OrbitControls(camera, renderer.domElement);
controls.autoRotate = true;
const key = new THREE.DirectionalLight(0xffffff, 2.2);
key.position.set(2.5, 4, 3.5);
scene.add(new THREE.HemisphereLight(0xffffff, 0x3a3f66, 1.6), key);
const outline = new OutlineEffect(renderer, { defaultThickness: 0.0045, defaultColor: [0.04, 0.04, 0.07] });
const frame = () => {
const [w, h] = [mount.clientWidth, mount.clientHeight];
if (!w || !h) return;
renderer.setSize(w, h);
camera.aspect = w / h;
const t = Math.tan(THREE.MathUtils.degToRad(camera.fov / 2));
const dist = Math.max((STAGE_H * 0.68) / t, (STAGE_H * 0.5) / (t * camera.aspect));
controls.target.set(0, STAGE_H * 0.55, 0);
camera.position.set(0.35, 0.12, 1).normalize().multiplyScalar(dist).add(controls.target);
camera.updateProjectionMatrix();
};
const ro = new ResizeObserver(frame);
ro.observe(mount);
let fig = null;
let raf = 0;
const clock = new THREE.Clock();
const loop = () => {
const dt = Math.min(clock.getDelta(), 0.1);
fig?.update(clock.elapsedTime, dt, camera);
controls.update();
outline.render(scene, camera);
raf = requestAnimationFrame(loop);
};
engine.current = {
show(spec) {
if (fig) scene.remove(fig.group);
fig?.dispose();
fig = buildFigure(spec);
scene.add(fig.group);
},
};
loop();
return () => {
cancelAnimationFrame(raf);
ro.disconnect();
fig?.dispose();
controls.dispose();
renderer.dispose();
renderer.domElement.remove();
engine.current = null;
};
}, []);
return engine;
}
export default function App() {
const mountRef = useRef(null);
const fileRef = useRef(null);
const engine = useStage(mountRef);
const [spec, setSpec] = useState(DEFAULT_SPEC);
const [words, setWords] = useState("");
const [busy, setBusy] = useState(false);
const [note, setNote] = useState("");
const { database } = useFireproof("figures");
const { me, can } = useVibe("figures");
const { requestLogin } = useViewer();
useEffect(() => engine.current?.show(spec), [spec, engine]);
async function read(input) {
setNote("");
setBusy(true);
try {
setSpec(await sculpt(input));
} catch (err) {
setNote(err?.reason === "sign-in" ? "sign-in" : "Try another picture, or a few more words about them.");
} finally {
setBusy(false);
}
}
async function onPicture(e) {
const file = e.target.files?.[0];
e.target.value = "";
if (file) await read({ picture: await pictureForModel(file) });
}
const characterId = `${me?.userHandle}-${spec.name.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
const draft = me ? { _id: `figure-${characterId}`, type: "figure", characterId, name: spec.name, spec, authorHandle: me.userHandle } : null;
const verdict = draft ? can.create(draft) : { ok: false };
return (
<Stack gap={3}>
<Heading level={1}>{spec.name}</Heading>
<div ref={mountRef} className="h-96 w-full" />
{spec.reads.length > 0 && <Text size="sm" muted>{spec.reads.join(" · ")}</Text>}
<input ref={fileRef} type="file" accept="image/*" hidden onChange={onPicture} />
<Row gap={2}>
<Button disabled={busy} onClick={() => fileRef.current?.click()}>Pick a character picture</Button>
{me ? (
<Button variant="quiet" disabled={!verdict.ok || busy} onClick={() => database.put({ ...draft, updatedAt: Date.now() })}>
Keep this figure
</Button>
) : (
<Button variant="quiet" onClick={() => requestLogin()}>Sign in to keep it</Button>
)}
</Row>
<Field label="Or describe them">
{(id, describedBy) => <Textarea id={id} describedBy={describedBy} value={words} onChange={setWords} />}
</Field>
<Button disabled={busy || !words.trim()} onClick={() => read({ about: words.trim() })}>Sculpt from words</Button>
{busy && <Text size="sm" muted>Sculpting…</Text>}
{note === "sign-in" ? (
<Row gap={2}>
<Text size="sm">Sign in and your figure builds right away.</Text>
<Button size="sm" onClick={() => requestLogin()}>Sign in</Button>
</Row>
) : (
note && <Text size="sm">{note}</Text>
)}
</Stack>
);
}
Sliders, colour swatches and accessory chips edit the spec in place through
sanitizeSpec; the lab keeps the working spec in localStorage.
The 3D character gallery
A room one screen tall, shown in place of the cast list while it is open:
every character's portrait hangs on a wall as a card, and the chosen
character's figure turns slowly on a stage in front of its card. Portraits hang on the wall as DOM cards through CSS3DRenderer: each
card is a div, React draws the portrait into it through a portal, and a
transparent WebGL canvas with the same camera draws the figure and its
shadow disc over the wall. Arrows, chips, a swipe and the arrow keys slide
the wall; tapping a side card jumps to it. A character with no figure yet is
sculpted once from its portrait by a signed-in viewer and saved for everyone;
a signed-out viewer sees a Sign in button in that spot.
components/Gallery3D.jsx
jsximport React, { useEffect, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";
import * as THREE from "three";
import { OutlineEffect } from "three/addons/effects/OutlineEffect.js";
import { CSS3DObject, CSS3DRenderer } from "three/addons/renderers/CSS3DRenderer.js";
import { Button, Icon, IconButton } from "@vibes.diy/ui";
import { useViewer } from "use-vibes";
import { buildFigure } from "../lib/figure.js";
import { hostable, sculpt } from "../lib/sculpt.js";
// items: [{ key, name, subtitle, about }]; figures: { [key]: spec }; renderPortrait(item) draws a portrait.
const CARD_PX = 480; // card size in CSS pixels
const CARD = 2.5; // card size in scene units
const WALL_Z = -1.7;
const GAP = 2.9;
const SPIN = 0.18; // radians per second
const STAGE_H = 1.8; // every figure is scaled to this height
// The card is a plain element CSS3D places; its portrait fills it edge to edge.
const CARD_CLASS =
"relative size-[480px] cursor-pointer overflow-hidden rounded-2xl border-6 border-white bg-neutral shadow-2xl [&_img]:size-full! [&_img]:object-cover!";
export default function Gallery3D({ title, items, figures, renderPortrait, onSculpted, onClose }) {
const { viewer, isViewerPending, requestLogin } = useViewer();
const [index, setIndex] = useState(0);
const [sculpting, setSculpting] = useState("");
const item = items[Math.min(index, items.length - 1)];
const spec = item ? figures[item.key] : null;
const mountRef = useRef(null);
const engine = useRef(null);
const tried = useRef(new Set());
const swipe = useRef(null);
const step = (d) => setIndex((i) => (i + d + items.length) % items.length);
// One DOM element per card; React draws each portrait into its card through a portal.
const keys = items.map((i) => i.key).join("|");
const cards = useMemo(() => items.map(() => Object.assign(document.createElement("div"), { className: CARD_CLASS })), [keys]);
useEffect(() => {
const onKey = (e) => (e.key === "Escape" ? onClose() : e.key === "ArrowRight" ? step(1) : e.key === "ArrowLeft" ? step(-1) : null);
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [items.length]);
// One scene for the life of the gallery: CSS3D draws the wall, a transparent WebGL canvas draws the figure over it.
useEffect(() => {
const mount = mountRef.current;
const css = new CSS3DRenderer();
css.domElement.className = "absolute inset-0";
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.domElement.className = "pointer-events-none absolute inset-0 h-full w-full";
mount.append(css.domElement, renderer.domElement);
const scene = new THREE.Scene();
const wall = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(32, 1, 0.05, 80);
const key = new THREE.DirectionalLight(0xffffff, 2.3);
key.position.set(2.5, 4, 3.5);
const rim = new THREE.DirectionalLight(0xffe2a8, 1.4);
rim.position.set(-3, 2.5, -3);
const shadow = new THREE.Mesh(new THREE.CircleGeometry(0.7, 32), new THREE.MeshBasicMaterial({ color: 0x000000, transparent: true, opacity: 0.4, depthWrite: false }));
shadow.material.userData.outlineParameters = { visible: false };
shadow.rotation.x = -Math.PI / 2;
shadow.position.y = 0.005;
scene.add(new THREE.HemisphereLight(0xffffff, 0x3a3f66, 1.7), key, rim, shadow);
const outline = new OutlineEffect(renderer, { defaultThickness: 0.005, defaultColor: [0.03, 0.03, 0.05] });
let fig = null;
let objs = [];
let target = 0;
let cur = 0;
const wrap = (d) => (objs.length > 2 ? ((((d + objs.length / 2) % objs.length) + objs.length) % objs.length) - objs.length / 2 : d);
const place = () => {
const [w, h] = [mount.clientWidth, mount.clientHeight];
if (!w || !h) return;
renderer.setSize(w, h, false);
css.setSize(w, h);
camera.aspect = w / h;
const t = Math.tan(THREE.MathUtils.degToRad(camera.fov / 2));
// The centre card behind the figure, plus a glimpse of each neighbour on a wide screen.
const needW = CARD * 0.6 + (camera.aspect > 1 ? CARD * 0.7 : 0);
const dist = Math.max((CARD * 0.75) / t, needW / (t * camera.aspect)) + WALL_Z;
camera.position.set(0, STAGE_H * 0.6, Math.max(dist, 3));
camera.lookAt(0, STAGE_H * 0.58, WALL_Z * 0.4);
camera.updateProjectionMatrix();
};
const ro = new ResizeObserver(place);
ro.observe(mount);
const clock = new THREE.Clock();
let raf = 0;
const loop = () => {
const dt = Math.min(clock.getDelta(), 0.1);
cur += wrap(target - cur) * Math.min(1, dt * 6);
objs.forEach((o, i) => {
const d = wrap(i - cur);
const a = Math.abs(d);
o.position.set(d * GAP, STAGE_H * 0.68, WALL_Z - Math.min(a, 2) * 0.7);
o.rotation.y = -Math.sign(d) * Math.min(a, 1) * 0.55;
o.visible = a < 3.2;
o.element.style.filter = `brightness(${Math.max(0.35, 1 - a * 0.35).toFixed(2)})`;
o.element.style.pointerEvents = a < 0.5 ? "none" : "auto";
});
if (fig) {
fig.group.rotation.y += dt * SPIN;
fig.group.updateMatrixWorld(true);
fig.update(clock.elapsedTime, dt, camera);
}
css.render(wall, camera);
outline.render(scene, camera);
raf = requestAnimationFrame(loop);
};
engine.current = {
show(next) {
if (fig) scene.remove(fig.group);
fig?.dispose();
fig = next ? buildFigure(next) : null;
if (!fig) return;
fig.group.scale.setScalar(Math.min(1.25, STAGE_H / fig.H));
scene.add(fig.group);
},
setCards(list) {
objs.forEach((o) => wall.remove(o));
objs = list.map((el) => {
const o = new CSS3DObject(el);
o.scale.setScalar(CARD / CARD_PX);
wall.add(o);
return o;
});
},
slideTo(i) {
target = i;
},
};
place();
loop();
return () => {
cancelAnimationFrame(raf);
ro.disconnect();
fig?.dispose();
objs.forEach((o) => wall.remove(o));
renderer.dispose();
css.domElement.remove();
renderer.domElement.remove();
engine.current = null;
};
}, []);
useEffect(() => {
engine.current?.setCards(cards);
cards.forEach((el, i) => (el.onclick = () => setIndex(i)));
}, [cards]);
useEffect(() => engine.current?.slideTo(index), [index]);
useEffect(() => engine.current?.show(spec || null), [spec, item?.key]);
// A character with no figure yet: wait for its portrait, read it once, save it for everyone.
useEffect(() => {
if (!item || spec || !viewer || tried.current.has(item.key)) return undefined;
let cancelled = false;
const card = cards[index];
(async () => {
let src = null;
for (let i = 0; i < 60 && !cancelled && !src; i++) {
const img = card?.querySelector("img");
if (img?.complete && img.naturalWidth > 0) src = await hostable(img.src);
else await new Promise((r) => setTimeout(r, 500));
}
if (cancelled || !src) return;
tried.current.add(item.key);
setSculpting(item.key);
try {
await onSculpted(item.key, await sculpt({ picture: src, name: item.name, about: item.about }));
} catch {
tried.current.delete(item.key); // stepping back to this character tries again
} finally {
setSculpting("");
}
})();
return () => {
cancelled = true;
};
}, [item?.key, spec, viewer, cards]);
// The section and its mount render even while the cast is still loading, so the scene always has a home.
return (
<section
aria-label={title}
className="relative h-dvh w-full touch-pan-y overflow-hidden bg-neutral"
onPointerDown={(e) => (swipe.current = e.clientX)}
onPointerUp={(e) => {
const dx = swipe.current == null ? 0 : e.clientX - swipe.current;
swipe.current = null;
if (Math.abs(dx) > 40) step(dx < 0 ? 1 : -1);
}}
>
<div ref={mountRef} className="absolute inset-0" />
{cards.map((el, i) => createPortal(<div className="absolute inset-0">{renderPortrait(items[i])}</div>, el, items[i].key))}
<div className="absolute inset-x-0 top-0 z-10 flex items-center justify-between px-4 py-3 font-extrabold">
<span>{title}</span>
<IconButton label="Close the gallery" icon={<Icon name="close" size="sm" />} onClick={onClose} />
</div>
{item && (
<div className="absolute top-16 left-1/2 z-10 -translate-x-1/2">
{!spec && sculpting === item.key && <span className="rounded-full bg-background/80 px-3 py-1">Sculpting {item.name} in 3D…</span>}
{!spec && !isViewerPending && !viewer && (
<Button size="sm" onClick={requestLogin}>
Sign in to sculpt {item.name} in 3D
</Button>
)}
</div>
)}
{item && (
<div className="absolute inset-x-0 bottom-12 z-10 flex items-center justify-center gap-4 px-4">
<IconButton label="Previous character" icon={<Icon name="prev" size="sm" />} onClick={() => step(-1)} />
<div className="min-w-0 max-w-80 flex-1 text-center text-2xl font-black">
{item.name}
<small className="block text-sm font-normal">{item.subtitle}</small>
</div>
<IconButton label="Next character" icon={<Icon name="next" size="sm" />} onClick={() => step(1)} />
</div>
)}
<div className="absolute inset-x-0 bottom-0 z-10 flex justify-center-safe gap-1.5 overflow-x-auto px-4 py-2">
{items.map((it, i) => (
<Button key={it.key} size="sm" variant={i === index ? undefined : "quiet"} aria-pressed={i === index} onClick={() => setIndex(i)}>
{it.name}
</Button>
))}
</div>
</section>
);
}
Wiring it into a cast
The cast's own records hold the characters and their ImgGen portraits; the
figures live in their own figures database, one record per character with
the id figure-<characterId>, so the first signed-in viewer who opens the
gallery sculpts a missing figure and every later visitor sees it.
jsxconst { database: figureDb, useLiveQuery: useFigures } = useFireproof("figures");
const { me, can } = useVibe("figures");
const figureDocs = useFigures("type", { key: "figure" }).docs;
const figures = Object.fromEntries(figureDocs.map((d) => [d.characterId, d.spec]));
async function saveFigure(characterId, spec) {
const old = figureDocs.find((d) => d._id === `figure-${characterId}`);
const doc = { ...old, _id: `figure-${characterId}`, type: "figure", characterId, name: spec.name, spec, authorHandle: old?.authorHandle ?? me?.userHandle, updatedAt: Date.now() };
if ((old ? can.edit(doc) : can.create(doc)).ok) await figureDb.put(doc);
}
// The gallery takes the screen in place of the cast list while it is open.
if (gallery) {
return (
<Gallery3D
title="The cast in 3D"
items={cast.map((c) => ({ key: c._id, name: c.name, subtitle: c.role, about: c.power }))}
figures={figures}
renderPortrait={(item) => <ImgGen _id={item.key} database={database} showControls={false} className="h-full w-full object-cover" />}
onSculpted={saveFigure}
onClose={() => setGallery(false)}
/>
);
}
The figures database
The figures database is public to read and each figure is written only by its sculptor.
access.js
js// Figures: everyone sees every figure; each one is written and removed only by its sculptor.
export function figures(doc, oldDoc, user) {
if (!user?.userHandle) throw { forbidden: "sign in to sculpt a figure" };
const me = user.userHandle;
if (doc._deleted) {
if (!oldDoc || oldDoc.authorHandle !== me) throw { forbidden: "only its sculptor removes a figure" };
return { channels: ["figures"] };
}
if (doc.type !== "figure") throw { forbidden: "unknown record" };
if (typeof doc.characterId !== "string" || !doc.characterId || doc.characterId.length > 120) throw { forbidden: "a figure names its character" };
if (!doc.spec || typeof doc.spec !== "object" || JSON.stringify(doc.spec).length > 20000) throw { forbidden: "a figure carries a small spec" };
const sculptor = oldDoc ? oldDoc.authorHandle : doc.authorHandle;
if (sculptor !== me || doc.authorHandle !== sculptor) throw { forbidden: "only its sculptor changes a figure" };
return { channels: ["figures"], grant: { public: ["figures"] } };
}
A figure that fights: joints, rim light and villains
A figure that stands on a shelf can be one mesh, but a figure that fights in a game is a tree of joints that one pose function bends every frame. These are the lessons from turning a Monkey King and his demons into game characters.
- Joints, not meshes. Each limb is a
Groupat the joint with its mesh hung below it, chained hips → thigh → shin and shoulder → upper arm → forearm. Apose(figure, state)function sets only rotations from game state: a walk phase advanced by speed (Math.sin(phase)swings legs and arms against each other), and an attack's progressk = t / duration. A heavy blow raises the weapon overk0 to 0.3, then brings it down over 0.3 to 0.42 with an ease-out. The game's hit moment sits inside the down-swing, so the blow lands where the eye sees contact. - Rim light keeps the silhouette. Inject a fresnel term into
totalEmissiveRadiancethroughonBeforeCompile, and give each variant its owncustomProgramCacheKey. Keep the rim at about 0.5 or less on gold and skin, or the figure turns into a glowing doll and the costume detail disappears. Lower the metalness on large gold plates for the same reason. - Curves taper. Horns, plumes and tails are a
TubeGeometryalong aCatmullRomCurve3. Scale each ring of vertices toward the curve point as it nears the tip, so the shape ends in a point. - Patterns are canvas textures. Draw a costume pattern (tiger stripes, scales, embroidery) once on a small canvas and wrap it on an open cylinder. For a ragged hem, push the bottom ring of vertices down by
Math.abs(Math.sin(angle * 5)). - Cloth moves on the CPU. A scarf or cape is a strip
PlaneGeometrywith a dozen segments. Keep a copy of its rest positions, and each frame set every vertex from that copy plus sine waves that grow toward the free end and stream back faster when the figure runs. - Villains glow from inside. Give a demon a near-black body with
fbmveins in object space added to the emissive, and a glow uniform that rises through its wind-up so the attack can be read. On defeat, raise a dissolve uniform thatdiscards the body away along the same noise with a hot edge, while embers rise. - A weapon can grow. Keep the weapon pointing along its own +z and set its length with a
setLength(L)that rescales the shaft and moves the caps. A smash that lengthens the staff mid-swing reads as a legend rather than a stick.
The six things that make it work
- Measured palette colours are pixel averages that read dark, so the prompt asks the model to judge hue from them and paint each costume colour true at full brightness.
- A picture the platform hosts reaches the model as its URL in the
image_urlpart, and the gallery hangs portraits as DOM cards inCSS3DRenderer, where each<img>draws straight from its address. - The aura sprite moves to the far side of the figure from the camera every frame, so the glow rims the figure and the figure stays crisp.
- Frame the camera from one fixed stage height and scale each figure to it, so stepping between characters keeps the room still.
- Card images fill their card with
object-fit: cover, because the<img>insideImgGencan be any shape. - Reading a picture runs for a signed-in viewer or a guest press; a
reason === "sign-in"answer gets a one-line invitation with a Sign in button, and the same press works after.