Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat: animation clips API, avatar wardrobe, pose library; studio + coin-communities updates

nirholas7bd237138c66
diff --git a/api/_lib/accessories.js b/api/_lib/accessories.js
index 162a57054..0829c8704 100644
--- a/api/_lib/accessories.js
+++ b/api/_lib/accessories.js
@@ -19,6 +19,12 @@ export function isValidPresetId(id) {
return PRESET_IDS.has(id);
}
+// Tintable color slots — mirror COLOR_SLOTS in src/avatar-studio.js and
+// SLOT_MATERIALS in api/_lib/bake.js. Each maps to one or more named GLB
+// materials whose baseColorFactor the baker multiplies.
+const COLOR_SLOT_IDS = new Set(['skin', 'hair', 'outfit']);
+const HEX_RE = /^#[0-9a-f]{6}$/i;
+
export function validateAppearance(appearance) {
if (!appearance) return null;
@@ -51,5 +57,21 @@ export function validateAppearance(appearance) {
}
}
+ if (appearance.colors !== undefined && appearance.colors !== null) {
+ if (typeof appearance.colors !== 'object' || Array.isArray(appearance.colors)) {
+ return 'appearance.colors must be an object';
+ }
+ const entries = Object.entries(appearance.colors);
+ if (entries.length > COLOR_SLOT_IDS.size) {
+ return `appearance.colors max ${COLOR_SLOT_IDS.size} keys`;
+ }
+ for (const [slot, hex] of entries) {
+ if (!COLOR_SLOT_IDS.has(slot)) return `unknown color slot: ${slot}`;
+ if (typeof hex !== 'string' || !HEX_RE.test(hex)) {
+ return `appearance.colors["${slot}"] must be a #rrggbb hex string`;
+ }
+ }
+ }
+
return null;
}
diff --git a/api/_lib/bake.js b/api/_lib/bake.js
index aa33fe93e..655a973cd 100644
--- a/api/_lib/bake.js
+++ b/api/_lib/bake.js
@@ -55,6 +55,8 @@ export function isBakeable(appearance) {
if (appearance.outfit) return true;
if (Array.isArray(appearance.accessories) && appearance.accessories.length > 0) return true;
if (appearance.morphs && Object.keys(appearance.morphs).length > 0) return true;
+ if (appearance.colors && Object.keys(appearance.colors).length > 0) return true;
+ if (Array.isArray(appearance.hidden) && appearance.hidden.length > 0) return true;
return false;
}
@@ -99,6 +101,18 @@ export async function bakeAppearance(baseGlbBytes, appearance) {
if (appearance?.morphs) Object.assign(morphMap, appearance.morphs);
if (Object.keys(morphMap).length > 0) applyMorphs(doc, morphMap);
+ // 1b) Material tints: multiply each slot's baseColorFactor by the chosen color.
+ if (appearance?.colors && Object.keys(appearance.colors).length > 0) {
+ applyColors(doc, appearance.colors);
+ }
+
+ // 1c) Hidden garment layers: drop the meshes so the bake exposes the base
+ // body (the "start minimal" wardrobe state). prune() in the compression
+ // pass reclaims the now-unreferenced meshes/materials/textures.
+ if (Array.isArray(appearance?.hidden) && appearance.hidden.length > 0) {
+ applyHidden(doc, appearance.hidden);
+ }
+
// 2) Bone-mounted accessory GLBs.
for (let i = 0; i < presetIds.length; i++) {
const id = presetIds[i];
@@ -340,6 +354,84 @@ function applyMorphs(doc, binding) {
}
}
+// Garment slots → GLB material names. Mirrors COLOR_SLOTS in src/avatar-studio.js,
+// WARDROBE_SLOTS in src/avatar-wardrobe.js, and the slot-id allowlists in
+// api/_lib/accessories.js. Tints key skin/hair/outfit; hide keys
+// hair/outfit/glasses (skin is never hidden).
+const SLOT_MATERIALS = {
+ skin: ['Wolf3D_Skin', 'Wolf3D_Body'],
+ hair: ['Wolf3D_Hair'],
+ outfit: ['Wolf3D_Outfit_Top', 'Wolf3D_Outfit_Bottom', 'Wolf3D_Outfit_Footwear'],
+ glasses: ['Wolf3D_Glasses'],
+};
+
+/**
+ * Set the baseColorFactor RGB of each slot's materials to the chosen color,
+ * preserving the existing alpha. This mirrors the studio live preview, which
+ * replaces `material.color` (the shader then multiplies factor × baseColorTexture
+ * at render, so texture detail is retained in both places).
+ *
+ * Colors arrive as sRGB hex (matching the browser <input type=color> and the
+ * three.js color pipeline); glTF baseColorFactor is linear, so convert per
+ * channel to keep the baked GLB identical to what the user saw in the studio.
+ */
+function applyColors(doc, colors) {
+ const nameToFactor = new Map();
+ for (const [slot, hex] of Object.entries(colors)) {
+ const mats = SLOT_MATERIALS[slot];
+ const rgb = hexToLinearRgb(hex);
+ if (!mats || !rgb) continue;
+ for (const name of mats) nameToFactor.set(name, rgb);
+ }
+ if (nameToFactor.size === 0) return;
+
+ for (const material of doc.getRoot().listMaterials()) {
+ const factor = nameToFactor.get(material.getName());
+ if (!factor) continue;
+ const prevAlpha = material.getBaseColorFactor()?.[3] ?? 1;
+ material.setBaseColorFactor([factor[0], factor[1], factor[2], prevAlpha]);
+ }
+}
+
+/**
+ * Remove the meshes belonging to each hidden slot. A node is dropped when any
+ * of its mesh primitives uses one of the slot's named materials; disposing the
+ * node orphans the mesh, which prune() then reclaims. Skeleton joints are never
+ * touched (they carry no mesh), so the rig stays intact for the base body and
+ * any still-visible garments.
+ */
+function applyHidden(doc, hidden) {
+ const names = new Set();
+ for (const slot of hidden) {
+ const mats = SLOT_MATERIALS[slot];
+ if (mats) for (const m of mats) names.add(m);
+ }
+ if (names.size === 0) return;
+
+ for (const node of doc.getRoot().listNodes()) {
+ const mesh = node.getMesh();
+ if (!mesh) continue;
+ const hit = mesh
+ .listPrimitives()
+ .some((p) => names.has(p.getMaterial()?.getName()));
+ if (hit) node.dispose();
+ }
+}
+
+function hexToLinearRgb(hex) {
+ if (typeof hex !== 'string' || !/^#[0-9a-f]{6}$/i.test(hex)) return null;
+ const n = parseInt(hex.slice(1), 16);
+ return [
+ srgbToLinear(((n >> 16) & 0xff) / 255),
+ srgbToLinear(((n >> 8) & 0xff) / 255),
+ srgbToLinear((n & 0xff) / 255),
+ ];
+}
+
+function srgbToLinear(c) {
+ return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
+}
+
function collectTargetNames(mesh) {
const ext = mesh.getExtras() || {};
if (Array.isArray(ext.targetNames) && ext.targetNames.length > 0) return ext.targetNames;
diff --git a/api/_lib/migrations/2026-05-31-animation-clips.sql b/api/_lib/migrations/2026-05-31-animation-clips.sql
new file mode 100644
index 000000000..1f4c87c98
--- /dev/null
+++ b/api/_lib/migrations/2026-05-31-animation-clips.sql
@@ -0,0 +1,93 @@
+-- Animation clip storage — keyframe animations users author in the Animation
+-- Studio (/pose), save to their account, share, sell, and replay on any
+-- three.ws avatar.
+--
+-- A clip is the JSON-serialized output of THREE.AnimationClip.toJSON() (canonical
+-- Avaturn/Mixamo bone track names — see public/animations/clips/*.json). We also
+-- persist the editable keyframe document (`editor_doc`) so the studio can reopen
+-- a saved clip and continue editing losslessly, not just replay a baked clip.
+--
+-- Clips are small (quaternion tracks resampled at fps for a few seconds are tens
+-- of KB), so the baked clip lives inline as JSONB. Anything over the inline cap
+-- is offloaded to R2 and we keep just the pointer in `storage_key`.
+--
+-- Mirrors mocap_clips (api/_lib/migrations/2026-05-24-mocap-clips.sql) for auth,
+-- ownership, slugs, visibility, soft-delete, and pricing. The monetization
+-- columns (price_*, artifact_*, creator_payto_*, listed) are populated by the
+-- sell flow; null/false here means "not for sale".
+
+CREATE TABLE IF NOT EXISTS animation_clips (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ owner_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ avatar_id uuid REFERENCES avatars(id) ON DELETE SET NULL,
+ slug text NOT NULL,
+ name text NOT NULL,
+ description text,
+ -- 'animation' (one-shot), 'loop' (cyclic, e.g. walk cycle), 'sequence'.
+ kind text NOT NULL DEFAULT 'animation' CHECK (kind IN ('animation','loop','sequence')),
+ -- Wire format identifier so the runtime can refuse incompatible clips.
+ format text NOT NULL DEFAULT 'three.ws.animation.v1',
+ duration_ms int NOT NULL DEFAULT 0,
+ frame_count int NOT NULL DEFAULT 0,
+ fps int,
+ loop boolean NOT NULL DEFAULT true,
+ -- Baked THREE.AnimationClip.toJSON() — { name, duration, tracks[] }. For
+ -- clips larger than the inline cap, this is null and the payload lives at
+ -- storage_key (R2).
+ clip jsonb,
+ storage_key text,
+ -- Editable keyframe document ({ name, duration, fps, loop, keyframes[] }) so
+ -- a saved clip can be reopened in the studio for lossless re-editing.
+ editor_doc jsonb,
+ thumbnail_key text,
+ tags text[] NOT NULL DEFAULT '{}',
+ visibility text NOT NULL DEFAULT 'private' CHECK (visibility IN ('private','unlisted','public')),
+ -- Optional pricing — when set + listed, the clip sells via the x402 paid
+ -- download endpoint (api/x402/animation-download.js). Mirrors mocap/avatars.
+ price_amount numeric(30,9),
+ price_currency text,
+ -- Sellable artifact (GLB with embedded animation) staged in R2 + its payout
+ -- routing. Populated by the sell flow; gate the file behind payment, not
+ -- behind listing visibility.
+ artifact_key text,
+ artifact_bytes bigint,
+ artifact_mime text,
+ creator_payto_base text,
+ creator_payto_solana text,
+ creator_payto_bsc text,
+ listed boolean NOT NULL DEFAULT false,
+ play_count bigint NOT NULL DEFAULT 0,
+ purchase_count bigint NOT NULL DEFAULT 0,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ deleted_at timestamptz,
+ UNIQUE (owner_id, slug)
+);
+
+CREATE INDEX IF NOT EXISTS animation_clips_owner_idx
+ ON animation_clips (owner_id, created_at DESC)
+ WHERE deleted_at IS NULL;
+
+CREATE INDEX IF NOT EXISTS animation_clips_public_idx
+ ON animation_clips (visibility, created_at DESC)
+ WHERE visibility = 'public' AND deleted_at IS NULL;
+
+CREATE INDEX IF NOT EXISTS animation_clips_kind_idx
+ ON animation_clips (kind, created_at DESC)
+ WHERE deleted_at IS NULL;
+
+-- Priced + listed clips, newest first — feeds the marketplace animations surface.
+CREATE INDEX IF NOT EXISTS animation_clips_listed_idx
+ ON animation_clips (listed, created_at DESC)
+ WHERE listed = true AND deleted_at IS NULL;
+
+CREATE INDEX IF NOT EXISTS animation_clips_tags_idx
+ ON animation_clips USING gin (tags);
+
+-- updated_at trigger
+DO $$ BEGIN
+ CREATE TRIGGER animation_clips_set_updated_at
+ BEFORE UPDATE ON animation_clips
+ FOR EACH ROW EXECUTE FUNCTION set_updated_at();
+EXCEPTION WHEN duplicate_object THEN NULL;
+END $$;
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index d0bce6406..05ce11c41 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -128,6 +128,50 @@ create index if not exists mocap_clips_public_idx on mocap_clips(visibility, cre
create index if not exists mocap_clips_kind_idx on mocap_clips(kind, created_at desc) where deleted_at is null;
create index if not exists mocap_clips_tags_idx on mocap_clips using gin(tags);
+-- ── animation_clips (keyframe animations authored in the Animation Studio) ──
+-- See api/_lib/migrations/2026-05-31-animation-clips.sql for the full schema +
+-- rationale. Mirrored here so a clean schema.sql apply provisions the table.
+create table if not exists animation_clips (
+ id uuid primary key default gen_random_uuid(),
+ owner_id uuid not null references users(id) on delete cascade,
+ avatar_id uuid references avatars(id) on delete set null,
+ slug text not null,
+ name text not null,
+ description text,
+ kind text not null default 'animation' check (kind in ('animation','loop','sequence')),
+ format text not null default 'three.ws.animation.v1',
+ duration_ms int not null default 0,
+ frame_count int not null default 0,
+ fps int,
+ loop boolean not null default true,
+ clip jsonb,
+ storage_key text,
+ editor_doc jsonb,
+ thumbnail_key text,
+ tags text[] not null default '{}',
+ visibility text not null default 'private' check (visibility in ('private','unlisted','public')),
+ price_amount numeric(30,9),
+ price_currency text,
+ artifact_key text,
+ artifact_bytes bigint,
+ artifact_mime text,
+ creator_payto_base text,
+ creator_payto_solana text,
+ creator_payto_bsc text,
+ listed boolean not null default false,
+ play_count bigint not null default 0,
+ purchase_count bigint not null default 0,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ deleted_at timestamptz,
+ unique (owner_id, slug)
+);
+create index if not exists animation_clips_owner_idx on animation_clips(owner_id, created_at desc) where deleted_at is null;
+create index if not exists animation_clips_public_idx on animation_clips(visibility, created_at desc) where visibility = 'public' and deleted_at is null;
+create index if not exists animation_clips_kind_idx on animation_clips(kind, created_at desc) where deleted_at is null;
+create index if not exists animation_clips_listed_idx on animation_clips(listed, created_at desc) where listed = true and deleted_at is null;
+create index if not exists animation_clips_tags_idx on animation_clips using gin(tags);
+
-- ── OAuth 2.1 clients (for MCP & third-party apps) ──────────────────────────
-- Supports RFC 7591 dynamic client registration.
create table if not exists oauth_clients (
diff --git a/api/_lib/validate.js b/api/_lib/validate.js
index bbc056d47..fae0feb53 100644
--- a/api/_lib/validate.js
+++ b/api/_lib/validate.js
@@ -24,6 +24,10 @@ export const avatarAppearance = z
outfit: z.string().min(1).max(64).nullable().optional(),
accessories: z.array(z.string().min(1).max(64)).max(8).optional(),
morphs: z.record(z.number().min(0).max(1)).optional(),
+ // Garment layers: per-slot recolour (hex) + hidden slot ids. Slot-id and
+ // hex validity is enforced in validateAppearance() (accessories.js).
+ colors: z.record(z.string().regex(/^#[0-9a-fA-F]{6}$/)).optional(),
+ hidden: z.array(z.string().min(1).max(32)).max(8).optional(),
})
.strict()
.superRefine((val, ctx) => {
diff --git a/api/animations/[id].js b/api/animations/[id].js
new file mode 100644
index 000000000..b2646234e
--- /dev/null
+++ b/api/animations/[id].js
@@ -0,0 +1,198 @@
+// GET /api/animations/clips/:id — fetch a clip (baked clip + editor_doc)
+// PATCH /api/animations/clips/:id — update metadata (owner only)
+// DELETE /api/animations/clips/:id — soft-delete (owner only)
+//
+// Mirrors api/mocap/[id].js. The baked clip resolves from R2 when offloaded
+// (storage_key set); the editor_doc is returned so the studio can reopen the
+// animation for lossless re-editing.
+
+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
+import { sql } from '../_lib/db.js';
+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
+import { getObjectBuffer, publicUrl } from '../_lib/r2.js';
+import { z } from 'zod';
+
+const patchSchema = z.object({
+ name: z.string().trim().min(1).max(120).optional(),
+ description: z.string().trim().max(2000).optional(),
+ tags: z.array(z.string().trim().min(1).max(40)).max(20).optional(),
+ visibility: z.enum(['private', 'unlisted', 'public']).optional(),
+ kind: z.enum(['animation', 'loop', 'sequence']).optional(),
+ loop: z.boolean().optional(),
+ avatar_id: z.string().uuid().nullable().optional(),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,PATCH,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'PATCH', 'DELETE'])) return;
+
+ const id =
+ req.query?.id ||
+ new URL(req.url, 'http://x').pathname.split('/').filter(Boolean).pop();
+ if (!id || !/^[0-9a-f-]{8,}$/i.test(id)) {
+ return error(res, 400, 'invalid_request', 'id required');
+ }
+
+ const auth = await resolveAuth(req);
+
+ if (req.method === 'GET') return handleGet(req, res, auth, id);
+ if (!auth) return error(res, 401, 'unauthorized', 'authentication required');
+ if (req.method === 'PATCH') return handlePatch(req, res, auth, id);
+ return handleDelete(req, res, auth, id);
+});
+
+async function handleGet(req, res, auth, id) {
+ const [row] = await sql`
+ select id, owner_id, avatar_id, slug, name, description, kind, format,
+ duration_ms, frame_count, fps, loop, clip, storage_key, editor_doc,
+ thumbnail_key, tags, visibility, price_amount, price_currency,
+ listed, play_count, purchase_count, created_at, updated_at
+ from animation_clips
+ where id = ${id} and deleted_at is null
+ limit 1
+ `;
+ if (!row) return error(res, 404, 'not_found', 'animation not found');
+ const ownerView = auth?.userId === row.owner_id;
+ if (!ownerView && row.visibility === 'private') {
+ return error(res, 404, 'not_found', 'animation not found');
+ }
+
+ // Resolve the baked clip body from R2 when it was offloaded.
+ let clip = row.clip || null;
+ if (!clip && row.storage_key) {
+ try {
+ const buf = await getObjectBuffer(row.storage_key);
+ clip = JSON.parse(buf.toString('utf8'));
+ } catch (err) {
+ console.error('[animations/get] R2 resolve failed', err?.message || err);
+ return error(res, 502, 'storage_error', 'Failed to load clip payload');
+ }
+ }
+
+ // Bump play_count only when a non-owner fetches with ?play=1 (real playback,
+ // not editor opens or scrubbing). Fire-and-forget.
+ const isPlay = new URL(req.url, 'http://x').searchParams.get('play') === '1';
+ if (!ownerView && isPlay) {
+ queueMicrotask(async () => {
+ try {
+ await sql`update animation_clips set play_count = play_count + 1 where id = ${id}`;
+ } catch (err) {
+ console.warn('[animations] play_count update failed', err?.message);
+ }
+ });
+ }
+
+ res.setHeader(
+ 'Cache-Control',
+ ownerView ? 'private, max-age=0' : 'public, s-maxage=60, stale-while-revalidate=300',
+ );
+ return json(res, 200, {
+ clip: {
+ id: row.id,
+ slug: row.slug,
+ name: row.name,
+ description: row.description,
+ kind: row.kind,
+ format: row.format,
+ duration_ms: row.duration_ms,
+ duration: row.duration_ms / 1000,
+ frame_count: row.frame_count,
+ fps: row.fps,
+ loop: row.loop,
+ clip, // baked THREE.AnimationClip.toJSON()
+ editor_doc: ownerView ? row.editor_doc || null : null, // editing source is owner-only
+ editable: ownerView && !!row.editor_doc,
+ tags: row.tags || [],
+ visibility: row.visibility,
+ avatar_id: row.avatar_id,
+ thumbnail_url: row.thumbnail_key ? publicUrl(row.thumbnail_key) : null,
+ play_count: Number(row.play_count || 0),
+ purchase_count: Number(row.purchase_count || 0),
+ listed: !!row.listed,
+ price: row.price_amount
+ ? { amount: String(row.price_amount), currency: row.price_currency }
+ : null,
+ owner: ownerView ? 'self' : 'other',
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ },
+ });
+}
+
+async function handlePatch(req, res, auth, id) {
+ if (auth.source === 'oauth' || auth.source === 'apikey') {
+ if (!hasScope(auth.scope, 'avatars:write'))
+ return error(res, 403, 'insufficient_scope', 'avatars:write required');
+ }
+ const body = await readJson(req);
+ const parsed = patchSchema.safeParse(body);
+ if (!parsed.success) {
+ return error(res, 400, 'validation_error', parsed.error.issues.map((i) => i.message).join('; '));
+ }
+ const patch = parsed.data;
+
+ const sets = [];
+ if (patch.name !== undefined) sets.push(sql`name = ${patch.name}`);
+ if (patch.description !== undefined) sets.push(sql`description = ${patch.description}`);
+ if (patch.tags !== undefined) sets.push(sql`tags = ${patch.tags}`);
+ if (patch.visibility !== undefined) sets.push(sql`visibility = ${patch.visibility}`);
+ if (patch.kind !== undefined) sets.push(sql`kind = ${patch.kind}`);
+ if (patch.loop !== undefined) sets.push(sql`loop = ${patch.loop}`);
+ if (patch.avatar_id !== undefined) {
+ if (patch.avatar_id) {
+ const ok = await sql`
+ select 1 from avatars
+ where id = ${patch.avatar_id} and owner_id = ${auth.userId} and deleted_at is null
+ limit 1
+ `;
+ if (!ok[0]) return error(res, 404, 'not_found', 'avatar_id not owned by you');
+ }
+ sets.push(sql`avatar_id = ${patch.avatar_id}`);
+ }
+ if (sets.length === 0) return error(res, 400, 'invalid_request', 'no patchable fields supplied');
+ const setClause = sets.reduce((acc, s, i) => (i === 0 ? sql`set ${s}` : sql`${acc}, ${s}`), sql``);
+
+ const [row] = await sql`
+ update animation_clips
+ ${setClause}
+ where id = ${id} and owner_id = ${auth.userId} and deleted_at is null
+ returning id, slug, name, description, kind, format, duration_ms, frame_count,
+ fps, loop, tags, visibility, avatar_id, price_amount, price_currency,
+ listed, created_at, updated_at
+ `;
+ if (!row) return error(res, 404, 'not_found', 'animation not found or not yours');
+ return json(res, 200, {
+ clip: {
+ ...row,
+ price: row.price_amount
+ ? { amount: String(row.price_amount), currency: row.price_currency }
+ : null,
+ },
+ });
+}
+
+async function handleDelete(req, res, auth, id) {
+ if (auth.source === 'oauth' || auth.source === 'apikey') {
+ if (!hasScope(auth.scope, 'avatars:delete'))
+ return error(res, 403, 'insufficient_scope', 'avatars:delete required');
+ }
+ const [row] = await sql`
+ update animation_clips
+ set deleted_at = now()
+ where id = ${id} and owner_id = ${auth.userId} and deleted_at is null
+ returning id
+ `;
+ if (!row) return error(res, 404, 'not_found', 'animation not found or not yours');
+ return json(res, 200, { ok: true });
+}
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session)
+ return {
+ userId: session.id,
+ source: 'session',
+ scope: 'avatars:read avatars:write avatars:delete',
+ };
+ return await authenticateBearer(extractBearer(req));
+}
diff --git a/api/animations/clips.js b/api/animations/clips.js
new file mode 100644
index 000000000..1135d9678
--- /dev/null
+++ b/api/animations/clips.js
@@ -0,0 +1,305 @@
+// GET /api/animations/clips — list (caller's own + ?include_public=true)
+// POST /api/animations/clips — create from a baked THREE.AnimationClip.toJSON()
+//
+// The stored clip is the JSON-serialized output of THREE.AnimationClip.toJSON()
+// (canonical Avaturn/Mixamo bone track names, e.g. "Hips.quaternion") — the
+// exact format AnimationManager plays everywhere on three.ws. We also persist
+// the editable keyframe document (`editor_doc`) so the studio can reopen a saved
+// clip and continue editing losslessly.
+//
+// Mirrors api/mocap/clips.js for auth, ownership, slugs, visibility, pagination.
+
+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
+import { sql } from '../_lib/db.js';
+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
+import { putObject, publicUrl } from '../_lib/r2.js';
+import { limits } from '../_lib/rate-limit.js';
+import { z } from 'zod';
+
+const FORMAT = 'three.ws.animation.v1';
+const MAX_BYTES_INLINE = 1_500_000; // 1.5 MB JSONB inline cap; larger → R2 offload
+const MAX_TRACKS = 512;
+
+const slugRe = /^[a-z0-9][a-z0-9-]{0,79}$/;
+
+// A baked THREE.AnimationClip.toJSON(): { name, duration, tracks: [{ name, type, times, values }] }.
+const trackSchema = z.object({
+ name: z.string().min(1).max(128),
+ type: z.string().min(1).max(32),
+ times: z.array(z.number()).max(200_000),
+ values: z.array(z.number()).max(4_000_000),
+});
+const clipSchema = z.object({
+ name: z.string().trim().min(1).max(120),
+ duration: z.number().nonnegative().max(3600),
+ tracks: z.array(trackSchema).min(1).max(MAX_TRACKS),
+});
+
+// The editable keyframe document the studio round-trips (src/pose-animation.js).
+const editorDocSchema = z.object({
+ name: z.string().max(120).optional(),
+ duration: z.number().nonnegative().max(3600),
+ fps: z.number().int().min(1).max(240).optional(),
+ loop: z.boolean().optional(),
+ keyframes: z.array(z.object({
+ id: z.string().max(64).optional(),
+ time: z.number().nonnegative(),
+ easing: z.string().max(32).optional(),
+ pose: z.object({
+ bones: z.record(z.string(), z.array(z.number())),
+ rootPosition: z.object({ x: z.number(), y: z.number(), z: z.number() }).partial().optional(),
+ }),
+ })).max(2000),
+});
+
+const createSchema = z.object({
+ name: z.string().trim().min(1).max(120),
+ slug: z.string().trim().regex(slugRe).optional(),
+ description: z.string().trim().max(2000).optional(),
+ avatar_id: z.string().uuid().optional(),
+ tags: z.array(z.string().trim().min(1).max(40)).max(20).optional(),
+ visibility: z.enum(['private', 'unlisted', 'public']).optional(),
+ kind: z.enum(['animation', 'loop', 'sequence']).optional(),
+ fps: z.number().int().min(1).max(240).optional(),
+ loop: z.boolean().optional(),
+ clip: clipSchema,
+ editor_doc: editorDocSchema.optional(),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const auth = await resolveAuth(req, req.method === 'GET' ? 'avatars:read' : 'avatars:write');
+ if (req.method === 'POST' && !auth) {
+ return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');
+ }
+
+ if (req.method === 'GET') return handleList(req, res, auth);
+ return handleCreate(req, res, auth);
+});
+
+async function handleList(req, res, auth) {
+ const url = new URL(req.url, 'http://x');
+ const limit = Math.min(Math.max(Number(url.searchParams.get('limit')) || 50, 1), 100);
+ const cursor = url.searchParams.get('cursor');
+ const kindFilter = url.searchParams.get('kind');
+ const tagFilter = url.searchParams.get('tag');
+ const visFilter = url.searchParams.get('visibility');
+ const includePublic = url.searchParams.get('include_public') === 'true';
+ const onlyPublic = !auth;
+
+ // Positional-parameter WHERE (the Neon client does not interpolate nested
+ // sql`` fragments) — same pattern as api/mocap/clips.js / searchPublicAvatars.
+ const params = [];
+ const conds = ['deleted_at is null'];
+
+ if (onlyPublic) {
+ conds.push(`visibility = 'public'`);
+ } else if (includePublic) {
+ params.push(auth.userId);
+ conds.push(`(owner_id = $${params.length} or visibility = 'public')`);
+ } else {
+ params.push(auth.userId);
+ conds.push(`owner_id = $${params.length}`);
+ }
+ if (kindFilter && /^[a-z]+$/.test(kindFilter)) {
+ params.push(kindFilter);
+ conds.push(`kind = $${params.length}`);
+ }
+ if (visFilter && ['private', 'unlisted', 'public'].includes(visFilter)) {
+ params.push(visFilter);
+ conds.push(`visibility = $${params.length}`);
+ }
+ if (tagFilter) {
+ params.push(tagFilter);
+ conds.push(`$${params.length} = any(tags)`);
+ }
+ if (cursor) {
+ const decoded = decodeCursor(cursor);
+ if (decoded) {
+ params.push(decoded.createdAt);
+ conds.push(`created_at < $${params.length}`);
+ }
+ }
+ params.push(limit + 1);
+
+ let rows;
+ try {
+ rows = await sql(
+ `select id, owner_id, slug, name, description, kind, format,
+ duration_ms, frame_count, fps, loop, tags, visibility,
+ thumbnail_key, price_amount, price_currency, listed,
+ play_count, purchase_count, created_at, updated_at, avatar_id
+ from animation_clips
+ where ${conds.join(' and ')}
+ order by created_at desc
+ limit $${params.length}`,
+ params,
+ );
+ } catch (err) {
+ console.error('[animations/clips/list]', err?.message || err);
+ return error(res, 500, 'db_error', 'Failed to list animations');
+ }
+
+ const hasMore = rows.length > limit;
+ const items = (hasMore ? rows.slice(0, limit) : rows).map((row) => listItem(row, auth));
+ const nextCursor = hasMore ? encodeCursor({ createdAt: rows[limit - 1].created_at }) : null;
+
+ res.setHeader(
+ 'Cache-Control',
+ auth ? 'private, max-age=0' : 'public, s-maxage=60, stale-while-revalidate=300',
+ );
+ return json(res, 200, { items, next_cursor: nextCursor });
+}
+
+async function handleCreate(req, res, auth) {
+ const rl = await limits.avatarPatch(auth.userId);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many animation saves');
+
+ const body = await readJson(req);
+ if (!body) return error(res, 400, 'invalid_request', 'body required');
+ const parsed = createSchema.safeParse(body);
+ if (!parsed.success) {
+ return error(res, 400, 'validation_error', parsed.error.issues.map((i) => i.message).join('; '));
+ }
+ const input = parsed.data;
+ const clip = input.clip;
+
+ // Every quaternion track must carry 4 floats per time sample, position 3.
+ for (const t of clip.tracks) {
+ const stride = /\.quaternion$/.test(t.name) ? 4 : t.name.endsWith('.position') || t.name.endsWith('.scale') ? 3 : 0;
+ if (stride && t.times.length && t.values.length !== t.times.length * stride) {
+ return error(res, 400, 'validation_error', `track ${t.name}: values length must be times×${stride}`);
+ }
+ }
+
+ if (input.avatar_id) {
+ const ok = await sql`
+ select 1 from avatars
+ where id = ${input.avatar_id} and owner_id = ${auth.userId} and deleted_at is null
+ limit 1
+ `;
+ if (!ok[0]) return error(res, 404, 'not_found', 'avatar_id not owned by you');
+ }
+
+ const slug = input.slug || autoSlug(input.name);
+ const dup = await sql`
+ select 1 from animation_clips
+ where owner_id = ${auth.userId} and slug = ${slug} and deleted_at is null
+ limit 1
+ `;
+ if (dup[0]) return error(res, 409, 'duplicate_slug', `slug "${slug}" already exists`);
+
+ const durationMs = Math.round(clip.duration * 1000);
+ const frameCount = input.editor_doc?.keyframes?.length || clip.tracks[0]?.times?.length || 0;
+ const fps = input.fps || input.editor_doc?.fps || null;
+ const loop = input.loop ?? input.editor_doc?.loop ?? true;
+ const kind = input.kind || (loop ? 'loop' : 'animation');
+ const tags = input.tags || [];
+ const visibility = input.visibility || 'private';
+ const editorJson = input.editor_doc ? JSON.stringify(input.editor_doc) : null;
+
+ // Inline small clips as JSONB; offload large ones to R2 and keep the pointer.
+ const clipJson = JSON.stringify(clip);
+ let inlineClip = clipJson;
+ let storageKey = null;
+ if (clipJson.length > MAX_BYTES_INLINE) {
+ try {
+ storageKey = `u/${auth.userId}/animations/clip-${slug}-${Date.now()}.json`;
+ await putObject({ key: storageKey, body: clipJson, contentType: 'application/json' });
+ inlineClip = null;
+ } catch (err) {
+ console.error('[animations/clips/create] R2 offload failed', err?.message || err);
+ return error(res, 502, 'storage_error', 'Failed to store large clip');
+ }
+ }
+
+ let row;
+ try {
+ [row] = await sql`
+ insert into animation_clips (
+ owner_id, avatar_id, slug, name, description, kind, format,
+ duration_ms, frame_count, fps, loop, clip, storage_key, editor_doc,
+ tags, visibility
+ ) values (
+ ${auth.userId}, ${input.avatar_id || null}, ${slug}, ${input.name},
+ ${input.description || null}, ${kind}, ${FORMAT},
+ ${durationMs}, ${frameCount}, ${fps}, ${loop},
+ ${inlineClip}::jsonb, ${storageKey}, ${editorJson}::jsonb,
+ ${tags}, ${visibility}
+ )
+ returning id, slug, name, description, kind, format, duration_ms,
+ frame_count, fps, loop, tags, visibility, avatar_id,
+ created_at, updated_at
+ `;
+ } catch (err) {
+ console.error('[animations/clips/create]', err?.message || err);
+ return error(res, 500, 'db_error', 'Failed to save animation');
+ }
+
+ return json(res, 201, { clip: row });
+}
+
+function listItem(row, auth) {
+ return {
+ id: row.id,
+ slug: row.slug,
+ name: row.name,
+ description: row.description,
+ kind: row.kind,
+ format: row.format,
+ duration_ms: row.duration_ms,
+ duration: row.duration_ms / 1000,
+ frame_count: row.frame_count,
+ fps: row.fps,
+ loop: row.loop,
+ tags: row.tags || [],
+ visibility: row.visibility,
+ avatar_id: row.avatar_id,
+ thumbnail_url: row.thumbnail_key ? publicUrl(row.thumbnail_key) : null,
+ play_count: Number(row.play_count || 0),
+ purchase_count: Number(row.purchase_count || 0),
+ listed: !!row.listed,
+ price: row.price_amount
+ ? { amount: String(row.price_amount), currency: row.price_currency }
+ : null,
+ owner: row.owner_id === auth?.userId ? 'self' : 'other',
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ };
+}
+
+async function resolveAuth(req, requiredScope) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id, source: 'session' };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (!bearer) return null;
+ if (!hasScope(bearer.scope, requiredScope)) return null;
+ return bearer;
+}
+
+function autoSlug(name) {
+ const base = String(name)
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 60) || 'animation';
+ const suffix = Math.random().toString(36).slice(2, 6);
+ return `${base}-${suffix}`;
+}
+
+function encodeCursor({ createdAt }) {
+ return Buffer.from(JSON.stringify({ c: createdAt })).toString('base64url');
+}
+function decodeCursor(cursor) {
+ try {
+ const obj = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
+ return { createdAt: new Date(obj.c) };
+ } catch {
+ return null;
+ }
+}
+
+// Exported for contract tests (validation/slug/cursor) without a live DB.
+export const __test__ = { createSchema, clipSchema, editorDocSchema, autoSlug, encodeCursor, decodeCursor, listItem, MAX_BYTES_INLINE };
diff --git a/api/animations/thumbnail.js b/api/animations/thumbnail.js
new file mode 100644
index 000000000..47f2f17b8
--- /dev/null
+++ b/api/animations/thumbnail.js
@@ -0,0 +1,85 @@
+// POST /api/animations/thumbnail — upload a PNG poster for an animation clip.
+// Body: { id: uuid, png_base64: "data:image/png;base64,..." | "<raw base64>" }
+// Owner-only. Stored at anim-thumb/<id>.png in R2; the clip row's thumbnail_key
+// is updated and served via publicUrl(). Mirrors api/avatars/thumbnail.js.
+
+import { sql } from '../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
+import { putObject, deleteObject, publicUrl } from '../_lib/r2.js';
+import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';
+import { limits } from '../_lib/rate-limit.js';
+
+const MAX_PNG_BYTES = 1_500_000;
+const PNG_HEADER = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');
+
+ const rl = await limits.upload(auth.userId);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'thumbnail upload rate exceeded');
+
+ const body = await readJson(req).catch(() => null);
+ const id = body?.id;
+ const pngB64 = body?.png_base64;
+
+ if (!id || typeof id !== 'string' || !/^[0-9a-f-]{8,}$/i.test(id)) {
+ return error(res, 400, 'invalid_request', 'id required');
+ }
+ if (!pngB64 || typeof pngB64 !== 'string') {
+ return error(res, 400, 'invalid_request', 'png_base64 required');
+ }
+
+ const raw = pngB64.replace(/^data:image\/png;base64,/, '');
+ let buf;
+ try {
+ buf = Buffer.from(raw, 'base64');
+ } catch {
+ return error(res, 400, 'invalid_request', 'png_base64 not valid base64');
+ }
+ if (buf.length === 0 || buf.length > MAX_PNG_BYTES) {
+ return error(res, 413, 'too_large', `png must be 1..${MAX_PNG_BYTES} bytes`);
+ }
+ if (!buf.subarray(0, 8).equals(PNG_HEADER)) {
+ return error(res, 400, 'invalid_request', 'body is not a PNG');
+ }
+
+ const [row] = await sql`
+ SELECT id, owner_id, thumbnail_key
+ FROM animation_clips
+ WHERE id = ${id} AND deleted_at IS NULL
+ LIMIT 1
+ `;
+ if (!row) return error(res, 404, 'not_found', 'animation not found');
+ if (row.owner_id !== auth.userId) return error(res, 403, 'forbidden', 'not your animation');
+
+ const key = `anim-thumb/${id}.png`;
+ await putObject({
+ key,
+ body: buf,
+ contentType: 'image/png',
+ metadata: { 'animation-id': id, 'uploaded-by': auth.userId },
+ });
+
+ if (row.thumbnail_key && row.thumbnail_key !== key) {
+ queueMicrotask(() => deleteObject(row.thumbnail_key).catch(() => {}));
+ }
+
+ await sql`UPDATE animation_clips SET thumbnail_key = ${key}, updated_at = now() WHERE id = ${id}`;
+
+ return json(res, 200, {
+ data: { id, thumbnail_key: key, thumbnail_url: publicUrl(key), bytes: buf.length },
+ });
+});
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (!bearer) return null;
+ if (!hasScope(bearer.scope, 'avatars:write')) return null;
+ return { userId: bearer.userId };
+}
diff --git a/multiplayer/src/block-store.js b/multiplayer/src/block-store.js
index f1a834005..72fc08b7b 100644
--- a/multiplayer/src/block-store.js
+++ b/multiplayer/src/block-store.js
@@ -33,17 +33,43 @@ class BlockStore {
this._saveTimers = new Map(); // coin → timeout handle
this._redis = null;
this._redisReady = null;
+ // True only once a real round-trip to Redis has succeeded. We don't trust
+ // "the client constructed" as proof of durability — bad credentials or a
+ // network partition surface only on the first request, so a startup PING
+ // confirms it. `durable` gates the WalkState.persistent flag the client
+ // reads, so we never tell a builder their work is saved when it isn't.
+ this._durable = false;
+ // Count consecutive write failures so a Redis outage mid-session escalates
+ // from a quiet warning to a loud one (and flips durability off) instead of
+ // scrolling identical warnings forever.
+ this._writeFailures = 0;
if (REDIS_URL && REDIS_TOKEN) {
// Lazy dynamic import so the dependency is only touched when configured.
this._redisReady = import('@upstash/redis')
- .then(({ Redis }) => { this._redis = new Redis({ url: REDIS_URL, token: REDIS_TOKEN }); })
- .catch((err) => { console.warn('[block-store] Redis init failed, memory-only:', err?.message); });
- console.log('[block-store] persistence: memory + Upstash Redis');
+ .then(async ({ Redis }) => {
+ this._redis = new Redis({ url: REDIS_URL, token: REDIS_TOKEN });
+ // Confirm the credentials actually work before we advertise durability.
+ await this._redis.ping();
+ this._durable = true;
+ console.log('[block-store] persistence: memory + Upstash Redis (verified)');
+ })
+ .catch((err) => {
+ this._redis = null;
+ console.error('[block-store] Redis unreachable — builds are MEMORY-ONLY and will not survive a restart:', err?.message);
+ });
} else {
console.log('[block-store] persistence: memory-only (set UPSTASH_REDIS_REST_URL/_TOKEN for cross-restart durability)');
}
}
+ // Has a real Redis round-trip succeeded? Drives WalkState.persistent so the
+ // build HUD can honestly say whether a creation survives a server restart.
+ get durable() { return this._durable; }
+
+ // Resolves once the Redis readiness probe has settled (success or failure), so
+ // callers can read `durable` with a definite answer. No-op when memory-only.
+ async ready() { if (this._redisReady) await this._redisReady; }
+
// Return the live Map for a coin, loading it from memory or Redis on first
// access. Subsequent edits mutate this same Map in place.
async load(coin) {
@@ -112,8 +138,22 @@ class BlockStore {
} else {
await this._redis.set(redisKey(coin), JSON.stringify(Object.fromEntries(map)));
}
+ // A successful write proves durability is back; reset the failure streak.
+ if (this._writeFailures > 0) {
+ console.log(`[block-store] Redis writes recovered after ${this._writeFailures} failure(s)`);
+ this._writeFailures = 0;
+ }
+ this._durable = true;
} catch (err) {
- console.warn(`[block-store] save failed for ${coin || 'mainland'}:`, err?.message);
+ this._writeFailures++;
+ // First failure: a clear error. After a few, the outage is sustained —
+ // flip durability off so new rooms report memory-only to their builders.
+ if (this._writeFailures >= 3) {
+ this._durable = false;
+ console.error(`[block-store] Redis save failing (${this._writeFailures}×) for ${coin || 'mainland'} — durability DEGRADED, builds at risk:`, err?.message);
+ } else {
+ console.warn(`[block-store] save failed for ${coin || 'mainland'}:`, err?.message);
+ }
}
}
}
diff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.js
index 5e350131d..31f760fc2 100644
--- a/multiplayer/src/rooms/WalkRoom.js
+++ b/multiplayer/src/rooms/WalkRoom.js
@@ -202,6 +202,11 @@ export class WalkRoom extends Room {
} catch (err) {
console.warn(`[walk_world ${this.roomId}] block restore failed:`, err?.message);
}
+ // Tell builders, honestly, whether this world survives a server restart.
+ // load() above already awaited the store's readiness probe, so durability
+ // is settled by now.
+ await blockStore.ready();
+ this.state.persistent = blockStore.durable;
}
onJoin(client, options) {
@@ -390,17 +395,24 @@ export class WalkRoom extends Room {
return `${x},${y},${z}`;
}
+ // Tell one client an edit didn't land, and why, so the build HUD can explain a
+ // block that never appeared instead of leaving the player guessing. The client
+ // throttles these into a single toast, so a flood reply is harmless.
+ _rejectEdit(client, reason) {
+ client.send('edit-reject', { reason });
+ }
+
_handlePlace(client, payload) {
if (!this.state.players.has(client.sessionId)) return;
- if (!this._editOk(client.sessionId)) return;
+ if (!this._editOk(client.sessionId)) { this._rejectEdit(client, 'rate'); return; }
const key = this._cellKey(payload);
- if (key === null) return;
+ if (key === null) { this._rejectEdit(client, 'bounds'); return; }
const t = payload.t;
- if (!Number.isInteger(t) || t < 0 || t >= BLOCK_TYPE_COUNT) return;
+ if (!Number.isInteger(t) || t < 0 || t >= BLOCK_TYPE_COUNT) { this._rejectEdit(client, 'type'); return; }
const existing = this.state.blocks.get(key);
// New cell — enforce the per-world budget. Re-painting an existing cell
// (changing its type) is always allowed since it doesn't grow the world.
- if (!existing && this.state.blocks.size >= MAX_BLOCKS) return;
+ if (!existing && this.state.blocks.size >= MAX_BLOCKS) { this._rejectEdit(client, 'budget'); return; }
if (existing) {
if (existing.t === t) return; // no-op
existing.t = t;
@@ -414,9 +426,9 @@ export class WalkRoom extends Room {
_handleRemove(client, payload) {
if (!this.state.players.has(client.sessionId)) return;
- if (!this._editOk(client.sessionId)) return;
+ if (!this._editOk(client.sessionId)) { this._rejectEdit(client, 'rate'); return; }
const key = this._cellKey(payload);
- if (key === null) return;
+ if (key === null) { this._rejectEdit(client, 'bounds'); return; }
if (!this.state.blocks.has(key)) return;
this.state.blocks.delete(key);
blockStore.delete(this.worldKey, key);
diff --git a/multiplayer/src/schemas.js b/multiplayer/src/schemas.js
index 68f408e79..cd51d9d9a 100644
--- a/multiplayer/src/schemas.js
+++ b/multiplayer/src/schemas.js
@@ -83,6 +83,11 @@ export class WalkState extends Schema {
// coordinate; the value carries only the block type. Persisted per coin so
// a community's build survives the room emptying and the server restarting.
this.blocks = new MapSchema();
+ // True when this world's build is backed by durable cross-restart storage
+ // (Upstash Redis). False = memory-only: the build survives the room emptying
+ // but not a full server restart. The client surfaces this so builders know
+ // whether their creation is saved for keeps.
+ this.persistent = false;
}
}
defineTypes(WalkState, {
@@ -94,4 +99,5 @@ defineTypes(WalkState, {
tier: 'string',
holderMinUsd: 'float32',
blocks: { map: Block },
+ persistent: 'boolean',
});
diff --git a/pages/agent-next.html b/pages/agent-next.html
index 70c7d5c98..a7abf76e3 100644
--- a/pages/agent-next.html
+++ b/pages/agent-next.html
@@ -186,6 +186,16 @@
display: flex; gap: 8px; align-items: center;
background: var(--panel); border: 1px solid var(--border-strong);
border-radius: 12px; padding: 5px 5px 5px 16px;
+ transition: border-color .2s ease, box-shadow .2s ease;
+ }
+ .chat-form--pulse {
+ border-color: var(--text);
+ animation: chat-form-pulse .9s ease;
+ }
+ @keyframes chat-form-pulse {
+ 0% { box-shadow: 0 0 0 0 rgba(232,232,232,0); }
+ 30% { box-shadow: 0 0 0 4px rgba(232,232,232,0.18); }
+ 100% { box-shadow: 0 0 0 0 rgba(232,232,232,0); }
}
.chat-input {
flex: 1; background: transparent; border: 0; outline: none;
@@ -734,7 +744,7 @@
</div>
<span class="brain-badge" id="brain-tier">Balanced</span>
</div>
- <a class="brain-link" href="/brain" id="brain-chat-link">Chat with AI →</a>
+ <a class="brain-link" href="#chat-form" id="brain-chat-link">Chat with AI →</a>
</div>
<div class="card brain-card">
@@ -862,7 +872,6 @@
document.getElementById('brain-model-name').textContent = meta.label;
document.getElementById('brain-network').textContent = meta.network;
document.getElementById('brain-tier').textContent = meta.tier;
- document.getElementById('brain-chat-link').href = `/brain`;
})();
// Update identity pills based on actual data
@@ -1166,6 +1175,18 @@
} catch (e) { console.warn('Agent send failed:', e); }
}
+ // ── "Chat with AI →" focuses the live on-page chat ─────────
+ const brainChatLink = document.getElementById('brain-chat-link');
+ if (brainChatLink) {
+ brainChatLink.addEventListener('click', (e) => {
+ e.preventDefault();
+ chatForm.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ chatInput.focus({ preventScroll: true });
+ chatForm.classList.add('chat-form--pulse');
+ setTimeout(() => chatForm.classList.remove('chat-form--pulse'), 900);
+ });
+ }
+
document.querySelectorAll('.chip[data-say]').forEach((c) => {
c.addEventListener('click', () => {
chatInput.value = c.dataset.say;
diff --git a/pages/avatar-studio.html b/pages/avatar-studio.html
index c8100e9d9..dcf897394 100644
--- a/pages/avatar-studio.html
+++ b/pages/avatar-studio.html
@@ -143,45 +143,92 @@
min-height: 0;
}
- /* ── Body type selector ───────────────────────────────── */
- .as-body-type {
+ /* ── Color customization panel ────────────────────────── */
+ .as-color-group { margin-bottom: 22px; }
+ .as-color-head {
display: flex;
- align-items: center;
- gap: 10px;
- padding: 12px 16px;
- border-bottom: 1px solid var(--border);
- background: var(--panel);
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 8px;
+ margin: 0 0 10px;
}
- .as-body-label {
- font-size: 11px;
- text-transform: uppercase;
- letter-spacing: 0.06em;
- color: var(--text-3);
+ .as-color-title {
+ font-size: 13px;
font-weight: 600;
+ color: var(--text);
}
- .as-body-toggle {
+ .as-color-current {
display: inline-flex;
- background: var(--panel-2);
+ align-items: center;
+ gap: 6px;
+ font-size: 11px;
+ color: var(--text-3);
+ font-variant-numeric: tabular-nums;
+ }
+ .as-color-current .dot {
+ width: 12px; height: 12px;
+ border-radius: 50%;
+ border: 1px solid rgba(255, 255, 255, 0.25);
+ }
+ .as-swatches {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(34px, 1fr));
+ gap: 8px;
+ }
+ .as-swatch {
+ position: relative;
+ aspect-ratio: 1 / 1;
+ border-radius: 9px;
border: 1px solid var(--border-2);
- border-radius: 8px;
- padding: 2px;
- gap: 2px;
+ cursor: pointer;
+ padding: 0;
+ transition: transform 0.12s, box-shadow 0.12s, border-color 0.12s;
+ outline: none;
}
- .as-body-toggle button {
- background: transparent;
- border: none;
- color: var(--text-3);
- font: 600 12px/1 inherit;
- padding: 7px 14px;
- border-radius: 6px;
+ .as-swatch:hover { transform: translateY(-1px); border-color: var(--text-3); }
+ .as-swatch:focus-visible { box-shadow: 0 0 0 2px var(--accent); }
+ .as-swatch[aria-pressed="true"] {
+ border-color: var(--accent);
+ box-shadow: 0 0 0 2px var(--accent), 0 0 0 4px rgba(0, 0, 0, 0.6);
+ }
+ .as-swatch[aria-pressed="true"]::after {
+ content: '';
+ position: absolute;
+ inset: 0;
+ margin: auto;
+ width: 7px; height: 7px;
+ border-radius: 50%;
+ background: rgba(255, 255, 255, 0.9);
+ box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.45);
+ }
+ .as-swatch-default {
+ background:
+ linear-gradient(135deg, transparent 46%, var(--danger) 46%, var(--danger) 54%, transparent 54%),
+ var(--panel-2);
+ }
+ .as-swatch-custom {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ background:
+ conic-gradient(from 0deg, #f43f5e, #f59e0b, #eab308, #22c55e, #3b82f6, #8b5cf6, #f43f5e);
+ color: #fff;
+ overflow: hidden;
+ }
+ .as-swatch-custom input[type='color'] {
+ position: absolute;
+ inset: 0;
+ width: 100%; height: 100%;
+ opacity: 0;
cursor: pointer;
- transition: color 0.12s, background 0.12s;
+ border: 0;
+ padding: 0;
}
- .as-body-toggle button[aria-pressed="true"] {
- background: rgba(255, 255, 255, 0.12);
- color: var(--text);
+ .as-swatch-custom svg {
+ width: 14px; height: 14px;
+ filter: drop-shadow(0 1px 1px rgba(0, 0, 0, 0.6));
+ pointer-events: none;
}
- .as-body-toggle button:hover { color: var(--text); }
/* ── Name input ───────────────────────────────────────── */
.as-name-row {
@@ -267,6 +314,12 @@
text-transform: uppercase;
letter-spacing: 0.06em;
}
+ .as-chip .as-chip-dot {
+ width: 11px; height: 11px;
+ border-radius: 50%;
+ border: 1px solid rgba(255, 255, 255, 0.3);
+ flex-shrink: 0;
+ }
.as-chip button {
background: transparent;
border: 0;
@@ -794,16 +847,9 @@
<div class="as-name-row">
<input class="as-name-input" id="as-name" type="text" placeholder="Name your avatar" maxlength="60" autocomplete="off" aria-label="Avatar name" />
</div>
- <div class="as-body-type">
- <span class="as-body-label">Body</span>
- <div class="as-body-toggle" role="group" aria-label="Body type">
- <button type="button" data-body="male" aria-pressed="true">Masculine</button>
- <button type="button" data-body="female" aria-pressed="false">Feminine</button>
- </div>
- </div>
<nav class="as-tabs" id="as-tabs" role="tablist"></nav>
- <div class="as-chips" id="as-chips" aria-label="Current outfit"></div>
- <div class="as-panel" id="as-panel"></div>
+ <div class="as-chips" id="as-chips" aria-label="Selected items"></div>
+ <div class="as-panel" id="as-panel" role="tabpanel" tabindex="0"></div>
<div class="as-status" id="as-status">Choose a style below to get started.</div>
<a href="/pricing" class="upgrade-banner" style="margin:12px 16px;text-decoration:none;">
<div class="upgrade-banner-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"/></svg></div>
diff --git a/pages/create-selfie.html b/pages/create-selfie.html
index cd43d1a57..6c2a4cde2 100644
--- a/pages/create-selfie.html
+++ b/pages/create-selfie.html
@@ -558,6 +558,32 @@
height: 100%;
--poster-color: transparent;
}
+ /* Skeleton shimmer while the GLB streams in. */
+ .done-viewer.loading::before {
+ content: '';
+ position: absolute;
+ inset: 0;
+ z-index: 1;
+ background: linear-gradient(100deg, var(--panel) 30%, rgba(255, 255, 255, 0.06) 50%, var(--panel) 70%);
+ background-size: 200% 100%;
+ animation: done-shimmer 1.4s ease-in-out infinite;
+ }
+ @keyframes done-shimmer { to { background-position: -200% 0; } }
+ /* GLB failed to load — show a recoverable message, never a black void. */
+ .done-viewer.failed::before {
+ content: 'Preview unavailable — open your avatar to view it.';
+ position: absolute;
+ inset: 0;
+ z-index: 1;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ text-align: center;
+ padding: 24px;
+ color: var(--muted);
+ font-size: 13px;
+ line-height: 1.5;
+ }
.name-row {
margin: 0 0 20px;
}
@@ -1081,7 +1107,6 @@
camera-controls
shadow-intensity="0.7"
shadow-softness="0.8"
- loading="lazy"
environment-image="neutral"
exposure="0.95"
camera-orbit="0deg 78deg auto"
@@ -1242,18 +1267,41 @@
s.className = 'build-step completed';
});
+ const viewer = document.querySelector('.done-viewer');
+ viewer?.classList.add('loading');
+ viewer?.classList.remove('failed');
+
try {
const res = await fetch(`/api/avatars/${encodeURIComponent(_avatarId)}`, {
credentials: 'include',
});
if (res.ok) {
- const avatar = await res.json();
+ // The API wraps the record: { avatar: { model_url, name, ... } }.
+ const { avatar } = await res.json();
const modelEl = document.getElementById('done-model');
- if (modelEl && avatar.model_url) modelEl.setAttribute('src', avatar.model_url);
+ const modelUrl = avatar?.model_url || avatar?.url;
+ if (modelEl && modelUrl) {
+ modelEl.addEventListener('load', () => viewer?.classList.remove('loading'), { once: true });
+ modelEl.addEventListener('error', () => {
+ viewer?.classList.remove('loading');
+ viewer?.classList.add('failed');
+ }, { once: true });
+ modelEl.setAttribute('src', modelUrl);
+ } else {
+ // Materialized but no GLB URL — don't leave a silent black void.
+ viewer?.classList.remove('loading');
+ viewer?.classList.add('failed');
+ }
const nameEl = /** @type {HTMLInputElement|null} */ (document.getElementById('done-name'));
- if (nameEl && avatar.name) nameEl.value = avatar.name;
+ if (nameEl && avatar?.name) nameEl.value = avatar.name;
+ } else {
+ viewer?.classList.remove('loading');
+ viewer?.classList.add('failed');
}
- } catch (_) {}
+ } catch (_) {
+ viewer?.classList.remove('loading');
+ viewer?.classList.add('failed');
+ }
notifyDone();
showStep('done');
diff --git a/pages/home.html b/pages/home.html
index 30e232f2b..18c7882ee 100644
--- a/pages/home.html
+++ b/pages/home.html
@@ -1023,7 +1023,27 @@
@media (max-width: 720px) { .cta-card { padding: 48px 24px; } }
/* ── FOOTER ──────────────────────────────────────────────── */
- footer { border-top: 1px solid var(--hairline); padding: 40px 0 56px; }
+ footer { border-top: 1px solid var(--hairline); padding: 56px 0; }
+ .foot-cols {
+ display: grid;
+ grid-template-columns: repeat(5, 1fr);
+ gap: 32px; margin-bottom: 48px;
+ padding-bottom: 40px; border-bottom: 1px solid var(--hairline);
+ }
+ .foot-col { display: flex; flex-direction: column; gap: 10px; }
+ .foot-col-h {
+ font-family: var(--font-mono); font-size: 11px;
+ text-transform: uppercase; letter-spacing: 0.16em;
+ color: var(--text-4); margin-bottom: 4px;
+ }
+ .foot-col a { color: var(--text-3); font-size: 13.5px; transition: color 0.15s; }
+ .foot-col a:hover { color: var(--text); }
+ @media (max-width: 880px) {
+ .foot-cols { grid-template-columns: repeat(2, 1fr); gap: 28px 24px; }
+ }
+ @media (max-width: 460px) {
+ .foot-cols { grid-template-columns: 1fr 1fr; }
+ }
.version-switch { display:inline-flex; align-items:center; gap:6px; margin-top:16px; padding:6px 14px; border-radius:100px; border:1px solid var(--hairline-strong); color:var(--text-3); font-size:12px; text-decoration:none; transition:color .2s, border-color .2s; }
.version-switch:hover { color:var(--text-2); border-color:var(--text-3); }
.version-switch svg { width:14px; height:14px; }
@@ -1033,9 +1053,6 @@
color: var(--text-4); font-size: 13px; font-family: var(--font-mono);
letter-spacing: 0.04em;
}
- .foot-links { display: flex; gap: 22px; flex-wrap: wrap; }
- .foot-links a { color: var(--text-3); transition: color 0.15s; }
- .foot-links a:hover { color: var(--text); }
/* ── MOBILE NAV ─────────────────────────────────────────── */
.nav-toggle {
@@ -2494,6 +2511,8 @@
<div class="nav-pop" role="menu" aria-label="Discover">
<a class="nav-mi" href="/features" role="menuitem"><span class="nav-mi-t">Features</span><span class="nav-mi-d">Everything an agent gets — interactive tour</span></a>
<a class="nav-mi" href="/discover" role="menuitem"><span class="nav-mi-t">ERC-8004 Agents</span><span class="nav-mi-d">On-chain agent directory</span></a>
+ <a class="nav-mi" href="/agents" role="menuitem"><span class="nav-mi-t">Agents Index</span><span class="nav-mi-d">Browse every registered agent</span></a>
+ <a class="nav-mi" href="/reputation" role="menuitem"><span class="nav-mi-t">Reputation Explorer</span><span class="nav-mi-d">On-chain scores &amp; attestations</span></a>
<a class="nav-mi" href="/marketplace" role="menuitem"><span class="nav-mi-t">Marketplace</span><span class="nav-mi-d">Buy, sell &amp; remix agents</span></a>
<a class="nav-mi" href="/gallery" role="menuitem"><span class="nav-mi-t">Avatar Gallery</span><span class="nav-mi-d">Every public 3D avatar</span></a>
<a class="nav-mi" href="/skills" role="menuitem"><span class="nav-mi-t">Skills <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Browse agent tool packs &amp; capabilities</span></a>
@@ -2542,6 +2561,14 @@
<a class="nav-mi" href="/three-live" role="menuitem"><span class="nav-mi-t">$THREE Live <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Protocol pulse — live trades in 3D</span></a>
<a class="nav-mi" href="/strategy-lab" role="menuitem"><span class="nav-mi-t">Strategy Lab</span><span class="nav-mi-d">DCA + subscriptions</span></a>
<a class="nav-mi" href="/club" role="menuitem"><span class="nav-mi-t">Pole Club <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">x402 micro-tip demo — $0.001 / dance</span></a>
+ <a class="nav-mi" href="/shopper" role="menuitem"><span class="nav-mi-t">Endpoint Shopper <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">AI chains x402 endpoints to answer a task</span></a>
+ <a class="nav-mi" href="/tutor" role="menuitem"><span class="nav-mi-t">Pay-As-You-Learn Tutor <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">$0.01 per answer in USDC over x402</span></a>
+ <a class="nav-mi" href="/fact-checker" role="menuitem"><span class="nav-mi-t">Fact Checker <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">$0.10 per claim — cited verdict + attestation</span></a>
+ <a class="nav-mi" href="/arbitrage" role="menuitem"><span class="nav-mi-t">x402 Arbitrage <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Cheapest endpoint per capability, live</span></a>
+ <a class="nav-mi" href="/providers" role="menuitem"><span class="nav-mi-t">x402 Providers <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Operator profiles for the paid API catalog</span></a>
+ <a class="nav-mi" href="/unstoppable" role="menuitem"><span class="nav-mi-t">Unstoppable Agent <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Self-funding agent dashboard, live</span></a>
+ <a class="nav-mi" href="/rider" role="menuitem"><span class="nav-mi-t">Rider (VR)</span><span class="nav-mi-d">Open-source VR music visualization</span></a>
+ <a class="nav-mi" href="/forever" role="menuitem"><span class="nav-mi-t">Forever</span><span class="nav-mi-d">Etch a message into Bitcoin — forever</span></a>
<a class="nav-mi" href="/eth-vanity" role="menuitem"><span class="nav-mi-t">ETH vanity (CREATE2)</span><span class="nav-mi-d">Grind a smart-contract address</span></a>
<a class="nav-mi" href="/vanity-wallet" role="menuitem"><span class="nav-mi-t">Vanity wallet</span><span class="nav-mi-d">Grind a Solana address</span></a>
</div>
@@ -2569,6 +2596,8 @@
<div class="dr-h">Discover</div>
<a href="/features">Features</a>
<a href="/discover">ERC-8004 Agents</a>
+ <a href="/agents">Agents Index</a>
+ <a href="/reputation">Reputation Explorer</a>
<a href="/marketplace">Marketplace</a>
<a href="/gallery">Avatar Gallery</a>
<a href="/skills">Skills</a>
@@ -2596,6 +2625,14 @@
<a href="/pumpfun">Pump.fun stream</a>
<a href="/three-live">$THREE Live</a>
<a href="/club">Pole Club</a>
+ <a href="/shopper">Endpoint Shopper</a>
+ <a href="/tutor">Pay-As-You-Learn Tutor</a>
+ <a href="/fact-checker">Fact Checker</a>
+ <a href="/arbitrage">x402 Arbitrage</a>
+ <a href="/providers">x402 Providers</a>
+ <a href="/unstoppable">Unstoppable Agent</a>
+ <a href="/rider">Rider (VR)</a>
+ <a href="/forever">Forever</a>
<div class="dr-h">More</div>
<a href="/pricing">Pricing</a>
<div class="sep"></div>
@@ -3938,16 +3975,46 @@
<!-- ── FOOTER ─────────────────────────────────────────────────────── -->
<footer>
<div class="wrap-1280">
- <div class="foot-inner">
- <div>© 2026 · three.ws · the 3D agent layer of the internet</div>
- <div class="foot-links">
- <a href="/docs">Docs</a>
- <a href="/pricing">Pricing</a>
+ <nav class="foot-cols" aria-label="Footer">
+ <div class="foot-col">
+ <div class="foot-col-h">Product</div>
+ <a href="/create">Build an agent</a>
+ <a href="/marketplace">Marketplace</a>
<a href="/discover">Discover</a>
+ <a href="/pricing">Pricing</a>
+ <a href="/dashboard">Console</a>
+ </div>
+ <div class="foot-col">
+ <div class="foot-col-h">Explore</div>
+ <a href="/agents">Agents Index</a>
+ <a href="/reputation">Reputation</a>
+ <a href="/characters">Characters</a>
+ <a href="/gallery">Avatar Gallery</a>
+ <a href="/bazaar">x402 Bazaar</a>
+ </div>
+ <div class="foot-col">
+ <div class="foot-col-h">Developers</div>
+ <a href="/docs">Docs</a>
+ <a href="/avatar-sdk">Avatar SDK</a>
<a href="/dashboard/api">API</a>
+ <a href="/artifact">Artifact Viewer</a>
+ <a href="/sitemap">Sitemap</a>
+ </div>
+ <div class="foot-col">
+ <div class="foot-col-h">Company</div>
+ <a href="/blog">Blog</a>
+ <a href="/community">Community</a>
<a href="https://github.com/nirholas/three.ws">GitHub</a>
<a href="mailto:[email protected]">Contact</a>
</div>
+ <div class="foot-col">
+ <div class="foot-col-h">Legal</div>
+ <a href="/legal/privacy">Privacy</a>
+ <a href="/legal/tos">Terms</a>
+ </div>
+ </nav>
+ <div class="foot-inner">
+ <div>© 2026 · three.ws · the 3D agent layer of the internet</div>
<a href="/home-classic" class="version-switch" aria-label="Switch to classic homepage">
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><path d="M2.5 8h11M6.5 4L2.5 8l4 4"/></svg>
Classic homepage
diff --git a/pages/pose.html b/pages/pose.html
index 0ced3b5ef..5b49acde6 100644
--- a/pages/pose.html
+++ b/pages/pose.html
@@ -682,6 +682,136 @@
.tl-export.is-ok { border-color: rgba(120, 255, 170, 0.5); color: #b6ffce; }
.tl-export.is-err { border-color: rgba(248, 113, 113, 0.6); color: var(--danger); }
+ /* ── Library: overlays, dialogs, drawer, cards ───────────── */
+ .pl-overlay {
+ position: fixed;
+ inset: 0;
+ z-index: 1000;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: rgba(0, 0, 0, 0.6);
+ backdrop-filter: blur(4px);
+ -webkit-backdrop-filter: blur(4px);
+ padding: 20px;
+ animation: pl-fade 0.14s ease;
+ }
+ @keyframes pl-fade { from { opacity: 0; } to { opacity: 1; } }
+ .pl-dialog {
+ width: min(440px, 100%);
+ max-height: 88vh;
+ overflow-y: auto;
+ background: var(--panel-solid);
+ border: 1px solid var(--border-strong);
+ border-radius: 16px;
+ padding: 22px;
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ box-shadow: 0 24px 60px rgba(0, 0, 0, 0.5);
+ }
+ .pl-dialog-title { margin: 0; font-size: 17px; font-weight: 600; color: var(--text); }
+ .pl-dialog-sub { margin: 0; font-size: 13px; line-height: 1.5; color: var(--text-2); }
+ .pl-field { display: flex; flex-direction: column; gap: 5px; font-size: 12px; color: var(--text-2); }
+ .pl-field > span { font-weight: 500; }
+ .pl-input {
+ width: 100%;
+ box-sizing: border-box;
+ background: rgba(255, 255, 255, 0.04);
+ color: var(--text);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 8px 10px;
+ font: inherit;
+ font-size: 13px;
+ }
+ .pl-input:focus { outline: none; border-color: var(--border-strong); background: rgba(255, 255, 255, 0.07); }
+ .pl-textarea { resize: vertical; min-height: 38px; }
+ .pl-link-note { margin: 0; font-size: 11.5px; color: var(--text-3); }
+ .pl-dialog-err {
+ font-size: 12px;
+ color: var(--danger);
+ background: rgba(248, 113, 113, 0.1);
+ border: 1px solid rgba(248, 113, 113, 0.3);
+ border-radius: 8px;
+ padding: 7px 10px;
+ }
+ .pl-dialog-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 4px; }
+ .pl-danger { color: var(--danger); border-color: rgba(248, 113, 113, 0.4); }
+ .pl-danger:hover { background: rgba(248, 113, 113, 0.12); }
+
+ /* Drawer */
+ .pl-drawer-overlay { justify-content: flex-end; align-items: stretch; padding: 0; }
+ .pl-drawer {
+ width: min(720px, 100%);
+ background: var(--panel-solid);
+ border-left: 1px solid var(--border-strong);
+ display: flex;
+ flex-direction: column;
+ transform: translateX(24px);
+ opacity: 0;
+ transition: transform 0.2s ease, opacity 0.2s ease;
+ }
+ .pl-drawer.pl-open { transform: translateX(0); opacity: 1; }
+ .pl-drawer-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 14px 18px;
+ border-bottom: 1px solid var(--border);
+ }
+ .pl-tabs { display: flex; gap: 4px; padding: 3px; background: rgba(255, 255, 255, 0.04); border: 1px solid var(--border); border-radius: 999px; }
+ .pl-tab {
+ appearance: none; border: none; background: transparent; color: var(--text-2);
+ font: inherit; font-size: 12.5px; padding: 6px 14px; border-radius: 999px; cursor: pointer;
+ transition: background 0.12s ease, color 0.12s ease;
+ }
+ .pl-tab:hover { color: var(--text); }
+ .pl-tab[aria-selected="true"] { background: rgba(255, 255, 255, 0.18); color: #e8e8e8; }
+ .pl-close {
+ appearance: none; border: 1px solid var(--border); background: rgba(255, 255, 255, 0.04);
+ color: var(--text-2); width: 30px; height: 30px; border-radius: 8px; cursor: pointer; font-size: 13px;
+ }
+ .pl-close:hover { color: var(--text); border-color: var(--border-strong); }
+ .pl-grid {
+ flex: 1;
+ overflow-y: auto;
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
+ gap: 14px;
+ padding: 18px;
+ align-content: start;
+ }
+ .pl-card {
+ border: 1px solid var(--border);
+ border-radius: 12px;
+ overflow: hidden;
+ background: rgba(255, 255, 255, 0.02);
+ display: flex;
+ flex-direction: column;
+ transition: border-color 0.12s ease, transform 0.12s ease;
+ }
+ .pl-card:hover { border-color: var(--border-strong); transform: translateY(-2px); }
+ .pl-card-thumb { width: 100%; aspect-ratio: 1 / 1; object-fit: cover; background: #0b0b10; display: block; }
+ .pl-card-thumb-empty { display: flex; align-items: center; justify-content: center; font-size: 28px; color: var(--text-3); }
+ .pl-card-badges { display: flex; gap: 5px; flex-wrap: wrap; padding: 8px 10px 0; }
+ .pl-badge { font-size: 9.5px; text-transform: uppercase; letter-spacing: 0.05em; padding: 2px 7px; border-radius: 999px; border: 1px solid var(--border); color: var(--text-3); }
+ .pl-badge-public { color: #b6ffce; border-color: rgba(120, 255, 170, 0.4); }
+ .pl-badge-unlisted { color: #ffe6a3; border-color: rgba(255, 210, 100, 0.4); }
+ .pl-badge-price { color: #a3d8ff; border-color: rgba(120, 180, 255, 0.4); }
+ .pl-card-name { padding: 6px 10px 0; font-size: 13.5px; font-weight: 600; color: var(--text); }
+ .pl-card-meta { padding: 2px 10px 0; font-size: 11px; color: var(--text-3); }
+ .pl-card-tags { display: flex; flex-wrap: wrap; gap: 4px; padding: 6px 10px 0; }
+ .pl-tag { font-size: 10px; color: var(--text-2); background: rgba(255, 255, 255, 0.05); border-radius: 4px; padding: 1px 6px; }
+ .pl-card-actions { display: flex; flex-wrap: wrap; gap: 5px; padding: 10px; margin-top: auto; }
+ .pl-card-actions .pose-btn { font-size: 11.5px; padding: 5px 9px; }
+ .pl-skeleton { min-height: 240px; background: linear-gradient(110deg, rgba(255,255,255,0.03) 30%, rgba(255,255,255,0.07) 50%, rgba(255,255,255,0.03) 70%); background-size: 200% 100%; animation: pl-shimmer 1.3s ease infinite; }
+ @keyframes pl-shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } }
+ .pl-empty { grid-column: 1 / -1; text-align: center; padding: 48px 20px; color: var(--text-2); }
+ .pl-empty-icon { font-size: 38px; margin-bottom: 8px; }
+ .pl-empty h3 { margin: 0 0 6px; font-size: 16px; color: var(--text); }
+ .pl-empty p { margin: 0 auto 14px; font-size: 13px; max-width: 320px; line-height: 1.5; }
+
/* ── Responsive ─────────────────────────────────────── */
@media (max-width: 1100px) {
#pose-app {
@@ -731,6 +861,10 @@
<span class="spacer"></span>
+ <button type="button" id="pose-library" class="pose-btn" title="Your saved animations">My animations</button>
+ <button type="button" id="pose-save" class="pose-btn pose-btn-primary" title="Save this animation to your account (Ctrl/Cmd+S)">Save</button>
+ <span class="sep"></span>
+
<button type="button" id="pose-reset" class="pose-btn" title="Reset the pose to rest">Reset pose</button>
<label class="pose-btn file-label" title="Load a pose from JSON">
diff --git a/public/features.json b/public/features.json
index f5dba14b9..a89de9db5 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-05-31T04:29:19.743Z",
+ "generated_at": "2026-05-31T04:41:48.080Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/scripts/_shot-studio.mjs b/scripts/_shot-studio.mjs
new file mode 100644
index 000000000..f8e2de1c4
--- /dev/null
+++ b/scripts/_shot-studio.mjs
@@ -0,0 +1,16 @@
+import { chromium } from 'playwright';
+const url = process.argv[2] || 'http://localhost:3001/create/studio';
+const out = process.argv[3] || '/tmp/studio.png';
+const b = await chromium.launch({
+ args: ['--use-gl=angle','--use-angle=swiftshader','--enable-unsafe-swiftshader','--ignore-gpu-blocklist']
+});
+const p = await b.newPage({ viewport: { width: 1440, height: 900 }, deviceScaleFactor: 1 });
+const errs = [];
+p.on('console', m => { if (m.type()==='error') errs.push(m.text()); });
+p.on('pageerror', e => errs.push('PAGEERROR: '+e.message));
+await p.goto(url, { waitUntil: 'networkidle' }).catch(e=>console.log('goto:',e.message));
+await p.waitForTimeout(6000);
+await p.screenshot({ path: out, fullPage: false });
+console.log('shot ->', out);
+console.log('console errors:', errs.length ? '\n'+errs.join('\n') : 'none');
+await b.close();
diff --git a/src/agent-accessories.js b/src/agent-accessories.js
index 92ced53d8..0154aa3a2 100644
--- a/src/agent-accessories.js
+++ b/src/agent-accessories.js
@@ -1,12 +1,16 @@
// AccessoryManager — applies outfit morph bindings and bone-attached GLB accessories
// at runtime without touching the canonical avatar GLB on R2.
//
-// Outfit state lives in agent_identities.meta.appearance = { outfit, accessories, morphs }.
+// Appearance lives in agent_identities.meta.appearance =
+// { outfit?, accessories, morphs, colors?, hidden? }.
+// colors/hidden drive the garment-layer system (recolour + show/hide) defined
+// in src/avatar-wardrobe.js; outfit is the legacy single-outfit field.
// The Empathy Layer's morph loop only iterates its own _morphTarget dict, so
// outfit morphs set here are never clobbered by emotion blending.
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { resolveURI } from './ipfs.js';
+import { collectSlotTargets } from './avatar-wardrobe.js';
const SINGLE_SLOT_KINDS = new Set(['outfit', 'hat', 'glasses']);
@@ -17,6 +21,12 @@ export class AccessoryManager {
this._loader = new GLTFLoader();
// id → { preset, object?: THREE.Group, morphs?: Array<{node,name,idx}> }
this._applied = new Map();
+ // material.uuid → original THREE.Color, captured the first time we tint a
+ // garment so "default" can restore the authored colour exactly.
+ this._slotColorOriginals = new Map();
+ // Last applied layer state ({colors, hidden}), replayed after a model
+ // swap (onModelReplaced).
+ this._layers = null;
}
/**
@@ -80,6 +90,11 @@ export class AccessoryManager {
_applyRawMorphs(this.viewer.content, appearance.morphs);
}
+ // Garment-layer state: hide/show + recolour the model's own meshes.
+ if (appearance.colors || appearance.hidden) {
+ this.applyLayers({ colors: appearance.colors, hidden: appearance.hidden });
+ }
+
for (const id of ids) {
const preset = byId.get(id);
if (preset) {
@@ -106,9 +121,40 @@ export class AccessoryManager {
}
this._applied.clear();
+ // The colour-restore receipts referenced the discarded model's materials.
+ this._slotColorOriginals = new Map();
+
for (const preset of snapshot) {
await this.applyPreset(preset);
}
+
+ // Replay garment-layer state onto the new skeleton's meshes.
+ if (this._layers) this.applyLayers(this._layers);
+ }
+
+ /**
+ * Apply garment-layer state to the live model: toggle each detected slot's
+ * meshes visible/hidden and tint their materials. Idempotent and absolute —
+ * pass the full layer state every call; slots not listed reset to visible +
+ * original colour. See src/avatar-wardrobe.js for the slot taxonomy.
+ *
+ * @param {{ colors?: { [slotId:string]: string }, hidden?: string[] }} layers
+ */
+ applyLayers(layers) {
+ const root = this.viewer?.content;
+ if (!root) return;
+ const colors = layers?.colors || {};
+ const hiddenSet = new Set(layers?.hidden || []);
+ this._layers = { colors: { ...colors }, hidden: [...hiddenSet] };
+
+ const targets = collectSlotTargets(root);
+ for (const [slotId, { meshes, materials }] of targets) {
+ const hide = hiddenSet.has(slotId);
+ for (const mesh of meshes) mesh.visible = !hide;
+ const hex = colors[slotId] || null;
+ for (const mat of materials) _tintMaterial(mat, hex, this._slotColorOriginals);
+ }
+ this.viewer?.invalidate?.();
}
// ── Private ──────────────────────────────────────────────────────────────
@@ -218,6 +264,20 @@ function _applyRawMorphs(model, morphs) {
});
}
+/**
+ * Tint (or restore) a single material. `hex` multiplies the authored base
+ * colour via material.color (glTF baseColorFactor); passing null restores the
+ * original colour captured on first tint. Records originals keyed by material
+ * uuid so repeated tints don't drift.
+ */
+function _tintMaterial(m, hex, originals) {
+ if (!m || !m.color) return;
+ if (!originals.has(m.uuid)) originals.set(m.uuid, m.color.clone());
+ if (hex) m.color.set(hex);
+ else m.color.copy(originals.get(m.uuid));
+ m.needsUpdate = true;
+}
+
function _zeroMorphs(receipts) {
for (const { node, idx } of receipts) {
if (node.morphTargetInfluences) node.morphTargetInfluences[idx] = 0;
diff --git a/src/avatar-face-capture.js b/src/avatar-face-capture.js
index d76428622..24960a4f1 100644
--- a/src/avatar-face-capture.js
+++ b/src/avatar-face-capture.js
@@ -29,13 +29,13 @@
// avoids breaking changes from auto-upgraded CDN aliases; jsDelivr's `+esm`
// suffix returns the ESM build.
const TASKS_VISION_URL =
- 'https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/+esm';
+ 'https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/+esm';
// Hosted by Google. They publish exactly one official URL per model — these
// are the standard locations used in every MediaPipe sample, public CORS,
// no auth.
const WASM_ROOT =
- 'https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/wasm';
+ 'https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/wasm';
const MODEL_URL =
'https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task';
diff --git a/src/avatar-studio.js b/src/avatar-studio.js
index a55cf7c07..696012a42 100644
--- a/src/avatar-studio.js
+++ b/src/avatar-studio.js
@@ -41,12 +41,11 @@ let idle = null;
let presets = [];
let presetsById = new Map();
-let workingAppearance = { outfit: null, accessories: [], morphs: {} };
+let workingAppearance = { accessories: [], morphs: {}, colors: {} };
let previewedId = null;
let previewToken = 0;
let opQueue = Promise.resolve();
let searchQuery = '';
-let bodyType = 'male';
function queueOp(fn) {
const next = opQueue.then(fn).catch((err) => {
@@ -57,15 +56,45 @@ function queueOp(fn) {
}
const TABS = [
- { id: 'outfit', label: 'Outfits', kinds: ['outfit'], emoji: '👕', single: true },
+ { id: 'color', label: 'Color', kinds: [], color: true },
{ id: 'hat', label: 'Hats', kinds: ['hat'], emoji: '🎩', single: true },
{ id: 'glasses', label: 'Glasses', kinds: ['glasses'], emoji: '🕶️', single: true },
{ id: 'earrings', label: 'Earrings', kinds: ['earrings'], emoji: '💎', single: false },
- { id: 'sculpt', label: 'Sculpt', kinds: [], emoji: '✨', single: true, sculpt: true },
+ { id: 'sculpt', label: 'Face', kinds: [], emoji: '✨', single: true, sculpt: true },
];
-const KIND_EMOJI = { outfit: '👕', hat: '🎩', glasses: '🕶️', earrings: '💎' };
-const KIND_LABEL = { outfit: 'Outfit', hat: 'Hat', glasses: 'Glasses', earrings: 'Earrings' };
-let activeTab = 'outfit';
+const KIND_EMOJI = { hat: '🎩', glasses: '🕶️', earrings: '💎' };
+const KIND_LABEL = { hat: 'Hat', glasses: 'Glasses', earrings: 'Earrings' };
+let activeTab = 'color';
+
+// ── Color customization ──────────────────────────────────────────────
+// The base avatar is a ReadyPlayerMe (Wolf3D) mesh with named, texture-backed
+// materials. We tint a slot by multiplying every material in that slot by a
+// chosen color (white = original texture, untinted). The same slot→material
+// map and tint semantics are mirrored server-side in api/_lib/bake.js so the
+// saved/baked GLB looks identical to the live preview.
+const COLOR_SLOTS = [
+ {
+ id: 'skin',
+ label: 'Skin tone',
+ materials: ['Wolf3D_Skin', 'Wolf3D_Body'],
+ swatches: ['#ffe9d6', '#f3c1a3', '#e0a878', '#c08552', '#9c6b44', '#6f4a32', '#4a2f20'],
+ },
+ {
+ id: 'hair',
+ label: 'Hair',
+ materials: ['Wolf3D_Hair'],
+ swatches: ['#0e0e0e', '#3b2417', '#6b4423', '#9a6a3a', '#c89b5a', '#d8b34a', '#b8b8b8', '#e2604a', '#9b5cc0', '#4a86d6'],
+ },
+ {
+ id: 'outfit',
+ label: 'Outfit',
+ materials: ['Wolf3D_Outfit_Top', 'Wolf3D_Outfit_Bottom', 'Wolf3D_Outfit_Footwear'],
+ swatches: ['#222831', '#f2f2f2', '#1e3a5f', '#7a1f2b', '#1f6b3a', '#c08a1e', '#6b3fa0', '#d4577e', '#3b6ea5', '#101010'],
+ },
+];
+const COLOR_SLOT_BY_ID = new Map(COLOR_SLOTS.map((s) => [s.id, s]));
+const HEX_RE = /^#[0-9a-f]{6}$/i;
+const BODY_TYPE = 'feminine'; // the single shipped base mesh is feminine-presenting
// ── Init ─────────────────────────────────────────────────────────────
@@ -84,9 +113,11 @@ async function init() {
renderChips();
renderActivePanel();
bindHeader();
- bindBodyType();
await scenePromise;
+ // Re-render once the mesh is live so the active panel (sculpt morphs, color
+ // preview) reflects the loaded avatar instead of the "waiting" placeholder.
+ renderActivePanel();
}
async function bootScene() {
@@ -127,19 +158,46 @@ async function fetchPresets() {
function renderTabs() {
const el = $('as-tabs');
- el.innerHTML = TABS.map(
- (t) => `
- <button class="as-tab${t.id === activeTab ? ' active' : ''}" data-tab="${t.id}" role="tab">
+ el.innerHTML = TABS.map((t) => {
+ const active = t.id === activeTab;
+ return `
+ <button class="as-tab${active ? ' active' : ''}" data-tab="${t.id}" role="tab"
+ id="as-tab-${t.id}" aria-selected="${active ? 'true' : 'false'}"
+ aria-controls="as-panel" tabindex="${active ? '0' : '-1'}">
${t.label}
- </button>
- `,
- ).join('');
- el.querySelectorAll('.as-tab').forEach((btn) => {
- btn.addEventListener('click', () => {
- activeTab = btn.dataset.tab;
- searchQuery = '';
- el.querySelectorAll('.as-tab').forEach((b) => b.classList.toggle('active', b === btn));
- renderActivePanel();
+ </button>`;
+ }).join('');
+
+ const tabs = [...el.querySelectorAll('.as-tab')];
+ const selectTab = (btn, { focus = false } = {}) => {
+ if (!btn || btn.dataset.tab === activeTab) {
+ if (focus) btn?.focus();
+ return;
+ }
+ activeTab = btn.dataset.tab;
+ searchQuery = '';
+ tabs.forEach((b) => {
+ const on = b === btn;
+ b.classList.toggle('active', on);
+ b.setAttribute('aria-selected', on ? 'true' : 'false');
+ b.tabIndex = on ? 0 : -1;
+ });
+ if (focus) btn.focus();
+ renderActivePanel();
+ };
+
+ tabs.forEach((btn, i) => {
+ btn.addEventListener('click', () => selectTab(btn));
+ // Roving-tabindex keyboard nav per WAI-ARIA tablist pattern.
+ btn.addEventListener('keydown', (e) => {
+ let target = null;
+ if (e.key === 'ArrowRight' || e.key === 'ArrowDown') target = tabs[(i + 1) % tabs.length];
+ else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') target = tabs[(i - 1 + tabs.length) % tabs.length];
+ else if (e.key === 'Home') target = tabs[0];
+ else if (e.key === 'End') target = tabs[tabs.length - 1];
+ else return;
+ e.preventDefault();
+ selectTab(target, { focus: true });
});
});
}
@@ -147,6 +205,12 @@ function renderTabs() {
function renderActivePanel() {
const tab = TABS.find((t) => t.id === activeTab);
const panel = $('as-panel');
+ panel.setAttribute('aria-labelledby', `as-tab-${activeTab}`);
+
+ if (tab.color) {
+ renderColorPanel(panel);
+ return;
+ }
if (tab.sculpt) {
if (!scene?.root) {
@@ -224,6 +288,119 @@ function tilePreviewMarkup(preset) {
`;
}
+// ── Color panel ──────────────────────────────────────────────────────
+
+function renderColorPanel(panel) {
+ const ready = !!scene?.root;
+ const groups = COLOR_SLOTS.map((slot) => {
+ const current = workingAppearance.colors[slot.id] || null;
+ const presetMatch = current && slot.swatches.some((h) => h.toLowerCase() === current);
+ const swatches = slot.swatches
+ .map((hex) => {
+ const pressed = current === hex.toLowerCase();
+ return `<button class="as-swatch" type="button" role="radio"
+ aria-checked="${pressed ? 'true' : 'false'}" aria-pressed="${pressed ? 'true' : 'false'}"
+ aria-label="${esc(slot.label)} ${esc(hex)}" data-slot="${slot.id}" data-hex="${esc(hex)}"
+ style="background:${esc(hex)}"></button>`;
+ })
+ .join('');
+ const noneSel = !current;
+ // A custom (non-palette) color counts as the custom swatch being active.
+ const customSel = current && !presetMatch;
+ return `
+ <div class="as-color-group" data-group="${slot.id}">
+ <div class="as-color-head">
+ <span class="as-color-title">${esc(slot.label)}</span>
+ <span class="as-color-current">
+ <span class="dot" data-current-dot style="background:${esc(current || '#ffffff')}"></span>
+ <span data-current-label>${current ? esc(current.toUpperCase()) : 'Default'}</span>
+ </span>
+ </div>
+ <div class="as-swatches" role="radiogroup" aria-label="${esc(slot.label)} color">
+ <button class="as-swatch as-swatch-default" type="button" role="radio"
+ aria-checked="${noneSel ? 'true' : 'false'}" aria-pressed="${noneSel ? 'true' : 'false'}"
+ aria-label="${esc(slot.label)} default" data-slot="${slot.id}" data-hex=""
+ title="Default"></button>
+ ${swatches}
+ <label class="as-swatch as-swatch-custom${customSel ? '' : ''}"
+ aria-label="${esc(slot.label)} custom color" title="Custom color"
+ ${customSel ? 'style="border-color:var(--accent);box-shadow:0 0 0 2px var(--accent),0 0 0 4px rgba(0,0,0,0.6)"' : ''}>
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 19l7-7 3 3-7 7-3-3z"/><path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"/><path d="M2 2l7.586 7.586"/><circle cx="11" cy="11" r="2"/></svg>
+ <input type="color" data-slot="${slot.id}" value="${esc(current || '#ffffff')}" />
+ </label>
+ </div>
+ </div>`;
+ }).join('');
+
+ panel.innerHTML = `
+ <p class="ae-sculpt-note" style="margin-top:2px;">Tint skin, hair and outfit. Colors bake into your saved avatar.</p>
+ ${groups}
+ ${ready ? '' : '<div class="as-empty" style="padding-top:8px;">Waiting for avatar to load…</div>'}`;
+
+ bindColorPanel(panel);
+}
+
+function bindColorPanel(panel) {
+ panel.querySelectorAll('.as-swatch[data-slot]').forEach((btn) => {
+ btn.addEventListener('click', () => setSlotColor(btn.dataset.slot, btn.dataset.hex || null));
+ });
+ panel.querySelectorAll('input[type="color"][data-slot]').forEach((input) => {
+ const slot = input.dataset.slot;
+ input.addEventListener('input', () => liveSlotColor(slot, input.value));
+ input.addEventListener('change', () => setSlotColor(slot, input.value));
+ });
+}
+
+function setSlotColor(slotId, hex) {
+ const slot = COLOR_SLOT_BY_ID.get(slotId);
+ if (!slot) return;
+ if (hex && HEX_RE.test(hex)) {
+ workingAppearance.colors[slotId] = hex.toLowerCase();
+ } else {
+ delete workingAppearance.colors[slotId];
+ }
+ applySlotColor(slot, workingAppearance.colors[slotId] || null);
+ if (activeTab === 'color') renderActivePanel();
+ renderChips();
+ const c = workingAppearance.colors[slotId];
+ setStatus('', c ? `${slot.label} → ${c.toUpperCase()}` : `${slot.label} reset to default.`);
+}
+
+// Live (uncommitted) preview while dragging the native color picker — applies
+// to the mesh and updates the slot's readout without a full re-render so the
+// picker stays open.
+function liveSlotColor(slotId, hex) {
+ const slot = COLOR_SLOT_BY_ID.get(slotId);
+ if (!slot || !HEX_RE.test(hex)) return;
+ applySlotColor(slot, hex);
+ const group = document.querySelector(`.as-color-group[data-group="${cssEscape(slotId)}"]`);
+ if (!group) return;
+ const dot = group.querySelector('[data-current-dot]');
+ const label = group.querySelector('[data-current-label]');
+ if (dot) dot.style.background = hex;
+ if (label) label.textContent = hex.toUpperCase();
+}
+
+// Multiply every material in the slot by `hex` (null → white = original texture).
+function applySlotColor(slot, hex) {
+ if (!scene?.root) return;
+ const color = hex || '#ffffff';
+ const names = new Set(slot.materials);
+ scene.root.traverse((obj) => {
+ if (!obj.isMesh) return;
+ const mats = Array.isArray(obj.material) ? obj.material : [obj.material];
+ for (const m of mats) {
+ if (m && m.color && names.has(m.name)) m.color.set(color);
+ }
+ });
+}
+
+function applyAllColors() {
+ for (const slot of COLOR_SLOTS) {
+ applySlotColor(slot, workingAppearance.colors[slot.id] || null);
+ }
+}
+
function bindSearch() {
const input = $('as-search');
if (!input) return;
@@ -252,37 +429,41 @@ function bindTiles(panel, tab) {
function renderChips() {
const el = $('as-chips');
- const picks = [];
- if (workingAppearance.outfit) picks.push(workingAppearance.outfit);
- for (const id of workingAppearance.accessories) picks.push(id);
-
- el.innerHTML = picks
- .map((id) => {
- const p = presetsById.get(id);
- if (!p) return '';
- return `
- <span class="as-chip" data-id="${esc(id)}">
- <span class="as-chip-kind">${esc(KIND_LABEL[p.kind] || p.kind)}</span>
- <span>${esc(p.name)}</span>
- <button type="button" aria-label="Remove ${esc(p.name)}" data-remove="${esc(id)}">×</button>
- </span>
- `;
- })
- .join('');
+ const parts = [];
+
+ for (const id of workingAppearance.accessories) {
+ const p = presetsById.get(id);
+ if (!p) continue;
+ parts.push(`
+ <span class="as-chip" data-id="${esc(id)}">
+ <span class="as-chip-kind">${esc(KIND_LABEL[p.kind] || p.kind)}</span>
+ <span>${esc(p.name)}</span>
+ <button type="button" aria-label="Remove ${esc(p.name)}" data-remove="${esc(id)}">×</button>
+ </span>`);
+ }
+
+ for (const slot of COLOR_SLOTS) {
+ const hex = workingAppearance.colors[slot.id];
+ if (!hex) continue;
+ parts.push(`
+ <span class="as-chip" data-color="${slot.id}">
+ <span class="as-chip-dot" style="background:${esc(hex)}"></span>
+ <span class="as-chip-kind">${esc(slot.label)}</span>
+ <button type="button" aria-label="Reset ${esc(slot.label)}" data-reset-color="${slot.id}">×</button>
+ </span>`);
+ }
+
+ el.innerHTML = parts.join('');
el.querySelectorAll('button[data-remove]').forEach((btn) => {
- btn.addEventListener('click', async () => {
- await removeCommitted(btn.dataset.remove);
- });
+ btn.addEventListener('click', () => removeCommitted(btn.dataset.remove));
+ });
+ el.querySelectorAll('button[data-reset-color]').forEach((btn) => {
+ btn.addEventListener('click', () => setSlotColor(btn.dataset.resetColor, null));
});
}
function tileSelected(tab, presetId) {
- if (tab.kinds.includes('outfit')) {
- return presetId
- ? workingAppearance.outfit === presetId
- : !workingAppearance.outfit;
- }
const matching = workingAppearance.accessories.filter((id) => {
const preset = presetsById.get(id);
return preset && tab.kinds.includes(preset.kind);
@@ -369,14 +550,10 @@ function cssEscape(s) {
function isCommitted(presetId) {
if (!presetId) return false;
- return (
- workingAppearance.outfit === presetId ||
- workingAppearance.accessories.includes(presetId)
- );
+ return workingAppearance.accessories.includes(presetId);
}
function committedIdForKind(kind) {
- if (kind === 'outfit') return workingAppearance.outfit || null;
for (const id of workingAppearance.accessories) {
const p = presetsById.get(id);
if (p && p.kind === kind) return id;
@@ -391,11 +568,7 @@ async function onTileClick(tab, presetId) {
previewToken++;
await queueOp(async () => {
- if (tab.kinds.includes('outfit')) {
- await applyOutfit(presetId || null);
- } else {
- await applyAccessory(tab, presetId || null);
- }
+ await applyAccessory(tab, presetId || null);
});
renderActivePanel();
renderChips();
@@ -409,27 +582,11 @@ async function removeCommitted(id) {
await queueOp(async () => {
accessoryManager?.removePreset(id);
});
- if (workingAppearance.outfit === id) {
- workingAppearance.outfit = null;
- } else {
- workingAppearance.accessories = workingAppearance.accessories.filter((a) => a !== id);
- }
+ workingAppearance.accessories = workingAppearance.accessories.filter((a) => a !== id);
renderActivePanel();
renderChips();
}
-async function applyOutfit(presetId) {
- if (!presetId) {
- if (workingAppearance.outfit) accessoryManager?.removePreset(workingAppearance.outfit);
- workingAppearance.outfit = null;
- return;
- }
- const preset = presetsById.get(presetId);
- if (!preset) return;
- if (accessoryManager) await accessoryManager.applyPreset(preset);
- workingAppearance.outfit = presetId;
-}
-
async function applyAccessory(tab, presetId) {
const inSlot = workingAppearance.accessories.filter((id) => {
const p = presetsById.get(id);
@@ -477,30 +634,18 @@ function bindHeader() {
$('as-reset').addEventListener('click', () => resetAll());
}
-function bindBodyType() {
- const btns = document.querySelectorAll('.as-body-toggle button[data-body]');
- btns.forEach((btn) => {
- btn.addEventListener('click', () => {
- bodyType = btn.dataset.body;
- btns.forEach((b) => b.setAttribute('aria-pressed', b === btn ? 'true' : 'false'));
- });
- });
-}
-
async function resetAll() {
previewedId = null;
previewToken++;
await queueOp(async () => {
- const wasIds = [
- workingAppearance.outfit,
- ...workingAppearance.accessories,
- ].filter(Boolean);
+ const wasIds = [...workingAppearance.accessories].filter(Boolean);
if (accessoryManager) {
for (const id of wasIds) accessoryManager.removePreset(id);
}
- workingAppearance = { outfit: null, accessories: [], morphs: {} };
+ workingAppearance = { accessories: [], morphs: {}, colors: {} };
if (scene?.root) {
applyMorphsToRoot(scene.root, {});
+ applyAllColors();
}
if (accessoryManager) await accessoryManager.hydrateFromAppearance(workingAppearance);
});
@@ -523,9 +668,9 @@ function setStatus(kind, text) {
function collapseAppearance(a) {
const out = {};
- if (a.outfit) out.outfit = a.outfit;
if (a.accessories?.length) out.accessories = [...a.accessories];
if (a.morphs && Object.keys(a.morphs).length) out.morphs = { ...a.morphs };
+ if (a.colors && Object.keys(a.colors).length) out.colors = { ...a.colors };
return Object.keys(out).length ? out : null;
}
@@ -584,7 +729,7 @@ async function saveAvatar() {
{
name,
source: 'studio',
- source_meta: { generator: 'avatar-studio', body_type: bodyType },
+ source_meta: { generator: 'avatar-studio', body_type: BODY_TYPE },
visibility: 'public',
},
{
diff --git a/src/avatar-wardrobe.js b/src/avatar-wardrobe.js
new file mode 100644
index 000000000..f6253be7f
--- /dev/null
+++ b/src/avatar-wardrobe.js
@@ -0,0 +1,419 @@
+/**
+ * Avatar wardrobe — layered garment editor for /create/studio and /avatars/:id/edit
+ *
+ * Modern rigged avatars (Ready Player Me / Wolf3D, Avaturn, most Blender/Mixamo
+ * exports) are NOT a single welded mesh — the body, hair, and garments ship as
+ * separate skinned meshes that share one skeleton, each with its own named,
+ * texture-backed material. That makes two real operations possible:
+ *
+ * 1. Recolour a layer — multiply its material(s) by a chosen colour. White /
+ * "default" leaves the authored texture untouched; a tint reads as dyed
+ * fabric, not a flat fill (glTF baseColorFactor semantics).
+ * 2. Strip to the base body — hide the garment meshes to expose the base
+ * mannequin, then dress it back up one layer at a time.
+ *
+ * This module is the single source of truth for that layer taxonomy. It detects
+ * which slots a loaded GLB actually exposes (no invented controls — same
+ * contract as the sculpt panel), renders the Wardrobe panel, and exports the
+ * pure helpers AccessoryManager uses to push slot state onto the live scene.
+ *
+ * Slot state round-trips through appearance:
+ * appearance.colors = { skin:'#rrggbb', hair, outfit, … } // per-slot tint
+ * appearance.hidden = ['outfit', 'glasses', …] // hidden slots
+ * It survives the same save → validate → server-bake → viewer path as
+ * accessories/morphs. Keep slot ids + the material/mesh patterns below in sync
+ * with api/_lib/bake.js (baker) and api/_lib/accessories.js (validation).
+ */
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * Slot taxonomy. `materials` lists exact material names for the avatars we ship
+ * (Wolf3D = Ready Player Me, avaturn_* = Avaturn); `match` is a name fallback so
+ * arbitrary user-uploaded GLBs in the editor still resolve. A mesh joins a slot
+ * if any of its materials matches by exact name OR regex (on material or mesh
+ * name). `strip` slots are the ones "Start minimal" hides — hair and skin stay.
+ * ────────────────────────────────────────────────────────────────────────── */
+
+export const WARDROBE_SLOTS = [
+ {
+ id: 'skin',
+ label: 'Skin tone',
+ materials: ['Wolf3D_Skin', 'Wolf3D_Body', 'avaturn_body_material'],
+ match: /(^|[_-])(skin|body)(?![a-z])/i,
+ palette: 'skin',
+ removable: false,
+ strip: false,
+ },
+ {
+ id: 'hair',
+ label: 'Hair',
+ materials: ['Wolf3D_Hair', 'avaturn_hair_0_material'],
+ match: /hair/i,
+ palette: 'hair',
+ removable: true,
+ strip: false,
+ },
+ {
+ id: 'outfit',
+ label: 'Outfit',
+ materials: [
+ 'Wolf3D_Outfit_Top', 'Wolf3D_Outfit_Bottom', 'Wolf3D_Outfit_Footwear',
+ 'avaturn_look_0_material', 'avaturn_shoes_0_material',
+ ],
+ match: /outfit|shirt|jacket|hoodie|sweater|dress|pants|trouser|jeans|skirt|shorts|footwear|shoe|boot|sneaker|(^|[_-])(top|bottom|look)(?![a-z])/i,
+ palette: 'garment',
+ removable: true,
+ strip: true,
+ },
+ {
+ id: 'glasses',
+ label: 'Glasses',
+ materials: ['Wolf3D_Glasses'],
+ match: /glass|eyewear|spectacle/i,
+ palette: null,
+ removable: true,
+ strip: true,
+ },
+];
+
+export const WARDROBE_SLOT_IDS = WARDROBE_SLOTS.map((s) => s.id);
+const SLOT_BY_ID = new Map(WARDROBE_SLOTS.map((s) => [s.id, s]));
+
+/* Curated palettes. The leading `null` swatch clears the tint (authored colour).
+ * Tints multiply the base-colour texture, so they read as a recolour. */
+export const PALETTES = {
+ skin: [null, '#ffe9d6', '#f3c1a3', '#e0a878', '#c08552', '#9c6b44', '#6f4a32', '#4a2f20'],
+ hair: [null, '#0e0e0e', '#3b2417', '#6b4423', '#9a6a3a', '#c89b5a', '#d8b34a', '#b8b8b8', '#e2604a', '#9b5cc0', '#4a86d6'],
+ garment: [null, '#222831', '#f2f2f2', '#1e3a5f', '#7a1f2b', '#1f6b3a', '#c08a1e', '#6b3fa0', '#d4577e', '#3b6ea5', '#101010'],
+};
+
+export const HEX_RE = /^#[0-9a-f]{6}$/i;
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * Detection — pure, shared with AccessoryManager and (by mirror) the baker
+ * ────────────────────────────────────────────────────────────────────────── */
+
+/**
+ * Resolve, for the loaded scene root, which slots are present and the concrete
+ * meshes + materials each one controls.
+ * @returns {Map<string, { meshes: Set<object>, materials: Set<object> }>}
+ */
+export function collectSlotTargets(root) {
+ const out = new Map();
+ root?.traverse?.((obj) => {
+ if (!obj.isMesh || !obj.geometry) return;
+ const mats = materialsOf(obj);
+ const def = slotDefFor(obj, mats);
+ if (!def) return;
+ if (!out.has(def.id)) out.set(def.id, { meshes: new Set(), materials: new Set() });
+ const entry = out.get(def.id);
+ entry.meshes.add(obj);
+ for (const m of mats) entry.materials.add(m);
+ });
+ return out;
+}
+
+function slotDefFor(mesh, mats) {
+ const meshName = mesh.name || '';
+ const matNames = mats.map((m) => m?.name || '');
+ for (const def of WARDROBE_SLOTS) {
+ if (matNames.some((n) => def.materials.includes(n))) return def;
+ if (def.match.test(meshName) || matNames.some((n) => def.match.test(n))) return def;
+ }
+ return null;
+}
+
+function materialsOf(mesh) {
+ if (Array.isArray(mesh.material)) return mesh.material.filter(Boolean);
+ return mesh.material ? [mesh.material] : [];
+}
+
+/** Ordered list of slots present on this model. Drives the panel. */
+export function discoverSlots(root) {
+ const targets = collectSlotTargets(root);
+ return WARDROBE_SLOTS.filter((def) => targets.has(def.id)).map((def) => ({ def }));
+}
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * Panel
+ * ────────────────────────────────────────────────────────────────────────── *
+ *
+ * @param {object} opts
+ * @param {HTMLElement} opts.container
+ * @param {object} opts.root three.js scene root (slot discovery)
+ * @param {object} opts.working workingAppearance — we mutate .colors & .hidden
+ * @param {(layers:{colors:object,hidden:string[]})=>void} opts.applyLayers
+ * @param {()=>void} opts.onDirty
+ */
+export function renderWardrobePanel({ container, root, working, applyLayers, onDirty }) {
+ injectCss();
+ working.colors = working.colors || {};
+ working.hidden = Array.isArray(working.hidden) ? working.hidden : [];
+
+ if (!root) {
+ container.innerHTML = `<div class="aw-empty">Waiting for the avatar to load…</div>`;
+ return;
+ }
+
+ const slots = discoverSlots(root);
+ if (!slots.length) {
+ container.innerHTML = `
+ <div class="aw-empty">
+ This model doesn't expose separate garment meshes, so there are no
+ layers to recolour or remove. Re-import through
+ <a href="/create" style="color:inherit">/create</a> for a layered avatar.
+ </div>`;
+ return;
+ }
+
+ const stripSlots = slots.filter((s) => s.def.strip);
+ const anyDressed = stripSlots.some((s) => !working.hidden.includes(s.def.id));
+ const anyHidden = stripSlots.some((s) => working.hidden.includes(s.def.id));
+
+ container.innerHTML = `
+ <p class="aw-note">
+ This avatar is built from separate layers. Hide a layer to strip back to
+ the base body, then dress it up — recolour each piece and stack
+ accessories on top.
+ </p>
+ <div class="aw-bulk">
+ <button class="aw-bulk-btn" type="button" id="aw-strip" ${anyDressed ? '' : 'disabled'}>
+ <span aria-hidden="true">◍</span> Start minimal
+ </button>
+ <button class="aw-bulk-btn" type="button" id="aw-dress" ${anyHidden ? '' : 'disabled'}>
+ <span aria-hidden="true">✦</span> Dress fully
+ </button>
+ </div>
+ <div class="aw-list">
+ ${slots.map((s) => slotCardHtml(s.def, working)).join('')}
+ </div>
+ `;
+
+ wirePanel(container, root, working, applyLayers, onDirty);
+}
+
+function slotCardHtml(def, working) {
+ const hidden = working.hidden.includes(def.id);
+ const color = working.colors[def.id] || null;
+ const palette = def.palette ? PALETTES[def.palette] : null;
+
+ const toggle = def.removable
+ ? `<button class="aw-eye" type="button" data-slot="${def.id}" role="switch"
+ aria-checked="${hidden ? 'false' : 'true'}" aria-label="${escAttr(def.label)} visible">
+ ${hidden ? eyeOff() : eyeOn()}
+ </button>`
+ : '';
+
+ const swatches = palette
+ ? `<div class="aw-swatches" data-slot="${def.id}" role="group" aria-label="${escAttr(def.label)} colour">
+ ${palette.map((c) => swatchHtml(def.id, c, color)).join('')}
+ ${customSwatchHtml(def.id, color, palette)}
+ </div>`
+ : '';
+
+ return `
+ <div class="aw-card${hidden ? ' aw-card-off' : ''}" data-slot-card="${def.id}">
+ <div class="aw-card-head">
+ <span class="aw-card-name">${escHtml(def.label)}</span>
+ <span class="aw-card-state" data-state="${def.id}">${hidden ? 'Hidden' : 'On'}</span>
+ ${toggle}
+ </div>
+ ${swatches}
+ </div>
+ `;
+}
+
+function swatchHtml(slotId, color, current) {
+ const isDefault = color === null;
+ const selected = isDefault ? !current : current?.toLowerCase() === color.toLowerCase();
+ const style = isDefault
+ ? 'background:repeating-conic-gradient(#3a3a3a 0deg 90deg,#2a2a2a 90deg 180deg) 0 0/10px 10px'
+ : `background:${color}`;
+ return `
+ <button class="aw-swatch${selected ? ' selected' : ''}${isDefault ? ' aw-swatch-default' : ''}"
+ type="button" data-slot="${slotId}" data-color="${isDefault ? '' : escAttr(color)}"
+ style="${style}" title="${isDefault ? 'Default (original)' : escAttr(color)}"
+ aria-label="${isDefault ? 'Default colour' : escAttr(color)}"
+ aria-pressed="${selected}"></button>
+ `;
+}
+
+function customSwatchHtml(slotId, current, palette) {
+ const inPalette = !current || palette.some((c) => c && c.toLowerCase() === current.toLowerCase());
+ const selected = !!current && !inPalette;
+ return `
+ <label class="aw-swatch aw-swatch-custom${selected ? ' selected' : ''}"
+ title="Custom colour" aria-label="Custom colour">
+ <input type="color" data-slot="${slotId}" value="${escAttr(current || '#888888')}" />
+ <span aria-hidden="true">+</span>
+ </label>
+ `;
+}
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * Wiring — targeted DOM updates so the native colour picker keeps focus
+ * ────────────────────────────────────────────────────────────────────────── */
+
+function wirePanel(container, root, working, applyLayers, onDirty) {
+ const commit = () => {
+ applyLayers({ colors: working.colors, hidden: working.hidden });
+ onDirty?.();
+ };
+
+ container.querySelectorAll('.aw-eye[data-slot]').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ const id = btn.dataset.slot;
+ const nowHidden = btn.getAttribute('aria-checked') === 'true'; // on → hide
+ setHidden(working, id, nowHidden);
+ reflectVisibility(container, id, nowHidden);
+ commit();
+ });
+ });
+
+ container.querySelectorAll('.aw-swatch[data-slot]').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ const id = btn.dataset.slot;
+ setColor(working, id, btn.dataset.color || null);
+ reflectColor(container, id, btn.dataset.color || null);
+ commit();
+ });
+ });
+
+ container.querySelectorAll('input[type="color"][data-slot]').forEach((input) => {
+ input.addEventListener('input', () => {
+ const id = input.dataset.slot;
+ setColor(working, id, input.value);
+ reflectColor(container, id, input.value);
+ commit();
+ });
+ });
+
+ container.querySelector('#aw-strip')?.addEventListener('click', () => {
+ for (const s of discoverSlots(root)) if (s.def.strip) setHidden(working, s.def.id, true);
+ commit();
+ renderWardrobePanel({ container, root, working, applyLayers, onDirty });
+ });
+ container.querySelector('#aw-dress')?.addEventListener('click', () => {
+ for (const s of discoverSlots(root)) if (s.def.strip) setHidden(working, s.def.id, false);
+ commit();
+ renderWardrobePanel({ container, root, working, applyLayers, onDirty });
+ });
+}
+
+function reflectVisibility(container, slotId, hidden) {
+ const card = container.querySelector(`[data-slot-card="${cssEscape(slotId)}"]`);
+ const eye = container.querySelector(`.aw-eye[data-slot="${cssEscape(slotId)}"]`);
+ const state = container.querySelector(`[data-state="${cssEscape(slotId)}"]`);
+ card?.classList.toggle('aw-card-off', hidden);
+ if (eye) {
+ eye.setAttribute('aria-checked', hidden ? 'false' : 'true');
+ eye.innerHTML = hidden ? eyeOff() : eyeOn();
+ }
+ if (state) state.textContent = hidden ? 'Hidden' : 'On';
+ const strip = container.querySelector('#aw-strip');
+ const dress = container.querySelector('#aw-dress');
+ if (strip) strip.disabled = !container.querySelector('.aw-eye[aria-checked="true"]');
+ if (dress) dress.disabled = !container.querySelector('.aw-eye[aria-checked="false"]');
+}
+
+function reflectColor(container, slotId, color) {
+ const group = container.querySelector(`.aw-swatches[data-slot="${cssEscape(slotId)}"]`);
+ if (!group) return;
+ const norm = color ? color.toLowerCase() : null;
+ let matched = false;
+ group.querySelectorAll('.aw-swatch[data-color]').forEach((sw) => {
+ const c = sw.dataset.color ? sw.dataset.color.toLowerCase() : null;
+ const sel = c === norm;
+ if (sel) matched = true;
+ sw.classList.toggle('selected', sel);
+ sw.setAttribute('aria-pressed', String(sel));
+ });
+ group.querySelector('.aw-swatch-custom')?.classList.toggle('selected', !!norm && !matched);
+}
+
+function setHidden(working, slotId, hidden) {
+ if (!SLOT_BY_ID.get(slotId)?.removable) return;
+ const has = working.hidden.includes(slotId);
+ if (hidden && !has) working.hidden.push(slotId);
+ else if (!hidden && has) working.hidden = working.hidden.filter((id) => id !== slotId);
+}
+
+function setColor(working, slotId, color) {
+ if (!SLOT_BY_ID.has(slotId)) return;
+ if (color && HEX_RE.test(color)) working.colors[slotId] = color.toLowerCase();
+ else delete working.colors[slotId];
+}
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * Icons + CSS
+ * ────────────────────────────────────────────────────────────────────────── */
+
+function eyeOn() {
+ return `<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>`;
+}
+function eyeOff() {
+ return `<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>`;
+}
+
+let _cssInjected = false;
+function injectCss() {
+ if (_cssInjected || typeof document === 'undefined') return;
+ _cssInjected = true;
+ const style = document.createElement('style');
+ style.id = 'aw-css';
+ style.textContent = `
+ .aw-note { font-size: 12px; color: var(--text-3, #71717a); line-height: 1.55; margin: 0 0 14px; }
+ .aw-empty { color: var(--text-3, #71717a); font-size: 13px; padding: 24px 4px; text-align: center; line-height: 1.6; }
+ .aw-bulk { display: flex; gap: 8px; margin-bottom: 14px; }
+ .aw-bulk-btn {
+ flex: 1; display: inline-flex; align-items: center; justify-content: center; gap: 7px;
+ background: var(--panel, #111); border: 1px solid var(--border-2, #2a2a2a);
+ color: var(--text-2, #a1a1aa); padding: 9px 12px; border-radius: 9px; cursor: pointer;
+ font: 600 12px/1 inherit; transition: color .15s, border-color .15s, background .15s;
+ }
+ .aw-bulk-btn:hover:not([disabled]) { color: var(--text, #fafafa); border-color: var(--text-3, #71717a); background: rgba(255,255,255,.03); }
+ .aw-bulk-btn[disabled] { opacity: .4; cursor: default; pointer-events: none; }
+ .aw-list { display: flex; flex-direction: column; gap: 8px; }
+ .aw-card {
+ border: 1px solid var(--border, #1f1f1f); border-radius: 11px; background: var(--panel, #111);
+ padding: 12px 14px; transition: border-color .15s, opacity .15s;
+ }
+ .aw-card-off { opacity: .62; border-style: dashed; }
+ .aw-card-head { display: flex; align-items: center; gap: 10px; }
+ .aw-card-name { font-size: 13px; font-weight: 600; color: var(--text, #fafafa); }
+ .aw-card-state {
+ font-size: 9px; text-transform: uppercase; letter-spacing: .08em; color: var(--text-3, #71717a);
+ border: 1px solid var(--border-2, #2a2a2a); border-radius: 999px; padding: 2px 7px; margin-left: auto;
+ }
+ .aw-eye {
+ display: inline-flex; align-items: center; justify-content: center;
+ width: 32px; height: 28px; border-radius: 7px; cursor: pointer;
+ background: var(--panel-2, #161616); border: 1px solid var(--border-2, #2a2a2a); color: var(--text-2, #a1a1aa);
+ transition: color .15s, border-color .15s;
+ }
+ .aw-eye:hover { color: var(--text, #fafafa); border-color: var(--text-3, #71717a); }
+ .aw-eye[aria-checked="false"] { color: var(--text-3, #555); }
+ .aw-card-state { margin-left: auto; }
+ .aw-card-head .aw-eye { margin-left: 0; }
+ .aw-swatches { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 12px; }
+ .aw-swatch {
+ width: 24px; height: 24px; border-radius: 7px; cursor: pointer; padding: 0;
+ border: 1px solid rgba(255,255,255,.16); position: relative; transition: transform .1s, box-shadow .12s;
+ }
+ .aw-swatch:hover { transform: translateY(-1px); }
+ .aw-swatch.selected { box-shadow: 0 0 0 2px var(--bg, #0a0a0a), 0 0 0 4px var(--accent, #fff); }
+ .aw-swatch-custom {
+ display: inline-flex; align-items: center; justify-content: center; overflow: hidden;
+ color: var(--text-2, #a1a1aa); font-size: 15px; font-weight: 600;
+ background: var(--panel-2, #161616); border-style: dashed;
+ }
+ .aw-swatch-custom input[type="color"] { position: absolute; inset: 0; opacity: 0; width: 100%; height: 100%; cursor: pointer; border: 0; padding: 0; }
+ `;
+ document.head.appendChild(style);
+}
+
+/* ── escapes ── */
+function escHtml(s) {
+ return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
+}
+function escAttr(s) { return escHtml(s); }
+function cssEscape(s) { return String(s).replace(/(["\\])/g, '\\$1'); }
diff --git a/src/face-quality.js b/src/face-quality.js
index bdf0532e6..ca284a924 100644
--- a/src/face-quality.js
+++ b/src/face-quality.js
@@ -21,11 +21,11 @@
*/
const TASKS_VISION_URL =
- 'https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/+esm';
+ 'https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/+esm';
const WASM_ROOT =
- 'https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/wasm';
+ 'https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/wasm';
const MODEL_URL =
- 'https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker.task';
+ 'https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task';
const BLUR_MIN = 3.5;
const LUMA_MIN = 40;
diff --git a/src/game/build-voxels.js b/src/game/build-voxels.js
index fda6bf19d..6fe74e144 100644
--- a/src/game/build-voxels.js
+++ b/src/game/build-voxels.js
@@ -176,6 +176,10 @@ export class VoxelWorld {
hasBlock(key) { return this.index.has(key); }
+ // Palette type at a cell, or -1 if empty. Lets a break record what it removed
+ // so undo can restore the exact block.
+ typeAt(gx, gy, gz) { const e = this.index.get(keyOf(gx, gy, gz)); return e ? e.type : -1; }
+
// Add or repaint a block. Idempotent for an unchanged (key,type).
setBlock(gx, gy, gz, type) {
if (type < 0 || type >= this.batches.length) return;
@@ -343,9 +347,31 @@ export function createBuildHud({ onToggle, onPick, onModeChange }) {
onclick: () => setMode(mode === 'place' ? 'remove' : 'place'),
}, [el('span', { class: 'cc-build-mode-ico', text: '▦' }), el('span', { class: 'cc-build-mode-text', text: 'Place' })]);
- const hint = el('div', { class: 'cc-build-hint', text: 'Tap to place · right-click to break · 1–0 pick block' });
+ // Touch has no right-click; long-press breaks, and the mode toggle is the
+ // explicit path. Tailor the hint so phone players aren't told to "right-click".
+ const touch = typeof matchMedia === 'function' && matchMedia('(hover: none), (pointer: coarse)').matches;
+ const hint = el('div', {
+ class: 'cc-build-hint',
+ text: touch
+ ? 'Tap to place · long-press to break · pick a block above'
+ : 'Click to place · right-click to break · 1–0 pick block',
+ });
- const panel = el('div', { class: 'cc-build-panel', hidden: true }, [modeBtn, hotbar, hint]);
+ // Live block-budget meter. The build is hard-capped per world (MAX_BLOCKS);
+ // without this the cap is a silent wall — a builder hits 6000 and blocks just
+ // stop appearing. The fill bar warms to amber, then red, as the world fills.
+ const budgetFill = el('span', { class: 'cc-build-budget-fill' });
+ const budgetText = el('span', { class: 'cc-build-budget-text', text: `0 / ${MAX_BLOCKS}` });
+ const budget = el('div', {
+ class: 'cc-build-budget', role: 'status', 'aria-label': 'Blocks used',
+ title: `Blocks placed in this world (max ${MAX_BLOCKS})`,
+ }, [el('span', { class: 'cc-build-budget-bar' }, [budgetFill]), budgetText]);
+
+ // Durability badge: tells builders, honestly, whether this world's creation is
+ // saved for keeps (Redis) or only for the life of the server process.
+ const durBadge = el('div', { class: 'cc-build-durability', role: 'status', hidden: true });
+
+ const panel = el('div', { class: 'cc-build-panel', hidden: true }, [modeBtn, hotbar, budget, durBadge, hint]);
const root = el('div', { id: 'cc-build', class: 'cc-build' }, [toggleBtn, panel]);
document.body.appendChild(root);
@@ -382,6 +408,29 @@ export function createBuildHud({ onToggle, onPick, onModeChange }) {
toggleBtn.title = enabled ? 'Build mode (B)' : (reason || 'Building needs a live connection');
if (!enabled && active) setActive(false);
},
+ // Reflect how full the world's block budget is. Warms the bar (amber ≥80%,
+ // red when full) and flags the panel so place actions can read "full".
+ setBudget(used, max = MAX_BLOCKS) {
+ const u = Math.max(0, Math.min(used | 0, max));
+ const pct = max > 0 ? u / max : 0;
+ budgetFill.style.transform = `scaleX(${pct})`;
+ budgetText.textContent = `${u.toLocaleString()} / ${max.toLocaleString()}`;
+ const full = u >= max;
+ budget.classList.toggle('cc-warn', pct >= 0.8 && !full);
+ budget.classList.toggle('cc-full', full);
+ root.classList.toggle('cc-build-full', full);
+ },
+ // Show whether this world's build survives a server restart. Online only —
+ // solo single-player builds aren't persisted at all (passing null hides it).
+ setPersistent(durable) {
+ if (durable == null) { durBadge.hidden = true; return; }
+ durBadge.hidden = false;
+ durBadge.classList.toggle('cc-durable', !!durable);
+ durBadge.textContent = durable ? '✓ Saved for everyone' : '⚠ This session only';
+ durBadge.title = durable
+ ? 'This world is saved to durable storage — your build is here when you return.'
+ : 'Durable storage is unavailable — this build lives only until the server restarts.';
+ },
dispose() { root.remove(); },
};
}
diff --git a/src/game/coincommunities-ui.js b/src/game/coincommunities-ui.js
index 838742193..56b337304 100644
--- a/src/game/coincommunities-ui.js
+++ b/src/game/coincommunities-ui.js
@@ -117,6 +117,7 @@ export class CommunityUI {
this.uploadStatus = el('div', { class: 'cc-upload-status', role: 'status', 'aria-live': 'polite', hidden: true });
this.lobby = el('div', { id: 'cc-lobby' }, [
+ this._buildSiteNav(),
el('div', { class: 'cc-lobby-inner' }, [
el('div', { class: 'cc-lobby-head' }, [
el('div', { class: 'cc-brand' }, [
@@ -147,14 +148,185 @@ export class CommunityUI {
el('p', { class: 'cc-section-title', text: 'Live communities' }),
this.grid,
]),
+ this._buildSiteFooter(),
]);
document.body.appendChild(this.lobby);
+ this._wireNav();
this._wireGlbDrop();
this._renderPresets();
this.setCoinsLoading();
}
+ // ---------------------------------------------------------- site chrome
+ // The platform-wide top nav + footer, so the lobby sits inside three.ws
+ // instead of feeling like an island. Mirrors the home page's navigation
+ // (Build / Discover / Embed / Learn / Labs) so links and ordering stay
+ // consistent across the site; styled with the lobby's own dark tokens.
+ _buildSiteNav() {
+ const THREE_MARK = '<svg viewBox="0 0 32 32" fill="currentColor" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M11.013 1.011a16 16 0 0 0-3.96 1.39C2.79 4.531.213 8.757.012 13.564c-.16 3.933 1.31 7.62 4.117 10.357l.736.715-.16.46c-.084.249-.13.504-.138.761 0 1.358 1.448 2.218 2.638 1.567.535-.292.879-.748 1.043-1.384.084-.331.092-.462.07-.882-.02-.43-.04-.535-.18-.83-.246-.52-.567-.86-1.087-1.153l-.297-.167.106-.32c.18-.543.79-1.717 1.181-2.276 1.91-2.729 5.066-4.395 8.4-4.434l.43-.005.012-1.19c.006-.654.024-1.19.04-1.19s.252.197.526.438c.71.624 2.296 1.95 2.785 2.328.23.178.41.34.4.36-.01.02-.214.156-.453.303-.926.57-2.265 1.65-3.13 2.524l-.27.273.012 1.064.013 1.064.32.027c1.327.114 2.598.685 3.578 1.607.21.198.39.343.4.323.04-.073.276-1.327.346-1.84.296-2.169-.094-4.317-1.129-6.16l-.19-.34.246-.45c.811-1.485 1.291-3.063 1.456-4.776.04-.42.046-.488.111-.488.111 0 1.327.715 1.94 1.143 2.953 2.057 4.96 5.241 5.579 8.856.21 1.22.234 1.585.234 3.063 0 1.485-.024 1.844-.234 3.064-.811 4.736-4.06 8.732-8.51 10.474-1.04.407-2.504.78-3.578.91l-.32.04v2.395l.41-.046c2.014-.226 4.222-.93 5.98-1.91 4.84-2.688 8.058-7.464 8.696-12.897.105-.892.105-3.063 0-3.956-.638-5.433-3.856-10.21-8.697-12.898C24.083.99 21.875.285 19.86.06 19.322 0 19.27 0 15.752.006c-3.346.006-4.234.02-4.74.105Z"/></svg>';
+
+ // [href, title, description, badge?] per menu item.
+ const GROUPS = [
+ ['Build', [
+ ['/create', 'Create agent', 'Avatar + brain wizard'],
+ ['/create/selfie', 'Selfie to avatar', 'One photo → rigged 3D avatar', 'New'],
+ ['/worlds', 'Worlds', 'Every coin is a 3D world — drop in & hang out', 'New'],
+ ['/app', 'Viewer', 'Drag-and-drop GLB'],
+ ['/playground', 'Playground', 'Viewer + environment + embed code'],
+ ['/voice', 'Voice Lab', 'Clone your voice · TTS playground', 'New'],
+ ]],
+ ['Discover', [
+ ['/features', 'Features', 'Everything an agent gets — interactive tour'],
+ ['/discover', 'ERC-8004 Agents', 'On-chain agent directory'],
+ ['/marketplace', 'Marketplace', 'Buy, sell & remix agents'],
+ ['/gallery', 'Avatar Gallery', 'Every public 3D avatar'],
+ ['/skills', 'Skills', 'Browse agent tool packs & capabilities', 'New'],
+ ['/bazaar', 'x402 Bazaar', 'Browse paid APIs and MCP tools'],
+ ['/community', 'Community', 'X, GitHub, and ways to get involved'],
+ ]],
+ ['Embed', [
+ ['/widgets', 'Widgets', 'Browse + customize embeddable widgets'],
+ ['/studio', 'Widget Studio', 'Pick avatar → copy snippet'],
+ ['/embed.html', 'Embed editor', 'Tune mode, size, position'],
+ ['/avatar-sdk', 'Avatar SDK', 'npm · web component · React · GLB upload', 'New'],
+ ['/docs#embedding', 'Embed docs', 'iframe + oEmbed'],
+ ]],
+ ['Learn', [
+ ['/docs', 'Docs', 'SDKs + API reference'],
+ ['/tutorials', 'Tutorials', 'Step-by-step guides'],
+ ['/brain', 'Brain', 'Claude · GPT · DeepSeek · Qwen · Llama', 'New'],
+ ['/chat', 'Chat', 'Talk to your agent'],
+ ['/pay', 'Pay', 'Agent payments — x402 + USDC', 'New'],
+ ]],
+ ['Labs', [
+ ['/launchpad', 'Launchpad Studio', 'Build a 3D launchpad · token · concierge', 'New'],
+ ['/mocap-studio', 'Mocap Studio', 'Record face → save clip → replay', 'New'],
+ ['/pose', 'Pose Studio', 'Click-to-pose mannequin + export PNG'],
+ ['/walk', 'Walk', 'Walk your avatar — multiplayer + AR', 'New'],
+ ['/xr', 'XR', 'Place your avatar in the real world', 'New'],
+ ['/three-live', '$THREE Live', 'Protocol pulse — live trades in 3D', 'New'],
+ ['/pump-visualizer', 'Pump Visualizer', '3D view of trending tokens'],
+ ['/club', 'Pole Club', 'x402 micro-tip demo — $0.001 / dance', 'New'],
+ ], true],
+ ];
+
+ const item = ([href, title, desc, badge]) => el('a', { class: 'cc-nav-mi', href, role: 'menuitem' }, [
+ el('span', { class: 'cc-nav-mi-t' }, [title, badge ? el('span', { class: 'cc-nav-pill', text: badge }) : null]),
+ el('span', { class: 'cc-nav-mi-d', text: desc }),
+ ]);
+
+ const group = ([label, items, wide]) => el('div', { class: 'cc-nav-grp' }, [
+ el('button', { type: 'button', class: 'cc-nav-trigger', 'aria-haspopup': 'true', 'aria-expanded': 'false' }, [
+ label,
+ el('span', { class: 'cc-nav-caret', 'aria-hidden': 'true', text: '▾' }),
+ ]),
+ el('div', { class: 'cc-nav-pop' + (wide ? ' cc-nav-wide' : ''), role: 'menu', 'aria-label': label }, items.map(item)),
+ ]);
+
+ // Mobile drawer mirrors the same destinations as a flat list.
+ const drawerSections = GROUPS.map(([label, items]) => [
+ el('div', { class: 'cc-dr-h', text: label }),
+ ...items.map(([href, title]) => el('a', { href, text: title })),
+ ]).flat();
+
+ this.navDrawer = el('nav', { class: 'cc-nav-drawer', id: 'cc-nav-drawer', 'aria-label': 'Mobile', 'aria-hidden': 'true' }, [
+ ...drawerSections,
+ el('div', { class: 'cc-dr-h', text: 'More' }),
+ el('a', { href: '/pricing', text: 'Pricing' }),
+ el('div', { class: 'cc-dr-sep' }),
+ el('a', { href: '/login', text: 'Sign in' }),
+ el('a', { class: 'cc-dr-console', href: '/dashboard', text: 'Console →' }),
+ ]);
+
+ this.navToggle = el('button', { class: 'cc-nav-toggle', id: 'cc-nav-toggle', 'aria-label': 'Menu', 'aria-expanded': 'false' }, [
+ el('span', { class: 'cc-nav-burger', 'aria-hidden': 'true', html: '<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"><line x1="2" y1="4" x2="14" y2="4"/><line x1="2" y1="8" x2="14" y2="8"/><line x1="2" y1="12" x2="14" y2="12"/></svg>' }),
+ el('span', { class: 'cc-nav-x', 'aria-hidden': 'true', html: '<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"><line x1="3" y1="3" x2="13" y2="13"/><line x1="13" y1="3" x2="3" y2="13"/></svg>' }),
+ ]);
+
+ return el('header', { class: 'cc-nav' }, [
+ el('div', { class: 'cc-nav-inner' }, [
+ el('a', { class: 'cc-nav-brand', href: '/', 'aria-label': 'three.ws home', html: THREE_MARK + '<span>three.ws</span>' }),
+ el('nav', { class: 'cc-nav-main', 'aria-label': 'Primary' }, [
+ ...GROUPS.map(group),
+ el('a', { class: 'cc-nav-flat', href: '/pricing', text: 'Pricing' }),
+ ]),
+ el('div', { class: 'cc-nav-end' }, [
+ el('a', { class: 'cc-nav-signin', href: '/login', text: 'Sign in' }),
+ el('a', { class: 'cc-nav-console', href: '/dashboard', text: 'Console →' }),
+ ]),
+ this.navToggle,
+ ]),
+ this.navDrawer,
+ ]);
+ }
+
+ _buildSiteFooter() {
+ const link = (href, text) => el('a', { href, text, ...(href.startsWith('http') ? { target: '_blank', rel: 'noopener' } : {}) });
+ return el('footer', { class: 'cc-foot' }, [
+ el('div', { class: 'cc-foot-inner' }, [
+ el('div', { class: 'cc-foot-copy', text: '© 2026 · three.ws · the 3D agent layer of the internet' }),
+ el('div', { class: 'cc-foot-links' }, [
+ link('/docs', 'Docs'),
+ link('/pricing', 'Pricing'),
+ link('/discover', 'Discover'),
+ link('/dashboard/api', 'API'),
+ link('https://github.com/nirholas/three.ws', 'GitHub'),
+ link('mailto:[email protected]', 'Contact'),
+ ]),
+ ]),
+ ]);
+ }
+
+ // Hover-to-open desktop dropdowns (click/keyboard for touch + a11y) plus the
+ // mobile drawer toggle. Mirrors the home page's nav behavior.
+ _wireNav() {
+ const groups = [...this.lobby.querySelectorAll('.cc-nav-main .cc-nav-grp')];
+ const hoverCapable = window.matchMedia('(hover: hover)').matches;
+ const setOpen = (grp, on) => {
+ grp.classList.toggle('cc-open', on);
+ grp.querySelector('.cc-nav-trigger')?.setAttribute('aria-expanded', on ? 'true' : 'false');
+ };
+ const closeAll = (except) => groups.forEach((g) => { if (g !== except) setOpen(g, false); });
+
+ groups.forEach((grp) => {
+ const trigger = grp.querySelector('.cc-nav-trigger');
+ if (!trigger) return;
+ let closeTimer;
+ trigger.addEventListener('click', (e) => {
+ e.stopPropagation();
+ if (hoverCapable) { closeAll(grp); setOpen(grp, true); return; }
+ const willOpen = !grp.classList.contains('cc-open');
+ closeAll(grp);
+ setOpen(grp, willOpen);
+ });
+ if (hoverCapable) {
+ grp.addEventListener('mouseenter', () => { clearTimeout(closeTimer); closeAll(grp); setOpen(grp, true); });
+ grp.addEventListener('mouseleave', () => { closeTimer = setTimeout(() => setOpen(grp, false), 120); });
+ }
+ grp.querySelectorAll('.cc-nav-mi').forEach((a) => a.addEventListener('click', () => setOpen(grp, false)));
+ });
+ document.addEventListener('click', (e) => { if (!e.target.closest('.cc-nav-main .cc-nav-grp')) closeAll(); });
+ document.addEventListener('keydown', (e) => {
+ if (e.key !== 'Escape') return;
+ const openGrp = this.lobby.querySelector('.cc-nav-main .cc-nav-grp.cc-open');
+ if (openGrp) { setOpen(openGrp, false); openGrp.querySelector('.cc-nav-trigger')?.focus(); }
+ });
+
+ // Mobile drawer
+ const toggle = this.navToggle, drawer = this.navDrawer;
+ const isOpen = () => drawer.classList.contains('cc-open');
+ const setDrawer = (open) => {
+ toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
+ drawer.setAttribute('aria-hidden', open ? 'false' : 'true');
+ drawer.classList.toggle('cc-open', open);
+ };
+ toggle.addEventListener('click', () => setDrawer(!isOpen()));
+ drawer.addEventListener('click', (e) => { if (e.target.closest('a')) setDrawer(false); });
+ document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && isOpen()) { setDrawer(false); toggle.focus(); } });
+ window.addEventListener('resize', () => { if (window.innerWidth > 880 && isOpen()) setDrawer(false); });
+ }
+
// Make the avatar bar a drop target for a local .glb. Only reacts to file
// drags so a stray text/element drag never lights it up.
_wireGlbDrop() {
diff --git a/src/game/coincommunities.css b/src/game/coincommunities.css
index 10b9bc54b..f25b27db8 100644
--- a/src/game/coincommunities.css
+++ b/src/game/coincommunities.css
@@ -138,7 +138,116 @@ html, body {
mask-image: radial-gradient(circle at 50% 30%, #000 0%, transparent 75%);
}
@keyframes cc-fade { from { opacity: 0; } }
-.cc-lobby-inner { position: relative; max-width: 1180px; margin: 0 auto; padding: 30px 22px 64px; }
+
+/* ---------------- site nav ---------------- */
+.cc-nav {
+ position: sticky; top: 0; z-index: 30;
+ background: rgba(6, 6, 7, 0.78); backdrop-filter: saturate(140%) blur(14px);
+ border-bottom: 1px solid var(--cc-edge-soft);
+}
+.cc-nav-inner {
+ display: flex; align-items: center; gap: 6px;
+ max-width: 1180px; margin: 0 auto; padding: 10px 22px;
+}
+.cc-nav-brand {
+ display: inline-flex; align-items: center; gap: 9px;
+ font-weight: 700; letter-spacing: 0.01em; color: var(--cc-text);
+ font-size: 15px; padding-right: 8px;
+}
+.cc-nav-brand svg { width: 20px; height: 20px; display: block; }
+.cc-nav-brand:hover { color: #fff; }
+.cc-nav-main { display: flex; align-items: center; gap: 2px; flex: 1; margin-left: 8px; }
+.cc-nav-flat, .cc-nav-trigger {
+ display: inline-flex; align-items: center; gap: 5px;
+ background: none; border: 0; cursor: pointer; font: inherit;
+ color: var(--cc-dim); font-size: 13.5px; font-weight: 500;
+ padding: 7px 11px; border-radius: var(--cc-radius-sm);
+ transition: color 0.15s ease, background 0.15s ease;
+}
+.cc-nav-flat:hover, .cc-nav-trigger:hover,
+.cc-nav-grp.cc-open .cc-nav-trigger { color: var(--cc-text); }
+.cc-nav-grp.cc-open .cc-nav-trigger { background: rgba(255, 255, 255, 0.05); }
+.cc-nav-caret { font-size: 9px; opacity: 0.55; transition: transform 0.2s ease; }
+.cc-nav-grp.cc-open .cc-nav-caret { transform: rotate(180deg); }
+.cc-nav-grp { position: relative; display: flex; }
+.cc-nav-pop {
+ position: absolute; top: calc(100% + 8px); left: 0; z-index: 40;
+ display: grid; gap: 2px; min-width: 290px; padding: 7px;
+ background: var(--cc-panel-solid); border: 1px solid var(--cc-edge);
+ border-radius: var(--cc-radius); box-shadow: var(--cc-shadow);
+ opacity: 0; transform: translateY(-6px); pointer-events: none;
+ transition: opacity 0.16s ease, transform 0.16s ease;
+}
+.cc-nav-pop.cc-nav-wide { grid-template-columns: 1fr 1fr; min-width: 540px; }
+.cc-nav-grp.cc-open .cc-nav-pop { opacity: 1; transform: translateY(0); pointer-events: auto; }
+.cc-nav-mi {
+ display: block; padding: 8px 10px; border-radius: var(--cc-radius-sm);
+ transition: background 0.13s ease;
+}
+.cc-nav-mi:hover { background: rgba(255, 255, 255, 0.05); }
+.cc-nav-mi-t { display: flex; align-items: center; gap: 7px; font-size: 13.5px; font-weight: 600; color: var(--cc-text); }
+.cc-nav-mi-d { display: block; font-size: 12px; color: var(--cc-dim); margin-top: 2px; }
+.cc-nav-pill {
+ font-size: 9px; font-weight: 700; letter-spacing: 0.06em; text-transform: uppercase;
+ color: var(--cc-ink); background: #fff; border-radius: 999px; padding: 1px 6px;
+}
+.cc-nav-end { display: flex; align-items: center; gap: 4px; }
+.cc-nav-signin {
+ color: var(--cc-dim); font-size: 13.5px; font-weight: 500; padding: 7px 12px;
+ border-radius: var(--cc-radius-sm); transition: color 0.15s ease;
+}
+.cc-nav-signin:hover { color: var(--cc-text); }
+.cc-nav-console {
+ color: var(--cc-ink); background: #fff; font-size: 13.5px; font-weight: 600;
+ padding: 7px 14px; border-radius: var(--cc-radius-sm);
+ box-shadow: var(--cc-glow); transition: transform 0.15s ease, opacity 0.15s ease;
+}
+.cc-nav-console:hover { transform: translateY(-1px); opacity: 0.92; }
+.cc-nav-toggle {
+ display: none; align-items: center; justify-content: center;
+ width: 38px; height: 34px; margin-left: auto;
+ background: none; border: 1px solid var(--cc-edge); border-radius: var(--cc-radius-sm);
+ color: var(--cc-text); cursor: pointer;
+}
+.cc-nav-toggle:hover { border-color: var(--cc-edge-hi); background: rgba(255, 255, 255, 0.04); }
+.cc-nav-toggle svg { width: 16px; height: 16px; display: block; }
+.cc-nav-x { display: none; }
+.cc-nav-toggle[aria-expanded="true"] .cc-nav-burger { display: none; }
+.cc-nav-toggle[aria-expanded="true"] .cc-nav-x { display: block; }
+.cc-nav-drawer {
+ display: none; flex-direction: column; gap: 1px;
+ padding: 14px 18px 22px; border-top: 1px solid var(--cc-edge-soft);
+ background: var(--cc-panel-solid);
+}
+.cc-nav-drawer.cc-open { display: flex; }
+.cc-dr-h {
+ font-size: 11px; font-weight: 700; letter-spacing: 0.12em; text-transform: uppercase;
+ color: var(--cc-faint); padding: 14px 0 6px;
+}
+.cc-dr-h:first-child { padding-top: 2px; }
+.cc-nav-drawer a {
+ color: var(--cc-dim); font-size: 14px; padding: 9px 10px; border-radius: var(--cc-radius-sm);
+}
+.cc-nav-drawer a:hover { background: rgba(255, 255, 255, 0.05); color: var(--cc-text); }
+.cc-dr-sep { height: 1px; background: var(--cc-edge-soft); margin: 12px 0; }
+.cc-dr-console { color: var(--cc-ink) !important; background: #fff; font-weight: 600; text-align: center; margin-top: 6px; }
+@media (max-width: 880px) {
+ .cc-nav-main, .cc-nav-end { display: none; }
+ .cc-nav-toggle { display: inline-flex; }
+}
+
+/* ---------------- site footer ---------------- */
+.cc-foot { position: relative; border-top: 1px solid var(--cc-edge-soft); margin-top: 24px; }
+.cc-foot-inner {
+ display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 16px;
+ max-width: 1180px; margin: 0 auto; padding: 28px 22px 40px;
+}
+.cc-foot-copy { color: var(--cc-faint); font-size: 12.5px; }
+.cc-foot-links { display: flex; flex-wrap: wrap; gap: 18px; }
+.cc-foot-links a { color: var(--cc-dim); font-size: 13px; transition: color 0.15s ease; }
+.cc-foot-links a:hover { color: var(--cc-text); }
+
+.cc-lobby-inner { position: relative; max-width: 1180px; margin: 0 auto; padding: 26px 22px 56px; }
.cc-lobby-head { display: flex; align-items: flex-end; gap: 16px; flex-wrap: wrap; margin-bottom: 20px; }
.cc-brand { display: flex; align-items: center; gap: 13px; }
.cc-brand-logo {
@@ -1216,6 +1325,59 @@ html, body {
letter-spacing: 0.01em;
}
+/* Block-budget meter — a thin fill bar plus an "N / 6000" readout. */
+.cc-build-budget {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 11px;
+ color: rgba(255, 255, 255, 0.62);
+ font-variant-numeric: tabular-nums;
+}
+.cc-build-budget-bar {
+ position: relative;
+ flex: 1;
+ height: 4px;
+ border-radius: 999px;
+ background: rgba(255, 255, 255, 0.12);
+ overflow: hidden;
+}
+.cc-build-budget-fill {
+ position: absolute;
+ inset: 0;
+ transform-origin: left center;
+ transform: scaleX(0);
+ border-radius: 999px;
+ background: #66ff8c;
+ transition:
+ transform 0.2s ease,
+ background 0.2s ease;
+}
+.cc-build-budget-text {
+ white-space: nowrap;
+}
+.cc-build-budget.cc-warn .cc-build-budget-fill {
+ background: #ffb648;
+}
+.cc-build-budget.cc-full .cc-build-budget-fill {
+ background: #ff5a5a;
+}
+.cc-build-budget.cc-full .cc-build-budget-text {
+ color: #ffb3b3;
+ font-weight: 600;
+}
+
+/* Durability badge — "Saved for everyone" vs "This session only". */
+.cc-build-durability {
+ font-size: 10.5px;
+ letter-spacing: 0.02em;
+ text-align: center;
+ color: #ffd28a;
+}
+.cc-build-durability.cc-durable {
+ color: #8fe9a8;
+}
+
@media (pointer: coarse) {
.cc-build-hint {
display: none;
diff --git a/src/game/coincommunities.js b/src/game/coincommunities.js
index 945cc85ef..5b039cd88 100644
--- a/src/game/coincommunities.js
+++ b/src/game/coincommunities.js
@@ -44,6 +44,8 @@ const JUMP_VELOCITY = 5.5; // m/s upward kick on Space; ~1m apex under GRAVITY
const GRAVITY = 15; // m/s^2 pulling the jumper back down
const REMOTE_LERP = 0.18;
const JOY_DEADZONE = 0.12; // swallow tiny stick grazes so the avatar doesn't drift
+const UNDO_LIMIT = 50; // how many build actions Ctrl/Cmd+Z can walk back
+const LONG_PRESS_MS = 420; // hold-to-break threshold for touch (no right-click there)
const TRENDING_URL = '/api/pump/trending?limit=30';
const SEARCH_URL = '/api/pump/search';
const COIN_URL = '/api/pump/coin';
@@ -652,12 +654,17 @@ export class CoinCommunities {
// Every (re)connect re-streams the server's authoritative build, so wipe
// the local layer first. On a manual retry out of single-player this also
// hands authority back: the solo build gives way to the shared world's.
- if (status === 'connecting') this.voxels?.clear();
+ if (status === 'connecting') { this.voxels?.clear(); this._undoStack = []; this._syncBudget(); }
// Building is available with a live server (synced + persisted for
// everyone) and in solo single-player mode (local-only) once multiplayer
// has been given up. The connecting window is the only time it's off, so
// the toggle never becomes a dead, silent button.
this.buildHud.setEnabled(this._buildableConnection(), 'Connecting to the world…');
+ // Durability badge: online reflects the server's persistent flag; solo
+ // single-player isn't saved at all, so hide it (null) to avoid a false
+ // promise. Re-sync the budget meter against whatever layer is now live.
+ this.buildHud.setPersistent(status === 'online' ? this.net?.persistent : (status === 'offline' ? false : null));
+ this._syncBudget();
// A reconnect reissues every sessionId, stranding the voice mesh — refresh
// our id, drop the stale peers, and re-announce so it re-forms.
if (status === 'online' && this.voice?.joined && this.net.sessionId !== this.voice.selfId) {
@@ -678,14 +685,32 @@ export class CoinCommunities {
this.net.on('remove', (id) => this._onRemove(id));
this.net.on('chat', (m) => this._onChat(m));
this.net.on('ping', (ms) => this.ui.setPing(ms));
- this.net.on('blockAdd', (key, t) => { const [x, y, z] = parseKey(key); this.voxels?.setBlock(x, y, z, t); });
+ this.net.on('blockAdd', (key, t) => { const [x, y, z] = parseKey(key); this.voxels?.setBlock(x, y, z, t); this._syncBudget(); });
this.net.on('blockChange', (key, t) => { const [x, y, z] = parseKey(key); this.voxels?.setBlock(x, y, z, t); });
- this.net.on('blockRemove', (key) => { const [x, y, z] = parseKey(key); this.voxels?.removeBlock(x, y, z); });
+ this.net.on('blockRemove', (key) => { const [x, y, z] = parseKey(key); this.voxels?.removeBlock(x, y, z); this._syncBudget(); });
+ this.net.on('editReject', ({ reason }) => this._onEditReject(reason));
+ // Durability flag for this world's build — drives the HUD "Saved" badge.
+ this.net.on('persistent', (durable) => { if (this.net?.status === 'online') this.buildHud.setPersistent(durable); });
this.buildHud.root.hidden = false;
await this.net.connect();
this._initVoice();
this.phase = 'world';
this._initJoystick();
+ this._onboardBuild();
+ }
+
+ // First-run nudge so players discover building exists — the HUD's ⛏ toggle is
+ // easy to miss. Shown once ever, a few seconds after the world settles so it
+ // doesn't collide with the entry toast.
+ _onboardBuild() {
+ try { if (localStorage.getItem('cc-build-onboarded')) return; } catch { return; }
+ clearTimeout(this._onboardTimer);
+ this._onboardTimer = setTimeout(() => {
+ if (this.phase !== 'world') return;
+ const touch = typeof matchMedia === 'function' && matchMedia('(hover: none), (pointer: coarse)').matches;
+ this.ui.toast(touch ? 'Tip: tap ⛏ to build this world together.' : 'Tip: press B (or tap ⛏) to build this world together.', 'info');
+ try { localStorage.setItem('cc-build-onboarded', '1'); } catch {}
+ }, 4200);
}
// Run the holder gate for a coin's Holders world. Drives the overlay through
@@ -808,8 +833,12 @@ export class CoinCommunities {
if (this._chartScreen) { this._chartScreen.dispose(); this._chartScreen = null; }
if (this._reactor) { this._reactor.dispose(); this._reactor = null; }
if (this.voxels) { this.voxels.dispose(); this.voxels = null; }
+ this._cancelLongPress();
+ clearTimeout(this._onboardTimer);
+ this._undoStack = []; // history is per-world; don't carry edits across coins
this.buildHud.setActive(false);
this.buildHud.setEnabled(false);
+ this.buildHud.setPersistent(null);
this.buildHud.root.hidden = true;
if (this.localRig) { this.scene.remove(this.localRig); this.localRig = null; }
if (this._nipple) { this._nipple.destroy(); this._nipple = null; }
@@ -912,6 +941,12 @@ export class CoinCommunities {
if (this._buildableConnection() || this.buildHud.active) this.buildHud.setActive(!this.buildHud.active);
return;
}
+ // Ctrl/Cmd+Z walks back the player's own recent build edits.
+ if (k === 'z' && (e.ctrlKey || e.metaKey) && this.buildHud.active) {
+ e.preventDefault();
+ this._undo();
+ return;
+ }
if (this.buildHud.active && k.length === 1 && k >= '0' && k <= '9') {
e.preventDefault();
this.buildHud.select(k === '0' ? 9 : Number(k) - 1);
@@ -924,16 +959,26 @@ export class CoinCommunities {
this.canvas.addEventListener('pointerdown', (e) => {
this._dragging = true; this._lastPtr = { x: e.clientX, y: e.clientY };
this._downPtr = { x: e.clientX, y: e.clientY };
+ this._longPressFired = false;
// Touch has no hover, so seed the ghost on press so the first tap aims true.
- if (this.phase === 'world' && this.buildHud.active && e.button !== 2) this._updateGhost(e.clientX, e.clientY);
+ if (this.phase === 'world' && this.buildHud.active && e.button !== 2) {
+ this._updateGhost(e.clientX, e.clientY);
+ // Touch has no right-click; a hold breaks the targeted block. Mouse keeps
+ // right-click / the mode toggle, but the hold works there too.
+ if (e.button !== 2) this._armLongPressBreak(e.clientX, e.clientY);
+ }
});
- window.addEventListener('pointerup', () => { this._dragging = false; });
+ window.addEventListener('pointerup', () => { this._dragging = false; this._cancelLongPress(); });
// A tap (negligible drag) builds in build mode, otherwise opens the coin on
// pump.fun when it lands on the live chart screen.
this.canvas.addEventListener('pointerup', (e) => {
+ this._cancelLongPress();
+ const consumed = this._longPressFired;
+ this._longPressFired = false;
if (!this._downPtr) return;
const moved = Math.hypot(e.clientX - this._downPtr.x, e.clientY - this._downPtr.y);
this._downPtr = null;
+ if (consumed) return; // a hold already broke a block — don't also place
if (moved >= 6 || e.button === 2) return; // a look-drag, or a right-click (handled by contextmenu)
if (this.phase === 'world' && this.buildHud.active) { this._buildAt(e.clientX, e.clientY, false); return; }
if (this._raycastScreen(e.clientX, e.clientY)) this._chartScreen.openExternal();
@@ -957,6 +1002,9 @@ export class CoinCommunities {
}
const dx = e.clientX - this._lastPtr.x, dy = e.clientY - this._lastPtr.y;
this._lastPtr = { x: e.clientX, y: e.clientY };
+ // A real drag is a look, not a hold — cancel the pending break so panning
+ // the camera in build mode never destroys a block.
+ if (this._downPtr && Math.hypot(e.clientX - this._downPtr.x, e.clientY - this._downPtr.y) >= 8) this._cancelLongPress();
this.camYaw -= dx * 0.005;
this.camPitch = Math.max(0.1, Math.min(1.2, this.camPitch + dy * 0.004));
});
@@ -1003,23 +1051,26 @@ export class CoinCommunities {
// — same result on screen, just not synced or persisted.
_buildAt(clientX, clientY, forceRemove) {
if (!this.voxels || this.phase !== 'world' || !this._buildableConnection()) return;
- const online = this.net?.status === 'online';
const target = this.voxels.raycast(this._pointerRay(clientX, clientY));
if (!target) return;
if (forceRemove || this.buildHud.mode === 'remove') {
if (target.hit === 'block' && target.cell) {
- if (online) this.net.sendRemove(target.cell[0], target.cell[1], target.cell[2]);
- else this.voxels.removeBlock(target.cell[0], target.cell[1], target.cell[2]);
+ // Capture the type before it's gone so undo can put it back exactly.
+ const prevType = this.voxels.typeAt(...target.cell);
+ if (this._applyEdit('remove', target.cell) && prevType >= 0) {
+ this._pushUndo({ kind: 'place', cell: target.cell.slice(), type: prevType });
+ }
}
} else if (target.placeValid) {
// The server enforces the build's block cap online; honour it locally too
// so a solo build can't outgrow what a shared one is allowed to be.
- if (!online && this.voxels.count >= MAX_BLOCKS) {
+ if (this.net?.status !== 'online' && this.voxels.count >= MAX_BLOCKS) {
this.ui.toast(`Build limit reached (${MAX_BLOCKS} blocks).`, 'warn');
return;
}
- if (online) this.net.sendPlace(target.placeCell[0], target.placeCell[1], target.placeCell[2], this.buildType);
- else this.voxels.setBlock(target.placeCell[0], target.placeCell[1], target.placeCell[2], this.buildType);
+ if (this._applyEdit('place', target.placeCell, this.buildType)) {
+ this._pushUndo({ kind: 'remove', cell: target.placeCell.slice() });
+ }
} else if (target.placeCell) {
// Aimed somewhere illegal (out of bounds / occupied) — flash the cursor.
this.voxels.showGhost(target.placeCell, 'blocked');
@@ -1028,6 +1079,84 @@ export class CoinCommunities {
this._updateGhost(clientX, clientY);
}
+ // Arm a hold-to-break timer for the current press. If the player keeps the
+ // pointer down and still (no drag) past LONG_PRESS_MS, break the targeted block
+ // — the touch-native equivalent of a right-click. Cancelled by movement or release.
+ _armLongPressBreak(clientX, clientY) {
+ this._cancelLongPress();
+ if (this.phase !== 'world' || !this.buildHud.active || !this._buildableConnection()) return;
+ this._longPressTimer = setTimeout(() => {
+ this._longPressTimer = null;
+ if (!this._downPtr) return;
+ this._longPressFired = true;
+ this._buildAt(clientX, clientY, true);
+ // A short haptic tick confirms the break on devices that support it.
+ if (typeof navigator !== 'undefined' && navigator.vibrate) navigator.vibrate(28);
+ }, LONG_PRESS_MS);
+ }
+
+ _cancelLongPress() {
+ if (this._longPressTimer) { clearTimeout(this._longPressTimer); this._longPressTimer = null; }
+ }
+
+ // Apply one edit to whichever layer is authoritative: online sends the intent
+ // (the block lands when the server echoes it); solo mutates the local layer
+ // directly. Returns true if the edit was issued, so undo history only records
+ // edits that actually happened.
+ _applyEdit(kind, cell, type) {
+ const online = this.net?.status === 'online';
+ if (kind === 'remove') {
+ if (online) this.net.sendRemove(cell[0], cell[1], cell[2]);
+ else { this.voxels.removeBlock(cell[0], cell[1], cell[2]); this._syncBudget(); }
+ } else {
+ if (online) this.net.sendPlace(cell[0], cell[1], cell[2], type);
+ else { this.voxels.setBlock(cell[0], cell[1], cell[2], type); this._syncBudget(); }
+ }
+ return true;
+ }
+
+ // Push an inverse action onto the bounded undo stack. Each entry is the edit
+ // that *reverses* what the player just did, so Ctrl/Cmd+Z replays it.
+ _pushUndo(action) {
+ (this._undoStack ||= []).push(action);
+ if (this._undoStack.length > UNDO_LIMIT) this._undoStack.shift();
+ }
+
+ // Reverse the player's most recent build action. Best-effort in a shared world:
+ // if a peer has since changed that cell, the inverse simply overrides or no-ops,
+ // which is the least-surprising outcome for a collaborative undo.
+ _undo() {
+ if (this.phase !== 'world' || !this.buildHud.active || !this._buildableConnection()) return;
+ const action = this._undoStack?.pop();
+ if (!action) { this.ui.toast('Nothing to undo.', 'info'); return; }
+ if (action.kind === 'place') this._applyEdit('place', action.cell, action.type);
+ else this._applyEdit('remove', action.cell);
+ this._refreshGhost();
+ }
+
+ // Keep the HUD's block-budget meter in step with the live build. voxels.count
+ // mirrors the server's authoritative block count (every block streams in), so
+ // this is accurate online and solo alike.
+ _syncBudget() {
+ this.buildHud?.setBudget(this.voxels?.count ?? 0, MAX_BLOCKS);
+ }
+
+ // Explain a server-refused edit so a block that never appeared isn't a mystery.
+ // Throttled to one toast per reason per window — a flood reply can't spam.
+ _onEditReject(reason) {
+ const now = performance.now();
+ this._rejectToastAt ||= {};
+ if (now - (this._rejectToastAt[reason] || 0) < 4000) return;
+ this._rejectToastAt[reason] = now;
+ const msg = {
+ budget: `Build limit reached (${MAX_BLOCKS} blocks) — break something to make room.`,
+ rate: 'Building too fast — slow down a moment.',
+ bounds: 'Can’t build there — outside the build area.',
+ type: 'That block type isn’t available.',
+ }[reason] || 'That edit couldn’t be applied.';
+ this.ui.toast(msg, 'warn');
+ }
+
// Move the ghost cursor to whatever the pointer aims at, tinted by intent
// (green place / red break / amber blocked).
_updateGhost(clientX, clientY) {
@@ -1049,13 +1178,13 @@ export class CoinCommunities {
_onBuildToggle(on) {
if (!on) { this.voxels?.hideGhost(); this.canvas.style.cursor = ''; return; }
+ const touch = typeof matchMedia === 'function' && matchMedia('(hover: none), (pointer: coarse)').matches;
const solo = this.net?.status !== 'online';
- this.ui.toast(
- solo
- ? 'Build mode (single-player) — tap to place, right-click to break, 1–0 pick a block'
- : 'Build mode — tap to place, right-click to break, 1–0 pick a block',
- 'info',
- );
+ const how = touch
+ ? 'tap to place, hold to break, pick a block, ⌘/Ctrl+Z to undo'
+ : 'click to place, right-click to break, 1–0 pick a block, ⌘/Ctrl+Z to undo';
+ this.ui.toast(`Build mode${solo ? ' (single-player)' : ''} — ${how}`, 'info');
+ this._syncBudget();
if (this._lastHover) this._updateGhost(this._lastHover.x, this._lastHover.y);
}
diff --git a/src/game/community-net.js b/src/game/community-net.js
index 74c537b90..930ff55bd 100644
--- a/src/game/community-net.js
+++ b/src/game/community-net.js
@@ -68,6 +68,7 @@ export class CommunityNet {
this.status = 'idle';
this.error = null;
this.sessionId = null;
+ this.persistent = false; // set true once the server says this world is Redis-backed
this._handlers = {
status: new Set(),
@@ -83,6 +84,8 @@ export class CommunityNet {
blockAdd: new Set(), // (key, type) — a voxel appeared (placed or restored)
blockChange: new Set(), // (key, type) — a voxel was repainted
blockRemove: new Set(), // (key) — a voxel was broken
+ editReject: new Set(), // ({reason}) — the server refused one of our edits
+ persistent: new Set(), // (bool) — whether this world's build is durably saved
};
this.ping = null; // smoothed RTT in ms, null until the first echo
this._pingSentAt = 0; // perf-clock stamp of the last move awaiting an echo
@@ -140,6 +143,9 @@ export class CommunityNet {
this.room.onMessage('chat', (msg) => this._emit('chat', msg));
this.room.onMessage('interact', (msg) => this._emit('interact', msg));
this.room.onMessage('voice-signal', (msg) => this._emit('voiceSignal', msg));
+ // The server replies here when it refuses one of our place/break edits
+ // (budget full, rate limited, …) so the HUD can explain the no-op.
+ this.room.onMessage('edit-reject', (msg) => this._emit('editReject', msg || {}));
const $ = getStateCallbacks(this.room);
$(this.room.state).players.onAdd((player, id) => {
@@ -171,6 +177,12 @@ export class CommunityNet {
});
$(this.room.state).blocks.onRemove((_b, key) => this._emit('blockRemove', key));
+ // Durability flag for this world's build (Redis-backed vs memory-only).
+ // Set once at room creation; listen so the HUD reflects it as soon as the
+ // first state patch lands and if it ever degrades mid-session.
+ this.persistent = !!this.room.state.persistent;
+ $(this.room.state).listen('persistent', (v) => { this.persistent = !!v; this._emit('persistent', !!v); });
+
this.room.onLeave((code) => {
this._setStatus('offline');
if (!this._destroyed && code !== 1000) this._scheduleReconnect();
diff --git a/src/pose-library.js b/src/pose-library.js
new file mode 100644
index 000000000..34dfc4ad8
--- /dev/null
+++ b/src/pose-library.js
@@ -0,0 +1,594 @@
+// Account integration for the Animation Studio: save the current animation to
+// the signed-in user's account, and a "My animations" library to reopen, edit,
+// rename, delete, and export saved clips.
+//
+// Talks to /api/animations/clips (Task 3 CRUD) and /api/animations/thumbnail.
+// The studio passes a small API surface (the timeline document, serialize, and
+// avatar helpers) so this module never reaches into the scene directly.
+
+import { Quaternion } from 'three';
+
+const SESSION_KEY = 'pose:pendingDoc';
+
+const el = (tag, attrs = {}, children = []) => {
+ const node = document.createElement(tag);
+ for (const [k, v] of Object.entries(attrs)) {
+ if (k === 'class') node.className = v;
+ else if (k === 'html') node.innerHTML = v;
+ else if (k === 'text') node.textContent = v;
+ else if (k.startsWith('on') && typeof v === 'function') node.addEventListener(k.slice(2), v);
+ else if (v !== false && v != null) node.setAttribute(k, v);
+ }
+ for (const c of [].concat(children)) {
+ if (c == null || c === false) continue;
+ node.appendChild(typeof c === 'string' ? document.createTextNode(c) : c);
+ }
+ return node;
+};
+
+async function apiFetch(url, opts = {}) {
+ const res = await fetch(url, { credentials: 'include', ...opts });
+ let body = null;
+ try { body = await res.json(); } catch {}
+ if (!res.ok) {
+ const msg = body?.error_description || body?.error || `request failed (${res.status})`;
+ const err = new Error(msg);
+ err.status = res.status;
+ throw err;
+ }
+ return body;
+}
+
+function fmtDuration(ms) {
+ const s = (Number(ms) || 0) / 1000;
+ return s >= 1 ? `${s.toFixed(s % 1 ? 1 : 0)}s` : `${Math.round(s * 1000)}ms`;
+}
+function fmtDate(iso) {
+ if (!iso) return '';
+ try {
+ return new Date(iso).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
+ } catch { return ''; }
+}
+
+export class PoseLibrary {
+ constructor(api) {
+ this.api = api;
+ this.user = undefined; // undefined = unknown, null = signed out, object = signed in
+ this.savedClip = null; // { id, slug, name, visibility } when editing a saved clip
+ this.tab = 'mine';
+ this.onSell = null; // Task 6 sets this to wire the Sell action
+ }
+
+ mount() {
+ const saveBtn = document.querySelector('#pose-save');
+ const libBtn = document.querySelector('#pose-library');
+ saveBtn?.addEventListener('click', () => this.openSaveDialog());
+ libBtn?.addEventListener('click', () => this.openLibrary());
+
+ // Ctrl/Cmd+S → save (don't trigger the browser's save-page dialog).
+ window.addEventListener('keydown', (ev) => {
+ if ((ev.ctrlKey || ev.metaKey) && (ev.key === 's' || ev.key === 'S')) {
+ ev.preventDefault();
+ this.openSaveDialog();
+ }
+ });
+
+ this._restorePending();
+ }
+
+ // ── Auth ────────────────────────────────────────────────────────────────
+ async getUser(force = false) {
+ if (this.user !== undefined && !force) return this.user;
+ try {
+ const body = await apiFetch('/api/auth/me');
+ this.user = body?.user || null;
+ } catch (err) {
+ this.user = err.status === 401 ? null : undefined;
+ }
+ return this.user;
+ }
+
+ // Preserve the in-progress document across a sign-in round-trip.
+ _restorePending() {
+ let pending;
+ try { pending = JSON.parse(sessionStorage.getItem(SESSION_KEY) || 'null'); } catch {}
+ if (!pending?.doc) return;
+ sessionStorage.removeItem(SESSION_KEY);
+ this.api.loadDocument(pending.doc);
+ this.api.setStatus('Restored your in-progress animation. Sign-in complete — saving…');
+ // Reopen the save dialog now that they're (hopefully) signed in.
+ this.getUser(true).then((user) => {
+ if (user) this.openSaveDialog();
+ else this.api.setStatus('Restored your work. Sign in to save it.', 'error');
+ });
+ }
+
+ promptSignIn() {
+ const overlay = this._overlay();
+ const card = el('div', { class: 'pl-dialog', role: 'dialog', 'aria-modal': 'true', 'aria-label': 'Sign in to save' }, [
+ el('h2', { class: 'pl-dialog-title' }, ['Sign in to save']),
+ el('p', { class: 'pl-dialog-sub' }, ['Saving an animation to your account requires an account. Your work is preserved — you’ll return right here after signing in.']),
+ el('div', { class: 'pl-dialog-actions' }, [
+ el('button', { class: 'pose-btn', type: 'button', onclick: () => overlay.remove() }, ['Cancel']),
+ el('button', {
+ class: 'pose-btn pose-btn-primary', type: 'button',
+ onclick: () => {
+ try {
+ sessionStorage.setItem(SESSION_KEY, JSON.stringify({ doc: this.api.getDocument(), openSave: true }));
+ sessionStorage.setItem('login_redirect', '/pose');
+ } catch {}
+ window.location.href = '/login?next=/pose';
+ },
+ }, ['Sign in →']),
+ ]),
+ ]);
+ overlay.appendChild(card);
+ document.body.appendChild(overlay);
+ }
+
+ // ── Save ──────────────────────────────────────────────────────────────────
+ async openSaveDialog() {
+ if (this.api.keyframeCount() === 0) {
+ this.api.setStatus('Add at least one keyframe before saving.', 'error');
+ return;
+ }
+ const user = await this.getUser();
+ if (!user) return this.promptSignIn();
+
+ const doc = this.api.getDocument();
+ const existing = this.savedClip;
+ const overlay = this._overlay();
+
+ const nameInput = el('input', { class: 'pl-input', id: 'pl-name', type: 'text', maxlength: '120', value: existing?.name || doc.name || 'My animation', 'aria-label': 'Animation name', required: true });
+ const descInput = el('textarea', { class: 'pl-input pl-textarea', id: 'pl-desc', maxlength: '2000', rows: '2', placeholder: 'Optional description', 'aria-label': 'Description' }, [existing?.description || '']);
+ const tagsInput = el('input', { class: 'pl-input', id: 'pl-tags', type: 'text', placeholder: 'walk, loop, dance (comma-separated)', value: (existing?.tags || []).join(', '), 'aria-label': 'Tags' });
+ const visSelect = el('select', { class: 'pl-input', id: 'pl-vis', 'aria-label': 'Visibility' }, [
+ el('option', { value: 'private' }, ['Private — only you']),
+ el('option', { value: 'unlisted' }, ['Unlisted — anyone with the link']),
+ el('option', { value: 'public' }, ['Public — listed in the gallery']),
+ ]);
+ visSelect.value = existing?.visibility || 'private';
+
+ const avatarId = this.api.currentAvatarId();
+ const avatarName = this.api.currentAvatarName();
+ const linkLabel = avatarId ? `Linked to: ${avatarName || 'loaded avatar'}` : 'Authored on the mannequin (no avatar link)';
+
+ const errLine = el('div', { class: 'pl-dialog-err', role: 'alert', hidden: true });
+ const primaryLabel = existing ? 'Update' : 'Save';
+ const primaryBtn = el('button', { class: 'pose-btn pose-btn-primary', type: 'submit' }, [primaryLabel]);
+ const copyBtn = existing ? el('button', { class: 'pose-btn', type: 'button' }, ['Save as copy']) : null;
+
+ const form = el('form', { class: 'pl-dialog', role: 'dialog', 'aria-modal': 'true', 'aria-label': 'Save animation' }, [
+ el('h2', { class: 'pl-dialog-title' }, [existing ? 'Update animation' : 'Save animation']),
+ el('label', { class: 'pl-field' }, [el('span', {}, ['Name']), nameInput]),
+ el('label', { class: 'pl-field' }, [el('span', {}, ['Description']), descInput]),
+ el('label', { class: 'pl-field' }, [el('span', {}, ['Tags']), tagsInput]),
+ el('label', { class: 'pl-field' }, [el('span', {}, ['Visibility']), visSelect]),
+ el('p', { class: 'pl-link-note' }, [linkLabel]),
+ errLine,
+ el('div', { class: 'pl-dialog-actions' }, [
+ el('button', { class: 'pose-btn', type: 'button', onclick: () => overlay.remove() }, ['Cancel']),
+ copyBtn,
+ primaryBtn,
+ ]),
+ ]);
+
+ const submit = async (asCopy) => {
+ const name = nameInput.value.trim();
+ if (!name) { errLine.hidden = false; errLine.textContent = 'Name is required.'; nameInput.focus(); return; }
+ const busyBtn = asCopy ? copyBtn : primaryBtn;
+ const original = busyBtn.textContent;
+ busyBtn.disabled = true;
+ if (copyBtn) copyBtn.disabled = true;
+ primaryBtn.disabled = true;
+ busyBtn.textContent = 'Saving…';
+ errLine.hidden = true;
+ try {
+ const meta = {
+ name,
+ description: descInput.value.trim() || undefined,
+ tags: tagsInput.value.split(',').map((t) => t.trim()).filter(Boolean).slice(0, 20),
+ visibility: visSelect.value,
+ avatar_id: avatarId || undefined,
+ };
+ const saved = await this._persist(meta, { asCopy });
+ overlay.remove();
+ this.api.setStatus(`Saved “${saved.name}” to your account.`);
+ } catch (err) {
+ errLine.hidden = false;
+ errLine.textContent = err.message;
+ busyBtn.disabled = false;
+ if (copyBtn) copyBtn.disabled = false;
+ primaryBtn.disabled = false;
+ busyBtn.textContent = original;
+ }
+ };
+ form.addEventListener('submit', (ev) => { ev.preventDefault(); submit(false); });
+ copyBtn?.addEventListener('click', () => submit(true));
+
+ overlay.appendChild(form);
+ document.body.appendChild(overlay);
+ nameInput.focus();
+ nameInput.select();
+ }
+
+ // Create or update the clip row, then upload the thumbnail. Returns the saved row.
+ async _persist(meta, { asCopy } = {}) {
+ const clip = this.api.serializeClip();
+ const editor_doc = this.api.getDocument();
+ const fps = editor_doc.fps;
+ const loop = editor_doc.loop;
+ const updating = this.savedClip && !asCopy;
+
+ let saved;
+ if (updating) {
+ const body = await apiFetch(`/api/animations/clips/${this.savedClip.id}`, {
+ method: 'PATCH',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ ...meta, loop, clip, editor_doc }),
+ });
+ saved = body.clip;
+ } else {
+ const body = await apiFetch('/api/animations/clips', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ ...meta, fps, loop, clip, editor_doc }),
+ });
+ saved = body.clip;
+ }
+
+ this.savedClip = {
+ id: saved.id, slug: saved.slug, name: saved.name,
+ description: meta.description || '', tags: meta.tags || [], visibility: meta.visibility,
+ };
+ this._reflectSavedState();
+
+ // Best-effort thumbnail upload — a save shouldn't fail if the poster does.
+ try {
+ const png = this.api.captureThumbnail();
+ if (png) {
+ await apiFetch('/api/animations/thumbnail', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ id: saved.id, png_base64: png }),
+ });
+ }
+ } catch (err) {
+ console.warn('[pose-library] thumbnail upload failed:', err.message);
+ }
+ return saved;
+ }
+
+ _reflectSavedState() {
+ const saveBtn = document.querySelector('#pose-save');
+ if (saveBtn && this.savedClip) {
+ saveBtn.textContent = 'Update';
+ saveBtn.title = `Update “${this.savedClip.name}” (Ctrl/Cmd+S)`;
+ }
+ }
+
+ // ── Library drawer ────────────────────────────────────────────────────────
+ async openLibrary() {
+ const overlay = this._overlay('pl-drawer-overlay');
+ const list = el('div', { class: 'pl-grid', id: 'pl-grid' });
+ const tabMine = el('button', { class: 'pl-tab', type: 'button', 'aria-selected': 'true' }, ['My animations']);
+ const tabPublic = el('button', { class: 'pl-tab', type: 'button', 'aria-selected': 'false' }, ['Community']);
+
+ const drawer = el('aside', { class: 'pl-drawer', role: 'dialog', 'aria-modal': 'true', 'aria-label': 'Animation library' }, [
+ el('header', { class: 'pl-drawer-head' }, [
+ el('div', { class: 'pl-tabs', role: 'tablist' }, [tabMine, tabPublic]),
+ el('button', { class: 'pl-close', type: 'button', 'aria-label': 'Close library', onclick: () => overlay.remove() }, ['✕']),
+ ]),
+ list,
+ ]);
+
+ const select = (tab) => {
+ this.tab = tab;
+ tabMine.setAttribute('aria-selected', String(tab === 'mine'));
+ tabPublic.setAttribute('aria-selected', String(tab === 'public'));
+ this._loadList(list, tab);
+ };
+ tabMine.addEventListener('click', () => select('mine'));
+ tabPublic.addEventListener('click', () => select('public'));
+
+ overlay.appendChild(drawer);
+ document.body.appendChild(overlay);
+ requestAnimationFrame(() => drawer.classList.add('pl-open'));
+ select('mine');
+ }
+
+ async _loadList(list, tab) {
+ list.innerHTML = '';
+ for (let i = 0; i < 4; i++) list.appendChild(el('div', { class: 'pl-card pl-skeleton' }));
+
+ const url = tab === 'public'
+ ? '/api/animations/clips?include_public=true&visibility=public&limit=60'
+ : '/api/animations/clips?limit=60';
+ let items;
+ try {
+ if (tab === 'mine') {
+ const user = await this.getUser();
+ if (!user) {
+ list.innerHTML = '';
+ list.appendChild(this._emptyState(
+ 'Sign in to see your animations',
+ 'Your saved animations live in your account.',
+ el('a', { class: 'pose-btn pose-btn-primary', href: '/login?next=/pose' }, ['Sign in']),
+ ));
+ return;
+ }
+ }
+ const body = await apiFetch(url);
+ items = body.items || [];
+ } catch (err) {
+ list.innerHTML = '';
+ list.appendChild(this._emptyState(
+ 'Could not load animations',
+ err.message,
+ el('button', { class: 'pose-btn', type: 'button', onclick: () => this._loadList(list, tab) }, ['Retry']),
+ ));
+ return;
+ }
+
+ list.innerHTML = '';
+ if (!items.length) {
+ list.appendChild(tab === 'mine'
+ ? this._emptyState('No animations yet', 'Pose the figure, drop keyframes, then press Save to keep your work here.', null)
+ : this._emptyState('No public animations yet', 'Be the first — set an animation to Public when you save it.', null));
+ return;
+ }
+ for (const clip of items) list.appendChild(this._card(clip, tab));
+ }
+
+ _card(clip, tab) {
+ const thumb = clip.thumbnail_url
+ ? el('img', { class: 'pl-card-thumb', src: clip.thumbnail_url, alt: '', loading: 'lazy' })
+ : el('div', { class: 'pl-card-thumb pl-card-thumb-empty' }, ['◷']);
+
+ const badges = el('div', { class: 'pl-card-badges' }, [
+ el('span', { class: `pl-badge pl-badge-${clip.visibility}` }, [clip.visibility]),
+ clip.price ? el('span', { class: 'pl-badge pl-badge-price' }, [`${clip.price.amount} ${clip.price.currency || 'USDC'}`]) : null,
+ ]);
+
+ const actions = el('div', { class: 'pl-card-actions' }, [
+ el('button', { class: 'pose-btn', type: 'button', onclick: () => this._open(clip) }, ['Open']),
+ tab === 'mine' ? el('button', { class: 'pose-btn', type: 'button', onclick: (e) => this._editMeta(clip, e) }, ['Edit']) : null,
+ el('button', { class: 'pose-btn', type: 'button', onclick: () => this._export(clip) }, ['Export']),
+ tab === 'mine' && this.onSell ? el('button', { class: 'pose-btn', type: 'button', onclick: () => this.onSell(clip) }, [clip.listed ? 'Manage sale' : 'Sell']) : null,
+ tab === 'mine' ? el('button', { class: 'pose-btn pl-danger', type: 'button', onclick: (e) => this._delete(clip, e) }, ['Delete']) : null,
+ ]);
+
+ return el('div', { class: 'pl-card', 'data-id': clip.id }, [
+ thumb,
+ badges,
+ el('div', { class: 'pl-card-name' }, [clip.name]),
+ el('div', { class: 'pl-card-meta' }, [
+ `${fmtDuration(clip.duration_ms)} · ${clip.frame_count || 0} keys`,
+ tab === 'public' && clip.owner === 'other' ? ' · community' : '',
+ clip.updated_at ? ` · ${fmtDate(clip.updated_at)}` : '',
+ ]),
+ (clip.tags?.length ? el('div', { class: 'pl-card-tags' }, clip.tags.slice(0, 4).map((t) => el('span', { class: 'pl-tag' }, [t]))) : null),
+ actions,
+ ]);
+ }
+
+ _emptyState(title, sub, action) {
+ return el('div', { class: 'pl-empty' }, [
+ el('div', { class: 'pl-empty-icon', 'aria-hidden': 'true' }, ['🎬']),
+ el('h3', {}, [title]),
+ el('p', {}, [sub]),
+ action,
+ ]);
+ }
+
+ // ── Card actions ────────────────────────────────────────────────────────
+ async _open(clip) {
+ this.api.setStatus(`Opening “${clip.name}”…`);
+ let full;
+ try {
+ const body = await apiFetch(`/api/animations/clips/${clip.id}`);
+ full = body.clip;
+ } catch (err) {
+ this.api.setStatus(`Could not open: ${err.message}`, 'error');
+ return;
+ }
+
+ // Load the linked avatar first (so the document applies onto the right rig).
+ if (full.avatar_id) {
+ try { await this.api.loadAvatarById(full.avatar_id); }
+ catch { this.api.switchToMannequin(); this.api.setStatus('Linked avatar unavailable — opened on the mannequin.', 'error'); }
+ } else {
+ this.api.switchToMannequin();
+ }
+
+ const doc = full.editor_doc || reconstructDocFromClip(full.clip, full);
+ if (!doc) { this.api.setStatus('This animation has no editable data.', 'error'); return; }
+ this.api.loadDocument(doc);
+
+ this.savedClip = {
+ id: full.id, slug: full.slug, name: full.name,
+ description: full.description || '', tags: full.tags || [], visibility: full.visibility,
+ };
+ this._reflectSavedState();
+ document.querySelector('.pl-drawer-overlay')?.remove();
+ this.api.setStatus(`Opened “${full.name}” — ${full.editor_doc ? 'keyframes restored' : 'rebuilt from clip'}.`);
+ }
+
+ _editMeta(clip, ev) {
+ const overlay = this._overlay();
+ const nameInput = el('input', { class: 'pl-input', type: 'text', maxlength: '120', value: clip.name, 'aria-label': 'Name' });
+ const descInput = el('textarea', { class: 'pl-input pl-textarea', maxlength: '2000', rows: '2', 'aria-label': 'Description' }, [clip.description || '']);
+ const tagsInput = el('input', { class: 'pl-input', type: 'text', value: (clip.tags || []).join(', '), 'aria-label': 'Tags' });
+ const visSelect = el('select', { class: 'pl-input', 'aria-label': 'Visibility' }, [
+ el('option', { value: 'private' }, ['Private']),
+ el('option', { value: 'unlisted' }, ['Unlisted']),
+ el('option', { value: 'public' }, ['Public']),
+ ]);
+ visSelect.value = clip.visibility;
+ const err = el('div', { class: 'pl-dialog-err', role: 'alert', hidden: true });
+ const saveBtn = el('button', { class: 'pose-btn pose-btn-primary', type: 'submit' }, ['Save changes']);
+
+ const form = el('form', { class: 'pl-dialog', role: 'dialog', 'aria-modal': 'true', 'aria-label': 'Edit animation' }, [
+ el('h2', { class: 'pl-dialog-title' }, ['Edit details']),
+ el('label', { class: 'pl-field' }, [el('span', {}, ['Name']), nameInput]),
+ el('label', { class: 'pl-field' }, [el('span', {}, ['Description']), descInput]),
+ el('label', { class: 'pl-field' }, [el('span', {}, ['Tags']), tagsInput]),
+ el('label', { class: 'pl-field' }, [el('span', {}, ['Visibility']), visSelect]),
+ err,
+ el('div', { class: 'pl-dialog-actions' }, [
+ el('button', { class: 'pose-btn', type: 'button', onclick: () => overlay.remove() }, ['Cancel']),
+ saveBtn,
+ ]),
+ ]);
+ form.addEventListener('submit', async (e) => {
+ e.preventDefault();
+ saveBtn.disabled = true; saveBtn.textContent = 'Saving…'; err.hidden = true;
+ try {
+ const body = await apiFetch(`/api/animations/clips/${clip.id}`, {
+ method: 'PATCH',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ name: nameInput.value.trim(),
+ description: descInput.value.trim() || undefined,
+ tags: tagsInput.value.split(',').map((t) => t.trim()).filter(Boolean).slice(0, 20),
+ visibility: visSelect.value,
+ }),
+ });
+ Object.assign(clip, {
+ name: body.clip.name, description: body.clip.description,
+ tags: body.clip.tags, visibility: body.clip.visibility,
+ });
+ if (this.savedClip?.id === clip.id) this.savedClip.name = body.clip.name;
+ overlay.remove();
+ // Refresh the visible card in place.
+ const card = document.querySelector(`.pl-card[data-id="${clip.id}"]`);
+ if (card) card.replaceWith(this._card(clip, this.tab));
+ this.api.setStatus('Animation details updated.');
+ } catch (e2) {
+ err.hidden = false; err.textContent = e2.message;
+ saveBtn.disabled = false; saveBtn.textContent = 'Save changes';
+ }
+ });
+ overlay.appendChild(form);
+ document.body.appendChild(overlay);
+ nameInput.focus();
+ }
+
+ _delete(clip, ev) {
+ const overlay = this._overlay();
+ const delBtn = el('button', { class: 'pose-btn pl-danger', type: 'button' }, ['Delete']);
+ const card = el('div', { class: 'pl-dialog', role: 'dialog', 'aria-modal': 'true', 'aria-label': 'Delete animation' }, [
+ el('h2', { class: 'pl-dialog-title' }, ['Delete this animation?']),
+ el('p', { class: 'pl-dialog-sub' }, [`“${clip.name}” will be removed from your library. This cannot be undone.`]),
+ el('div', { class: 'pl-dialog-actions' }, [
+ el('button', { class: 'pose-btn', type: 'button', onclick: () => overlay.remove() }, ['Cancel']),
+ delBtn,
+ ]),
+ ]);
+ delBtn.addEventListener('click', async () => {
+ delBtn.disabled = true; delBtn.textContent = 'Deleting…';
+ try {
+ await apiFetch(`/api/animations/clips/${clip.id}`, { method: 'DELETE' });
+ overlay.remove();
+ document.querySelector(`.pl-card[data-id="${clip.id}"]`)?.remove();
+ if (this.savedClip?.id === clip.id) { this.savedClip = null; this._resetSaveBtn(); }
+ this.api.setStatus('Animation deleted.');
+ } catch (err) {
+ delBtn.disabled = false; delBtn.textContent = 'Delete';
+ this.api.setStatus(`Delete failed: ${err.message}`, 'error');
+ }
+ });
+ overlay.appendChild(card);
+ document.body.appendChild(overlay);
+ }
+
+ async _export(clip) {
+ try {
+ let clipJson;
+ if (this.savedClip?.id === clip.id) {
+ clipJson = this.api.serializeClip();
+ } else {
+ const body = await apiFetch(`/api/animations/clips/${clip.id}`);
+ clipJson = body.clip.clip;
+ }
+ const blob = new Blob([JSON.stringify(clipJson, null, 2)], { type: 'application/json' });
+ const url = URL.createObjectURL(blob);
+ const a = el('a', { href: url, download: `${clip.slug || 'animation'}.json` });
+ document.body.appendChild(a); a.click(); a.remove();
+ setTimeout(() => URL.revokeObjectURL(url), 1500);
+ this.api.setStatus('Clip JSON downloaded.');
+ } catch (err) {
+ this.api.setStatus(`Export failed: ${err.message}`, 'error');
+ }
+ }
+
+ _resetSaveBtn() {
+ const saveBtn = document.querySelector('#pose-save');
+ if (saveBtn) { saveBtn.textContent = 'Save'; saveBtn.title = 'Save this animation to your account (Ctrl/Cmd+S)'; }
+ }
+
+ // ── Overlay helper ────────────────────────────────────────────────────────
+ _overlay(extraClass = '') {
+ const overlay = el('div', { class: `pl-overlay ${extraClass}`.trim() });
+ overlay.addEventListener('pointerdown', (ev) => { if (ev.target === overlay) overlay.remove(); });
+ overlay.addEventListener('keydown', (ev) => { if (ev.key === 'Escape') overlay.remove(); });
+ return overlay;
+ }
+}
+
+// Rebuild an editable keyframe document from a baked AnimationClip.toJSON() when
+// no editor_doc was stored (e.g. an imported clip). Samples each quaternion
+// track at the union of all track keyframe times.
+const _q = new Quaternion();
+function reconstructDocFromClip(clipJson, meta = {}) {
+ if (!clipJson || !Array.isArray(clipJson.tracks)) return null;
+ const quatTracks = clipJson.tracks.filter((t) => t.name.endsWith('.quaternion'));
+ const posTrack = clipJson.tracks.find((t) => t.name.endsWith('.position'));
+ if (!quatTracks.length) return null;
+
+ const timeSet = new Set();
+ for (const t of clipJson.tracks) for (const v of t.times || []) timeSet.add(Number(v.toFixed(4)));
+ let times = [...timeSet].sort((a, b) => a - b);
+ if (times.length > 240) {
+ // Downsample to keep the editing doc manageable.
+ const step = Math.ceil(times.length / 240);
+ times = times.filter((_, i) => i % step === 0);
+ }
+ if (!times.length) times = [0];
+
+ const sampleQuat = (track, t) => {
+ const ts = track.times, vs = track.values;
+ if (!ts?.length) return [0, 0, 0, 1];
+ let i = ts.findIndex((x) => x >= t);
+ if (i < 0) i = ts.length - 1;
+ const j = Math.max(0, i - 1);
+ const o = i * 4, p = j * 4;
+ if (i === j || ts[i] === ts[j]) return [vs[o], vs[o + 1], vs[o + 2], vs[o + 3]];
+ const a = (t - ts[j]) / (ts[i] - ts[j]);
+ _q.set(vs[p], vs[p + 1], vs[p + 2], vs[p + 3]).slerp(new Quaternion(vs[o], vs[o + 1], vs[o + 2], vs[o + 3]), a);
+ return [_q.x, _q.y, _q.z, _q.w];
+ };
+ const samplePos = (t) => {
+ if (!posTrack?.times?.length) return { x: 0, y: 0, z: 0 };
+ let i = posTrack.times.findIndex((x) => x >= t);
+ if (i < 0) i = posTrack.times.length - 1;
+ const o = i * 3;
+ return { x: posTrack.values[o] || 0, y: posTrack.values[o + 1] || 0, z: posTrack.values[o + 2] || 0 };
+ };
+
+ const keyframes = times.map((t, i) => {
+ const bones = {};
+ for (const track of quatTracks) bones[track.name.replace('.quaternion', '')] = sampleQuat(track, t);
+ return { id: `kf_rebuilt_${i}`, time: t, easing: 'linear', pose: { bones, rootPosition: samplePos(t) } };
+ });
+
+ return {
+ name: clipJson.name || meta.name || 'animation',
+ duration: clipJson.duration || times[times.length - 1] || 1,
+ fps: meta.fps || 30,
+ loop: meta.loop !== false,
+ keyframes,
+ };
+}
+
+export const __test__ = { reconstructDocFromClip, fmtDuration };
diff --git a/src/pose-studio.js b/src/pose-studio.js
index 81f07302e..17b1f6247 100644
--- a/src/pose-studio.js
+++ b/src/pose-studio.js
@@ -54,8 +54,10 @@ import {
sampleAtTime,
bakeClip,
serializeClip,
+ EASINGS,
DEFAULT_EASING,
} from './pose-animation.js';
+import { PoseLibrary } from './pose-library.js';
// ─── DOM helpers ────────────────────────────────────────────────────────
const $ = (sel) => document.querySelector(sel);
@@ -1229,15 +1231,84 @@ function boot() {
renderKeyframes();
setPlayhead(0);
+ // Snapshot the editing document (deep clone) for saving.
+ function getDocument() {
+ return {
+ name: doc.name,
+ duration: doc.duration,
+ fps: doc.fps,
+ loop: doc.loop,
+ keyframes: doc.keyframes.map((k) => ({
+ id: k.id,
+ time: k.time,
+ easing: k.easing,
+ pose: {
+ bones: { ...k.pose.bones },
+ rootPosition: { ...(k.pose.rootPosition || { x: 0, y: 0, z: 0 }) },
+ },
+ })),
+ };
+ }
+
+ // Replace the editing document (reopening a saved clip). Rebuilds the
+ // timeline and applies the first frame so the rig reflects the animation.
+ function loadDocument(nd) {
+ if (!nd) return;
+ pause();
+ doc.name = nd.name || 'animation';
+ doc.duration = clamp(Number(nd.duration) || 4, 0.25, 120);
+ doc.fps = Math.round(clamp(Number(nd.fps) || 30, 1, 240));
+ doc.loop = nd.loop !== false;
+ doc.keyframes = (nd.keyframes || [])
+ .map((k, i) => ({
+ id: typeof k.id === 'string' && k.id ? k.id : `kf_load_${i}`,
+ time: clamp(Number(k.time) || 0, 0, doc.duration),
+ easing: EASINGS[k.easing] ? k.easing : DEFAULT_EASING,
+ pose:
+ k.pose && k.pose.bones
+ ? { bones: { ...k.pose.bones }, rootPosition: k.pose.rootPosition || { x: 0, y: 0, z: 0 } }
+ : { bones: {} },
+ }))
+ .sort((a, b) => a.time - b.time);
+ anim.selectedId = null;
+ tl.name.value = doc.name;
+ tl.duration.value = String(doc.duration);
+ tl.fps.value = String(doc.fps);
+ tl.loop.setAttribute('aria-pressed', String(doc.loop));
+ tl.track.setAttribute('aria-valuemax', String(doc.duration));
+ renderRuler();
+ renderKeyframes();
+ setPlayhead(0, { render: true });
+ }
+
return {
update: advance,
onRigChanged: () => { if (doc.keyframes.length) applyPreview(); },
bake: () => bakeClip(doc, { resolveBoneName: (k) => k, rootName: 'Hips' }),
serialize: () => serializeClip(doc, { resolveBoneName: (k) => k, rootName: 'Hips' }),
captureThumbnail: () => { renderer.render(scene, camera); return renderer.domElement.toDataURL('image/png'); },
+ getDocument,
+ loadDocument,
+ keyframeCount: () => doc.keyframes.length,
};
}
+ // ── Account: save + "My animations" library ──────────────────────────────
+ const library = new PoseLibrary({
+ getDocument: () => timeline.getDocument(),
+ loadDocument: (d) => timeline.loadDocument(d),
+ serializeClip: () => timeline.serialize(),
+ captureThumbnail: () => timeline.captureThumbnail(),
+ keyframeCount: () => timeline.keyframeCount(),
+ currentAvatarId: () => state.avatar?.id || null,
+ currentAvatarName: () => state.avatar?.name || null,
+ loadAvatarById: (id) => loadAvatarById(id),
+ switchToMannequin: () => switchToMannequin(),
+ setStatus: (m, k) => setStatus(m, k),
+ });
+ state.library = library;
+ library.mount();
+
// ── Boot: honor ?avatar= ─────────────────────────────────────────────────
const requestedAvatar = new URL(window.location.href).searchParams.get('avatar');
if (requestedAvatar) {
diff --git a/src/selfie-pipeline.js b/src/selfie-pipeline.js
index 286647c4d..6f1843361 100644
--- a/src/selfie-pipeline.js
+++ b/src/selfie-pipeline.js
@@ -75,6 +75,10 @@ document.addEventListener('selfie:submit', (event) => {
}
}).catch((err) => {
console.error('[selfie-pipeline] resume failed:', err);
+ if (err?.redirect) {
+ window.location.assign(err.redirect);
+ return;
+ }
document.dispatchEvent(new CustomEvent('selfie:build-error', {
detail: { message: err.userMessage || 'Could not resume. Try again.', slot: null },
}));
@@ -251,6 +255,13 @@ async function pollUntilDone(jobId) {
if (res.status === 404) {
throw withMessage(new Error('job vanished'), 'Job disappeared. Try again.');
}
+ if (res.status === 401 || res.status === 403) {
+ // Session expired (or never authenticated) mid-build. Bounce to
+ // login and resume this job on return — don't spin for 8 minutes
+ // on a status that retrying can never recover from.
+ try { sessionStorage.setItem('selfie:pendingJobId', jobId); } catch (_) {}
+ throw mapApiError(res.status, await res.json().catch(() => ({})));
+ }
consecutiveErrors += 1;
continue;
}
diff --git a/tests/api/animation-clips.test.js b/tests/api/animation-clips.test.js
new file mode 100644
index 000000000..c96f7e241
--- /dev/null
+++ b/tests/api/animation-clips.test.js
@@ -0,0 +1,121 @@
+import { describe, it, expect } from 'vitest';
+import { __test__ } from '../../api/animations/clips.js';
+
+const { createSchema, clipSchema, editorDocSchema, autoSlug, encodeCursor, decodeCursor, listItem } = __test__;
+
+// A minimal valid baked AnimationClip.toJSON() payload.
+const validClip = {
+ name: 'wave',
+ duration: 2,
+ tracks: [
+ { name: 'LeftArm.quaternion', type: 'quaternion', times: [0, 1, 2], values: new Array(12).fill(0) },
+ { name: 'Hips.position', type: 'vector', times: [0, 2], values: [0, 0, 0, 0, 0, 0] },
+ ],
+};
+
+describe('animation-clips create schema', () => {
+ it('accepts a well-formed create payload', () => {
+ const r = createSchema.safeParse({
+ name: 'My Wave',
+ visibility: 'public',
+ tags: ['greeting', 'loop'],
+ fps: 30,
+ loop: true,
+ clip: validClip,
+ });
+ expect(r.success).toBe(true);
+ });
+
+ it('rejects empty name and a clip with no tracks', () => {
+ expect(createSchema.safeParse({ name: '', clip: validClip }).success).toBe(false);
+ expect(createSchema.safeParse({ name: 'x', clip: { name: 'a', duration: 1, tracks: [] } }).success).toBe(false);
+ });
+
+ it('rejects bad slug, bad visibility, and oversized fps', () => {
+ expect(createSchema.safeParse({ name: 'x', slug: 'Has Spaces', clip: validClip }).success).toBe(false);
+ expect(createSchema.safeParse({ name: 'x', visibility: 'secret', clip: validClip }).success).toBe(false);
+ expect(createSchema.safeParse({ name: 'x', fps: 9999, clip: validClip }).success).toBe(false);
+ });
+
+ it('rejects a non-uuid avatar_id', () => {
+ expect(createSchema.safeParse({ name: 'x', avatar_id: 'not-a-uuid', clip: validClip }).success).toBe(false);
+ });
+
+ it('accepts an optional editor_doc and validates its keyframes', () => {
+ const ok = createSchema.safeParse({
+ name: 'x',
+ clip: validClip,
+ editor_doc: {
+ duration: 2,
+ fps: 30,
+ loop: true,
+ keyframes: [
+ { id: 'kf_1', time: 0, easing: 'ease-in-out', pose: { bones: { Hips: [0, 0, 0, 1] } } },
+ { time: 2, pose: { bones: { Hips: [0, 0, 0, 1] }, rootPosition: { x: 0, y: 1, z: 0 } } },
+ ],
+ },
+ });
+ expect(ok.success).toBe(true);
+ });
+});
+
+describe('clipSchema track validation', () => {
+ it('requires name/type/times/values on every track', () => {
+ expect(clipSchema.safeParse({ name: 'a', duration: 1, tracks: [{ name: 'X.quaternion' }] }).success).toBe(false);
+ });
+});
+
+describe('editorDocSchema', () => {
+ it('requires a duration and a pose.bones map per keyframe', () => {
+ expect(editorDocSchema.safeParse({ keyframes: [] }).success).toBe(false); // no duration
+ expect(editorDocSchema.safeParse({ duration: 1, keyframes: [{ time: 0 }] }).success).toBe(false); // no pose
+ });
+});
+
+describe('autoSlug', () => {
+ it('lowercases, hyphenates, and suffixes', () => {
+ const s = autoSlug('My Cool Walk Cycle!');
+ expect(s).toMatch(/^my-cool-walk-cycle-[a-z0-9]{4}$/);
+ });
+ it('falls back to "animation" for empty input', () => {
+ expect(autoSlug('!!!')).toMatch(/^animation-[a-z0-9]{4}$/);
+ });
+});
+
+describe('cursor round-trip', () => {
+ it('encodes and decodes a created_at cursor', () => {
+ const now = new Date('2026-05-31T12:00:00.000Z');
+ const cur = encodeCursor({ createdAt: now });
+ const back = decodeCursor(cur);
+ expect(back.createdAt.toISOString()).toBe(now.toISOString());
+ });
+ it('returns null for a garbage cursor', () => {
+ expect(decodeCursor('@@@not-base64@@@')).toBeNull();
+ });
+});
+
+describe('listItem projection', () => {
+ const row = {
+ id: 'id-1', owner_id: 'owner-1', slug: 'wave', name: 'Wave', description: null,
+ kind: 'loop', format: 'three.ws.animation.v1', duration_ms: 2000, frame_count: 3,
+ fps: 30, loop: true, tags: ['hi'], visibility: 'public', avatar_id: null,
+ thumbnail_key: null, price_amount: null, price_currency: null, listed: false,
+ play_count: 5, purchase_count: 0, created_at: 'now', updated_at: 'now',
+ };
+
+ it('marks the owner as self and hides price when unpriced', () => {
+ const item = listItem(row, { userId: 'owner-1' });
+ expect(item.owner).toBe('self');
+ expect(item.price).toBeNull();
+ expect(item.duration).toBe(2);
+ expect(item.thumbnail_url).toBeNull();
+ });
+
+ it('marks non-owner as other and surfaces a price when set', () => {
+ const priced = { ...row, price_amount: '1.5', price_currency: 'USDC', listed: true };
+ const item = listItem(priced, { userId: 'someone-else' });
+ expect(item.owner).toBe('other');
+ expect(item.price).toEqual({ amount: '1.5', currency: 'USDC' });
+ expect(item.listed).toBe(true);
+ });
+});
diff --git a/tests/block-store.test.js b/tests/block-store.test.js
new file mode 100644
index 000000000..ac9f5acec
--- /dev/null
+++ b/tests/block-store.test.js
@@ -0,0 +1,58 @@
+// BlockStore — the per-coin build persistence layer. Without Redis env vars it
+// runs memory-only, which is the documented production baseline (Cloud Run
+// min=1/max=1): a build must outlive the room emptying within the process. These
+// tests lock that guarantee and the honest `durable` reporting the HUD reads.
+
+import { describe, it, expect, beforeEach } from 'vitest';
+
+// Ensure no Redis credentials leak in from the environment for this suite.
+delete process.env.UPSTASH_REDIS_REST_URL;
+delete process.env.UPSTASH_REDIS_REST_TOKEN;
+
+const { blockStore } = await import('../multiplayer/src/block-store.js');
+
+describe('BlockStore (memory-only)', () => {
+ it('reports not-durable without Redis configured', async () => {
+ await blockStore.ready();
+ expect(blockStore.durable).toBe(false);
+ });
+
+ it('keeps a coin world alive across reloads within the process', async () => {
+ const coin = 'CoinAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
+ const first = await blockStore.load(coin);
+ blockStore.set(coin, '0,0,0', 3);
+ blockStore.set(coin, '1,0,0', 5);
+
+ // A fresh load (e.g. the room disposed and was recreated) returns the SAME
+ // live map — the community's build is still there.
+ const second = await blockStore.load(coin);
+ expect(second).toBe(first);
+ expect(second.get('0,0,0')).toBe(3);
+ expect(second.get('1,0,0')).toBe(5);
+ expect(second.size).toBe(2);
+ });
+
+ it('delete removes a cell from the persisted world', async () => {
+ const coin = 'CoinBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB';
+ await blockStore.load(coin);
+ blockStore.set(coin, '2,2,2', 1);
+ blockStore.delete(coin, '2,2,2');
+ const map = await blockStore.load(coin);
+ expect(map.has('2,2,2')).toBe(false);
+ });
+
+ it('isolates builds between coins', async () => {
+ const a = 'CoinCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC';
+ const z = 'CoinDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD';
+ await blockStore.load(a);
+ await blockStore.load(z);
+ blockStore.set(a, '0,0,0', 9);
+ const zMap = await blockStore.load(z);
+ expect(zMap.has('0,0,0')).toBe(false);
+ });
+
+ it('set/delete on an unloaded coin is a safe no-op', () => {
+ expect(() => blockStore.set('NeverLoadedCoin', '0,0,0', 1)).not.toThrow();
+ expect(() => blockStore.delete('NeverLoadedCoin', '0,0,0')).not.toThrow();
+ });
+});
diff --git a/tests/build-hud.test.js b/tests/build-hud.test.js
new file mode 100644
index 000000000..b85a417c5
--- /dev/null
+++ b/tests/build-hud.test.js
@@ -0,0 +1,105 @@
+// @vitest-environment jsdom
+//
+// Build HUD controller — the DOM-facing half of /play's building. Verifies the
+// budget meter, durability badge, mode toggle, and enable/disable behaviour the
+// scene drives, so regressions in the player-facing build chrome get caught
+// without standing up a browser.
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+
+globalThis.self = globalThis;
+
+import { createBuildHud, BLOCK_TYPES, MAX_BLOCKS } from '../src/game/build-voxels.js';
+
+let hud;
+afterEach(() => { hud?.dispose(); hud = null; document.body.innerHTML = ''; });
+
+function mount(handlers = {}) {
+ hud = createBuildHud(handlers);
+ return hud;
+}
+
+describe('build HUD', () => {
+ it('mounts with the full palette and a place/break default', () => {
+ mount();
+ expect(document.querySelectorAll('.cc-build-slot').length).toBe(BLOCK_TYPES.length);
+ expect(hud.mode).toBe('place');
+ expect(hud.active).toBe(false);
+ // First slot is selected by default.
+ expect(document.querySelector('.cc-build-slot.cc-on')).toBeTruthy();
+ });
+
+ it('budget meter scales the fill and escalates warn → full', () => {
+ mount();
+ const fill = document.querySelector('.cc-build-budget-fill');
+ const meter = document.querySelector('.cc-build-budget');
+
+ hud.setBudget(0);
+ expect(fill.style.transform).toBe('scaleX(0)');
+ expect(meter.classList.contains('cc-warn')).toBe(false);
+
+ hud.setBudget(Math.round(MAX_BLOCKS * 0.5));
+ expect(fill.style.transform).toBe('scaleX(0.5)');
+ expect(meter.classList.contains('cc-warn')).toBe(false);
+
+ hud.setBudget(Math.round(MAX_BLOCKS * 0.9)); // ≥80% → warn
+ expect(meter.classList.contains('cc-warn')).toBe(true);
+ expect(meter.classList.contains('cc-full')).toBe(false);
+
+ hud.setBudget(MAX_BLOCKS); // full → red, root flagged, warn cleared
+ expect(meter.classList.contains('cc-full')).toBe(true);
+ expect(meter.classList.contains('cc-warn')).toBe(false);
+ expect(hud.root.classList.contains('cc-build-full')).toBe(true);
+
+ // Clamps an over-cap value rather than overflowing the bar.
+ hud.setBudget(MAX_BLOCKS + 500);
+ expect(fill.style.transform).toBe('scaleX(1)');
+ });
+
+ it('durability badge tells the truth and hides for solo', () => {
+ mount();
+ const badge = document.querySelector('.cc-build-durability');
+
+ hud.setPersistent(true);
+ expect(badge.hidden).toBe(false);
+ expect(badge.classList.contains('cc-durable')).toBe(true);
+ expect(badge.textContent).toMatch(/saved/i);
+
+ hud.setPersistent(false);
+ expect(badge.hidden).toBe(false);
+ expect(badge.classList.contains('cc-durable')).toBe(false);
+ expect(badge.textContent).toMatch(/session/i);
+
+ hud.setPersistent(null); // solo single-player → no promise either way
+ expect(badge.hidden).toBe(true);
+ });
+
+ it('mode toggle and selection fire their callbacks', () => {
+ const modes = [];
+ const picks = [];
+ mount({ onModeChange: (m) => modes.push(m), onPick: (i) => picks.push(i) });
+
+ hud.setMode('remove');
+ expect(hud.mode).toBe('remove');
+ expect(modes).toContain('remove');
+ expect(document.querySelector('.cc-build-mode').classList.contains('cc-removing')).toBe(true);
+
+ hud.select(4);
+ expect(picks).toContain(4);
+ expect(document.querySelectorAll('.cc-build-slot')[4].classList.contains('cc-on')).toBe(true);
+ });
+
+ it('setEnabled disables the toggle and collapses an open panel', () => {
+ const toggles = [];
+ mount({ onToggle: (v) => toggles.push(v) });
+ const toggleBtn = document.querySelector('.cc-build-toggle');
+
+ hud.setActive(true);
+ expect(hud.active).toBe(true);
+ hud.setEnabled(false, 'Connecting…');
+ expect(toggleBtn.disabled).toBe(true);
+ expect(toggleBtn.title).toBe('Connecting…');
+ expect(hud.active).toBe(false); // disabling closed the active panel
+ expect(toggles).toContain(false);
+ });
+});
diff --git a/tests/build-voxels.test.js b/tests/build-voxels.test.js
new file mode 100644
index 000000000..cb7b843b6
--- /dev/null
+++ b/tests/build-voxels.test.js
@@ -0,0 +1,187 @@
+// Build (voxel) feature — grid math, VoxelWorld instanced-batch integrity, and
+// client↔server constant parity. These are the load-bearing invariants behind
+// /play's collaborative building: the swap-pop index repair must never desync a
+// rendered instance from its grid key, and the client's bounds/budget caps must
+// mirror the server's exactly (drift = blocks the client lets you place that the
+// server silently rejects).
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, resolve } from 'node:path';
+
+// three's instanced meshes touch a couple of browser globals on import in some
+// builds; mirror the polyfill the other three-using tests use.
+globalThis.self = globalThis;
+
+import {
+ VoxelWorld, keyOf, parseKey, cellToWorld, cellInBounds,
+ BLOCK, MAX_GRID_XZ, MAX_GRID_Y, MAX_BLOCKS, BLOCK_TYPE_COUNT, BLOCK_TYPES,
+} from '../src/game/build-voxels.js';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const ROOT = resolve(__dirname, '..');
+
+// A minimal stand-in for a three.Scene — VoxelWorld only ever add()/remove()s.
+function fakeScene() {
+ const children = new Set();
+ return { add: (o) => children.add(o), remove: (o) => children.delete(o), children };
+}
+
+// The core invariant: for every key the world knows about, the batch slot it
+// points at must actually hold that key, and the InstancedMesh's live instance
+// count must equal the number of keys in that batch. If swap-pop ever fails to
+// repair an index, this catches it.
+function assertConsistent(world) {
+ for (const [key, entry] of world.index) {
+ const batch = world.batches[entry.type];
+ expect(batch.keys[entry.i], `index for ${key} points at the right slot`).toBe(key);
+ }
+ for (const batch of world.batches) {
+ const live = batch.mesh ? batch.mesh.count : 0;
+ expect(live, `batch ${batch.type} instance count tracks key count`).toBe(batch.keys.length);
+ }
+ // Every key appears exactly once across all batches.
+ const all = world.batches.flatMap((b) => b.keys);
+ expect(new Set(all).size).toBe(all.length);
+ expect(all.length).toBe(world.index.size);
+}
+
+describe('grid math', () => {
+ it('keyOf / parseKey round-trip including negatives', () => {
+ for (const c of [[0, 0, 0], [1, 2, 3], [-5, 7, -12], [MAX_GRID_XZ, MAX_GRID_Y - 1, -MAX_GRID_XZ]]) {
+ expect(parseKey(keyOf(...c))).toEqual(c);
+ }
+ });
+
+ it('cellToWorld lands gy=0 flush on the ground plane', () => {
+ const v = cellToWorld(2, 0, -3);
+ expect(v.x).toBeCloseTo(2 * BLOCK);
+ expect(v.z).toBeCloseTo(-3 * BLOCK);
+ // Base sits at y=0: centre is half a block up.
+ expect(v.y).toBeCloseTo(BLOCK / 2);
+ expect(cellToWorld(0, 1, 0).y).toBeCloseTo(BLOCK + BLOCK / 2);
+ });
+
+ it('cellInBounds enforces integers, the height ceiling, and the circular area', () => {
+ expect(cellInBounds(0, 0, 0)).toBe(true);
+ expect(cellInBounds(1.5, 0, 0)).toBe(false); // non-integer
+ expect(cellInBounds(0, -1, 0)).toBe(false); // below the floor
+ expect(cellInBounds(0, MAX_GRID_Y, 0)).toBe(false); // at/over the ceiling
+ expect(cellInBounds(0, MAX_GRID_Y - 1, 0)).toBe(true);
+ expect(cellInBounds(MAX_GRID_XZ, 0, 0)).toBe(true); // on the radius
+ expect(cellInBounds(MAX_GRID_XZ, 0, MAX_GRID_XZ)).toBe(false); // corner is outside the circle
+ expect(cellInBounds(MAX_GRID_XZ + 1, 0, 0)).toBe(false);
+ });
+});
+
+describe('VoxelWorld', () => {
+ it('places, repaints, and reports count/typeAt', () => {
+ const w = new VoxelWorld(fakeScene());
+ expect(w.count).toBe(0);
+ w.setBlock(0, 0, 0, 1);
+ w.setBlock(1, 0, 0, 4);
+ expect(w.count).toBe(2);
+ expect(w.typeAt(0, 0, 0)).toBe(1);
+ expect(w.typeAt(9, 9, 9)).toBe(-1);
+ assertConsistent(w);
+
+ // Repaint moves the block between type batches without growing the world.
+ w.setBlock(0, 0, 0, 7);
+ expect(w.count).toBe(2);
+ expect(w.typeAt(0, 0, 0)).toBe(7);
+ expect(w.batches[1].keys).not.toContain('0,0,0');
+ expect(w.batches[7].keys).toContain('0,0,0');
+ assertConsistent(w);
+
+ // Idempotent: setting the same type again is a no-op.
+ w.setBlock(0, 0, 0, 7);
+ expect(w.count).toBe(2);
+ assertConsistent(w);
+ w.dispose();
+ });
+
+ it('repairs the swap-pop index when removing from the middle of a batch', () => {
+ const w = new VoxelWorld(fakeScene());
+ // Three blocks of the same type → same batch, slots 0,1,2.
+ w.setBlock(0, 0, 0, 2);
+ w.setBlock(1, 0, 0, 2);
+ w.setBlock(2, 0, 0, 2);
+ // Remove the middle one: the last (2,0,0) must swap into slot 1.
+ w.removeBlock(1, 0, 0);
+ expect(w.count).toBe(2);
+ expect(w.hasBlock('1,0,0')).toBe(false);
+ expect(w.index.get('2,0,0').i).toBe(1); // swapped into the freed slot
+ assertConsistent(w);
+ // Removing the (now) moved block still leaves a consistent world.
+ w.removeBlock(2, 0, 0);
+ w.removeBlock(0, 0, 0);
+ expect(w.count).toBe(0);
+ assertConsistent(w);
+ w.dispose();
+ });
+
+ it('survives a randomized place/remove/repaint churn with the invariant intact', () => {
+ const w = new VoxelWorld(fakeScene());
+ // Deterministic LCG so the test is reproducible without Math.random.
+ let seed = 1234567;
+ const rnd = () => (seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff;
+ const live = new Map();
+ for (let step = 0; step < 800; step++) {
+ const gx = Math.floor(rnd() * 7) - 3;
+ const gz = Math.floor(rnd() * 7) - 3;
+ const gy = Math.floor(rnd() * 4);
+ const key = keyOf(gx, gy, gz);
+ if (rnd() < 0.5) {
+ const t = Math.floor(rnd() * BLOCK_TYPE_COUNT);
+ w.setBlock(gx, gy, gz, t);
+ live.set(key, t);
+ } else {
+ w.removeBlock(gx, gy, gz);
+ live.delete(key);
+ }
+ }
+ expect(w.count).toBe(live.size);
+ for (const [key, t] of live) expect(w.typeAt(...parseKey(key))).toBe(t);
+ assertConsistent(w);
+ w.dispose();
+ });
+
+ it('clear() empties every batch', () => {
+ const w = new VoxelWorld(fakeScene());
+ for (let i = 0; i < 20; i++) w.setBlock(i % 5, 0, Math.floor(i / 5), i % BLOCK_TYPE_COUNT);
+ expect(w.count).toBe(20);
+ w.clear();
+ expect(w.count).toBe(0);
+ assertConsistent(w);
+ w.dispose();
+ });
+
+ it('ignores out-of-palette types defensively', () => {
+ const w = new VoxelWorld(fakeScene());
+ w.setBlock(0, 0, 0, -1);
+ w.setBlock(0, 0, 0, BLOCK_TYPE_COUNT);
+ expect(w.count).toBe(0);
+ w.dispose();
+ });
+});
+
+describe('client ↔ server constant parity', () => {
+ // The server validates every edit against its own copies of these caps. If the
+ // client's diverge, players get a build experience that lies (placeable cells
+ // the server rejects, or a budget bar that disagrees with the real limit).
+ const server = readFileSync(resolve(ROOT, 'multiplayer/src/rooms/WalkRoom.js'), 'utf8');
+ const num = (name) => {
+ const m = server.match(new RegExp(`const ${name}\\s*=\\s*(\\d+)`));
+ expect(m, `${name} present in WalkRoom.js`).toBeTruthy();
+ return Number(m[1]);
+ };
+
+ it('grid bounds, block budget, and palette size match WalkRoom', () => {
+ expect(MAX_GRID_XZ).toBe(num('MAX_GRID_XZ'));
+ expect(MAX_GRID_Y).toBe(num('MAX_GRID_Y'));
+ expect(MAX_BLOCKS).toBe(num('MAX_BLOCKS'));
+ expect(BLOCK_TYPE_COUNT).toBe(num('BLOCK_TYPE_COUNT'));
+ expect(BLOCK_TYPES.length).toBe(BLOCK_TYPE_COUNT);
+ });
+});
diff --git a/tests/e2e/usdz-pipeline.spec.js b/tests/e2e/usdz-pipeline.spec.js
new file mode 100644
index 000000000..593497d4c
--- /dev/null
+++ b/tests/e2e/usdz-pipeline.spec.js
@@ -0,0 +1,38 @@
+/**
+ * Real-browser coverage for the GLB → USDZ conversion in
+ * `src/usdz-pipeline.js`.
+ *
+ * three.js's USDZExporter reads raw image bytes through OffscreenCanvas /
+ * drawImage paths that jsdom cannot honour, so the embedded-texture sample
+ * GLB deadlocks the loader under Vitest (the byte-level cases there are
+ * skipped with a pointer to this file). Here we drive real Chromium against
+ * the Vite dev server and exercise the exporter end-to-end, asserting the
+ * USDZ container is a well-formed ZIP with the right mime and a sane size.
+ */
+
+import { test, expect } from '@playwright/test';
+
+test.describe('usdz-pipeline — GLB → USDZ in a real browser', () => {
+ test('produces a PK-zip USDZ blob from the sample GLB', async ({ page }) => {
+ // First import of usdz-pipeline pulls the full three.js + addons graph,
+ // then exports a ~1 MB GLB — well past the default per-test budget.
+ test.setTimeout(180_000);
+
+ await page.goto('/');
+
+ const result = await page.evaluate(async () => {
+ const res = await fetch('/avatars/cz.glb');
+ if (!res.ok) throw new Error(`sample GLB fetch failed: ${res.status}`);
+ const glbBlob = await res.blob();
+ const mod = await import('/src/usdz-pipeline.js');
+ const out = await mod.glbBlobToUsdzBlob(glbBlob);
+ const head = new Uint8Array(await out.slice(0, 4).arrayBuffer());
+ return { type: out.type, size: out.size, magic: Array.from(head) };
+ });
+
+ expect(result.type).toBe('model/vnd.usdz+zip');
+ expect(result.size).toBeGreaterThan(1000);
+ // ZIP local-file-header magic: PK\x03\x04
+ expect(result.magic).toEqual([0x50, 0x4b, 0x03, 0x04]);
+ });
+});
diff --git a/tests/src/usdz-pipeline.test.js b/tests/src/usdz-pipeline.test.js
index 2226e3955..cd7af7731 100644
--- a/tests/src/usdz-pipeline.test.js
+++ b/tests/src/usdz-pipeline.test.js
@@ -149,28 +149,16 @@ describe('three.ws usdz-pipeline — sample GLB sanity', () => {
});
describe('three.ws usdz-pipeline — glbBlobToUsdzBlob', () => {
- // USDZ export under jsdom: the source GLB has embedded textures, and
- // even with our toBlob shim three.js's USDZExporter attempts to read
- // raw image bytes via OffscreenCanvas / drawImage paths that jsdom
- // can't honour. The structural assertions (mime, magic, size) are
- // still meaningful but require a real-browser renderer to exercise
- // reliably. See note at file head — a Playwright-driven test is the
- // right next step.
- it('returns a non-empty USDZ blob with mime model/vnd.usdz+zip and size > 1000 bytes', { timeout: 60000 }, async () => {
- const out = await glbBlobToUsdzBlob(makeGlbBlob());
- expect(out).toBeInstanceOf(Blob);
- expect(out.type).toBe('model/vnd.usdz+zip');
- expect(out.size).toBeGreaterThan(1000);
- });
-
- it('returns bytes that start with the ZIP magic number PK\\x03\\x04', { timeout: 60000 }, async () => {
- const out = await glbBlobToUsdzBlob(makeGlbBlob());
- const bytes = await blobBytes(out);
- expect(bytes[0]).toBe(0x50); // P
- expect(bytes[1]).toBe(0x4B); // K
- expect(bytes[2]).toBe(0x03);
- expect(bytes[3]).toBe(0x04);
- });
+ // USDZ export needs a real browser: three.js's USDZExporter reads raw
+ // image bytes via OffscreenCanvas / drawImage paths that jsdom can't
+ // honour, so the embedded-texture GLB deadlocks the loader here. Faking
+ // those canvas paths would test the shim, not the exporter — so the two
+ // byte-level assertions live in a real Chromium harness instead:
+ // `tests/e2e/usdz-pipeline.spec.js`. The structural API checks below
+ // (function shape, half-body branch) still run in jsdom.
+ it.skip('returns a non-empty USDZ blob with mime model/vnd.usdz+zip and size > 1000 bytes — covered by tests/e2e/usdz-pipeline.spec.js', async () => {});
+
+ it.skip('returns bytes that start with the ZIP magic number PK\\x03\\x04 — covered by tests/e2e/usdz-pipeline.spec.js', async () => {});
it('is an async function exported by the pipeline module', () => {
// Structural check that survives the jsdom canvas gap — confirms
diff --git a/vercel.json b/vercel.json
index c7de44448..c7db9864e 100644
--- a/vercel.json
+++ b/vercel.json
@@ -509,6 +509,10 @@
"src": "/api/mocap/clips/([0-9a-f-]+)",
"dest": "/api/mocap/[id]?id=$1"
},
+ {
+ "src": "/api/animations/clips/([0-9a-f-]+)",
+ "dest": "/api/animations/[id]?id=$1"
+ },
{
"src": "/widget",
"headers": {