Files
shimejic/apps/demo/src/routes/+page.svelte
T

1406 lines
37 KiB
Svelte
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script lang="ts">
import {
angleFromPoint, AssetCache, BehaviorController, Canvas2DRenderer,
ChatterOverlay,
distanceBetween, Mumble, type AnimationClip,
type BehaviorState, type BubbleRenderData, type CacheStats, type DebugSnapshot,
type EventDef,
type LookSector
} from 'shimejic';
import { onMount } from 'svelte';
/* ================================================================== */
/* ASSET FOLDER CONVENTION */
/* ================================================================== */
/*
* Drop PNGs under `src/lib/assets/` and the demo auto-discovers them.
*
* assets/
* ├── image.png → single-file fallback: state "image"
* ├── idle/
* │ ├── 0.png → base clip "idle"
* │ ├── 1.png
* │ ├── 2.png
* │ ├── look/ → optional look sectors
* │ │ ├── t/
* │ │ │ ├── 0.png (must match base frame count)
* │ │ │ ├── 1.png
* │ │ │ └── 2.png
* │ │ ├── l/
* │ │ │ └── ...
* │ │ └── r/
* │ │ └── ...
* │ └── event/ → optional event clips
* │ ├── sneeze/
* │ │ ├── 0.png
* │ │ └── ...
* │ └── blink/
* │ └── ...
* ├── walk/
* │ ├── 0.png
* │ └── ...
* └── ...
*
* Rules:
* - `<state>/<frame>.png` → base clip for `<state>`
* - `<state>/look/<dir>/<f>.png` → look sector for `<state>`
* - `<state>/event/<n>/<f>.png` → event clip for `<state>`
* - Root `<name>.png` → base clip `<name>` with 1 frame
* - No "idle" state → first base clip renamed "idle"
*
* Look sector directions (8-way compass, 45° each):
* t 337.5–22.5 (wraps 0)
* tr 22.5–67.5
* r 67.5–112.5
* br 112.5–157.5
* b 157.5–202.5
* bl 202.5–247.5
* l 247.5–292.5
* tl 292.5–337.5
* If you only create some directions, the others are gaps (no look).
*
* Look clips MUST match their state's base frame count, otherwise the
* sector is skipped with a console warning.
*/
/* ================================================================== */
const manifest = import.meta.glob('#lib/assets/**/*.png', {
eager: true,
query: '?url',
import: 'default'
}) as Record<string, string>;
/* Per-state fps. Look sectors inherit their state's fps. */
const CLIP_FPS = 8;
const FPS_OVERRIDES: Record<string, number> = {
// 'idle': 6,
// 'idle/event/sneeze': 10,
};
interface EventOverride {
chance?: number;
interval?: [number, number];
cooldown?: number;
weight?: number;
}
/**
* Per-event overrides. Keys are `<state>/event/<name>`, matching the folder
* structure.
*
* chance 0..1 probability per roll
* interval [min, max] seconds between roll attempts
* cooldown seconds of lockout after the event fires
* weight selection weight when multiple events pass their rolls together
*
* Any field left out falls back to DEFAULT_EVENT.
*/
const EVENT_OVERRIDES: Record<string, EventOverride> = {
// 'idle/event/sneeze': { chance: 0.15, interval: [8, 20], cooldown: 25 },
// 'idle/event/blink': { chance: 0.6, interval: [2, 5], cooldown: 3 },
// 'walk/event/sniff': { chance: 0.3, cooldown: 10 }
};
const DEFAULT_EVENT: Required<EventOverride> = {
chance: 0.4,
interval: [4, 10],
cooldown: 6,
weight: 1
};
const LOOK_HYSTERESIS = 2;
const LOOK_DISTANCE = {min: 50, max: 600};
const LOOK_PIVOT = { x: 0.2, y: 0.3 };
const DIRECTION_RANGES: Record<string, [number, number]> = {
t: [337.5, 22.5],
tr: [22.5, 67.5],
r: [67.5, 112.5],
br: [112.5, 157.5],
b: [157.5, 202.5],
bl: [202.5, 247.5],
l: [247.5, 292.5],
tl: [292.5, 337.5]
};
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
interface EventListItem {
state: string;
name: string;
chance: number;
interval: [number, number];
cooldown: number;
weight: number;
}
/* ------------------------------------------------------------------ */
/* Helpers */
/* ------------------------------------------------------------------ */
/**
* Trace an annular sector (wedge with a hole) as a closed path.
* Angles use our convention: 0° = up, 90° = right, 180° = down, 270° = left.
* Wraps correctly when startAngle > endAngle.
*/
function traceAnnularSector(
ctx: CanvasRenderingContext2D,
cx: number,
cy: number,
startAngleDeg: number,
endAngleDeg: number,
innerRadius: number,
outerRadius: number
): void {
const startRad = (startAngleDeg * Math.PI) / 180 - Math.PI / 2;
let sweep = endAngleDeg - startAngleDeg;
if (sweep <= 0) sweep += 360;
const endRad = startRad + (sweep * Math.PI) / 180;
ctx.beginPath();
ctx.arc(cx, cy, outerRadius, startRad, endRad);
ctx.arc(cx, cy, innerRadius, endRad, startRad, true);
ctx.closePath();
}
/**
* Build a bubble image procedurally. Rounded rect + tail, white fill,
* dark outline, so the demo doesn't depend on external assets.
*/
function makeBubbleImage(width: number, height: number): HTMLCanvasElement {
const c = document.createElement('canvas');
c.width = width;
c.height = height;
const bc = c.getContext('2d')!;
bc.fillStyle = '#ffffff';
bc.strokeStyle = '#1a1a1a';
bc.lineWidth = 3;
const r = 14;
const pad = 6;
const x0 = pad;
const y0 = pad;
const w = width - pad * 2;
const h = height - pad * 2 - 16;
bc.beginPath();
bc.moveTo(x0 + r, y0);
bc.lineTo(x0 + w - r, y0);
bc.quadraticCurveTo(x0 + w, y0, x0 + w, y0 + r);
bc.lineTo(x0 + w, y0 + h - r);
bc.quadraticCurveTo(x0 + w, y0 + h, x0 + w - r, y0 + h);
bc.lineTo(x0 + w / 2 + 14, y0 + h);
bc.lineTo(x0 + w / 2 + 4, y0 + h + 16);
bc.lineTo(x0 + w / 2 - 8, y0 + h);
bc.lineTo(x0 + r, y0 + h);
bc.quadraticCurveTo(x0, y0 + h, x0, y0 + h - r);
bc.lineTo(x0, y0 + r);
bc.quadraticCurveTo(x0, y0, x0 + r, y0);
bc.closePath();
bc.fill();
bc.stroke();
return c;
}
/**
* Build a tiny heart icon procedurally.
*/
function makeHeartIcon(): HTMLCanvasElement {
const c = document.createElement('canvas');
c.width = 16;
c.height = 16;
const hc = c.getContext('2d')!;
hc.fillStyle = '#e11d48';
hc.font = '16px serif';
hc.textBaseline = 'top';
hc.fillText('♥', 0, 0);
return c;
}
/**
* Draw a chatter bubble. Bubbles scale with the sprite's display scale so
* the text stays readable regardless of the sprite's natural pixel size.
*/
function drawBubble(
ctx: CanvasRenderingContext2D,
centerX: number,
spriteTop: number,
data: BubbleRenderData
): void {
// Bubble dims are CSS pixels — no sprite scaling
const w = data.width;
const h = data.height;
const bubbleX = centerX + data.anchorX - w / 2;
const bubbleY = spriteTop - data.anchorY - h;
ctx.save();
ctx.globalAlpha = data.alpha;
ctx.drawImage(data.image, bubbleX, bubbleY, w, h);
ctx.globalAlpha = 1;
ctx.font = data.font;
ctx.textBaseline = 'top';
ctx.textAlign = 'left';
const padL = data.padding.left;
const padT = data.padding.top;
const lineHeight = data.layout.lineHeight;
for (const item of data.layout.items) {
if (item.visibleIndex >= data.charsShown) break;
const offsetX = data.layout.lineOffsets[item.lineIndex] ?? 0;
const ix = bubbleX + padL + item.x + offsetX;
const iy = bubbleY + padT + item.y;
// Per-style animation offsets
let animX = 0;
let animY = 0;
const t = data.elapsed;
const idx = item.visibleIndex;
if (item.kind === 'text') {
const s = item.style;
// Wave: traveling vertical sine
if (s.wave) animY += Math.sin(t * 5 - item.x * 0.15) * 3;
// Shake: small, moderate-frequency jitter
if (s.shake) {
animX += Math.sin(t * 28 + idx * 1.7) * 0.7;
animY += Math.cos(t * 31 + idx * 1.3) * 0.7;
}
// Wobble: per-char rotation + subtle bob
const wobbleAngle = s.wobble ? Math.sin(t * 8 + idx * 1.4) * 0.09 : 0;
const wobbleY = s.wobble ? Math.sin(t * 8 + idx * 1.4 + Math.PI / 4) * 0.8 : 0;
if (wobbleAngle !== 0) {
// Rotation path: draw inside a rotated transform
const pivotX = ix + animX + item.width / 2;
const pivotY = iy + animY + wobbleY + lineHeight * 0.8;
ctx.save();
ctx.translate(pivotX, pivotY);
ctx.rotate(wobbleAngle);
ctx.fillStyle = s.color;
const lx = -item.width / 2;
const ly = -lineHeight * 0.8;
if (s.bold) ctx.fillText(item.text, lx + 1, ly);
ctx.fillText(item.text, lx, ly);
if (s.underline) {
const textW = ctx.measureText(item.text).width;
ctx.fillRect(lx, ly + lineHeight * 0.9, textW, 1);
}
ctx.restore();
} else {
// Non-rotated path — same as before
ctx.fillStyle = s.color;
if (s.bold) ctx.fillText(item.text, ix + animX + 1, iy + animY);
ctx.fillText(item.text, ix + animX, iy + animY);
if (s.underline) {
const textW = ctx.measureText(item.text).width;
ctx.fillRect(ix + animX, iy + animY + lineHeight * 0.9, textW, 1);
}
}
}
}
ctx.restore();
}
/* ------------------------------------------------------------------ */
/* Reactive state */
/* ------------------------------------------------------------------ */
let canvas = $state<HTMLCanvasElement>();
let ready = $state(false);
let errorMsg = $state<string | null>(null);
let debug = $state<DebugSnapshot | null>(null);
let cursorInfo = $state<{ angle: number; distance: number } | null>(null);
let chatterLog = $state<string[]>([]);
let stats = $state<CacheStats | null>(null);
let clipSummary = $state<
Array<{ name: string; role: string; frames: number; fps: number }>
>([]);
let currentState = $state('');
let availableStates = $state<string[]>([]);
let availableEvents = $state<EventListItem[]>([]);
let hasLookForCurrent = $state(false);
let setStateFn: (s: string) => void = () => {};
let triggerEventFn: (state: string, name: string) => void = () => {};
let overlayFn: () => void = () => {};
/** Deferred trigger for when we need to switch state first. */
let pendingTrigger: { state: string; event: string } | null = $state(null);
/* ------------------------------------------------------------------ */
/* Mount */
/* ------------------------------------------------------------------ */
onMount(() => {
if (!canvas) return;
let cancelled = false;
let raf = 0;
let builtStates: Record<string, BehaviorState> = {};
/* ---------------- renderer + sizing ---------------- */
const renderer = new Canvas2DRenderer({ canvas, pixelArt: true });
canvas.style.imageRendering = 'pixelated';
const resize = () => {
if (!canvas) return;
const rect = canvas.getBoundingClientRect();
renderer.resize(rect.width, rect.height);
};
resize();
const ro = new ResizeObserver(resize);
ro.observe(canvas);
const mumble = new Mumble();
let audioCtx: AudioContext | null = null;
const unlockAudio = async () => {
if(audioCtx) return;
try {
audioCtx = new AudioContext();
await audioCtx.resume();
mumble.attach(audioCtx);
} catch (err) {
console.warn('[demo] audio unavailable', err);
}
}
window.addEventListener('keydown', unlockAudio, {once: true});
window.addEventListener('pointerdown', unlockAudio, {once: true});
/* ---------------- pointer input ---------------- */
const cursorPos = { x: 0, y: 0 };
let hasCursor = false;
const onPointerMove = (e: PointerEvent) => {
if (!canvas) return;
const rect = canvas.getBoundingClientRect();
cursorPos.x = e.clientX - rect.left;
cursorPos.y = e.clientY - rect.top;
hasCursor = true;
};
const onPointerLeave = () => {
hasCursor = false;
};
window.addEventListener('pointermove', onPointerMove);
window.addEventListener('pointerleave', onPointerLeave);
/* ---------------- async asset load + setup ---------------- */
void (async () => {
if (Object.keys(manifest).length === 0) {
errorMsg = 'No PNG assets found under src/lib/assets/.';
return;
}
const cache = new AssetCache({ manifest });
try {
await cache.preload();
if (cancelled) return;
stats = cache.stats();
const built = buildFromAssets(cache);
if (built === null) {
errorMsg = 'Could not build any clips from loaded assets.';
return;
}
builtStates = built.states;
ready = true;
availableStates = Object.keys(built.states);
availableEvents = built.events;
clipSummary = built.clipSummary;
/* ---------------- chatter overlay ---------------- */
const overlay = new ChatterOverlay({mumble});
const bubbleImg = makeBubbleImage(240, 100);
const heartIcon = makeHeartIcon();
overlay.registerIcon('heart', heartIcon);
overlay.setConfig('cat', {
bubble: {
image: bubbleImg,
width: 240,
height: 100,
anchorY: 14
},
text: {
font: '13px ui-monospace, monospace',
color: '#1a1a1a',
align: 'center',
padding: { top: 18, right: 16, bottom: 32, left: 16 },
lineHeight: 1.3,
speed: 22
},
timing: { holdLast: 1.8 },
voice: {
basePitch: 1.5,
formantScale: 1.3,
volume: 0.7
}
});
/* ---------------- controller ---------------- */
const ctrl = new BehaviorController({
states: built.states,
onChatter: (text, source) => {
chatterLog = [...chatterLog, `[${source}] ${text}`].slice(-8);
overlay.say('cat', text);
}
});
currentState = availableStates[0] ?? '';
const updateHasLook = () => {
const def = built.states[currentState];
hasLookForCurrent = def?.look !== undefined;
};
updateHasLook();
setStateFn = (s) => {
if (!availableStates.includes(s)) return;
currentState = s;
updateHasLook();
};
triggerEventFn = (state, name) => {
ctrl.pushEvent(state, name);
};
overlayFn = () => {
overlay.say(
'cat',
'Hello{pause 200} {color #e11d48}{wobble}WATCH OUT{/wobble}{/color} {wave}WATCH OUT{/wave} {shake}WATCH OUT{/shake} {icon fish}!'
);
};
/* ---------------- render loop ---------------- */
let last = 0;
const draw = (now: number) => {
const dt = last === 0 ? 1 / 60 : Math.min((now - last) / 1000, 1 / 20);
last = now;
const { width, height } = renderer.size;
const catX = width / 2;
const catY = height / 2;
// Reference size = base clip's frame 0, so scale stays constant
// within a state regardless of event/look frame dimensions.
const baseDef = builtStates[currentState];
const baseImage = baseDef?.base.frames[0];
const baseSize = baseImage
? { w: imageSize(baseImage).width, h: imageSize(baseImage).height }
: { w: 64, h: 64 };
const scale = fitScale(baseSize.w, baseSize.h, Math.min(width, height) * 0.4);
const frame = ctrl.frame();
const frameSize = frame ? { w: frame.width, h: frame.height } : baseSize;
const displayW = frameSize.w * scale;
const displayH = frameSize.h * scale;
const bounds = {
x: catX - displayW / 2,
y: catY - displayH / 2,
width: displayW,
height: displayH
};
const pivotX = bounds.x + LOOK_PIVOT.x * displayW;
const pivotY = bounds.y + LOOK_PIVOT.y * displayH;
ctrl.update(dt, {
state: currentState,
cursor: hasCursor ? cursorPos : null,
bounds
});
overlay.update(dt);
// Deferred trigger: fired after the state change has been applied.
if (pendingTrigger !== null && ctrl.state === pendingTrigger.state) {
ctrl.pushEvent(pendingTrigger.state, pendingTrigger.event);
pendingTrigger = null;
}
debug = ctrl.debugSnapshot();
if (hasCursor) {
cursorInfo = {
angle: angleFromPoint({ x: pivotX, y: pivotY }, cursorPos),
distance: distanceBetween({ x: pivotX, y: pivotY }, cursorPos)
};
} else {
cursorInfo = null;
}
renderer.clear();
const ctx = renderer.ctx;
/* ---- look sector backdrop (under sprite) ---- */
const stateLook = builtStates[currentState]?.look;
if (stateLook !== undefined) {
const innerR = stateLook.distance.min;
const outerR = stateLook.distance.max;
const activeFolder = ctrl.lookSector;
for (const sector of stateLook.sectors) {
const isActive = sector.folder === activeFolder;
traceAnnularSector(
ctx,
pivotX,
pivotY,
sector.minAngle,
sector.maxAngle,
innerR,
outerR
);
ctx.fillStyle = isActive
? 'rgba(126, 200, 255, 0.20)'
: 'rgba(126, 200, 255, 0.04)';
ctx.fill();
ctx.strokeStyle = isActive
? 'rgba(126, 200, 255, 0.70)'
: 'rgba(126, 200, 255, 0.15)';
ctx.lineWidth = 1;
ctx.stroke();
let sweep = sector.maxAngle - sector.minAngle;
if (sweep <= 0) sweep += 360;
const midAngle = sector.minAngle + sweep / 2;
const midRad = (midAngle * Math.PI) / 180 - Math.PI / 2;
const labelR = innerR + (outerR - innerR) * 0.5;
const lx = pivotX + Math.cos(midRad) * labelR;
const ly = pivotY + Math.sin(midRad) * labelR;
ctx.save();
ctx.fillStyle = isActive ? '#7ec8ff' : 'rgba(126, 200, 255, 0.5)';
ctx.font = 'bold 10px ui-monospace, monospace';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(sector.folder, lx, ly);
ctx.restore();
}
ctx.save();
ctx.strokeStyle = 'rgba(126, 200, 255, 0.25)';
ctx.lineWidth = 1;
const boundaries = new Set<number>();
for (const s of stateLook.sectors) {
boundaries.add(s.minAngle);
boundaries.add(s.maxAngle);
}
for (const a of boundaries) {
const rad = (a * Math.PI) / 180 - Math.PI / 2;
ctx.beginPath();
ctx.moveTo(pivotX + Math.cos(rad) * innerR, pivotY + Math.sin(rad) * innerR);
ctx.lineTo(pivotX + Math.cos(rad) * outerR, pivotY + Math.sin(rad) * outerR);
ctx.stroke();
}
ctx.restore();
ctx.save();
ctx.strokeStyle = 'rgba(255, 255, 255, 0.12)';
ctx.lineWidth = 1;
ctx.setLineDash([4, 6]);
if (innerR > 0) {
ctx.beginPath();
ctx.arc(pivotX, pivotY, innerR, 0, Math.PI * 2);
ctx.stroke();
}
ctx.beginPath();
ctx.arc(pivotX, pivotY, outerR, 0, Math.PI * 2);
ctx.stroke();
ctx.setLineDash([]);
ctx.restore();
}
/* ---- sprite ---- */
if (frame) {
renderer.drawSprite({
image: frame.image,
x: catX,
y: catY,
width: displayW,
height: displayH,
anchor: 'center',
sx: frame.sx,
sy: frame.sy,
sw: frame.sw,
sh: frame.sh
});
ctx.save();
ctx.fillStyle = 'rgba(0, 0, 0, 0.6)';
ctx.font = '11px ui-monospace, monospace';
const label = `${ctrl.frameNumber}`;
const m = ctx.measureText(label);
const lx = catX + displayW / 2 + 8;
const ly = catY - displayH / 2;
ctx.fillRect(lx - 2, ly - 2, m.width + 8, 16);
ctx.fillStyle = '#7ec8ff';
ctx.fillText(label, lx + 2, ly + 11);
ctx.restore();
}
/* ---- chatter bubble (above the sprite) ---- */
const bubbleData = overlay.getRenderData('cat');
if (bubbleData !== null) {
drawBubble(ctx, catX, bounds.y, bubbleData);
}
/* ---- pivot marker (on top of sprite) ---- */
ctx.save();
ctx.strokeStyle = 'rgba(255, 107, 107, 0.85)';
ctx.lineWidth = 1;
ctx.setLineDash([3, 3]);
ctx.beginPath();
ctx.moveTo(pivotX - 15, pivotY);
ctx.lineTo(pivotX + 15, pivotY);
ctx.moveTo(pivotX, pivotY - 15);
ctx.lineTo(pivotX, pivotY + 15);
ctx.stroke();
ctx.setLineDash([]);
ctx.beginPath();
ctx.arc(pivotX, pivotY, 2.5, 0, Math.PI * 2);
ctx.fillStyle = 'rgba(255, 107, 107, 0.9)';
ctx.fill();
ctx.restore();
/* ---- cursor line + dot (on top) ---- */
if (hasCursor) {
ctx.save();
const inRange = ctrl.lookSector !== null;
ctx.strokeStyle = inRange ? '#7ec8ff' : 'rgba(255,255,255,0.15)';
ctx.lineWidth = 1;
ctx.setLineDash([3, 3]);
ctx.beginPath();
ctx.moveTo(pivotX, pivotY);
ctx.lineTo(cursorPos.x, cursorPos.y);
ctx.stroke();
ctx.setLineDash([]);
ctx.beginPath();
ctx.arc(cursorPos.x, cursorPos.y, 4, 0, Math.PI * 2);
ctx.fillStyle = inRange ? '#7ec8ff' : 'rgba(255,255,255,0.4)';
ctx.fill();
ctx.restore();
}
raf = requestAnimationFrame(draw);
};
if (import.meta.env.DEV) {
(window as any).__demo = {
overlay,
mumble,
ctrl,
unlockAudio,
builtStates,
get audioState() {
return audioCtx?.state ?? 'not-created';
},
say: (text: string) => {
void unlockAudio();
overlay.say('cat', text);
},
stop: () => mumble.stopAll(),
skip: () => overlay.skip('cat'),
dismiss: () => overlay.dismiss('cat'),
clear: () => overlay.clear('cat'),
progress: () => overlay.progress('cat'),
pushEvent: (state: string, name: string) => ctrl.pushEvent(state, name),
voice: (v: Parameters<typeof mumble.setVoiceDefaults>[0]) => mumble.setVoiceDefaults(v)
};
}
raf = requestAnimationFrame(draw);
} catch (err) {
if (cancelled) return;
errorMsg = err instanceof Error ? err.message : String(err);
}
})();
return () => {
cancelled = true;
cancelAnimationFrame(raf);
ro.disconnect();
window.removeEventListener('pointermove', onPointerMove);
window.removeEventListener('pointerleave', onPointerLeave);
mumble.detach();
if(audioCtx) void audioCtx.close();
if (import.meta.env.DEV) delete (window as any).__demo;
};
});
/* ------------------------------------------------------------------ */
/* Event trigger helper */
/* ------------------------------------------------------------------ */
function handleEventClick(stateName: string, eventName: string) {
if (currentState === stateName) {
triggerEventFn(stateName, eventName);
} else {
setStateFn(stateName);
pendingTrigger = { state: stateName, event: eventName };
}
}
/* ------------------------------------------------------------------ */
/* Asset discovery */
/* ------------------------------------------------------------------ */
function imageSize(image: CanvasImageSource): { width: number; height: number } {
const anyImg = image as unknown as Record<string, unknown>;
const nw = anyImg.naturalWidth;
const nh = anyImg.naturalHeight;
if (typeof nw === 'number' && typeof nh === 'number') {
return { width: nw, height: nh };
}
const w = anyImg.width;
const h = anyImg.height;
if (typeof w === 'number' && typeof h === 'number') {
return { width: w, height: h };
}
return { width: 0, height: 0 };
}
function fitScale(naturalW: number, naturalH: number, maxDim: number): number {
if (naturalW === 0 || naturalH === 0) return 1;
const s = Math.min(maxDim / naturalW, maxDim / naturalH);
return Math.max(1, Math.floor(s * 2) / 2);
}
function getRelativePath(absolutePath: string): string {
const known = '/src/lib/assets/';
if (absolutePath.startsWith(known)) return absolutePath.slice(known.length);
const idx = absolutePath.indexOf('/assets/');
if (idx >= 0) return absolutePath.slice(idx + '/assets/'.length);
return absolutePath;
}
function numericSuffix(path: string): number {
const base = path.split('/').pop() ?? '';
const m = base.match(/(\d+)/);
return m ? parseInt(m[1]!, 10) : 0;
}
interface BuiltAssets {
states: Record<string, BehaviorState>;
events: EventListItem[];
clipSummary: Array<{ name: string; role: string; frames: number; fps: number }>;
}
function buildFromAssets(cache: AssetCache): BuiltAssets | null {
const baseGroups = new Map<string, string[]>();
const lookGroups = new Map<string, Map<string, string[]>>();
const eventGroups = new Map<string, Map<string, string[]>>();
for (const name of cache.names()) {
const rel = getRelativePath(name);
const parts = rel.split('/');
if (parts.length === 1) {
const stateName = parts[0]!.replace(/\.[^.]+$/, '');
if (!baseGroups.has(stateName)) baseGroups.set(stateName, []);
baseGroups.get(stateName)!.push(name);
continue;
}
if (parts.length === 2) {
const stateName = parts[0]!;
if (!baseGroups.has(stateName)) baseGroups.set(stateName, []);
baseGroups.get(stateName)!.push(name);
continue;
}
if (parts.length === 4 && parts[1] === 'look') {
const stateName = parts[0]!;
const dir = parts[2]!;
if (!lookGroups.has(stateName)) lookGroups.set(stateName, new Map());
const dirMap = lookGroups.get(stateName)!;
if (!dirMap.has(dir)) dirMap.set(dir, []);
dirMap.get(dir)!.push(name);
continue;
}
if (parts.length === 4 && parts[1] === 'event') {
const stateName = parts[0]!;
const evName = parts[2]!;
if (!eventGroups.has(stateName)) eventGroups.set(stateName, new Map());
const evMap = eventGroups.get(stateName)!;
if (!evMap.has(evName)) evMap.set(evName, []);
evMap.get(evName)!.push(name);
continue;
}
console.warn(`[demo] unrecognized asset path: ${rel}`);
}
if (baseGroups.size === 0) return null;
if (!baseGroups.has('idle')) {
const [firstKey, firstNames] = [...baseGroups.entries()][0]!;
baseGroups.delete(firstKey);
baseGroups.set('idle', firstNames);
}
const collectFrames = (names: string[]): CanvasImageSource[] => {
const sorted = [...names].sort((a, b) => numericSuffix(a) - numericSuffix(b));
const frames: CanvasImageSource[] = [];
for (const n of sorted) {
const info = cache.get(n);
if (info) frames.push(info.image);
}
return frames;
};
const states: Record<string, BehaviorState> = {};
const events: EventListItem[] = [];
const clipSummary: Array<{ name: string; role: string; frames: number; fps: number }> = [];
for (const [stateName, baseNames] of baseGroups) {
const fps = FPS_OVERRIDES[stateName] ?? CLIP_FPS;
const baseFrames = collectFrames(baseNames);
if (baseFrames.length === 0) continue;
const baseClip: AnimationClip = { frames: baseFrames, fps, loop: true };
const state: BehaviorState = { base: baseClip };
const stateLooks = lookGroups.get(stateName);
if (stateLooks) {
const sectors: LookSector[] = [];
for (const [dir, names] of stateLooks) {
const range = DIRECTION_RANGES[dir];
if (range === undefined) {
console.warn(`[demo] unknown look direction "${dir}" (state "${stateName}").`);
continue;
}
const frames = collectFrames(names);
if (frames.length === 0) continue;
if (frames.length !== baseFrames.length) {
console.warn(
`[demo] ${stateName}/look/${dir}: ${frames.length} frames, base has ${baseFrames.length}. Skipping sector.`
);
continue;
}
sectors.push({
minAngle: range[0],
maxAngle: range[1],
folder: dir,
clip: { frames, fps, loop: true }
});
clipSummary.push({
name: `${stateName}/look/${dir}`,
role: `look (${stateName})`,
frames: frames.length,
fps
});
}
if (sectors.length > 0) {
state.look = {
pivot: LOOK_PIVOT,
distance: LOOK_DISTANCE,
hysteresis: LOOK_HYSTERESIS,
sectors
};
}
}
const stateEvents = eventGroups.get(stateName);
if (stateEvents) {
const eventDefs: EventDef[] = [];
for (const [evName, names] of stateEvents) {
const evKey = `${stateName}/event/${evName}`;
const evFps = FPS_OVERRIDES[evKey] ?? fps;
const ov = EVENT_OVERRIDES[evKey] ?? {};
const chance = ov.chance ?? DEFAULT_EVENT.chance;
const interval = ov.interval ?? DEFAULT_EVENT.interval;
const cooldown = ov.cooldown ?? DEFAULT_EVENT.cooldown;
const weight = ov.weight ?? DEFAULT_EVENT.weight;
const frames = collectFrames(names);
if (frames.length === 0) continue;
eventDefs.push({
name: evName,
clip: { frames, fps: evFps, loop: false },
chance,
interval,
cooldown,
weight,
chatter: [{ at: 0, unit: 'frame', text: evName }]
});
events.push({ state: stateName, name: evName, chance, interval, cooldown, weight });
clipSummary.push({
name: evKey,
role: `event (${stateName})`,
frames: frames.length,
fps: evFps
});
}
if (eventDefs.length > 0) state.events = eventDefs;
}
states[stateName] = state;
clipSummary.push({
name: stateName,
role: 'base',
frames: baseFrames.length,
fps
});
}
return { states, events, clipSummary };
}
</script>
<canvas bind:this={canvas}></canvas>
<div class="panel">
<h2>Asset Playground</h2>
{#if errorMsg}
<p class="error">{errorMsg}</p>
{:else if !ready}
<p class="loading">Loading assets…</p>
{:else}
<!-- State switcher -->
<div class="section-title">State</div>
<div class="controls">
{#each availableStates as s}
<button class:active={currentState === s} onclick={() => setStateFn(s)}>
{s}
</button>
{/each}
</div>
<!-- Event triggers -->
{#if availableEvents.length > 0}
<div class="section-title">Trigger event</div>
<div class="event-grid">
{#each availableEvents as ev}
{@const key = `${ev.state}:${ev.name}`}
{@const cd = debug?.cooldowns[key] ?? 0}
{@const isQueued = debug?.queuedEvent === ev.name && debug?.state === ev.state}
{@const isActive = debug?.activeEvent === ev.name && debug?.state === ev.state}
{@const stateMismatch = currentState !== ev.state}
<button
class:is-mismatch={stateMismatch}
class:is-queued={isQueued}
class:is-playing={isActive}
disabled={isActive}
onclick={() => handleEventClick(ev.state, ev.name)}
title={isActive
? 'Already playing'
: isQueued
? 'Queued — plays at next cycle boundary'
: stateMismatch
? `Switch to "${ev.state}" and queue "${ev.name}"`
: cd > 0
? `Queue "${ev.name}" (on cooldown ${cd.toFixed(1)}s — manual push bypasses)`
: `Queue "${ev.name}"`}
>
<div class="ev-main">
<span class="ev-label">{ev.state} / {ev.name}</span>
{#if isActive}
<span class="ev-tag tag-playing">PLAYING</span>
{:else if isQueued}
<span class="ev-tag tag-queued">QUEUED</span>
{:else if cd > 0}
<span class="ev-tag tag-cd">{cd.toFixed(1)}s</span>
{/if}
</div>
<div class="ev-config">
{Math.round(ev.chance * 100)}% · {ev.interval[0]}-{ev.interval[1]}s · {ev.cooldown}s cd{#if ev.weight !== 1} · w{ev.weight}{/if}
</div>
</button>
{/each}
</div>
{#if pendingTrigger}
<p class="pending">
Switching to <strong>{pendingTrigger.state}</strong> to queue
<strong>{pendingTrigger.event}</strong>…
</p>
{/if}
{/if}
<!-- Test escapes -->
<div class="section-title">Chatter test</div>
<div class="controls small">
<button onclick={() => overlayFn()}>Test escapes</button>
</div>
<!-- Debug -->
{#if debug}
<dl>
<dt>state</dt>
<dd>{debug.state}</dd>
<dt>track</dt>
<dd class:highlight={debug.track !== 'base'}>{debug.track}</dd>
<dt>frame</dt>
<dd>{debug.frameIndex} / {debug.frameCount - 1}</dd>
<dt>look folder</dt>
<dd>{debug.lookFolder ?? '—'}</dd>
<dt>matched</dt>
<dd>{debug.matchedFolder ?? '—'}</dd>
<dt>active event</dt>
<dd>{debug.activeEvent ?? '—'}</dd>
<dt>queued event</dt>
<dd>{debug.queuedEvent ?? '—'}</dd>
{#if Object.keys(debug.cooldowns).length > 0}
<dt>cooldowns</dt>
<dd>
{#each Object.entries(debug.cooldowns) as [key, sec]}
<div>{key.replace(':', ' / ')}: {sec.toFixed(1)}s</div>
{/each}
</dd>
{/if}
</dl>
{/if}
{#if cursorInfo}
<div class="cursor-info">
<div>angle <strong>{cursorInfo.angle.toFixed(1)}°</strong></div>
<div>distance <strong>{cursorInfo.distance.toFixed(0)} px</strong></div>
</div>
{/if}
{#if chatterLog.length > 0}
<div class="chatter">
{#each chatterLog as line}
<div>{line}</div>
{/each}
</div>
{/if}
<div class="assets">
<div class="assets-header">Loaded clips</div>
{#each clipSummary as clip}
<div class="asset-row">
<span class="asset-role">{clip.role}</span>
<span class="asset-name">{clip.name}</span>
<span class="asset-meta">{clip.frames}f · {clip.fps}fps</span>
</div>
{/each}
{#if stats}
<div class="assets-footer">
{stats.count} image{stats.count === 1 ? '' : 's'} · {(stats.decodedBytes / 1024).toFixed(1)} KB decoded
</div>
{/if}
</div>
<p class="hint">hover to look · drop PNGs in src/lib/assets/</p>
{/if}
</div>
<style>
:global(html, body) {
margin: 0;
padding: 0;
background: #0a0a0a;
color: #e6e6e6;
font-family: ui-monospace, monospace;
overflow: hidden;
}
canvas {
display: block;
width: 100vw;
height: 100vh;
cursor: crosshair;
}
.panel {
position: fixed;
top: 1rem;
left: 1rem;
padding: 1rem 1.25rem;
background: rgba(0, 0, 0, 0.88);
border: 1px solid #333;
border-radius: 6px;
font-size: 12px;
min-width: 22rem;
max-width: 28rem;
max-height: calc(100vh - 2rem);
overflow-y: auto;
line-height: 1.5;
}
.panel h2 {
margin: 0 0 0.75rem;
font-size: 13px;
font-weight: 600;
color: #7ec8ff;
}
.section-title {
font-size: 10px;
color: #666;
text-transform: uppercase;
letter-spacing: 0.5px;
margin: 0.6rem 0 0.35rem;
}
.controls {
display: flex;
gap: 0.4rem;
margin-bottom: 0.4rem;
flex-wrap: wrap;
}
.controls.small button {
font-size: 10px;
padding: 0.2rem 0.4rem;
}
button {
background: #1a1a1a;
border: 1px solid #333;
color: #ccc;
padding: 0.3rem 0.55rem;
border-radius: 4px;
font: inherit;
cursor: pointer;
transition: all 0.1s;
display: inline-flex;
align-items: center;
gap: 0.4rem;
}
button:hover:not(:disabled) {
background: #222;
border-color: #555;
}
button:disabled {
cursor: default;
}
button.active {
background: #1e3a5f;
border-color: #7ec8ff;
color: #7ec8ff;
}
.event-grid {
display: flex;
flex-direction: column;
gap: 0.3rem;
margin-bottom: 0.4rem;
}
.event-grid button {
display: flex;
flex-direction: column;
align-items: stretch;
width: 100%;
text-align: left;
font-size: 11px;
padding: 0.35rem 0.55rem;
}
.ev-main {
display: flex;
justify-content: space-between;
align-items: center;
gap: 0.4rem;
width: 100%;
}
.ev-label {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.ev-config {
font-size: 9px;
color: #666;
margin-top: 0.2rem;
letter-spacing: 0.2px;
font-variant-numeric: tabular-nums;
}
.event-grid button.is-playing .ev-config,
.event-grid button.is-queued .ev-config {
color: currentColor;
opacity: 0.65;
}
.event-grid button.is-mismatch {
opacity: 0.55;
border-style: dashed;
}
.event-grid button.is-queued {
border-color: #fbbf24;
background: rgba(251, 191, 36, 0.08);
color: #fbbf24;
}
.event-grid button.is-playing {
border-color: #4ade80;
background: rgba(74, 222, 128, 0.10);
color: #4ade80;
opacity: 1;
}
.ev-tag {
font-size: 9px;
padding: 0.1rem 0.35rem;
border-radius: 3px;
font-weight: 600;
letter-spacing: 0.3px;
}
.tag-playing {
background: rgba(74, 222, 128, 0.2);
color: #4ade80;
}
.tag-queued {
background: rgba(251, 191, 36, 0.2);
color: #fbbf24;
}
.tag-cd {
background: rgba(120, 120, 120, 0.2);
color: #888;
font-variant-numeric: tabular-nums;
}
.pending {
font-size: 10px;
color: #fbbf24;
margin: 0.3rem 0 0;
padding: 0.35rem 0.5rem;
background: rgba(251, 191, 36, 0.08);
border-radius: 3px;
}
dl {
display: grid;
grid-template-columns: 7rem 1fr;
gap: 0.15rem 0.5rem;
margin: 0.6rem 0;
font-size: 11px;
}
dt {
color: #666;
}
dd {
margin: 0;
color: #ccc;
}
dd.highlight {
color: #7ec8ff;
font-weight: 600;
}
.cursor-info {
margin-top: 0.5rem;
padding-top: 0.5rem;
border-top: 1px solid #333;
font-size: 11px;
color: #888;
}
.cursor-info strong {
color: #ccc;
}
.chatter {
margin-top: 0.5rem;
padding: 0.5rem;
background: rgba(126, 200, 255, 0.08);
border-left: 2px solid #7ec8ff;
font-size: 11px;
color: #a8d8ff;
border-radius: 2px;
}
.assets {
margin-top: 0.75rem;
padding-top: 0.5rem;
border-top: 1px solid #333;
font-size: 10px;
}
.assets-header {
color: #7ec8ff;
font-weight: 600;
margin-bottom: 0.3rem;
}
.asset-row {
display: grid;
grid-template-columns: 5rem 1fr 5rem;
gap: 0.4rem;
padding: 0.1rem 0;
color: #666;
}
.asset-role {
color: #888;
}
.asset-name {
color: #ccc;
overflow: hidden;
text-overflow: ellipsis;
}
.asset-meta {
text-align: right;
color: #555;
}
.assets-footer {
margin-top: 0.4rem;
padding-top: 0.4rem;
border-top: 1px solid #222;
color: #555;
}
.hint {
margin: 0.75rem 0 0;
padding-top: 0.5rem;
border-top: 1px solid #333;
color: #444;
font-size: 10px;
}
.error {
color: #ff6b6b;
}
.loading {
color: #888;
}
</style>