Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(society): pixel creatures as the default agent look, shapes as 3D figures (#545)
Ruben Lütke8c64ee0719e9
diff --git a/jarvis/society/agent_template.py b/jarvis/society/agent_template.pyindex a8e47c8884..5f7dfff86a 100644--- a/jarvis/society/agent_template.py+++ b/jarvis/society/agent_template.py@@ -110,7 +110,7 @@ _AVATAR_STRINGS: Final[tuple[str, ...]] = ("eyewear",)_COMPANION_KEYS: Final[frozenset[str]] = frozenset(- {"shape", "color", "eyes", "enabled", "sizeM", "followDistanceM", "pet"}+ {"shape", "color", "eyes", "enabled", "sizeM", "followDistanceM", "pet", "creature", "look"})diff --git a/jarvis/society/companion.py b/jarvis/society/companion.pyindex 28590e5c10..55e9cfa550 100644--- a/jarvis/society/companion.py+++ b/jarvis/society/companion.py@@ -17,6 +17,8 @@ HexColor = Annotated[str, StringConstraints(pattern=r"^#[0-9a-fA-F]{6}$")]# Effect ids stay open like accessory ids: a design saved by a newer build keeps# its colours in an older one, which simply draws no effect it does not know.SkinEffect = Annotated[str, StringConstraints(pattern=r"^[a-z]{1,20}$")]+# Colour-world and eye ids of a pixel creature, open for the same reason.+CreatureId = Annotated[str, StringConstraints(pattern=r"^[a-z]{1,20}$")]#: Mirrors ``COMPANION_SHAPES`` / ``COMPANION_COLORS`` in the frontend's#: ``components/society/companion/appearance.ts`` (parity test pins both).@@ -31,6 +33,14 @@ COMPANION_COLORS: Final[tuple[str, ...]] = ()+#: Mirrors ``CREATURE_PALETTES`` / ``CREATURE_EYES`` in the frontend's+#: ``components/society/companion/creature.ts`` (parity test pins both).+CREATURE_PALETTES: Final[tuple[str, ...]] = (+ "lava", "ocean", "neon", "moss", "glacier", "gold", "candy", "midnight",+)+CREATURE_EYES: Final[tuple[str, ...]] = ("dot", "tall", "wide", "visor")++class CompanionSkin(BaseModel):"""A colour design worn instead of the flat colour (mirrors ``skinSchema`` inthe frontend's ``components/society/companion/skins.ts``).@@ -49,6 +59,21 @@ class CompanionSkin(BaseModel):name: str = Field(default="", max_length=40, pattern=r"^[^\x00-\x1f\x7f]*$")+class CompanionCreature(BaseModel):+ """A pixel creature worn instead of the shape (mirrors ``creatureSchema`` in+ the frontend's ``components/society/companion/creature.ts``).++ The frontend grows the whole figure from ``seed``; nothing but these three+ values is stored.+ """++ model_config = ConfigDict(extra="forbid", strict=True)++ seed: int = Field(ge=0, le=99_999)+ palette: CreatureId+ eyes: CreatureId++class CompanionAppearance(BaseModel):"""One identity for the profile and its presentation-only world follower."""@@ -63,17 +88,31 @@ class CompanionAppearance(BaseModel):pet: PetId | None = None#: A colour design (gradient + effect) instead of the flat colour.skin: CompanionSkin | None = None+ #: A pixel creature instead of the shape; a worn pet still wins.+ creature: CompanionCreature | None = None+ #: The agent explicitly wears its shape. A look without it, without a creature+ #: and without a pet shows the creature the frontend grows from the shape.+ look: Literal["shape"] | None = NonesizeM: float = Field(default=0.5, ge=0.25, le=0.8)followDistanceM: float = Field(default=1.0, ge=0.5, le=2.0)def random_companion() -> dict[str, Any]:- """A random, valid companion look for a newly created agent."""+ """A random, valid companion look for a newly created agent.++ A new agent starts as a pixel creature; the shape underneath is what it+ shows once its creature is taken off.+ """rng = secrets.SystemRandom()look = CompanionAppearance(shape=rng.choice(COMPANION_SHAPES), # type: ignore[arg-type]color=rng.choice(COMPANION_COLORS),eyes=rng.choice(("dots", "lines")), # type: ignore[arg-type]+ creature=CompanionCreature(+ seed=rng.randrange(100_000),+ palette=rng.choice(CREATURE_PALETTES),+ eyes=rng.choice(CREATURE_EYES),+ ),).model_dump()return _bare(look)@@ -86,6 +125,10 @@ def _bare(look: dict[str, Any]) -> dict[str, Any]:look.pop("pet", None)if look.get("skin") is None:look.pop("skin", None)+ if look.get("creature") is None:+ look.pop("creature", None)+ if look.get("look") is None:+ look.pop("look", None)return lookdiff --git a/jarvis/ui/web/frontend/src/components/society/AgentSwatch.test.tsx b/jarvis/ui/web/frontend/src/components/society/AgentSwatch.test.tsxindex f7917046da..087864d3d4 100644--- a/jarvis/ui/web/frontend/src/components/society/AgentSwatch.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/AgentSwatch.test.tsx@@ -1,8 +1,9 @@-import { render } from "@testing-library/react";-import { describe, expect, it } from "vitest";+import { cleanup, render } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it } from "vitest";import { AgentSwatch } from "./AgentSwatch";import { symbolAppearance } from "./AgentSymbol";+import { useCreatureDefault } from "./companion/creatureDefault";import type { SocietyAgent } from "./data";const agent: Pick<SocietyAgent, "agentId" | "tier" | "figure" | "palette" | "name"> = {@@ -13,7 +14,26 @@ const agent: Pick<SocietyAgent, "agentId" | "tier" | "figure" | "palette" | "nampalette: { primary: "#111111", secondary: "#222222", accent: "#333333" },};+describe("an agent that never picked a look", () => {+ afterEach(cleanup);++ it("shows as a pixel creature that acts out the agent's run state", () => {+ const { container, rerender } = render(<AgentSwatch agent={{ ...agent, state: "idle" }} />);+ const face = () => container.querySelector<HTMLElement>("[data-agent-creature]")!;+ expect(container.querySelector("svg")).toBeNull();+ expect(face().dataset.creatureState).toBe("idle");+ rerender(<AgentSwatch agent={{ ...agent, state: "working" }} />);+ expect(face().dataset.creatureState).toBe("working");+ rerender(<AgentSwatch agent={{ ...agent, state: "waiting" }} />);+ expect(face().dataset.creatureState).toBe("asking");+ });+});+describe("agent vector identities", () => {+ // The shape symbols, as they show with pixel creatures switched off on this device.+ beforeEach(() => useCreatureDefault.setState({ enabled: false }));+ afterEach(() => { cleanup(); useCreatureDefault.setState({ enabled: true }); });+it("animates only a real working status, including the lead", () => {const { container, rerender } = render(<AgentSwatch agent={{ ...agent, state: "working" }} />);expect(container.querySelector("[data-thinking=true]")).not.toBeNull();diff --git a/jarvis/ui/web/frontend/src/components/society/AgentSwatch.tsx b/jarvis/ui/web/frontend/src/components/society/AgentSwatch.tsxindex 9bc9191868..59870282a3 100644--- a/jarvis/ui/web/frontend/src/components/society/AgentSwatch.tsx+++ b/jarvis/ui/web/frontend/src/components/society/AgentSwatch.tsx@@ -3,6 +3,7 @@ import { cn } from "@/lib/utils";import { SymbolThinkingDots } from "./AgentSymbol";import { resolveCompanion } from "./companion/appearance";+import { creatureColor } from "./companion/creature";import { CompanionMark } from "./companion/CompanionMark";import type { SocietyAgent } from "./data";@@ -18,7 +19,9 @@ export const LEAD_COLOR = "#ffcd61";*/export function agentColor(agent: SwatchAgent): string {if (isLead(agent)) return LEAD_COLOR;- return resolveCompanion(agent.agentId || agent.name, agent.figure?.companion).color;+ const look = resolveCompanion(agent.agentId || agent.name, agent.figure?.companion);+ // A creature is known by its colour world; the shape colour underneath stays for the way back.+ return look.creature && !look.pet ? creatureColor(look.creature) : look.color;}function isLead(agent: SwatchAgent): boolean {@@ -60,7 +63,7 @@ export function AgentSwatch({{thinking && <svg aria-hidden viewBox="0 0 40 44" className="pointer-events-none absolute inset-0 h-full w-full"><SymbolThinkingDots color="#ffcf45" /></svg>}</>) : (- <CompanionMark appearance={appearance} size={size} thinking={thinking} expressive={expressive} />+ <CompanionMark appearance={appearance} size={size} thinking={thinking} expressive={expressive} run={agent.state} />)}</span>);diff --git a/jarvis/ui/web/frontend/src/components/society/AgentSymbol.tsx b/jarvis/ui/web/frontend/src/components/society/AgentSymbol.tsxindex 919c358433..d10caae80a 100644--- a/jarvis/ui/web/frontend/src/components/society/AgentSymbol.tsx+++ b/jarvis/ui/web/frontend/src/components/society/AgentSymbol.tsx@@ -6,6 +6,10 @@** Jarvis adaptation: stable ID-based appearance and state-driven CSS motion,* without a SDK, JavaScript frame clock, model download or WebGL in the roster.+ *+ * Where a worker is available the symbol is shown as a 3D figure instead: the+ * map companion's own meshes, drawn once on the CPU (companion/ShapeFigure).+ * The flat drawing below stays for the working dots and as the fallback.*/import { useId, useMemo, type ReactNode } from "react";@@ -14,8 +18,10 @@ import {ACCESSORY_CATALOG, FACE_SLOTS, partDepth, resolveFill, smoothPath, symbolViewBox, wornAccessories,type AccessoryChoice, type AccessoryItem, type AccessoryPart,} from "./companion/accessories";+import type { FigureLook } from "./companion/figureScene";+import { ShapeFigure, useFiguresSupported } from "./companion/ShapeFigure";import { SkinDefs, SkinGlow, SkinOverlay } from "./companion/SkinLayers";-import type { CompanionSkin } from "./companion/skins";+import { SKIN_EFFECTS, skinEffect, skinHighlight, type CompanionSkin } from "./companion/skins";import "./agentSymbol.css";export type { SymbolShape } from "./companion/appearance";@@ -158,8 +164,49 @@ function ExpressiveEye({ side, cx, cy, rx, ry }: { side: "l" | "r"; cx: number;</g>;}-export function AgentSymbol({ shape, color, size, eyes = "lines", thinking = false, accessories, expressive = false, skin }: { shape: SymbolShape; color: string; size: number; eyes?: "dots" | "lines"; thinking?: boolean; accessories?: AccessoryChoice; expressive?: boolean; skin?: CompanionSkin }) {- const eyeY = shape === "cloud" || shape === "triangle" ? 23 : shape === "drop" ? 25 : 17.2;+interface SymbolProps { shape: SymbolShape; color: string; size: number; eyes?: "dots" | "lines"; thinking?: boolean; accessories?: AccessoryChoice; expressive?: boolean; skin?: CompanionSkin }++function symbolEyeY(shape: SymbolShape): number {+ return shape === "cloud" || shape === "triangle" ? 23 : shape === "drop" ? 25 : 17.2;+}++/**+ * An agent's shape: a small 3D figure of its body, eyes and accessories, or+ * the flat symbol where figures cannot be drawn. A working agent shows the+ * three flat dots either way.+ */+export function AgentSymbol(props: SymbolProps) {+ const supported = useFiguresSupported();+ if (!supported || props.thinking) return <FlatSymbol {...props} />;+ return <FigureSymbol {...props} />;+}++function FigureSymbol(props: SymbolProps) {+ const { shape, color, size, eyes = "lines", accessories, expressive = false, skin } = props;+ const id = useId().replace(/[^a-zA-Z0-9_-]/g, "");+ const worn = wornAccessories(accessories);+ // Moving eyes are drawn on top of an eyeless figure; glasses cover them, so the figure keeps its own.+ const moving = expressive && !worn.some(item => item.slot === "face");+ const wornKey = worn.map(item => item.id).join(","), skinKey = skin ? JSON.stringify(skin) : "";+ const look = useMemo<FigureLook>(() => ({+ shape, color, eyes, accessories, blind: moving,+ skin: skin && { colors: skin.colors, radial: skin.pattern === "radial", angle: skin.angle, effect: SKIN_EFFECTS.indexOf(skinEffect(skin)), highlight: skinHighlight(skin.colors) },+ // eslint-disable-next-line react-hooks/exhaustive-deps -- accessories and skin are read through their keys+ }), [shape, color, eyes, wornKey, skinKey, moving]);+ const effect = skin ? skinEffect(skin) : "none";+ const eyeY = symbolEyeY(shape);+ return <ShapeFigure look={look} size={size} shape={shape} fallback={<FlatSymbol {...props} />}+ behind={skin && effect === "glow" ? <span aria-hidden className="agent-figure-halo" style={{ background: `radial-gradient(closest-side, ${skinHighlight(skin.colors)}, transparent)` }} /> : undefined}+ overlay={skin && effect === "sparkle" ? <svg aria-hidden focusable="false" viewBox="0 0 40 44" className="society-agent-symbol"><SkinOverlay id={id} skin={skin} body={() => null} /></svg> : undefined}>+ {moving && <g className="agent-symbol-gaze"><g data-agent-eyes fill={companionEyeColors(color).eye}><g className="agent-symbol-lids">+ <ExpressiveEye side="l" cx={15.2} cy={eyeY} rx={eyes === "lines" ? 1.8 : 2.4} ry={eyes === "lines" ? 3.5 : 2.7} />+ <ExpressiveEye side="r" cx={24.8} cy={eyeY} rx={eyes === "lines" ? 1.8 : 2.4} ry={eyes === "lines" ? 3.5 : 2.7} />+ </g></g></g>}+ </ShapeFigure>;+}++function FlatSymbol({ shape, color, size, eyes = "lines", thinking = false, accessories, expressive = false, skin }: SymbolProps) {+ const eyeY = symbolEyeY(shape);const ink = companionEyeColors(color);const maskId = `agent-body-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;const worn = useMemo(() => wornAccessories(accessories), [accessories]);diff --git a/jarvis/ui/web/frontend/src/components/society/agentSymbol.css b/jarvis/ui/web/frontend/src/components/society/agentSymbol.cssindex 964670a6fd..4a766f241a 100644--- a/jarvis/ui/web/frontend/src/components/society/agentSymbol.css+++ b/jarvis/ui/web/frontend/src/components/society/agentSymbol.css@@ -104,3 +104,48 @@stroke-linecap: round;opacity: 0;}++/* The 3D figure (companion/ShapeFigure): a canvas at the face's size, with+ optional vector layers over it. It fades in once, when its first picture+ arrives; later pictures replace it without a flicker. */+.society-agent-figure {+ position: relative;+ display: inline-block;+ flex-shrink: 0;+}+.society-agent-figure > canvas {+ position: relative;+ display: block;+ width: 100%;+ height: 100%;+ opacity: 0;+ transition: opacity 0.18s ease-out;+}+.society-agent-figure[data-ready="true"] > canvas { opacity: 1; }+.society-agent-figure > svg {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ overflow: visible;+ pointer-events: none;+}++/* A glowing design: a soft halo of its brightest colour breathes behind the figure. */+.society-agent-figure > .agent-figure-halo {+ position: absolute;+ inset: -12%;+ border-radius: 50%;+ opacity: 0.4;+ pointer-events: none;+ animation: agent-figure-halo 2.8s ease-in-out infinite alternate;+}+@keyframes agent-figure-halo {+ from { opacity: 0.22; transform: scale(0.94); }+ to { opacity: 0.5; transform: scale(1.04); }+}++@media (prefers-reduced-motion: reduce) {+ .society-agent-figure > canvas { transition: none; }+ .society-agent-figure > .agent-figure-halo { animation: none; }+}diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentProfileDialog.test.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentProfileDialog.test.tsxindex 64f25b55e4..80ac46bef7 100644--- a/jarvis/ui/web/frontend/src/components/society/card/AgentProfileDialog.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentProfileDialog.test.tsx@@ -115,6 +115,8 @@ it("opens the avatar profile without selecting the chat and leaves name-click nait("customizes the agent's look and saves it with the character recipe kept", async () => {const { fetcher } = setup();fireEvent.click(screen.getAllByRole("button", { name: "society.profile_card.look" })[0]);+ // Accessories belong to the shape; an agent that never picked a look opens on its pixel creature.+ fireEvent.click(await screen.findByRole("button", { name: "society.companion.look_shape" }));fireEvent.click(await screen.findByRole("button", { name: "society.companion.items.suit" }));fireEvent.click(screen.getByRole("button", { name: "society.card.save" }));await screen.findByText("society.profile_card.saved");diff --git a/jarvis/ui/web/frontend/src/components/society/companion/AccessoryPicker.tsx b/jarvis/ui/web/frontend/src/components/society/companion/AccessoryPicker.tsxindex 93af80b720..ab8edd8a60 100644--- a/jarvis/ui/web/frontend/src/components/society/companion/AccessoryPicker.tsx+++ b/jarvis/ui/web/frontend/src/components/society/companion/AccessoryPicker.tsx@@ -5,6 +5,7 @@ import { AgentSymbol } from "../AgentSymbol";import { ACCESSORY_IDS_BY_SLOT, OFFERED_SLOTS, randomAccessories, type AccessoryChoice, type AccessorySlot } from "./accessories";import { lookOpen, nextLook, useAgentLooks } from "./agentLooks";import type { CompanionAppearance } from "./appearance";+import { SegmentedChoice } from "./SegmentedChoice";/** Picker order: what people change most comes first; empty slots stay hidden. */const PICKER_SLOTS = (["outfit", "head", "face", "mouth", "neck", "back", "held"] as AccessorySlot[])@@ -31,7 +32,7 @@ export function AccessoryPicker({ value, onChange, agentId }: { value: Companionconst rolled = randomAccessories();onChange(Object.fromEntries(Object.entries(rolled).filter(([, id]) => id && wearable(id))) as AccessoryChoice);};- const tile = "relative grid h-[76px] w-[76px] place-items-center rounded-lg border focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";+ const tile = "relative grid h-[84px] w-[84px] place-items-center rounded-lg border transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";return <div data-testid="accessory-picker"><div className="mb-2 flex items-center justify-between gap-2"><span className="text-sm font-medium">{t("society.companion.accessories")}</span>@@ -52,13 +53,9 @@ export function AccessoryPicker({ value, onChange, agentId }: { value: Companion: t("society.companion.all_looks_open")}</p>)}- <div className="mb-3 flex flex-wrap gap-1.5" role="tablist" aria-label={t("society.companion.accessories")}>- {PICKER_SLOTS.map(s => <button key={s} type="button" role="tab" aria-selected={slot === s} onClick={() => setSlot(s)}- className={`relative rounded-full border px-2.5 py-1 text-xs ${slot === s ? "border-transparent bg-primary text-primary-foreground" : "border-border bg-background text-foreground hover:bg-secondary"}`}>- {t(`society.companion.slots.${s}`)}- {worn[s] && <span aria-hidden className="ml-1.5 inline-block h-1.5 w-1.5 rounded-full bg-current align-middle" />}- </button>)}- </div>+ <div className="mb-3"><SegmentedChoice role="tablist" label={t("society.companion.accessories")} value={slot} onChange={setSlot}+ options={PICKER_SLOTS.map(id => ({ id, label: t(`society.companion.slots.${id}`) }))}+ marked={new Set(PICKER_SLOTS.filter(s => worn[s]))} /></div><div className="flex flex-wrap gap-2" role="group" aria-label={t(`society.companion.slots.${slot}`)}><button type="button" aria-pressed={!worn[slot]} aria-label={t("society.companion.none")} title={t("society.companion.none")} onClick={() => choose(undefined)}className={`${tile} text-xs text-muted-foreground ${!worn[slot] ? "border-foreground bg-secondary" : "border-border hover:bg-secondary"}`}>@@ -75,7 +72,7 @@ export function AccessoryPicker({ value, onChange, agentId }: { value: Companiondata-locked={open ? undefined : "true"}className={`${tile} ${active ? "border-foreground bg-secondary" : open ? "border-border hover:bg-secondary" : "cursor-not-allowed border-dashed border-border"}`}><span className={open ? undefined : "opacity-35 grayscale"}>- <AgentSymbol shape={value.shape} color={value.color} eyes={value.eyes} skin={value.skin} accessories={{ ...worn, [slot]: id }} size={60} />+ <AgentSymbol shape={value.shape} color={value.color} eyes={value.eyes} skin={value.skin} accessories={{ ...worn, [slot]: id }} size={68} /></span>{!open && <span className="absolute bottom-1 left-1/2 inline-flex -translate-x-1/2 items-center gap-0.5 rounded-full bg-background/90 px-1.5 py-0.5 text-[10px] font-semibold text-foreground shadow-sm"><Lock size={9} aria-hidden />{t("society.level.lv").replace("{0}", String(at))}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/AgentAppearanceDialog.test.tsx b/jarvis/ui/web/frontend/src/components/society/companion/AgentAppearanceDialog.test.tsxindex b6bbe51ad7..24782ec3b1 100644--- a/jarvis/ui/web/frontend/src/components/society/companion/AgentAppearanceDialog.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/companion/AgentAppearanceDialog.test.tsx@@ -1,4 +1,4 @@-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { afterEach, expect, it, vi } from "vitest";import { AgentAppearanceDialog } from "./AgentAppearanceDialog";@@ -14,10 +14,10 @@ const PETS = { active: "gigi", scale: 1, bubble: true, strip_always: false, visiid, name: id, description: "", builtin: true, frame_size: 48, animations: { idle: { row: 0, frames: 1, fps: 1, loop: true } }, sheet_url: `/api/pets/${id}/sheet.png`,})) };-function setup(fail = false, legacy = false) {+function setup(fail = false, legacy = false, unpicked = false) {const original = SAMPLE_ROSTER.find(a => a.tier !== "lead")!;const figure = legacy ? { contract: 1 as const, archetype: "biped" as const, base: "rogue", parts: {} } : original.figure!;- const agent = { ...original, agentId: "appearance-test", figure: { ...figure, companion: { ...defaultCompanion("test"), shape: "circle" as const } } };+ const agent = { ...original, agentId: "appearance-test", figure: { ...figure, companion: { ...defaultCompanion("test"), shape: "circle" as const, ...(unpicked ? {} : { look: "shape" as const }) } } };const close = vi.fn();// The look picker reads agent levels; an unreachable level system leaves every look open.const fetcher = vi.fn(async (url: RequestInfo | URL) => String(url).startsWith("/api/progression")@@ -102,3 +102,74 @@ it("lets an agent wear a pet instead of its shape, and take the shape back", asyconst bare = JSON.parse((saves()[1] as unknown as [string, RequestInit])[1].body as string);expect("pet" in bare.avatar.companion).toBe(false);});++it("saves a pixel creature with the look and brings the chosen one back after a detour over the shape", async () => {+ const { saves } = setup();+ fireEvent.click(screen.getByRole("button", { name: "society.companion.look_creature" }));+ fireEvent.click(screen.getByRole("button", { name: "society.companion.creature.palettes.neon" }));+ fireEvent.click(screen.getByRole("button", { name: "society.companion.creature.eye_kinds.visor" }));+ // Back to the shape and to the creature again: the picked one returns, the shape was never lost.+ fireEvent.click(screen.getByRole("button", { name: "society.companion.look_shape" }));+ expect(screen.queryByTestId("creature-picker")).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "society.companion.look_creature" }));+ expect(screen.getByRole("button", { name: "society.companion.creature.palettes.neon" }).getAttribute("aria-pressed")).toBe("true");+ fireEvent.click(screen.getByRole("button", { name: "society.card.save" }));+ await waitFor(() => expect(saves()).toHaveLength(1));+ const [, init] = saves()[0] as unknown as [string, RequestInit];+ const companion = JSON.parse(init.body as string).avatar.companion;+ expect(companion.creature).toMatchObject({ palette: "neon", eyes: "visor" });+ expect(Number.isInteger(companion.creature.seed)).toBe(true);+ expect(companion.shape).toBe("circle");+ expect(companion.pet).toBeUndefined();+ expect(companion.look).toBeUndefined();+});++it("stores no creature when the look goes back to the shape", async () => {+ const { saves } = setup();+ fireEvent.click(screen.getByRole("button", { name: "society.companion.look_creature" }));+ fireEvent.click(screen.getByRole("button", { name: "society.companion.look_shape" }));+ fireEvent.click(screen.getByRole("button", { name: "society.companion.shapes.cloud" }));+ fireEvent.click(screen.getByRole("button", { name: "society.card.save" }));+ await waitFor(() => expect(saves()).toHaveLength(1));+ const [, init] = saves()[0] as unknown as [string, RequestInit];+ const companion = JSON.parse(init.body as string).avatar.companion;+ expect(companion.creature).toBeUndefined();+ expect(companion.look).toBe("shape");+});++it("opens an agent that never picked a look on its pixel creature, and stores the shape once it is chosen", async () => {+ const { saves } = setup(false, false, true);+ expect(screen.getByRole("button", { name: "society.companion.look_creature" }).getAttribute("aria-pressed")).toBe("true");+ expect(screen.getByTestId("creature-picker")).toBeTruthy();+ // The creature previews on its own canvas stage; the 3D studio is for shapes and pets.+ expect(screen.getByTestId("creature-stage")).toBeTruthy();+ expect(screen.queryByTestId("preview")).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "society.companion.creature.state_names.asking" }));+ expect(screen.getByTestId("creature-stage").dataset.creatureState).toBe("asking");+ fireEvent.click(screen.getByRole("button", { name: "society.companion.look_shape" }));+ expect(screen.queryByTestId("creature-stage")).toBeNull();+ expect(await screen.findByTestId("preview")).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "society.card.save" }));+ await waitFor(() => expect(saves()).toHaveLength(1));+ const [, init] = saves()[0] as unknown as [string, RequestInit];+ expect(JSON.parse(init.body as string).avatar.companion.look).toBe("shape");+});++it("rolls a whole new creature at once: figure, colour world and eyes, and wears it", async () => {+ const { saves } = setup();+ fireEvent.click(screen.getByRole("button", { name: "society.companion.look_creature" }));+ const pressedWorld = () => screen.getAllByRole("button", { pressed: true }).map(button => button.getAttribute("aria-label") ?? "").find(label => label.startsWith("society.companion.creature.palettes."));+ const before = pressedWorld();+ fireEvent.click(screen.getByRole("button", { name: "society.companion.creature.roll" }));+ const rolled = pressedWorld();+ expect(rolled).toBeTruthy();+ expect(rolled).not.toBe(before);+ // The rolled figure is worn and leads the row of choices.+ const figures = within(screen.getByTestId("creature-picker")).getAllByRole("button").filter(button => (button.getAttribute("aria-label") ?? "").startsWith("society.companion.creature.number"));+ expect(figures[0].getAttribute("aria-pressed")).toBe("true");+ fireEvent.click(screen.getByRole("button", { name: "society.card.save" }));+ await waitFor(() => expect(saves()).toHaveLength(1));+ const [, init] = saves()[0] as unknown as [string, RequestInit];+ const creature = JSON.parse(init.body as string).avatar.companion.creature;+ expect("society.companion.creature.palettes." + creature.palette).toBe(rolled);+});diff --git a/jarvis/ui/web/frontend/src/components/society/companion/AgentFollower.tsx b/jarvis/ui/web/frontend/src/components/society/companion/AgentFollower.tsxindex 9159899a9c..297ff67101 100644--- a/jarvis/ui/web/frontend/src/components/society/companion/AgentFollower.tsx+++ b/jarvis/ui/web/frontend/src/components/society/companion/AgentFollower.tsx@@ -13,6 +13,8 @@ import { useWornPet } from "./companionPetStore";import { companionFlies, type CompanionPet } from "./petCompanions";import { PetModel, VoxelPet, type PetDrive } from "./PetModel";import { advanceSkin, createSkinMaterial } from "./skinMaterial";+import { CreatureModel } from "./CreatureModel";+import { useShownCreature } from "./creatureDefault";class PetBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {state = { failed: false };@@ -25,8 +27,8 @@ class PetBoundary extends Component<{ children: ReactNode }, { failed: boolean }export const WORN_PET_LIFT_M = 0.32;/**- * An agent's companion in 3D: its shape, or the pet it wears instead- * (`companion.pet`) with that pet's own model and gait. While the pets+ * An agent's companion in 3D: its shape, the pixel creature it wears+ * instead, or its pet (`companion.pet`) with that pet's own model and gait. While the pets* answer is still on its way a worn pet draws nothing, so no shape flashes* first; a pet this machine does not have falls back to the shape.*/@@ -36,8 +38,10 @@ export function CompanionModel({ appearance, lead = false, drive, paused = falsedrive?: { current: PetDrive }; paused?: boolean;}) {const pet = useWornPet(lead ? undefined : appearance.pet);+ const creature = useShownCreature(appearance);if (pet === undefined) return null;if (pet) return <WornPet pet={pet} drive={drive} paused={paused} />;+ if (creature && !lead) return <CreatureModel creature={creature} sizeM={appearance.sizeM} />;return <ShapeModel appearance={appearance} lead={lead} />;}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/CompanionEditor.tsx b/jarvis/ui/web/frontend/src/components/society/companion/CompanionEditor.tsxindex f0b1c03ed9..923f7c0baf 100644--- a/jarvis/ui/web/frontend/src/components/society/companion/CompanionEditor.tsx+++ b/jarvis/ui/web/frontend/src/components/society/companion/CompanionEditor.tsx@@ -4,7 +4,12 @@ import { AgentSymbol } from "../AgentSymbol";import { AccessoryPicker } from "./AccessoryPicker";import { COMPANION_COLORS, COMPANION_SHAPES, type CompanionAppearance } from "./appearance";import { CompanionMark } from "./CompanionMark";+import { creatureFromShape, type CreatureLook, type CreatureState } from "./creature";+import { CreaturePicker } from "./CreaturePicker";+import { CreatureStage } from "./PixelCreature";+import { growsCreature, useCreatureDefault } from "./creatureDefault";import { DesignPicker } from "./DesignPicker";+import { SegmentedChoice } from "./SegmentedChoice";import { PetSprite } from "@/components/pets/PetSprite";import { usePets } from "@/hooks/usePets";import gigiMark from "@/assets/gigi-companion-avatar.png";@@ -23,12 +28,21 @@ export function CompanionEditor({ value, onChange, disabled = false, lead = falsconst update = (patch: Partial<CompanionAppearance>) => onChange({ ...value, ...("color" in patch && !("skin" in patch) ? { skin: undefined } : {}), ...patch });const petsQuery = usePets();const pets = petsQuery.data?.pets ?? [];- // The look is a shape or a pet; "Pet" stays chosen even before a pet exists to pick.- const [kind, setKind] = useState<"shape" | "pet">(value.pet ? "pet" : "shape");- const choose = (next: "shape" | "pet") => {+ const { enabled: creaturesByDefault, setEnabled: setCreaturesByDefault } = useCreatureDefault();+ // The creature last worn in this dialog comes back when the look returns to it; a first one grows from the shape.+ const [lastCreature, setLastCreature] = useState(value.creature);+ const creature = value.creature ?? lastCreature ?? creatureFromShape(value);+ const wear = (next: CreatureLook) => { setLastCreature(next); update({ pet: undefined, look: undefined, creature: next }); };+ const [mood, setMood] = useState<CreatureState>("idle");+ // The look is a shape, a pixel creature or a pet; "Pet" stays chosen even before a pet exists to pick.+ const [kind, setKind] = useState<"shape" | "creature" | "pet">(value.pet ? "pet" : value.creature || growsCreature(value, creaturesByDefault) ? "creature" : "shape");+ const choose = (next: "shape" | "creature" | "pet") => {setKind(next);- if (next === "shape" && value.pet) update({ pet: undefined });- if (next === "pet" && !value.pet && pets[0]) update({ pet: pets[0].id });+ // The shape, its colour and its accessories stay underneath a creature, for the way back.+ // Choosing the shape is stored: without that mark the look would grow a creature again.+ if (next === "shape") update({ pet: undefined, creature: undefined, look: "shape" });+ if (next === "creature") wear(creature);+ if (next === "pet") update({ creature: undefined, look: undefined, ...(!value.pet && pets[0] ? { pet: pets[0].id } : {}) });};// "Pet" chosen before the pets arrived: wear the first one as soon as they do.const firstPet = pets[0]?.id;@@ -37,18 +51,25 @@ export function CompanionEditor({ value, onChange, disabled = false, lead = fals}, [kind, value, firstPet, onChange]);return <fieldset disabled={disabled} className="flex min-w-0 flex-col gap-5 p-4" data-testid="companion-editor"><div className="flex items-center gap-5 rounded-xl bg-secondary/50 p-5">- {lead ? <img src={gigiMark} width={88} height={88} alt="" /> : <CompanionMark appearance={value} size={88} />}+ {lead ? <img src={gigiMark} width={88} height={88} alt="" /> : <CompanionMark appearance={value} size={88} mood={kind === "creature" ? mood : undefined} />}+ {/* A previewed state plays its sign beside the head; keep the text clear of it. */}+ {!lead && kind === "creature" && <span aria-hidden className="w-2 shrink-0" />}<div><h3 className="font-medium">{t("society.companion.title")}</h3><p className="mt-1 text-sm text-muted-foreground">{t("society.companion.hint")}</p></div></div>- {preview3d && <Suspense fallback={null}><CompanionPreview appearance={value} lead={lead} /></Suspense>}- {!lead && <div className="flex items-center justify-between gap-3 text-sm"><span>{t("society.companion.look")}</span>- <div className="flex gap-1.5" role="group" aria-label={t("society.companion.look")}>- {(["shape", "pet"] as const).map(option => <button key={option} type="button" aria-pressed={kind === option} onClick={() => choose(option)}- className={`rounded-full border px-2.5 py-1 text-xs ${kind === option ? "border-transparent bg-primary text-primary-foreground" : "border-border bg-background text-foreground hover:bg-secondary"}`}>- {t(`society.companion.look_${option}`)}- </button>)}- </div>+ {/* A creature previews on a plain canvas, so it shows without a WebGL context; shapes and pets turn in the 3D studio. */}+ {preview3d && (!lead && kind === "creature"+ ? <CreatureStage creature={creature} state={mood} />+ : <Suspense fallback={null}><CompanionPreview appearance={value} lead={lead} /></Suspense>)}+ {/* One switch across the full width, like the access switch of the create dialog. */}+ {!lead && <div className="flex flex-col gap-1.5 text-sm"><span className="font-medium">{t("society.companion.look")}</span>+ <SegmentedChoice label={t("society.companion.look")} value={kind} onChange={choose}+ options={(["creature", "shape", "pet"] as const).map(id => ({ id, label: t(`society.companion.look_${id}`) }))} /></div>}+ {!lead && kind !== "pet" && <label className="flex items-start justify-between gap-3 text-sm">+ <span>{t("society.companion.creature.by_default")}<span className="mt-0.5 block text-xs text-muted-foreground">{t("society.companion.creature.by_default_hint")}</span></span>+ <Switch checked={creaturesByDefault} onCheckedChange={setCreaturesByDefault} aria-label={t("society.companion.creature.by_default")} />+ </label>}+ {!lead && kind === "creature" && <CreaturePicker value={creature} onChange={wear} mood={mood} onMood={setMood} />}{!lead && kind === "pet" && <div data-testid="companion-pet-picker"><span className="mb-1 block text-sm font-medium">{t("society.companion.pet")}</span><p className="mb-2 text-xs text-muted-foreground">{pets.length || petsQuery.isLoading ? t("society.companion.pet_hint") : t("society.companion.no_pets")}</p><div className="flex flex-wrap gap-2">{pets.map(pet => <button key={pet.id} type="button" title={pet.name}@@ -60,18 +81,15 @@ export function CompanionEditor({ value, onChange, disabled = false, lead = fals{!lead && kind === "shape" && <><div><span className="mb-2 block text-sm font-medium">{t("society.companion.shape")}</span><div className="flex flex-wrap gap-2">{COMPANION_SHAPES.map(shape => <button key={shape} type="button"aria-label={t(`society.companion.shapes.${shape}`)} aria-pressed={value.shape === shape}- onClick={() => update({ shape })} className={`grid h-12 w-12 place-items-center rounded-lg border focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${value.shape === shape ? "border-foreground bg-secondary" : "border-border hover:bg-secondary"}`}>- <AgentSymbol shape={shape} color={value.color} eyes={value.eyes} accessories={value.accessories} skin={value.skin} size={36} />+ title={t(`society.companion.shapes.${shape}`)}+ onClick={() => update({ shape })} className={`grid h-16 w-16 place-items-center rounded-lg border transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${value.shape === shape ? "border-foreground bg-secondary" : "border-border hover:bg-secondary"}`}>+ <AgentSymbol shape={shape} color={value.color} eyes={value.eyes} accessories={value.accessories} skin={value.skin} size={52} /></button>)}</div></div>- <div className="flex items-center justify-between gap-3 text-sm"><span>{t("society.companion.eyes")}</span>+ <div className="flex flex-col gap-1.5 text-sm"><span className="font-medium">{t("society.companion.eyes")}</span>{/* Plain toggles: a popup menu inside a modal dialog can strand its pointer lock. */}- <div className="flex gap-1.5" role="group" aria-label={t("society.companion.eyes")}>- {(["dots", "lines"] as const).map(eyes => <button key={eyes} type="button" aria-pressed={value.eyes === eyes} onClick={() => update({ eyes })}- className={`rounded-full border px-2.5 py-1 text-xs ${value.eyes === eyes ? "border-transparent bg-primary text-primary-foreground" : "border-border bg-background text-foreground hover:bg-secondary"}`}>- {t(`society.companion.${eyes}`)}- </button>)}- </div>+ <SegmentedChoice label={t("society.companion.eyes")} value={value.eyes} onChange={eyes => update({ eyes })}+ options={(["dots", "lines"] as const).map(id => ({ id, label: t(`society.companion.${id}`) }))} /></div><AccessoryPicker value={value} onChange={accessories => update({ accessories })} agentId={agentId} /></>}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/CompanionMark.test.tsx b/jarvis/ui/web/frontend/src/components/society/companion/CompanionMark.test.tsxindex 3ce33404e3..740a17a729 100644--- a/jarvis/ui/web/frontend/src/components/society/companion/CompanionMark.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/companion/CompanionMark.test.tsx@@ -1,4 +1,4 @@-import { cleanup, render, screen } from "@testing-library/react";+import { act, cleanup, render, screen } from "@testing-library/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { afterEach, describe, expect, it } from "vitest";@@ -7,6 +7,7 @@ import { petKeys } from "@/hooks/usePets";import type { Pet, PetsState } from "@/lib/petsApi";import { CompanionMark } from "./CompanionMark";import { defaultCompanion, type CompanionAppearance } from "./appearance";+import { useCreatureDefault } from "./creatureDefault";function pet(id: string): Pet {return {@@ -26,11 +27,11 @@ function renderWith(ui: React.ReactElement, state: PetsState | null = PETS) {return render(<QueryClientProvider client={client}>{ui}</QueryClientProvider>);}-afterEach(cleanup);+afterEach(() => { cleanup(); useCreatureDefault.setState({ enabled: true }); });describe("CompanionMark", () => {- it("draws the shape for an agent that wears no pet", () => {- const { container } = renderWith(<CompanionMark appearance={look()} size={30} />);+ it("draws the shape for an agent that explicitly wears it", () => {+ const { container } = renderWith(<CompanionMark appearance={look({ look: "shape" })} size={30} />);expect(container.querySelector("svg")).not.toBeNull();expect(screen.queryByTestId("pet-sprite")).toBeNull();});@@ -57,8 +58,45 @@ describe("CompanionMark", () => {expect((container.firstElementChild as HTMLElement).style.width).toBe("30px");});+ it("draws the worn pixel creature instead of the shape and lets it act out the agent's state", () => {+ const creature = { seed: 24, palette: "neon", eyes: "dot" };+ const { container, rerender } = renderWith(<CompanionMark appearance={look({ creature })} size={36} />);+ const face = () => container.querySelector<HTMLElement>("[data-agent-creature='24']")!;+ expect(container.querySelector("svg")).toBeNull();+ expect(face().style.width).toBe("36px");+ expect(face().dataset.creatureState).toBe("idle");+ const states = [[{ run: "working" }, "working"], [{ run: "waiting" }, "asking"], [{ run: "paused" }, "sleeping"], [{ state: "searching" }, "working"], [{ run: "paused", mood: "success" }, "success"]] as const;+ for (const [props, shown] of states) {+ rerender(<QueryClientProvider client={new QueryClient()}><CompanionMark appearance={look({ creature })} size={36} {...props} /></QueryClientProvider>);+ expect(face().dataset.creatureState).toBe(shown);+ }+ rerender(<QueryClientProvider client={new QueryClient()}><PetStageContext.Provider value="talking"><CompanionMark appearance={look({ creature })} size={36} /></PetStageContext.Provider></QueryClientProvider>);+ expect(face().dataset.creatureState).toBe("talking");+ });++ it("keeps the worn pet over a creature, and shows the creature when that pet is missing here", () => {+ const creature = { seed: 24, palette: "neon", eyes: "dot" };+ const worn = renderWith(<CompanionMark appearance={look({ creature, pet: "cocoa" })} size={30} />);+ expect(worn.container.querySelector("[data-agent-pet='cocoa']")).not.toBeNull();+ expect(worn.container.querySelector("[data-agent-creature]")).toBeNull();+ worn.unmount();+ const missing = renderWith(<CompanionMark appearance={look({ creature, pet: "u0123456789abcdef" })} size={30} />);+ expect(missing.container.querySelector("[data-agent-creature='24']")).not.toBeNull();+ });++ it("grows a creature for a look nobody picked, and shows the shape again once the switch is off", () => {+ const { container } = renderWith(<CompanionMark appearance={look()} size={30} />);+ expect(container.querySelector("svg")).toBeNull();+ expect(container.querySelector("[data-agent-creature]")).not.toBeNull();+ act(() => useCreatureDefault.getState().setEnabled(false));+ expect(container.querySelector("svg")).not.toBeNull();+ expect(container.querySelector("[data-agent-creature]")).toBeNull();+ act(() => useCreatureDefault.getState().setEnabled(true));+ expect(container.querySelector("[data-agent-creature]")).not.toBeNull();+ });+it("falls back to the shape for a pet this machine does not have", () => {- const { container } = renderWith(<CompanionMark appearance={look({ pet: "u0123456789abcdef" })} size={30} />);+ const { container } = renderWith(<CompanionMark appearance={look({ pet: "u0123456789abcdef", look: "shape" })} size={30} />);expect(screen.queryByTestId("pet-sprite")).toBeNull();expect(container.querySelector("svg")).not.toBeNull();});diff --git a/jarvis/ui/web/frontend/src/components/society/companion/CompanionMark.tsx b/jarvis/ui/web/frontend/src/components/society/companion/CompanionMark.tsxindex 6f2640e0cb..56c573f1bc 100644--- a/jarvis/ui/web/frontend/src/components/society/companion/CompanionMark.tsx+++ b/jarvis/ui/web/frontend/src/components/society/companion/CompanionMark.tsx@@ -7,6 +7,9 @@ import { usePetById } from "@/hooks/usePets";import type { PetState } from "@/lib/petStates";import { AgentSymbol } from "../AgentSymbol";import type { CompanionAppearance } from "./appearance";+import type { CreatureState } from "./creature";+import { useShownCreature } from "./creatureDefault";+import { PixelCreature } from "./PixelCreature";type MarkProps = {appearance: CompanionAppearance;@@ -17,11 +20,23 @@ type MarkProps = {expressive?: boolean;/** Fixes the pet's row; otherwise a surrounding stage or `thinking` decides. */state?: PetState;+ /** The agent's coarse run state: a creature asks while it waits and sleeps while paused. */+ run?: "idle" | "working" | "waiting" | "paused";+ /** Fixes what a creature acts out (the look editor's preview). */+ mood?: CreatureState;};+/** A creature acts out the pet vocabulary every stage already speaks. */+const CREATURE_FOR_PET: Readonly<Record<PetState, CreatureState>> = {+ idle: "idle", listening: "listening", thinking: "thinking", talking: "talking", success: "success",+ error: "error", sleeping: "sleeping", working: "working", searching: "working", held: "listening",+};+const CREATURE_FOR_RUN = { idle: "idle", working: "working", waiting: "asking", paused: "sleeping" } as const;+/**- * An agent's face in 2D: its shape symbol, or the pet it wears instead- * (`companion.pet`, chosen in the look dialog from My Pets). Every surface+ * An agent's face in 2D: its shape symbol, the pixel creature it wears+ * instead (`companion.creature`), or its pet (`companion.pet`, chosen in the+ * look dialog from My Pets). Every surface* that draws an agent goes through here, so choosing a pet changes the* roster, the chats, the bot stage and the level hall at once.*@@ -30,8 +45,13 @@ type MarkProps = {* does not exist here (deleted, or drawn on another machine) shows the shape.*/export function CompanionMark(props: MarkProps) {- const { appearance, size, thinking = false, expressive = false } = props;- const shape = <AgentSymbol {...appearance} size={size} thinking={thinking} expressive={expressive} />;+ const { appearance, size, thinking = false, expressive = false, state, run, mood } = props;+ const creature = useShownCreature(appearance);+ const staged = useContext(PetStageContext);+ const pose = state ?? staged;+ const shape = creature+ ? <PixelCreature creature={creature} size={size} state={mood ?? (pose ? CREATURE_FOR_PET[pose] : thinking ? "working" : CREATURE_FOR_RUN[run ?? "idle"])} />+ : <AgentSymbol {...appearance} size={size} thinking={thinking} expressive={expressive} />;// Outside a query client (an isolated render, a bare preview) there is no catalog to read.const client = useContext(QueryClientContext);if (!appearance.pet || !client) return shape;diff --git a/jarvis/ui/web/frontend/src/components/society/companion/CreatureModel.tsx b/jarvis/ui/web/frontend/src/components/society/companion/CreatureModel.tsxnew file mode 100644index 0000000000..3ff56a9834--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/CreatureModel.tsx@@ -0,0 +1,41 @@+import { useEffect, useMemo } from "react";+import { BoxGeometry, Color, InstancedMesh, Matrix4, MeshStandardMaterial } from "three";+import { creatureBody, creatureCubes, creaturePose, GRID, type CreatureLook } from "./creature";++/**+ * A pixel creature in the Verse: the same cubes the profile face paints, as+ * one instanced mesh standing on the ground and facing +z like the shapes.+ * It is built once per look and holds its resting pose.+ */+export function CreatureModel({ creature, sizeM }: { creature: CreatureLook; sizeM: number }) {+ const { seed, palette, eyes } = creature;+ const resources = useMemo(() => {+ const body = creatureBody({ seed, palette, eyes });+ // Frame 5 of the idle loop: eyes open, looking ahead.+ const cubes = creatureCubes(body, creaturePose("idle", 5));+ // A full grid stands as tall as a shape; a shorter creature keeps its cube size.+ const cube = sizeM / GRID;+ const geometry = new BoxGeometry(1, 1, 1);+ const material = new MeshStandardMaterial({ roughness: 0.7 });+ const mesh = new InstancedMesh(geometry, material, cubes.length);+ mesh.castShadow = true;+ mesh.frustumCulled = false;+ const matrix = new Matrix4();+ const colour = new Color();+ cubes.forEach((entry, index) => {+ matrix.makeScale(cube, cube, cube);+ matrix.setPosition((entry.x - 4) * cube, (body.bottom - entry.y + 0.5) * cube, entry.z * cube);+ mesh.setMatrixAt(index, matrix);+ mesh.setColorAt(index, colour.setRGB(entry.color[0] / 255, entry.color[1] / 255, entry.color[2] / 255, "srgb"));+ });+ mesh.instanceMatrix.needsUpdate = true;+ if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;+ return { mesh, geometry, material };+ }, [seed, palette, eyes, sizeM]);+ useEffect(() => () => {+ resources.mesh.dispose();+ resources.geometry.dispose();+ resources.material.dispose();+ }, [resources]);+ return <primitive object={resources.mesh} dispose={null} />;+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/CreaturePicker.tsx b/jarvis/ui/web/frontend/src/components/society/companion/CreaturePicker.tsxnew file mode 100644index 0000000000..2f82e839c1--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/CreaturePicker.tsx@@ -0,0 +1,72 @@+import { useState } from "react";+import { Dices } from "lucide-react";+import { useT } from "@/i18n";+import {+ CREATURE_EYES, CREATURE_PALETTES, CREATURE_SEED_MAX, CREATURE_STATES, randomCreature, type CreatureLook, type CreatureState,+} from "./creature";+import { PixelCreature } from "./PixelCreature";+import { SegmentedChoice } from "./SegmentedChoice";++const CHOICES = 8;+const rollSeed = () => Math.floor(Math.random() * (CREATURE_SEED_MAX + 1));+const chip = (on: boolean) => `rounded-full border px-2.5 py-1 text-xs ${on ? "border-transparent bg-primary text-primary-foreground" : "border-border bg-background text-foreground hover:bg-secondary"}`;++/**+ * Everything a pixel creature has to choose: one of eight rolled figures, a+ * colour world and an eye kind. "Roll again" rolls all three at once and+ * wears the result, so one click gives a whole new creature; the rows below+ * fine-tune it. The state row only previews what the creature acts out; it+ * is never saved.+ */+export function CreaturePicker({ value, onChange, mood, onMood }: {+ value: CreatureLook; onChange: (next: CreatureLook) => void;+ mood: CreatureState; onMood: (mood: CreatureState) => void;+}) {+ const t = useT();+ // The worn figure leads the first row, so opening the dialog never loses it.+ const [seeds, setSeeds] = useState(() => [value.seed, ...Array.from({ length: CHOICES - 1 }, rollSeed)]);+ const roll = () => {+ // Always another colour world, so a roll is never mistaken for a reshuffle of the same figure.+ let next = randomCreature();+ for (let tries = 0; next.palette === value.palette && tries < 8; tries++) next = randomCreature();+ setSeeds([next.seed, ...Array.from({ length: CHOICES - 1 }, rollSeed)]);+ onChange(next);+ };+ return <div className="flex flex-col gap-5" data-testid="creature-picker">+ <div>+ <div className="mb-2 flex items-center justify-between gap-3">+ <span className="text-sm font-medium">{t("society.companion.creature.figure")}</span>+ <button type="button" onClick={roll}+ className="inline-flex h-9 items-center gap-2 rounded-lg bg-primary px-4 text-sm font-medium text-primary-foreground hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-popover">+ <Dices size={18} aria-hidden />{t("society.companion.creature.roll")}+ </button>+ </div>+ <div className="flex flex-wrap gap-2">{seeds.map((seed, index) => <button key={`${index}-${seed}`} type="button"+ aria-label={t("society.companion.creature.number").replace("{0}", String(seed))} aria-pressed={value.seed === seed} onClick={() => onChange({ ...value, seed })}+ className={`grid h-14 w-14 place-items-center rounded-lg border focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${value.seed === seed ? "border-foreground bg-secondary" : "border-border hover:bg-secondary"}`}>+ <PixelCreature creature={{ ...value, seed }} size={40} />+ </button>)}</div>+ </div>+ <div>+ <span className="mb-2 block text-sm font-medium">{t("society.companion.creature.palette")}</span>+ <div className="flex flex-wrap gap-2">{CREATURE_PALETTES.map(palette => <button key={palette.id} type="button"+ aria-label={t(`society.companion.creature.palettes.${palette.id}`)} title={t(`society.companion.creature.palettes.${palette.id}`)}+ aria-pressed={value.palette === palette.id} onClick={() => onChange({ ...value, palette: palette.id })}+ className={`h-9 w-9 rounded-full border border-border ring-offset-2 ring-offset-popover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${value.palette === palette.id ? "ring-2 ring-foreground" : ""}`}+ style={{ background: `linear-gradient(180deg, ${palette.colors.join(", ")})` }} />)}</div>+ </div>+ <div className="flex flex-col gap-1.5 text-sm"><span className="font-medium">{t("society.companion.eyes")}</span>+ <SegmentedChoice label={t("society.companion.eyes")} value={value.eyes} onChange={eyes => onChange({ ...value, eyes })}+ options={CREATURE_EYES.map(id => ({ id, label: t(`society.companion.creature.eye_kinds.${id}`) }))} />+ </div>+ <div>+ <span className="mb-1 block text-sm font-medium">{t("society.companion.creature.states")}</span>+ <p className="mb-2 text-xs text-muted-foreground">{t("society.companion.creature.states_hint")}</p>+ <div className="flex flex-wrap gap-1.5" role="group" aria-label={t("society.companion.creature.states")}>+ {CREATURE_STATES.map(state => <button key={state} type="button" aria-pressed={mood === state} onClick={() => onMood(state)} className={chip(mood === state)}>+ {t(`society.companion.creature.state_names.${state}`)}+ </button>)}+ </div>+ </div>+ </div>;+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/PixelCreature.tsx b/jarvis/ui/web/frontend/src/components/society/companion/PixelCreature.tsxnew file mode 100644index 0000000000..1bb2f8c181--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/PixelCreature.tsx@@ -0,0 +1,220 @@+import { useEffect, useRef } from "react";+import { useReducedMotion } from "framer-motion";+import {+ creatureBody, creaturePose, CREATURE_STILL_FRAME, CREATURE_TICK_MS, GRID, STAGE_H, STAGE_W, STAGE_X, STAGE_Y,+ type CreatureLook, type CreatureState,+} from "./creature";+import { FACE_YAW, paintCreature } from "./creaturePaint";++/**+ * One clock for every creature on screen. It only runs while a visible+ * creature listens and the window is shown, and each face repaints only when+ * its pose actually changed: a resting roster costs a blink every six seconds.+ */+const listeners = new Set<(frame: number) => void>();+let timer: number | undefined;+let watching = false;++/** The most time one tick spends painting, milliseconds; faces left over paint on the next tick. */+const TICK_BUDGET_MS = 6;+let cursor = 0;++/**+ * Paints the faces whose pose changed, round robin, and stops at the budget:+ * a tick must never hold the UI thread, however many faces are on screen or+ * however slow one paint is. A face that waits a tick shows its frame late.+ */+function tick(): void {+ const frame = Math.floor(performance.now() / CREATURE_TICK_MS);+ const order = [...listeners];+ const deadline = performance.now() + TICK_BUDGET_MS;+ for (let done = 0; done < order.length; done++) {+ order[(cursor + done) % order.length]!(frame);+ if (performance.now() >= deadline) {+ cursor = (cursor + done + 1) % order.length;+ return;+ }+ }+ cursor = 0;+}++/** Runs the timer exactly while someone listens and the window is visible. */+function syncClock(): void {+ const run = listeners.size > 0 && !document.hidden;+ if (run && timer === undefined) timer = window.setInterval(tick, CREATURE_TICK_MS);+ else if (!run && timer !== undefined) {+ window.clearInterval(timer);+ timer = undefined;+ }+}++function onFrame(listener: (frame: number) => void): () => void {+ listeners.add(listener);+ if (!watching) {+ watching = true;+ document.addEventListener("visibilitychange", syncClock);+ }+ syncClock();+ return () => {+ listeners.delete(listener);+ syncClock();+ };+}++/**+ * A 2D context that paints on the CPU. A roster holds many small canvases+ * that repaint rarely; as GPU canvases each one owns graphics memory and+ * every paint crosses to the graphics process, where a busy GPU (a 3D map, a+ * video capture) can hold the UI thread for seconds. `willReadFrequently` is+ * how a page asks for the CPU path.+ */+function softwareContext(canvas: HTMLCanvasElement): CanvasRenderingContext2D | null {+ return canvas.getContext("2d", { willReadFrequently: true });+}++/**+ * An agent's pixel creature at `size` pixels, acting out `state`. The figure+ * fills the square like every other agent face; the canvas reaches a little+ * past it on each side, so a question mark or a spark can play beside the+ * head without a wider layout. Reduced motion shows one still frame per state.+ */+export function PixelCreature({ creature, size, state = "idle" }: { creature: CreatureLook; size: number; state?: CreatureState }) {+ const canvas = useRef<HTMLCanvasElement>(null);+ const reduced = useReducedMotion() ?? false;+ const { seed, palette, eyes } = creature;+ useEffect(() => {+ const node = canvas.current;+ // No 2D canvas (a test DOM): the box keeps its size and stays empty.+ if (!node || typeof CanvasRenderingContext2D === "undefined") return;+ const context = softwareContext(node);+ if (!context) return;+ const body = creatureBody({ seed, palette, eyes });+ // Twice the layout size at least: the turned cubes need the extra pixels to stay crisp.+ const scale = Math.max(2, Math.min(window.devicePixelRatio || 1, 3));+ const width = Math.round((size * STAGE_W / GRID) * scale);+ node.width = width;+ node.height = Math.round((width * STAGE_H) / STAGE_W);+ if (reduced) {+ paintCreature(context, width, body, creaturePose(state, CREATURE_STILL_FRAME[state]), FACE_YAW);+ return;+ }+ // Each creature runs a little out of step, so a roster never blinks as one.+ const offset = (seed * 13) % 60;+ let shown = "";+ const draw = (frame: number) => {+ const pose = creaturePose(state, frame + offset);+ const key = JSON.stringify(pose);+ if (key === shown) return;+ shown = key;+ paintCreature(context, width, body, pose, FACE_YAW);+ };+ draw(Math.floor(performance.now() / CREATURE_TICK_MS));+ let stop: (() => void) | undefined;+ const watch = (visible: boolean) => {+ if (visible && !stop) stop = onFrame(draw);+ else if (!visible && stop) { stop(); stop = undefined; }+ };+ if (typeof IntersectionObserver === "undefined") {+ watch(true);+ return () => watch(false);+ }+ const observer = new IntersectionObserver((entries) => watch(entries.some((entry) => entry.isIntersecting)));+ observer.observe(node);+ return () => { observer.disconnect(); watch(false); };+ }, [seed, palette, eyes, size, state, reduced]);+ const cell = size / GRID;+ return <span className="relative inline-block shrink-0" data-agent-creature={seed} data-creature-state={state} style={{ width: size, height: size }}>+ <canvas ref={canvas} aria-hidden className="pointer-events-none absolute max-w-none"+ style={{ left: -STAGE_X * cell, top: -STAGE_Y * cell, width: STAGE_W * cell, height: STAGE_H * cell }} />+ </span>;+}++/** How far the stage figure sways to each side of its resting turn, radians. */+const STAGE_SWAY = 0.5;+/** One sway takes this long, milliseconds. */+const STAGE_SWAY_MS = 7000;+/** The stage repaints at most this often, milliseconds: the sway is slow, and a preview must stay cheap. */+const STAGE_FRAME_MS = 33;+/** How far a drag across the whole stage turns the figure, radians. */+const STAGE_DRAG_TURN = Math.PI * 1.5;++/**+ * The large preview of a pixel creature in the look editor: the same cubes+ * as the profile face, big, swaying slowly so every side shows, and turned+ * by dragging. It is a 2D canvas on purpose: it needs no WebGL context, so it+ * shows on every machine and never competes with the map for one.+ */+export function CreatureStage({ creature, state = "idle" }: { creature: CreatureLook; state?: CreatureState }) {+ const canvas = useRef<HTMLCanvasElement>(null);+ const turn = useRef(0);+ const reduced = useReducedMotion() ?? false;+ const { seed, palette, eyes } = creature;+ useEffect(() => {+ const node = canvas.current;+ if (!node || typeof CanvasRenderingContext2D === "undefined") return;+ const context = softwareContext(node);+ if (!context) return;+ const body = creatureBody({ seed, palette, eyes });+ let width = 0;+ let shown = "";+ let frameRequest = 0;+ let visible = true;+ let painted = -Infinity;+ const paint = (now: number, force = false) => {+ if (!force && now - painted < STAGE_FRAME_MS) return;+ painted = now;+ const scale = Math.min(window.devicePixelRatio || 1, 2);+ const next = Math.round(node.clientWidth * scale);+ if (next === 0) return;+ if (next !== width) {+ width = next;+ node.width = width;+ node.height = Math.round((width * STAGE_H) / STAGE_W);+ shown = "";+ }+ const frame = reduced ? CREATURE_STILL_FRAME[state] : Math.floor(now / CREATURE_TICK_MS);+ const sway = reduced ? 0 : Math.sin((now / STAGE_SWAY_MS) * Math.PI * 2) * STAGE_SWAY;+ const yaw = FACE_YAW + sway + turn.current;+ const key = `${frame}|${yaw.toFixed(3)}`;+ if (key === shown) return;+ shown = key;+ paintCreature(context, width, body, creaturePose(state, frame), yaw);+ };+ const loop = (now: number) => {+ paint(now);+ // Reduced motion paints once and again only after a drag.+ frameRequest = visible && !reduced ? requestAnimationFrame(loop) : 0;+ };+ const start = () => { if (!frameRequest) frameRequest = requestAnimationFrame(loop); };+ start();++ let dragFrom: number | null = null;+ const onDown = (event: PointerEvent) => { dragFrom = event.clientX; node.setPointerCapture(event.pointerId); };+ const onMove = (event: PointerEvent) => {+ if (dragFrom === null) return;+ turn.current += ((event.clientX - dragFrom) / Math.max(1, node.clientWidth)) * STAGE_DRAG_TURN;+ dragFrom = event.clientX;+ // A still figure (reduced motion) repaints on the drag itself.+ if (reduced) paint(performance.now(), true); else start();+ };+ const onUp = () => { dragFrom = null; };+ node.addEventListener("pointerdown", onDown);+ node.addEventListener("pointermove", onMove);+ node.addEventListener("pointerup", onUp);+ node.addEventListener("pointercancel", onUp);+ const observer = typeof IntersectionObserver === "undefined" ? null+ : new IntersectionObserver((entries) => { visible = entries.some((entry) => entry.isIntersecting); if (visible) start(); });+ observer?.observe(node);+ return () => {+ observer?.disconnect();+ if (frameRequest) cancelAnimationFrame(frameRequest);+ node.removeEventListener("pointerdown", onDown);+ node.removeEventListener("pointermove", onMove);+ node.removeEventListener("pointerup", onUp);+ node.removeEventListener("pointercancel", onUp);+ };+ }, [seed, palette, eyes, state, reduced]);+ return <div className="flex h-56 w-full items-center justify-center" data-testid="creature-stage" data-creature-state={state}>+ <canvas ref={canvas} aria-hidden className="h-full max-w-full cursor-grab touch-none active:cursor-grabbing" style={{ aspectRatio: `${STAGE_W} / ${STAGE_H}` }} />+ </div>;+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/SegmentedChoice.tsx b/jarvis/ui/web/frontend/src/components/society/companion/SegmentedChoice.tsxnew file mode 100644index 0000000000..4c11cdcf8c--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/SegmentedChoice.tsx@@ -0,0 +1,22 @@+/**+ * One of a few choices as a single switch across the full width: the look+ * editor's rows (look, eyes, accessory slot) all read and click alike.+ */+export function SegmentedChoice<T extends string>({ options, value, onChange, label, role = "group", marked }: {+ options: readonly { id: T; label: string }[]; value: T; onChange: (next: T) => void;+ /** What the row chooses, for assistive technology. */+ label: string;+ /** "tablist" when the choice swaps the panel below it. */+ role?: "group" | "tablist";+ /** Choices that carry a small dot (a slot that already wears something). */+ marked?: ReadonlySet<T>;+}) {+ return <div className="flex gap-1 rounded-lg border border-border p-1" role={role} aria-label={label}>+ {options.map(option => <button key={option.id} type="button" onClick={() => onChange(option.id)}+ {...(role === "tablist" ? { role: "tab", "aria-selected": value === option.id } : { "aria-pressed": value === option.id })}+ className={`min-w-0 flex-1 truncate rounded-md px-3 py-1.5 text-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${value === option.id ? "bg-secondary text-foreground" : "text-muted-foreground hover:bg-secondary hover:text-foreground"}`}>+ {option.label}+ {marked?.has(option.id) && <span aria-hidden className="ml-1.5 inline-block h-1.5 w-1.5 rounded-full bg-current align-middle" />}+ </button>)}+ </div>;+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/ShapeFigure.tsx b/jarvis/ui/web/frontend/src/components/society/companion/ShapeFigure.tsxnew file mode 100644index 0000000000..48bfef4272--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/ShapeFigure.tsx@@ -0,0 +1,68 @@+import { useCallback, useLayoutEffect, useRef, useState, useSyncExternalStore, type ReactNode } from "react";+import { figureKey, type FigureLook } from "./figureScene";+import { FIGURE_BROKEN, figuresSupported, readFigure, watchFigure, watchFigureSupport, type Figure } from "./figureStore";++/** True while agent shapes can be drawn as 3D figures here; re-renders when that changes. */+export function useFiguresSupported(): boolean {+ return useSyncExternalStore(watchFigureSupport, figuresSupported, () => false);+}++/** The widest picture a face asks for, device pixels. */+const MAX_PIXELS = 288;++/** Device pixels for a face `size` CSS pixels wide: twice at least, so an enlarged window stays crisp. */+function figurePixels(size: number): number {+ const ratio = typeof window === "undefined" ? 2 : Math.max(2, Math.min(window.devicePixelRatio || 1, 3));+ return Math.max(8, Math.min(MAX_PIXELS, Math.round(size * ratio)));+}++/**+ * An agent's shape as a 3D figure, `size` pixels wide. The picture is drawn+ * once by the figure worker and painted into a plain 2D canvas; until it is+ * there the box is empty at its final size, and while a changed look is on+ * its way the previous picture stays. `children` is drawn over the eyes, in+ * the flat symbol's own units (a face with moving eyes). A look that cannot+ * be drawn shows `fallback` instead.+ */+export function ShapeFigure({ look, size, shape, behind, children, overlay, fallback }: {+ look: FigureLook; size: number;+ /** Shown when this look could not be drawn and no earlier picture is there. */+ fallback: ReactNode;+ /** For `data-agent-figure`: what tests and styles tell figures apart by. */+ shape: string;+ /** Drawn behind the picture (a glow). */+ behind?: ReactNode;+ /** Drawn over the picture, unscaled (glints around the figure). */+ overlay?: ReactNode;+ children?: ReactNode;+}) {+ const pixels = figurePixels(size);+ const key = figureKey(look, pixels);+ const subscribe = useCallback((listener: () => void) => watchFigure(look, pixels, listener),+ // eslint-disable-next-line react-hooks/exhaustive-deps -- the key names the look and the size+ [key]);+ const answer = useSyncExternalStore(subscribe, () => readFigure(look, pixels), () => undefined);+ const figure = answer === FIGURE_BROKEN ? undefined : answer;+ // The last picture stays while the next one is drawn.+ const [last, setLast] = useState<Figure | undefined>(figure);+ if (figure && figure !== last) setLast(figure);+ const shown = figure ?? last;+ const canvas = useRef<HTMLCanvasElement>(null);+ useLayoutEffect(() => {+ const node = canvas.current;+ if (!node || !shown) return;+ if (node.width !== shown.pixels) { node.width = shown.pixels; node.height = shown.pixels; }+ // Painted on the CPU like the pixel creatures: many small GPU canvases can hold the UI thread.+ const context = node.getContext("2d", { willReadFrequently: true });+ context?.putImageData(new ImageData(shown.data, shown.pixels, shown.pixels), 0, 0);+ }, [shown]);+ if (answer === FIGURE_BROKEN && !shown) return <>{fallback}</>;+ return <span className="society-agent-figure" data-agent-figure={shape} data-ready={shown ? "true" : undefined} style={{ width: size, height: size }}>+ {behind}+ <canvas ref={canvas} aria-hidden />+ {shown && children && <svg aria-hidden focusable="false" viewBox={`0 0 ${shown.pixels} ${shown.pixels}`} className="society-agent-symbol" data-expressive="true">+ <g transform={`matrix(${shown.face.map(value => +value.toFixed(4)).join(" ")})`}>{children}</g>+ </svg>}+ {shown && overlay}+ </span>;+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/appearance.ts b/jarvis/ui/web/frontend/src/components/society/companion/appearance.tsindex 73e395e799..7a969eaf7e 100644--- a/jarvis/ui/web/frontend/src/components/society/companion/appearance.ts+++ b/jarvis/ui/web/frontend/src/components/society/companion/appearance.ts@@ -1,5 +1,6 @@import { z } from "zod";import { ACCESSORY_SLOTS, type AccessoryChoice } from "./accessories";+import { creatureSchema } from "./creature";import { skinSchema } from "./skins";export const COMPANION_SHAPES = ["circle", "squircle", "pill", "triangle", "hexagon", "cloud", "drop"] as const;@@ -26,6 +27,11 @@ export const companionSchema = z.object({pet: z.string().regex(PET_ID).optional(),// A colour design (gradient + effect) worn instead of the flat colour; see skins.ts.skin: skinSchema.optional(),+ // A pixel creature worn instead of the shape; see creature.ts.+ creature: creatureSchema.optional(),+ // The agent explicitly wears its shape. Without it (and without a creature or a+ // pet) a look shows the creature grown from its shape; see creatureDefault.ts.+ look: z.literal("shape").optional(),// Accept earlier saved slider values, but every presentation uses one scale.sizeM: z.number().finite().min(0.25).max(0.8).default(COMPANION_SIZE_M).transform(() => COMPANION_SIZE_M),followDistanceM: z.number().finite().min(0.5).max(2).default(COMPANION_FOLLOW_DISTANCE_M).transform(() => COMPANION_FOLLOW_DISTANCE_M),diff --git a/jarvis/ui/web/frontend/src/components/society/companion/creature.test.ts b/jarvis/ui/web/frontend/src/components/society/companion/creature.test.tsnew file mode 100644index 0000000000..9192c96b71--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/creature.test.ts@@ -0,0 +1,98 @@+import { describe, expect, it } from "vitest";+import {+ composeCreature, creatureBody, creatureColor, creatureCubes, creatureFromShape, creaturePose, creatureSchema,+ CREATURE_PALETTES, CREATURE_STATES, CREATURE_STILL_FRAME, GRID, growCreature, nearestPalette,+ STAGE_H, STAGE_W, STAGE_X, STAGE_Y,+} from "./creature";++const SEEDS = [0, 1, 5, 24, 4711, 99_999];++describe("growing a pixel creature", () => {+ it("gives the same mirrored figure for the same number, with a full middle", () => {+ for (const seed of SEEDS) {+ const cells = growCreature(seed);+ expect(cells).toEqual(growCreature(seed));+ expect(cells).toHaveLength(GRID);+ for (const row of cells) expect(row).toEqual([...row].reverse());+ for (let r = 2; r <= 6; r++) for (let c = 2; c <= 6; c++) expect(cells[r]![c]).toBe(true);+ }+ expect(growCreature(5)).not.toEqual(growCreature(24));+ });++ it("never leaves an ornament or a leg floating", () => {+ for (let seed = 0; seed < 200; seed++) {+ const cells = growCreature(seed);+ for (let c = 0; c < GRID; c++) {+ if (cells[0]![c]) expect(cells[1]![c]).toBe(true);+ if (cells[1]![c]) expect(cells[2]![c]).toBe(true);+ if (cells[7]![c]) expect(cells[6]![c]).toBe(true);+ if (cells[8]![c]) expect(cells[7]![c]).toBe(true);+ }+ }+ });++ it("builds a solid block three cubes deep with the face on its front", () => {+ const body = creatureBody({ seed: 24, palette: "neon", eyes: "dot" });+ const cubes = creatureCubes(body, creaturePose("idle", 5));+ const filled = body.cells.flat().filter(Boolean).length;+ expect(cubes).toHaveLength(filled * 3);+ const ink = cubes.filter((cube) => cube.color === body.palette.ink);+ expect(ink).toHaveLength(2);+ expect(ink.every((cube) => cube.z === 1)).toBe(true);+ });++ it("wears the first colour world and dot eyes for ids it does not know", () => {+ const body = creatureBody({ seed: 3, palette: "futureworld", eyes: "futureeyes" });+ expect(body.palette.id).toBe(CREATURE_PALETTES[0]!.id);+ expect(body.eyes).toBe("dot");+ });+});++describe("what a creature acts out", () => {+ it("keeps every sign and spark of every state inside the stage", () => {+ for (const state of CREATURE_STATES) for (let frame = 0; frame < 120; frame++) {+ for (const bit of creaturePose(state, frame).bits) {+ expect(bit.x).toBeGreaterThanOrEqual(-STAGE_X);+ expect(bit.x).toBeLessThan(STAGE_W - STAGE_X);+ expect(bit.y).toBeGreaterThanOrEqual(-STAGE_Y);+ expect(bit.y).toBeLessThan(STAGE_H - STAGE_Y);+ }+ }+ });++ it("gives each state its own still frame", () => {+ const stills = CREATURE_STATES.map((state) => JSON.stringify(creaturePose(state, CREATURE_STILL_FRAME[state])));+ expect(new Set(stills).size).toBe(CREATURE_STATES.length);+ });++ it("rests most of the time: an idle creature only blinks and glances", () => {+ const poses = new Set(Array.from({ length: 60 }, (_, frame) => JSON.stringify(creaturePose("idle", frame))));+ expect(poses.size).toBe(4);+ });++ it("draws the face on the body in every state, on every eye kind", () => {+ for (const eyes of ["dot", "tall", "wide", "visor"]) for (const state of CREATURE_STATES) {+ const body = creatureBody({ seed: 24, palette: "ocean", eyes });+ const cells = [...composeCreature(body, creaturePose(state, CREATURE_STILL_FRAME[state])).values()];+ expect(cells.some((cell) => cell.front !== null)).toBe(true);+ }+ });+});++describe("a creature for an agent that never chose one", () => {+ const shape = { shape: "drop", color: "#1174da", eyes: "dots", accessories: { head: "crown" } };++ it("is the same on every surface and passes the stored contract", () => {+ const creature = creatureFromShape(shape);+ expect(creature).toEqual(creatureFromShape({ ...shape, color: "#1174DA" }));+ expect(creatureSchema.safeParse(creature).success).toBe(true);+ expect(creature.eyes).toBe("dot");+ expect(creatureFromShape({ ...shape, shape: "cloud" }).seed).not.toBe(creature.seed);+ });++ it("lands in the colour world nearest the agent's own colour", () => {+ expect(nearestPalette("#029858")).toBe("moss");+ expect(nearestPalette("#dd2233")).toBe("lava");+ expect(creatureColor({ seed: 1, palette: "gold", eyes: "dot" })).toBe("#ffcd61");+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/companion/creature.ts b/jarvis/ui/web/frontend/src/components/society/companion/creature.tsnew file mode 100644index 0000000000..adde09a95e--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/creature.ts@@ -0,0 +1,456 @@+/**+ * A pixel creature: an agent face grown from three stored values (a number, a+ * colour world, an eye kind). The number seeds a mirrored 9 x 9 grid whose+ * middle is always filled, so every roll reads as a figure; the eyes sit in+ * the same cells on every creature, so each state plays on every shape.+ *+ * Everything here is pure: the grid, the poses of each state and the cubes+ * the painters draw. `creaturePaint.ts` draws them on a 2D canvas for the+ * profile faces, `CreatureModel.tsx` builds them for the Verse.+ */+import { z } from "zod";++export type Rgb = readonly [number, number, number];++function hexRgb(hex: string): Rgb {+ const n = parseInt(hex.slice(1), 16);+ return [n >> 16, (n >> 8) & 255, n & 255];+}++export function mixRgb(a: Rgb, b: Rgb, t: number): Rgb {+ return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];+}++const DARK_INK = "#15151d";++/** A colour world: three stops from the head down, and the ink of the face. */+export interface CreaturePalette {+ id: string;+ colors: readonly [string, string, string];+ rgb: readonly [Rgb, Rgb, Rgb];+ ink: Rgb;+}++function palette(id: string, top: string, middle: string, bottom: string, ink = DARK_INK): CreaturePalette {+ return { id, colors: [top, middle, bottom], rgb: [hexRgb(top), hexRgb(middle), hexRgb(bottom)], ink: hexRgb(ink) };+}++export const CREATURE_PALETTES: readonly CreaturePalette[] = [+ palette("lava", "#ffe45c", "#ff8a3c", "#ff3d6e"),+ palette("ocean", "#5ef2d6", "#2a9dff", "#5a48f0"),+ palette("neon", "#ff5fd2", "#a25bff", "#3fc8ff"),+ palette("moss", "#e2ff5a", "#4fdc7a", "#0c9c8c"),+ palette("glacier", "#d4f6ff", "#6fbcff", "#3d5fe0"),+ palette("gold", "#fff0a6", "#ffcd61", "#f08a2c"),+ palette("candy", "#ffc6ec", "#ff86b6", "#ff5a6e"),+ palette("midnight", "#8f9bff", "#5546d6", "#2a1e78", "#f1f3ff"),+];++export const CREATURE_EYES = ["dot", "tall", "wide", "visor"] as const;+export type CreatureEyes = typeof CREATURE_EYES[number];++export const CREATURE_SEED_MAX = 99_999;++/** `CompanionCreature` in `jarvis/society/companion.py` (a parity test pins the palette and eye ids). Ids stay open, so a newer catalog never invalidates a saved look. */+export const creatureSchema = z.object({+ seed: z.number().int().min(0).max(CREATURE_SEED_MAX),+ palette: z.string().regex(/^[a-z]{1,20}$/),+ eyes: z.string().regex(/^[a-z]{1,20}$/),+}).strict();+export type CreatureLook = z.infer<typeof creatureSchema>;++/** What a creature can act out; every surface maps its own vocabulary onto these. */+export const CREATURE_STATES = ["idle", "listening", "thinking", "working", "talking", "asking", "success", "error", "sleeping"] as const;+export type CreatureState = typeof CREATURE_STATES[number];++/** An unknown colour world (a look saved by a newer build) wears the first one. */+export function creaturePalette(id: string): CreaturePalette {+ return CREATURE_PALETTES.find((entry) => entry.id === id) ?? CREATURE_PALETTES[0]!;+}++function creatureEyes(id: string): CreatureEyes {+ return (CREATURE_EYES as readonly string[]).includes(id) ? id as CreatureEyes : "dot";+}++/** The creature a new agent starts with: any figure, any colour world, any eyes. */+export function randomCreature(random: () => number = Math.random): CreatureLook {+ const pick = <T>(list: readonly T[]): T => list[Math.floor(random() * list.length)]!;+ return { seed: Math.floor(random() * (CREATURE_SEED_MAX + 1)), palette: pick(CREATURE_PALETTES).id, eyes: pick(CREATURE_EYES) };+}++/** The one colour a surface that knows no gradient (a chat bubble) uses for this creature. */+export function creatureColor(creature: CreatureLook): string {+ return creaturePalette(creature.palette).colors[1];+}++function textHash(text: string): number {+ let hash = 2166136261;+ for (const character of text) hash = Math.imul(hash ^ character.charCodeAt(0), 16777619) >>> 0;+ return hash;+}++/** The colour world closest to a plain colour, by its nearest stop. */+export function nearestPalette(color: string): string {+ const [r, g, b] = hexRgb(color);+ let best = CREATURE_PALETTES[0]!.id;+ let bestDistance = Infinity;+ for (const entry of CREATURE_PALETTES) for (const stop of entry.rgb) {+ const distance = (stop[0] - r) ** 2 + (stop[1] - g) ** 2 + (stop[2] - b) ** 2;+ if (distance < bestDistance) { bestDistance = distance; best = entry.id; }+ }+ return best;+}++/**+ * The creature an agent gets before anyone chose one: grown from its shape+ * look, so the same look gives the same creature on every surface, in the+ * colour world nearest its own colour.+ */+export function creatureFromShape(look: { shape: string; color: string; eyes: string; accessories?: Record<string, string> }): CreatureLook {+ const worn = Object.entries(look.accessories ?? {}).sort(([a], [b]) => a.localeCompare(b)).map((pair) => pair.join("=")).join(",");+ return {+ seed: textHash(`creature:${look.shape}:${look.color.toLowerCase()}:${look.eyes}:${worn}`) % (CREATURE_SEED_MAX + 1),+ palette: nearestPalette(look.color),+ eyes: look.eyes === "dots" ? "dot" : "tall",+ };+}++/* ---------- Growing the grid from one number ---------- */++export const GRID = 9;+const HALF = 5;+const ROWS = [0, 1, 2, 3, 4, 5, 6, 7, 8] as const;++function mulberry(seed: number): () => number {+ let a = seed >>> 0;+ return () => {+ a = (a + 0x6D2B79F5) >>> 0;+ let t = a;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++/** Chance of a filled cell, left half only (column 4 is the mirror axis): ornament, body, legs. */+const ODDS: readonly (readonly number[])[] = [+ [0, .22, .3, .18, .3], [.08, .45, .6, .5, .6], [.2, .8, 1, 1, 1], [.55, 1, 1, 1, 1], [.6, 1, 1, 1, 1],+ [.55, 1, 1, 1, 1], [.25, .85, 1, 1, 1], [.15, .6, .7, .45, .6], [.08, .4, .45, .25, .3],+];++/** The filled cells of a seed, rows top to bottom. Ornaments and legs only grow from a filled neighbour. */+export function growCreature(seed: number): boolean[][] {+ const next = mulberry(seed);+ const half = ODDS.map((row) => row.map((odds) => next() < odds));+ for (let r = 2; r <= 6; r++) half[r]![0] = half[r]![0]! && half[r]![1]!;+ for (let c = 0; c < HALF; c++) {+ half[1]![c] = half[1]![c]! && half[2]![c]!;+ half[0]![c] = half[0]![c]! && half[1]![c]!;+ half[7]![c] = half[7]![c]! && half[6]![c]!;+ half[8]![c] = half[8]![c]! && half[7]![c]!;+ }+ return half.map((row) => ROWS.map((c) => row[c < HALF ? c : GRID - 1 - c]!));+}++/** A creature ready to draw: its cells and the colour of each row. */+export interface CreatureBody {+ key: string;+ seed: number;+ palette: CreaturePalette;+ eyes: CreatureEyes;+ cells: boolean[][];+ rows: Rgb[];+ /** First and last row that holds a cell. */+ top: number;+ bottom: number;+}++const BODIES = new Map<string, CreatureBody>();+/** The picker rolls many seeds; the cache forgets them all once it grows past this. */+const BODY_CACHE = 256;++export function creatureBody(look: CreatureLook): CreatureBody {+ const key = `${look.seed}|${look.palette}|${look.eyes}`;+ const cached = BODIES.get(key);+ if (cached) return cached;+ const cells = growCreature(look.seed);+ const pal = creaturePalette(look.palette);+ const rows = ROWS.map((r) => {+ const t = r / (GRID - 1);+ return t < .5 ? mixRgb(pal.rgb[0], pal.rgb[1], t * 2) : mixRgb(pal.rgb[1], pal.rgb[2], (t - .5) * 2);+ });+ const filled = ROWS.filter((r) => cells[r]!.some(Boolean));+ const body: CreatureBody = {+ key, seed: look.seed, palette: pal, eyes: creatureEyes(look.eyes), cells, rows,+ top: filled[0]!, bottom: filled[filled.length - 1]!,+ };+ if (BODIES.size >= BODY_CACHE) BODIES.clear();+ BODIES.set(key, body);+ return body;+}++/* ---------- Poses: what one frame of a state looks like ---------- */++/** One animation frame lasts this long: whole cells at ten frames a second. */+export const CREATURE_TICK_MS = 100;++/**+ * The stage around the 9 x 9 grid, in cells: two spare columns on each side+ * and one spare row above and below, where signs and sparks play. The grid+ * itself starts at (STAGE_X, STAGE_Y).+ */+export const STAGE_W = 13;+export const STAGE_H = 11;+export const STAGE_X = 2;+export const STAGE_Y = 1;++export const SIGN_AMBER: Rgb = [255, 176, 32];+export const SIGN_GREEN: Rgb = [34, 197, 94];+export const SIGN_RED: Rgb = [255, 61, 84];++/** A loose cell beside the body, in grid coordinates: a palette stop or its own colour. */+export interface CreatureBit {+ x: number;+ y: number;+ color: 0 | 1 | 2 | Rgb;+ alpha: number;+}++export interface CreaturePose {+ dx: number;+ dy: number;+ /** Shifts the upper half sideways: a tilted head. */+ head: number;+ /** Drops the upper rows one cell: a landing, or a slow breath. */+ squash: boolean;+ eyes: "open" | "shut" | "wide" | "flat" | "happy";+ ex: number;+ ey: number;+ mouth: 0 | 1 | 2;+ /** 0..1 towards the error red. */+ tint: number;+ /** 0..1 towards a pale, sleeping body. */+ dim: number;+ /** The row a light wave is passing, or -1. */+ sweep: number;+ /** 0..1 strength of the ring around the body. */+ halo: number;+ bits: CreatureBit[];+}++const GLYPHS = {+ question: ["##.", "..#", ".#.", "...", ".#."],+ bang: ["##", "##", "##", "..", "##"],+ check: ["..#", "#.#", ".#."],+ z: ["###", ".#.", "###"],+} as const;++function stamp(bits: CreatureBit[], glyph: keyof typeof GLYPHS, x: number, y: number, color: CreatureBit["color"], alpha = 1): void {+ GLYPHS[glyph].forEach((row, j) => [...row].forEach((mark, i) => { if (mark === "#") bits.push({ x: x + i, y: y + j, color, alpha }); }));+}++const CONFETTI: readonly (readonly [number, number, 0 | 1 | 2])[] = [[-1.2, -.9, 0], [-.6, -1.3, 2], [.5, -1.4, 1], [1.1, -1, 0], [-1.6, -.3, 1], [1.6, -.4, 2]];+const SPARK_PATH: readonly (readonly [number, number, number])[] = [[-1, 8, 1], [-2, 7, 1], [-2, 6, .7], [-2, 5, .4]];++export function creaturePose(state: CreatureState, frame: number): CreaturePose {+ const f = Math.max(0, Math.floor(frame));+ const p: CreaturePose = { dx: 0, dy: 0, head: 0, squash: false, eyes: "open", ex: 0, ey: 0, mouth: 0, tint: 0, dim: 0, sweep: -1, halo: 0, bits: [] };+ switch (state) {+ case "idle": {+ const k = f % 60;+ if (k < 2) p.eyes = "shut"; else if (k >= 26 && k < 32) p.ex = -1; else if (k >= 36 && k < 42) p.ex = 1;+ break;+ }+ case "listening":+ p.eyes = "wide";+ p.halo = [.15, .35, .6, .8, .6, .35][Math.floor(f / 2) % 6]!;+ break;+ case "thinking": {+ p.ey = -1;+ p.ex = Math.floor(f / 14) % 2 ? 1 : -1;+ const wave = f % 16;+ if (wave < GRID) p.sweep = wave;+ // A thought trail beside the head: a dot, a second one, then the bubble.+ const k = Math.floor(f / 4) % 4;+ if (k >= 1) p.bits.push({ x: 9, y: 3, color: 1, alpha: 1 });+ if (k >= 2) p.bits.push({ x: 10, y: 2, color: 1, alpha: 1 });+ if (k >= 3) for (const [x, y] of [[9, -1], [10, -1], [9, 0], [10, 0]]) p.bits.push({ x: x!, y: y!, color: 1, alpha: 1 });+ break;+ }+ case "working": {+ p.dy = [0, 0, -1, -1][f % 4]!;+ p.ey = 1;+ const spark = SPARK_PATH[f % 6];+ if (spark) {+ const [x, y, alpha] = spark;+ p.bits.push({ x, y, color: 0, alpha }, { x: GRID - 1 - x, y, color: 0, alpha });+ }+ break;+ }+ case "talking": {+ p.mouth = ([0, 2, 1, 2, 0, 1, 2, 2, 1, 0, 2, 1] as const)[f % 12]!;+ const height = [1, 3, 2, 3, 1, 2][f % 6]!;+ for (const x of [-2, 10]) for (let i = 0; i < height; i++) p.bits.push({ x, y: 5 - Math.floor(height / 2) + i, color: 1, alpha: 1 });+ break;+ }+ case "asking":+ // Away from the sign, so the question mark never touches the head.+ p.head = -(Math.floor(f / 12) % 2);+ if (f % 10 < 8) stamp(p.bits, "question", 8, -1, SIGN_AMBER);+ break;+ case "success": {+ const k = f % 26;+ if (k < 6) p.dy = [0, -1, -1, -1, -1, 0][k]!;+ p.squash = k === 6 || k === 7;+ p.eyes = "happy";+ if (k >= 2) stamp(p.bits, "check", 8, -1, SIGN_GREEN);+ if (k >= 2 && k < 12) {+ const t = k - 2;+ for (const [vx, vy, color] of CONFETTI) {+ const x = Math.round(4 + vx * t), y = Math.round(1 + vy * t + .13 * t * t);+ if (x >= -STAGE_X && x < STAGE_W - STAGE_X && y >= -STAGE_Y && y < STAGE_H - STAGE_Y) p.bits.push({ x, y, color, alpha: 1 - t / 11 });+ }+ }+ break;+ }+ case "error": {+ const k = f % 22;+ if (k < 6) { p.dx = k % 2 ? -1 : 1; p.tint = .6; } else p.tint = .18;+ p.eyes = "flat";+ if (f % 6 < 4) stamp(p.bits, "bang", 9, -1, SIGN_RED);+ break;+ }+ case "sleeping": {+ p.dim = .55;+ p.eyes = "shut";+ p.squash = Math.floor(f / 16) % 2 === 1;+ const g = Math.floor(f / 5) % 8;+ if (g === 1 || g === 2) stamp(p.bits, "z", 8, 0, 1, g === 1 ? .6 : 1);+ if (g === 3 || g === 4) stamp(p.bits, "z", 8, -1, 1, g === 3 ? 1 : .45);+ break;+ }+ }+ return p;+}++/** One representative frame per state, for people who asked for less motion. */+export const CREATURE_STILL_FRAME: Readonly<Record<CreatureState, number>> = {+ idle: 5, listening: 6, thinking: 12, working: 1, talking: 1, asking: 0, success: 8, error: 7, sleeping: 10,+};++/** Eye cells per kind as [row, column]; the lower row is the one a lid closes. */+const EYE_CELLS: Readonly<Record<CreatureEyes, readonly (readonly [number, number])[]>> = {+ dot: [[4, 3], [4, 5]],+ tall: [[3, 3], [4, 3], [3, 5], [4, 5]],+ wide: [[4, 2], [4, 6]],+ visor: [[4, 2], [4, 3], [4, 4], [4, 5], [4, 6]],+};++type Cell = readonly [number, number];++function face(kind: CreatureEyes, p: CreaturePose): { ink: Cell[]; lid: Cell[] } {+ const base = EYE_CELLS[kind];+ const low = base.filter(([r]) => r === 4);+ let ink: Cell[] = [];+ let lid: Cell[] = [];+ if (p.eyes === "shut") lid = low;+ else if (p.eyes === "wide") ink = [...base, ...base.map(([r, c]) => [r - 1, c] as const)];+ else if (p.eyes === "flat") ink = kind === "visor" ? [...base] : low.flatMap(([r, c]) => [[r, c], [r, c < 4 ? c - 1 : c + 1]] as const);+ else if (p.eyes === "happy") ink = [...low.map(([, c]) => [3, c] as const), [5, 3], [6, 4], [5, 5]];+ else ink = base.map(([r, c]) => [r + p.ey, c + p.ex] as const);+ if (p.mouth === 1) ink.push([6, 4]);+ if (p.mouth === 2) ink.push([6, 3], [6, 4], [6, 5]);+ return { ink, lid };+}++/** A body cell after the pose moved it. `front` marks the cells the face paints. */+export interface PosedCell {+ x: number;+ y: number;+ /** The grid row it came from, which sets its colour. */+ row: number;+ front: "ink" | "lid" | null;+}++export function composeCreature(body: CreatureBody, p: CreaturePose): Map<string, PosedCell> {+ const map = new Map<string, PosedCell>();+ const X = (r: number, c: number) => c + p.dx + (r <= 4 ? p.head : 0);+ const Y = (r: number) => r + p.dy + (p.squash && r <= 3 ? 1 : 0);+ for (let r = 0; r < GRID; r++) for (let c = 0; c < GRID; c++) {+ if (!body.cells[r]![c]) continue;+ const x = X(r, c), y = Y(r);+ map.set(`${x},${y}`, { x, y, row: r, front: null });+ }+ const drawn = face(body.eyes, p);+ for (const [kind, list] of [["lid", drawn.lid], ["ink", drawn.ink]] as const) for (const [r, c] of list) {+ const cell = map.get(`${X(r, c)},${Y(r)}`);+ if (cell) cell.front = kind;+ }+ return map;+}++/** The empty cells that touch the body: where the listening ring lights up. */+export function creatureRim(cells: Map<string, PosedCell>): Cell[] {+ const out = new Map<string, Cell>();+ for (const cell of cells.values()) for (const [dx, dy] of [[0, -1], [0, 1], [-1, 0], [1, 0]] as const) {+ const key = `${cell.x + dx},${cell.y + dy}`;+ if (!cells.has(key)) out.set(key, [cell.x + dx, cell.y + dy]);+ }+ return [...out.values()];+}++const WHITE: Rgb = [255, 255, 255];+const BLACK: Rgb = [0, 0, 0];+const SLEEP: Rgb = [44, 44, 62];++export function creatureRowColor(body: CreatureBody, row: number, p: CreaturePose): Rgb {+ let color = body.rows[row]!;+ if (p.sweep >= 0) {+ const distance = Math.abs(row - p.sweep);+ if (distance < 2) color = mixRgb(color, WHITE, distance === 0 ? .55 : .22);+ }+ if (p.tint) color = mixRgb(color, SIGN_RED, p.tint);+ if (p.dim) {+ const grey = color[0] * .3 + color[1] * .59 + color[2] * .11;+ color = mixRgb(mixRgb(color, [grey, grey, grey], p.dim * .7), SLEEP, p.dim * .45);+ }+ return color;+}++/** One cube of a creature, in cells: x to the right, y down from the top row, z towards the viewer. */+export interface CreatureCube {+ x: number;+ y: number;+ z: number;+ color: Rgb;+ alpha: number;+}++/** How many cubes a creature reaches to the front and to the back of its middle layer. */+export const CREATURE_DEPTH = 1;++/**+ * The cubes of one pose: every cell is a column three cubes deep, so the+ * figure is a solid block with a flat front, and the face on that front+ * reads as clearly as on a flat sprite.+ */+export function creatureCubes(body: CreatureBody, p: CreaturePose): CreatureCube[] {+ const cells = composeCreature(body, p);+ const cubes: CreatureCube[] = [];+ for (const cell of cells.values()) {+ const color = creatureRowColor(body, cell.row, p);+ for (let z = -CREATURE_DEPTH; z <= CREATURE_DEPTH; z++) {+ const front = z === CREATURE_DEPTH ? cell.front : null;+ cubes.push({ x: cell.x, y: cell.y, z, alpha: 1, color: front === "ink" ? body.palette.ink : front === "lid" ? mixRgb(color, BLACK, .4) : color });+ }+ }+ if (p.halo) {+ const ring = mixRgb(body.palette.rgb[0], WHITE, .55);+ for (const [x, y] of creatureRim(cells)) cubes.push({ x, y, z: 0, color: ring, alpha: p.halo * .6 });+ }+ return cubes;+}++export function creatureBitColor(body: CreatureBody, bit: CreatureBit): Rgb {+ return typeof bit.color === "number" ? body.palette.rgb[bit.color] : bit.color;+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/creatureDefault.ts b/jarvis/ui/web/frontend/src/components/society/companion/creatureDefault.tsnew file mode 100644index 0000000000..4e62d0284c--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/creatureDefault.ts@@ -0,0 +1,56 @@+/**+ * Which face an agent shows when nobody picked one for it. By default that is+ * a pixel creature grown from its shape and colour, so a roster of agents+ * that were created with shapes reads as creatures without anyone editing+ * them. An agent that explicitly wears its shape (`look: "shape"`), a+ * creature of its own or a pet is never touched.+ *+ * The switch is a presentation choice of this device, like the companion's+ * visibility: it lives in local storage and changes no agent.+ */+import { useMemo } from "react";+import { create } from "zustand";+import type { CompanionAppearance } from "./appearance";+import { creatureFromShape, type CreatureLook } from "./creature";++const STORAGE_KEY = "jarvis.companion.creatures-by-default.v1";++function readEnabled(): boolean {+ try { return localStorage.getItem(STORAGE_KEY) !== "false"; }+ catch { return true; } // Storage can be unavailable in private browser profiles.+}++export const useCreatureDefault = create<{ enabled: boolean; setEnabled: (enabled: boolean) => void }>((set) => ({+ enabled: readEnabled(),+ setEnabled: (enabled) => {+ try { localStorage.setItem(STORAGE_KEY, String(enabled)); }+ catch { /* The open windows keep the in-memory choice. */ }+ set({ enabled });+ },+}));++// Another window of the app flipped the switch: follow it.+if (typeof window !== "undefined") {+ window.addEventListener("storage", (event) => {+ if (event.key === STORAGE_KEY) useCreatureDefault.setState({ enabled: event.newValue !== "false" });+ });+}++/** Whether a look without a creature of its own is drawn as one grown from its shape. */+export function growsCreature(appearance: Pick<CompanionAppearance, "creature" | "look">, enabled: boolean): boolean {+ return !appearance.creature && enabled && appearance.look !== "shape";+}++/**+ * The creature a surface draws for this look, or undefined when it draws the+ * shape: the one the agent wears, or the one grown from its shape. A worn pet+ * always wins; the pet surfaces decide that themselves.+ */+export function useShownCreature(appearance: CompanionAppearance): CreatureLook | undefined {+ const enabled = useCreatureDefault((state) => state.enabled);+ const { creature, look, shape, color, eyes, accessories } = appearance;+ return useMemo(+ () => creature ?? (growsCreature({ creature, look }, enabled) ? creatureFromShape({ shape, color, eyes, accessories }) : undefined),+ [creature, look, enabled, shape, color, eyes, accessories],+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/creaturePaint.ts b/jarvis/ui/web/frontend/src/components/society/companion/creaturePaint.tsnew file mode 100644index 0000000000..96d22bb586--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/creaturePaint.ts@@ -0,0 +1,114 @@+/**+ * Paints a pixel creature as small cubes on a 2D canvas: a profile face with+ * depth, without WebGL. The cubes are turned a little to the side and seen+ * slightly from above, lit from the front and painted back to front. A+ * roster of faces costs a few hundred filled quads each, and only when a+ * face actually changes.+ */+import {+ creatureBitColor, creatureCubes, mixRgb, STAGE_H, STAGE_W, STAGE_X, STAGE_Y,+ type CreatureBody, type CreaturePose, type Rgb,+} from "./creature";++/** How far a profile face is turned, radians: enough to show one side of the block. */+export const FACE_YAW = -0.34;+/** The share of its square a full 9 x 9 figure fills, leaving the air a shape symbol has. */+const FACE_FILL = 0.88;+/** How far the viewer looks down on it, radians. */+const PITCH = 0.34;++const WHITE: Rgb = [255, 255, 255];+const BLACK: Rgb = [0, 0, 0];++function css(color: Rgb, alpha = 1): string {+ return `rgba(${color[0] | 0},${color[1] | 0},${color[2] | 0},${alpha})`;+}++interface CubeFace {+ normal: readonly [number, number, number];+ corners: readonly (readonly [number, number, number])[];+}++const CUBE_FACES: CubeFace[] = [];+for (const axis of [0, 1, 2]) for (const sign of [1, -1]) {+ const normal: [number, number, number] = [0, 0, 0];+ normal[axis] = sign;+ const [a, b] = [0, 1, 2].filter((index) => index !== axis) as [number, number];+ const corners = ([[-.5, -.5], [.5, -.5], [.5, .5], [-.5, .5]] as const).map(([s, t]) => {+ const corner: [number, number, number] = [0, 0, 0];+ corner[axis] = sign * .5;+ corner[a] = s;+ corner[b] = t;+ return corner;+ });+ CUBE_FACES.push({ normal, corners });+}++interface Quad {+ points: [number, number][];+ depth: number;+ alpha: number;+ color: string;+}++/**+ * Draws one pose into a canvas `width` pixels wide that shows the whole+ * stage (STAGE_W x STAGE_H cells). The figure is centred on its own rows,+ * so a creature without legs or ornaments does not sit off-centre.+ */+export function paintCreature(ctx: CanvasRenderingContext2D, width: number, body: CreatureBody, pose: CreaturePose, yaw: number = FACE_YAW): void {+ const unit = width / STAGE_W, scale = unit * FACE_FILL;+ ctx.clearRect(0, 0, width, Math.round(unit * STAGE_H));+ const cubes = creatureCubes(body, pose);+ const taken = new Set<string>();+ for (const cube of cubes) if (cube.alpha === 1) taken.add(`${cube.x},${cube.y},${cube.z}`);+ const cy = Math.cos(yaw), sy = Math.sin(yaw), cp = Math.cos(PITCH), sp = Math.sin(PITCH);+ const lift = (body.top + body.bottom) / 2 - 4;+ const ox = (STAGE_X + 4.5) * unit, oy = (STAGE_Y + 4.5) * unit;+ const quads: Quad[] = [];+ for (const cube of cubes) {+ const X = cube.x - 4, Y = 4 + lift - cube.y;+ for (const side of CUBE_FACES) {+ // The pose uses y downwards, the cube faces y upwards.+ if (cube.alpha === 1 && taken.has(`${cube.x + side.normal[0]},${cube.y - side.normal[1]},${cube.z + side.normal[2]}`)) continue;+ const turned = -side.normal[0] * sy + side.normal[2] * cy;+ const ny = side.normal[1] * cp - turned * sp, nz = side.normal[1] * sp + turned * cp;+ if (nz <= .01) continue;+ let depth = 0;+ const points = side.corners.map(([a, b, c]): [number, number] => {+ const x = X + a, y = Y + b, z = cube.z + c, x1 = x * cy + z * sy, z1 = -x * sy + z * cy;+ depth += y * sp + z1 * cp;+ return [ox + x1 * scale, oy - (y * cp - z1 * sp) * scale];+ });+ const light = .7 + .3 * nz + .3 * Math.max(0, ny);+ quads.push({ points, depth, alpha: cube.alpha, color: css(light <= 1 ? mixRgb(BLACK, cube.color, light) : mixRgb(cube.color, WHITE, (light - 1) * 1.5)) });+ }+ }+ quads.sort((a, b) => a.depth - b.depth);+ // Every solid face reaches a little past its edges, which closes the seams+ // between neighbours for the price of one fill (a stroke would double the work).+ const overlap = Math.max(.5, scale * .02);+ for (const quad of quads) {+ const grow = quad.alpha === 1 ? overlap : 0;+ const cx = (quad.points[0]![0] + quad.points[2]![0]) / 2, cy = (quad.points[0]![1] + quad.points[2]![1]) / 2;+ ctx.globalAlpha = quad.alpha;+ ctx.fillStyle = quad.color;+ ctx.beginPath();+ for (let i = 0; i < 4; i++) {+ const dx = quad.points[i]![0] - cx, dy = quad.points[i]![1] - cy;+ const reach = grow / (Math.hypot(dx, dy) || 1);+ const x = quad.points[i]![0] + dx * reach, y = quad.points[i]![1] + dy * reach;+ if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);+ }+ ctx.closePath();+ ctx.fill();+ }+ // Signs and sparks stay flat and upright: they are read, not looked at.+ for (const bit of pose.bits) {+ const x0 = Math.round((STAGE_X + bit.x) * unit), y0 = Math.round((STAGE_Y + bit.y) * unit);+ ctx.globalAlpha = bit.alpha;+ ctx.fillStyle = css(creatureBitColor(body, bit));+ ctx.fillRect(x0, y0, Math.round((STAGE_X + bit.x + 1) * unit) - x0, Math.round((STAGE_Y + bit.y + 1) * unit) - y0);+ }+ ctx.globalAlpha = 1;+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/figure.worker.ts b/jarvis/ui/web/frontend/src/components/society/companion/figure.worker.tsnew file mode 100644index 0000000000..76e4e2f3e2--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/figure.worker.ts@@ -0,0 +1,93 @@+/**+ * Draws 3D profile faces off the UI thread: reads the companion models once,+ * traces a figure per shape, outfit and size, and shades it in the asked+ * colours. Traces are kept, so another colour on the same figure is only+ * the cheap half of the work. Terminating the worker releases everything.+ */+import { meshesByName, readGlb, type FigureMesh } from "./figureGlb";+import { shadeFigure, traceFigure, type FigureTrace } from "./figureRender";+import { figureFaceMatrix, figureParts, figureTraceKey, wearsAccessories, type FigureLook } from "./figureScene";++export interface FigureRequest {+ id: number;+ look: FigureLook;+ /** Width and height of the picture, device pixels. */+ pixels: number;+ /** Absolute URLs of companions.glb and accessories.glb. */+ bodies: string;+ worn: string;+}++export type FigureResponse =+ | { id: number; ok: true; pixels: number; data: ArrayBuffer; face: [number, number, number, number, number, number] }+ | { id: number; ok: false };++type Meshes = Map<string, FigureMesh[]>;++const files = new Map<string, Promise<Meshes>>();++function load(url: string): Promise<Meshes> {+ let file = files.get(url);+ if (!file) {+ file = fetch(url).then(async response => {+ if (!response.ok) throw new Error(`HTTP ${response.status}`);+ return meshesByName(readGlb(await response.arrayBuffer()));+ });+ files.set(url, file);+ // A failed download is tried again with the next picture.+ file.catch(() => files.delete(url));+ }+ return file;+}++/** The most trace memory kept, bytes: ten bytes per sample. */+const TRACE_BUDGET = 40 * 1024 * 1024;+const traces = new Map<string, FigureTrace>();+let traceBytes = 0;++function traceSize(trace: FigureTrace): number {+ return trace.depth.byteLength + trace.normal.byteLength + trace.owner.byteLength + trace.light.byteLength + trace.open.byteLength;+}++function remember(key: string, trace: FigureTrace): void {+ traces.set(key, trace);+ traceBytes += traceSize(trace);+ // Oldest first: a Map keeps insertion order, and a hit is moved to the end.+ for (const [old, value] of traces) {+ if (traceBytes <= TRACE_BUDGET || old === key) break;+ traces.delete(old);+ traceBytes -= traceSize(value);+ }+}++async function draw(request: FigureRequest): Promise<FigureResponse> {+ const { look, pixels } = request;+ const bodies = await load(request.bodies);+ const worn = wearsAccessories(look) ? await load(request.worn) : undefined;+ const parts = figureParts(look, bodies, worn);+ const key = figureTraceKey(look, pixels);+ let trace = traces.get(key);+ if (trace) { traces.delete(key); traces.set(key, trace); }+ else { trace = traceFigure(parts, pixels); remember(key, trace); }+ const image = shadeFigure(trace, parts);+ return { id: request.id, ok: true, pixels, data: image.data.buffer as ArrayBuffer, face: figureFaceMatrix(look, bodies, image.frame) };+}++// One picture at a time, in the order asked.+let chain: Promise<void> = Promise.resolve();++self.onmessage = (event: MessageEvent<FigureRequest>) => {+ const request = event.data;+ chain = chain.then(async () => {+ let answer: FigureResponse;+ try {+ answer = await draw(request);+ } catch (error) {+ // The face falls back to the flat symbol; the reason stays readable in the console.+ console.warn("Companion figure unavailable", error);+ answer = { id: request.id, ok: false };+ }+ if (answer.ok) (self as unknown as { postMessage: (message: FigureResponse, transfer: Transferable[]) => void }).postMessage(answer, [answer.data]);+ else self.postMessage(answer);+ });+};diff --git a/jarvis/ui/web/frontend/src/components/society/companion/figureGlb.ts b/jarvis/ui/web/frontend/src/components/society/companion/figureGlb.tsnew file mode 100644index 0000000000..e717d84cf5--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/figureGlb.ts@@ -0,0 +1,111 @@+/**+ * Reads the companion models (companions.glb, accessories.glb) without a 3D+ * library: binary glTF holding plain triangle meshes with positions, normals+ * and indices, no textures, no compression and no node transforms. The+ * profile faces draw these meshes on the CPU (figureRender.ts), so a roster+ * needs neither WebGL nor the map's renderer.+ */++/** Linear red, green and blue, 0 to 1. */+export type LinearRgb = [number, number, number];++export interface FigureMaterial {+ name: string;+ color: LinearRgb;+ roughness: number;+ /** Emits its own light (an ember, a lamp): drawn unlit and bright. */+ glow: boolean;+}++export interface FigureMesh {+ /** The node that carries the mesh, for example `squircle.Body` or `acc_cap`. */+ name: string;+ positions: Float32Array;+ normals: Float32Array;+ indices: Uint16Array | Uint32Array;+ material: FigureMaterial;+}++const GLB_MAGIC = 0x46546c67;+const CHUNK_JSON = 0x4e4f534a;+const CHUNK_BIN = 0x004e4942;+const FLOAT = 5126, UNSIGNED_SHORT = 5123, UNSIGNED_INT = 5125;++interface GltfAccessor { bufferView: number; byteOffset?: number; componentType: number; count: number; type: string }+interface GltfView { byteOffset?: number; byteLength: number; byteStride?: number }+interface GltfJson {+ accessors: GltfAccessor[];+ bufferViews: GltfView[];+ nodes: { name?: string; mesh?: number }[];+ meshes: { primitives: { attributes: Record<string, number>; indices?: number; material?: number; mode?: number }[] }[];+ materials?: { name?: string; emissiveFactor?: number[]; pbrMetallicRoughness?: { baseColorFactor?: number[]; roughnessFactor?: number } }[];+}++/** Every mesh of a binary glTF file, one entry per primitive, named after its node. */+export function readGlb(file: ArrayBuffer): FigureMesh[] {+ const view = new DataView(file);+ if (view.byteLength < 20 || view.getUint32(0, true) !== GLB_MAGIC) throw new Error("Not a binary glTF file");+ let json: GltfJson | undefined;+ let binStart = -1;+ for (let offset = 12; offset + 8 <= view.byteLength;) {+ const length = view.getUint32(offset, true), type = view.getUint32(offset + 4, true);+ if (type === CHUNK_JSON) json = JSON.parse(new TextDecoder().decode(new Uint8Array(file, offset + 8, length))) as GltfJson;+ if (type === CHUNK_BIN) binStart = offset + 8;+ offset += 8 + length;+ }+ if (!json || binStart < 0) throw new Error("Binary glTF without a mesh buffer");+ const gltf = json;++ const read = (index: number, parts: number): Float32Array | Uint16Array | Uint32Array => {+ const accessor = gltf.accessors[index];+ const span = accessor && gltf.bufferViews[accessor.bufferView];+ if (!accessor || !span || span.byteStride) throw new Error("Unsupported glTF accessor");+ const start = binStart + (span.byteOffset ?? 0) + (accessor.byteOffset ?? 0);+ const length = accessor.count * parts;+ const Kind = accessor.componentType === FLOAT ? Float32Array : accessor.componentType === UNSIGNED_SHORT ? Uint16Array+ : accessor.componentType === UNSIGNED_INT ? Uint32Array : undefined;+ if (!Kind) throw new Error("Unsupported glTF component type");+ // A typed array must start on a multiple of its element size; copy when the file does not.+ return start % Kind.BYTES_PER_ELEMENT === 0 ? new Kind(file, start, length)+ : new Kind(file.slice(start, start + length * Kind.BYTES_PER_ELEMENT));+ };++ const materials: FigureMaterial[] = (gltf.materials ?? []).map(material => {+ const base = material.pbrMetallicRoughness?.baseColorFactor ?? [1, 1, 1];+ return {+ name: material.name ?? "",+ color: [base[0] ?? 1, base[1] ?? 1, base[2] ?? 1],+ roughness: material.pbrMetallicRoughness?.roughnessFactor ?? 1,+ glow: (material.emissiveFactor ?? []).some(value => value > 0),+ };+ });+ const plain: FigureMaterial = { name: "", color: [1, 1, 1], roughness: 1, glow: false };++ const meshes: FigureMesh[] = [];+ for (const node of gltf.nodes) {+ const mesh = node.mesh === undefined ? undefined : gltf.meshes[node.mesh];+ if (!mesh) continue;+ for (const primitive of mesh.primitives) {+ const { POSITION, NORMAL } = primitive.attributes;+ if ((primitive.mode ?? 4) !== 4 || POSITION === undefined || NORMAL === undefined || primitive.indices === undefined) continue;+ meshes.push({+ name: node.name ?? "",+ positions: read(POSITION, 3) as Float32Array,+ normals: read(NORMAL, 3) as Float32Array,+ indices: read(primitive.indices, 1) as Uint16Array | Uint32Array,+ material: (primitive.material === undefined ? undefined : materials[primitive.material]) ?? plain,+ });+ }+ }+ return meshes;+}++/** The meshes of one file, by node name. */+export function meshesByName(meshes: readonly FigureMesh[]): Map<string, FigureMesh[]> {+ const byName = new Map<string, FigureMesh[]>();+ for (const mesh of meshes) {+ const list = byName.get(mesh.name);+ if (list) list.push(mesh); else byName.set(mesh.name, [mesh]);+ }+ return byName;+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/figureRender.test.ts b/jarvis/ui/web/frontend/src/components/society/companion/figureRender.test.tsnew file mode 100644index 0000000000..4389ff793b--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/figureRender.test.ts@@ -0,0 +1,107 @@+// @vitest-environment node+import fs from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";+import { ACCESSORY_CATALOG, ACCESSORY_ITEMS } from "./accessories";+import { COMPANION_SHAPES } from "./appearance";+import { meshesByName, readGlb } from "./figureGlb";+import { renderFigure, shadeFigure, traceFigure } from "./figureRender";+import { figureFaceMatrix, figureKey, figureParts, figureTraceKey, type FigureLook } from "./figureScene";++const ASSETS = path.resolve(__dirname, "../../../assets/society/companions");+function load(name: string) {+ const file = fs.readFileSync(path.join(ASSETS, name));+ return meshesByName(readGlb(file.buffer.slice(file.byteOffset, file.byteOffset + file.byteLength) as ArrayBuffer));+}+const bodies = load("companions.glb");+const worn = load("accessories.glb");+const look = (extra: Partial<FigureLook> = {}): FigureLook => ({ shape: "squircle", color: "#00a591", eyes: "lines", accessories: {}, ...extra });+const pixel = (image: { size: number; data: Uint8ClampedArray }, x: number, y: number) => {+ const at = (Math.round(y) * image.size + Math.round(x)) * 4;+ return [image.data[at]!, image.data[at + 1]!, image.data[at + 2]!, image.data[at + 3]!] as const;+};++describe("companion models", () => {+ it.each(COMPANION_SHAPES)("holds a body and both eye kinds for %s", shape => {+ expect(bodies.get(`${shape}.Body`)?.length).toBeGreaterThan(0);+ for (const kind of ["Dots", "Lines"]) for (const side of [0, 1]) expect(bodies.get(`${shape}.${kind}.${side}`)?.length).toBe(1);+ });++ it("holds every catalog item for every shape", () => {+ for (const item of ACCESSORY_ITEMS) for (const shape of COMPANION_SHAPES) {+ const meshes = [worn.get(`acc_${item.id}__${shape}__fit`), worn.get(`acc_${item.id}`), worn.get(`acc_${item.id}__${shape}`)];+ expect(meshes.some(Boolean), `${item.id} on ${shape}`).toBe(true);+ }+ });++ it("refuses a file that is not binary glTF", () => {+ expect(() => readGlb(new ArrayBuffer(64))).toThrow();+ });+});++describe("3D profile faces", () => {+ it.each(COMPANION_SHAPES)("draws %s inside its square, in its own colour", shape => {+ const image = renderFigure(figureParts(look({ shape }), bodies), 48);+ let solid = 0;+ for (let y = 0; y < 48; y++) for (let x = 0; x < 48; x++) {+ const [, , , alpha] = pixel(image, x, y);+ if (alpha > 200) solid++;+ // The figure never touches the edge; only its faint shadow may reach it.+ if (x === 0 || y === 0 || x === 47 || y === 47) expect(alpha).toBeLessThan(120);+ }+ expect(solid).toBeGreaterThan(48 * 48 * 0.2);+ // Teal body: green leads, red trails, wherever the middle of the body is lit.+ const meta = ACCESSORY_CATALOG.shapes[shape];+ const [a, b, c, d, e, f] = figureFaceMatrix(look({ shape }), bodies, image.frame);+ const [red, green, , alpha] = pixel(image, a * 20 + c * (meta.eyeY + 5) + e, b * 20 + d * (meta.eyeY + 5) + f);+ expect(alpha).toBe(255);+ expect(green).toBeGreaterThan(red + 40);+ });++ it("puts the ink eyes where the face matrix says, and leaves them out for a blind figure", () => {+ const seeing = look(), image = renderFigure(figureParts(seeing, bodies), 96);+ const [a, b, c, d, e, f] = figureFaceMatrix(seeing, bodies, image.frame);+ const eyeY = ACCESSORY_CATALOG.shapes.squircle.eyeY;+ for (const eyeX of [15.4, 24.6]) {+ const [red, green, blue] = pixel(image, a * eyeX + c * eyeY + e, b * eyeX + d * eyeY + f);+ expect(Math.max(red, green, blue)).toBeLessThan(60);+ }+ const blind = renderFigure(figureParts(look({ blind: true }), bodies), 96);+ const [, green] = pixel(blind, a * 15.4 + c * eyeY + e, b * 15.4 + d * eyeY + f);+ expect(green).toBeGreaterThan(100);+ });++ it("shades one trace in any colour without changing its outline", () => {+ const teal = figureParts(look(), bodies), red = figureParts(look({ color: "#dd2233" }), bodies);+ const trace = traceFigure(teal, 40);+ const first = shadeFigure(trace, teal), second = shadeFigure(trace, red);+ const mid = (40 * 24 + 16) * 4;+ expect(first.data[mid + 1]).toBeGreaterThan(first.data[mid]!);+ expect(second.data[mid]).toBeGreaterThan(second.data[mid + 1]!);+ for (let at = 3; at < first.data.length; at += 4) expect(second.data[at]).toBe(first.data[at]);+ expect(figureTraceKey(look(), 40)).toBe(figureTraceKey(look({ color: "#dd2233" }), 40));+ expect(figureKey(look(), 40)).not.toBe(figureKey(look({ color: "#dd2233" }), 40));+ });++ it("makes room for what the figure wears", () => {+ const bare = renderFigure(figureParts(look(), bodies, worn), 64);+ const hat = renderFigure(figureParts(look({ accessories: { head: "top_hat" } }), bodies, worn), 64);+ // A tall hat shrinks the body instead of leaving the picture.+ expect(hat.frame.k).toBeLessThan(bare.frame.k);+ for (let x = 0; x < 64; x++) expect(pixel(hat, x, 0)[3]).toBeLessThan(120);+ });++ it("paints a colour design across the body", () => {+ const skin = { colors: ["#ff0000", "#0000ff"], radial: false, angle: 180, effect: 0, highlight: "#ff0000" };+ const image = renderFigure(figureParts(look({ skin }), bodies), 64);+ const [a, b, c, d, e, f] = figureFaceMatrix(look(), bodies, image.frame);+ const top = pixel(image, a * 20 + c * 9 + e, b * 20 + d * 9 + f), bottom = pixel(image, a * 20 + c * 31 + e, b * 20 + d * 31 + f);+ // 180 degrees runs from the top (first colour) to the bottom (last colour).+ expect(top[0]).toBeGreaterThan(top[2]);+ expect(bottom[2]).toBeGreaterThan(bottom[0]);+ });++ it("draws nothing for an empty figure", () => {+ expect(renderFigure([], 16).data.every(value => value === 0)).toBe(true);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/companion/figureRender.ts b/jarvis/ui/web/frontend/src/components/society/companion/figureRender.tsnew file mode 100644index 0000000000..c31ca9a48d--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/figureRender.ts@@ -0,0 +1,443 @@+/**+ * Draws an agent's shape as a small 3D figure on the CPU: the same meshes+ * the map uses, turned a little to the side, lit from the upper left and+ * set on a soft ground shadow. The result is a plain RGBA image, so a profile+ * face is real 3D without a WebGL context. Everything here is pure; the+ * worker (figure.worker.ts) calls it off the UI thread.+ *+ * The work is split in two. `traceFigure` finds what every sample sees (the+ * surface, its normal, how much light and sky reach it); that depends only on+ * the meshes and the size. `shadeFigure` turns it into colours, which is+ * cheap, so trying another colour on the same figure costs almost nothing.+ */+import type { FigureMesh, LinearRgb } from "./figureGlb";++/** How far a figure is turned, radians: the same turn a pixel creature has. */+export const FIGURE_YAW = -0.34;+/** How far the viewer looks down on it, radians. */+export const FIGURE_PITCH = 0.3;++/** A colour design over a part; the layout matches the map's body material (skinMaterial.ts). */+export interface FigurePaint {+ colors: LinearRgb[];+ radial: boolean;+ /** CSS angle, degrees (0 = up, 90 = right). */+ angle: number;+ /** Index in SKIN_EFFECTS: none, stars, shimmer, flow, glow, sparkle. */+ effect: number;+ highlight: LinearRgb;+}++export interface FigurePart {+ mesh: FigureMesh;+ color: LinearRgb;+ /** "ink" (eyes) and "glow" (an ember) are drawn unlit. */+ finish: "matte" | "ink" | "glow";+ roughness: number;+ /** Where the mesh sits: model = offset + scale x position. */+ offset?: readonly [number, number, number];+ scale?: number;+ /** Wins against surfaces up to this far in front of it, metres (glasses over the eyes). */+ lift?: number;+ paint?: FigurePaint;+ /** Part of the body itself: the ground shadow follows its footprint. */+ body?: boolean;+}++/** What the look of one part adds to its traced surface. */+export type FigureCoat = Pick<FigurePart, "color" | "finish" | "roughness" | "paint">;++/** How model metres land on the image: `x = ox + xv * k`, `y = oy - yv * k` in view space. */+export interface FigureFrame { k: number; ox: number; oy: number; yaw: number; pitch: number }++export interface FigureImage {+ size: number;+ /** Straight-alpha RGBA, `size` x `size`. */+ data: Uint8ClampedArray;+ frame: FigureFrame;+}++/** Everything about a figure that does not depend on its colours. */+export interface FigureTrace {+ size: number;+ /** Samples per pixel along one axis. */+ samples: number;+ /** In samples, like the buffers below. */+ frame: FigureFrame;+ /** View depth of the nearest surface per sample. */+ depth: Float32Array;+ /** Its view-space normal, three signed bytes. */+ normal: Int8Array;+ /** Its part, counted from 1; 0 where nothing was hit. */+ owner: Uint8Array;+ /** How much of the key light reaches it, 0 to 255. */+ light: Uint8Array;+ /** How much of the sky it sees, 0 to 255. */+ open: Uint8Array;+ /** The body's box in model space: a colour design spans it. */+ box: { min: [number, number, number]; max: [number, number, number] };+ /** The body's footprint on the ground, model x and z; undefined when nothing stands. */+ foot?: { x: number; z: number; rx: number; rz: number };+}++/** Where a model point lands on an image with this frame, pixels. */+export function projectFigure(frame: FigureFrame, x: number, y: number, z: number): [number, number] {+ const cy = Math.cos(frame.yaw), sy = Math.sin(frame.yaw), cp = Math.cos(frame.pitch), sp = Math.sin(frame.pitch);+ const x1 = x * cy + z * sy, z1 = -x * sy + z * cy;+ return [frame.ox + x1 * frame.k, frame.oy - (y * cp - z1 * sp) * frame.k];+}++function normalize(x: number, y: number, z: number): [number, number, number] {+ const length = Math.hypot(x, y, z) || 1;+ return [x / length, y / length, z / length];+}++// View space: x to the right, y up, z toward the viewer.+const KEY = normalize(-0.5, 0.72, 0.5);+const FILL = normalize(0.75, 0.05, 0.6);+const RIM = normalize(0.6, 0.5, -0.6);+const HALF = normalize(KEY[0], KEY[1], KEY[2] + 1);+const KEY_COLOR: LinearRgb = [0.8, 0.77, 0.72];+const SKY: LinearRgb = [0.5, 0.53, 0.6];+const GROUND: LinearRgb = [0.25, 0.23, 0.23];+const FILL_COLOR: LinearRgb = [0.1, 0.12, 0.15];++/** The share of the image left free around the figure and its shadow. */+const PAD = 0.03;+const SHADOW_ALPHA = 0.3;+/** The shadow reaches this far past the footprint, in footprint radii. */+const SHADOW_REACH = 1.18;+/** It lies a little away from the light: this far along x and z, in footprint radii. */+const SHADOW_SHIFT_X = 0.16, SHADOW_SHIFT_Z = -0.1;++const AO_TAPS: readonly (readonly [number, number])[] = Array.from({ length: 10 }, (_, index) => {+ // A golden-angle spiral: even cover of the disc from few taps.+ const radius = Math.sqrt((index + 0.5) / 10), angle = index * 2.399963;+ return [Math.cos(angle) * radius, Math.sin(angle) * radius] as const;+});++function fract(value: number): number { return value - Math.floor(value); }+function hash(x: number, y: number, z: number): number { return fract(Math.sin(x * 127.1 + y * 311.7 + z * 74.7) * 43758.5453); }+function smooth(edge0: number, edge1: number, value: number): number {+ const t = Math.max(0, Math.min(1, (value - edge0) / (edge1 - edge0)));+ return t * t * (3 - 2 * t);+}++/** Bright specks scattered through the body's volume (stars, sparkles). */+function specks(x: number, y: number, z: number, cells: number, density: number): number {+ const qx = x * cells, qy = y * cells, qz = z * cells;+ const cx = Math.floor(qx), cy = Math.floor(qy), cz = Math.floor(qz);+ if (hash(cx, cy, cz) < 1 - density) return 0;+ const dx = qx - cx - 0.5 - (hash(cx + 1.7, cy + 1.7, cz + 1.7) - 0.5) * 0.5;+ const dy = qy - cy - 0.5 - (hash(cx + 4.3, cy + 4.3, cz + 4.3) - 0.5) * 0.5;+ const dz = qz - cz - 0.5 - (hash(cx + 8.9, cy + 8.9, cz + 8.9) - 0.5) * 0.5;+ return smooth(0.24, 0.02, Math.hypot(dx, dy, dz)) * 0.85;+}++function ramp(colors: readonly LinearRgb[], t: number, out: Float32Array): void {+ const at = Math.max(0, Math.min(1, t)) * (colors.length - 1);+ const index = Math.min(colors.length - 2, Math.floor(at)), mix = at - index;+ const a = colors[index]!, b = colors[index + 1]!;+ out[0] = a[0] + (b[0] - a[0]) * mix; out[1] = a[1] + (b[1] - a[1]) * mix; out[2] = a[2] + (b[2] - a[2]) * mix;+}++function ring(colors: readonly LinearRgb[], u: number, out: Float32Array): void {+ const at = fract(u) * colors.length;+ const index = Math.min(colors.length - 1, Math.floor(at)), mix = at - index;+ const a = colors[index]!, b = colors[(index + 1) % colors.length]!;+ out[0] = a[0] + (b[0] - a[0]) * mix; out[1] = a[1] + (b[1] - a[1]) * mix; out[2] = a[2] + (b[2] - a[2]) * mix;+}++const TO_SRGB = new Uint8Array(4097);+for (let i = 0; i <= 4096; i++) {+ const c = i / 4096;+ TO_SRGB[i] = Math.round(255 * (c <= 0.0031308 ? c * 12.92 : 1.055 * c ** (1 / 2.4) - 0.055));+}++/** Bright light rolls off softly instead of clipping to a flat patch. */+function shoulder(value: number): number {+ return value <= 0.8 ? value : 0.8 + 0.2 * Math.tanh((value - 0.8) / 0.2);+}++/**+ * Fills a depth buffer with the nearest surface per cell. `sx`, `sy` are+ * cell coordinates, `sz` grows toward the eye. With `shade`, the winning+ * triangle also leaves its interpolated normal and the part's number.+ */+export function rasterize(+ width: number, depth: Float32Array, indices: Uint16Array | Uint32Array, sx: Float32Array, sy: Float32Array, sz: Float32Array,+ shade?: { nx: Float32Array; ny: Float32Array; nz: Float32Array; id: number; normal: Int8Array; owner: Uint8Array },+): void {+ for (let t = 0; t < indices.length; t += 3) {+ const a = indices[t]!, b = indices[t + 1]!, c = indices[t + 2]!;+ const x0 = sx[a]!, y0 = sy[a]!, x1 = sx[b]!, y1 = sy[b]!, x2 = sx[c]!, y2 = sy[c]!;+ const area = (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0);+ if (area === 0) continue;+ const minX = Math.max(0, Math.floor(Math.min(x0, x1, x2))), maxX = Math.min(width - 1, Math.ceil(Math.max(x0, x1, x2)));+ const minY = Math.max(0, Math.floor(Math.min(y0, y1, y2))), maxY = Math.min(width - 1, Math.ceil(Math.max(y0, y1, y2)));+ if (minX > maxX || minY > maxY) continue;+ const inv = 1 / area, z0 = sz[a]!, z1 = sz[b]!, z2 = sz[c]!;+ const step0 = (y1 - y2) * inv, step1 = (y2 - y0) * inv;+ for (let py = minY; py <= maxY; py++) {+ const cy = py + 0.5, cx = minX + 0.5;+ let w0 = ((x1 - cx) * (y2 - cy) - (x2 - cx) * (y1 - cy)) * inv;+ let w1 = ((x2 - cx) * (y0 - cy) - (x0 - cx) * (y2 - cy)) * inv;+ let at = py * width + minX;+ for (let px = minX; px <= maxX; px++, at++, w0 += step0, w1 += step1) {+ const w2 = 1 - w0 - w1;+ if (w0 < -1e-4 || w1 < -1e-4 || w2 < -1e-4) continue;+ const z = w0 * z0 + w1 * z1 + w2 * z2;+ if (z <= depth[at]!) continue;+ depth[at] = z;+ if (!shade) continue;+ let nx = w0 * shade.nx[a]! + w1 * shade.nx[b]! + w2 * shade.nx[c]!;+ let ny = w0 * shade.ny[a]! + w1 * shade.ny[b]! + w2 * shade.ny[c]!;+ let nz = w0 * shade.nz[a]! + w1 * shade.nz[b]! + w2 * shade.nz[c]!;+ // A surface seen from behind (an open patch of cloth) is lit like its front.+ const scale = (nz < 0 ? -127 : 127) / (Math.hypot(nx, ny, nz) || 1);+ nx *= scale; ny *= scale; nz *= scale;+ shade.normal[at * 3] = Math.round(nx); shade.normal[at * 3 + 1] = Math.round(ny); shade.normal[at * 3 + 2] = Math.round(nz);+ shade.owner[at] = shade.id;+ }+ }+ }+}++/** The colour-independent half of a picture: see the file comment. */+export function traceFigure(parts: readonly Pick<FigurePart, "mesh" | "offset" | "scale" | "lift" | "body" | "finish">[], size: number, yaw: number = FIGURE_YAW, pitch: number = FIGURE_PITCH): FigureTrace {+ const cy = Math.cos(yaw), sy = Math.sin(yaw), cp = Math.cos(pitch), sp = Math.sin(pitch);+ // Small faces get more samples per pixel: their edges are most of the picture.+ const samples = size <= 48 ? 4 : size <= 110 ? 3 : 2;+ const width = Math.max(1, size) * samples, area = width * width;+ const trace: FigureTrace = {+ size, samples, frame: { k: 1, ox: 0, oy: 0, yaw, pitch },+ depth: new Float32Array(area).fill(-Infinity), normal: new Int8Array(area * 3), owner: new Uint8Array(area),+ light: new Uint8Array(area), open: new Uint8Array(area), box: { min: [0, 0, 0], max: [1, 1, 1] },+ };+ if (!parts.length || size < 1) return trace;++ // 1. Every vertex into view space; the bounds decide the framing.+ let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity, bodyTop = 0;+ const min: [number, number, number] = [Infinity, Infinity, Infinity], max: [number, number, number] = [-Infinity, -Infinity, -Infinity];+ const placed = parts.map(part => {+ const count = part.mesh.positions.length / 3;+ const out = {+ part, x: new Float32Array(count), y: new Float32Array(count), z: new Float32Array(count),+ nx: new Float32Array(count), ny: new Float32Array(count), nz: new Float32Array(count),+ };+ const scale = part.scale ?? 1, [dx, dy, dz] = part.offset ?? [0, 0, 0];+ const { positions, normals } = part.mesh;+ for (let i = 0; i < count; i++) {+ const mx = dx + positions[i * 3]! * scale, my = dy + positions[i * 3 + 1]! * scale, mz = dz + positions[i * 3 + 2]! * scale;+ const z1 = -mx * sy + mz * cy;+ const xv = mx * cy + mz * sy, yv = my * cp - z1 * sp;+ out.x[i] = xv; out.y[i] = yv; out.z[i] = my * sp + z1 * cp;+ if (xv < minX) minX = xv; if (xv > maxX) maxX = xv; if (yv < minY) minY = yv; if (yv > maxY) maxY = yv;+ const ax = normals[i * 3]!, ay = normals[i * 3 + 1]!, az = normals[i * 3 + 2]!;+ const nz1 = -ax * sy + az * cy;+ out.nx[i] = ax * cy + az * sy; out.ny[i] = ay * cp - nz1 * sp; out.nz[i] = ay * sp + nz1 * cp;+ if (part.body) {+ if (my > bodyTop) bodyTop = my;+ if (mx < min[0]) min[0] = mx; if (mx > max[0]) max[0] = mx;+ if (my < min[1]) min[1] = my; if (my > max[1]) max[1] = my;+ if (mz < min[2]) min[2] = mz; if (mz > max[2]) max[2] = mz;+ }+ }+ return out;+ });+ if (!(maxX > minX) || !(maxY > minY)) return trace;+ if (max[0] > min[0]) trace.box = { min, max };++ // What stands on the ground casts the shadow under it; the picture makes room for it.+ let footMinX = Infinity, footMaxX = -Infinity, footMinZ = Infinity, footMaxZ = -Infinity;+ for (const item of placed) {+ if (!item.part.body) continue;+ const scale = item.part.scale ?? 1, [dx, , dz] = item.part.offset ?? [0, 0, 0];+ const { positions } = item.part.mesh;+ for (let i = 0; i < positions.length; i += 3) {+ if (positions[i + 1]! * scale > bodyTop * 0.3) continue;+ const mx = dx + positions[i]! * scale, mz = dz + positions[i + 2]! * scale;+ if (mx < footMinX) footMinX = mx; if (mx > footMaxX) footMaxX = mx; if (mz < footMinZ) footMinZ = mz; if (mz > footMaxZ) footMaxZ = mz;+ }+ }+ if (sp > 0.05 && footMaxX > footMinX && footMaxZ > footMinZ) {+ const rx = (footMaxX - footMinX) / 2, rz = (footMaxZ - footMinZ) / 2;+ const foot = { x: (footMinX + footMaxX) / 2 + rx * SHADOW_SHIFT_X, z: (footMinZ + footMaxZ) / 2 + rz * SHADOW_SHIFT_Z, rx, rz };+ trace.foot = foot;+ // Only the dense middle of the shadow has to fit; its faint rim may leave the picture.+ for (let step = 0; step < 16; step++) {+ const angle = step / 16 * Math.PI * 2;+ const mx = foot.x + Math.cos(angle) * rx * 0.75, mz = foot.z + Math.sin(angle) * rz * 0.75;+ const z1 = -mx * sy + mz * cy;+ const xv = mx * cy + mz * sy, yv = -z1 * sp;+ if (xv < minX) minX = xv; if (xv > maxX) maxX = xv; if (yv < minY) minY = yv; if (yv > maxY) maxY = yv;+ }+ }++ const spanX = maxX - minX, spanY = maxY - minY, extent = Math.max(spanX, spanY);+ const k = width * (1 - 2 * PAD) / extent;+ const ox = width / 2 - (minX + maxX) / 2 * k, oy = width / 2 + (minY + maxY) / 2 * k;+ trace.frame = { k, ox, oy, yaw, pitch };++ // 2. The nearest surface per sample, with its normal and its part.+ const { depth, normal, owner, light, open } = trace;+ placed.forEach((item, index) => {+ if (index >= 255) return;+ const lift = item.part.lift ?? 0;+ rasterize(width, depth, item.part.mesh.indices, item.x.map(value => ox + value * k), item.y.map(value => oy - value * k), lift ? item.z.map(value => value + lift) : item.z,+ { nx: item.nx, ny: item.ny, nz: item.nz, id: index + 1, normal, owner });+ });++ // 3. The same scene seen from the key light: what it cannot see lies in shadow.+ const lx = normalize(KEY[2], 0, -KEY[0]);+ const ly: [number, number, number] = [KEY[1] * lx[2] - KEY[2] * lx[1], KEY[2] * lx[0] - KEY[0] * lx[2], KEY[0] * lx[1] - KEY[1] * lx[0]];+ let minU = Infinity, maxU = -Infinity, minV = Infinity, maxV = -Infinity;+ const lit = placed.map(item => {+ const count = item.x.length, u = new Float32Array(count), v = new Float32Array(count), d = new Float32Array(count);+ for (let i = 0; i < count; i++) {+ const x = item.x[i]!, y = item.y[i]!, z = item.z[i]!;+ const pu = x * lx[0] + y * lx[1] + z * lx[2], pv = x * ly[0] + y * ly[1] + z * ly[2];+ u[i] = pu; v[i] = pv; d[i] = x * KEY[0] + y * KEY[1] + z * KEY[2];+ if (pu < minU) minU = pu; if (pu > maxU) maxU = pu; if (pv < minV) minV = pv; if (pv > maxV) maxV = pv;+ }+ return { u, v, d };+ });+ const map = Math.min(width, 320);+ const mapScale = (map - 4) / Math.max(maxU - minU, maxV - minV);+ const lightDepth = new Float32Array(map * map).fill(-Infinity);+ placed.forEach((item, index) => {+ // Ink lies on the surface and casts nothing.+ if (item.part.finish === "ink") return;+ const { u, v, d } = lit[index]!;+ rasterize(map, lightDepth, item.part.mesh.indices, u.map(value => 2 + (value - minU) * mapScale), v.map(value => 2 + (value - minV) * mapScale), d);+ });+ const shadowBias = extent * 0.035;++ // 4. Per sample: how much key light arrives, and how much of the sky is in view.+ const aoRadius = width * 0.075, aoReach = extent * 0.16;+ for (let py = 0; py < width; py++) {+ for (let px = 0; px < width; px++) {+ const at = py * width + px;+ if (!owner[at]) continue;+ const zv = depth[at]!;+ const xv = (px + 0.5 - ox) / k, yv = (oy - py - 0.5) / k;+ const lu = 2 + (xv * lx[0] + yv * lx[1] + zv * lx[2] - minU) * mapScale;+ const lv = 2 + (xv * ly[0] + yv * ly[1] + zv * ly[2] - minV) * mapScale;+ const ld = xv * KEY[0] + yv * KEY[1] + zv * KEY[2] + shadowBias;+ let seen = 0;+ for (let tapY = -1; tapY <= 1; tapY++) for (let tapX = -1; tapX <= 1; tapX++) {+ const mu = Math.max(0, Math.min(map - 1, Math.round(lu + tapX * 1.4))), mv = Math.max(0, Math.min(map - 1, Math.round(lv + tapY * 1.4)));+ if (ld >= lightDepth[mv * map + mu]!) seen++;+ }+ light[at] = Math.round(seen / 9 * 255);++ // Ambient occlusion: nearby surface in front of this one darkens the crease.+ const nx = normal[at * 3]! / 127, ny = normal[at * 3 + 1]! / 127, nz = normal[at * 3 + 2]! / 127;+ let occluded = 0;+ const turn = hash(px, py, 1) * 6.2832, tc = Math.cos(turn), ts = Math.sin(turn);+ for (const [tapX, tapY] of AO_TAPS) {+ const ax = Math.round(px + (tapX * tc - tapY * ts) * aoRadius), ay = Math.round(py + (tapX * ts + tapY * tc) * aoRadius);+ if (ax < 0 || ay < 0 || ax >= width || ay >= width) continue;+ const other = ay * width + ax;+ if (!owner[other]) continue;+ const vx = (ax - px) / k, vy = (py - ay) / k, vz = depth[other]! - zv;+ const distance = Math.hypot(vx, vy, vz);+ if (distance < 1e-5 || distance > aoReach) continue;+ occluded += Math.max(0, (vx * nx + vy * ny + vz * nz) / distance - 0.18) * (1 - distance / aoReach);+ }+ open[at] = Math.round((1 - Math.min(0.7, occluded / AO_TAPS.length * 2.4)) * 255);+ }+ }+ return trace;+}++/** The colours of a traced figure: one coat per part, in the order the parts were traced. */+export function shadeFigure(trace: FigureTrace, coats: readonly FigureCoat[]): FigureImage {+ const { size, samples, depth, normal, owner, light, open, box, foot } = trace;+ const { k, ox, oy, yaw, pitch } = trace.frame;+ const cy = Math.cos(yaw), sy = Math.sin(yaw), cp = Math.cos(pitch), sp = Math.sin(pitch);+ const width = size * samples;+ const data = new Uint8ClampedArray(size * size * 4);+ const skin = new Float32Array(3);+ const boxX = Math.max(box.max[0] - box.min[0], 1e-4), boxY = Math.max(box.max[1] - box.min[1], 1e-4), boxZ = Math.max(box.max[2] - box.min[2], 1e-4);+ for (let oyPixel = 0; oyPixel < size; oyPixel++) {+ for (let oxPixel = 0; oxPixel < size; oxPixel++) {+ let sumR = 0, sumG = 0, sumB = 0, hits = 0;+ for (let subY = 0; subY < samples; subY++) {+ for (let subX = 0; subX < samples; subX++) {+ const px = oxPixel * samples + subX, py = oyPixel * samples + subY, at = py * width + px;+ const coat = coats[owner[at]! - 1];+ if (!coat) continue;+ let r: number, g: number, b: number;+ if (coat.finish === "ink") { r = coat.color[0]; g = coat.color[1]; b = coat.color[2]; }+ else if (coat.finish === "glow") { r = coat.color[0] * 1.7; g = coat.color[1] * 1.7; b = coat.color[2] * 1.7; }+ else {+ const nx = normal[at * 3]! / 127, ny = normal[at * 3 + 1]! / 127, nz = normal[at * 3 + 2]! / 127;+ const shadow = light[at]! / 255, ao = open[at]! / 255;+ let cr = coat.color[0], cg = coat.color[1], cb = coat.color[2];+ let er = 0, eg = 0, eb = 0;+ const paint = coat.paint;+ if (paint) {+ // Back from the sample to the body's own space, where the design is laid out.+ const xv = (px + 0.5 - ox) / k, yv = (oy - py - 0.5) / k, zv = depth[at]!;+ const z1 = -yv * sp + zv * cp, my = yv * cp + zv * sp;+ const mx = xv * cy - z1 * sy, mz = xv * sy + z1 * cy;+ const bx = (mx - box.min[0]) / boxX - 0.5, by = (my - box.min[1]) / boxY - 0.5, bz = (mz - box.min[2]) / boxZ - 0.5;+ const rad = paint.angle * Math.PI / 180;+ const along = paint.radial ? Math.hypot(bx + 0.12, by - 0.16, bz - 0.3) * 1.25 : bx * Math.sin(rad) + by * Math.cos(rad) + 0.5;+ if (paint.effect === 3) ring(paint.colors, along * 0.9, skin); else ramp(paint.colors, along, skin);+ cr = skin[0]!; cg = skin[1]!; cb = skin[2]!;+ if (paint.effect === 1) { const s = specks(bx, by, bz, 7, 0.3) * 2.2; er = s; eg = s; eb = s; }+ if (paint.effect === 2) { const band = Math.exp(-(((bx + by * 0.6 + 0.12) * 6) ** 2)) * 0.4; er = band; eg = band; eb = band; }+ if (paint.effect === 4) { er = paint.highlight[0] * 0.3; eg = paint.highlight[1] * 0.3; eb = paint.highlight[2] * 0.3; }+ if (paint.effect === 5) { const s = specks(bx, by, bz, 5, 0.18) * 2.2; er = paint.highlight[0] * s; eg = paint.highlight[1] * s; eb = paint.highlight[2] * s; }+ }+ const key = Math.max(0, Math.min(1, (nx * KEY[0] + ny * KEY[1] + nz * KEY[2] + 0.3) / 1.3)) * shadow;+ const sky = 0.5 + 0.5 * ny;+ const fill = Math.max(0, (nx * FILL[0] + ny * FILL[1] + nz * FILL[2] + 0.5) / 1.5);+ const lr = (GROUND[0] + (SKY[0] - GROUND[0]) * sky + FILL_COLOR[0] * fill) * ao + KEY_COLOR[0] * key;+ const lg = (GROUND[1] + (SKY[1] - GROUND[1]) * sky + FILL_COLOR[1] * fill) * ao + KEY_COLOR[1] * key;+ const lb = (GROUND[2] + (SKY[2] - GROUND[2]) * sky + FILL_COLOR[2] * fill) * ao + KEY_COLOR[2] * key;+ // A soft sheen: wide on a rough surface, tight on a glossy one.+ const rough = Math.max(0.2, Math.min(1, coat.roughness));+ const gloss = Math.max(0, nx * HALF[0] + ny * HALF[1] + nz * HALF[2]) ** (2 / (rough * rough * rough * rough) + 4);+ const sheen = gloss * Math.min(0.14, (1 - rough) * 0.4) * shadow;+ // A back light catches the far edge, so a dark body never sinks into a dark page.+ const edge = (1 - Math.min(1, nz)) ** 3 * Math.max(0, (nx * RIM[0] + ny * RIM[1] + nz * RIM[2]) * 0.5 + 0.5) * ao;+ r = cr * lr + er + sheen + (cr * 0.5 + 0.13) * edge * 0.9;+ g = cg * lg + eg + sheen + (cg * 0.5 + 0.13) * edge * 0.9;+ b = cb * lb + eb + sheen + (cb * 0.5 + 0.14) * edge * 0.9;+ }+ sumR += shoulder(r); sumG += shoulder(g); sumB += shoulder(b); hits++;+ }+ }+ const cover = hits / (samples * samples);+ let ground = 0;+ if (foot && cover < 1) {+ // Where this pixel's view ray meets the ground (model y = 0).+ const xv = ((oxPixel + 0.5) * samples - ox) / k, z1 = -((oy - (oyPixel + 0.5) * samples) / k) / sp;+ const qx = (xv * cy - z1 * sy - foot.x) / foot.rx, qz = (xv * sy + z1 * cy - foot.z) / foot.rz;+ ground = SHADOW_ALPHA * smooth(SHADOW_REACH, 0.3, Math.hypot(qx, qz)) * (1 - cover);+ }+ const alpha = cover + ground;+ if (alpha <= 0) continue;+ const out = (oyPixel * size + oxPixel) * 4;+ // The samples carry the figure's light; the shadow under it adds only darkness.+ const weight = 1 / (samples * samples * alpha);+ data[out] = TO_SRGB[Math.round(Math.max(0, Math.min(1, sumR * weight)) * 4096)]!;+ data[out + 1] = TO_SRGB[Math.round(Math.max(0, Math.min(1, sumG * weight)) * 4096)]!;+ data[out + 2] = TO_SRGB[Math.round(Math.max(0, Math.min(1, sumB * weight)) * 4096)]!;+ data[out + 3] = Math.round(alpha * 255);+ }+ }+ return { size, data, frame: { k: k / samples, ox: ox / samples, oy: oy / samples, yaw, pitch } };+}++/**+ * Renders the parts into a square image `size` pixels wide. The figure is+ * fitted into the square whatever it wears, so a tall hat makes the body a+ * little smaller instead of leaving the picture.+ */+export function renderFigure(parts: readonly FigurePart[], size: number, yaw?: number, pitch?: number): FigureImage {+ return shadeFigure(traceFigure(parts, size, yaw, pitch), parts);+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/figureScene.ts b/jarvis/ui/web/frontend/src/components/society/companion/figureScene.tsnew file mode 100644index 0000000000..319b29773e--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/figureScene.ts@@ -0,0 +1,125 @@+/**+ * Puts an agent's shape together for the CPU renderer (figureRender.ts):+ * the body, its eyes and whatever it wears, from the same meshes and the+ * same catalog the map companion uses (AgentFollower.tsx), so a profile+ * face and the figure on the map always show the same look.+ */+import { ACCESSORY_CATALOG, resolveFill, slotDepthM, wornAccessories, type AccessoryChoice } from "./accessories";+import type { SymbolShape } from "./appearance";+import type { FigureMesh, LinearRgb } from "./figureGlb";+import { projectFigure, type FigureFrame, type FigurePaint, type FigurePart } from "./figureRender";++/** Everything that decides what a figure looks like; plain data, so it can cross to a worker. */+export interface FigureLook {+ shape: SymbolShape;+ color: string;+ eyes: "dots" | "lines";+ accessories?: AccessoryChoice;+ /** A colour design, already resolved: its effect as an index in SKIN_EFFECTS. */+ skin?: { colors: string[]; radial: boolean; angle: number; effect: number; highlight: string };+ /** Leaves the eyes out, for a face that draws moving eyes on top. */+ blind?: boolean;+}++const INK: LinearRgb = [0.0052, 0.0052, 0.007];++/** A `#rrggbb` colour in linear light. */+export function linearRgb(hex: string): LinearRgb {+ const value = parseInt(hex.slice(1), 16);+ const channel = (shift: number) => {+ const c = ((value >> shift) & 255) / 255;+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;+ };+ return [channel(16), channel(8), channel(0)];+}++/**+ * An item worn on the face wins against the face within this depth, metres.+ * Glasses are wrapped onto each body, but an eye or a ridge of the body can+ * still reach through a lens; the flat symbol paints them over the eyes too.+ */+const FACE_LIFT_M = 0.08;++/** True when the look needs the accessory meshes as well as the bodies. */+export function wearsAccessories(look: FigureLook): boolean {+ return wornAccessories(look.accessories).length > 0;+}++/**+ * The parts of one figure. `bodies` are the meshes of companions.glb by+ * node name, `worn` those of accessories.glb (only read when something is+ * worn). An item the files do not know is skipped, like on the map.+ */+export function figureParts(look: FigureLook, bodies: ReadonlyMap<string, FigureMesh[]>, worn?: ReadonlyMap<string, FigureMesh[]>): FigurePart[] {+ const parts: FigurePart[] = [];+ const color = linearRgb(look.color);+ const paint: FigurePaint | undefined = look.skin && {+ colors: look.skin.colors.map(linearRgb), radial: look.skin.radial, angle: look.skin.angle,+ effect: look.skin.effect, highlight: linearRgb(look.skin.highlight),+ };+ for (const mesh of bodies.get(`${look.shape}.Body`) ?? []) {+ // A soft vinyl sheen lets the light show the volume; a shimmering design is glossier.+ parts.push({ mesh, color, finish: "matte", roughness: paint?.effect === 2 ? 0.38 : 0.62, paint, body: true });+ }+ const kind = look.eyes === "dots" ? "Dots" : "Lines";+ const eyes = [0, 1].flatMap(side => bodies.get(`${look.shape}.${kind}.${side}`) ?? []);+ if (!look.blind) for (const mesh of eyes) parts.push({ mesh, color: INK, finish: "ink", roughness: 1 });+ if (!worn) return parts;++ const meta = ACCESSORY_CATALOG.shapes[look.shape];+ const unit = 1 / (meta.bottom - meta.top);+ const add = (meshes: FigureMesh[] | undefined, lift: number, offset?: readonly [number, number, number], scale?: number) => {+ for (const mesh of meshes ?? []) {+ // A material named `acc:<token>` takes a tint of the agent's own colour.+ const token = mesh.material.name.split(":")[1] ?? "";+ parts.push({+ mesh, offset, scale, lift,+ color: token && !token.startsWith("#") ? linearRgb(resolveFill(token, look.color)) : mesh.material.color,+ finish: mesh.material.glow ? "glow" : "matte", roughness: mesh.material.roughness,+ });+ }+ };+ for (const item of wornAccessories(look.accessories)) {+ // Items worn on the body come pre-fitted to each silhouette's curved surface.+ const fitted = worn.get(`acc_${item.id}__${look.shape}__fit`);+ const lift = item.slot === "face" ? FACE_LIFT_M : 0;+ if (fitted) add(fitted, lift);+ else {+ const [x, y, k] = meta.anchors[item.slot];+ add(worn.get(`acc_${item.id}`), lift, [(x - 20) * unit, (meta.bottom - y) * unit, slotDepthM(look.shape, item.slot)], k * (item.scale ?? 1) * unit);+ }+ // Clothing is authored per silhouette, already in the body's frame.+ if (item.regions) add(worn.get(`acc_${item.id}__${look.shape}`), lift);+ }+ return parts;+}++/**+ * Where the eyes lie, as an SVG matrix from the flat symbol's units (40 wide,+ * eyes at the shape's `eyeY`) to the picture's pixels. A face that draws+ * moving eyes on top of a figure places them with it.+ */+export function figureFaceMatrix(look: FigureLook, bodies: ReadonlyMap<string, FigureMesh[]>, frame: FigureFrame): [number, number, number, number, number, number] {+ const meta = ACCESSORY_CATALOG.shapes[look.shape];+ const unit = 1 / (meta.bottom - meta.top);+ let depth = -Infinity;+ for (const side of [0, 1]) for (const mesh of bodies.get(`${look.shape}.${look.eyes === "dots" ? "Dots" : "Lines"}.${side}`) ?? []) {+ for (let i = 2; i < mesh.positions.length; i += 3) if (mesh.positions[i]! > depth) depth = mesh.positions[i]!;+ }+ if (!Number.isFinite(depth)) depth = slotDepthM(look.shape, "face");+ const at = (x: number, y: number) => projectFigure(frame, (x - 20) * unit, (meta.bottom - y) * unit, depth);+ const origin = at(0, 0), right = at(1, 0), down = at(0, 1);+ return [right[0] - origin[0], right[1] - origin[1], down[0] - origin[0], down[1] - origin[1], origin[0], origin[1]];+}++/** Names what a figure is made of, whatever its colours: equal keys trace alike. */+export function figureTraceKey(look: FigureLook, pixels: number): string {+ return `${look.shape}|${look.blind ? "blind" : look.eyes}|${wornAccessories(look.accessories).map(item => item.id).join(",")}|${pixels}`;+}++/** One line that names a look and a size: equal keys draw equal pictures. */+export function figureKey(look: FigureLook, pixels: number): string {+ const worn = wornAccessories(look.accessories).map(item => item.id).join(",");+ const skin = look.skin ? `${look.skin.colors.join("")}${look.skin.radial ? "r" : "l"}${look.skin.angle}e${look.skin.effect}` : "";+ return `${look.shape}|${look.color.toLowerCase()}|${look.blind ? "blind" : look.eyes}|${worn}|${skin}|${pixels}`;+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/figureStore.ts b/jarvis/ui/web/frontend/src/components/society/companion/figureStore.tsnew file mode 100644index 0000000000..bba4eb5245--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/figureStore.ts@@ -0,0 +1,193 @@+/**+ * The pictures of 3D profile faces, shared by every face on screen. A face+ * asks for its look at its size; the worker (figure.worker.ts) draws each+ * picture once and it is kept here, so a roster, a chat and a dialog showing+ * the same agent share one drawing. Without a worker (an old webview, a test+ * DOM) or after a failure, faces fall back to the flat symbol.+ */+import accessoryModels from "@/assets/society/companions/accessories.glb";+import companionModels from "@/assets/society/companions/companions.glb";+import type { FigureRequest, FigureResponse } from "./figure.worker";+import { figureKey, type FigureLook } from "./figureScene";++export interface Figure {+ /** Width and height, device pixels. */+ pixels: number;+ /** Straight-alpha RGBA. */+ data: Uint8ClampedArray<ArrayBuffer>;+ /** SVG matrix from flat symbol units to picture pixels, at the eyes (figureFaceMatrix). */+ face: [number, number, number, number, number, number];+}++/** The most picture memory kept, bytes. */+const PICTURE_BUDGET = 24 * 1024 * 1024;+/** A worker with nothing to draw is released after this long, milliseconds. */+const IDLE_MS = 45_000;+/** A picture that takes longer than this is given up, milliseconds. */+const ANSWER_MS = 30_000;+/** A picture that failed, or a worker that broke, is tried again after this long, milliseconds. */+const RETRY_MS = 60_000;+/** A worker that keeps breaking is left alone after this many tries. */+const WORKER_TRIES = 3;++/** What `readFigure` answers for a look that could not be drawn: the face shows its flat symbol. */+export const FIGURE_BROKEN = "broken";++const pictures = new Map<string, Figure>();+let pictureBytes = 0;+/** Looks that could not be drawn, with the time they failed. */+const broken = new Map<string, number>();+const wanted = new Map<string, { look: FigureLook; pixels: number; listeners: Set<() => void> }>();+const supportListeners = new Set<() => void>();+let worker: Worker | undefined;+let current: { id: number; key: string } | undefined;+let nextId = 1;+let failed = false;+let workerFailures = 0;+let idleTimer: ReturnType<typeof setTimeout> | undefined;+let answerTimer: ReturnType<typeof setTimeout> | undefined;++/** True while faces can be drawn in 3D here. */+export function figuresSupported(): boolean {+ return !failed && typeof Worker !== "undefined" && typeof ImageData !== "undefined";+}++export function watchFigureSupport(listener: () => void): () => void {+ supportListeners.add(listener);+ return () => { supportListeners.delete(listener); };+}++/** The finished picture of a look at a size, `FIGURE_BROKEN` if it could not be drawn, or nothing yet. */+export function readFigure(look: FigureLook, pixels: number): Figure | typeof FIGURE_BROKEN | undefined {+ const key = figureKey(look, pixels);+ return pictures.get(key) ?? (broken.has(key) ? FIGURE_BROKEN : undefined);+}++function release(): void {+ clearTimeout(idleTimer);+ clearTimeout(answerTimer);+ worker?.terminate();+ worker = undefined;+ current = undefined;+}++/**+ * The worker itself is unusable: every face falls back to the flat symbol.+ * A worker that broke while running (its script could not be fetched during+ * a restart, say) gets a few more tries later; one that cannot be built at+ * all (no module workers, a strict content policy) does not.+ */+function fail(retry: boolean): void {+ failed = true;+ release();+ const listeners = [...wanted.values()].flatMap(entry => [...entry.listeners]);+ wanted.clear();+ for (const listener of [...supportListeners, ...listeners]) listener();+ if (!retry || ++workerFailures >= WORKER_TRIES) return;+ setTimeout(() => {+ failed = false;+ supportListeners.forEach(listener => listener());+ }, RETRY_MS);+}++/** One look could not be drawn: its faces show the flat symbol, the others carry on. */+function giveUp(key: string): void {+ broken.set(key, Date.now());+ if (current?.key === key) current = undefined;+ const entry = wanted.get(key);+ wanted.delete(key);+ entry?.listeners.forEach(listener => listener());+ pump();+}++function keep(key: string, figure: Figure): void {+ pictures.set(key, figure);+ pictureBytes += figure.data.byteLength;+ // Oldest first; a Map keeps insertion order. A face that still shows an evicted picture keeps its own copy.+ for (const [old, value] of pictures) {+ if (pictureBytes <= PICTURE_BUDGET || old === key) break;+ pictures.delete(old);+ pictureBytes -= value.data.byteLength;+ }+}++function answer(message: FigureResponse): void {+ if (!current || message.id !== current.id) return;+ clearTimeout(answerTimer);+ const { key } = current;+ // The worker logged why; a failed download is tried again with the next look.+ if (!message.ok) { giveUp(key); return; }+ current = undefined;+ workerFailures = 0;+ keep(key, { pixels: message.pixels, data: new Uint8ClampedArray(message.data), face: message.face });+ const entry = wanted.get(key);+ wanted.delete(key);+ entry?.listeners.forEach(listener => listener());+ pump();+}++function pump(): void {+ if (current || failed) return;+ // The newest request first: what was asked last is what the person looks at now.+ let key: string | undefined;+ for (const candidate of wanted.keys()) key = candidate;+ if (key === undefined) {+ clearTimeout(idleTimer);+ idleTimer = setTimeout(release, IDLE_MS);+ return;+ }+ const asking = key;+ const entry = wanted.get(asking)!;+ clearTimeout(idleTimer);+ try {+ if (!worker) {+ worker = new Worker(new URL("./figure.worker.ts", import.meta.url), { type: "module" });+ worker.onmessage = (event: MessageEvent<FigureResponse>) => answer(event.data);+ worker.onerror = event => {+ console.warn("Companion figure worker failed", event.message);+ fail(true);+ };+ }+ const asked = current = { id: nextId++, key: asking };+ const request: FigureRequest = {+ id: asked.id, look: entry.look, pixels: entry.pixels,+ bodies: new URL(companionModels, location.href).href, worn: new URL(accessoryModels, location.href).href,+ };+ worker.postMessage(request);+ answerTimer = setTimeout(() => {+ if (current !== asked) return;+ // A stuck worker is replaced; only this look is given up.+ console.warn("Companion figure took too long", asking);+ release();+ giveUp(asking);+ }, ANSWER_MS);+ } catch (error) {+ // No worker here (a strict content policy, an old webview): the flat symbol stays.+ console.warn("Companion figures unavailable", error);+ fail(false);+ }+}++/**+ * Asks for a picture and calls `listener` once it is there (or once it turned+ * out that it cannot be drawn). A picture nobody waits for any more is not+ * drawn. Returns the function that stops waiting.+ */+export function watchFigure(look: FigureLook, pixels: number, listener: () => void): () => void {+ if (!figuresSupported()) return () => {};+ const key = figureKey(look, pixels);+ if (pictures.has(key)) return () => {};+ const since = broken.get(key);+ if (since !== undefined) {+ if (Date.now() - since < RETRY_MS) return () => {};+ broken.delete(key);+ }+ let entry = wanted.get(key);+ if (!entry) wanted.set(key, entry = { look, pixels, listeners: new Set() });+ entry.listeners.add(listener);+ pump();+ return () => {+ entry.listeners.delete(listener);+ if (!entry.listeners.size && current?.key !== key && wanted.get(key) === entry) wanted.delete(key);+ };+}diff --git a/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx b/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsxindex 28d909bb83..8ac01b9a75 100644--- a/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx+++ b/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx@@ -19,6 +19,7 @@ import { useT } from "@/i18n";import type { AgentRuntime } from "@/lib/societyApi";import { AgentNameTaken, RuntimeProviderUnsupported, useCreateSocietyAgent } from "../data";import { defaultCompanion, type CompanionAppearance } from "../companion/appearance";+import { randomCreature } from "../companion/creature";import { RuntimeChoice, useAgentRuntimes } from "../card/RuntimePicker";import { modelSeats, runtimeSeats } from "../chat/modelChoices";import { useModelMenuData } from "../chat/useModelMenuData";@@ -39,8 +40,9 @@ function list(value: unknown): string[] {return Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : [];}+/** A new agent starts as a pixel creature; the shape underneath is there for a change of mind. */function randomCompanion(): CompanionAppearance {- return defaultCompanion(`${Date.now()}:${Math.random()}`);+ return { ...defaultCompanion(`${Date.now()}:${Math.random()}`), creature: randomCreature() };}export function CreateAgentDialogHost() {diff --git a/jarvis/ui/web/frontend/src/components/society/office/TeamRoomPanel.test.tsx b/jarvis/ui/web/frontend/src/components/society/office/TeamRoomPanel.test.tsxindex 55c7c79b9e..c09e79c00e 100644--- a/jarvis/ui/web/frontend/src/components/society/office/TeamRoomPanel.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/TeamRoomPanel.test.tsx@@ -176,14 +176,17 @@ describe("team room panel", () => {test("a working agent's face is its symbol, never the three thinking dots", async () => {mount();await screen.findByText("Launch crew");+ // A face is the agent's pixel creature, or its shape as a symbol or a 3D figure.+ const drawn = "[data-agent-creature], [data-agent-symbol], [data-agent-figure]";const face = screen.getByTitle("Bo · Working");- expect(face.querySelector("[data-agent-symbol]")).toBeTruthy();+ expect(face.querySelector(drawn)).toBeTruthy();expect(face.querySelector("[data-thinking='true']")).toBeNull();+ expect(face.querySelector("[data-creature-state]")?.getAttribute("data-creature-state") ?? "idle").toBe("idle");// Every face sits on the neutral tile, so a white or black symbol never vanishes into the dialog.- expect(face.querySelector(".office-face [data-agent-symbol]")).toBeTruthy();+ expect(face.querySelector(".office-face")?.querySelector(drawn)).toBeTruthy();fireEvent.click(screen.getByRole("button", { name: "Edit" }));const picker = screen.getByRole("group", { name: "Members" });- expect(picker.querySelectorAll(".office-face [data-agent-symbol]")).toHaveLength(agents.length);+ expect([...picker.querySelectorAll(".office-face")].filter(tile => tile.querySelector(drawn))).toHaveLength(agents.length);});test("opened to start a team it shows the new-team form at once, and Cancel leads to the teams", async () => {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json b/jarvis/ui/web/frontend/src/i18n/locales/society/de.jsonindex 768d8fcedf..e3970fdf4c 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json@@ -1011,8 +1011,8 @@"error": "Fehler","sleeping": "Schläft"},- "everywhere": "Alle Agenten als Pixel-Wesen zeigen",- "everywhere_hint": "Ein Testschalter für dieses Gerät. Agenten ohne eigenes Wesen bekommen eines aus ihrer Form und Farbe. Schaltest du ihn aus, ist jedes Aussehen wieder da."+ "by_default": "Pixel-Wesen als Standard",+ "by_default_hint": "Agenten ohne eigene Auswahl erscheinen als Pixel-Wesen, das aus ihrer Form und Farbe entsteht. Schalte es aus, um wieder ihre Formen zu sehen. Gilt für dieses Gerät."},"pet": "Pet","pet_hint": "Der Agent trägt dieses Pet überall: in Chats, bei der Arbeit und als Begleiter in der Verse.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json b/jarvis/ui/web/frontend/src/i18n/locales/society/en.jsonindex d7695f76c6..ca7c0897ee 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json@@ -1011,8 +1011,8 @@"error": "Error","sleeping": "Asleep"},- "everywhere": "Show every agent as a pixel creature",- "everywhere_hint": "A trial switch for this device. Agents without their own creature get one grown from their shape and colour. Switch it off and every look is back."+ "by_default": "Pixel creatures by default",+ "by_default_hint": "Agents that have not picked a look show as a pixel creature grown from their shape and colour. Switch it off to see their shapes again. Applies to this device."},"pet": "Pet","pet_hint": "The agent wears this pet everywhere: in chats, while it works and as its companion in the Verse.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json b/jarvis/ui/web/frontend/src/i18n/locales/society/es.jsonindex 7a1e6ce39e..a045a56ff5 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json@@ -1011,8 +1011,8 @@"error": "Error","sleeping": "Dormido"},- "everywhere": "Mostrar todos los agentes como criaturas de píxeles",- "everywhere_hint": "Un interruptor de prueba para este dispositivo. Los agentes sin criatura propia reciben una creada a partir de su forma y su color. Al apagarlo, todos los aspectos vuelven."+ "by_default": "Criaturas de píxeles por defecto",+ "by_default_hint": "Los agentes que no han elegido un aspecto aparecen como una criatura de píxeles creada a partir de su forma y su color. Apágalo para volver a ver sus formas. Se aplica a este dispositivo."},"pet": "Mascota","pet_hint": "El agente lleva esta mascota en todas partes: en los chats, mientras trabaja y como compañero en el Verse.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/pt.json b/jarvis/ui/web/frontend/src/i18n/locales/society/pt.jsonindex 3ecab70ed5..34231355f8 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/pt.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/pt.json@@ -1011,8 +1011,8 @@"error": "Erro","sleeping": "A dormir"},- "everywhere": "Mostrar todos os agentes como criaturas de píxeis",- "everywhere_hint": "Um interruptor experimental para este dispositivo. Os agentes sem criatura própria recebem uma criada a partir da sua forma e cor. Desliga-o e todos os aspetos voltam."+ "by_default": "Criaturas de píxeis por omissão",+ "by_default_hint": "Os agentes que ainda não escolheram um aspeto aparecem como uma criatura de píxeis criada a partir da sua forma e da sua cor. Desative para voltar a ver as formas. Aplica-se a este dispositivo."},"pet": "Animal","pet_hint": "O agente leva este animal para todo o lado: nos chats, enquanto trabalha e como companheiro no Verse.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/zh.json b/jarvis/ui/web/frontend/src/i18n/locales/society/zh.jsonindex a88725f3ac..4a52179e53 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/zh.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/zh.json@@ -1011,8 +1011,8 @@"error": "出错","sleeping": "休眠"},- "everywhere": "将所有智能体显示为像素生物",- "everywhere_hint": "此设备的试用开关。没有专属生物的智能体会根据其形状和颜色生成一个。关闭后,所有外观恢复原样。"+ "by_default": "默认使用像素生物",+ "by_default_hint": "尚未选择外观的智能体会显示为根据其形状和颜色生成的像素生物。关闭后将重新显示它们的形状。仅适用于此设备。"},"pet": "宠物","pet_hint": "这个智能体在所有地方都会以这只宠物出现:聊天中、工作时,以及在 Verse 中作为伙伴。",diff --git a/tests/contract/fixtures/agent-companion.json b/tests/contract/fixtures/agent-companion.jsonindex db282602e1..890765fd05 100644--- a/tests/contract/fixtures/agent-companion.json+++ b/tests/contract/fixtures/agent-companion.json@@ -8,7 +8,11 @@{"shape":"circle","color":"#8b5cf6","pet":"u0123456789abcdef"},{"shape":"circle","color":"#7a3fb8","skin":{"colors":["#e05cc5","#6a2fc2","#160f3d"],"pattern":"radial","angle":135,"effect":"stars","name":"Galaxy"}},{"shape":"drop","color":"#123456","skin":{"colors":["#000000","#FFFFFF"]}},- {"shape":"hexagon","color":"#123456","skin":{"colors":["#111111","#222222","#333333","#444444"],"pattern":"linear","angle":359,"effect":"futureeffect","name":""}}+ {"shape":"hexagon","color":"#123456","skin":{"colors":["#111111","#222222","#333333","#444444"],"pattern":"linear","angle":359,"effect":"futureeffect","name":""}},+ {"shape":"circle","color":"#a25bff","creature":{"seed":24,"palette":"neon","eyes":"dot"}},+ {"shape":"drop","color":"#123456","creature":{"seed":0,"palette":"futureworld","eyes":"futureeyes"}},+ {"shape":"pill","color":"#123456","creature":{"seed":99999,"palette":"midnight","eyes":"visor"}},+ {"shape":"triangle","color":"#123456","look":"shape"}],"invalid": [{"shape":"unknown","color":"#123456"},@@ -43,6 +47,17 @@{"shape":"circle","color":"#123456","skin":{"colors":["#111111","#222222"],"name":"line\nbreak"}},{"shape":"circle","color":"#123456","skin":{"colors":["#111111","#222222"],"name":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}},{"shape":"circle","color":"#123456","skin":{"colors":["#111111","#222222"],"url":"https://example.org"}},- {"shape":"circle","color":"#123456","skin":"galaxy"}+ {"shape":"circle","color":"#123456","skin":"galaxy"},+ {"shape":"circle","color":"#123456","creature":{"seed":-1,"palette":"neon","eyes":"dot"}},+ {"shape":"circle","color":"#123456","creature":{"seed":100000,"palette":"neon","eyes":"dot"}},+ {"shape":"circle","color":"#123456","creature":{"seed":1.5,"palette":"neon","eyes":"dot"}},+ {"shape":"circle","color":"#123456","creature":{"seed":"24","palette":"neon","eyes":"dot"}},+ {"shape":"circle","color":"#123456","creature":{"seed":24,"palette":"Neon","eyes":"dot"}},+ {"shape":"circle","color":"#123456","creature":{"seed":24,"palette":"neon","eyes":"dot eyes"}},+ {"shape":"circle","color":"#123456","creature":{"seed":24,"palette":"neon"}},+ {"shape":"circle","color":"#123456","creature":{"seed":24,"palette":"neon","eyes":"dot","url":"https://example.org"}},+ {"shape":"circle","color":"#123456","creature":"24"},+ {"shape":"circle","color":"#123456","look":"creature"},+ {"shape":"circle","color":"#123456","look":7}]}diff --git a/tests/contract/test_agent_companion.py b/tests/contract/test_agent_companion.pyindex b4adf267fc..6a0a6b6134 100644--- a/tests/contract/test_agent_companion.py+++ b/tests/contract/test_agent_companion.py@@ -56,6 +56,19 @@ def test_a_worn_pet_survives_and_a_look_without_one_stores_no_pet_key():assert "pet" not in bare["companion"]+def test_a_worn_creature_survives_storage_and_sharing_and_a_bare_look_stores_none():+ creature = {"seed": 24, "palette": "neon", "eyes": "dot"}+ look = {"shape": "circle", "color": "#a25bff", "creature": creature}+ assert validate_avatar_companion({"companion": look})["companion"]["creature"] == creature+ assert public_avatar({"companion": look})["companion"]["creature"] == creature+ bare = validate_avatar_companion({"companion": {**look, "creature": None}})+ assert "creature" not in bare["companion"]+ assert "look" not in bare["companion"]+ worn_shape = {"shape": "triangle", "color": "#a25bff", "look": "shape"}+ assert validate_avatar_companion({"companion": worn_shape})["companion"]["look"] == "shape"+ assert public_avatar({"companion": worn_shape})["companion"]["look"] == "shape"++def test_a_shared_template_keeps_a_builtin_pet_and_drops_a_drawn_one():builtin = public_avatar({"companion": {"shape": "drop", "color": "#79c7c4", "pet": "cocoa"}})assert builtin["companion"]["pet"] == "cocoa"@@ -107,6 +120,12 @@ def test_fresh_headless_create_edit_reload_without_inference_or_credentials(tmp_assert response.json()["agent"]["avatar"]["companion"]["enabled"] is Falsebad = client.patch(url, json={"avatar": {**avatar, "companion": CASES["invalid"][0]}})assert bad.status_code == 409+ # A pixel creature is stored with the look and comes back after a restart.+ creature = {"seed": 24, "palette": "neon", "eyes": "dot"}+ updated = {**avatar, "companion": {**CASES["valid"][1], "creature": creature}}+ response = client.patch(url, json={"avatar": updated})+ assert response.status_code == 200, response.text+ assert response.json()["agent"]["avatar"]["companion"]["creature"] == creaturefinally:client.portal.call(runtime.close)app, runtime = open_app()diff --git a/tests/contract/test_society_one_click_create.py b/tests/contract/test_society_one_click_create.pyindex f95a6d2ab0..cd9171be4d 100644--- a/tests/contract/test_society_one_click_create.py+++ b/tests/contract/test_society_one_click_create.py@@ -3,6 +3,7 @@from __future__ import annotationsimport asyncio+import jsonimport refrom pathlib import Path@@ -13,6 +14,8 @@ from fastapi.testclient import TestClientfrom jarvis.society.companion import (COMPANION_COLORS,COMPANION_SHAPES,+ CREATURE_EYES,+ CREATURE_PALETTES,CompanionAppearance,random_companion,)@@ -26,6 +29,7 @@ APPEARANCE_TS = (Path(__file__).resolve().parents[2]/ "jarvis/ui/web/frontend/src/components/society/companion/appearance.ts")+CREATURE_TS = APPEARANCE_TS.with_name("creature.ts")@pytest.fixture@@ -99,6 +103,10 @@ async def test_every_new_agent_gets_a_valid_random_companion(roster: Roster):companion = CompanionAppearance.model_validate(agent.avatar["companion"])assert companion.shape in COMPANION_SHAPESassert companion.color in COMPANION_COLORS+ # A new agent starts as a pixel creature.+ assert companion.creature is not None+ assert companion.creature.palette in CREATURE_PALETTES+ assert companion.creature.eyes in CREATURE_EYESasync def test_an_explicit_avatar_is_kept(roster: Roster):@@ -108,10 +116,10 @@ async def test_an_explicit_avatar_is_kept(roster: Roster):def test_random_companion_is_valid_and_varies():- looks = {tuple(sorted(random_companion().items())) for _ in range(40)}- assert len(looks) > 1+ looks = [random_companion() for _ in range(40)]+ assert len({json.dumps(look, sort_keys=True) for look in looks}) > 1for look in looks:- CompanionAppearance.model_validate(dict(look))+ CompanionAppearance.model_validate(look)def test_companion_choices_match_the_frontend():@@ -123,6 +131,14 @@ def test_companion_choices_match_the_frontend():assert tuple(re.findall(r'"([^"]+)"', colors.group(1))) == COMPANION_COLORS+def test_creature_choices_match_the_frontend():+ source = CREATURE_TS.read_text(encoding="utf-8")+ eyes = re.search(r"CREATURE_EYES = \[([^\]]*)\]", source)+ assert eyes+ assert tuple(re.findall(r'palette\("([a-z]+)"', source)) == CREATURE_PALETTES+ assert tuple(re.findall(r'"([^"]+)"', eyes.group(1))) == CREATURE_EYES++def test_post_without_a_name_creates_a_fresh_agent(tmp_path: Path):runtime = SocietyRuntime(tmp_path, seed_starter_team=False)app = FastAPI()